dsqlbase 0.1.6 → 0.2.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/CHANGELOG.md +211 -0
- package/LICENSE +21 -0
- package/README.md +206 -2
- package/dist/client/create.d.ts +24 -4
- package/dist/client/create.d.ts.map +1 -1
- package/dist/client/create.js +21 -9
- package/dist/client/create.js.map +1 -1
- package/dist/client/database/base.d.ts +92 -1
- package/dist/client/database/base.d.ts.map +1 -1
- package/dist/client/database/base.js +196 -1
- package/dist/client/database/base.js.map +1 -1
- package/dist/client/database/client.d.ts +21 -5
- package/dist/client/database/client.d.ts.map +1 -1
- package/dist/client/database/client.js +39 -1
- package/dist/client/database/client.js.map +1 -1
- package/dist/client/database/index.d.ts +60 -4
- package/dist/client/database/index.d.ts.map +1 -1
- package/dist/client/database/index.js.map +1 -1
- package/dist/client/index.d.ts +4 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +4 -2
- package/dist/client/index.js.map +1 -1
- package/dist/client/model/base.d.ts +553 -136
- package/dist/client/model/base.d.ts.map +1 -1
- package/dist/client/model/base.js +1 -6
- package/dist/client/model/base.js.map +1 -1
- package/dist/client/model/client.d.ts +45 -8
- package/dist/client/model/client.d.ts.map +1 -1
- package/dist/client/model/client.js +58 -2
- package/dist/client/model/client.js.map +1 -1
- package/dist/client/model/filters.d.ts +276 -0
- package/dist/client/model/filters.d.ts.map +1 -0
- package/dist/client/model/filters.js +470 -0
- package/dist/client/model/filters.js.map +1 -0
- package/dist/client/model/normalizer.d.ts +127 -3
- package/dist/client/model/normalizer.d.ts.map +1 -1
- package/dist/client/model/normalizer.js +526 -106
- package/dist/client/model/normalizer.js.map +1 -1
- package/dist/client/nodes.d.ts +62 -0
- package/dist/client/nodes.d.ts.map +1 -0
- package/dist/client/nodes.js +378 -0
- package/dist/client/nodes.js.map +1 -0
- package/dist/client/pagination/cursor.d.ts +40 -0
- package/dist/client/pagination/cursor.d.ts.map +1 -0
- package/dist/client/pagination/cursor.js +79 -0
- package/dist/client/pagination/cursor.js.map +1 -0
- package/dist/client/pagination/page.d.ts +23 -0
- package/dist/client/pagination/page.d.ts.map +1 -0
- package/dist/client/pagination/page.js +37 -0
- package/dist/client/pagination/page.js.map +1 -0
- package/dist/client/transaction/index.js.map +1 -1
- package/dist/client/transaction/occ-retry.d.ts +2 -2
- package/dist/client/transaction/occ-retry.d.ts.map +1 -1
- package/dist/client/transaction/occ-retry.js.map +1 -1
- package/dist/client/transaction/transaction-client.d.ts +4 -6
- package/dist/client/transaction/transaction-client.d.ts.map +1 -1
- package/dist/client/transaction/transaction-client.js +7 -18
- package/dist/client/transaction/transaction-client.js.map +1 -1
- package/dist/client/union/client.d.ts +55 -0
- package/dist/client/union/client.d.ts.map +1 -0
- package/dist/client/union/client.js +74 -0
- package/dist/client/union/client.js.map +1 -0
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -2
- package/dist/index.js.map +1 -1
- package/dist/pg/index.d.ts +13 -1
- package/dist/pg/index.d.ts.map +1 -1
- package/dist/pg/index.js +52 -5
- package/dist/pg/index.js.map +1 -1
- package/dist/pglite/index.d.ts +7 -6
- package/dist/pglite/index.d.ts.map +1 -1
- package/dist/pglite/index.js +18 -4
- package/dist/pglite/index.js.map +1 -1
- package/dist/schema/columns/array.d.ts +12 -8
- package/dist/schema/columns/array.d.ts.map +1 -1
- package/dist/schema/columns/array.js +11 -14
- package/dist/schema/columns/array.js.map +1 -1
- package/dist/schema/columns/bigint.d.ts +1 -1
- package/dist/schema/columns/bigint.d.ts.map +1 -1
- package/dist/schema/columns/bigint.js +1 -0
- package/dist/schema/columns/bigint.js.map +1 -1
- package/dist/schema/columns/boolean.d.ts +1 -1
- package/dist/schema/columns/boolean.d.ts.map +1 -1
- package/dist/schema/columns/boolean.js +1 -0
- package/dist/schema/columns/boolean.js.map +1 -1
- package/dist/schema/columns/bytea.d.ts +1 -1
- package/dist/schema/columns/bytea.d.ts.map +1 -1
- package/dist/schema/columns/bytea.js +1 -0
- package/dist/schema/columns/bytea.js.map +1 -1
- package/dist/schema/columns/char.d.ts +1 -1
- package/dist/schema/columns/char.d.ts.map +1 -1
- package/dist/schema/columns/char.js +1 -0
- package/dist/schema/columns/char.js.map +1 -1
- package/dist/schema/columns/date.d.ts +3 -3
- package/dist/schema/columns/date.d.ts.map +1 -1
- package/dist/schema/columns/date.js +1 -0
- package/dist/schema/columns/date.js.map +1 -1
- package/dist/schema/columns/double.d.ts +1 -1
- package/dist/schema/columns/double.d.ts.map +1 -1
- package/dist/schema/columns/double.js +1 -0
- package/dist/schema/columns/double.js.map +1 -1
- package/dist/schema/columns/guid.d.ts +57 -0
- package/dist/schema/columns/guid.d.ts.map +1 -0
- package/dist/schema/columns/guid.js +53 -0
- package/dist/schema/columns/guid.js.map +1 -0
- package/dist/schema/columns/identity.d.ts +6 -6
- package/dist/schema/columns/identity.d.ts.map +1 -1
- package/dist/schema/columns/identity.js +2 -0
- package/dist/schema/columns/identity.js.map +1 -1
- package/dist/schema/columns/int.d.ts +1 -1
- package/dist/schema/columns/int.d.ts.map +1 -1
- package/dist/schema/columns/int.js +1 -0
- package/dist/schema/columns/int.js.map +1 -1
- package/dist/schema/columns/interval.d.ts +4 -3
- package/dist/schema/columns/interval.d.ts.map +1 -1
- package/dist/schema/columns/interval.js +1 -0
- package/dist/schema/columns/interval.js.map +1 -1
- package/dist/schema/columns/json.d.ts +79 -2
- package/dist/schema/columns/json.d.ts.map +1 -1
- package/dist/schema/columns/json.js +158 -8
- package/dist/schema/columns/json.js.map +1 -1
- package/dist/schema/columns/numeric.d.ts +61 -3
- package/dist/schema/columns/numeric.d.ts.map +1 -1
- package/dist/schema/columns/numeric.js +92 -6
- package/dist/schema/columns/numeric.js.map +1 -1
- package/dist/schema/columns/real.d.ts +1 -1
- package/dist/schema/columns/real.d.ts.map +1 -1
- package/dist/schema/columns/real.js +1 -0
- package/dist/schema/columns/real.js.map +1 -1
- package/dist/schema/columns/record.d.ts +20 -0
- package/dist/schema/columns/record.d.ts.map +1 -0
- package/dist/schema/columns/record.js +21 -0
- package/dist/schema/columns/record.js.map +1 -0
- package/dist/schema/columns/smallint.d.ts +1 -1
- package/dist/schema/columns/smallint.d.ts.map +1 -1
- package/dist/schema/columns/smallint.js +1 -0
- package/dist/schema/columns/smallint.js.map +1 -1
- package/dist/schema/columns/text.d.ts +1 -1
- package/dist/schema/columns/text.d.ts.map +1 -1
- package/dist/schema/columns/text.js +1 -0
- package/dist/schema/columns/text.js.map +1 -1
- package/dist/schema/columns/time.d.ts +3 -3
- package/dist/schema/columns/time.d.ts.map +1 -1
- package/dist/schema/columns/time.js +1 -0
- package/dist/schema/columns/time.js.map +1 -1
- package/dist/schema/columns/timestamp.d.ts +6 -6
- package/dist/schema/columns/timestamp.d.ts.map +1 -1
- package/dist/schema/columns/timestamp.js +1 -0
- package/dist/schema/columns/timestamp.js.map +1 -1
- package/dist/schema/columns/uuid.d.ts +1 -1
- package/dist/schema/columns/uuid.d.ts.map +1 -1
- package/dist/schema/columns/uuid.js +1 -0
- package/dist/schema/columns/uuid.js.map +1 -1
- package/dist/schema/columns/varchar.d.ts +1 -1
- package/dist/schema/columns/varchar.d.ts.map +1 -1
- package/dist/schema/columns/varchar.js +1 -0
- package/dist/schema/columns/varchar.js.map +1 -1
- package/dist/schema/domain.d.ts +2 -2
- package/dist/schema/domain.d.ts.map +1 -1
- package/dist/schema/domain.js +2 -0
- package/dist/schema/domain.js.map +1 -1
- package/dist/schema/embedded.d.ts +31 -0
- package/dist/schema/embedded.d.ts.map +1 -0
- package/dist/schema/embedded.js +33 -0
- package/dist/schema/embedded.js.map +1 -0
- package/dist/schema/index.d.ts +9 -1
- package/dist/schema/index.d.ts.map +1 -1
- package/dist/schema/index.js +6 -1
- package/dist/schema/index.js.map +1 -1
- package/dist/schema/namespace.js.map +1 -1
- package/dist/schema/relations.d.ts +17 -5
- package/dist/schema/relations.d.ts.map +1 -1
- package/dist/schema/relations.js +9 -0
- package/dist/schema/relations.js.map +1 -1
- package/dist/schema/sequence.js.map +1 -1
- package/dist/schema/table.d.ts +2 -2
- package/dist/schema/table.d.ts.map +1 -1
- package/dist/schema/table.js.map +1 -1
- package/dist/schema/tenant.d.ts +31 -0
- package/dist/schema/tenant.d.ts.map +1 -0
- package/dist/schema/tenant.js +33 -0
- package/dist/schema/tenant.js.map +1 -0
- package/dist/schema/union.d.ts +25 -0
- package/dist/schema/union.d.ts.map +1 -0
- package/dist/schema/union.js +27 -0
- package/dist/schema/union.js.map +1 -0
- package/dist/schema/utils/column-validation.d.ts +19 -0
- package/dist/schema/utils/column-validation.d.ts.map +1 -0
- package/dist/schema/utils/column-validation.js +37 -0
- package/dist/schema/utils/column-validation.js.map +1 -0
- package/dist/schema/utils/date.js.map +1 -1
- package/dist/schema/utils/duration.d.ts +2 -2
- package/dist/schema/utils/duration.d.ts.map +1 -1
- package/dist/schema/utils/duration.js.map +1 -1
- package/dist/schema/utils/global-id.d.ts +67 -0
- package/dist/schema/utils/global-id.d.ts.map +1 -0
- package/dist/schema/utils/global-id.js +99 -0
- package/dist/schema/utils/global-id.js.map +1 -0
- package/dist/schema/utils/standard-schema.d.ts +30 -0
- package/dist/schema/utils/standard-schema.d.ts.map +1 -0
- package/dist/schema/utils/standard-schema.js +2 -0
- package/dist/schema/utils/standard-schema.js.map +1 -0
- package/package.json +21 -16
- package/dist/schema/utils/json.d.ts +0 -2
- package/dist/schema/utils/json.d.ts.map +0 -1
- package/dist/schema/utils/json.js +0 -12
- package/dist/schema/utils/json.js.map +0 -1
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { KEY_FIELD } from "@dsqlbase/core/definition";
|
|
2
|
+
import { Column, ColumnGroup, sql, } from "@dsqlbase/core";
|
|
3
|
+
import { decodeMemberId, getDynamicGuidBinding } from "../nodes.js";
|
|
4
|
+
import { isGlobalId } from "../../schema/utils/global-id.js";
|
|
5
|
+
/**
|
|
6
|
+
* The `where` language: what a column of each runtime type can be filtered and ordered by, the
|
|
7
|
+
* filter types written from that table, and {@link WhereBuilder}, which enforces it while
|
|
8
|
+
* turning a `where` object into SQL. An operator the types refuse is also refused at runtime —
|
|
9
|
+
* before any SQL is built.
|
|
10
|
+
*/
|
|
11
|
+
const COMPARISON = ["eq", "neq", "in", "gt", "gte", "lt", "lte", "between", "exists"];
|
|
12
|
+
const PATTERN = ["beginsWith", "endsWith", "contains"];
|
|
13
|
+
const KEYED = ["hasKey"];
|
|
14
|
+
const comparable = {
|
|
15
|
+
operators: COMPARISON,
|
|
16
|
+
shorthand: true,
|
|
17
|
+
orderable: true,
|
|
18
|
+
distinct: true,
|
|
19
|
+
};
|
|
20
|
+
const document = {
|
|
21
|
+
operators: ["exists"],
|
|
22
|
+
shorthand: false,
|
|
23
|
+
orderable: false,
|
|
24
|
+
distinct: true,
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* `jsonb` equality and containment. `contains` means `@>` here, not `LIKE`: the value is a
|
|
28
|
+
* fragment of a document, matched recursively.
|
|
29
|
+
*/
|
|
30
|
+
const jsonbDocument = {
|
|
31
|
+
...document,
|
|
32
|
+
operators: ["eq", "neq", "contains", "exists"],
|
|
33
|
+
};
|
|
34
|
+
export const RUNTIME_TYPE_RULES = {
|
|
35
|
+
string: { ...comparable, operators: [...COMPARISON, ...PATTERN] },
|
|
36
|
+
uuid: comparable,
|
|
37
|
+
number: comparable,
|
|
38
|
+
bigint: comparable,
|
|
39
|
+
date: comparable,
|
|
40
|
+
interval: comparable,
|
|
41
|
+
boolean: { ...comparable, operators: ["eq", "neq", "exists"] },
|
|
42
|
+
bytes: document,
|
|
43
|
+
// `json` has no equality operator at all.
|
|
44
|
+
json: { ...document, distinct: false },
|
|
45
|
+
jsonb: jsonbDocument,
|
|
46
|
+
array: jsonbDocument,
|
|
47
|
+
object: { ...jsonbDocument, operators: [...jsonbDocument.operators, ...KEYED] },
|
|
48
|
+
};
|
|
49
|
+
/** Every operator any runtime type accepts — what tells an operator object from a value. */
|
|
50
|
+
export const FILTER_OPERATORS = new Set([
|
|
51
|
+
...COMPARISON,
|
|
52
|
+
...PATTERN,
|
|
53
|
+
...KEYED,
|
|
54
|
+
]);
|
|
55
|
+
/**
|
|
56
|
+
* Inside a column's filter, `where` is reserved for filtering into the column's value — a
|
|
57
|
+
* document's keys, later an embedded object's members. Reserved so that no operator takes the
|
|
58
|
+
* name; not supported yet.
|
|
59
|
+
*/
|
|
60
|
+
export const NESTED_FILTER = "where";
|
|
61
|
+
/** The runtime types stored as `jsonb`, where `contains` is containment (`@>`). */
|
|
62
|
+
export const JSONB_RUNTIME_TYPES = new Set([
|
|
63
|
+
"jsonb",
|
|
64
|
+
"array",
|
|
65
|
+
"object",
|
|
66
|
+
]);
|
|
67
|
+
/** The runtime types whose values can be plain objects: a `Duration`, a JSON document. */
|
|
68
|
+
const PLAIN_OBJECT_VALUES = new Set([
|
|
69
|
+
"interval",
|
|
70
|
+
"json",
|
|
71
|
+
"jsonb",
|
|
72
|
+
"object",
|
|
73
|
+
]);
|
|
74
|
+
function isPlainObject(value) {
|
|
75
|
+
if (typeof value !== "object" || value === null)
|
|
76
|
+
return false;
|
|
77
|
+
const prototype = Object.getPrototypeOf(value);
|
|
78
|
+
return prototype === Object.prototype || prototype === null;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A pattern operator's value as a `LIKE` literal: `%` and `_` match themselves, not any text.
|
|
82
|
+
* Backslash is PostgreSQL's default `LIKE` escape character, so it is escaped first.
|
|
83
|
+
*/
|
|
84
|
+
function escapeLike(value) {
|
|
85
|
+
return String(value).replace(/[\\%_]/g, "\\$&");
|
|
86
|
+
}
|
|
87
|
+
export function rulesOf(column) {
|
|
88
|
+
return RUNTIME_TYPE_RULES[column.runtimeType];
|
|
89
|
+
}
|
|
90
|
+
export function isFilterType(value, type) {
|
|
91
|
+
return (typeof value === "object" &&
|
|
92
|
+
value !== null &&
|
|
93
|
+
type in value &&
|
|
94
|
+
value[type] !== undefined);
|
|
95
|
+
}
|
|
96
|
+
/* -------------------------------------------------------------------------------------------
|
|
97
|
+
* Building
|
|
98
|
+
* ---------------------------------------------------------------------------------------- */
|
|
99
|
+
/**
|
|
100
|
+
* Turns a `where` object into one SQL node, checking every operator against the column's runtime
|
|
101
|
+
* type, encoding every value through the column's codec, and — across a union — checking shared
|
|
102
|
+
* fields and deciding `$$key` per member.
|
|
103
|
+
*/
|
|
104
|
+
export class WhereBuilder {
|
|
105
|
+
build(table, where) {
|
|
106
|
+
return this._build(table, undefined, where);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* A `where` over the fields of `table`, or — inside a group's nested `where` — over the members
|
|
110
|
+
* of `group`. The same language at every level: fields, `and` / `or` / `not`.
|
|
111
|
+
*/
|
|
112
|
+
_build(table, group, where, path = []) {
|
|
113
|
+
if (!where) {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
const expressions = [];
|
|
117
|
+
for (const [fieldName, condition] of Object.entries(where)) {
|
|
118
|
+
if ((fieldName === "and" || fieldName === "or") && Array.isArray(condition)) {
|
|
119
|
+
const children = condition
|
|
120
|
+
.map((expr) => this._build(table, group, expr, path))
|
|
121
|
+
.filter(Boolean);
|
|
122
|
+
// An empty group constrains nothing; left in, it would render as `()`. Nor does an `or`
|
|
123
|
+
// with a branch that matches every row (`{}`): dropping that branch would narrow it.
|
|
124
|
+
const everyRow = fieldName === "or" && children.length < condition.length;
|
|
125
|
+
if (children.length > 0 && !everyRow) {
|
|
126
|
+
expressions.push(sql.wrap(fieldName === "and" ? sql.and(children) : sql.or(children)));
|
|
127
|
+
}
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (fieldName === "not" &&
|
|
131
|
+
typeof condition === "object" &&
|
|
132
|
+
condition !== null &&
|
|
133
|
+
!Array.isArray(condition)) {
|
|
134
|
+
const shouldWrapNot = Object.keys(condition).length > 1;
|
|
135
|
+
const expr = this._build(table, group, condition, path);
|
|
136
|
+
if (expr) {
|
|
137
|
+
expressions.push(shouldWrapNot ? sql.wrap(sql.not(expr)) : sql.not(expr));
|
|
138
|
+
}
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const field = group ? group.getColumn(fieldName) : table.getColumn(fieldName);
|
|
142
|
+
const fieldPath = [...path, fieldName].join(".");
|
|
143
|
+
if (field instanceof ColumnGroup) {
|
|
144
|
+
expressions.push(...this._getGroupFilter(table, [...path, fieldName], field, condition));
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (!(field instanceof Column)) {
|
|
148
|
+
throw new Error(`Invalid field "${fieldPath}" in where clause for table "${table.name}".`);
|
|
149
|
+
}
|
|
150
|
+
expressions.push(...this._getColumnFilter(table, fieldPath, field, condition));
|
|
151
|
+
}
|
|
152
|
+
// `{}` selects everything, the same as no `where` at all — not an empty `WHERE`.
|
|
153
|
+
return expressions.length > 0 ? sql.and(expressions) : undefined;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* One column's filter, as its runtime type allows ({@link RUNTIME_TYPE_RULES}): a bare value means
|
|
157
|
+
* `{ eq: value }` where the type takes one, and every operator in an object adds a condition,
|
|
158
|
+
* AND-ed with the rest. Anything the type does not allow throws before SQL is built.
|
|
159
|
+
*/
|
|
160
|
+
_getColumnFilter(table, fieldName, column, condition) {
|
|
161
|
+
const rules = rulesOf(column);
|
|
162
|
+
const subject = `${column.runtimeType} column "${fieldName}" of "${table.name}"`;
|
|
163
|
+
if (!this._isOperatorObject(condition)) {
|
|
164
|
+
if (!rules.shorthand) {
|
|
165
|
+
throw new Error(`Filter the ${subject} with one of its operators (${rules.operators.join(", ")}), ` +
|
|
166
|
+
`not a bare value.`);
|
|
167
|
+
}
|
|
168
|
+
// An object naming no operator is a value only where values can be plain objects; on any
|
|
169
|
+
// other column it is a misspelt operator (`{ isNull: true }`), not a value to compare.
|
|
170
|
+
if (isPlainObject(condition) && !PLAIN_OBJECT_VALUES.has(column.runtimeType)) {
|
|
171
|
+
throw new Error(`Unknown operator ${Object.keys(condition)
|
|
172
|
+
.map((key) => `"${key}"`)
|
|
173
|
+
.join(", ")} in the filter on the ${subject} (valid: ${rules.operators.join(", ")}).`);
|
|
174
|
+
}
|
|
175
|
+
// Value shorthand: `{ id: "123" }` means `{ id: { eq: "123" } }`.
|
|
176
|
+
return [this._getOperatorFilter(column, "eq", condition)];
|
|
177
|
+
}
|
|
178
|
+
const nodes = [];
|
|
179
|
+
for (const [operator, value] of Object.entries(condition)) {
|
|
180
|
+
if (value === undefined) {
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
if (operator === NESTED_FILTER) {
|
|
184
|
+
throw new Error(`A nested \`where\` on the ${subject} is not supported yet.`);
|
|
185
|
+
}
|
|
186
|
+
if (!rules.operators.includes(operator)) {
|
|
187
|
+
throw new Error(FILTER_OPERATORS.has(operator)
|
|
188
|
+
? `Operator "${operator}" is not valid on the ${subject} ` +
|
|
189
|
+
`(valid: ${rules.operators.join(", ")}).`
|
|
190
|
+
: `Unknown operator "${operator}" in the filter on the ${subject}.`);
|
|
191
|
+
}
|
|
192
|
+
nodes.push(this._getOperatorFilter(column, operator, value));
|
|
193
|
+
}
|
|
194
|
+
return nodes;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* A column group's filter: `exists` — whether the group is present, by the rule it is read
|
|
198
|
+
* `null` by — and the nested `where` over its members. Members are only ever named inside
|
|
199
|
+
* `where`, so a member called `exists` cannot be mistaken for the operator.
|
|
200
|
+
*/
|
|
201
|
+
_getGroupFilter(table, path, group, condition) {
|
|
202
|
+
const subject = `group "${path.join(".")}" of "${table.name}"`;
|
|
203
|
+
if (typeof condition !== "object" ||
|
|
204
|
+
condition === null ||
|
|
205
|
+
Array.isArray(condition) ||
|
|
206
|
+
![Object.prototype, null].includes(Object.getPrototypeOf(condition))) {
|
|
207
|
+
throw new Error(`Filter the ${subject} with \`exists\` or a nested \`where\`, not a value.`);
|
|
208
|
+
}
|
|
209
|
+
const nodes = [];
|
|
210
|
+
for (const [operator, value] of Object.entries(condition)) {
|
|
211
|
+
if (value === undefined) {
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (operator === "exists") {
|
|
215
|
+
nodes.push(group.exists(Boolean(value)));
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
if (operator === NESTED_FILTER) {
|
|
219
|
+
const nested = this._build(table, group, value, path);
|
|
220
|
+
if (nested) {
|
|
221
|
+
nodes.push(nested);
|
|
222
|
+
}
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
throw new Error(`Operator "${operator}" is not valid on the ${subject} (valid: exists, ${NESTED_FILTER}); ` +
|
|
226
|
+
`filter its members inside \`${NESTED_FILTER}\`.`);
|
|
227
|
+
}
|
|
228
|
+
return nodes;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Whether a column's filter is an object of operators rather than a value: a plain object
|
|
232
|
+
* naming at least one. A value can itself be a plain object — an `interval` read as a
|
|
233
|
+
* `Duration`, a JSON document — so one that names no operator is a value.
|
|
234
|
+
*/
|
|
235
|
+
_isOperatorObject(condition) {
|
|
236
|
+
if (typeof condition !== "object" || condition === null) {
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
const prototype = Object.getPrototypeOf(condition);
|
|
240
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
return Object.keys(condition).some((key) => FILTER_OPERATORS.has(key) || key === NESTED_FILTER);
|
|
244
|
+
}
|
|
245
|
+
_getOperatorFilter(column, operator, value) {
|
|
246
|
+
// Comparison values go through `column.param` so the column's codec writes them the same
|
|
247
|
+
// way it wrote them on insert. Pattern operators stay raw: they compare against a `LIKE`
|
|
248
|
+
// pattern, not a column value. A `jsonb` fragment is encoded but, like every filter value,
|
|
249
|
+
// not validated, so a partial document reaches the database as given.
|
|
250
|
+
switch (operator) {
|
|
251
|
+
case "eq":
|
|
252
|
+
return (this._getPolymorphicFilter(column, value) ??
|
|
253
|
+
sql.eq(column, column.param(value)));
|
|
254
|
+
case "neq":
|
|
255
|
+
return (this._getPolymorphicFilter(column, { neq: value }) ??
|
|
256
|
+
sql.ne(column, column.param(value)));
|
|
257
|
+
case "in":
|
|
258
|
+
return (this._getPolymorphicFilter(column, { in: value }) ??
|
|
259
|
+
sql.in(column, value.map((item) => column.param(item))));
|
|
260
|
+
case "gt":
|
|
261
|
+
return sql.gt(column, column.param(value));
|
|
262
|
+
case "gte":
|
|
263
|
+
return sql.gte(column, column.param(value));
|
|
264
|
+
case "lt":
|
|
265
|
+
return sql.lt(column, column.param(value));
|
|
266
|
+
case "lte":
|
|
267
|
+
return sql.lte(column, column.param(value));
|
|
268
|
+
case "between": {
|
|
269
|
+
const [from, to] = value;
|
|
270
|
+
return sql `${column} BETWEEN ${column.param(from)} AND ${column.param(to)}`;
|
|
271
|
+
}
|
|
272
|
+
case "exists":
|
|
273
|
+
return value ? sql.isNotNull(column) : sql.isNull(column);
|
|
274
|
+
case "beginsWith":
|
|
275
|
+
return sql.like(column, `${escapeLike(value)}%`);
|
|
276
|
+
case "endsWith":
|
|
277
|
+
return sql.like(column, `%${escapeLike(value)}`);
|
|
278
|
+
case "contains":
|
|
279
|
+
if (!JSONB_RUNTIME_TYPES.has(column.runtimeType)) {
|
|
280
|
+
return sql.like(column, `%${escapeLike(value)}%`);
|
|
281
|
+
}
|
|
282
|
+
// On an array column the fragment lists items; a lone item would be ambiguous when the
|
|
283
|
+
// items are themselves arrays.
|
|
284
|
+
if (column.runtimeType === "array" && !Array.isArray(value)) {
|
|
285
|
+
throw new Error(`\`contains\` on the array column "${column.name}" of "${column.table.name}" ` +
|
|
286
|
+
`takes an array of items.`);
|
|
287
|
+
}
|
|
288
|
+
return sql.jsonbContains(column, column.param(value));
|
|
289
|
+
case "hasKey":
|
|
290
|
+
// A key, not a value: sent as is, never through the codec.
|
|
291
|
+
return sql.jsonbHasKey(column, value);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* The `where` of an operation that requires one — `findOne`, `update`, `delete` — refusing a
|
|
296
|
+
* filter that selects nothing in particular. `{}` means "every row" everywhere else; here it
|
|
297
|
+
* would pick an arbitrary row to read, or every row to change.
|
|
298
|
+
*/
|
|
299
|
+
buildRequired(table, where, operation) {
|
|
300
|
+
const expression = this.build(table, where);
|
|
301
|
+
if (!expression) {
|
|
302
|
+
throw new Error(`${operation} on "${table.name}" needs a where that names the rows it applies to; ` +
|
|
303
|
+
`an empty one would match every row.`);
|
|
304
|
+
}
|
|
305
|
+
return expression;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Refuses a field the members of `union` do not all share, anywhere in a shared `where` —
|
|
309
|
+
* inside `and` / `or` / `not` included. Checked on the union rather than per member, so the
|
|
310
|
+
* error names the union instead of whichever member happened to lack the field.
|
|
311
|
+
*/
|
|
312
|
+
assertShared(union, where) {
|
|
313
|
+
for (const [fieldName, condition] of Object.entries(where ?? {})) {
|
|
314
|
+
if ((fieldName === "and" || fieldName === "or") && Array.isArray(condition)) {
|
|
315
|
+
for (const child of condition) {
|
|
316
|
+
this.assertShared(union, child);
|
|
317
|
+
}
|
|
318
|
+
continue;
|
|
319
|
+
}
|
|
320
|
+
if (fieldName === "not" && typeof condition === "object" && condition !== null) {
|
|
321
|
+
this.assertShared(union, condition);
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (fieldName === KEY_FIELD) {
|
|
325
|
+
this._getKeyCondition(union, condition);
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (!union.isShared(fieldName)) {
|
|
329
|
+
throw new Error(`Invalid field "${fieldName}" in where for union "${union.alias}": only fields every ` +
|
|
330
|
+
`member shares filter across a union. Filter one member through \`on\`.`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* A `$$key` condition as a test on a member alias. `$$key` accepts `eq`, `neq`, `in` and the
|
|
336
|
+
* bare-value shorthand, each naming member aliases; anything else — another operator, a
|
|
337
|
+
* value that is not a member — is refused, since it could only ever be a typo.
|
|
338
|
+
*/
|
|
339
|
+
_getKeyCondition(union, condition) {
|
|
340
|
+
const assertMembers = (values) => {
|
|
341
|
+
for (const value of values) {
|
|
342
|
+
if (typeof value !== "string" || !union.hasMember(value)) {
|
|
343
|
+
throw new Error(`${KEY_FIELD} in where for union "${union.alias}" names ${JSON.stringify(value)}, ` +
|
|
344
|
+
`which is not a member (members: ${union.memberAliases.join(", ")}).`);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
if (typeof condition === "string") {
|
|
349
|
+
assertMembers([condition]);
|
|
350
|
+
return (alias) => alias === condition;
|
|
351
|
+
}
|
|
352
|
+
const entries = Object.entries((condition ?? {})).filter(([, value]) => value !== undefined);
|
|
353
|
+
const tests = entries.map(([operator, value]) => {
|
|
354
|
+
if (operator === "eq" || operator === "neq") {
|
|
355
|
+
assertMembers([value]);
|
|
356
|
+
return operator === "eq" ? (alias) => alias === value : (alias) => alias !== value;
|
|
357
|
+
}
|
|
358
|
+
if (operator === "in" && Array.isArray(value)) {
|
|
359
|
+
assertMembers(value);
|
|
360
|
+
return (alias) => value.includes(alias);
|
|
361
|
+
}
|
|
362
|
+
throw new Error(`${KEY_FIELD} in where for union "${union.alias}" accepts eq, neq and in; got "${operator}".`);
|
|
363
|
+
});
|
|
364
|
+
return (alias) => tests.every((test) => test(alias));
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* A shared `where` as seen from one member, with every `$$key` condition decided.
|
|
368
|
+
*
|
|
369
|
+
* Inside a branch the member alias is a constant, so a `$$key` condition is simply true or
|
|
370
|
+
* false there. Folding it away here, rather than rendering `'photos' = 'videos'` into SQL,
|
|
371
|
+
* lets a member that can never match be pruned before a branch is built at all:
|
|
372
|
+
*
|
|
373
|
+
* - `false` — no row of this member can match; the member produces no branch;
|
|
374
|
+
* - otherwise the `where` that is left, with every decided condition removed. An `or` holding
|
|
375
|
+
* a true child is dropped whole; a `not` flips its child.
|
|
376
|
+
*/
|
|
377
|
+
foldKey(union, where, alias) {
|
|
378
|
+
const residual = {};
|
|
379
|
+
for (const [fieldName, condition] of Object.entries(where)) {
|
|
380
|
+
if (fieldName === KEY_FIELD) {
|
|
381
|
+
if (!this._getKeyCondition(union, condition)(alias)) {
|
|
382
|
+
return false;
|
|
383
|
+
}
|
|
384
|
+
continue;
|
|
385
|
+
}
|
|
386
|
+
if ((fieldName === "and" || fieldName === "or") && Array.isArray(condition)) {
|
|
387
|
+
// An empty group constrains nothing, exactly as outside a union.
|
|
388
|
+
if (condition.length === 0) {
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
const children = condition.map((child) => this.foldKey(union, child, alias));
|
|
392
|
+
if (fieldName === "and") {
|
|
393
|
+
if (children.some((child) => child === false)) {
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
const kept = children.filter((child) => Object.keys(child).length > 0);
|
|
397
|
+
if (kept.length > 0) {
|
|
398
|
+
residual.and = kept;
|
|
399
|
+
}
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
// `or`: one child true for this member makes the whole group true.
|
|
403
|
+
if (children.some((child) => child !== false && Object.keys(child).length === 0)) {
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
const kept = children.filter((child) => child !== false);
|
|
407
|
+
if (kept.length === 0) {
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
residual.or = kept;
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
if (fieldName === "not" && typeof condition === "object" && condition !== null) {
|
|
414
|
+
const inner = this.foldKey(union, condition, alias);
|
|
415
|
+
if (inner === false) {
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
if (Object.keys(inner).length === 0 && Object.keys(condition).length > 0) {
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
residual.not = inner;
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
residual[fieldName] = condition;
|
|
425
|
+
}
|
|
426
|
+
return residual;
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* A filter on a polymorphic id. A global id names a member as well as a key, and two members
|
|
430
|
+
* may hold the same key, so matching it takes both: `(discriminator = key AND id = pk)`. `in`
|
|
431
|
+
* becomes an `OR` of such groups, raw uuids among them compared on the id alone. `undefined`
|
|
432
|
+
* for any other operator, or a filter with no global id in it — the ordinary path handles those.
|
|
433
|
+
*/
|
|
434
|
+
_getPolymorphicFilter(column, condition) {
|
|
435
|
+
const binding = getDynamicGuidBinding(column);
|
|
436
|
+
if (!binding) {
|
|
437
|
+
return undefined;
|
|
438
|
+
}
|
|
439
|
+
const { discriminator, members } = binding;
|
|
440
|
+
const match = (value) => {
|
|
441
|
+
const member = decodeMemberId(value, members);
|
|
442
|
+
return member
|
|
443
|
+
? sql.and([
|
|
444
|
+
sql.eq(discriminator, discriminator.param(member.key)),
|
|
445
|
+
sql.eq(column, column.param(member.value)),
|
|
446
|
+
])
|
|
447
|
+
: undefined;
|
|
448
|
+
};
|
|
449
|
+
if (isFilterType(condition, "in")) {
|
|
450
|
+
const values = condition.in;
|
|
451
|
+
if (!values.some(isGlobalId)) {
|
|
452
|
+
return undefined;
|
|
453
|
+
}
|
|
454
|
+
const raw = values.filter((value) => !isGlobalId(value));
|
|
455
|
+
const groups = values.flatMap((value) => isGlobalId(value) ? [sql.wrap(match(value))] : []);
|
|
456
|
+
if (raw.length > 0) {
|
|
457
|
+
groups.push(sql.in(column, raw.map((value) => column.param(value))));
|
|
458
|
+
}
|
|
459
|
+
return sql.wrap(sql.or(groups));
|
|
460
|
+
}
|
|
461
|
+
if (isFilterType(condition, "neq")) {
|
|
462
|
+
const group = match(condition.neq);
|
|
463
|
+
return group ? sql.not(group) : undefined;
|
|
464
|
+
}
|
|
465
|
+
const value = isFilterType(condition, "eq") ? condition.eq : condition;
|
|
466
|
+
const group = typeof value === "string" ? match(value) : undefined;
|
|
467
|
+
return group ? sql.wrap(group) : undefined;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
//# sourceMappingURL=filters.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"filters.js","sourceRoot":"","sources":["../../../src/client/model/filters.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAMtD,OAAO,EAIL,MAAM,EACN,WAAW,EACX,GAAG,GAIJ,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAS7D;;;;;GAKG;AAEH,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,CAAU,CAAC;AAC/F,MAAM,OAAO,GAAG,CAAC,YAAY,EAAE,UAAU,EAAE,UAAU,CAAU,CAAC;AAChE,MAAM,KAAK,GAAG,CAAC,QAAQ,CAAU,CAAC;AAkBlC,MAAM,UAAU,GAAqB;IACnC,SAAS,EAAE,UAAU;IACrB,SAAS,EAAE,IAAI;IACf,SAAS,EAAE,IAAI;IACf,QAAQ,EAAE,IAAI;CACf,CAAC;AACF,MAAM,QAAQ,GAAqB;IACjC,SAAS,EAAE,CAAC,QAAQ,CAAC;IACrB,SAAS,EAAE,KAAK;IAChB,SAAS,EAAE,KAAK;IAChB,QAAQ,EAAE,IAAI;CACf,CAAC;AAEF;;;GAGG;AACH,MAAM,aAAa,GAAqB;IACtC,GAAG,QAAQ;IACX,SAAS,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,CAAC;CAC/C,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAA0D;IACvF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E,EAAE,CACjD,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAY,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAC7D,CAAC;YAEF,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACnB,MAAM,CAAC,IAAI,CACT,GAAG,CAAC,EAAE,CACJ,MAAM,EACN,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,KAAiB,CAAC,CAAC,CACpD,CACF,CAAC;YACJ,CAAC;YAED,OAAO,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QAClC,CAAC;QAED,IAAI,YAAY,CAAC,SAAS,EAAE,KAAK,CAAC,EAAE,CAAC;YACnC,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;YACnC,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC5C,CAAC;QAED,MAAM,KAAK,GAAG,YAAY,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;QACvE,MAAM,KAAK,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAEnE,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC7C,CAAC;CACF","sourcesContent":["import { KEY_FIELD } from \"@dsqlbase/core/definition\";\nimport type {\n AnyColumnDefinition,\n ColumnConfig,\n ColumnRuntimeType,\n} from \"@dsqlbase/core/definition\";\nimport {\n AnyColumn,\n AnyColumnGroup,\n AnyTable,\n Column,\n ColumnGroup,\n sql,\n SQLNode,\n SQLValue,\n Union,\n} from \"@dsqlbase/core\";\nimport type { Prettify } from \"@dsqlbase/core/utils\";\nimport { decodeMemberId, getDynamicGuidBinding } from \"../nodes.js\";\nimport { isGlobalId } from \"../../schema/utils/global-id.js\";\nimport type {\n ColumnTypeOf,\n ColumnFieldNamesOf,\n GroupFieldNamesOf,\n GroupOf,\n ValueTypeOf,\n} from \"./base.js\";\n\n/**\n * The `where` language: what a column of each runtime type can be filtered and ordered by, the\n * filter types written from that table, and {@link WhereBuilder}, which enforces it while\n * turning a `where` object into SQL. An operator the types refuse is also refused at runtime —\n * before any SQL is built.\n */\n\nconst COMPARISON = [\"eq\", \"neq\", \"in\", \"gt\", \"gte\", \"lt\", \"lte\", \"between\", \"exists\"] as const;\nconst PATTERN = [\"beginsWith\", \"endsWith\", \"contains\"] as const;\nconst KEYED = [\"hasKey\"] as const;\n\nexport type FilterOperator =\n | (typeof COMPARISON)[number]\n | (typeof PATTERN)[number]\n | (typeof KEYED)[number];\n\nexport type RuntimeTypeRules = {\n /** The operators a filter on the column may use. */\n operators: readonly FilterOperator[];\n /** Whether a bare value stands for `{ eq: value }`. */\n shorthand: boolean;\n /** Whether the column can be an `orderBy` key. */\n orderable: boolean;\n /** Whether the database can compare two values for equality, which `distinct` needs. */\n distinct: boolean;\n};\n\nconst comparable: RuntimeTypeRules = {\n operators: COMPARISON,\n shorthand: true,\n orderable: true,\n distinct: true,\n};\nconst document: RuntimeTypeRules = {\n operators: [\"exists\"],\n shorthand: false,\n orderable: false,\n distinct: true,\n};\n\n/**\n * `jsonb` equality and containment. `contains` means `@>` here, not `LIKE`: the value is a\n * fragment of a document, matched recursively.\n */\nconst jsonbDocument: RuntimeTypeRules = {\n ...document,\n operators: [\"eq\", \"neq\", \"contains\", \"exists\"],\n};\n\nexport const RUNTIME_TYPE_RULES: Readonly<Record<ColumnRuntimeType, RuntimeTypeRules>> = {\n string: { ...comparable, operators: [...COMPARISON, ...PATTERN] },\n uuid: comparable,\n number: comparable,\n bigint: comparable,\n date: comparable,\n interval: comparable,\n boolean: { ...comparable, operators: [\"eq\", \"neq\", \"exists\"] },\n bytes: document,\n // `json` has no equality operator at all.\n json: { ...document, distinct: false },\n jsonb: jsonbDocument,\n array: jsonbDocument,\n object: { ...jsonbDocument, operators: [...jsonbDocument.operators, ...KEYED] },\n};\n\n/** Every operator any runtime type accepts — what tells an operator object from a value. */\nexport const FILTER_OPERATORS: ReadonlySet<string> = new Set<string>([\n ...COMPARISON,\n ...PATTERN,\n ...KEYED,\n]);\n\n/**\n * Inside a column's filter, `where` is reserved for filtering into the column's value — a\n * document's keys, later an embedded object's members. Reserved so that no operator takes the\n * name; not supported yet.\n */\nexport const NESTED_FILTER = \"where\";\n\n/** The runtime types stored as `jsonb`, where `contains` is containment (`@>`). */\nexport const JSONB_RUNTIME_TYPES: ReadonlySet<ColumnRuntimeType> = new Set([\n \"jsonb\",\n \"array\",\n \"object\",\n]);\n\n/** The runtime types whose values can be plain objects: a `Duration`, a JSON document. */\nconst PLAIN_OBJECT_VALUES: ReadonlySet<ColumnRuntimeType> = new Set([\n \"interval\",\n \"json\",\n \"jsonb\",\n \"object\",\n]);\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * A pattern operator's value as a `LIKE` literal: `%` and `_` match themselves, not any text.\n * Backslash is PostgreSQL's default `LIKE` escape character, so it is escaped first.\n */\nfunction escapeLike(value: unknown): string {\n return String(value).replace(/[\\\\%_]/g, \"\\\\$&\");\n}\n\nexport function rulesOf(column: AnyColumn): RuntimeTypeRules {\n return RUNTIME_TYPE_RULES[column.runtimeType];\n}\n\n/* -------------------------------------------------------------------------------------------\n * The same table, at type level\n * ---------------------------------------------------------------------------------------- */\n\n/** The operators a runtime type accepts. Mirrors {@link RUNTIME_TYPE_RULES}. */\nexport type OperatorsOf<R extends ColumnRuntimeType> = R extends \"string\"\n ? (typeof COMPARISON)[number] | (typeof PATTERN)[number]\n : R extends \"uuid\" | \"number\" | \"bigint\" | \"date\" | \"interval\"\n ? (typeof COMPARISON)[number]\n : R extends \"boolean\"\n ? \"eq\" | \"neq\" | \"exists\"\n : R extends \"object\"\n ? \"eq\" | \"neq\" | \"contains\" | \"hasKey\" | \"exists\"\n : R extends JsonbRuntimeType\n ? \"eq\" | \"neq\" | \"contains\" | \"exists\"\n : \"exists\";\n\n/** The runtime types stored as `jsonb`. Mirrors {@link JSONB_RUNTIME_TYPES}. */\nexport type JsonbRuntimeType = \"jsonb\" | \"array\" | \"object\";\n\n/**\n * What `contains` takes on runtime type `R` holding `V`: a substring on `string`, a fragment of\n * the document on a `jsonb` type — never `null`, and anything on an untyped document. On `array`\n * the fragment is itself an array, of item fragments.\n */\nexport type ContainsValueOf<R extends ColumnRuntimeType, V> = R extends \"string\"\n ? string\n : R extends JsonbRuntimeType\n ? unknown extends V\n ? unknown\n : JsonFragment<NonNullable<V>>\n : never;\n\n/**\n * A part of a JSON value, as `@>` matches it: any object member may be left out, at any depth,\n * and an array lists some of its items.\n */\nexport type JsonFragment<T> = T extends Date\n ? T\n : T extends readonly (infer I)[]\n ? JsonFragment<I>[]\n : T extends object\n ? { [K in keyof T]?: JsonFragment<T[K]> }\n : T;\n\n/** The runtime types where a bare value stands for `{ eq: value }`. */\nexport type ShorthandRuntimeType =\n | \"string\"\n | \"uuid\"\n | \"number\"\n | \"bigint\"\n | \"date\"\n | \"interval\"\n | \"boolean\";\n\n/** The runtime types a column can be ordered by. */\nexport type OrderableRuntimeType = ShorthandRuntimeType;\n\n/* -------------------------------------------------------------------------------------------\n * Filter types\n * ---------------------------------------------------------------------------------------- */\n\nexport type FilterCondition<Value = unknown> = {\n /**\n * Equality condition - matches records where the field is equal to the specified value.\n *\n * ```sql\n * \"table\".\"column\" = value\n * ```\n */\n eq?: Value;\n\n /**\n * Inequality condition - matches records where the field is not equal to the specified value.\n *\n * ```sql\n * \"table\".\"column\" <> value\n * ```\n */\n neq?: Value;\n\n /**\n * Greater than condition - matches records where the field is greater than the specified value.\n *\n * ```sql\n * \"table\".\"column\" > value\n * ```\n */\n gt?: Value;\n\n /**\n * Greater than or equal condition - matches records where the field is greater than or equal to the specified value.\n *\n * ```sql\n * \"table\".\"column\" >= value\n * ```\n */\n gte?: Value;\n\n /**\n * Less than condition - matches records where the field is less than the specified value.\n *\n * ```sql\n * \"table\".\"column\" < value\n * ```\n */\n lt?: Value;\n\n /**\n * Less than or equal condition - matches records where the field is less than or equal to the specified value.\n *\n * ```sql\n * \"table\".\"column\" <= value\n * ```\n */\n lte?: Value;\n\n /**\n * In condition - matches records where the field is equal to any of the values in the specified array.\n *\n * ```sql\n * \"table\".\"column\" IN (value1, value2, ...)\n * ```\n */\n in?: Value[];\n\n /**\n * Between condition - matches records where the field is between the two specified values (inclusive).\n *\n * ```sql\n * \"table\".\"column\" BETWEEN value1 AND value2\n * ```\n */\n between?: [Value, Value];\n\n /**\n * Exists condition - matches records where the field exists (is not null).\n *\n * ```sql\n * \"table\".\"column\" IS NOT NULL\n * ```\n */\n exists?: boolean;\n\n /**\n * Begins with condition - matches records where the field starts with the specified string.\n *\n * ```sql\n * \"table\".\"column\" LIKE 'value%'\n * ```\n */\n beginsWith?: string;\n\n /**\n * Ends with condition - matches records where the field ends with the specified string.\n *\n * ```sql\n * \"table\".\"column\" LIKE '%value'\n * ```\n */\n endsWith?: string;\n\n /**\n * Contains condition. On a string column, matches records where the field contains the\n * specified string; on a `jsonb` column, where the document contains the specified fragment\n * (see {@link ContainsValueOf}).\n *\n * ```sql\n * \"table\".\"column\" LIKE '%value%'\n * \"table\".\"column\" @> '{\"fragment\":true}'\n * ```\n */\n contains?: string;\n\n /**\n * Key condition, on a `record()` column - matches records whose object has the key at its top\n * level.\n *\n * ```sql\n * \"table\".\"column\" ? 'key'\n * ```\n */\n hasKey?: string;\n};\n\n/**\n * A filter on a value of runtime type `R` holding `V`: the operators the runtime type allows,\n * and, where it allows one, a bare value meaning `{ eq: value }`. Mirrors\n * {@link RUNTIME_TYPE_RULES}, which {@link WhereBuilder} enforces.\n */\nexport type FilterOf<R extends ColumnRuntimeType, V> =\n | Prettify<\n Pick<FilterCondition<V>, Exclude<OperatorsOf<R>, \"contains\">> &\n (\"contains\" extends OperatorsOf<R> ? { contains?: ContainsValueOf<R, V> } : unknown)\n >\n | (R extends ShorthandRuntimeType ? V : never);\n\n/** The filter a column accepts. */\nexport type ColumnFilterOf<C extends ColumnConfig> = FilterOf<C[\"runtimeType\"], ValueTypeOf<C>>;\n\nexport type WhereExpressionOf<T extends AnyTable> = {\n [K in ColumnFieldNamesOf<T>]?: T[\"__type\"][\"columns\"][K] extends AnyColumnDefinition\n ? ColumnFilterOf<ColumnTypeOf<T, K>>\n : never;\n} & {\n and?: WhereExpressionOf<T>[];\n or?: WhereExpressionOf<T>[];\n not?: WhereExpressionOf<T>;\n} & ([GroupFieldNamesOf<T>] extends [never]\n ? unknown\n : {\n [K in GroupFieldNamesOf<T>]?: T[\"__type\"][\"columns\"][K] extends GroupOf<infer C>\n ? GroupFilterOf<C>\n : never;\n });\n\n/**\n * A column group's filter: whether it is present, and a nested `where` over its members. Members\n * are named only inside `where`, never beside `exists`.\n */\nexport type GroupFilterOf<C> = {\n exists?: boolean;\n where?: MembersWhereOf<C>;\n};\n\n/** A nested `where` over a group's members: the same language as a table's. */\nexport type MembersWhereOf<C> = {\n -readonly [K in keyof C]?: C[K] extends GroupOf<infer GC>\n ? GroupFilterOf<GC>\n : C[K] extends { __type: infer TConfig extends ColumnConfig }\n ? ColumnFilterOf<TConfig>\n : never;\n} & {\n and?: MembersWhereOf<C>[];\n or?: MembersWhereOf<C>[];\n not?: MembersWhereOf<C>;\n};\n\nexport function isFilterType<T extends keyof FilterCondition>(\n value: unknown,\n type: T\n): value is Required<Pick<FilterCondition<SQLValue>, T>> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n type in value &&\n value[type as keyof typeof value] !== undefined\n );\n}\n\n/* -------------------------------------------------------------------------------------------\n * Building\n * ---------------------------------------------------------------------------------------- */\n\n/**\n * Turns a `where` object into one SQL node, checking every operator against the column's runtime\n * type, encoding every value through the column's codec, and — across a union — checking shared\n * fields and deciding `$$key` per member.\n */\nexport class WhereBuilder {\n public build<TTable extends AnyTable>(\n table: TTable,\n where: WhereExpressionOf<TTable> | null | undefined\n ): SQLNode | undefined {\n return this._build(table, undefined, where as Record<string, unknown> | null | undefined);\n }\n\n /**\n * A `where` over the fields of `table`, or — inside a group's nested `where` — over the members\n * of `group`. The same language at every level: fields, `and` / `or` / `not`.\n */\n private _build(\n table: AnyTable,\n group: AnyColumnGroup | undefined,\n where: Record<string, unknown> | null | undefined,\n path: string[] = []\n ): SQLNode | undefined {\n if (!where) {\n return undefined;\n }\n\n const expressions: SQLNode[] = [];\n\n for (const [fieldName, condition] of Object.entries(where)) {\n if ((fieldName === \"and\" || fieldName === \"or\") && Array.isArray(condition)) {\n const children = condition\n .map((expr) => this._build(table, group, expr as Record<string, unknown>, path))\n .filter(Boolean) as SQLNode[];\n\n // An empty group constrains nothing; left in, it would render as `()`. Nor does an `or`\n // with a branch that matches every row (`{}`): dropping that branch would narrow it.\n const everyRow = fieldName === \"or\" && children.length < condition.length;\n\n if (children.length > 0 && !everyRow) {\n expressions.push(sql.wrap(fieldName === \"and\" ? sql.and(children) : sql.or(children)));\n }\n\n continue;\n }\n\n if (\n fieldName === \"not\" &&\n typeof condition === \"object\" &&\n condition !== null &&\n !Array.isArray(condition)\n ) {\n const shouldWrapNot = Object.keys(condition).length > 1;\n const expr = this._build(table, group, condition as Record<string, unknown>, path);\n\n if (expr) {\n expressions.push(shouldWrapNot ? sql.wrap(sql.not(expr)) : sql.not(expr));\n }\n\n continue;\n }\n\n const field = group ? group.getColumn(fieldName) : table.getColumn(fieldName);\n const fieldPath = [...path, fieldName].join(\".\");\n\n if (field instanceof ColumnGroup) {\n expressions.push(...this._getGroupFilter(table, [...path, fieldName], field, condition));\n continue;\n }\n\n if (!(field instanceof Column)) {\n throw new Error(`Invalid field \"${fieldPath}\" in where clause for table \"${table.name}\".`);\n }\n\n expressions.push(...this._getColumnFilter(table, fieldPath, field, condition));\n }\n\n // `{}` selects everything, the same as no `where` at all — not an empty `WHERE`.\n return expressions.length > 0 ? sql.and(expressions) : undefined;\n }\n\n /**\n * One column's filter, as its runtime type allows ({@link RUNTIME_TYPE_RULES}): a bare value means\n * `{ eq: value }` where the type takes one, and every operator in an object adds a condition,\n * AND-ed with the rest. Anything the type does not allow throws before SQL is built.\n */\n private _getColumnFilter(\n table: AnyTable,\n fieldName: string,\n column: AnyColumn,\n condition: unknown\n ): SQLNode[] {\n const rules = rulesOf(column);\n const subject = `${column.runtimeType} column \"${fieldName}\" of \"${table.name}\"`;\n\n if (!this._isOperatorObject(condition)) {\n if (!rules.shorthand) {\n throw new Error(\n `Filter the ${subject} with one of its operators (${rules.operators.join(\", \")}), ` +\n `not a bare value.`\n );\n }\n\n // An object naming no operator is a value only where values can be plain objects; on any\n // other column it is a misspelt operator (`{ isNull: true }`), not a value to compare.\n if (isPlainObject(condition) && !PLAIN_OBJECT_VALUES.has(column.runtimeType)) {\n throw new Error(\n `Unknown operator ${Object.keys(condition)\n .map((key) => `\"${key}\"`)\n .join(\", \")} in the filter on the ${subject} (valid: ${rules.operators.join(\", \")}).`\n );\n }\n\n // Value shorthand: `{ id: \"123\" }` means `{ id: { eq: \"123\" } }`.\n return [this._getOperatorFilter(column, \"eq\", condition)];\n }\n\n const nodes: SQLNode[] = [];\n\n for (const [operator, value] of Object.entries(condition)) {\n if (value === undefined) {\n continue;\n }\n\n if (operator === NESTED_FILTER) {\n throw new Error(`A nested \\`where\\` on the ${subject} is not supported yet.`);\n }\n\n if (!rules.operators.includes(operator as FilterOperator)) {\n throw new Error(\n FILTER_OPERATORS.has(operator)\n ? `Operator \"${operator}\" is not valid on the ${subject} ` +\n `(valid: ${rules.operators.join(\", \")}).`\n : `Unknown operator \"${operator}\" in the filter on the ${subject}.`\n );\n }\n\n nodes.push(this._getOperatorFilter(column, operator as FilterOperator, value));\n }\n\n return nodes;\n }\n\n /**\n * A column group's filter: `exists` — whether the group is present, by the rule it is read\n * `null` by — and the nested `where` over its members. Members are only ever named inside\n * `where`, so a member called `exists` cannot be mistaken for the operator.\n */\n private _getGroupFilter(\n table: AnyTable,\n path: string[],\n group: AnyColumnGroup,\n condition: unknown\n ): SQLNode[] {\n const subject = `group \"${path.join(\".\")}\" of \"${table.name}\"`;\n\n if (\n typeof condition !== \"object\" ||\n condition === null ||\n Array.isArray(condition) ||\n ![Object.prototype, null].includes(Object.getPrototypeOf(condition) as object | null)\n ) {\n throw new Error(`Filter the ${subject} with \\`exists\\` or a nested \\`where\\`, not a value.`);\n }\n\n const nodes: SQLNode[] = [];\n\n for (const [operator, value] of Object.entries(condition)) {\n if (value === undefined) {\n continue;\n }\n\n if (operator === \"exists\") {\n nodes.push(group.exists(Boolean(value)));\n continue;\n }\n\n if (operator === NESTED_FILTER) {\n const nested = this._build(table, group, value as Record<string, unknown>, path);\n\n if (nested) {\n nodes.push(nested);\n }\n\n continue;\n }\n\n throw new Error(\n `Operator \"${operator}\" is not valid on the ${subject} (valid: exists, ${NESTED_FILTER}); ` +\n `filter its members inside \\`${NESTED_FILTER}\\`.`\n );\n }\n\n return nodes;\n }\n\n /**\n * Whether a column's filter is an object of operators rather than a value: a plain object\n * naming at least one. A value can itself be a plain object — an `interval` read as a\n * `Duration`, a JSON document — so one that names no operator is a value.\n */\n private _isOperatorObject(condition: unknown): condition is Record<string, unknown> {\n if (typeof condition !== \"object\" || condition === null) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(condition) as unknown;\n\n if (prototype !== Object.prototype && prototype !== null) {\n return false;\n }\n\n return Object.keys(condition).some((key) => FILTER_OPERATORS.has(key) || key === NESTED_FILTER);\n }\n\n private _getOperatorFilter(column: AnyColumn, operator: FilterOperator, value: unknown): SQLNode {\n // Comparison values go through `column.param` so the column's codec writes them the same\n // way it wrote them on insert. Pattern operators stay raw: they compare against a `LIKE`\n // pattern, not a column value. A `jsonb` fragment is encoded but, like every filter value,\n // not validated, so a partial document reaches the database as given.\n switch (operator) {\n case \"eq\":\n return (\n this._getPolymorphicFilter(column, value) ??\n sql.eq(column, column.param(value as SQLValue))\n );\n case \"neq\":\n return (\n this._getPolymorphicFilter(column, { neq: value }) ??\n sql.ne(column, column.param(value as SQLValue))\n );\n case \"in\":\n return (\n this._getPolymorphicFilter(column, { in: value }) ??\n sql.in(\n column,\n (value as SQLValue[]).map((item) => column.param(item))\n )\n );\n case \"gt\":\n return sql.gt(column, column.param(value as SQLValue));\n case \"gte\":\n return sql.gte(column, column.param(value as SQLValue));\n case \"lt\":\n return sql.lt(column, column.param(value as SQLValue));\n case \"lte\":\n return sql.lte(column, column.param(value as SQLValue));\n case \"between\": {\n const [from, to] = value as [SQLValue, SQLValue];\n return sql`${column} BETWEEN ${column.param(from)} AND ${column.param(to)}`;\n }\n case \"exists\":\n return value ? sql.isNotNull(column) : sql.isNull(column);\n case \"beginsWith\":\n return sql.like(column, `${escapeLike(value)}%`);\n case \"endsWith\":\n return sql.like(column, `%${escapeLike(value)}`);\n case \"contains\":\n if (!JSONB_RUNTIME_TYPES.has(column.runtimeType)) {\n return sql.like(column, `%${escapeLike(value)}%`);\n }\n\n // On an array column the fragment lists items; a lone item would be ambiguous when the\n // items are themselves arrays.\n if (column.runtimeType === \"array\" && !Array.isArray(value)) {\n throw new Error(\n `\\`contains\\` on the array column \"${column.name}\" of \"${column.table.name}\" ` +\n `takes an array of items.`\n );\n }\n\n return sql.jsonbContains(column, column.param(value as SQLValue));\n case \"hasKey\":\n // A key, not a value: sent as is, never through the codec.\n return sql.jsonbHasKey(column, value as string);\n }\n }\n\n /**\n * The `where` of an operation that requires one — `findOne`, `update`, `delete` — refusing a\n * filter that selects nothing in particular. `{}` means \"every row\" everywhere else; here it\n * would pick an arbitrary row to read, or every row to change.\n */\n public buildRequired<TTable extends AnyTable>(\n table: TTable,\n where: WhereExpressionOf<TTable> | null | undefined,\n operation: string\n ): SQLNode {\n const expression = this.build(table, where);\n\n if (!expression) {\n throw new Error(\n `${operation} on \"${table.name}\" needs a where that names the rows it applies to; ` +\n `an empty one would match every row.`\n );\n }\n\n return expression;\n }\n\n /**\n * Refuses a field the members of `union` do not all share, anywhere in a shared `where` —\n * inside `and` / `or` / `not` included. Checked on the union rather than per member, so the\n * error names the union instead of whichever member happened to lack the field.\n */\n public assertShared(union: Union, where: Record<string, unknown> | null | undefined) {\n for (const [fieldName, condition] of Object.entries(where ?? {})) {\n if ((fieldName === \"and\" || fieldName === \"or\") && Array.isArray(condition)) {\n for (const child of condition) {\n this.assertShared(union, child as Record<string, unknown>);\n }\n\n continue;\n }\n\n if (fieldName === \"not\" && typeof condition === \"object\" && condition !== null) {\n this.assertShared(union, condition as Record<string, unknown>);\n continue;\n }\n\n if (fieldName === KEY_FIELD) {\n this._getKeyCondition(union, condition);\n continue;\n }\n\n if (!union.isShared(fieldName)) {\n throw new Error(\n `Invalid field \"${fieldName}\" in where for union \"${union.alias}\": only fields every ` +\n `member shares filter across a union. Filter one member through \\`on\\`.`\n );\n }\n }\n }\n\n /**\n * A `$$key` condition as a test on a member alias. `$$key` accepts `eq`, `neq`, `in` and the\n * bare-value shorthand, each naming member aliases; anything else — another operator, a\n * value that is not a member — is refused, since it could only ever be a typo.\n */\n private _getKeyCondition(union: Union, condition: unknown): (alias: string) => boolean {\n const assertMembers = (values: unknown[]) => {\n for (const value of values) {\n if (typeof value !== \"string\" || !union.hasMember(value)) {\n throw new Error(\n `${KEY_FIELD} in where for union \"${union.alias}\" names ${JSON.stringify(value)}, ` +\n `which is not a member (members: ${union.memberAliases.join(\", \")}).`\n );\n }\n }\n };\n\n if (typeof condition === \"string\") {\n assertMembers([condition]);\n return (alias) => alias === condition;\n }\n\n const entries = Object.entries((condition ?? {}) as Record<string, unknown>).filter(\n ([, value]) => value !== undefined\n );\n\n const tests = entries.map(([operator, value]): ((alias: string) => boolean) => {\n if (operator === \"eq\" || operator === \"neq\") {\n assertMembers([value]);\n return operator === \"eq\" ? (alias) => alias === value : (alias) => alias !== value;\n }\n\n if (operator === \"in\" && Array.isArray(value)) {\n assertMembers(value);\n return (alias) => value.includes(alias);\n }\n\n throw new Error(\n `${KEY_FIELD} in where for union \"${union.alias}\" accepts eq, neq and in; got \"${operator}\".`\n );\n });\n\n return (alias) => tests.every((test) => test(alias));\n }\n\n /**\n * A shared `where` as seen from one member, with every `$$key` condition decided.\n *\n * Inside a branch the member alias is a constant, so a `$$key` condition is simply true or\n * false there. Folding it away here, rather than rendering `'photos' = 'videos'` into SQL,\n * lets a member that can never match be pruned before a branch is built at all:\n *\n * - `false` — no row of this member can match; the member produces no branch;\n * - otherwise the `where` that is left, with every decided condition removed. An `or` holding\n * a true child is dropped whole; a `not` flips its child.\n */\n public foldKey(\n union: Union,\n where: Record<string, unknown>,\n alias: string\n ): Record<string, unknown> | false {\n const residual: Record<string, unknown> = {};\n\n for (const [fieldName, condition] of Object.entries(where)) {\n if (fieldName === KEY_FIELD) {\n if (!this._getKeyCondition(union, condition)(alias)) {\n return false;\n }\n\n continue;\n }\n\n if ((fieldName === \"and\" || fieldName === \"or\") && Array.isArray(condition)) {\n // An empty group constrains nothing, exactly as outside a union.\n if (condition.length === 0) {\n continue;\n }\n\n const children = condition.map((child) =>\n this.foldKey(union, child as Record<string, unknown>, alias)\n );\n\n if (fieldName === \"and\") {\n if (children.some((child) => child === false)) {\n return false;\n }\n\n const kept = children.filter((child) => Object.keys(child as object).length > 0);\n\n if (kept.length > 0) {\n residual.and = kept;\n }\n\n continue;\n }\n\n // `or`: one child true for this member makes the whole group true.\n if (children.some((child) => child !== false && Object.keys(child).length === 0)) {\n continue;\n }\n\n const kept = children.filter((child) => child !== false);\n\n if (kept.length === 0) {\n return false;\n }\n\n residual.or = kept;\n continue;\n }\n\n if (fieldName === \"not\" && typeof condition === \"object\" && condition !== null) {\n const inner = this.foldKey(union, condition as Record<string, unknown>, alias);\n\n if (inner === false) {\n continue;\n }\n\n if (Object.keys(inner).length === 0 && Object.keys(condition).length > 0) {\n return false;\n }\n\n residual.not = inner;\n continue;\n }\n\n residual[fieldName] = condition;\n }\n\n return residual;\n }\n\n /**\n * A filter on a polymorphic id. A global id names a member as well as a key, and two members\n * may hold the same key, so matching it takes both: `(discriminator = key AND id = pk)`. `in`\n * becomes an `OR` of such groups, raw uuids among them compared on the id alone. `undefined`\n * for any other operator, or a filter with no global id in it — the ordinary path handles those.\n */\n private _getPolymorphicFilter(column: AnyColumn, condition: unknown): SQLNode | undefined {\n const binding = getDynamicGuidBinding(column);\n\n if (!binding) {\n return undefined;\n }\n\n const { discriminator, members } = binding;\n const match = (value: unknown) => {\n const member = decodeMemberId(value, members);\n\n return member\n ? sql.and([\n sql.eq(discriminator, discriminator.param(member.key)),\n sql.eq(column, column.param(member.value)),\n ])\n : undefined;\n };\n\n if (isFilterType(condition, \"in\")) {\n const values = condition.in as unknown[];\n\n if (!values.some(isGlobalId)) {\n return undefined;\n }\n\n const raw = values.filter((value) => !isGlobalId(value));\n const groups: SQLNode[] = values.flatMap((value) =>\n isGlobalId(value) ? [sql.wrap(match(value) as SQLNode)] : []\n );\n\n if (raw.length > 0) {\n groups.push(\n sql.in(\n column,\n raw.map((value) => column.param(value as SQLValue))\n )\n );\n }\n\n return sql.wrap(sql.or(groups));\n }\n\n if (isFilterType(condition, \"neq\")) {\n const group = match(condition.neq);\n return group ? sql.not(group) : undefined;\n }\n\n const value = isFilterType(condition, \"eq\") ? condition.eq : condition;\n const group = typeof value === \"string\" ? match(value) : undefined;\n\n return group ? sql.wrap(group) : undefined;\n }\n}\n"]}
|