@protobase/query 0.117.6 → 0.118.0

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.
@@ -0,0 +1,35 @@
1
+ import { Db } from "./db.js";
2
+ import { Scope } from "./scope.js";
3
+ import { FacetCount } from "./facet-counts.js";
4
+ import { BucketOptions } from "./series-buckets.js";
5
+ import { SeriesPoint } from "./series.js";
6
+ import { Histogram } from "./histogram.js";
7
+ import { CheckedFilter, ResourceModel } from "@protobase/schema";
8
+ //#region src/aggregate-scan.d.ts
9
+ export type ScanRequests = {
10
+ facets?: Array<{
11
+ field: string;
12
+ limit?: number;
13
+ }>;
14
+ histograms?: Array<{
15
+ field: string;
16
+ buckets: number;
17
+ }>;
18
+ series?: Array<{
19
+ field: string;
20
+ } & BucketOptions>;
21
+ };
22
+ export type ScanResults = {
23
+ facets: FacetCount[][];
24
+ histograms: Histogram[];
25
+ series: SeriesPoint[][];
26
+ };
27
+ /**
28
+ * The facet counts, histograms and series of one filter and scope, each as `facetCounts`, `histogram` and `series` find
29
+ * it, in few scans of the table however many are asked for: one for the bounds of every histogram, and one per
30
+ * `setsPerScan` groupings that count facets' values, histograms' buckets and series' buckets together (`groupedCounts`).
31
+ * The filter applies to each as given, so a facet that leaves out its own terms is asked for with them left out
32
+ * (`withoutField`). Results come in request order.
33
+ */
34
+ export declare const aggregateScan: (db: Db, model: ResourceModel, filter: CheckedFilter | undefined, scope: Scope | undefined, requests: ScanRequests) => Promise<ScanResults>;
35
+ //#endregion
@@ -0,0 +1,108 @@
1
+ import { columnRef, requireField } from "./columns.js";
2
+ import { assertFilterRequirements } from "./filter-requirements.js";
3
+ import { toNumber } from "./numbers.js";
4
+ import { facetLimit } from "./facet-counts.js";
5
+ import { seriesBuckets } from "./series-buckets.js";
6
+ import { bucketOf, histogramColumn, histogramOf } from "./histogram.js";
7
+ import { groupedCounts } from "./grouped-counts.js";
8
+ import { histogramBounds } from "./histogram-bounds.js";
9
+ import { sql } from "kysely";
10
+ //#region src/aggregate-scan.ts
11
+ const bucketText = (value) => sql`to_char(${value}, 'YYYY-MM-DD"T"HH24:MI:SS')`;
12
+ const bucketList = async (db, buckets) => {
13
+ const { from, truncate, local, laterBucket, step } = buckets;
14
+ return (await sql`select ${bucketText(sql`b`)} as bucket from generate_series(${truncate(local(from))}, ${laterBucket}, ${step}) as b order by b`.execute(db)).rows.map((row) => row.bucket);
15
+ };
16
+ const seriesKey = ({ col, from, to, bound, truncate, local, isDate }) => sql`case when ${col} >= ${from}::${bound} and ${col} < ${to}::${bound} then ${bucketText(truncate(isDate ? sql`${col}::timestamp` : local(col)))} end`;
17
+ const countSets = () => {
18
+ const sets = [];
19
+ const indexes = /* @__PURE__ */ new Map();
20
+ const add = (id, set) => {
21
+ const known = indexes.get(id);
22
+ if (known !== void 0) return known;
23
+ indexes.set(id, sets.length);
24
+ sets.push(set);
25
+ return sets.length - 1;
26
+ };
27
+ return {
28
+ sets,
29
+ add
30
+ };
31
+ };
32
+ /**
33
+ * The facet counts, histograms and series of one filter and scope, each as `facetCounts`, `histogram` and `series` find
34
+ * it, in few scans of the table however many are asked for: one for the bounds of every histogram, and one per
35
+ * `setsPerScan` groupings that count facets' values, histograms' buckets and series' buckets together (`groupedCounts`).
36
+ * The filter applies to each as given, so a facet that leaves out its own terms is asked for with them left out
37
+ * (`withoutField`). Results come in request order.
38
+ */
39
+ const aggregateScan = async (db, model, filter, scope, requests) => {
40
+ const facets = (requests.facets ?? []).map(({ field, limit }) => ({
41
+ field,
42
+ column: columnRef(requireField(model, field, "filterable")),
43
+ limit: facetLimit(limit)
44
+ }));
45
+ const histograms = (requests.histograms ?? []).map(({ field, buckets }) => ({
46
+ field,
47
+ column: histogramColumn(model, field, buckets),
48
+ buckets
49
+ }));
50
+ const series = (requests.series ?? []).map(({ field, ...options }) => ({
51
+ id: JSON.stringify([field, options]),
52
+ buckets: seriesBuckets(model, field, options)
53
+ }));
54
+ await assertFilterRequirements(db, filter, scope);
55
+ const bounds = await histogramBounds(db, model, filter, scope, histograms.map(({ column }) => column));
56
+ const { sets, add } = countSets();
57
+ const facetSets = facets.map(({ field, column }) => add(`facet:${field}`, {
58
+ key: sql`${column}`,
59
+ ranked: true
60
+ }));
61
+ const histogramSets = histograms.map(({ field, column, buckets }, index) => {
62
+ const { min, max } = bounds[index];
63
+ if (buckets === 1 || min === null || max === null || min === max) return;
64
+ return add(`histogram:${field}:${buckets}`, {
65
+ key: sql`case when ${column} is not null then ${bucketOf(column, min, max, buckets)} end`,
66
+ ranked: false
67
+ });
68
+ });
69
+ const seriesSets = series.map(({ id, buckets }) => add(`series:${id}`, {
70
+ key: seriesKey(buckets),
71
+ ranked: false
72
+ }));
73
+ const counted = await groupedCounts(db, model, filter, scope, sets, Math.max(0, ...facets.map(({ limit }) => limit)));
74
+ const lists = [];
75
+ for (const { buckets } of series) lists.push(await bucketList(db, buckets));
76
+ return {
77
+ facets: facets.map(({ limit }, index) => counted[facetSets[index]].slice(0, limit)),
78
+ histograms: histograms.map(({ buckets }, index) => {
79
+ const { min, max, count } = bounds[index];
80
+ if (min === null || max === null) return {
81
+ min: null,
82
+ max: null,
83
+ buckets: []
84
+ };
85
+ if (min === max) return {
86
+ min,
87
+ max,
88
+ buckets: [{
89
+ from: min,
90
+ to: max,
91
+ count
92
+ }]
93
+ };
94
+ const set = histogramSets[index];
95
+ if (set === void 0) return histogramOf(min, max, buckets, /* @__PURE__ */ new Map([[1, count]]));
96
+ return histogramOf(min, max, buckets, new Map(counted[set].flatMap(({ value, count }) => value === null ? [] : [[toNumber(value), count]])));
97
+ }),
98
+ series: series.map((_, index) => {
99
+ const counts = new Map(counted[seriesSets[index]].flatMap(({ value, count }) => value === null ? [] : [[String(value), count]]));
100
+ return lists[index].map((bucket) => ({
101
+ bucket,
102
+ count: counts.get(bucket) ?? 0
103
+ }));
104
+ })
105
+ };
106
+ };
107
+ //#endregion
108
+ export { aggregateScan };
@@ -0,0 +1,6 @@
1
+ import { RawBuilder } from "kysely";
2
+ import { FieldModel, ResourceModel } from "@protobase/schema";
3
+ //#region src/columns.d.ts
4
+ /** The column of a field of the table aliased `t`, or a lookup field's value. */
5
+ export declare const columnRef: (field: FieldModel) => RawBuilder<unknown>;
6
+ //#endregion
package/dist/columns.js CHANGED
@@ -1,11 +1,25 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
+ import { lookupReadOf } from "./lookup-read.js";
2
3
  import { sql } from "kysely";
