fastify-auto-sqlapi 0.5.1 → 1.0.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/AGENTS.md +5 -5
- package/AGENTS_BACKEND.md +166 -130
- package/AGENTS_FRONTEND.md +60 -38
- package/BREAKING_CHANGES.md +9 -893
- package/CHANGELOG.md +246 -15
- package/README.md +71 -45
- package/dist/bin/generate-schema.js +12 -12
- package/dist/bin/generate-tables.js +1 -2
- package/dist/bin/utils.d.ts +2 -6
- package/dist/bin/utils.d.ts.map +1 -1
- package/dist/bin/utils.js +13 -33
- package/dist/index.d.ts +13 -33
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -37
- package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
- package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
- package/dist/lib/adapters/pg-adapter.d.ts +5 -2
- package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
- package/dist/lib/agent/manifest.d.ts +27 -10
- package/dist/lib/agent/manifest.d.ts.map +1 -1
- package/dist/lib/agent/manifest.js +43 -26
- package/dist/lib/agent/tool-schemas.d.ts +5 -4
- package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
- package/dist/lib/agent/tool-schemas.js +5 -5
- package/dist/lib/cli/config.d.ts +37 -2
- package/dist/lib/cli/config.d.ts.map +1 -1
- package/dist/lib/cli/config.js +106 -16
- package/dist/lib/cli/mysql-introspect.d.ts +6 -1
- package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
- package/dist/lib/cli/mysql-introspect.js +15 -15
- package/dist/lib/cli/pg-introspect.d.ts +0 -1
- package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
- package/dist/lib/cli/pg-introspect.js +2 -13
- package/dist/lib/cli/tables-codegen.d.ts +0 -4
- package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
- package/dist/lib/cli/tables-codegen.js +24 -87
- package/dist/lib/db.d.ts +42 -17
- package/dist/lib/db.d.ts.map +1 -1
- package/dist/lib/db.js +114 -40
- package/dist/lib/dialect.d.ts +5 -0
- package/dist/lib/dialect.d.ts.map +1 -1
- package/dist/lib/dialect.js +3 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-delete.js +66 -30
- package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
- package/dist/lib/engine/read-hooks.d.ts +3 -3
- package/dist/lib/engine/read-hooks.d.ts.map +1 -1
- package/dist/lib/engine/read-hooks.js +3 -3
- package/dist/lib/engine/rest/delete.d.ts.map +1 -1
- package/dist/lib/engine/rest/delete.js +12 -18
- package/dist/lib/engine/rest/get.js +8 -8
- package/dist/lib/engine/rest/insert.d.ts.map +1 -1
- package/dist/lib/engine/rest/insert.js +31 -18
- package/dist/lib/engine/rest/update.d.ts.map +1 -1
- package/dist/lib/engine/rest/update.js +34 -17
- package/dist/lib/engine/search/aggregations.d.ts +3 -3
- package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
- package/dist/lib/engine/search/aggregations.js +20 -16
- package/dist/lib/engine/search/conditions.d.ts +9 -5
- package/dist/lib/engine/search/conditions.d.ts.map +1 -1
- package/dist/lib/engine/search/conditions.js +31 -20
- package/dist/lib/engine/search/fields.d.ts +44 -11
- package/dist/lib/engine/search/fields.d.ts.map +1 -1
- package/dist/lib/engine/search/fields.js +93 -27
- package/dist/lib/engine/search/join-families.d.ts +7 -7
- package/dist/lib/engine/search/join-families.d.ts.map +1 -1
- package/dist/lib/engine/search/join-families.js +84 -75
- package/dist/lib/engine/search/joins.d.ts +15 -7
- package/dist/lib/engine/search/joins.d.ts.map +1 -1
- package/dist/lib/engine/search/joins.js +23 -13
- package/dist/lib/engine/search/order-by.d.ts +11 -12
- package/dist/lib/engine/search/order-by.d.ts.map +1 -1
- package/dist/lib/engine/search/order-by.js +24 -28
- package/dist/lib/engine/search/search.d.ts.map +1 -1
- package/dist/lib/engine/search/search.js +111 -64
- package/dist/lib/engine/validate.d.ts +21 -3
- package/dist/lib/engine/validate.d.ts.map +1 -1
- package/dist/lib/engine/validate.js +106 -16
- package/dist/lib/engine/write-helpers.d.ts +69 -16
- package/dist/lib/engine/write-helpers.d.ts.map +1 -1
- package/dist/lib/engine/write-helpers.js +257 -105
- package/dist/lib/errors.d.ts +42 -10
- package/dist/lib/errors.d.ts.map +1 -1
- package/dist/lib/errors.js +69 -15
- package/dist/lib/nullable.d.ts +3 -2
- package/dist/lib/nullable.d.ts.map +1 -1
- package/dist/lib/nullable.js +14 -5
- package/dist/lib/read-access.d.ts +25 -16
- package/dist/lib/read-access.d.ts.map +1 -1
- package/dist/lib/read-access.js +33 -17
- package/dist/lib/schema/bulk-delete.d.ts +13 -7
- package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
- package/dist/lib/schema/bulk-delete.js +18 -8
- package/dist/lib/schema/bulk-upsert.d.ts +3 -3
- package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/schema/bulk-upsert.js +9 -14
- package/dist/lib/schema/get.d.ts +1 -1
- package/dist/lib/schema/get.d.ts.map +1 -1
- package/dist/lib/schema/get.js +2 -2
- package/dist/lib/schema/helpers.d.ts +41 -23
- package/dist/lib/schema/helpers.d.ts.map +1 -1
- package/dist/lib/schema/helpers.js +80 -33
- package/dist/lib/schema/insert.d.ts +1 -1
- package/dist/lib/schema/insert.d.ts.map +1 -1
- package/dist/lib/schema/insert.js +12 -20
- package/dist/lib/schema/search.d.ts +2 -13
- package/dist/lib/schema/search.d.ts.map +1 -1
- package/dist/lib/schema/search.js +64 -61
- package/dist/lib/schema/update.d.ts +1 -1
- package/dist/lib/schema/update.d.ts.map +1 -1
- package/dist/lib/schema/update.js +6 -13
- package/dist/lib/sql-api.d.ts +47 -25
- package/dist/lib/sql-api.d.ts.map +1 -1
- package/dist/lib/sql-api.js +70 -27
- package/dist/lib/table-helpers.d.ts +92 -14
- package/dist/lib/table-helpers.d.ts.map +1 -1
- package/dist/lib/table-helpers.js +367 -128
- package/dist/lib/tenant.d.ts +16 -22
- package/dist/lib/tenant.d.ts.map +1 -1
- package/dist/lib/tenant.js +38 -54
- package/dist/lib/write-access.d.ts +15 -9
- package/dist/lib/write-access.d.ts.map +1 -1
- package/dist/lib/write-access.js +12 -4
- package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
- package/dist/routes/auto/agent-manifest.routes.js +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-delete.routes.js +1 -7
- package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-upsert.routes.js +2 -2
- package/dist/routes/auto/delete.routes.d.ts +2 -2
- package/dist/routes/auto/delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/delete.routes.js +8 -10
- package/dist/routes/auto/get.routes.d.ts +2 -2
- package/dist/routes/auto/get.routes.d.ts.map +1 -1
- package/dist/routes/auto/get.routes.js +5 -5
- package/dist/routes/auto/insert.routes.d.ts +2 -2
- package/dist/routes/auto/insert.routes.d.ts.map +1 -1
- package/dist/routes/auto/insert.routes.js +1 -7
- package/dist/routes/auto/plugin.d.ts +6 -0
- package/dist/routes/auto/plugin.d.ts.map +1 -1
- package/dist/routes/auto/plugin.js +60 -36
- package/dist/routes/auto/route-helpers.d.ts +26 -12
- package/dist/routes/auto/route-helpers.d.ts.map +1 -1
- package/dist/routes/auto/route-helpers.js +50 -19
- package/dist/routes/auto/search.routes.d.ts +2 -2
- package/dist/routes/auto/search.routes.d.ts.map +1 -1
- package/dist/routes/auto/search.routes.js +36 -24
- package/dist/routes/auto/update.routes.d.ts +2 -2
- package/dist/routes/auto/update.routes.d.ts.map +1 -1
- package/dist/routes/auto/update.routes.js +1 -8
- package/dist/routes/sql-api-decorator.d.ts +30 -12
- package/dist/routes/sql-api-decorator.d.ts.map +1 -1
- package/dist/routes/sql-api-decorator.js +44 -27
- package/dist/types/cli.d.ts +17 -6
- package/dist/types/cli.d.ts.map +1 -1
- package/dist/types/computed.d.ts +1 -1
- package/dist/types/computed.d.ts.map +1 -1
- package/dist/types/conditions.d.ts +3 -1
- package/dist/types/conditions.d.ts.map +1 -1
- package/dist/types/db.d.ts +44 -4
- package/dist/types/db.d.ts.map +1 -1
- package/dist/types/dml.d.ts +26 -17
- package/dist/types/dml.d.ts.map +1 -1
- package/dist/types/hooks.d.ts +62 -0
- package/dist/types/hooks.d.ts.map +1 -0
- package/dist/types/hooks.js +1 -0
- package/dist/types/join.d.ts +25 -8
- package/dist/types/join.d.ts.map +1 -1
- package/dist/types/plugin.d.ts +58 -19
- package/dist/types/plugin.d.ts.map +1 -1
- package/dist/types/plugin.js +2 -0
- package/dist/types/request.d.ts +2 -2
- package/dist/types/schema.d.ts +3 -3
- package/dist/types/schema.d.ts.map +1 -1
- package/dist/types/search.d.ts +28 -13
- package/dist/types/search.d.ts.map +1 -1
- package/dist/types/search.js +2 -1
- package/dist/types/table.d.ts +109 -94
- package/dist/types/table.d.ts.map +1 -1
- package/dist/types/table.js +7 -2
- package/dist/types/tenant.d.ts +28 -2
- package/dist/types/tenant.d.ts.map +1 -1
- package/dist/types/tenant.js +7 -1
- package/dist/types/validation.d.ts +69 -13
- package/dist/types/validation.d.ts.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -0
- package/docs/GLOSSARY.md +11 -5
- package/docs/adr/0003-bulk-not-transactional.md +2 -1
- package/docs/adr/0006-raw-db-errors.md +2 -1
- package/docs/adr/0013-sanitized-db-errors.md +2 -1
- package/docs/adr/0014-what-follows-a-write-join.md +1 -1
- package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
- package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
- package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
- package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
- package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
- package/docs/adr/0027-the-1-0-contract.md +74 -0
- package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
- package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
- package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
- package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
- package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
- package/docs/adr/README.md +12 -1
- package/docs/upgrading/0.x.md +906 -0
- package/docs/upgrading/1.0.md +628 -0
- package/package.json +4 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ConditionBuilder } from 'node-condition-builder';
|
|
2
|
-
import { Type } from '
|
|
2
|
+
import { Type } from 'typebox';
|
|
3
3
|
import { getDialect } from './dialect.js';
|
|
4
|
-
import { hasOwnField } from './read-access.js';
|
|
4
|
+
import { hasOwnField, extraFilterFields } from './read-access.js';
|
|
5
5
|
// Quote an identifier using the given ConditionBuilder dialect (or the global
|
|
6
6
|
// default when not provided). Needed so that DB columns with uppercase letters
|
|
7
7
|
// (e.g. betterauth "userId") are preserved on PostgreSQL (which folds unquoted
|
|
@@ -10,94 +10,192 @@ import { hasOwnField } from './read-access.js';
|
|
|
10
10
|
function qi(field, dialect) {
|
|
11
11
|
return getDialect(dialect ?? ConditionBuilder.DIALECT).qi(field);
|
|
12
12
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
13
|
+
/**
|
|
14
|
+
* The WHERE ConditionBuilder for a table's `filters`: equality on every schema field the
|
|
15
|
+
* values carry (an explicit `null` is `IS NULL`), then the table's `extendedCondition`, which
|
|
16
|
+
* alone gives `extraFilters` a meaning.
|
|
17
|
+
*
|
|
18
|
+
* `dialect` selects identifier quoting (the engines pass the one of the QueryClient running
|
|
19
|
+
* the query). `qualifier` is the raw table name or alias the columns are prefixed with; it
|
|
20
|
+
* defaults to the table's own name, and the engines pass an alias when the condition lands
|
|
21
|
+
* inside a correlated subquery whose FROM is aliased — there the bare table name would
|
|
22
|
+
* resolve against the OUTER query.
|
|
23
|
+
*/
|
|
24
|
+
export function buildTableFilters(tableConf, filterValues, dialect, qualifier) {
|
|
25
|
+
const { schema, extendedCondition } = tableConf;
|
|
26
|
+
const condition = new ConditionBuilder('AND', dialect);
|
|
27
|
+
// Only auto-match real schema fields (DB columns). Columns are table-qualified: the
|
|
28
|
+
// statement may carry joins (LEFT JOIN parents, tenant through-joins), and a bare column
|
|
29
|
+
// shared with a joined table would be ambiguous.
|
|
30
|
+
const table = qi(qualifier ?? schema.tableName, dialect);
|
|
31
|
+
const columnOf = (field) => `${table}.${qi(schema.col(field), dialect)}`;
|
|
32
|
+
for (const field of Object.keys(schema.fields)) {
|
|
33
|
+
if (!(field in filterValues) || filterValues[field] === undefined)
|
|
34
|
+
continue;
|
|
35
|
+
const col = columnOf(field);
|
|
36
|
+
// An explicit null filters by IS NULL: equality with NULL never matches, and silently
|
|
37
|
+
// dropping the filter would return unfiltered results for a request that asked for
|
|
38
|
+
// "field is null".
|
|
39
|
+
if (filterValues[field] === null) {
|
|
40
|
+
// Second arg is CB's enable-guard: without `true` the call is a no-op.
|
|
41
|
+
condition.isNull(col, true);
|
|
35
42
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
extendedCondition(condition, filterValues);
|
|
43
|
+
else {
|
|
44
|
+
condition.isEqual(col, filterValues[field]);
|
|
39
45
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
46
|
+
}
|
|
47
|
+
// `col` is the qualifier this statement needs, which the consumer cannot know: the same
|
|
48
|
+
// condition runs in the main search and inside aliased join subqueries.
|
|
49
|
+
if (extendedCondition) {
|
|
50
|
+
extendedCondition(condition, filterValues, {
|
|
51
|
+
col: (field) => {
|
|
52
|
+
if (!hasOwnField(schema.fields, field)) {
|
|
53
|
+
throw new Error(`extendedCondition of table '${schema.tableName}': col('${field}') names no field of ` +
|
|
54
|
+
`its schema. Fields: ${Object.keys(schema.fields).join(', ')}`);
|
|
55
|
+
}
|
|
56
|
+
return columnOf(field);
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return condition;
|
|
47
61
|
}
|
|
48
|
-
export function defineTable(
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
62
|
+
export function defineTable(definition) {
|
|
63
|
+
const config = definition;
|
|
64
|
+
assertTableShape(config, 'defineTable');
|
|
65
|
+
validateAliasUniqueness(config.readJoins, 'readJoins');
|
|
66
|
+
validateAliasUniqueness(config.writeJoins, 'writeJoins');
|
|
67
|
+
validateWriteJoinsUnrestricted(config.writeJoins);
|
|
52
68
|
validateComputedFields(config);
|
|
53
69
|
validatePrimary(config);
|
|
54
70
|
validateReadExclude(config);
|
|
55
71
|
validateWriteExclude(config);
|
|
72
|
+
rejectExcludeFromCreation(config);
|
|
56
73
|
validateTenantScope(config);
|
|
57
|
-
|
|
58
|
-
|
|
74
|
+
validateUpsertKeys(config);
|
|
75
|
+
refuseUpsertKeyOnReadJoins(config);
|
|
76
|
+
validateDefaultOrder(config);
|
|
59
77
|
return config;
|
|
60
78
|
}
|
|
79
|
+
/** One term of an order string in its 1-part form: `field [ASC|DESC]`. */
|
|
80
|
+
export const PLAIN_ORDER_TERM = /^(\w+)(?:\s+(ASC|DESC))?$/i;
|
|
81
|
+
/**
|
|
82
|
+
* Why one term of a `defaultOrder` is not valid on `tableConf`, or null when it is a schema
|
|
83
|
+
* field or a computed field with an optional direction — the grammar of a 1-part request
|
|
84
|
+
* `orderBy`. The dotted notations stay request-only: the default applies to requests that carry
|
|
85
|
+
* no join. Nothing else is accepted, since nothing reaches the SQL as written: an expression is
|
|
86
|
+
* declared as a computed field and ordered by its name.
|
|
87
|
+
*/
|
|
88
|
+
export function defaultOrderTermProblem(term, tableConf) {
|
|
89
|
+
if (!term)
|
|
90
|
+
return 'the term is empty';
|
|
91
|
+
if (/^\w+(\.\w+)+(\s+\w+)?$/.test(term)) {
|
|
92
|
+
return 'a dotted notation is for a request orderBy only: the default applies to requests without joins';
|
|
93
|
+
}
|
|
94
|
+
const plain = PLAIN_ORDER_TERM.exec(term);
|
|
95
|
+
if (!plain) {
|
|
96
|
+
return "the grammar is 'field [ASC|DESC]': declare an expression in computedFields and order by its name";
|
|
97
|
+
}
|
|
98
|
+
const name = plain[1];
|
|
99
|
+
const { schema } = tableConf;
|
|
100
|
+
if (hasOwnField(schema.fields, name) || hasOwnField(tableConf.computedFields, name))
|
|
101
|
+
return null;
|
|
102
|
+
const owner = Object.keys(schema.fields).find((f) => schema.col(f) === name);
|
|
103
|
+
if (owner)
|
|
104
|
+
return `'${name}' is the DB column of field '${owner}': defaultOrder names fields, write '${owner}'`;
|
|
105
|
+
return `'${name}' is not a field or computed field of the table`;
|
|
106
|
+
}
|
|
107
|
+
/** The error for a `defaultOrder` term `defaultOrderTermProblem` refused; `where` names the caller. */
|
|
108
|
+
export function defaultOrderError(where, term, tableConf, problem) {
|
|
109
|
+
return new Error(`${where}: defaultOrder term '${term}' on table '${tableConf.schema.tableName}': ${problem}`);
|
|
110
|
+
}
|
|
111
|
+
function validateDefaultOrder(config) {
|
|
112
|
+
const order = config.defaultOrder;
|
|
113
|
+
if (order === undefined)
|
|
114
|
+
return;
|
|
115
|
+
if (typeof order !== 'string' || !order.trim()) {
|
|
116
|
+
throw new TypeError(`defineTable: defaultOrder on table '${config.schema.tableName}' is a non-empty string, ` +
|
|
117
|
+
`e.g. 'createdAt DESC, id'`);
|
|
118
|
+
}
|
|
119
|
+
for (const part of order.split(',')) {
|
|
120
|
+
const term = part.trim();
|
|
121
|
+
const problem = defaultOrderTermProblem(term, config);
|
|
122
|
+
if (problem)
|
|
123
|
+
throw defaultOrderError('defineTable', term, config, problem);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The keys of the pre-1.0 config shape, each with what replaced it. Refused rather than
|
|
128
|
+
* ignored: a config still carrying them would run without its schema, with its
|
|
129
|
+
* `extendedCondition` dropped, or with its upserts degraded to plain inserts, in silence.
|
|
130
|
+
*/
|
|
131
|
+
const RETIRED_CONFIG_KEYS = {
|
|
132
|
+
Schema: "'schema'",
|
|
133
|
+
filters: "'extendedCondition' (column filters are built from 'schema')",
|
|
134
|
+
upsertMap: "'upsertKey' on the table for its main rows, and buildRelation(…, { upsertKey }) for the secondaries of a write join",
|
|
135
|
+
allowedReadJoins: "'readJoins'",
|
|
136
|
+
allowedWriteJoins: "'writeJoins'",
|
|
137
|
+
};
|
|
138
|
+
/** Throw when a table config is in the pre-1.0 shape or has no schema. `where` names the caller. */
|
|
139
|
+
function assertTableShape(config, where) {
|
|
140
|
+
if (!config || typeof config !== 'object') {
|
|
141
|
+
throw new TypeError(`${where}: a table config must be an object`);
|
|
142
|
+
}
|
|
143
|
+
for (const [key, instead] of Object.entries(RETIRED_CONFIG_KEYS)) {
|
|
144
|
+
if (Object.hasOwn(config, key)) {
|
|
145
|
+
throw new TypeError(`${where}: '${key}' is the pre-1.0 config shape, use ${instead}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const schema = config.schema;
|
|
149
|
+
if (!schema || typeof schema !== 'object' || !schema.fields || typeof schema.tableName !== 'string') {
|
|
150
|
+
throw new TypeError(`${where}: 'schema' is required — the table's generated Schema`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* The column a `tenantScope` name stands for: a field of `schema` resolves through its `col()`,
|
|
155
|
+
* any other name is already a column (a 0.x scope names real columns). `defineTable` has refused
|
|
156
|
+
* a name that is neither (`checkScopeName`, ADR 0032); a config built without it, or with no
|
|
157
|
+
* schema to look in, gets every other name as written.
|
|
158
|
+
*/
|
|
159
|
+
function scopeColumn(schema, name) {
|
|
160
|
+
return schema && hasOwnField(schema.fields, name) ? schema.col(name) : name;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* A table's `tenantScope` with every name resolved to its column, the form the SQL needs. Each
|
|
164
|
+
* name goes through the schema of the table it lives on: `column`, `anyOf` and
|
|
165
|
+
* `through.localField` through the table's own; the `column` and `through.foreignField` of an
|
|
166
|
+
* indirect scope through `through.schema`, the parent's.
|
|
167
|
+
*/
|
|
168
|
+
export function resolvedTenantScope(tableConf) {
|
|
169
|
+
const scope = tableConf?.tenantScope;
|
|
170
|
+
if (!scope)
|
|
171
|
+
return undefined;
|
|
172
|
+
const own = tableConf.schema;
|
|
173
|
+
if ('anyOf' in scope)
|
|
174
|
+
return { anyOf: scope.anyOf.map((name) => scopeColumn(own, name)) };
|
|
175
|
+
if (!('through' in scope))
|
|
176
|
+
return { column: scopeColumn(own, scope.column) };
|
|
177
|
+
const { through } = scope;
|
|
178
|
+
return {
|
|
179
|
+
column: scopeColumn(through.schema, scope.column),
|
|
180
|
+
through: {
|
|
181
|
+
schema: through.schema,
|
|
182
|
+
localField: scopeColumn(own, through.localField),
|
|
183
|
+
foreignField: scopeColumn(through.schema, through.foreignField),
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
61
187
|
/**
|
|
62
188
|
* `tenantScope` has three forms and they do not mix: `{ column }`, `{ column, through }`, and
|
|
63
189
|
* `{ anyOf }`. A config naming more than one form is ambiguous rather than additive — an `anyOf`
|
|
64
190
|
* entry reached through a parent FK would need its own join per entry — and an empty `anyOf`
|
|
65
191
|
* would fail closed on every row, which looks like a broken deployment rather than a rule.
|
|
66
|
-
*
|
|
67
|
-
* The columns it names are **real DB column names**, not camelCase schema fields — the one place
|
|
68
|
-
* in `defineTable` where the convention flips. That is not an oversight: a scope is applied to
|
|
69
|
-
* the SQL, after the payload has already been converted, and `through.foreignField` belongs to a
|
|
70
|
-
* parent table that may have no config, no `colMap`, or no generated schema at all. It is the
|
|
71
|
-
* same category as `db.*` and `extendedCondition`: names that go straight to the database.
|
|
72
|
-
*
|
|
73
|
-
* So existence cannot be checked — a hand-written schema may legitimately omit the column. What
|
|
74
|
-
* *is* checked is the mistake that exception invites: naming the schema **field** whose real
|
|
75
|
-
* column is something else. Left alone that surfaces as `column "organizationId" does not exist`
|
|
76
|
-
* on every request to the table — an opaque 500 (ADR 0006), failing closed but saying nothing.
|
|
192
|
+
* Its names are schema fields, like every other key of a table config (ADR 0032).
|
|
77
193
|
*/
|
|
78
|
-
/**
|
|
79
|
-
* Reject a tenant column that is really a schema field name mapping to a different column.
|
|
80
|
-
*
|
|
81
|
-
* The check is deliberately narrow, and it self-adjusts: on a camelCase database `col()` is the
|
|
82
|
-
* identity, so a camelCase name raises nothing. A name the schema does not carry raises nothing
|
|
83
|
-
* either — that is the hand-written-schema case, and there is nothing to compare it against.
|
|
84
|
-
*/
|
|
85
|
-
function assertNamesColumn(schema, name, where, table) {
|
|
86
|
-
if (!hasOwnField(schema.fields, name))
|
|
87
|
-
return;
|
|
88
|
-
const column = schema.col(name);
|
|
89
|
-
if (column === name)
|
|
90
|
-
return;
|
|
91
|
-
throw new Error(`defineTable: tenantScope ${where} on table '${table}' names '${name}', which is a ` +
|
|
92
|
-
`schema field, not a column: its column is '${column}'. tenantScope names real DB ` +
|
|
93
|
-
`columns — the scope is applied to the SQL, after the payload has been converted — so ` +
|
|
94
|
-
`write '${column}' here. Clients keep sending '${name}'.`);
|
|
95
|
-
}
|
|
96
194
|
function validateTenantScope(config) {
|
|
97
195
|
const scope = config.tenantScope;
|
|
98
196
|
if (!scope)
|
|
99
197
|
return;
|
|
100
|
-
const table = config.
|
|
198
|
+
const table = config.schema.tableName;
|
|
101
199
|
const hasAnyOf = 'anyOf' in scope;
|
|
102
200
|
const hasColumn = 'column' in scope;
|
|
103
201
|
if (hasAnyOf && hasColumn) {
|
|
@@ -114,65 +212,67 @@ function validateTenantScope(config) {
|
|
|
114
212
|
const { anyOf } = scope;
|
|
115
213
|
if (!Array.isArray(anyOf) || !anyOf.length) {
|
|
116
214
|
throw new Error(`defineTable: tenantScope 'anyOf' on table '${table}' must be a non-empty array of ` +
|
|
117
|
-
`
|
|
215
|
+
`field names. An empty list would hide every row of the table.`);
|
|
118
216
|
}
|
|
119
217
|
if (anyOf.some((c) => typeof c !== 'string' || !c)) {
|
|
120
|
-
throw new Error(`defineTable: tenantScope 'anyOf' on table '${table}' must contain
|
|
218
|
+
throw new Error(`defineTable: tenantScope 'anyOf' on table '${table}' must contain field names as ` +
|
|
121
219
|
`non-empty strings.`);
|
|
122
220
|
}
|
|
123
|
-
if (new Set(anyOf).size !== anyOf.length) {
|
|
221
|
+
if (new Set(anyOf.map((name) => scopeColumn(config.schema, name))).size !== anyOf.length) {
|
|
124
222
|
throw new Error(`defineTable: tenantScope 'anyOf' on table '${table}' repeats a column. ` +
|
|
125
|
-
`Each owner column must appear once.`);
|
|
223
|
+
`Each owner column must appear once, by its field or by its column name.`);
|
|
126
224
|
}
|
|
225
|
+
checkScopeNames(config);
|
|
127
226
|
return;
|
|
128
227
|
}
|
|
129
228
|
if (!hasColumn || typeof scope.column !== 'string') {
|
|
130
229
|
throw new Error(`defineTable: tenantScope on table '${table}' declares neither 'column' nor 'anyOf'. ` +
|
|
131
230
|
`A scope with no owner column would filter nothing.`);
|
|
132
231
|
}
|
|
232
|
+
checkScopeNames(config);
|
|
133
233
|
}
|
|
134
234
|
/**
|
|
135
|
-
*
|
|
136
|
-
*
|
|
235
|
+
* Refuse a `tenantScope` name its schema does not know: each must be a field of the schema it
|
|
236
|
+
* belongs to, or the column of one. Taken as a column, a misspelled name would pass startup
|
|
237
|
+
* and fail as a 500 on the first request (ADR 0032).
|
|
137
238
|
*/
|
|
138
|
-
function
|
|
239
|
+
function checkScopeNames(config) {
|
|
139
240
|
const scope = config.tenantScope;
|
|
140
241
|
if (!scope)
|
|
141
242
|
return;
|
|
142
|
-
const
|
|
243
|
+
const own = config.schema;
|
|
143
244
|
if ('anyOf' in scope) {
|
|
144
|
-
for (const
|
|
145
|
-
|
|
146
|
-
}
|
|
245
|
+
for (const name of scope.anyOf)
|
|
246
|
+
checkScopeName(own, 'anyOf', name);
|
|
147
247
|
return;
|
|
148
248
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
// `through.localField` is a column of THIS table; `through.foreignField` one of the parent's,
|
|
152
|
-
// which is why the parent schema travels in the scope.
|
|
153
|
-
const through = direct.through;
|
|
154
|
-
if (!through || typeof through !== 'object')
|
|
249
|
+
if (!('through' in scope)) {
|
|
250
|
+
checkScopeName(own, 'column', scope.column);
|
|
155
251
|
return;
|
|
156
|
-
if (typeof through.localField === 'string') {
|
|
157
|
-
assertNamesColumn(config.Schema, through.localField, "'through.localField'", table);
|
|
158
|
-
}
|
|
159
|
-
if (typeof through.foreignField === 'string' && typeof through.schema?.col === 'function') {
|
|
160
|
-
assertNamesColumn(through.schema, through.foreignField, "'through.foreignField'", table);
|
|
161
252
|
}
|
|
253
|
+
const { through } = scope;
|
|
254
|
+
checkScopeName(own, 'through.localField', through.localField);
|
|
255
|
+
checkScopeName(through.schema, 'column', scope.column, own.tableName);
|
|
256
|
+
checkScopeName(through.schema, 'through.foreignField', through.foreignField, own.tableName);
|
|
257
|
+
}
|
|
258
|
+
function checkScopeName(schema, key, name, scopedTable) {
|
|
259
|
+
const fields = Object.keys(schema.fields);
|
|
260
|
+
if (hasOwnField(schema.fields, name) || fields.some((f) => schema.col(f) === name))
|
|
261
|
+
return;
|
|
262
|
+
const whose = scopedTable ? ` (the parent of '${scopedTable}', through.schema)` : '';
|
|
263
|
+
throw new Error(`defineTable: tenantScope '${key}' on table '${schema.tableName}'${whose} names '${name}', ` +
|
|
264
|
+
`neither a field of its schema nor the column of one. Fields: ${fields.join(', ')}`);
|
|
162
265
|
}
|
|
163
266
|
/**
|
|
164
267
|
* `fields` narrows a relation for reading; it has no meaning on a write join and would be
|
|
165
|
-
* actively harmful there
|
|
166
|
-
* schema object up in `upsertMap` **by identity**, and a narrowed relation carries a copy —
|
|
167
|
-
* the lookup would miss and the upsert would silently degrade to a plain insert. The
|
|
168
|
-
* narrowed schema would also drop columns the caller legitimately sends.
|
|
268
|
+
* actively harmful there: the narrowed schema would drop columns the caller legitimately sends.
|
|
169
269
|
*/
|
|
170
270
|
function validateWriteJoinsUnrestricted(joins) {
|
|
171
271
|
for (const join of joins ?? []) {
|
|
172
272
|
if (join.fields) {
|
|
173
|
-
throw new Error(`defineTable: relation '${join.alias}' in
|
|
273
|
+
throw new Error(`defineTable: relation '${join.alias}' in writeJoins declares 'fields'. ` +
|
|
174
274
|
`The fields allowlist restricts reading only — remove it, and use a separate ` +
|
|
175
|
-
`buildRelation for the read side if that relation is also in
|
|
275
|
+
`buildRelation for the read side if that relation is also in readJoins.`);
|
|
176
276
|
}
|
|
177
277
|
}
|
|
178
278
|
}
|
|
@@ -180,16 +280,16 @@ function validateReadExclude(config) {
|
|
|
180
280
|
const excluded = config.readExclude;
|
|
181
281
|
if (!excluded?.length)
|
|
182
282
|
return;
|
|
183
|
-
const schemaFields = Object.keys(config.
|
|
283
|
+
const schemaFields = Object.keys(config.schema.fields);
|
|
184
284
|
const pkFields = Array.isArray(config.primary) ? config.primary : [config.primary];
|
|
185
285
|
for (const field of excluded) {
|
|
186
286
|
if (!schemaFields.includes(field)) {
|
|
187
287
|
throw new Error(`defineTable: readExclude field '${field}' is not a schema field on ` +
|
|
188
|
-
`table '${config.
|
|
288
|
+
`table '${config.schema.tableName}'.`);
|
|
189
289
|
}
|
|
190
290
|
if (pkFields.includes(field)) {
|
|
191
291
|
throw new Error(`defineTable: readExclude cannot hide the primary key field '${field}' on ` +
|
|
192
|
-
`table '${config.
|
|
292
|
+
`table '${config.schema.tableName}' — reads and joins rely on it.`);
|
|
193
293
|
}
|
|
194
294
|
}
|
|
195
295
|
}
|
|
@@ -206,9 +306,9 @@ function validateReadExclude(config) {
|
|
|
206
306
|
* a working config — not a broken one waiting to be fixed.
|
|
207
307
|
*/
|
|
208
308
|
function validatePrimary(config) {
|
|
209
|
-
const schemaFields = Object.keys(config.
|
|
309
|
+
const schemaFields = Object.keys(config.schema.fields);
|
|
210
310
|
const pkFields = Array.isArray(config.primary) ? config.primary : [config.primary];
|
|
211
|
-
const table = config.
|
|
311
|
+
const table = config.schema.tableName;
|
|
212
312
|
const missing = pkFields.filter((f) => !schemaFields.includes(f));
|
|
213
313
|
if (missing.length === 0)
|
|
214
314
|
return;
|
|
@@ -228,6 +328,17 @@ function validatePrimary(config) {
|
|
|
228
328
|
`Name a column that is unique in this relation, or restrict the table to ` +
|
|
229
329
|
`operations: ['search'] with an explicit defaultOrder.`);
|
|
230
330
|
}
|
|
331
|
+
/**
|
|
332
|
+
* `excludeFromCreation` is what `insertExclude` was called before 1.0. The type no longer
|
|
333
|
+
* has it, but a JavaScript consumer, or a cast, can still pass it: ignoring it would let
|
|
334
|
+
* clients write the fields it was meant to protect, so it is refused with the new name.
|
|
335
|
+
*/
|
|
336
|
+
function rejectExcludeFromCreation(config) {
|
|
337
|
+
if (!('excludeFromCreation' in config))
|
|
338
|
+
return;
|
|
339
|
+
throw new Error(`defineTable: table '${config.schema.tableName}' sets excludeFromCreation, which was ` +
|
|
340
|
+
`renamed to insertExclude in 1.0.0 with the same behaviour. Rename the key.`);
|
|
341
|
+
}
|
|
231
342
|
/**
|
|
232
343
|
* `writeExclude` names schema fields that no write may carry. A field outside the schema is a
|
|
233
344
|
* typo; the primary key is refused because the update body identifies the row with it; and a
|
|
@@ -238,9 +349,9 @@ function validateWriteExclude(config) {
|
|
|
238
349
|
const excluded = config.writeExclude;
|
|
239
350
|
if (!excluded?.length)
|
|
240
351
|
return;
|
|
241
|
-
const schemaFields = Object.keys(config.
|
|
352
|
+
const schemaFields = Object.keys(config.schema.fields);
|
|
242
353
|
const pkFields = Array.isArray(config.primary) ? config.primary : [config.primary];
|
|
243
|
-
const table = config.
|
|
354
|
+
const table = config.schema.tableName;
|
|
244
355
|
for (const field of excluded) {
|
|
245
356
|
if (!schemaFields.includes(field)) {
|
|
246
357
|
throw new Error(`defineTable: writeExclude field '${field}' is not a schema field on table '${table}'.`);
|
|
@@ -259,22 +370,49 @@ function validateWriteExclude(config) {
|
|
|
259
370
|
const formatKey = (fields) => `(${fields.join(', ')})`;
|
|
260
371
|
const sameFieldSet = (a, b) => a.length === b.length && a.every((f) => b.includes(f));
|
|
261
372
|
/**
|
|
262
|
-
* An `
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
373
|
+
* An `upsertKey` must name a unique key the database enforces — the Schema's `primaryKey` or
|
|
374
|
+
* one of its `uniqueKeys`, as a set: same fields, any order, nothing extra (ADR 0021).
|
|
375
|
+
* Anything else fails every write on PostgreSQL, and on MySQL duplicates rows or updates a row
|
|
376
|
+
* matched through another key, in silence.
|
|
377
|
+
*
|
|
378
|
+
* Fail-closed: a key the Schema cannot vouch for is refused. The Schema is what is read, not a
|
|
379
|
+
* table config, so a child written only through a write join needs no `defineTable`.
|
|
266
380
|
*
|
|
267
|
-
*
|
|
268
|
-
* a table config, so a child written only through a write join needs no `defineTable`.
|
|
381
|
+
* A read relation carrying one is refused too, see `refuseUpsertKeyOnReadJoins`.
|
|
269
382
|
*/
|
|
270
|
-
function
|
|
271
|
-
|
|
272
|
-
|
|
383
|
+
function validateUpsertKeys(config) {
|
|
384
|
+
const table = config.schema.tableName;
|
|
385
|
+
if (config.upsertKey !== undefined) {
|
|
386
|
+
if (!Array.isArray(config.upsertKey) || !config.upsertKey.length) {
|
|
387
|
+
throw new TypeError(`defineTable: 'upsertKey' on table '${table}' is a non-empty array of field names`);
|
|
388
|
+
}
|
|
389
|
+
const problem = upsertKeyProblem(config.schema, config.upsertKey);
|
|
390
|
+
if (problem) {
|
|
391
|
+
throw new Error(`defineTable: upsertKey of table '${table}' ${formatKey(config.upsertKey)} ${problem} (ADR 0021).`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
for (const join of config.writeJoins ?? []) {
|
|
395
|
+
if (!join.upsertKey)
|
|
396
|
+
continue;
|
|
397
|
+
const problem = upsertKeyProblem(join.joinSchema, join.upsertKey);
|
|
273
398
|
if (problem) {
|
|
274
|
-
throw new Error(`defineTable:
|
|
399
|
+
throw new Error(`defineTable: upsertKey of relation '${join.alias}' on '${join.joinSchema.tableName}' ` +
|
|
400
|
+
`${formatKey(join.upsertKey)} ${problem} (ADR 0021).`);
|
|
275
401
|
}
|
|
276
402
|
}
|
|
277
403
|
}
|
|
404
|
+
/**
|
|
405
|
+
* A read relation declaring `upsertKey` is refused: reads never write, and a key that does
|
|
406
|
+
* nothing where it is declared hides that the write relation lacks it.
|
|
407
|
+
*/
|
|
408
|
+
function refuseUpsertKeyOnReadJoins(config) {
|
|
409
|
+
for (const join of config.readJoins ?? []) {
|
|
410
|
+
if (!join.upsertKey)
|
|
411
|
+
continue;
|
|
412
|
+
throw new Error(`defineTable: relation '${join.alias}' in readJoins declares 'upsertKey'. Reads ` +
|
|
413
|
+
`never write — declare it on the relation in writeJoins, with a separate buildRelation.`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
278
416
|
/** Why `keys` is not a verified unique key of `schema`, or null when it is one. */
|
|
279
417
|
function upsertKeyProblem(schema, keys) {
|
|
280
418
|
if (schema.isView)
|
|
@@ -300,16 +438,16 @@ function validateComputedFields(config) {
|
|
|
300
438
|
const computed = config.computedFields;
|
|
301
439
|
if (!computed)
|
|
302
440
|
return;
|
|
303
|
-
const schemaFields = Object.keys(config.
|
|
304
|
-
const extraKeys = Object.keys(config
|
|
441
|
+
const schemaFields = Object.keys(config.schema.fields);
|
|
442
|
+
const extraKeys = Object.keys(extraFilterFields(config));
|
|
305
443
|
for (const name of Object.keys(computed)) {
|
|
306
444
|
if (schemaFields.includes(name)) {
|
|
307
445
|
throw new Error(`defineTable: computedFields name '${name}' collides with a schema field on ` +
|
|
308
|
-
`table '${config.
|
|
446
|
+
`table '${config.schema.tableName}'. Choose a different name.`);
|
|
309
447
|
}
|
|
310
448
|
if (extraKeys.includes(name)) {
|
|
311
449
|
throw new Error(`defineTable: computedFields name '${name}' collides with an extraFilters key on ` +
|
|
312
|
-
`table '${config.
|
|
450
|
+
`table '${config.schema.tableName}'. Choose a different name.`);
|
|
313
451
|
}
|
|
314
452
|
}
|
|
315
453
|
}
|
|
@@ -330,9 +468,9 @@ function validateAliasUniqueness(joins, label) {
|
|
|
330
468
|
* Copy of `schema` exposing only `fields`, in schema declaration order.
|
|
331
469
|
*
|
|
332
470
|
* `tableName`, `col` and `colMap` are carried over untouched: the engine resolves the
|
|
333
|
-
* target's configuration through `
|
|
334
|
-
* must still answer to
|
|
335
|
-
* fields that survive.
|
|
471
|
+
* target's configuration through `resolveJoinTableConf`, which matches on the real table
|
|
472
|
+
* name, so a narrowed relation must still answer to it, and column mapping must keep working
|
|
473
|
+
* for the fields that survive.
|
|
336
474
|
*/
|
|
337
475
|
function narrowSchemaToFields(schema, fields, joinField) {
|
|
338
476
|
const declared = Object.keys(schema.fields);
|
|
@@ -360,21 +498,122 @@ function narrowSchemaToFields(schema, fields, joinField) {
|
|
|
360
498
|
partialValidation: Type.Partial(Type.Object(picked)),
|
|
361
499
|
};
|
|
362
500
|
}
|
|
501
|
+
/**
|
|
502
|
+
* The relation's default `select`, checked against the joined schema at startup: a typo here
|
|
503
|
+
* would otherwise surface as a 400 on the first request that uses the relation. The pre-1.0
|
|
504
|
+
* `selection` option is rejected rather than ignored.
|
|
505
|
+
*/
|
|
506
|
+
function relationSelect(options, joinSchema) {
|
|
507
|
+
if (options && Object.hasOwn(options, 'selection')) {
|
|
508
|
+
throw new TypeError(`buildRelation: 'selection' was removed in 1.0, use 'select' (an array of field names)`);
|
|
509
|
+
}
|
|
510
|
+
const select = options?.select;
|
|
511
|
+
if (select === undefined)
|
|
512
|
+
return undefined;
|
|
513
|
+
if (!Array.isArray(select)) {
|
|
514
|
+
throw new TypeError(`buildRelation: 'select' is an array of field names on '${joinSchema.tableName}'`);
|
|
515
|
+
}
|
|
516
|
+
for (const field of select) {
|
|
517
|
+
if (!Object.hasOwn(joinSchema.fields, field)) {
|
|
518
|
+
throw new Error(`buildRelation: 'select' entry '${field}' is not a field of schema '${joinSchema.tableName}'. ` +
|
|
519
|
+
`Available: ${Object.keys(joinSchema.fields).join(', ')}.`);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return [...select];
|
|
523
|
+
}
|
|
524
|
+
/** The relation's `upsertKey`, each entry a field of the joined schema; uniqueness is `defineTable`'s check. */
|
|
525
|
+
function relationUpsertKey(options, joinSchema) {
|
|
526
|
+
const key = options?.upsertKey;
|
|
527
|
+
if (key === undefined)
|
|
528
|
+
return undefined;
|
|
529
|
+
if (!Array.isArray(key) || !key.length || key.some((f) => typeof f !== 'string')) {
|
|
530
|
+
throw new TypeError(`buildRelation: 'upsertKey' is a non-empty array of field names on '${joinSchema.tableName}'`);
|
|
531
|
+
}
|
|
532
|
+
for (const field of key) {
|
|
533
|
+
if (!Object.hasOwn(joinSchema.fields, field)) {
|
|
534
|
+
throw new Error(`buildRelation: 'upsertKey' entry '${field}' is not a field of schema '${joinSchema.tableName}'. ` +
|
|
535
|
+
`Available: ${Object.keys(joinSchema.fields).join(', ')}.`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
return [...key];
|
|
539
|
+
}
|
|
363
540
|
export function buildRelation(mainSchema, mainField, joinSchema, joinField, options) {
|
|
364
541
|
const fields = options?.fields;
|
|
542
|
+
const reachable = fields ? narrowSchemaToFields(joinSchema, fields, joinField) : joinSchema;
|
|
543
|
+
const select = relationSelect(options, reachable);
|
|
544
|
+
const upsertKey = relationUpsertKey(options, joinSchema);
|
|
365
545
|
return {
|
|
366
|
-
joinSchema:
|
|
546
|
+
joinSchema: reachable,
|
|
367
547
|
joinField,
|
|
368
548
|
mainField,
|
|
369
549
|
alias: options?.alias ?? joinSchema.tableName,
|
|
370
|
-
|
|
550
|
+
...(select ? { select } : {}),
|
|
371
551
|
unique: options?.unique ?? false,
|
|
552
|
+
...(options?.target !== undefined ? { target: options.target } : {}),
|
|
372
553
|
...(fields ? { fields: [...fields] } : {}),
|
|
554
|
+
...(upsertKey ? { upsertKey } : {}),
|
|
373
555
|
};
|
|
374
556
|
}
|
|
375
|
-
|
|
376
|
-
|
|
557
|
+
/**
|
|
558
|
+
* The `TableConfig` that governs the target of a relation.
|
|
559
|
+
*
|
|
560
|
+
* A relation is declared against a Schema, while `dbTables` is keyed by route name and may
|
|
561
|
+
* expose one physical table under several keys, each with its own `readExclude`, `tenantScope`,
|
|
562
|
+
* `afterRead` and write-side rules (ADR 0010 makes those follow a join). Which key governs a
|
|
563
|
+
* join must therefore be one rule, shared by the generated body schemas and the engines — a
|
|
564
|
+
* body schema built from one config and an engine running another would advertise fields the
|
|
565
|
+
* engine hides, or the reverse.
|
|
566
|
+
*
|
|
567
|
+
* - `target` set: that key, which must exist and must be a config over the joined table.
|
|
568
|
+
* - Otherwise exactly one key over the joined table: that config, whatever the key is called.
|
|
569
|
+
* - Several keys and no `target`: a configuration error. Picking the first would make the
|
|
570
|
+
* outcome depend on object key order, and the keys differ precisely in what they hide.
|
|
571
|
+
* - No key at all: `undefined` — the joined table has no config, and no rule applies to it.
|
|
572
|
+
*
|
|
573
|
+
* Throws on a configuration error; `validateJoinTargets` runs it over every relation at
|
|
574
|
+
* startup so the error names the table and surfaces before the first request.
|
|
575
|
+
*/
|
|
576
|
+
export function resolveJoinTableConf(dbTables, joinDef) {
|
|
577
|
+
const joinedTable = joinDef.joinSchema.tableName;
|
|
578
|
+
if (joinDef.target !== undefined) {
|
|
579
|
+
const conf = Object.hasOwn(dbTables, joinDef.target) ? dbTables[joinDef.target] : undefined;
|
|
580
|
+
if (!conf) {
|
|
581
|
+
throw new Error(`relation "${joinDef.alias}" names target "${joinDef.target}", which is not a key of dbTables`);
|
|
582
|
+
}
|
|
583
|
+
if (conf.schema.tableName !== joinedTable) {
|
|
584
|
+
throw new Error(`relation "${joinDef.alias}" names target "${joinDef.target}", a config over "${conf.schema.tableName}", ` +
|
|
585
|
+
`but the relation joins "${joinedTable}"`);
|
|
586
|
+
}
|
|
587
|
+
return conf;
|
|
588
|
+
}
|
|
589
|
+
const keys = Object.keys(dbTables).filter((key) => dbTables[key].schema.tableName === joinedTable);
|
|
590
|
+
if (keys.length > 1) {
|
|
591
|
+
throw new Error(`relation "${joinDef.alias}" joins "${joinedTable}", which dbTables exposes under several keys ` +
|
|
592
|
+
`(${keys.join(', ')}): name the one that governs the join with buildRelation(…, { target: '<key>' })`);
|
|
593
|
+
}
|
|
594
|
+
return keys.length === 1 ? dbTables[keys[0]] : undefined;
|
|
377
595
|
}
|
|
378
|
-
|
|
379
|
-
|
|
596
|
+
/**
|
|
597
|
+
* Startup check of a whole `dbTables` map, run by the plugin and by `createSqlApi`: every
|
|
598
|
+
* entry has the 1.0 config shape — an entry written by hand, not through `defineTable`, would
|
|
599
|
+
* otherwise reach the engines in the pre-1.0 shape — and the target of every read and write
|
|
600
|
+
* relation resolves, so a broken one fails with the host table's name rather than on the
|
|
601
|
+
* first request that uses it.
|
|
602
|
+
*/
|
|
603
|
+
export function validateDbTables(dbTables) {
|
|
604
|
+
if (!dbTables || typeof dbTables !== 'object') {
|
|
605
|
+
throw new TypeError("'dbTables' is required: { <route name>: defineTable({ ... }) }");
|
|
606
|
+
}
|
|
607
|
+
for (const [key, conf] of Object.entries(dbTables))
|
|
608
|
+
assertTableShape(conf, `dbTables.${key}`);
|
|
609
|
+
for (const [key, conf] of Object.entries(dbTables)) {
|
|
610
|
+
for (const join of [...(conf.readJoins ?? []), ...(conf.writeJoins ?? [])]) {
|
|
611
|
+
try {
|
|
612
|
+
resolveJoinTableConf(dbTables, join);
|
|
613
|
+
}
|
|
614
|
+
catch (err) {
|
|
615
|
+
throw new Error(`Table "${key}": ${err.message}`, { cause: err });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
380
619
|
}
|