@protobase/query 0.99.0 → 0.99.1
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/group-totals.d.ts +10 -1
- package/dist/group-totals.js +14 -5
- package/dist/index-coverage.d.ts +11 -4
- package/dist/index-coverage.js +24 -3
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/list-per-value.d.ts +17 -0
- package/dist/list-per-value.js +29 -0
- package/dist/list-query.js +2 -1
- package/dist/related-rows.d.ts +19 -11
- package/dist/related-rows.js +33 -14
- package/package.json +2 -2
package/dist/group-totals.d.ts
CHANGED
|
@@ -9,9 +9,18 @@ export type GroupTotalsOptions = {
|
|
|
9
9
|
measure?: Measure;
|
|
10
10
|
limit?: number;
|
|
11
11
|
scope?: Scope;
|
|
12
|
+
/** Groups by `field` too and keeps, per value of it, the first `limit` groups. */
|
|
13
|
+
per?: {
|
|
14
|
+
field: string;
|
|
15
|
+
limit: number;
|
|
16
|
+
};
|
|
12
17
|
};
|
|
13
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
* One value of the grouped field: how many rows have it and, with a measure, their sum or average; with `per`, the
|
|
20
|
+
* value of the per field it is a group of.
|
|
21
|
+
*/
|
|
14
22
|
export type GroupTotal = {
|
|
23
|
+
per?: unknown;
|
|
15
24
|
value: unknown;
|
|
16
25
|
count: number;
|
|
17
26
|
sum?: number | null;
|
package/dist/group-totals.js
CHANGED
|
@@ -2,6 +2,7 @@ import { QueryError } from "./fields/query-error.js";
|
|
|
2
2
|
import { columnRef, requireField } from "./columns.js";
|
|
3
3
|
import { baseQuery } from "./base-query.js";
|
|
4
4
|
import { assertFilterRequirements } from "./filter-requirements.js";
|
|
5
|
+
import { checkPerLimit, firstPerValue, ownerAlias, rankAlias } from "./related-rows.js";
|
|
5
6
|
import { toNumber } from "./numbers.js";
|
|
6
7
|
import { withStatementTimeout } from "./with-statement-timeout.js";
|
|
7
8
|
import { measureSql, measureValue } from "./measure.js";
|
|
@@ -22,13 +23,21 @@ const groupTotals = async (db, model, field, options) => {
|
|
|
22
23
|
const amount = measure ? measureSql(model, measure) : void 0;
|
|
23
24
|
const column = columnRef(target);
|
|
24
25
|
await assertFilterRequirements(db, options.filter, options.scope);
|
|
26
|
+
const order = amount ? sql`${amount} desc nulls last, ${column} asc` : sql`count(*) desc, ${column} asc`;
|
|
27
|
+
const groups = (trx) => baseQuery(trx, model, options.filter, options.scope).select([
|
|
28
|
+
sql`${column}`.as("value"),
|
|
29
|
+
sql`count(*)::text`.as("n"),
|
|
30
|
+
...amount ? [sql`${amount}::text`.as("m")] : []
|
|
31
|
+
]).groupBy(column).orderBy(order);
|
|
32
|
+
const { per } = options;
|
|
33
|
+
if (per) checkPerLimit(per.limit);
|
|
25
34
|
return withStatementTimeout(db, options.statementTimeoutMs, async (trx) => {
|
|
26
|
-
return (await
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
]).groupBy(column).orderBy(amount ? sql`${amount} desc nulls last` : sql`count(*) desc`).orderBy(column, "asc").limit(limit).execute()).map((row) => {
|
|
35
|
+
return (per ? await firstPerValue(trx, model, {
|
|
36
|
+
field: per.field,
|
|
37
|
+
...options.filter && { filter: options.filter }
|
|
38
|
+
}, options.scope, (sameValue) => groups(trx).select(sql`row_number() over (order by ${order})`.as(rankAlias)).where(sameValue).limit(per.limit)).select(sql.ref(`k.${ownerAlias}`).as("per")).selectAll("r").limit(limit).execute() : await groups(trx).limit(limit).execute()).map((row) => {
|
|
31
39
|
const total = {
|
|
40
|
+
...per && { per: row.per },
|
|
32
41
|
value: row.value,
|
|
33
42
|
count: toNumber(row.n)
|
|
34
43
|
};
|
package/dist/index-coverage.d.ts
CHANGED
|
@@ -10,9 +10,10 @@ import { CheckedFilter, FieldModel, ResourceModel, SortSpec } from "@protobase/s
|
|
|
10
10
|
export type IndexNeed = 'btree' | 'trigram' | 'digits' | 'gin';
|
|
11
11
|
/**
|
|
12
12
|
* Where a column is read: the caller's filter, the access rule's row filter, the relation to a parent the caller must
|
|
13
|
-
* read (`.parent(fk, 'read')`), a `related()` term, the sort,
|
|
13
|
+
* read (`.parent(fk, 'read')`), a `related()` term, the sort, a facet's grouping, or the field a read keeps the first
|
|
14
|
+
* rows per value of (`limit_per`).
|
|
14
15
|
*/
|
|
15
|
-
export type ColumnUse = 'filter' | 'access' | 'parent' | 'related' | 'sort' | 'facet';
|
|
16
|
+
export type ColumnUse = 'filter' | 'access' | 'parent' | 'related' | 'sort' | 'facet' | 'per';
|
|
16
17
|
/** A column read without an index that serves it, and a statement that adds one. */
|
|
17
18
|
export type UncoveredColumn = {
|
|
18
19
|
field: string;
|
|
@@ -21,12 +22,16 @@ export type UncoveredColumn = {
|
|
|
21
22
|
need: IndexNeed;
|
|
22
23
|
suggestion: string;
|
|
23
24
|
};
|
|
24
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* What a read does with the table: the filter it keeps rows by, the order it walks them in, a field it groups by, the
|
|
27
|
+
* field a `related()` term selects, and the field it keeps the first rows per value of.
|
|
28
|
+
*/
|
|
25
29
|
export type CoverageQuery = {
|
|
26
30
|
filter?: CheckedFilter;
|
|
27
31
|
sort?: SortSpec;
|
|
28
32
|
groupBy?: string;
|
|
29
33
|
selects?: FieldModel;
|
|
34
|
+
per?: string;
|
|
30
35
|
};
|
|
31
36
|
/** Whether the index serves reading the column with the given need, while the query pins the `pinned` columns. */
|
|
32
37
|
export declare const indexServes: (index: TableIndex, column: string, need: IndexNeed, pinned: ReadonlySet<string>) => boolean;
|
|
@@ -36,7 +41,9 @@ export declare const indexServes: (index: TableIndex, column: string, need: Inde
|
|
|
36
41
|
* field, a grouped field and each relation to a parent the caller must read a btree index; the parent's own reads are
|
|
37
42
|
* judged against its table by a call of their own. Tenant, soft delete and `=` terms pin columns, so a later key of a
|
|
38
43
|
* btree index serves under them. A `related()` term is judged as a parent is and pins its relation as `in()` does, and
|
|
39
|
-
* the read of its resource also needs a btree index on the key it selects. A
|
|
44
|
+
* the read of its resource also needs a btree index on the key it selects. A read that keeps the first rows per value
|
|
45
|
+
* of a field needs a btree index on that field with the sort's first field under it, which serves the sort too.
|
|
46
|
+
* A plain view or a foreign table has no
|
|
40
47
|
* indexes of its own and is not judged.
|
|
41
48
|
*/
|
|
42
49
|
export declare const uncoveredColumns: (model: ResourceModel, table: TableIndexes, query: CoverageQuery, scope?: Scope) => UncoveredColumn[];
|
package/dist/index-coverage.js
CHANGED
|
@@ -7,8 +7,9 @@ const tableName = (model) => {
|
|
|
7
7
|
const { schema, name } = model.table;
|
|
8
8
|
return schema ? `${quoted(schema)}.${quoted(name)}` : quoted(name);
|
|
9
9
|
};
|
|
10
|
-
const suggestion = (model, column, need) => {
|
|
10
|
+
const suggestion = (model, column, need, under) => {
|
|
11
11
|
const table = tableName(model);
|
|
12
|
+
if (under !== void 0) return `create index on ${table} (${quoted(column)}, ${quoted(under)})`;
|
|
12
13
|
if (need === "trigram") return `create index on ${table} using gin (${quoted(column)} gin_trgm_ops)`;
|
|
13
14
|
if (need === "digits") return `create index on ${table} using gin ((regexp_replace(${quoted(column)}, '[^0-9]', '', 'g')) gin_trgm_ops)`;
|
|
14
15
|
if (need === "gin") return `create index on ${table} using gin (${quoted(column)})`;
|
|
@@ -48,6 +49,22 @@ const need = (ctx, field, kind, pinned, also) => ctx.indexes.some((index) => ind
|
|
|
48
49
|
need: kind,
|
|
49
50
|
suggestion: suggestion(ctx.model, field.column, kind)
|
|
50
51
|
}];
|
|
52
|
+
const perNeed = (ctx, per, sort, pinned) => {
|
|
53
|
+
if (!sort || sort.column === per.column) return need(ctx, per, "btree", pinned);
|
|
54
|
+
const under = /* @__PURE__ */ new Set([...pinned, per.column]);
|
|
55
|
+
const serves = (index) => {
|
|
56
|
+
const position = index.keys.findIndex((key) => key.column === sort.column);
|
|
57
|
+
return btreeServes(index, per.column, pinned) && btreeServes(index, sort.column, under) && index.keys.slice(0, position).some((key) => key.column === per.column);
|
|
58
|
+
};
|
|
59
|
+
if (ctx.indexes.some(serves)) return [];
|
|
60
|
+
return [{
|
|
61
|
+
field: per.name,
|
|
62
|
+
column: per.column,
|
|
63
|
+
use: ctx.use,
|
|
64
|
+
need: "btree",
|
|
65
|
+
suggestion: suggestion(ctx.model, per.column, "btree", sort.column)
|
|
66
|
+
}];
|
|
67
|
+
};
|
|
51
68
|
const compareNeed = (ctx, node, pinned) => {
|
|
52
69
|
if (isPatternCompare(node)) return need(ctx, node.field, "trigram", pinned);
|
|
53
70
|
return need(ctx, node.field, "btree", pinned, node.op === "=" && node.field.type === "text" ? "trigram" : void 0);
|
|
@@ -79,7 +96,9 @@ const unique = (columns) => columns.filter((column, i) => columns.findIndex((oth
|
|
|
79
96
|
* field, a grouped field and each relation to a parent the caller must read a btree index; the parent's own reads are
|
|
80
97
|
* judged against its table by a call of their own. Tenant, soft delete and `=` terms pin columns, so a later key of a
|
|
81
98
|
* btree index serves under them. A `related()` term is judged as a parent is and pins its relation as `in()` does, and
|
|
82
|
-
* the read of its resource also needs a btree index on the key it selects. A
|
|
99
|
+
* the read of its resource also needs a btree index on the key it selects. A read that keeps the first rows per value
|
|
100
|
+
* of a field needs a btree index on that field with the sort's first field under it, which serves the sort too.
|
|
101
|
+
* A plain view or a foreign table has no
|
|
83
102
|
* indexes of its own and is not judged.
|
|
84
103
|
*/
|
|
85
104
|
const uncoveredColumns = (model, table, query, scope) => {
|
|
@@ -101,13 +120,15 @@ const uncoveredColumns = (model, table, query, scope) => {
|
|
|
101
120
|
});
|
|
102
121
|
const sortField = query.sort?.[0] && model.fields[query.sort[0][0]];
|
|
103
122
|
const groupField = query.groupBy !== void 0 ? model.fields[query.groupBy] : void 0;
|
|
123
|
+
const perField = query.per !== void 0 ? model.fields[query.per] : void 0;
|
|
104
124
|
return unique([
|
|
105
125
|
...scope?.rowFilter ? walk(ctx("access", full), scope.rowFilter, pinned, false) : [],
|
|
106
126
|
...(scope?.parents ?? []).flatMap((read) => need(ctx(read.related ? "related" : "parent", full), read.field, "btree", pinned)),
|
|
107
127
|
...query.filter ? walk(ctx("filter"), query.filter, pinned, false) : [],
|
|
108
128
|
...scope?.within ? walk(ctx("filter", full), scope.within, pinned, false) : [],
|
|
109
129
|
...query.selects ? need(ctx("related", full), query.selects, "btree", pinned) : [],
|
|
110
|
-
...
|
|
130
|
+
...perField ? perNeed(ctx("per"), perField, sortField, pinned) : [],
|
|
131
|
+
...sortField && !perField ? need(ctx("sort"), sortField, "btree", pinned) : [],
|
|
111
132
|
...groupField ? need(ctx("facet"), groupField, "btree", pinned) : []
|
|
112
133
|
]);
|
|
113
134
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { CompileOptions, compileFilter } from "./compile-filter.js";
|
|
2
2
|
import { Db } from "./db.js";
|
|
3
3
|
import { KeyItemType, ParentRead, RelatedPage, Scope, tenantCondition } from "./scope.js";
|
|
4
|
-
import { RelatedRowsQuery, buildRelatedRows, relatedRows } from "./related-rows.js";
|
|
4
|
+
import { PerValue, RelatedRowsQuery, buildRelatedRows, relatedRows } from "./related-rows.js";
|
|
5
5
|
import { ExtraColumn, ListOptions, ListPlan, ListResult, buildListQuery, listQuery, maxLimit } from "./list-query.js";
|
|
6
|
+
import { LimitPer, listPerValue } from "./list-per-value.js";
|
|
6
7
|
import { estimateCount } from "./estimate-count.js";
|
|
7
8
|
import { exactCount } from "./exact-count.js";
|
|
8
9
|
import { countUpTo } from "./count-up-to.js";
|
|
@@ -23,4 +24,4 @@ import { RelatedPageRequest, relatedPage } from "./related-page.js";
|
|
|
23
24
|
import { parentCondition } from "./read-conditions.js";
|
|
24
25
|
import { readsParent } from "./reads-parent.js";
|
|
25
26
|
import { SeekRequest, seekToPosition } from "./seek-to-position.js";
|
|
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 };
|
|
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, withoutField };
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,7 @@ import { tenantCondition } from "./scope.js";
|
|
|
4
4
|
import { parentCondition } from "./read-conditions.js";
|
|
5
5
|
import { buildListQuery, listQuery, maxLimit } from "./list-query.js";
|
|
6
6
|
import { buildRelatedRows, relatedRows } from "./related-rows.js";
|
|
7
|
+
import { listPerValue } from "./list-per-value.js";
|
|
7
8
|
import { estimateCount } from "./estimate-count.js";
|
|
8
9
|
import { exactCount } from "./exact-count.js";
|
|
9
10
|
import { countUpTo } from "./count-up-to.js";
|
|
@@ -20,4 +21,4 @@ import { indexServes, uncoveredColumns } from "./index-coverage.js";
|
|
|
20
21
|
import { relatedPage } from "./related-page.js";
|
|
21
22
|
import { readsParent } from "./reads-parent.js";
|
|
22
23
|
import { seekToPosition } from "./seek-to-position.js";
|
|
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 };
|
|
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, withoutField };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Db } from "./db.js";
|
|
2
|
+
import { Scope } from "./scope.js";
|
|
3
|
+
import { ListOptions, ListResult } from "./list-query.js";
|
|
4
|
+
import { ListQuery, ResourceModel } from "@protobase/schema";
|
|
5
|
+
//#region src/list-per-value.d.ts
|
|
6
|
+
/** How many rows a list keeps per value of a field: `limit_per=<field>:<limit>`. */
|
|
7
|
+
export type LimitPer = {
|
|
8
|
+
field: string;
|
|
9
|
+
limit: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* A list that keeps, per value of `per.field` among the rows the filter finds, the first `per.limit` in the list's
|
|
13
|
+
* order: by value, then in that order within each value, at most `query.limit` rows in all. It has no further page, so
|
|
14
|
+
* it takes no cursor and answers none.
|
|
15
|
+
*/
|
|
16
|
+
export declare const listPerValue: (db: Db, model: ResourceModel, query: ListQuery, per: LimitPer, scope?: Scope, options?: ListOptions) => Promise<ListResult>;
|
|
17
|
+
//#endregion
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { QueryError } from "./fields/query-error.js";
|
|
2
|
+
import { assertFilterRequirements } from "./filter-requirements.js";
|
|
3
|
+
import { clampLimit, extraSelections } from "./list-query.js";
|
|
4
|
+
import { relatedRows } from "./related-rows.js";
|
|
5
|
+
//#region src/list-per-value.ts
|
|
6
|
+
/**
|
|
7
|
+
* A list that keeps, per value of `per.field` among the rows the filter finds, the first `per.limit` in the list's
|
|
8
|
+
* order: by value, then in that order within each value, at most `query.limit` rows in all. It has no further page, so
|
|
9
|
+
* it takes no cursor and answers none.
|
|
10
|
+
*/
|
|
11
|
+
const listPerValue = async (db, model, query, per, scope, options = {}) => {
|
|
12
|
+
if (query.cursor !== void 0) throw new QueryError("invalid_cursor", "A page token cannot continue a list that keeps the first rows per value");
|
|
13
|
+
const total = clampLimit(query.limit);
|
|
14
|
+
await assertFilterRequirements(db, query.filter, scope);
|
|
15
|
+
return {
|
|
16
|
+
rows: await relatedRows(db, model, {
|
|
17
|
+
field: per.field,
|
|
18
|
+
...query.filter && { filter: query.filter },
|
|
19
|
+
columns: query.columns ?? Object.keys(model.fields),
|
|
20
|
+
...query.sort && { sort: query.sort },
|
|
21
|
+
limit: per.limit,
|
|
22
|
+
total
|
|
23
|
+
}, scope, extraSelections(model, options.extraColumns)),
|
|
24
|
+
nextCursor: null,
|
|
25
|
+
prevCursor: null
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { listPerValue };
|
package/dist/list-query.js
CHANGED
|
@@ -15,6 +15,7 @@ const clampLimit = (limit) => {
|
|
|
15
15
|
return Math.min(limit, 500);
|
|
16
16
|
};
|
|
17
17
|
const requestedFields = (model, columns) => (columns ?? Object.keys(model.fields)).map((name) => findField(model, name));
|
|
18
|
+
/** The selections of `extraColumns`, refusing an alias that collides with a field or an internal column. */
|
|
18
19
|
const extraSelections = (model, extras = []) => extras.map(({ field, as, alias }) => {
|
|
19
20
|
if (as !== "text") throw new QueryError("invalid_option", "extraColumns only supports as: \"text\"");
|
|
20
21
|
if (Object.hasOwn(model.fields, alias) || alias.startsWith("__pb_key")) throw new QueryError("invalid_option", `extra column alias "${alias}" collides with a field or internal column`);
|
|
@@ -58,4 +59,4 @@ const listQuery = async (db, model, query, scope, options = {}) => {
|
|
|
58
59
|
};
|
|
59
60
|
};
|
|
60
61
|
//#endregion
|
|
61
|
-
export { buildListQuery, listQuery, maxLimit };
|
|
62
|
+
export { buildListQuery, clampLimit, extraSelections, listQuery, maxLimit };
|
package/dist/related-rows.d.ts
CHANGED
|
@@ -1,24 +1,32 @@
|
|
|
1
1
|
import { Db } from "./db.js";
|
|
2
2
|
import { Scope } from "./scope.js";
|
|
3
|
-
import {
|
|
3
|
+
import { AliasedRawBuilder, Expression, SelectQueryBuilder, SqlBool } from "kysely";
|
|
4
|
+
import { CheckedFilter, KeyValue, ResourceModel, SortSpec } from "@protobase/schema";
|
|
4
5
|
//#region src/related-rows.d.ts
|
|
5
|
-
/** The
|
|
6
|
-
export type
|
|
7
|
-
/** The field
|
|
6
|
+
/** The values of `field` a per-value read keeps: those among `values` when given, else every one the filter keeps. */
|
|
7
|
+
export type PerValue = {
|
|
8
|
+
/** The field the rows are counted per, such as a photo's `listing_id`. */
|
|
8
9
|
field: string;
|
|
9
|
-
/** The
|
|
10
|
-
values
|
|
10
|
+
/** The values to read rows of; every value of the rows the filter keeps when omitted. */
|
|
11
|
+
values?: readonly KeyValue[];
|
|
12
|
+
/** The rows it keeps, on both sides of the join: the values and the rows of each. */
|
|
13
|
+
filter?: CheckedFilter;
|
|
14
|
+
};
|
|
15
|
+
/** The rows of `model` per value of `field`, at most `limit` for each value, in `sort` order. */
|
|
16
|
+
export type RelatedRowsQuery = PerValue & {
|
|
11
17
|
/** The fields it reads, by name; `field` is always among them. */
|
|
12
18
|
columns: string[];
|
|
13
19
|
/** The order within each value; the primary key decides ties. */
|
|
14
20
|
sort?: SortSpec;
|
|
15
21
|
limit: number;
|
|
22
|
+
/** The most rows it reads over all values together; no cap when omitted. */
|
|
23
|
+
total?: number;
|
|
16
24
|
};
|
|
17
25
|
/**
|
|
18
|
-
* The query `relatedRows` runs:
|
|
19
|
-
*
|
|
26
|
+
* The query `relatedRows` runs: per value of `field`, its first `limit` rows in `sort` order, with `extra` selected
|
|
27
|
+
* beside the columns. The result runs by value, then by `sort` within each value.
|
|
20
28
|
*/
|
|
21
|
-
export declare const buildRelatedRows: (db: Db, model: ResourceModel, query: RelatedRowsQuery, scope?: Scope) =>
|
|
29
|
+
export declare const buildRelatedRows: (db: Db, model: ResourceModel, query: RelatedRowsQuery, scope?: Scope, extra?: Array<AliasedRawBuilder<unknown, string>>) => SelectQueryBuilder<{
|
|
22
30
|
[x: string]: any;
|
|
23
31
|
[x: number]: any;
|
|
24
32
|
[x: symbol]: any;
|
|
@@ -27,7 +35,7 @@ export declare const buildRelatedRows: (db: Db, model: ResourceModel, query: Rel
|
|
|
27
35
|
}>;
|
|
28
36
|
/**
|
|
29
37
|
* The rows of every value in one query, in `sort` order for each value, with `field` holding the value they belong to.
|
|
30
|
-
*
|
|
38
|
+
* Given `values` are never read from the caller's input: they are the keys of records already read.
|
|
31
39
|
*/
|
|
32
|
-
export declare const relatedRows: (db: Db, model: ResourceModel, query: RelatedRowsQuery, scope?: Scope) => Promise<Array<Record<string, unknown>>>;
|
|
40
|
+
export declare const relatedRows: (db: Db, model: ResourceModel, query: RelatedRowsQuery, scope?: Scope, extra?: Array<AliasedRawBuilder<unknown, string>>) => Promise<Array<Record<string, unknown>>>;
|
|
33
41
|
//#endregion
|
package/dist/related-rows.js
CHANGED
|
@@ -8,28 +8,47 @@ import { sql } from "kysely";
|
|
|
8
8
|
//#region src/related-rows.ts
|
|
9
9
|
const ownerAlias = "__pb_owner";
|
|
10
10
|
const rankAlias = "__pb_rank";
|
|
11
|
+
/** Refuses a per-value limit outside a list's page sizes. */
|
|
12
|
+
const checkPerLimit = (limit) => {
|
|
13
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 500) throw new QueryError("invalid_limit", `limit must be a whole number from 1 to 500`);
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* The values of `per.field` that have rows, each joined to the rows `rowsOf` reads for it by a lateral subquery, so an
|
|
17
|
+
* index on the field and the order under it reads only those rows. `rowsOf` gets the condition that keeps a row to the
|
|
18
|
+
* value and selects `rankAlias`, its place within the value; the result runs by value, then by that place. The field is
|
|
19
|
+
* matched with `=`, so rows whose field is null have no value and are never read. Both sides stay inside the scope.
|
|
20
|
+
*/
|
|
21
|
+
const firstPerValue = (db, model, per, scope, rowsOf) => {
|
|
22
|
+
const owner = findField(model, per.field);
|
|
23
|
+
if (owner.type === "json") throw new QueryError("unsupported_field_type", `Cannot read rows per value of "${per.field}", which is json`);
|
|
24
|
+
let owners = baseQuery(db, model, per.filter, scope).select(sql`${columnRef(owner)}`.as(ownerAlias)).distinct();
|
|
25
|
+
if (per.values) owners = owners.where(sql`${columnRef(owner)} in (${sql.join(per.values)})`);
|
|
26
|
+
const sameValue = sql`${columnRef(owner)} = ${sql.ref(`k.${ownerAlias}`)}`;
|
|
27
|
+
return db.selectFrom(owners.as("k")).innerJoinLateral(rowsOf(sameValue).as("r"), (join) => join.onTrue()).orderBy(sql.ref(`k.${ownerAlias}`)).orderBy(sql.ref(`r.${rankAlias}`));
|
|
28
|
+
};
|
|
11
29
|
/**
|
|
12
|
-
* The query `relatedRows` runs:
|
|
13
|
-
*
|
|
30
|
+
* The query `relatedRows` runs: per value of `field`, its first `limit` rows in `sort` order, with `extra` selected
|
|
31
|
+
* beside the columns. The result runs by value, then by `sort` within each value.
|
|
14
32
|
*/
|
|
15
|
-
const buildRelatedRows = (db, model, query, scope) => {
|
|
16
|
-
|
|
17
|
-
const owner = findField(model, query.field);
|
|
33
|
+
const buildRelatedRows = (db, model, query, scope, extra = []) => {
|
|
34
|
+
checkPerLimit(query.limit);
|
|
18
35
|
const columns = [.../* @__PURE__ */ new Set([query.field, ...query.columns])].map((name) => findField(model, name));
|
|
19
36
|
const order = effectiveSort(model, query.sort).map((key) => orderTerm(key));
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
37
|
+
const built = firstPerValue(db, model, query, scope, (sameValue) => {
|
|
38
|
+
let rows = baseQuery(db, model, query.filter, scope).select(columns.map((field) => sql`${columnRef(field)}`.as(field.name))).select(extra).select(sql`row_number() over (order by ${sql.join(order)})`.as(rankAlias)).where(sameValue);
|
|
39
|
+
for (const term of order) rows = rows.orderBy(term);
|
|
40
|
+
return rows.limit(query.limit);
|
|
41
|
+
}).selectAll("r");
|
|
42
|
+
return query.total === void 0 ? built : built.limit(query.total);
|
|
24
43
|
};
|
|
25
44
|
/**
|
|
26
45
|
* The rows of every value in one query, in `sort` order for each value, with `field` holding the value they belong to.
|
|
27
|
-
*
|
|
46
|
+
* Given `values` are never read from the caller's input: they are the keys of records already read.
|
|
28
47
|
*/
|
|
29
|
-
const relatedRows = async (db, model, query, scope) => {
|
|
30
|
-
const built = buildRelatedRows(db, model, query, scope);
|
|
31
|
-
if (query.values
|
|
48
|
+
const relatedRows = async (db, model, query, scope, extra = []) => {
|
|
49
|
+
const built = buildRelatedRows(db, model, query, scope, extra);
|
|
50
|
+
if (query.values?.length === 0) return [];
|
|
32
51
|
return (await built.execute()).map(({ [rankAlias]: _rank, ...row }) => row);
|
|
33
52
|
};
|
|
34
53
|
//#endregion
|
|
35
|
-
export { buildRelatedRows, relatedRows };
|
|
54
|
+
export { buildRelatedRows, checkPerLimit, firstPerValue, ownerAlias, rankAlias, relatedRows };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/query",
|
|
3
|
-
"version": "0.99.
|
|
3
|
+
"version": "0.99.1",
|
|
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.99.
|
|
32
|
+
"@protobase/schema": "0.99.1",
|
|
33
33
|
"kysely": "^0.29.6"
|
|
34
34
|
}
|
|
35
35
|
}
|