3
- const columnRef = (field) => sql`${sql.id("t", field.column)}`;
4
4
  const tableSource = (model) => {
5
5
  const { schema, name } = model.table;
6
6
  const table = schema ? sql.id(schema, name) : sql.id(name);
7
7
  return sql`${table}`.as("t");
8
8
  };
9
+ const whereAll = (conditions) => conditions.length === 0 ? sql`` : sql` where ${sql.join(conditions, sql` and `)}`;
10
+ /**
11
+ * A lookup field's value: the linked field of the one linked record the caller reads, or null. The linked table is
12
+ * aliased `t` inside its own subquery, so its conditions read its columns, and only the link reads the outer row.
13
+ */
14
+ const lookupValue = (read) => {
15
+ const linked = sql`select ${sql.id("t", read.match.column)} as k, ${sql.id("t", read.value.column)} as v from ${tableSource(read.model)}${whereAll(read.conditions)}`;
16
+ return sql`(select l.v from (${linked}) as l where l.k = ${columnRef(read.link)})`;
17
+ };
18
+ /** The column of a field of the table aliased `t`, or a lookup field's value. */
19
+ const columnRef = (field) => {
20
+ const read = lookupReadOf(field);
21
+ return read ? lookupValue(read) : sql`${sql.id("t", field.column)}`;
22
+ };
9
23
  const findField = (model, name) => {
10
24
  const field = Object.hasOwn(model.fields, name) ? model.fields[name] : void 0;
11
25
  if (!field) throw new QueryError("unknown_field", `Unknown field "${name}" on resource "${model.name}"`);
@@ -1,6 +1,7 @@
1
1
  import { jsonHas, jsonPresent } from "./fields/json.js";
2
2
  import { QueryError } from "./fields/query-error.js";
3
- import { columnRef } from "./columns.js";
3
+ import { lookupReadOf } from "./lookup-read.js";
4
+ import { columnRef, tableSource } from "./columns.js";
4
5
  import { compileCompare, compileIn } from "./compile-compare.js";
5
6
  import { compileRegex, compileSearch, compileSimilar } from "./compile-text-match.js";
6
7
  import { sql } from "kysely";
@@ -10,7 +11,24 @@ const combine = (parts, joiner) => {
10
11
  if (parts.length === 0) return sql`${sql.lit(joiner === "and")}`;
11
12
  return sql`(${sql.join(parts, sql` ${sql.raw(joiner)} `)})`;
12
13
  };
14
+ const lookupTerm = (node, read, threshold) => {
15
+ const held = node.kind === "isNull" ? sql`${columnRef(read.value)} is not null` : compileNode(read.model, {
16
+ ...node,
17
+ field: read.value
18
+ }, threshold);
19
+ const matched = read.match.nullable ? [sql`${columnRef(read.match)} is not null`] : [];
20
+ const keys = sql`select ${columnRef(read.match)} from ${tableSource(read.model)} where ${sql.join([
21
+ ...read.conditions,
22
+ ...matched,
23
+ held
24
+ ], sql` and `)}`;
25
+ const link = columnRef(read.link);
26
+ const linked = read.link.nullable ? sql`(${link} is not null and ${link} in (${keys}))` : sql`${link} in (${keys})`;
27
+ return node.kind === "isNull" ? sql`not ${linked}` : linked;
28
+ };
13
29
  const compileNode = (model, node, threshold) => {
30
+ const read = "field" in node ? lookupReadOf(node.field) : void 0;
31
+ if (read) return lookupTerm(node, read, threshold);
14
32
  switch (node.kind) {
15
33
  case "and":
16
34
  case "or": return combine(node.args.map((arg) => compileNode(model, arg, threshold)), node.kind);
@@ -9,11 +9,15 @@ import { sql } from "kysely";
9
9
  //#region src/facet-counts.ts
10
10
  const defaultLimit = 100;
11
11
  const maxLimit = 1e3;
12
+ /** How many values a facet keeps, the most frequent first: `limit`, 100 by default, or a `QueryError`. */
13
+ const facetLimit = (limit = defaultLimit) => {
14
+ if (!Number.isInteger(limit) || limit < 1 || limit > maxLimit) throw new QueryError("invalid_option", `limit must be between 1 and ${maxLimit}`);
15
+ return limit;
16
+ };
12
17
  /** Counts per value of `field`, with every filter applied except the ones on `field` itself. */
13
18
  const facetCounts = async (db, model, field, filter, options) => {
14
19
  const column = columnRef(requireField(model, field, "filterable"));
15
- const limit = options.limit ?? defaultLimit;
16
- if (!Number.isInteger(limit) || limit < 1 || limit > maxLimit) throw new QueryError("invalid_option", `limit must be between 1 and ${maxLimit}`);
20
+ const limit = facetLimit(options.limit);
17
21
  const others = withoutField(filter, field);
18
22
  await assertFilterRequirements(db, others, options.scope);
19
23
  return withStatementTimeout(db, options.statementTimeoutMs, async (trx) => {
@@ -24,4 +28,4 @@ const facetCounts = async (db, model, field, filter, options) => {
24
28
  });
25
29
  };
26
30
  //#endregion
27
- export { facetCounts };
31
+ export { facetCounts, facetLimit };
@@ -0,0 +1,6 @@
1
+ import { Scope } from "./scope.js";
2
+ import { CheckedFilter } from "@protobase/schema";
3
+ //#region src/filter-fingerprint.d.ts
4
+ /** What a read keeps to, as text: equal for two reads that filter the same rows, however their filters were written. */
5
+ export declare const readIdentity: (filter: CheckedFilter | undefined, scope?: Scope) => string;
6
+ //#endregion
@@ -34,6 +34,12 @@ const hash = (text) => {
34
34
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
35
35
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
36
36
  };
37
+ /** What a read keeps to, as text: equal for two reads that filter the same rows, however their filters were written. */
38
+ const readIdentity = (filter, scope) => canonical({
39
+ filter,
40
+ terms: relatedTerms(scope),
41
+ within: scope?.within
42
+ });
37
43
  /** A short fingerprint of the filter a cursor was issued for and what its scope narrows it by; empty without either. */
38
44
  const filterFingerprint = (filter, scope) => {
39
45
  const terms = relatedTerms(scope);
@@ -45,4 +51,4 @@ const filterFingerprint = (filter, scope) => {
45
51
  return filter ? hash(canonical(filter)) : "";
46
52
  };
47
53
  //#endregion
48
- export { filterFingerprint };
54
+ export { filterFingerprint, readIdentity };
@@ -0,0 +1,40 @@
1
+ import { baseQuery } from "./base-query.js";
2
+ import { toNumber } from "./numbers.js";
3
+ import { sql } from "kysely";
4
+ /**
5
+ * Counts the rows per value of every set's key, the filter and scope applying to each, in one scan of the table
6
+ * (`GROUPING SETS`) per `setsPerScan` sets. A ranked set keeps its `limit` most frequent values, ties by value, as
7
+ * `facetCounts` orders them; the others keep every value. Returns each set's values in that order, a null key included.
8
+ */
9
+ const groupedCounts = async (db, model, filter, scope, sets, limit) => {
10
+ const counts = [];
11
+ for (let start = 0; start < sets.length; start += 4) counts.push(...await countScan(db, model, filter, scope, sets.slice(start, start + 4), limit));
12
+ return counts;
13
+ };
14
+ const countScan = async (db, model, filter, scope, sets, limit) => {
15
+ const keys = sets.map((_, index) => sql.id(`k${index}`));
16
+ const keyed = baseQuery(db, model, filter, scope).select(sets.map(({ key }, index) => key.as(`k${index}`))).offset(0);
17
+ const setOf = sql`case ${sql.join(keys.map((key, index) => sql`when grouping(${key}) = 0 then ${sql.lit(index)}`), sql` `)} end`;
18
+ const ranked = sets.flatMap(({ ranked }, index) => ranked ? [sql.lit(index)] : []);
19
+ const kept = ranked.length === 0 ? sql`true` : sql`s not in (${sql.join(ranked)}) or rank <= ${limit}`;
20
+ const result = await sql`
21
+ with g as (
22
+ select ${setOf} as s, ${sql.join(keys)}, count(*) as n
23
+ from (${keyed}) as v
24
+ group by grouping sets (${sql.join(keys.map((key) => sql`(${key})`))})
25
+ ), r as (
26
+ select g.*, row_number() over (partition by s order by n desc, ${sql.join(keys)}) as rank from g
27
+ )
28
+ select s, ${sql.join(keys)}, n::text as n from r
29
+ where ${kept}
30
+ order by s, rank
31
+ `.execute(db);
32
+ const counts = sets.map(() => []);
33
+ for (const row of result.rows) counts[row.s].push({
34
+ value: row[`k${row.s}`],
35
+ count: toNumber(row.n)
36
+ });
37
+ return counts;
38
+ };
39
+ //#endregion
40
+ export { groupedCounts };
@@ -0,0 +1,24 @@
1
+ import { baseQuery } from "./base-query.js";
2
+ import { toNumber } from "./numbers.js";
3
+ import { sql } from "kysely";
4
+ //#region src/histogram-bounds.ts
5
+ /** The bounds of every column in one scan of the table, in the order given. */
6
+ const histogramBounds = async (db, model, filter, scope, columns) => {
7
+ if (columns.length === 0) return [];
8
+ const row = await baseQuery(db, model, filter, scope).select(columns.flatMap((column, index) => [
9
+ sql`min(${column})::float8::text`.as(`lo${index}`),
10
+ sql`max(${column})::float8::text`.as(`hi${index}`),
11
+ sql`count(${column})::text`.as(`n${index}`)
12
+ ])).executeTakeFirstOrThrow();
13
+ return columns.map((_, index) => {
14
+ const lo = row[`lo${index}`] ?? null;
15
+ const hi = row[`hi${index}`] ?? null;
16
+ return {
17
+ min: lo === null ? null : Number(lo),
18
+ max: hi === null ? null : Number(hi),
19
+ count: toNumber(row[`n${index}`])
20
+ };
21
+ });
22
+ };
23
+ //#endregion
24
+ export { histogramBounds };
package/dist/histogram.js CHANGED
@@ -12,13 +12,32 @@ const numericTypes = [
12
12
  "decimal",
13
13
  "currency"
14
14
  ];
15
- /** Equal-width buckets between the filtered min and max, empty buckets included. */
16
- const histogram = async (db, model, field, filter, buckets, scope) => {
15
+ /** The column of a numeric filterable field that a histogram of `buckets` can bucket, or a `QueryError`. */
16
+ const histogramColumn = (model, field, buckets) => {
17
17
  const target = requireField(model, field, "filterable");
18
18
  if (!numericTypes.includes(target.type)) throw new QueryError("unsupported_field_type", `Histogram needs a numeric field, "${field}" is ${target.type}`);
19
19
  if (!Number.isInteger(buckets) || buckets < 1 || buckets > maxBuckets) throw new QueryError("invalid_option", `buckets must be between 1 and ${maxBuckets}`);
20
+ return columnRef(target);
21
+ };
22
+ /** Which of `buckets` equal-width buckets between `min` and `max` a value falls in, from 1; the maximum is in the last. */
23
+ const bucketOf = (column, min, max, buckets) => sql`least(width_bucket(${column}::float8, ${min}::float8, ${max}::float8, ${buckets}::int), ${buckets}::int)`;
24
+ /** The buckets between `min` and `max` with their counts by `bucketOf`, empty ones included. */
25
+ const histogramOf = (min, max, buckets, counts) => {
26
+ const width = (max - min) / buckets;
27
+ return {
28
+ min,
29
+ max,
30
+ buckets: Array.from({ length: buckets }, (_, i) => ({
31
+ from: min + i * width,
32
+ to: i === buckets - 1 ? max : min + (i + 1) * width,
33
+ count: counts.get(i + 1) ?? 0
34
+ }))
35
+ };
36
+ };
37
+ /** Equal-width buckets between the filtered min and max, empty buckets included. */
38
+ const histogram = async (db, model, field, filter, buckets, scope) => {
39
+ const col = histogramColumn(model, field, buckets);
20
40
  await assertFilterRequirements(db, filter, scope);
21
- const col = columnRef(target);
22
41
  const present = baseQuery(db, model, filter, scope).where(sql`${col} is not null`);
23
42
  const bounds = await present.select([sql`min(${col})::float8::text`.as("lo"), sql`max(${col})::float8::text`.as("hi")]).executeTakeFirstOrThrow();
24
43
  if (bounds.lo === null || bounds.hi === null) return {
@@ -40,18 +59,8 @@ const histogram = async (db, model, field, filter, buckets, scope) => {
40
59
  }]
41
60
  };
42
61
  }
43
- const counted = await present.select([sql`least(width_bucket(${col}::float8, ${min}::float8, ${max}::float8, ${buckets}::int), ${buckets}::int)`.as("bucket"), sql`count(*)::text`.as("n")]).groupBy(sql`1`).execute();
44
- const counts = new Map(counted.map((row) => [toNumber(row.bucket), toNumber(row.n)]));
45
- const width = (max - min) / buckets;
46
- return {
47
- min,
48
- max,
49
- buckets: Array.from({ length: buckets }, (_, i) => ({
50
- from: min + i * width,
51
- to: i === buckets - 1 ? max : min + (i + 1) * width,
52
- count: counts.get(i + 1) ?? 0
53
- }))
54
- };
62
+ const counted = await present.select([bucketOf(col, min, max, buckets).as("bucket"), sql`count(*)::text`.as("n")]).groupBy(sql`1`).execute();
63
+ return histogramOf(min, max, buckets, new Map(counted.map((row) => [toNumber(row.bucket), toNumber(row.n)])));
55
64
  };
56
65
  //#endregion
57
- export { histogram };
66
+ export { bucketOf, histogram, histogramColumn, histogramOf };
@@ -12,9 +12,10 @@ export type IndexNeed = 'btree' | 'trigram' | 'digits' | 'gin' | 'file';
12
12
  /**
13
13
  * Where a column is read: the caller's filter, the access rule's row filter, the relation to a parent the caller must
14
14
  * read (`.parent(fk, 'read')`), a `related()` term, the sort, a facet's grouping, the field a read keeps the first rows
15
- * per value of (`limit_per`), or the file cleanup's check that no row holds a file it is about to delete.
15
+ * per value of (`limit_per`), the file cleanup's check that no row holds a file it is about to delete, or the field a
16
+ * lookup field finds each record's linked record by.
16
17
  */
17
- export type ColumnUse = 'filter' | 'access' | 'parent' | 'related' | 'sort' | 'facet' | 'per' | 'cleanup';
18
+ export type ColumnUse = 'filter' | 'access' | 'parent' | 'related' | 'sort' | 'facet' | 'per' | 'cleanup' | 'lookup';
18
19
  /** A column read without an index that serves it, and a statement that adds one. */
19
20
  export type UncoveredColumn = {
20
21
  field: string;
@@ -50,7 +51,8 @@ export declare const uncoveredFileColumns: (model: ResourceModel, table: TableIn
50
51
  * btree index serves under them. A `related()` term is judged as a parent is and pins its relation as `in()` does, and
51
52
  * the read of its resource also needs a btree index on the key it selects. A read that keeps the first rows per value
52
53
  * of a field needs a btree index on that field with the sort's first field under it, which serves the sort too.
53
- * A plain view or a foreign table has no
54
+ * A lookup field read in any of these ways needs a btree index on its link instead; what it reads of the linked
55
+ * table is judged against that table (`lookupQueries`). A plain view or a foreign table has no
54
56
  * indexes of its own and is not judged.
55
57
  */
56
58
  export declare const uncoveredColumns: (model: ResourceModel, table: TableIndexes, query: CoverageQuery, scope?: Scope) => UncoveredColumn[];
@@ -1,3 +1,4 @@
1
+ import { lookupReadOf } from "./lookup-read.js";
1
2
  import { isPatternCompare } from "./compile-compare.js";
2
3
  import { fullModelOf } from "./scope.js";
3
4
  //#region src/index-coverage.ts
@@ -20,6 +21,7 @@ const suggestion = (model, column, need, under) => {
20
21
  const pinnedColumns = (filter) => {
21
22
  if (!filter) return [];
22
23
  if (filter.kind === "and") return filter.args.flatMap(pinnedColumns);
24
+ if ("field" in filter && filter.field.lookup) return [];
23
25
  if (filter.kind === "compare") return filter.op === "=" && !isPatternCompare(filter) ? [filter.field.column] : [];
24
26
  if (filter.kind === "in" || filter.kind === "isNull") return [filter.field.column];
25
27
  return [];
@@ -86,6 +88,7 @@ const perNeed = (ctx, per, sort, pinned) => {
86
88
  suggestion: suggestion(ctx.model, per.column, "btree", sort.column)
87
89
  }];
88
90
  };
91
+ const linkOf = (field) => lookupReadOf(field)?.link ?? field;
89
92
  const compareNeed = (ctx, node, pinned) => {
90
93
  if (isPatternCompare(node)) return need(ctx, node.field, "trigram", pinned);
91
94
  return need(ctx, node.field, "btree", pinned, node.op === "=" && node.field.type === "text" ? "trigram" : void 0);
@@ -96,6 +99,7 @@ const searchNeeds = (ctx, pinned) => (ctx.model.search ?? []).flatMap((name) =>
96
99
  return need(ctx, field, ctx.model.searchMatch?.[name] === "digitsEnd" ? "digits" : "trigram", pinned);
97
100
  });
98
101
  const walk = (ctx, node, pinned, negated) => {
102
+ if ("field" in node && node.field.lookup) return need(ctx, linkOf(node.field), "btree", pinned);
99
103
  switch (node.kind) {
100
104
  case "and": return node.args.flatMap((arg) => walk(ctx, arg, pinned, negated));
101
105
  case "or": return node.args.flatMap((arg) => walk(ctx, arg, negated ? pinned : /* @__PURE__ */ new Set([...pinned, ...pinnedColumns(arg)]), negated));
@@ -119,7 +123,8 @@ const unique = (columns) => columns.filter((column, i) => columns.findIndex((oth
119
123
  * btree index serves under them. A `related()` term is judged as a parent is and pins its relation as `in()` does, and
120
124
  * the read of its resource also needs a btree index on the key it selects. A read that keeps the first rows per value
121
125
  * of a field needs a btree index on that field with the sort's first field under it, which serves the sort too.
122
- * A plain view or a foreign table has no
126
+ * A lookup field read in any of these ways needs a btree index on its link instead; what it reads of the linked
127
+ * table is judged against that table (`lookupQueries`). A plain view or a foreign table has no
123
128
  * indexes of its own and is not judged.
124
129
  */
125
130
  const uncoveredColumns = (model, table, query, scope) => {
@@ -139,9 +144,10 @@ const uncoveredColumns = (model, table, query, scope) => {
139
144
  indexes: table.indexes,
140
145
  use
141
146
  });
142
- const sortField = query.sort?.[0] && model.fields[query.sort[0][0]];
143
- const groupField = query.groupBy !== void 0 ? model.fields[query.groupBy] : void 0;
144
- const perField = query.per !== void 0 ? model.fields[query.per] : void 0;
147
+ const own = (name) => name !== void 0 && model.fields[name] ? linkOf(model.fields[name]) : void 0;
148
+ const sortField = own(query.sort?.[0]?.[0]);
149
+ const groupField = own(query.groupBy);
150
+ const perField = own(query.per);
145
151
  return unique([
146
152
  ...perField ? perNeed(ctx("per"), perField, sortField, pinned) : [],
147
153
  ...scope?.rowFilter ? walk(ctx("access", full), scope.rowFilter, pinned, false) : [],
package/dist/index.d.ts CHANGED
@@ -14,6 +14,8 @@ import { Granularity } from "./series-buckets.js";
14
14
  import { SeriesOptions, SeriesPoint, series } from "./series.js";
15
15
  import { SplitPoint, SplitSeriesOptions, splitSeries } from "./split-series.js";
16
16
  import { Histogram, HistogramBucket, histogram } from "./histogram.js";
17
+ import { ScanRequests, ScanResults, aggregateScan } from "./aggregate-scan.js";
18
+ import { readIdentity } from "./filter-fingerprint.js";
17
19
  import { MapBounds, MapBucket, MapBuckets, MapPosition, cellsAcross, checkMapPosition, mapBuckets, mapCellPixels, maxMapBuckets, maxMapZoom } from "./map-buckets.js";
18
20
  import { withoutField } from "./prune-filter.js";
19
21
  import { ScrollMode, scrollMode } from "./scroll-mode.js";
@@ -22,6 +24,10 @@ import { ColumnUse, CoverageQuery, IndexNeed, UncoveredColumn, indexServes, unco
22
24
  import { QueryError, QueryErrorCode } from "./fields/query-error.js";
23
25
  import { RelatedPageRequest, relatedPage } from "./related-page.js";
24
26
  import { parentCondition } from "./read-conditions.js";
27
+ import { LookupRead, lookupReadOf, withLookupRead } from "./lookup-read.js";
28
+ import { columnRef } from "./columns.js";
29
+ import { lookupRead } from "./linked-read.js";
30
+ import { LookupCoverage, lookupQueries, uncoveredLookupMatch } from "./lookup-coverage.js";
25
31
  import { readsParent } from "./reads-parent.js";
26
32
  import { SeekRequest, seekToPosition } from "./seek-to-position.js";
27
- export { type ColumnUse, type CompileOptions, type CoverageQuery, type Db, type ExtraColumn, type FacetCount, type FacetOptions, type Granularity, type GroupTotal, type GroupTotalsOptions, type Histogram, type HistogramBucket, type IndexKey, type IndexNeed, type KeyItemType, type LimitPer, type ListOptions, type ListPlan, type ListResult, type MapBounds, type MapBucket, type MapBuckets, type MapPosition, type Measure, type ParentRead, type PerValue, QueryError, type QueryErrorCode, type RelatedPage, type RelatedPageRequest, type RelatedRowsQuery, type Scope, type ScrollMode, type SeekRequest, type SeriesOptions, type SeriesPoint, type SplitPoint, type SplitSeriesOptions, type TableIndex, type TableIndexes, type UncoveredColumn, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, compileFilter, countUpTo, estimateCount, exactCount, facetCounts, groupTotals, histogram, indexServes, listPerValue, listQuery, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readsParent, relatedPage, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, withoutField };
33
+ export { type ColumnUse, type CompileOptions, type CoverageQuery, type Db, type ExtraColumn, type FacetCount, type FacetOptions, type Granularity, type GroupTotal, type GroupTotalsOptions, type Histogram, type HistogramBucket, type IndexKey, type IndexNeed, type KeyItemType, type LimitPer, type ListOptions, type ListPlan, type ListResult, type LookupCoverage, type LookupRead, type MapBounds, type MapBucket, type MapBuckets, type MapPosition, type Measure, type ParentRead, type PerValue, QueryError, type QueryErrorCode, type RelatedPage, type RelatedPageRequest, type RelatedRowsQuery, type ScanRequests, type ScanResults, type Scope, type ScrollMode, type SeekRequest, type SeriesOptions, type SeriesPoint, type SplitPoint, type SplitSeriesOptions, type TableIndex, type TableIndexes, type UncoveredColumn, aggregateScan, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, columnRef, compileFilter, countUpTo, estimateCount, exactCount, facetCounts, groupTotals, histogram, indexServes, listPerValue, listQuery, lookupQueries, lookupRead, lookupReadOf, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readIdentity, readsParent, relatedPage, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, uncoveredLookupMatch, withLookupRead, withoutField };
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
+ import { lookupReadOf, withLookupRead } from "./lookup-read.js";
3
+ import { columnRef } from "./columns.js";
2
4
  import { compileFilter } from "./compile-filter.js";
3
5
  import { tenantCondition } from "./scope.js";
4
6
  import { parentCondition } from "./read-conditions.js";
7
+ import { readIdentity } from "./filter-fingerprint.js";
5
8
  import { buildListQuery, listQuery, maxLimit } from "./list-query.js";
6
9
  import { buildRelatedRows, relatedRows } from "./related-rows.js";
7
10
  import { listPerValue } from "./list-per-value.js";
@@ -14,11 +17,14 @@ import { groupTotals } from "./group-totals.js";
14
17
  import { splitSeries } from "./split-series.js";
15
18
  import { series } from "./series.js";
16
19
  import { histogram } from "./histogram.js";
20
+ import { aggregateScan } from "./aggregate-scan.js";
17
21
  import { cellsAcross, checkMapPosition, mapBuckets, mapCellPixels, maxMapBuckets, maxMapZoom } from "./map-buckets.js";
18
22
  import { scrollMode } from "./scroll-mode.js";
19
23
  import { tableIndexes } from "./table-indexes.js";
20
24
  import { indexServes, uncoveredColumns, uncoveredFileColumns } from "./index-coverage.js";
21
25
  import { relatedPage } from "./related-page.js";
26
+ import { lookupRead } from "./linked-read.js";
27
+ import { lookupQueries, uncoveredLookupMatch } from "./lookup-coverage.js";
22
28
  import { readsParent } from "./reads-parent.js";
23
29
  import { seekToPosition } from "./seek-to-position.js";
24
- export { QueryError, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, compileFilter, countUpTo, estimateCount, exactCount, facetCounts, groupTotals, histogram, indexServes, listPerValue, listQuery, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readsParent, relatedPage, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, withoutField };
30
+ export { QueryError, aggregateScan, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, columnRef, compileFilter, countUpTo, estimateCount, exactCount, facetCounts, groupTotals, histogram, indexServes, listPerValue, listQuery, lookupQueries, lookupRead, lookupReadOf, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readIdentity, readsParent, relatedPage, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, uncoveredLookupMatch, withLookupRead, withoutField };
@@ -0,0 +1,5 @@
1
+ import { LookupRead } from "./lookup-read.js";
2
+ //#region src/linked-read.d.ts
3
+ /** How a read reads a lookup field, with the conditions the caller's scope on the linked resource keeps to. */
4
+ export declare const lookupRead: (read: Omit<LookupRead, "conditions">) => LookupRead;
5
+ //#endregion
@@ -0,0 +1,9 @@
1
+ import { readConditions } from "./read-conditions.js";
2
+ //#region src/linked-read.ts
3
+ /** How a read reads a lookup field, with the conditions the caller's scope on the linked resource keeps to. */
4
+ const lookupRead = (read) => ({
5
+ ...read,
6
+ conditions: readConditions(read.model, read.scope)
7
+ });
8
+ //#endregion
9
+ export { lookupRead };
@@ -1,6 +1,7 @@
1
1
  import { Db } from "./db.js";
2
- import { SortKey } from "./sort.js";
2
+ import { SortKey } from "./sort-key.js";
3
3
  import { Scope } from "./scope.js";
4
+ import "./sort.js";
4
5
  import { ListQuery, ResourceModel } from "@protobase/schema";
5
6
  //#region src/list-query.d.ts
6
7
  export declare const maxLimit = 500;
@@ -0,0 +1,23 @@
1
+ import { TableIndexes } from "./table-indexes.js";
2
+ import { CoverageQuery, UncoveredColumn } from "./index-coverage.js";
3
+ import { LookupRead } from "./lookup-read.js";
4
+ import { ResourceModel } from "@protobase/schema";
5
+ //#region src/lookup-coverage.d.ts
6
+ /** A read of a lookup field's linked records, judged against their table's indexes in the caller's scope on them. */
7
+ export type LookupCoverage = {
8
+ field: string;
9
+ read: LookupRead;
10
+ query: CoverageQuery;
11
+ };
12
+ /**
13
+ * What a read of the resource reads of its lookup fields' linked records: each term on a lookup field filters them by
14
+ * the linked field, and a sort, grouping or first rows per value of one walks them by it. Empty is read as a linked
15
+ * value that is not empty, negated, as the filter compiles it.
16
+ */
17
+ export declare const lookupQueries: (model: ResourceModel, query: CoverageQuery) => LookupCoverage[];
18
+ /**
19
+ * Whether an index of the linked table serves finding each record's linked record, by the linked record's key or its
20
+ * relation that points at the record: every read that shows the lookup field does that once per record.
21
+ */
22
+ export declare const uncoveredLookupMatch: (read: LookupRead, table: TableIndexes) => UncoveredColumn[];
23
+ //#endregion
@@ -0,0 +1,58 @@
1
+ import { lookupReadOf } from "./lookup-read.js";
2
+ import { uncoveredColumns } from "./index-coverage.js";
3
+ //#region src/lookup-coverage.ts
4
+ const lookupTerms = (node) => {
5
+ if (!node) return [];
6
+ if (node.kind === "and" || node.kind === "or") return node.args.flatMap(lookupTerms);
7
+ if (node.kind === "not") return lookupTerms(node.arg);
8
+ return "field" in node && node.field.lookup ? [node] : [];
9
+ };
10
+ /**
11
+ * What a read of the resource reads of its lookup fields' linked records: each term on a lookup field filters them by
12
+ * the linked field, and a sort, grouping or first rows per value of one walks them by it. Empty is read as a linked
13
+ * value that is not empty, negated, as the filter compiles it.
14
+ */
15
+ const lookupQueries = (model, query) => {
16
+ const walked = (name, walk) => {
17
+ const field = name === void 0 ? void 0 : model.fields[name];
18
+ const read = field && lookupReadOf(field);
19
+ return field && read ? [{
20
+ field: field.name,
21
+ read,
22
+ query: walk(read.value.name)
23
+ }] : [];
24
+ };
25
+ const sort = query.sort?.[0];
26
+ return [
27
+ ...lookupTerms(query.filter).map((term) => {
28
+ const read = lookupReadOf(term.field);
29
+ const linked = {
30
+ ...term,
31
+ field: read.value
32
+ };
33
+ const filter = term.kind === "isNull" ? {
34
+ kind: "not",
35
+ arg: linked,
36
+ span: term.span
37
+ } : linked;
38
+ return {
39
+ field: term.field.name,
40
+ read,
41
+ query: { filter }
42
+ };
43
+ }),
44
+ ...walked(sort?.[0], (value) => ({ sort: [[value, sort[1]]] })),
45
+ ...walked(query.groupBy, (value) => ({ groupBy: value })),
46
+ ...walked(query.per, (value) => ({ groupBy: value }))
47
+ ];
48
+ };
49
+ /**
50
+ * Whether an index of the linked table serves finding each record's linked record, by the linked record's key or its
51
+ * relation that points at the record: every read that shows the lookup field does that once per record.
52
+ */
53
+ const uncoveredLookupMatch = (read, table) => uncoveredColumns(read.model, table, { selects: read.match }).map((column) => ({
54
+ ...column,
55
+ use: "lookup"
56
+ }));
57
+ //#endregion
58
+ export { lookupQueries, uncoveredLookupMatch };
@@ -0,0 +1,26 @@
1
+ import { Scope } from "./scope.js";
2
+ import { Expression, SqlBool } from "kysely";
3
+ import { FieldModel, ResourceModel } from "@protobase/schema";
4
+ //#region src/lookup-read.d.ts
5
+ /**
6
+ * How one read reads a lookup field: the linked resource's full model and the caller's scope on it with the conditions
7
+ * it keeps to, the linked field it shows (`value`), the linked record's field matched (`match`: its key, or the
8
+ * relation that points at this record) and this record's field matched with it (`link`: the relation, or this record's
9
+ * key). It holds the caller's scope, so it is only on the model a query runs against, never on one sent to the caller.
10
+ */
11
+ export type LookupRead = {
12
+ model: ResourceModel;
13
+ scope: Scope;
14
+ conditions: Expression<SqlBool>[];
15
+ value: FieldModel;
16
+ match: FieldModel;
17
+ link: FieldModel;
18
+ };
19
+ /** The lookup field as this read reads it. */
20
+ export declare const withLookupRead: (field: FieldModel, read: LookupRead) => FieldModel;
21
+ /**
22
+ * How this read reads the field when it is a lookup field. A lookup field of a model the server did not resolve for a
23
+ * caller has no read, which is a bug of the caller's code, not of the request: it throws.
24
+ */
25
+ export declare const lookupReadOf: (field: FieldModel) => LookupRead | undefined;
26
+ //#endregion
@@ -0,0 +1,18 @@
1
+ //#region src/lookup-read.ts
2
+ /** The lookup field as this read reads it. */
3
+ const withLookupRead = (field, read) => ({
4
+ ...field,
5
+ lookupRead: read
6
+ });
7
+ /**
8
+ * How this read reads the field when it is a lookup field. A lookup field of a model the server did not resolve for a
9
+ * caller has no read, which is a bug of the caller's code, not of the request: it throws.
10
+ */
11
+ const lookupReadOf = (field) => {
12
+ if (!field.lookup) return;
13
+ const read = field.lookupRead;
14
+ if (!read) throw new Error(`Lookup field "${field.name}" is read without the caller's access to its linked record`);
15
+ return read;
16
+ };
17
+ //#endregion
18
+ export { lookupReadOf, withLookupRead };
package/dist/scope.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SortKey } from "./sort.js";
1
+ import { SortKey } from "./sort-key.js";
2
2
  import { Expression, SqlBool } from "kysely";
3
3
  import { CheckedFilter, FieldModel, ResourceModel, SortSpec } from "@protobase/schema";
4
4
  //#region src/scope.d.ts
package/dist/scope.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
- import { columnRef } from "./columns.js";
3
2
  import { sql } from "kysely";
4
3
  //#region src/scope.ts
5
4
  const fullModelOf = (model, scope) => scope?.fullModel ?? model;
@@ -12,7 +11,7 @@ const tenantCondition = (model, scope) => {
12
11
  const tenant = full.tenant ?? model.tenant;
13
12
  if (!tenant) return void 0;
14
13
  const field = Object.hasOwn(full.fields, tenant) ? full.fields[tenant] : void 0;
15
- const column = field ? columnRef(field) : sql`${sql.id("t", tenant)}`;
14
+ const column = sql`${sql.id("t", field?.column ?? tenant)}`;
16
15
  if (scope?.tenantValues) {
17
16
  if (scope.tenantValues.length === 0) return sql`false`;
18
17
  return sql`${column} in (${sql.join(scope.tenantValues)})`;
@@ -0,0 +1,8 @@
1
+ import { FieldModel } from "@protobase/schema";
2
+ //#region src/sort-key.d.ts
3
+ export type Direction = 'asc' | 'desc';
4
+ export type SortKey = {
5
+ field: FieldModel;
6
+ direction: Direction;
7
+ };
8
+ //#endregion
package/dist/sort.d.ts CHANGED
@@ -1,8 +1,3 @@
1
- import { FieldModel, ResourceModel, SortSpec } from "@protobase/schema";
2
- //#region src/sort.d.ts
3
- export type Direction = 'asc' | 'desc';
4
- export type SortKey = {
5
- field: FieldModel;
6
- direction: Direction;
7
- };
8
- //#endregion
1
+ import { Direction, SortKey } from "./sort-key.js";
2
+ import { ResourceModel, SortSpec } from "@protobase/schema";
3
+ export type { SortKey };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/query",
3
- "version": "0.117.6",
3
+ "version": "0.118.0",
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.117.6",
32
+ "@protobase/schema": "0.118.0",
33
33
  "kysely": "^0.29.6"
34
34
  }
35
35
  }