@protobase/query 0.0.0-stage → 0.1.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.
- package/LICENSE +202 -0
- package/dist/anchor-positions.js +37 -0
- package/dist/base-query.js +26 -0
- package/dist/columns.js +26 -0
- package/dist/compile-compare.js +25 -0
- package/dist/compile-filter.d.ts +10 -0
- package/dist/compile-filter.js +35 -0
- package/dist/compile-text-match.js +48 -0
- package/dist/cursor.js +52 -0
- package/dist/db.d.ts +5 -0
- package/dist/db.js +5 -0
- package/dist/estimate-count.d.ts +10 -0
- package/dist/estimate-count.js +35 -0
- package/dist/exact-count.d.ts +7 -0
- package/dist/exact-count.js +13 -0
- package/dist/explain-guard.d.ts +21 -0
- package/dist/explain-guard.js +42 -0
- package/dist/explain.js +10 -0
- package/dist/facet-counts.d.ts +16 -0
- package/dist/facet-counts.js +27 -0
- package/dist/field-values.js +36 -0
- package/dist/fields/bigint.js +13 -0
- package/dist/fields/boolean.js +8 -0
- package/dist/fields/country.js +5 -0
- package/dist/fields/currency.js +5 -0
- package/dist/fields/date.js +11 -0
- package/dist/fields/decimal.js +9 -0
- package/dist/fields/enum.js +9 -0
- package/dist/fields/integer.js +9 -0
- package/dist/fields/json.js +15 -0
- package/dist/fields/query-error.d.ts +8 -0
- package/dist/fields/query-error.js +12 -0
- package/dist/fields/relation.js +10 -0
- package/dist/fields/sql-common.js +30 -0
- package/dist/fields/text.js +10 -0
- package/dist/fields/timestamp.js +10 -0
- package/dist/fields/uuid.js +10 -0
- package/dist/filter-requirements.js +15 -0
- package/dist/histogram.d.ts +17 -0
- package/dist/histogram.js +57 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +12 -0
- package/dist/list-query.d.ts +40 -0
- package/dist/list-query.js +61 -0
- package/dist/numbers.js +5 -0
- package/dist/order.js +14 -0
- package/dist/prune-filter.js +26 -0
- package/dist/range-bound.js +15 -0
- package/dist/scope.d.ts +17 -0
- package/dist/scope.js +17 -0
- package/dist/scroll-anchors.js +68 -0
- package/dist/scroll-exact.js +27 -0
- package/dist/scroll-mode.d.ts +4 -0
- package/dist/scroll-mode.js +10 -0
- package/dist/scroll-stats.js +27 -0
- package/dist/seek-to-position.d.ts +20 -0
- package/dist/seek-to-position.js +30 -0
- package/dist/seek.js +52 -0
- package/dist/series.d.ts +33 -0
- package/dist/series.js +63 -0
- package/dist/sort.d.ts +8 -0
- package/dist/sort.js +33 -0
- package/dist/with-statement-timeout.js +32 -0
- package/package.json +31 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
//#region src/anchor-positions.ts
|
|
2
|
+
const comparators = {
|
|
3
|
+
integer: (a, b) => Number(a) - Number(b),
|
|
4
|
+
bigint: (a, b) => Number(a) - Number(b),
|
|
5
|
+
decimal: (a, b) => Number(a) - Number(b),
|
|
6
|
+
currency: (a, b) => Number(a) - Number(b),
|
|
7
|
+
date: (a, b) => Date.parse(a) - Date.parse(b),
|
|
8
|
+
timestamp: (a, b) => Date.parse(a) - Date.parse(b),
|
|
9
|
+
uuid: (a, b) => a < b ? -1 : a > b ? 1 : 0
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Approximate row position of each histogram bound, in ascending sort order.
|
|
13
|
+
* Histogram buckets hold equal shares of the rows that are neither NULL nor most-common values.
|
|
14
|
+
* Most-common values are interleaved by value where the type has a JS ordering that matches Postgres;
|
|
15
|
+
* for other types (text, enum) their rows are not counted below a bound, so positions are less precise.
|
|
16
|
+
*/
|
|
17
|
+
const ascendingAnchors = (stats, totalRows, type) => {
|
|
18
|
+
const buckets = stats.bounds.length - 1;
|
|
19
|
+
const compare = comparators[type];
|
|
20
|
+
const commonShare = stats.commonFrequencies.reduce((sum, frequency) => sum + frequency, 0);
|
|
21
|
+
const histogramShare = Math.max(0, 1 - stats.nullFraction - commonShare);
|
|
22
|
+
return stats.bounds.map((value, i) => {
|
|
23
|
+
const histogramRows = totalRows * histogramShare * i / buckets;
|
|
24
|
+
const commonRows = compare ? stats.commonValues.reduce((sum, common, j) => compare(common, value) < 0 ? sum + (stats.commonFrequencies[j] ?? 0) * totalRows : sum, 0) : 0;
|
|
25
|
+
return {
|
|
26
|
+
position: Math.round(histogramRows + commonRows),
|
|
27
|
+
value
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
/** Anchors for a descending sort: same bounds walked from the top, positions measured from the first row. */
|
|
32
|
+
const descendingAnchors = (ascending, totalRows) => ascending.map((anchor) => ({
|
|
33
|
+
position: Math.max(0, totalRows - anchor.position),
|
|
34
|
+
value: anchor.value
|
|
35
|
+
})).reverse();
|
|
36
|
+
//#endregion
|
|
37
|
+
export { ascendingAnchors, descendingAnchors };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { columnRef, tableSource } from "./columns.js";
|
|
2
|
+
import { compileFilter } from "./compile-filter.js";
|
|
3
|
+
import { fullModelOf, tenantCondition } from "./scope.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
//#region src/base-query.ts
|
|
6
|
+
const softDeleteColumn = (model, name) => {
|
|
7
|
+
const field = Object.hasOwn(model.fields, name) ? model.fields[name] : void 0;
|
|
8
|
+
return field ? columnRef(field) : sql`${sql.id("t", name)}`;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The table aliased as `t`, minus soft-deleted rows, inside the tenant and the access rule's row filter,
|
|
12
|
+
* narrowed by the user's filter. Every query starts here, so no query can see rows the scope hides.
|
|
13
|
+
*/
|
|
14
|
+
const baseQuery = (db, model, filter, scope) => {
|
|
15
|
+
const full = fullModelOf(model, scope);
|
|
16
|
+
const softDelete = full.softDelete ?? model.softDelete;
|
|
17
|
+
let query = db.selectFrom(tableSource(model));
|
|
18
|
+
if (softDelete) query = query.where(sql`${softDeleteColumn(full, softDelete)} is null`);
|
|
19
|
+
const tenant = tenantCondition(model, scope);
|
|
20
|
+
if (tenant) query = query.where(tenant);
|
|
21
|
+
if (scope?.rowFilter) query = query.where(compileFilter(full, scope.rowFilter));
|
|
22
|
+
if (filter) query = query.where(compileFilter(model, filter));
|
|
23
|
+
return query;
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
export { baseQuery };
|
package/dist/columns.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { QueryError } from "./fields/query-error.js";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
const columnRef = (field) => sql`${sql.id("t", field.column)}`;
|
|
4
|
+
const tableSource = (model) => {
|
|
5
|
+
const { schema, name } = model.table;
|
|
6
|
+
const table = schema ? sql.id(schema, name) : sql.id(name);
|
|
7
|
+
return sql`${table}`.as("t");
|
|
8
|
+
};
|
|
9
|
+
const findField = (model, name) => {
|
|
10
|
+
const field = Object.hasOwn(model.fields, name) ? model.fields[name] : void 0;
|
|
11
|
+
if (!field) throw new QueryError("unknown_field", `Unknown field "${name}" on resource "${model.name}"`);
|
|
12
|
+
return field;
|
|
13
|
+
};
|
|
14
|
+
const requireField = (model, name, capability) => {
|
|
15
|
+
const field = findField(model, name);
|
|
16
|
+
if (field[capability]) return field;
|
|
17
|
+
throw new QueryError(capability === "filterable" ? "not_filterable" : "not_sortable", `Field "${name}" is not ${capability}`);
|
|
18
|
+
};
|
|
19
|
+
/** Primary key entries may name a field or its column. */
|
|
20
|
+
const primaryKeyFields = (model) => model.primaryKey.map((key) => {
|
|
21
|
+
const field = Object.hasOwn(model.fields, key) ? model.fields[key] : Object.values(model.fields).find((candidate) => candidate.column === key);
|
|
22
|
+
if (!field) throw new QueryError("unknown_field", `Primary key "${key}" is not a field of "${model.name}"`);
|
|
23
|
+
return field;
|
|
24
|
+
});
|
|
25
|
+
//#endregion
|
|
26
|
+
export { columnRef, findField, primaryKeyFields, requireField, tableSource };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { wildcardPattern } from "./fields/text.js";
|
|
2
|
+
import { columnRef } from "./columns.js";
|
|
3
|
+
import { paramFor } from "./field-values.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
//#region src/compile-compare.ts
|
|
6
|
+
const operators = {
|
|
7
|
+
"=": "=",
|
|
8
|
+
"!=": "<>",
|
|
9
|
+
"<": "<",
|
|
10
|
+
"<=": "<=",
|
|
11
|
+
">": ">",
|
|
12
|
+
">=": ">="
|
|
13
|
+
};
|
|
14
|
+
/** `=` and `!=` on text with a `*` in the value become (NOT) ILIKE with the rest escaped. */
|
|
15
|
+
const compileCompare = ({ field, op, value }) => {
|
|
16
|
+
const col = columnRef(field);
|
|
17
|
+
if (field.type === "text" && (op === "=" || op === "!=") && value.kind === "string" && value.value.includes("*")) {
|
|
18
|
+
const pattern = wildcardPattern(value.value);
|
|
19
|
+
return op === "=" ? sql`${col} ilike ${pattern}` : sql`${col} not ilike ${pattern}`;
|
|
20
|
+
}
|
|
21
|
+
return sql`${col} ${sql.raw(operators[op])} ${paramFor(value, field)}`;
|
|
22
|
+
};
|
|
23
|
+
const compileIn = ({ field, values }) => sql`${columnRef(field)} in (${sql.join(values.map((value) => paramFor(value, field)))})`;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { compileCompare, compileIn };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Expression, SqlBool } from "kysely";
|
|
2
|
+
import { CheckedFilter, ResourceModel } from "@protobase/schema";
|
|
3
|
+
//#region src/compile-filter.d.ts
|
|
4
|
+
export type CompileOptions = {
|
|
5
|
+
/** Minimum pg_trgm similarity for `similar`, from 0.3 (the `%` operator's own floor) to 1. */
|
|
6
|
+
similarityThreshold?: number;
|
|
7
|
+
};
|
|
8
|
+
/** Compiles a checked filter; every user value becomes a bound parameter. */
|
|
9
|
+
export declare const compileFilter: (model: ResourceModel, filter: CheckedFilter, options?: CompileOptions) => Expression<SqlBool>;
|
|
10
|
+
//#endregion
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { jsonHas, jsonPresent } from "./fields/json.js";
|
|
2
|
+
import { QueryError } from "./fields/query-error.js";
|
|
3
|
+
import { columnRef } from "./columns.js";
|
|
4
|
+
import { compileCompare, compileIn } from "./compile-compare.js";
|
|
5
|
+
import { compileRegex, compileSearch, compileSimilar } from "./compile-text-match.js";
|
|
6
|
+
import { sql } from "kysely";
|
|
7
|
+
//#region src/compile-filter.ts
|
|
8
|
+
const defaultSimilarity = .3;
|
|
9
|
+
const combine = (parts, joiner) => {
|
|
10
|
+
if (parts.length === 0) return sql`${sql.lit(joiner === "and")}`;
|
|
11
|
+
return sql`(${sql.join(parts, sql` ${sql.raw(joiner)} `)})`;
|
|
12
|
+
};
|
|
13
|
+
const compileNode = (model, node, threshold) => {
|
|
14
|
+
switch (node.kind) {
|
|
15
|
+
case "and":
|
|
16
|
+
case "or": return combine(node.args.map((arg) => compileNode(model, arg, threshold)), node.kind);
|
|
17
|
+
case "not": return sql`not ${compileNode(model, node.arg, threshold)}`;
|
|
18
|
+
case "compare": return compileCompare(node);
|
|
19
|
+
case "in": return compileIn(node);
|
|
20
|
+
case "has": return jsonHas(columnRef(node.field), node.value);
|
|
21
|
+
case "present": return node.field.type === "json" ? jsonPresent(columnRef(node.field)) : sql`${columnRef(node.field)} is not null`;
|
|
22
|
+
case "isNull": return sql`${columnRef(node.field)} is null`;
|
|
23
|
+
case "regex": return compileRegex(node);
|
|
24
|
+
case "similar": return compileSimilar(node, threshold);
|
|
25
|
+
case "search": return compileSearch(model, node);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/** Compiles a checked filter; every user value becomes a bound parameter. */
|
|
29
|
+
const compileFilter = (model, filter, options = {}) => {
|
|
30
|
+
const threshold = options.similarityThreshold ?? defaultSimilarity;
|
|
31
|
+
if (!(threshold >= defaultSimilarity && threshold <= 1)) throw new QueryError("invalid_option", `similarityThreshold must be between ${defaultSimilarity} and 1`);
|
|
32
|
+
return compileNode(model, filter, threshold);
|
|
33
|
+
};
|
|
34
|
+
//#endregion
|
|
35
|
+
export { compileFilter };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { QueryError } from "./fields/query-error.js";
|
|
2
|
+
import { containsPattern } from "./fields/text.js";
|
|
3
|
+
import { columnRef, findField } from "./columns.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
import { searchTerms } from "@protobase/schema";
|
|
6
|
+
//#region src/compile-text-match.ts
|
|
7
|
+
const maxRegexLength = 200;
|
|
8
|
+
const compileRegex = ({ field, pattern }) => {
|
|
9
|
+
if (pattern.length > maxRegexLength) throw new QueryError("invalid_value", `Regex patterns are limited to ${maxRegexLength} characters`);
|
|
10
|
+
return sql`${columnRef(field)} ~* ${pattern}`;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* pg_trgm: `%` lets a trigram index prune candidates (it applies the session's default threshold, 0.3),
|
|
14
|
+
* and the explicit similarity() check enforces the requested threshold on top of it.
|
|
15
|
+
*/
|
|
16
|
+
const compileSimilar = ({ field, text }, threshold) => {
|
|
17
|
+
const col = columnRef(field);
|
|
18
|
+
return sql`(${col} % ${text} and similarity(${col}, ${text}) >= ${threshold})`;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Partial match across the resource's `search` fields: every whitespace-separated word of the text appears, ignoring
|
|
22
|
+
* case, somewhere in one of them. Each word is an ILIKE per column, so a pg_trgm index on a search column can serve it.
|
|
23
|
+
* A `digitsEnd` field instead matches when its digits end with the word's (spaces, `+` and dashes ignored, and only for
|
|
24
|
+
* words written like phone numbers), or with the whole text's when that is a phone number of several words; a pg_trgm
|
|
25
|
+
* index on `regexp_replace(column, '[^0-9]', '', 'g')` can serve it. `searchTerms` and `matchesSearch` (schema) are the
|
|
26
|
+
* same rules in memory. Text without words matches nothing. A null column is a non-match rather than unknown, so
|
|
27
|
+
* `NOT search(...)` keeps its rows.
|
|
28
|
+
*/
|
|
29
|
+
const compileSearch = (model, { text }) => {
|
|
30
|
+
const names = model.search ?? [];
|
|
31
|
+
if (names.length === 0) throw new QueryError("no_search_fields", `Resource "${model.name}" has no search fields; set model.search to use text search`);
|
|
32
|
+
const terms = searchTerms(text);
|
|
33
|
+
const words = terms.filter((term) => !term.whole);
|
|
34
|
+
if (words.length === 0) return sql`false`;
|
|
35
|
+
const matchesTerm = (term) => {
|
|
36
|
+
const matches = names.flatMap((name) => {
|
|
37
|
+
const col = sql`${columnRef(findField(model, name))}::text`;
|
|
38
|
+
if (model.searchMatch?.[name] === "digitsEnd") return term.digits ? [sql`(${col} is not null and regexp_replace(${col}, '[^0-9]', '', 'g') like ${`%${term.digits}`})`] : [];
|
|
39
|
+
return term.whole ? [] : [sql`(${col} is not null and ${col} ilike ${containsPattern(term.text)})`];
|
|
40
|
+
});
|
|
41
|
+
return matches.length > 0 ? sql`(${sql.join(matches, sql` or `)})` : sql`false`;
|
|
42
|
+
};
|
|
43
|
+
const allWords = sql`(${sql.join(words.map(matchesTerm), sql` and `)})`;
|
|
44
|
+
const whole = terms.find((term) => term.whole);
|
|
45
|
+
return whole ? sql`(${matchesTerm(whole)} or ${allWords})` : allWords;
|
|
46
|
+
};
|
|
47
|
+
//#endregion
|
|
48
|
+
export { compileRegex, compileSearch, compileSimilar };
|
package/dist/cursor.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { QueryError } from "./fields/query-error.js";
|
|
2
|
+
import { sortSignature } from "./sort.js";
|
|
3
|
+
//#region src/cursor.ts
|
|
4
|
+
const invalidCursor = () => new QueryError("invalid_cursor", "Cursor is malformed or does not match the requested sort");
|
|
5
|
+
const isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
6
|
+
const isCellList = (value) => Array.isArray(value) && value.every((item) => item === null || typeof item === "string");
|
|
7
|
+
/**
|
|
8
|
+
* Opaque cursor: the sort signature plus the row's sort values as text (so timestamps and bigints round-trip exactly,
|
|
9
|
+
* null for NULL values). The JSON is UTF-8 encoded before base64url, so any text value survives.
|
|
10
|
+
* `values` may be a prefix of the sort keys; such a boundary cursor is produced by scroll anchors.
|
|
11
|
+
*/
|
|
12
|
+
const encodeCursor = (keys, values) => {
|
|
13
|
+
const payload = {
|
|
14
|
+
s: sortSignature(keys).slice(0, values.length),
|
|
15
|
+
v: values
|
|
16
|
+
};
|
|
17
|
+
return toBase64Url(JSON.stringify(payload));
|
|
18
|
+
};
|
|
19
|
+
const decodeCursor = (cursor, keys) => {
|
|
20
|
+
const payload = parse(cursor);
|
|
21
|
+
const signature = sortSignature(keys);
|
|
22
|
+
const prefixOk = payload.s.length === payload.v.length && payload.s.every((part, i) => part === signature[i]);
|
|
23
|
+
const lengthOk = payload.v.length === keys.length || payload.v.length === 1;
|
|
24
|
+
if (!prefixOk || !lengthOk) throw invalidCursor();
|
|
25
|
+
return payload.v;
|
|
26
|
+
};
|
|
27
|
+
const parse = (cursor) => {
|
|
28
|
+
const payload = parseJson(cursor);
|
|
29
|
+
if (typeof payload !== "object" || payload === null) throw invalidCursor();
|
|
30
|
+
const { s, v } = payload;
|
|
31
|
+
if (!isStringList(s) || !isCellList(v)) throw invalidCursor();
|
|
32
|
+
return {
|
|
33
|
+
s,
|
|
34
|
+
v
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
const toBase64Url = (text) => btoa(String.fromCharCode(...new TextEncoder().encode(text))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
|
|
38
|
+
const fromBase64Url = (encoded) => {
|
|
39
|
+
const binary = atob(encoded.replaceAll("-", "+").replaceAll("_", "/"));
|
|
40
|
+
return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
|
|
41
|
+
};
|
|
42
|
+
/** atob throws DOMException (InvalidCharacterError) and TextDecoder/JSON throw TypeError/SyntaxError on garbage. */
|
|
43
|
+
const parseJson = (cursor) => {
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(fromBase64Url(cursor));
|
|
46
|
+
} catch (error) {
|
|
47
|
+
if (error instanceof SyntaxError || error instanceof TypeError || error instanceof DOMException) throw invalidCursor();
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
//#endregion
|
|
52
|
+
export { decodeCursor, encodeCursor };
|
package/dist/db.d.ts
ADDED
package/dist/db.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { Db } from "./db.js";
|
|
2
|
+
import { Scope } from "./scope.js";
|
|
3
|
+
import { CheckedFilter, ResourceModel } from "@protobase/schema";
|
|
4
|
+
//#region src/estimate-count.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Without a filter (and no soft delete, tenant or row filter to narrow by) this is pg_class.reltuples, which is O(1).
|
|
7
|
+
* Otherwise, or before the table was ever analyzed, it is the planner's row estimate.
|
|
8
|
+
*/
|
|
9
|
+
export declare const estimateCount: (db: Db, model: ResourceModel, filter?: CheckedFilter, scope?: Scope) => Promise<number>;
|
|
10
|
+
//#endregion
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { fullModelOf } from "./scope.js";
|
|
2
|
+
import { baseQuery } from "./base-query.js";
|
|
3
|
+
import { assertFilterRequirements } from "./filter-requirements.js";
|
|
4
|
+
import { quoteIdent } from "./db.js";
|
|
5
|
+
import { explainPlan } from "./explain.js";
|
|
6
|
+
import { toNumber } from "./numbers.js";
|
|
7
|
+
import { sql } from "kysely";
|
|
8
|
+
//#region src/estimate-count.ts
|
|
9
|
+
/** Planner estimate of the number of live rows matching the filter. */
|
|
10
|
+
const planEstimate = async (db, model, filter, scope) => {
|
|
11
|
+
await assertFilterRequirements(db, filter, scope);
|
|
12
|
+
const compiled = baseQuery(db, model, filter, scope).select(sql.lit(1).as("one")).compile();
|
|
13
|
+
const plan = await explainPlan(db, compiled);
|
|
14
|
+
return Math.round(plan["Plan Rows"]);
|
|
15
|
+
};
|
|
16
|
+
const tableReltuples = async (db, model) => {
|
|
17
|
+
const { schema, name } = model.table;
|
|
18
|
+
const qualified = schema ? `${quoteIdent(schema)}.${quoteIdent(name)}` : quoteIdent(name);
|
|
19
|
+
const result = await sql`
|
|
20
|
+
select reltuples::float8 as reltuples from pg_class where oid = to_regclass(${qualified})
|
|
21
|
+
`.execute(db);
|
|
22
|
+
return toNumber(result.rows[0]?.reltuples ?? -1);
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Without a filter (and no soft delete, tenant or row filter to narrow by) this is pg_class.reltuples, which is O(1).
|
|
26
|
+
* Otherwise, or before the table was ever analyzed, it is the planner's row estimate.
|
|
27
|
+
*/
|
|
28
|
+
const estimateCount = async (db, model, filter, scope) => {
|
|
29
|
+
const full = fullModelOf(model, scope);
|
|
30
|
+
if (filter || scope?.rowFilter || full.softDelete || full.tenant || model.softDelete || model.tenant) return planEstimate(db, model, filter, scope);
|
|
31
|
+
const reltuples = await tableReltuples(db, model);
|
|
32
|
+
return reltuples >= 0 ? Math.round(reltuples) : planEstimate(db, model);
|
|
33
|
+
};
|
|
34
|
+
//#endregion
|
|
35
|
+
export { estimateCount, planEstimate };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Db } from "./db.js";
|
|
2
|
+
import { Scope } from "./scope.js";
|
|
3
|
+
import { CheckedFilter, ResourceModel } from "@protobase/schema";
|
|
4
|
+
//#region src/exact-count.d.ts
|
|
5
|
+
/** Runs a real count(*); call only when the user asks for an exact total. */
|
|
6
|
+
export declare const exactCount: (db: Db, model: ResourceModel, filter?: CheckedFilter, scope?: Scope) => Promise<number>;
|
|
7
|
+
//#endregion
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { baseQuery } from "./base-query.js";
|
|
2
|
+
import { assertFilterRequirements } from "./filter-requirements.js";
|
|
3
|
+
import { toNumber } from "./numbers.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
//#region src/exact-count.ts
|
|
6
|
+
/** Runs a real count(*); call only when the user asks for an exact total. */
|
|
7
|
+
const exactCount = async (db, model, filter, scope) => {
|
|
8
|
+
await assertFilterRequirements(db, filter, scope);
|
|
9
|
+
const row = await baseQuery(db, model, filter, scope).select(sql`count(*)::text`.as("n")).executeTakeFirstOrThrow();
|
|
10
|
+
return toNumber(row.n);
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { exactCount };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Db } from "./db.js";
|
|
2
|
+
import { Compilable, CompiledQuery } from "kysely";
|
|
3
|
+
//#region src/explain-guard.d.ts
|
|
4
|
+
export type GuardOptions = {
|
|
5
|
+
/** A Seq Scan on a table with more rows than this is a finding. */
|
|
6
|
+
seqScanRows?: number;
|
|
7
|
+
/** A Sort over more rows than this is a finding. */
|
|
8
|
+
sortRows?: number;
|
|
9
|
+
};
|
|
10
|
+
export type GuardFinding = {
|
|
11
|
+
kind: 'seqScan' | 'sort';
|
|
12
|
+
relation?: string;
|
|
13
|
+
rows: number;
|
|
14
|
+
};
|
|
15
|
+
export type GuardReport = {
|
|
16
|
+
ok: boolean;
|
|
17
|
+
findings: GuardFinding[];
|
|
18
|
+
};
|
|
19
|
+
/** Plans the query (never executes it) and reports expensive nodes (Seq Scan and Parallel Seq Scan). Pass a Kysely query or a compiled one. */
|
|
20
|
+
export declare const explainGuard: (db: Db, query: Compilable<unknown> | CompiledQuery, options?: GuardOptions) => Promise<GuardReport>;
|
|
21
|
+
//#endregion
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { quoteIdent } from "./db.js";
|
|
2
|
+
import { explainPlan, walkPlan } from "./explain.js";
|
|
3
|
+
import { toNumber } from "./numbers.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
//#region src/explain-guard.ts
|
|
6
|
+
const relationRows = async (db, schema, relation, planRows) => {
|
|
7
|
+
const qualified = schema ? `${quoteIdent(schema)}.${quoteIdent(relation)}` : quoteIdent(relation);
|
|
8
|
+
const result = await sql`
|
|
9
|
+
select reltuples::float8 as reltuples from pg_class where oid = to_regclass(${qualified})
|
|
10
|
+
`.execute(db);
|
|
11
|
+
const reltuples = toNumber(result.rows[0]?.reltuples ?? -1);
|
|
12
|
+
return reltuples >= 0 ? reltuples : planRows;
|
|
13
|
+
};
|
|
14
|
+
/** Plans the query (never executes it) and reports expensive nodes (Seq Scan and Parallel Seq Scan). Pass a Kysely query or a compiled one. */
|
|
15
|
+
const explainGuard = async (db, query, options = {}) => {
|
|
16
|
+
const { seqScanRows = 1e4, sortRows = 1e5 } = options;
|
|
17
|
+
const compiled = "sql" in query ? query : query.compile();
|
|
18
|
+
const nodes = walkPlan(await explainPlan(db, compiled));
|
|
19
|
+
const findings = [];
|
|
20
|
+
for (const node of nodes) {
|
|
21
|
+
const type = node["Node Type"];
|
|
22
|
+
const relation = node["Relation Name"];
|
|
23
|
+
if (type.endsWith("Seq Scan") && relation) {
|
|
24
|
+
const rows = await relationRows(db, node.Schema, relation, node["Plan Rows"]);
|
|
25
|
+
if (rows > seqScanRows) findings.push({
|
|
26
|
+
kind: "seqScan",
|
|
27
|
+
relation,
|
|
28
|
+
rows
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if ((type === "Sort" || type === "Incremental Sort") && node["Plan Rows"] > sortRows) findings.push({
|
|
32
|
+
kind: "sort",
|
|
33
|
+
rows: node["Plan Rows"]
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
ok: findings.length === 0,
|
|
38
|
+
findings
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
//#endregion
|
|
42
|
+
export { explainGuard };
|
package/dist/explain.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { CompiledQuery } from "kysely";
|
|
2
|
+
//#region src/explain.ts
|
|
3
|
+
/** Plans a compiled query without executing it (EXPLAIN, never ANALYZE; VERBOSE adds each relation's schema). */
|
|
4
|
+
const explainPlan = async (db, compiled) => {
|
|
5
|
+
const output = (await db.executeQuery(CompiledQuery.raw(`EXPLAIN (VERBOSE, FORMAT JSON) ${compiled.sql}`, [...compiled.parameters]))).rows[0]["QUERY PLAN"];
|
|
6
|
+
return (typeof output === "string" ? JSON.parse(output) : output)[0].Plan;
|
|
7
|
+
};
|
|
8
|
+
const walkPlan = (node) => [node, ...(node.Plans ?? []).flatMap(walkPlan)];
|
|
9
|
+
//#endregion
|
|
10
|
+
export { explainPlan, walkPlan };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Db } from "./db.js";
|
|
2
|
+
import { Scope } from "./scope.js";
|
|
3
|
+
import { CheckedFilter, ResourceModel } from "@protobase/schema";
|
|
4
|
+
//#region src/facet-counts.d.ts
|
|
5
|
+
export type FacetOptions = {
|
|
6
|
+
statementTimeoutMs: number;
|
|
7
|
+
limit?: number;
|
|
8
|
+
scope?: Scope;
|
|
9
|
+
};
|
|
10
|
+
export type FacetCount = {
|
|
11
|
+
value: unknown;
|
|
12
|
+
count: number;
|
|
13
|
+
};
|
|
14
|
+
/** Counts per value of `field`, with every filter applied except the ones on `field` itself. */
|
|
15
|
+
export declare const facetCounts: (db: Db, model: ResourceModel, field: string, filter: CheckedFilter | undefined, options: FacetOptions) => Promise<FacetCount[]>;
|
|
16
|
+
//#endregion
|