@protobase/query 0.121.8 → 0.121.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import { assertFilterRequirements } from "./filter-requirements.js";
3
3
  import { toNumber } from "./numbers.js";
4
4
  import { facetLimit } from "./facet-counts.js";
5
5
  import { seriesBuckets } from "./series-buckets.js";
6
+ import { series } from "./series.js";
6
7
  import { bucketOf, histogramColumn, histogramOf } from "./histogram.js";
7
8
  import { groupedCounts } from "./grouped-counts.js";
8
9
  import { histogramBounds } from "./histogram-bounds.js";
@@ -47,7 +48,7 @@ const aggregateScan = async (db, model, filter, scope, requests) => {
47
48
  column: histogramColumn(model, field, buckets),
48
49
  buckets
49
50
  }));
50
- const series = (requests.series ?? []).map(({ field, ...options }) => ({
51
+ const series$1 = (requests.series ?? []).map(({ field, ...options }) => ({
51
52
  id: JSON.stringify([field, options]),
52
53
  buckets: seriesBuckets(model, field, options)
53
54
  }));
@@ -66,13 +67,20 @@ const aggregateScan = async (db, model, filter, scope, requests) => {
66
67
  ranked: false
67
68
  });
68
69
  });
69
- const seriesSets = series.map(({ id, buckets }) => add(`series:${id}`, {
70
+ const ownSeries = model.buckets !== void 0;
71
+ const seriesSets = ownSeries ? [] : series$1.map(({ id, buckets }) => add(`series:${id}`, {
70
72
  key: seriesKey(buckets),
71
73
  ranked: false
72
74
  }));
73
75
  const counted = await groupedCounts(db, model, filter, scope, sets, Math.max(0, ...facets.map(({ limit }) => limit)));
74
76
  const lists = [];
75
- for (const { buckets } of series) lists.push(await bucketList(db, buckets));
77
+ if (!ownSeries) for (const { buckets } of series$1) lists.push(await bucketList(db, buckets));
78
+ const own = [];
79
+ if (ownSeries) for (const { field, ...options } of requests.series ?? []) own.push(await series(db, model, field, {
80
+ ...options,
81
+ ...filter && { filter },
82
+ ...scope && { scope }
83
+ }));
76
84
  return {
77
85
  facets: facets.map(({ limit }, index) => counted[facetSets[index]].slice(0, limit)),
78
86
  histograms: histograms.map(({ buckets }, index) => {
@@ -95,7 +103,7 @@ const aggregateScan = async (db, model, filter, scope, requests) => {
95
103
  if (set === void 0) return histogramOf(min, max, buckets, /* @__PURE__ */ new Map([[1, count]]));
96
104
  return histogramOf(min, max, buckets, new Map(counted[set].flatMap(({ value, count }) => value === null ? [] : [[toNumber(value), count]])));
97
105
  }),
98
- series: series.map((_, index) => {
106
+ series: ownSeries ? own : series$1.map((_, index) => {
99
107
  const counts = new Map(counted[seriesSets[index]].flatMap(({ value, count }) => value === null ? [] : [[String(value), count]]));
100
108
  return lists[index].map((bucket) => ({
101
109
  bucket,
@@ -6,6 +6,7 @@ import { rankAlias } from "./internal-aliases.js";
6
6
  import { checkPerLimit, firstPerValue, ownerAlias } from "./related-rows.js";
7
7
  import { toNumber } from "./numbers.js";
8
8
  import { withStatementTimeout } from "./with-statement-timeout.js";
9
+ import { countSql } from "./rollup-measure.js";
9
10
  import { measureSql, measureValue } from "./measure.js";
10
11
  import { sql } from "kysely";
11
12
  //#region src/group-totals.ts
@@ -24,10 +25,10 @@ const groupTotals = async (db, model, field, options) => {
24
25
  const amount = measure ? measureSql(model, measure) : void 0;
25
26
  const column = columnRef(target);
26
27
  await assertFilterRequirements(db, options.filter, options.scope);
27
- const order = amount ? sql`${amount} desc nulls last, ${column} asc` : sql`count(*) desc, ${column} asc`;
28
+ const order = amount ? sql`${amount} desc nulls last, ${column} asc` : sql`${countSql(model)} desc, ${column} asc`;
28
29
  const groups = (trx) => baseQuery(trx, model, options.filter, options.scope).select([
29
30
  sql`${column}`.as("value"),
30
- sql`count(*)::text`.as("n"),
31
+ sql`${countSql(model)}::text`.as("n"),
31
32
  ...amount ? [sql`${amount}::text`.as("m")] : []
32
33
  ]).groupBy(column).orderBy(order);
33
34
  const { per } = options;
package/dist/measure.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
2
  import { columnRef, findField } from "./columns.js";
3
+ import { rollupMeasureSql } from "./rollup-measure.js";
3
4
  import { sql } from "kysely";
4
5
  //#region src/measure.ts
5
6
  const numericTypes = [
@@ -12,12 +13,16 @@ const aggregates = {
12
13
  average: "avg",
13
14
  maximum: "max"
14
15
  };
15
- /** The SQL aggregate of a measure; select it `::text`, so a decimal keeps its digits until it is read. */
16
+ /**
17
+ * The SQL aggregate of a measure, over a time rollup's stored columns for a rollup; select it `::text`, so a decimal keeps
18
+ * its digits until it is read.
19
+ */
16
20
  const measureSql = (model, measure) => {
17
21
  const field = findField(model, measure.field);
18
22
  if (!numericTypes.includes(field.type)) throw new QueryError("unsupported_field_type", `A ${measure.kind} needs a numeric field, "${measure.field}" is ${field.type}`);
19
23
  if (field.sensitive) throw new QueryError("unsupported_field_type", `"${measure.field}" is sensitive, so it cannot be added up`);
20
24
  const column = columnRef(field);
25
+ if (model.buckets) return rollupMeasureSql(model, model.buckets, measure, column);
21
26
  return sql`${sql.raw(aggregates[measure.kind])}(${column})`;
22
27
  };
23
28
  /** A measure's value: `null` when no row of the group has a value to add up. */
@@ -0,0 +1,32 @@
1
+ import { QueryError } from "./fields/query-error.js";
2
+ import { columnRef, findField } from "./columns.js";
3
+ import { sql } from "kysely";
4
+ import { keptMeasure } from "@protobase/schema/internal";
5
+ //#region src/rollup-measure.ts
6
+ const refused = (message) => new QueryError("invalid_option", message);
7
+ /**
8
+ * A measure over a time rollup's stored columns, so it gives what the same measure over the source's records gives:
9
+ * a sum adds up `<field>_sum` (or `events`, the count), an average divides that sum by the records it holds, and a
10
+ * maximum takes the greatest `<field>_max`. Throws on what the buckets cannot give, such as an average of greatest values.
11
+ */
12
+ const rollupMeasureSql = (model, buckets, measure, column) => {
13
+ const events = columnRef(findField(model, "events"));
14
+ if (measure.field === "events") {
15
+ if (measure.kind === "sum") return sql`sum(${column})`;
16
+ throw refused(`"events" counts each bucket's records, so a time rollup gives only their sum, the count`);
17
+ }
18
+ const kept = keptMeasure(buckets, measure.field);
19
+ if (!kept) throw refused(`"${measure.field}" is no measure of the time rollup "${model.name}": give events, or a <field>_sum or <field>_max field`);
20
+ if (kept.measure === "max") {
21
+ if (measure.kind === "maximum") return sql`max(${column})`;
22
+ throw refused(`"${measure.field}" keeps each bucket's greatest value, so a time rollup gives only its maximum`);
23
+ }
24
+ if (measure.kind === "sum") return sql`sum(${column})`;
25
+ if (measure.kind === "maximum") throw refused(`"${measure.field}" keeps each bucket's sum, so a time rollup gives its sum or average, not a maximum`);
26
+ if (buckets.optional.includes(kept.field)) throw refused(`"${kept.field}" is optional in "${buckets.from}" and "events" counts its records without a value too, so a time rollup cannot give its average`);
27
+ return sql`(sum(${column}) / sum(${events}))`;
28
+ };
29
+ /** How many records a group holds: its rows, or for a time rollup the records its buckets count. */
30
+ const countSql = (model) => model.buckets ? sql`sum(${columnRef(findField(model, "events"))})` : sql`count(*)`;
31
+ //#endregion
32
+ export { countSql, rollupMeasureSql };
@@ -0,0 +1,46 @@
1
+ import { QueryError } from "./fields/query-error.js";
2
+ import { sql } from "kysely";
3
+ //#region src/rollup-series.ts
4
+ const granularities = [
5
+ "minute",
6
+ "5_minutes",
7
+ "15_minutes",
8
+ "hour",
9
+ "day",
10
+ "week",
11
+ "month",
12
+ "year"
13
+ ];
14
+ const bucketSeconds = {
15
+ hour: 3600,
16
+ day: 86400
17
+ };
18
+ /** Whether a series of `field` reads a time rollup's buckets, whose hours or days in UTC are all it knows of time. */
19
+ const readsBuckets = (model, field) => model.buckets !== void 0 && field === "bucket";
20
+ /**
21
+ * Refuses a series a time rollup's buckets cannot give: a granularity finer than its bucket, or for a daily rollup a time
22
+ * zone other than UTC, whose days start at other hours than its own.
23
+ */
24
+ const checkBucketSeries = (model, field, granularity, timeZone) => {
25
+ if (!readsBuckets(model, field)) return;
26
+ const { every } = model.buckets;
27
+ if (granularities.indexOf(granularity) < granularities.indexOf(every)) throw new QueryError("invalid_option", `"${model.name}" keeps ${every}s, so it has no granularity finer than ${every}`);
28
+ if (every === "day" && timeZone !== "UTC") throw new QueryError("invalid_option", `"${model.name}" keeps days in UTC, so its series take only the time zone UTC`);
29
+ };
30
+ /**
31
+ * Refuses an hourly rollup's series in a time zone where one of its buckets would start or end inside a UTC hour, such
32
+ * as Asia/Kolkata's days, which start at half past: its hours cannot be split. It checks every bucket boundary the series
33
+ * has, the end of the last included, in one query, so a zone is judged by the offsets it has over the range.
34
+ */
35
+ const assertBucketBoundaries = async (db, model, field, { first, last, step, timeZone }) => {
36
+ if (!readsBuckets(model, field)) return;
37
+ const seconds = bucketSeconds[model.buckets.every];
38
+ if ((await sql`
39
+ select exists (
40
+ select 1 from generate_series(${first}, ${last} + ${step}, ${step}) as b
41
+ where extract(epoch from b at time zone ${timeZone}::text) % ${sql.lit(seconds)} <> 0
42
+ ) as inside
43
+ `.execute(db)).rows[0]?.inside) throw new QueryError("invalid_option", `"${model.name}" keeps whole UTC ${model.buckets.every}s, and buckets of the time zone ${timeZone} start inside them over this range`);
44
+ };
45
+ //#endregion
46
+ export { assertBucketBoundaries, checkBucketSeries, readsBuckets };
@@ -1,5 +1,6 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
2
  import { columnRef, requireField } from "./columns.js";
3
+ import { checkBucketSeries } from "./rollup-series.js";
3
4
  import { rangeBound } from "./range-bound.js";
4
5
  import { sql } from "kysely";
5
6
  //#region src/series-buckets.ts
@@ -28,7 +29,7 @@ const checkTimeZone = (timeZone) => {
28
29
  };
29
30
  /**
30
31
  * Validates a date or timestamp field, range, granularity and time zone, and builds the SQL pieces that bucket the
31
- * field over time. Shared by `series` and `splitSeries`.
32
+ * field over time. Shared by `series` and `splitSeries`; a time rollup's buckets also refuse what they cannot give.
32
33
  */
33
34
  const seriesBuckets = (model, field, options) => {
34
35
  const target = requireField(model, field, "filterable");
@@ -36,6 +37,7 @@ const seriesBuckets = (model, field, options) => {
36
37
  if (!Object.hasOwn(approxMs, options.granularity)) throw new QueryError("invalid_option", "Unknown granularity");
37
38
  const timeZone = options.timeZone ?? "UTC";
38
39
  checkTimeZone(timeZone);
40
+ checkBucketSeries(model, field, options.granularity, timeZone);
39
41
  const from = rangeBound(options.range.from, target);
40
42
  const to = rangeBound(options.range.to, target);
41
43
  const spanMs = new Date(to).getTime() - new Date(from).getTime();
@@ -57,8 +59,10 @@ const seriesBuckets = (model, field, options) => {
57
59
  step,
58
60
  bound,
59
61
  local,
62
+ firstBucket: truncate(local(from)),
60
63
  laterBucket: truncate(sql`${local(to)} - interval '1 microsecond'`),
61
- isDate
64
+ isDate,
65
+ timeZone
62
66
  };
63
67
  };
64
68
  //#endregion
package/dist/series.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { baseQuery } from "./base-query.js";
2
2
  import { assertFilterRequirements } from "./filter-requirements.js";
3
3
  import { toNumber } from "./numbers.js";
4
+ import { countSql } from "./rollup-measure.js";
4
5
  import { measureSql, measureValue } from "./measure.js";
6
+ import { assertBucketBoundaries } from "./rollup-series.js";
5
7
  import { seriesBuckets } from "./series-buckets.js";
6
8
  import { sql } from "kysely";
7
9
  //#region src/series.ts
@@ -12,18 +14,24 @@ import { sql } from "kysely";
12
14
  * up has `null` for it.
13
15
  */
14
16
  const series = async (db, model, field, options) => {
15
- const { col, from, to, truncate, step, bound, local, laterBucket, isDate } = seriesBuckets(model, field, options);
17
+ const { col, from, to, truncate, step, bound, local, firstBucket, laterBucket, isDate, timeZone } = seriesBuckets(model, field, options);
16
18
  const { measure } = options;
17
19
  const amount = measure ? measureSql(model, measure) : void 0;
18
20
  await assertFilterRequirements(db, options.filter, options.scope);
21
+ await assertBucketBoundaries(db, model, field, {
22
+ first: firstBucket,
23
+ last: laterBucket,
24
+ step,
25
+ timeZone
26
+ });
19
27
  const counts = baseQuery(db, model, options.filter, options.scope).where(sql`${col} >= ${from}::${bound} and ${col} < ${to}::${bound}`).select([
20
28
  truncate(isDate ? sql`${col}::timestamp` : local(col)).as("bucket"),
21
- sql`count(*)::text`.as("n"),
29
+ sql`${countSql(model)}::text`.as("n"),
22
30
  ...amount ? [sql`${amount}::text`.as("m")] : []
23
31
  ]).groupBy(sql`1`);
24
32
  return (await sql`
25
33
  with b as (
26
- select generate_series(${truncate(local(from))}, ${laterBucket}, ${step}) as bucket
34
+ select generate_series(${firstBucket}, ${laterBucket}, ${step}) as bucket
27
35
  ), c as (${counts})
28
36
  select to_char(b.bucket, 'YYYY-MM-DD"T"HH24:MI:SS') as bucket, coalesce(c.n, '0') as n${amount ? sql`, c.m` : sql``}
29
37
  from b left join c on c.bucket = b.bucket
@@ -3,7 +3,9 @@ import { columnRef, requireField } from "./columns.js";
3
3
  import { baseQuery } from "./base-query.js";
4
4
  import { assertFilterRequirements } from "./filter-requirements.js";
5
5
  import { toNumber } from "./numbers.js";
6
+ import { countSql } from "./rollup-measure.js";
6
7
  import { measureSql, measureValue } from "./measure.js";
8
+ import { assertBucketBoundaries } from "./rollup-series.js";
7
9
  import { seriesBuckets } from "./series-buckets.js";
8
10
  import { sql } from "kysely";
9
11
  //#region src/split-series.ts
@@ -21,7 +23,7 @@ const unsplittable = [
21
23
  * where a value has rows. What the other values hold is the bucket's total from `series` minus its points.
22
24
  */
23
25
  const splitSeries = async (db, model, field, split, options) => {
24
- const { col, from, to, truncate, bound, local, isDate } = seriesBuckets(model, field, options);
26
+ const { col, from, to, truncate, step, bound, local, firstBucket, laterBucket, isDate, timeZone } = seriesBuckets(model, field, options);
25
27
  const splitField = requireField(model, split, "filterable");
26
28
  if (unsplittable.includes(splitField.type)) throw new QueryError("unsupported_field_type", `Cannot split by "${split}", which is ${splitField.type}`);
27
29
  if (splitField.sensitive) throw new QueryError("unsupported_field_type", `"${split}" is sensitive, so it cannot be split by`);
@@ -31,12 +33,18 @@ const splitSeries = async (db, model, field, split, options) => {
31
33
  const { measure } = options;
32
34
  const amount = measure ? measureSql(model, measure) : void 0;
33
35
  await assertFilterRequirements(db, options.filter, options.scope);
36
+ await assertBucketBoundaries(db, model, field, {
37
+ first: firstBucket,
38
+ last: laterBucket,
39
+ step,
40
+ timeZone
41
+ });
34
42
  const splitCol = columnRef(splitField);
35
43
  const bucketSql = sql`to_char(${truncate(isDate ? sql`${col}::timestamp` : local(col))}, 'YYYY-MM-DD"T"HH24:MI:SS')`;
36
44
  const parts = baseQuery(db, model, options.filter, options.scope).where(sql`${col} >= ${from}::${bound} and ${col} < ${to}::${bound}`).select([
37
45
  bucketSql.as("bucket"),
38
46
  sql`${splitCol}`.as("split"),
39
- sql`count(*)`.as("n"),
47
+ countSql(model).as("n"),
40
48
  ...amount ? [sql`${amount}`.as("m")] : []
41
49
  ]).groupBy([sql`1`, sql`2`]);
42
50
  const largest = measure?.kind === "sum" ? sql`sum(m::numeric) desc nulls last` : sql`sum(n::bigint) desc`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/query",
3
- "version": "0.121.8",
3
+ "version": "0.121.9",
4
4
  "description": "Kysely list, filter, count and aggregate queries over Protobase resources.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@protobase/schema": "0.121.8",
32
+ "@protobase/schema": "0.121.9",
33
33
  "kysely": "^0.29.6"
34
34
  }
35
35
  }