@protobase/query 0.98.1 → 0.98.3

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.
package/dist/cursor.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
- import { filterFingerprint } from "./filter-fingerprint.js";
3
2
  import { sortSignature } from "./sort.js";
3
+ import { filterFingerprint } from "./filter-fingerprint.js";
4
4
  //#region src/cursor.ts
5
5
  const invalidCursor = () => new QueryError("invalid_cursor", "Cursor is malformed or does not match the requested sort and filter");
6
6
  const isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
@@ -1,11 +1,20 @@
1
1
  //#region src/filter-fingerprint.ts
2
- const relatedTerms = (scope) => (scope?.parents ?? []).flatMap(({ field, parent, related }) => related ? [{
3
- column: field.column,
4
- resource: parent?.model.name,
5
- key: parent?.key.column,
6
- subfilter: related.filter,
7
- terms: relatedTerms(parent?.scope)
8
- }] : []);
2
+ const relatedTerms = (scope) => (scope?.parents ?? []).flatMap(({ field, parent, related }) => {
3
+ if (!related) return [];
4
+ const page = related.page && {
5
+ keys: related.page.keys,
6
+ limit: related.page.limit,
7
+ after: related.page.after
8
+ };
9
+ return [{
10
+ column: field.column,
11
+ resource: parent?.model.name,
12
+ key: parent?.key.column,
13
+ subfilter: related.filter,
14
+ ...page && { page },
15
+ terms: relatedTerms(parent?.scope)
16
+ }];
17
+ });
9
18
  /** The filter's structure without source spans, each field named by its column, so equal filters match however they were written. */
