@protobase/query 0.133.2 → 0.133.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/index.d.ts CHANGED
@@ -36,4 +36,5 @@ import { EveryOrganization, OrganizationSource, ScopeOrganization, everyOrganiza
36
36
  import { ScopedDb, scopedDb } from "./table-scope/scoped-db.js";
37
37
  import { ScopePlugin } from "./table-scope/scope-plugin.js";
38
38
  import { scoped, unscoped } from "./table-scope/raw-tables.js";
39
- export { type ColumnUse, type CompileOptions, type CoverageQuery, type Db, type EveryOrganization, 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 Organization, type OrganizationSource, type ParentRead, type PerValue, QueryError, type QueryErrorCode, type RelatedPage, type RelatedPageRequest, type RelatedRowsQuery, type ScanRequests, type ScanResults, type Scope, type ScopeOrganization, ScopePlugin, ScopeRefused, type ScopedDb, type ScopedTable, type ScopedTables, 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, everyOrganization, exactCount, facetCounts, groupTotals, histogram, indexServes, isEveryOrganization, listPerValue, listQuery, lookupQueries, lookupRead, lookupReadOf, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readIdentity, readsParent, relatedPage, relatedRows, scoped, scopedDb, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, uncoveredLookupMatch, unscoped, withLookupRead, withoutField };
39
+ import { sameRowFilter } from "./same-row-filter.js";
40
+ export { type ColumnUse, type CompileOptions, type CoverageQuery, type Db, type EveryOrganization, 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 Organization, type OrganizationSource, type ParentRead, type PerValue, QueryError, type QueryErrorCode, type RelatedPage, type RelatedPageRequest, type RelatedRowsQuery, type ScanRequests, type ScanResults, type Scope, type ScopeOrganization, ScopePlugin, ScopeRefused, type ScopedDb, type ScopedTable, type ScopedTables, 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, everyOrganization, exactCount, facetCounts, groupTotals, histogram, indexServes, isEveryOrganization, listPerValue, listQuery, lookupQueries, lookupRead, lookupReadOf, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readIdentity, readsParent, relatedPage, relatedRows, sameRowFilter, scoped, scopedDb, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, uncoveredLookupMatch, unscoped, withLookupRead, withoutField };
package/dist/index.js CHANGED
@@ -32,4 +32,5 @@ import { ScopeRefused } from "./table-scope/scope-condition.js";
32
32
  import { scoped, unscoped } from "./table-scope/raw-tables.js";
33
33
  import { ScopePlugin } from "./table-scope/scope-plugin.js";
34
34
  import { scopedDb } from "./table-scope/scoped-db.js";
35
- export { QueryError, ScopePlugin, ScopeRefused, aggregateScan, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, columnRef, compileFilter, countUpTo, estimateCount, everyOrganization, exactCount, facetCounts, groupTotals, histogram, indexServes, isEveryOrganization, listPerValue, listQuery, lookupQueries, lookupRead, lookupReadOf, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readIdentity, readsParent, relatedPage, relatedRows, scoped, scopedDb, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, uncoveredLookupMatch, unscoped, withLookupRead, withoutField };
35
+ import { sameRowFilter } from "./same-row-filter.js";
36
+ export { QueryError, ScopePlugin, ScopeRefused, aggregateScan, buildListQuery, buildRelatedRows, cellsAcross, checkMapPosition, columnRef, compileFilter, countUpTo, estimateCount, everyOrganization, exactCount, facetCounts, groupTotals, histogram, indexServes, isEveryOrganization, listPerValue, listQuery, lookupQueries, lookupRead, lookupReadOf, mapBuckets, mapCellPixels, maxLimit, maxMapBuckets, maxMapZoom, parentCondition, readIdentity, readsParent, relatedPage, relatedRows, sameRowFilter, scoped, scopedDb, scrollMode, seekToPosition, series, splitSeries, tableIndexes, tenantCondition, uncoveredColumns, uncoveredFileColumns, uncoveredLookupMatch, unscoped, withLookupRead, withoutField };
@@ -0,0 +1,12 @@
1
+ import { Db } from "./db.js";
2
+ import { Scope } from "./scope.js";
3
+ import { RawBuilder } from "kysely";
4
+ import { CheckedFilter, ResourceModel } from "@protobase/schema";
5
+ //#region src/same-row-filter.d.ts
6
+ /**
7
+ * What a read keeps to as one filter on the row alone: its soft delete, tenant, row filter and parents (`readConditions`)
8
+ * and `filter`, with each subquery among them read once, all in one statement, in `trx`, so with its snapshot. Undefined
9
+ * for a read that keeps no row out, `false` when a part cannot be made to read the row alone.
10
+ */
11
+ export declare const sameRowFilter: (trx: Db, model: ResourceModel, scope: Scope | undefined, filter: CheckedFilter | undefined) => Promise<false | CheckedFilter | undefined>;
12
+ //#endregion
@@ -0,0 +1,168 @@
1
+ import { lookupReadOf } from "./lookup-read.js";
2
+ import { columnRef, tableSource } from "./columns.js";
3
+ import { compileFilter } from "./compile-filter.js";
4
+ import { parentKeys } from "./parent-keys.js";
5
+ import { fullModelOf } from "./scope.js";
6
+ import { readConditions } from "./read-conditions.js";
7
+ import { sql } from "kysely";
8
+ //#region src/same-row-filter.ts
9
+ const span = {
10
+ start: 0,
11
+ end: 0
12
+ };
13
+ const numeric = (field) => field.type === "integer" || field.type === "bigint";
14
+ const literalOf = (value, number) => number ? {
15
+ kind: "number",
16
+ value: Number(value),
17
+ raw: value,
18
+ span
19
+ } : {
20
+ kind: "string",
21
+ value,
22
+ span
23
+ };
24
+ const and = (args) => args.length === 1 ? args[0] : {
25
+ kind: "and",
26
+ args,
27
+ span
28
+ };
29
+ /**
30
+ * The read's filter with every condition that reads another row (a parent the caller must read, a `related()` term, a
31
+ * lookup field) resolved to the values it holds now, so the rest only reads the row itself: what a subscriber of the
32
+ * read checks each changed row against. Undefined when a part cannot be made so: a search over a lookup field.
33
+ */
34
+ const sameRowPlan = (model, scope, filter) => {
35
+ const full = fullModelOf(model, scope);
36
+ const subqueries = [];
37
+ const pending = (query) => subqueries.push(query) - 1;
38
+ const none = {
39
+ kind: "isNull",
40
+ field: full.fields[full.primaryKey[0]],
41
+ span
42
+ };
43
+ const among = (field, values, number) => values.length === 0 ? none : {
44
+ kind: "in",
45
+ field,
46
+ values: values.map((value) => literalOf(value, number)),
47
+ span
48
+ };
49
+ const lookupTerm = (node) => {
50
+ const read = lookupReadOf(node.field);
51
+ if (!read) return () => node;
52
+ const held = node.kind === "isNull" ? sql`${columnRef(read.value)} is not null` : compileFilter(read.model, {
53
+ ...node,
54
+ field: read.value
55
+ });
56
+ const matched = read.match.nullable ? [sql`${columnRef(read.match)} is not null`] : [];
57
+ const index = pending(sql`select ${columnRef(read.match)} from ${tableSource(read.model)} where ${sql.join([
58
+ ...read.conditions,
59
+ ...matched,
60
+ held
61
+ ], sql` and `)}`);
62
+ return (resolved) => {
63
+ const keys = resolved[index];
64
+ const linked = among(read.link, keys, numeric(read.match) || numeric(read.link));
65
+ if (node.kind !== "isNull") return linked;
66
+ const unlinked = {
67
+ kind: "not",
68
+ arg: linked,
69
+ span
70
+ };
71
+ return read.link.nullable && keys.length > 0 ? {
72
+ kind: "or",
73
+ args: [{
74
+ kind: "isNull",
75
+ field: read.link,
76
+ span
77
+ }, unlinked],
78
+ span
79
+ } : unlinked;
80
+ };
81
+ };
82
+ const walk = (node) => {
83
+ if (node.kind === "and" || node.kind === "or") {
84
+ const args = node.args.map(walk);
85
+ if (args.some((arg) => arg === void 0)) return;
86
+ return (resolved) => ({
87
+ kind: node.kind,
88
+ args: args.map((arg) => arg(resolved)),
89
+ span
90
+ });
91
+ }
92
+ if (node.kind === "not") {
93
+ const arg = walk(node.arg);
94
+ return arg && ((resolved) => ({
95
+ kind: "not",
96
+ arg: arg(resolved),
97
+ span
98
+ }));
99
+ }
100
+ if (node.kind === "search") return model.search?.some((name) => model.fields[name]?.lookup) ? void 0 : () => node;
101
+ return lookupTerm(node);
102
+ };
103
+ const parent = (read) => {
104
+ if (!read.parent) return () => read.field.nullable && !read.related ? {
105
+ kind: "isNull",
106
+ field: read.field,
107
+ span
108
+ } : none;
109
+ const subfilter = read.related?.filter ? [compileFilter(read.related.model, read.related.filter)] : [];
110
+ const index = pending(parentKeys(read.parent, read.related?.page, [...readConditions(read.parent.model, read.parent.scope), ...subfilter]));
111
+ return (resolved) => {
112
+ const keys = read.parent.items ? read.parent.items === "integer" || read.parent.items === "bigint" : numeric(read.parent.key);
113
+ const within = among(read.field, resolved[index], keys);
114
+ return read.field.nullable && !read.related ? {
115
+ kind: "or",
116
+ args: [{
117
+ kind: "isNull",
118
+ field: read.field,
119
+ span
120
+ }, within],
121
+ span
122
+ } : within;
123
+ };
124
+ };
125
+ const tenant = () => {
126
+ const name = full.tenant ?? model.tenant;
127
+ if (!name) return [];
128
+ const field = full.fields[name];
129
+ if (scope?.tenantValues) return [() => among(field, scope.tenantValues.map(String), numeric(field))];
130
+ if (scope?.tenantValue === void 0) throw new Error(`Resource "${model.name}" is tenant-scoped; pass scope.tenantValue`);
131
+ return [() => among(field, [String(scope.tenantValue)], numeric(field))];
132
+ };
133
+ const softDelete = full.softDelete ?? model.softDelete;
134
+ const parts = [
135
+ ...softDelete ? [() => ({
136
+ kind: "isNull",
137
+ field: full.fields[softDelete],
138
+ span
139
+ })] : [],
140
+ ...tenant(),
141
+ ...[
142
+ scope?.rowFilter,
143
+ scope?.within,
144
+ filter
145
+ ].filter((node) => node !== void 0).map(walk),
146
+ ...(scope?.parents ?? []).map(parent)
147
+ ];
148
+ if (parts.some((part) => part === void 0)) return;
149
+ return {
150
+ subqueries,
151
+ build: (resolved) => parts.length === 0 ? void 0 : and(parts.map((part) => part(resolved)))
152
+ };
153
+ };
154
+ /**
155
+ * What a read keeps to as one filter on the row alone: its soft delete, tenant, row filter and parents (`readConditions`)
156
+ * and `filter`, with each subquery among them read once, all in one statement, in `trx`, so with its snapshot. Undefined
157
+ * for a read that keeps no row out, `false` when a part cannot be made to read the row alone.
158
+ */
159
+ const sameRowFilter = async (trx, model, scope, filter) => {
160
+ const planned = sameRowPlan(model, scope, filter);
161
+ if (!planned) return false;
162
+ if (planned.subqueries.length === 0) return planned.build([]);
163
+ const columns = planned.subqueries.map((query, i) => sql`array(select v::text from (${query}) as s(v) where v is not null) as ${sql.id(`s${i}`)}`);
164
+ const { rows } = await sql`select ${sql.join(columns)}`.execute(trx);
165
+ return planned.build(planned.subqueries.map((_, i) => rows[0][`s${i}`]));
166
+ };
167
+ //#endregion
168
+ export { sameRowFilter, sameRowPlan };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/query",
3
- "version": "0.133.2",
3
+ "version": "0.133.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.133.2",
32
+ "@protobase/schema": "0.133.3",
33
33
  "kysely": "^0.29.6"
34
34
  }
35
35
  }