10
19
  const canonical = (filter) => JSON.stringify(filter, (key, value) => {
11
20
  if (key === "span") return void 0;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { CompileOptions, compileFilter } from "./compile-filter.js";
2
2
  import { Db } from "./db.js";
3
- import { ParentRead, Scope, tenantCondition } from "./scope.js";
3
+ import { KeyItemType, ParentRead, RelatedPage, Scope, tenantCondition } from "./scope.js";
4
4
  import { RelatedRowsQuery, buildRelatedRows, relatedRows } from "./related-rows.js";
5
5
  import { ExtraColumn, ListOptions, ListPlan, ListResult, buildListQuery, listQuery, maxLimit } from "./list-query.js";
6
6
  import { estimateCount } from "./estimate-count.js";
@@ -19,7 +19,8 @@ import { ScrollMode, scrollMode } from "./scroll-mode.js";
19
19
  import { IndexKey, TableIndex, TableIndexes, tableIndexes } from "./table-indexes.js";
20
20
  import { ColumnUse, CoverageQuery, IndexNeed, UncoveredColumn, indexServes, uncoveredColumns } from "./index-coverage.js";
21
21
  import { QueryError, QueryErrorCode } from "./fields/query-error.js";
22
+ import { RelatedPageRequest, relatedPage } from "./related-page.js";
22
23
  import { parentCondition } from "./read-conditions.js";
23
24
  import { readsParent } from "./reads-parent.js";
24
25
  import { SeekRequest, seekToPosition } from "./seek-to-position.js";
25
- 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 ListOptions, type ListPlan, type ListResult, type MapBounds, type MapBucket, type MapBuckets, type MapPosition, type Measure, type ParentRead, QueryError, type QueryErrorCode, 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, listQuery, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readsParent, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, withoutField };
26
+ 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 ListOptions, type ListPlan, type ListResult, type MapBounds, type MapBucket, type MapBuckets, type MapPosition, type Measure, type ParentRead, 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, listQuery, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readsParent, relatedPage, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, withoutField };
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ import { cellsAcross, checkMapPosition, mapBuckets, mapCellPixels, maxMapBuckets
17
17
  import { scrollMode } from "./scroll-mode.js";
18
18
  import { tableIndexes } from "./table-indexes.js";
19
19
  import { indexServes, uncoveredColumns } from "./index-coverage.js";
20
+ import { relatedPage } from "./related-page.js";
20
21
  import { readsParent } from "./reads-parent.js";
21
22
  import { seekToPosition } from "./seek-to-position.js";
22
- export { QueryError, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, compileFilter, countUpTo, estimateCount, exactCount, facetCounts, groupTotals, histogram, indexServes, listQuery, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readsParent, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, withoutField };
23
+ export { QueryError, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, compileFilter, countUpTo, estimateCount, exactCount, facetCounts, groupTotals, histogram, indexServes, listQuery, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readsParent, relatedPage, relatedRows, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, withoutField };
@@ -1,6 +1,6 @@
1
1
  import { Db } from "./db.js";
2
- import { Scope } from "./scope.js";
3
2
  import { SortKey } from "./sort.js";
3
+ import { Scope } from "./scope.js";
4
4
  import { ListQuery, ResourceModel } from "@protobase/schema";
5
5
  //#region src/list-query.d.ts
6
6
  export declare const maxLimit = 500;
@@ -1,11 +1,11 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
2
  import { columnRef, findField } from "./columns.js";
3
- import { baseQuery } from "./base-query.js";
3
+ import { orderTerm } from "./order.js";
4
4
  import { effectiveSort, flip } from "./sort.js";
5
+ import { seekCondition } from "./seek.js";
6
+ import { baseQuery } from "./base-query.js";
5
7
  import { decodeCursor, encodeCursor } from "./cursor.js";
6
8
  import { assertFilterRequirements } from "./filter-requirements.js";
7
- import { orderTerm } from "./order.js";
8
- import { seekCondition } from "./seek.js";
9
9
  import { sql } from "kysely";
10
10
  //#region src/list-query.ts
11
11
  const maxLimit = 500;
@@ -0,0 +1,28 @@
1
+ import { columnRef, tableSource } from "./columns.js";
2
+ import { orderTerm } from "./order.js";
3
+ import { seekCondition } from "./seek.js";
4
+ import { sql } from "kysely";
5
+ //#region src/parent-keys.ts
6
+ const whereAll = (conditions) => conditions.length === 0 ? sql`` : sql` where ${sql.join(conditions, sql` and `)}`;
7
+ const pageOf = (page, conditions) => {
8
+ const after = page?.after ? [seekCondition(page.keys, page.after, "after")] : [];
9
+ const where = whereAll([...conditions, ...after]);
10
+ if (page?.limit === void 0) return where;
11
+ return sql`${where} order by ${sql.join(page.keys.map((key) => orderTerm(key)))} limit ${page.limit}`;
12
+ };
13
+ /**
14
+ * The keys of the parent records the conditions keep, on the page the term reads: the parent's `key`, or, when it is a
15
+ * JSON list of keys, each item of each record's list that is a valid value of the item type. A record whose list is
16
+ * null, empty or no list at all adds none, and neither does an item such as `"x"` among integer keys.
17
+ */
18
+ const parentKeys = (parent, page, conditions) => {
19
+ const key = columnRef(parent.key);
20
+ const rows = sql`from ${tableSource(parent.model)}${pageOf(page, conditions)}`;
21
+ if (!parent.items) return sql`select ${key} ${rows}`;
22
+ const type = sql.raw(parent.items);
23
+ const list = sql`p.k::jsonb`;
24
+ const items = sql`jsonb_array_elements_text(case when jsonb_typeof(${list}) = 'array' then ${list} end) as e(v)`;
25
+ return sql`select e.v::${type} from (select ${key} as k ${rows}) as p cross join lateral ${items} where pg_input_is_valid(e.v, ${parent.items})`;
26
+ };
27
+ //#endregion
28
+ export { parentKeys };
@@ -5,7 +5,7 @@ import { ResourceModel } from "@protobase/schema";
5
5
  /**
6
6
  * `fk in (select key from parent where <the caller's scope on it>)`, or `false` when the caller reads no parent; a
7
7
  * nullable `fk` also keeps the rows that name no parent, unless this is a `related()` term, which also holds its
8
- * subfilter. The subquery aliases the parent `t` too, so its conditions read the parent's columns and only `fk` reads the
8
+ * subfilter and its page. The subquery aliases the parent `t` too, so its conditions read the parent's columns and only `fk` reads the
9
9
  * outer row.
10
10
  */
11
11
  export declare const parentCondition: (read: ParentRead) => Expression<SqlBool>;
@@ -1,5 +1,6 @@
1
- import { columnRef, tableSource } from "./columns.js";
1
+ import { columnRef } from "./columns.js";
2
2
  import { compileFilter } from "./compile-filter.js";
3
+ import { parentKeys } from "./parent-keys.js";
3
4
  import { fullModelOf, tenantCondition } from "./scope.js";
4
5
  import { sql } from "kysely";
5
6
  //#region src/read-conditions.ts
@@ -10,17 +11,16 @@ const softDeleteColumn = (model, name) => {
10
11
  /**
11
12
  * `fk in (select key from parent where <the caller's scope on it>)`, or `false` when the caller reads no parent; a
12
13
  * nullable `fk` also keeps the rows that name no parent, unless this is a `related()` term, which also holds its
13
- * subfilter. The subquery aliases the parent `t` too, so its conditions read the parent's columns and only `fk` reads the
14
+ * subfilter and its page. The subquery aliases the parent `t` too, so its conditions read the parent's columns and only `fk` reads the
14
15
  * outer row.
15
16
  */
16
17
  const parentCondition = (read) => {
17
18
  const column = columnRef(read.field);
18
19
  const { parent, related } = read;
19
20
  const subfilter = related?.filter ? [compileFilter(related.model, related.filter)] : [];
20
- const within = parent ? sql`${column} in (select ${columnRef(parent.key)} from ${tableSource(parent.model)}${whereAll([...readConditions(parent.model, parent.scope), ...subfilter])})` : sql`false`;
21
+ const within = parent ? sql`${column} in (${parentKeys(parent, related?.page, [...readConditions(parent.model, parent.scope), ...subfilter])})` : sql`false`;
21
22
  return read.field.nullable && !related ? sql`(${column} is null or ${within})` : within;
22
23
  };
23
- const whereAll = (conditions) => conditions.length === 0 ? sql`` : sql` where ${sql.join(conditions, sql` and `)}`;
24
24
  /** What the scope hides of the table aliased as `t`: soft-deleted rows, other tenants, the row filter and unread parents. */
25
25
  const readConditions = (model, scope) => {
26
26
  const full = fullModelOf(model, scope);
@@ -0,0 +1,16 @@
1
+ import { RelatedPage, Scope } from "./scope.js";
2
+ import { CheckedFilter, ResourceModel, SortSpec } from "@protobase/schema";
3
+ //#region src/related-page.d.ts
4
+ /** What a `related()` term asks of its resource's read, as a list's `order_by`, `page_size` and `page_token` say it. */
5
+ export type RelatedPageRequest = {
6
+ sort?: SortSpec;
7
+ limit?: number;
8
+ cursor?: string;
9
+ };
10
+ /**
11
+ * The page a list of `model` with `filter` in `scope` would read for the same order, size and token, so a `related()`
12
+ * term keeps to exactly the records that page shows: the limit is capped as a list's page size is, and the token only
13
+ * continues the list it came from. A token needs a limit, as a page needs a size.
14
+ */
15
+ export declare const relatedPage: (model: ResourceModel, request: RelatedPageRequest, filter?: CheckedFilter, scope?: Scope) => RelatedPage;
16
+ //#endregion
@@ -0,0 +1,24 @@
1
+ import { QueryError } from "./fields/query-error.js";
2
+ import { effectiveSort } from "./sort.js";
3
+ import { decodeCursor } from "./cursor.js";
4
+ import "./list-query.js";
5
+ //#region src/related-page.ts
6
+ /**
7
+ * The page a list of `model` with `filter` in `scope` would read for the same order, size and token, so a `related()`
8
+ * term keeps to exactly the records that page shows: the limit is capped as a list's page size is, and the token only
9
+ * continues the list it came from. A token needs a limit, as a page needs a size.
10
+ */
11
+ const relatedPage = (model, request, filter, scope) => {
12
+ const { sort, limit, cursor } = request;
13
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1)) throw new QueryError("invalid_limit", "limit must be a positive integer");
14
+ if (cursor !== void 0 && limit === void 0) throw new QueryError("invalid_cursor", "A page token needs the page size it was read with");
15
+ const keys = effectiveSort(model, sort);
16
+ return {
17
+ ...sort && { sort },
18
+ keys,
19
+ ...limit !== void 0 && { limit: Math.min(limit, 500) },
20
+ ...cursor !== void 0 && { after: decodeCursor(cursor, keys, filter, scope) }
21
+ };
22
+ };
23
+ //#endregion
24
+ export { relatedPage };
@@ -1,8 +1,8 @@
1
1
  import { QueryError } from "./fields/query-error.js";
2
2
  import { columnRef, findField } from "./columns.js";
3
- import { baseQuery } from "./base-query.js";
4
- import { effectiveSort } from "./sort.js";
5
3
  import { orderTerm } from "./order.js";
4
+ import { effectiveSort } from "./sort.js";
5
+ import { baseQuery } from "./base-query.js";
6
6
  import "./list-query.js";
7
7
  import { sql } from "kysely";
8
8
  //#region src/related-rows.ts
package/dist/scope.d.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import { SortKey } from "./sort.js";
1
2
  import { Expression, SqlBool } from "kysely";
2
- import { CheckedFilter, FieldModel, ResourceModel } from "@protobase/schema";
3
+ import { CheckedFilter, FieldModel, ResourceModel, SortSpec } from "@protobase/schema";
3
4
  //#region src/scope.d.ts
4
5
  /**
5
6
  * Who is asking, and which rows they may see.
@@ -26,21 +27,36 @@ export type Scope = {
26
27
  /**
27
28
  * A relation whose parent the caller must read for a row to be seen: `field` of the full model, and the parent's full
28
29
  * model, key and the caller's scope on it; without `parent` the caller reads no parent, so only a null `field` is seen.
29
- * With `related` it is a `related()` term of the caller's filter instead: a null `field` is not seen, and `filter`,
30
- * checked against `model`, the resource as the caller sees it, narrows what is read.
30
+ * With `related` it is a `related()` term of the caller's filter instead: a null `field` is not seen, `filter`, checked
31
+ * against `model`, the resource as the caller sees it, narrows what is read, and `page` keeps to one page of it. A
32
+ * parent's `items` says its `key` is a JSON list of keys, read as that Postgres type.
31
33
  */
32
34
  export type ParentRead = {
33
35
  field: FieldModel;
34
36
  parent?: {
35
37
  model: ResourceModel;
36
38
  key: FieldModel;
39
+ items?: KeyItemType;
37
40
  scope: Scope;
38
41
  };
39
42
  related?: {
40
43
  model: ResourceModel;
41
44
  filter?: CheckedFilter;
45
+ page?: RelatedPage;
42
46
  };
43
47
  };
48
+ /** The Postgres types a JSON list's keys are read as. */
49
+ export type KeyItemType = 'integer' | 'bigint' | 'uuid' | 'text';
50
+ /**
51
+ * One page of a `related()` term's records, as a list reads it: `sort` as the caller asked for it, `keys` that sort with
52
+ * the primary key breaking ties, at most `limit` rows, after the row whose sort values are `after` when there is one.
53
+ */
54
+ export type RelatedPage = {
55
+ sort?: SortSpec;
56
+ keys: SortKey[];
57
+ limit?: number;
58
+ after?: Array<string | null>;
59
+ };
44
60
  /**
45
61
  * `tenant = value`, or `tenant in (values)`, for tenant models; throws when the scope is missing, so a forgotten scope
46
62
  * never leaks rows.
@@ -1,7 +1,7 @@
1
1
  import { columnRef } from "./columns.js";
2
+ import { orderTerm } from "./order.js";
2
3
  import { baseQuery } from "./base-query.js";
3
4
  import { encodeCursor } from "./cursor.js";
4
- import { orderTerm } from "./order.js";
5
5
  import { toNumber } from "./numbers.js";
6
6
  import { sql } from "kysely";
7
7
  //#region src/scroll-exact.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/query",
3
- "version": "0.98.1",
3
+ "version": "0.98.3",
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.98.1",
32
+ "@protobase/schema": "0.98.3",
33
33
  "kysely": "^0.29.6"
34
34
  }
35
35
  }