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,34 +1,28 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { buildTenantRowGuard, assertTenantOwnsAll } from '../../tenant.js';
|
|
2
2
|
import { httpError } from '../../errors.js';
|
|
3
3
|
import { primaryAsString, isCompositePrimary } from '../../../types.js';
|
|
4
4
|
export async function deleteEngine(params) {
|
|
5
5
|
const { db, tableConf, id, tenant, request } = params;
|
|
6
6
|
if (isCompositePrimary(tableConf.primary)) {
|
|
7
|
-
throw httpError(400, `Table "${tableConf.
|
|
7
|
+
throw httpError(400, `Table "${tableConf.schema.tableName}" has a composite primary key: delete-by-id would match on "${primaryAsString(tableConf.primary)}" alone and could remove multiple rows. Use a custom query.`);
|
|
8
8
|
}
|
|
9
9
|
const pk = primaryAsString(tableConf.primary);
|
|
10
|
-
const pkCol = tableConf.
|
|
11
|
-
const tableName = tableConf.
|
|
10
|
+
const pkCol = tableConf.schema.col(pk);
|
|
11
|
+
const tableName = tableConf.schema.tableName;
|
|
12
12
|
if (tableConf.beforeDelete) {
|
|
13
13
|
// Enforce tenant ownership before the hook so it never runs for rows the tenant
|
|
14
14
|
// cannot access. (When no hook is defined, the tenant-scoped DELETE below already
|
|
15
15
|
// prevents deleting non-owned rows, so the extra SELECT is skipped.)
|
|
16
|
-
await assertTenantOwnsAll(db, tenant, tableName, pkCol, [id]);
|
|
17
|
-
await tableConf.beforeDelete(db, request, id);
|
|
18
|
-
}
|
|
19
|
-
if (!tenant) {
|
|
20
|
-
const affectedRows = await db.delete(tableName, { [pkCol]: id });
|
|
21
|
-
if (affectedRows === 0)
|
|
22
|
-
throw httpError(404, `Record not found: ${id}`);
|
|
23
|
-
}
|
|
24
|
-
else {
|
|
25
|
-
const { where, values } = buildTenantDeleteWhere(db, tableName, pkCol, id, tenant);
|
|
26
|
-
const result = await db.query(`DELETE FROM ${db.qi(tableName)} WHERE ${where}`, values);
|
|
27
|
-
if (result.affectedRows === 0)
|
|
28
|
-
throw httpError(404, `Record not found: ${id}`);
|
|
16
|
+
await assertTenantOwnsAll(db, tenant, tableName, [pkCol], [[id]]);
|
|
17
|
+
await tableConf.beforeDelete({ db, req: request, id });
|
|
29
18
|
}
|
|
19
|
+
// The tenant's guard, when the table is scoped, joins the key in the same DELETE: a row the
|
|
20
|
+
// caller does not own is not deleted, and answers 404 like a missing one.
|
|
21
|
+
const affectedRows = await db.delete(tableName, { [pkCol]: id }, buildTenantRowGuard(db, tenant, tableName));
|
|
22
|
+
if (affectedRows === 0)
|
|
23
|
+
throw httpError(404, `Record not found: ${id}`);
|
|
30
24
|
if (tableConf.afterDelete) {
|
|
31
|
-
await tableConf.afterDelete(db, request, id);
|
|
25
|
+
await tableConf.afterDelete({ db, req: request, id });
|
|
32
26
|
}
|
|
33
27
|
return { main: { [pk]: id } };
|
|
34
28
|
}
|
|
@@ -8,26 +8,26 @@ import { primaryAsString, isCompositePrimary } from '../../../types.js';
|
|
|
8
8
|
export async function getEngine(params) {
|
|
9
9
|
const { db, tableConf, id, tenant, request } = params;
|
|
10
10
|
if (isCompositePrimary(tableConf.primary)) {
|
|
11
|
-
throw httpError(400, `Table "${tableConf.
|
|
11
|
+
throw httpError(400, `Table "${tableConf.schema.tableName}" has a composite primary key: get-by-id would match on "${primaryAsString(tableConf.primary)}" alone. Use search with all PK fields.`);
|
|
12
12
|
}
|
|
13
|
-
const pkCol = tableConf.
|
|
13
|
+
const pkCol = tableConf.schema.col(primaryAsString(tableConf.primary));
|
|
14
14
|
const cb = new ConditionBuilder('AND', db.cbDialect);
|
|
15
15
|
// Table-qualified: the tenant scope may add a through-join, and a bare PK column
|
|
16
16
|
// shared with the through table would be ambiguous.
|
|
17
|
-
cb.isEqual(`${db.qi(tableConf.
|
|
17
|
+
cb.isEqual(`${db.qi(tableConf.schema.tableName)}.${db.qi(pkCol)}`, id);
|
|
18
18
|
const joins = [];
|
|
19
19
|
if (tenant?.scope) {
|
|
20
20
|
const scope = tenant.scope;
|
|
21
|
-
cb.append(buildTenantCondition(db, scope, tenant.ids, tableConf.
|
|
21
|
+
cb.append(buildTenantCondition(db, scope, tenant.ids, tableConf.schema.tableName));
|
|
22
22
|
if ('through' in scope) {
|
|
23
|
-
joins.push(buildTenantJoin(db, scope, tableConf.
|
|
23
|
+
joins.push(buildTenantJoin(db, scope, tableConf.schema.tableName));
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
const where = cb.build(1, db.ph);
|
|
27
27
|
const values = cb.getValues();
|
|
28
28
|
const rows = await db.select({
|
|
29
|
-
tableName: tableConf.
|
|
30
|
-
columns: readableSelectColumns(tableConf, tableConf.
|
|
29
|
+
tableName: tableConf.schema.tableName,
|
|
30
|
+
columns: readableSelectColumns(tableConf, tableConf.schema, db),
|
|
31
31
|
where,
|
|
32
32
|
values,
|
|
33
33
|
limit: '1',
|
|
@@ -35,7 +35,7 @@ export async function getEngine(params) {
|
|
|
35
35
|
});
|
|
36
36
|
if (rows.length === 0)
|
|
37
37
|
throw httpError(404, `Record not found: ${id}`);
|
|
38
|
-
const main = camelcaseObject(rows[0], tableConf.
|
|
38
|
+
const main = camelcaseObject(rows[0], tableConf.schema);
|
|
39
39
|
await runAfterRead(db, request, [main], tableConf, 'get');
|
|
40
40
|
return { main };
|
|
41
41
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"insert.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/rest/insert.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"insert.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/rest/insert.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,YAAY,EACZ,YAAY,EAIb,MAAM,mBAAmB,CAAC;AAE3B,wBAAsB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CA+E9E"}
|
|
@@ -1,50 +1,63 @@
|
|
|
1
1
|
import { camelcaseObject } from '../../naming.js';
|
|
2
|
-
import { processSecondaries, prepareInsertRecord, assertUpsertKeys } from '../write-helpers.js';
|
|
2
|
+
import { processSecondaries, prepareInsertRecord, assertUpsertKeys, assertWriteJoinAliases, hasAliases, assertExcludedKeysExist, insertExcludedKeyFields, } from '../write-helpers.js';
|
|
3
3
|
import { enforceTenantOnWrites, assertTenantOwnsConflicts } from '../../tenant.js';
|
|
4
4
|
import { primaryAsCols } from '../../../types.js';
|
|
5
5
|
export async function insertEngine(params) {
|
|
6
|
-
const { db, tableConf, dbTables, request, record,
|
|
7
|
-
const
|
|
6
|
+
const { db, tableConf, dbTables, request, record, upsert, replace, tenant } = params;
|
|
7
|
+
const children = { upsert, replace };
|
|
8
|
+
const schema = tableConf.schema;
|
|
8
9
|
// Full primary key columns (composite PKs need every column for RETURNING /
|
|
9
10
|
// mysql synthesis, otherwise the response is missing PK fields).
|
|
10
11
|
const pkCol = primaryAsCols(tableConf.primary, (f) => schema.col(f));
|
|
12
|
+
assertWriteJoinAliases(tableConf, children);
|
|
11
13
|
// 1. Validate, run beforeInsert hook, snakecase, drop excluded fields.
|
|
12
|
-
const { camel: inputRecord, snake: mainRecord } = await prepareInsertRecord({ db, tableConf, request }, record,
|
|
13
|
-
// Steps 2-5 are atomic: a failure in
|
|
14
|
-
// main insert too.
|
|
14
|
+
const { camel: inputRecord, snake: mainRecord } = await prepareInsertRecord({ db, tableConf, dbTables, request }, record, children);
|
|
15
|
+
// Steps 2-5 are atomic: a failure in the child rows or afterInsert rolls back the
|
|
16
|
+
// main insert too. An adapter without connect() cannot run this at all (ADR 0023).
|
|
15
17
|
return db.withTransaction(async (tx) => {
|
|
16
18
|
// 2. Tenant: inject (direct) or validate FK (indirect) — enforced after user mutations
|
|
17
19
|
await enforceTenantOnWrites(tx, tenant, [mainRecord]);
|
|
18
|
-
// 3. Insert main →
|
|
19
|
-
let
|
|
20
|
-
const upsertKeys = tableConf.
|
|
20
|
+
// 3. Insert main → its PK, and what the statement did to the row
|
|
21
|
+
let written;
|
|
22
|
+
const upsertKeys = tableConf.upsertKey;
|
|
21
23
|
if (upsertKeys) {
|
|
22
24
|
const conflictCols = upsertKeys.map((k) => schema.col(k));
|
|
23
25
|
assertUpsertKeys(schema, conflictCols, [pkCol].flat(), [mainRecord]);
|
|
26
|
+
await assertExcludedKeysExist(tx, schema, conflictCols, insertExcludedKeyFields(tableConf, upsertKeys), [mainRecord], [record], (_, field) => `main.${field}`);
|
|
24
27
|
// Tenant isolation: a conflicting upsert must not overwrite a row owned by another tenant.
|
|
25
28
|
await assertTenantOwnsConflicts(tx, tenant, schema.tableName, conflictCols, [mainRecord]);
|
|
26
|
-
|
|
29
|
+
written = await tx.upsert(schema.tableName, mainRecord, conflictCols, pkCol);
|
|
27
30
|
}
|
|
28
31
|
else {
|
|
29
|
-
|
|
32
|
+
const pk = await tx.insert(schema.tableName, mainRecord, pkCol);
|
|
33
|
+
written = { pk, action: 'inserted' };
|
|
30
34
|
}
|
|
31
|
-
const mainPkCamel = camelcaseObject(
|
|
32
|
-
// 4.
|
|
35
|
+
const mainPkCamel = camelcaseObject(written.pk, schema);
|
|
36
|
+
// 4. Child rows: need full record for FK auto-fill (camelCase). A `replace` also removes
|
|
37
|
+
// the child rows the request left out — an upserted main row may have some (ADR 0029).
|
|
33
38
|
let secondaryResults;
|
|
34
|
-
|
|
39
|
+
let deletionResults;
|
|
40
|
+
if (hasAliases(upsert, replace)) {
|
|
35
41
|
const mainForFK = { ...inputRecord, ...mainPkCamel };
|
|
36
|
-
|
|
42
|
+
const outcome = await processSecondaries({ db: tx, tableConf, dbTables, mainRecord: mainForFK, tenant, request }, children);
|
|
43
|
+
secondaryResults = outcome.written;
|
|
44
|
+
if (Object.keys(outcome.removed).length > 0)
|
|
45
|
+
deletionResults = outcome.removed;
|
|
37
46
|
}
|
|
38
47
|
// 5. afterInsert hook (camelCase — input merged with generated PK)
|
|
39
48
|
if (tableConf.afterInsert) {
|
|
40
49
|
const mainForHook = { ...inputRecord, ...mainPkCamel };
|
|
41
|
-
await tableConf.afterInsert(
|
|
50
|
+
await tableConf.afterInsert({
|
|
51
|
+
db: tx, req: request, record: mainForHook, secondaries: secondaryResults, deletions: deletionResults,
|
|
52
|
+
});
|
|
42
53
|
}
|
|
43
|
-
// 6. Return PK
|
|
44
|
-
const result = { main: mainPkCamel };
|
|
54
|
+
// 6. Return the PK and the action
|
|
55
|
+
const result = { main: mainPkCamel, action: written.action };
|
|
45
56
|
if (secondaryResults && Object.keys(secondaryResults).length > 0) {
|
|
46
57
|
result.secondaries = secondaryResults;
|
|
47
58
|
}
|
|
59
|
+
if (deletionResults)
|
|
60
|
+
result.deletions = deletionResults;
|
|
48
61
|
return result;
|
|
49
62
|
});
|
|
50
63
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/rest/update.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,YAAY,EACZ,YAAY,
|
|
1
|
+
{"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/rest/update.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,YAAY,EACZ,YAAY,EAGb,MAAM,mBAAmB,CAAC;AAiC3B,wBAAsB,YAAY,CAAC,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CA2H9E"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { snakecaseRecord } from '../../naming.js';
|
|
2
2
|
import { removeWriteExcluded } from '../../write-access.js';
|
|
3
|
-
import { processSecondaries, processDeletions } from '../write-helpers.js';
|
|
3
|
+
import { processSecondaries, processDeletions, assertWriteJoinAliases, hasAliases } from '../write-helpers.js';
|
|
4
4
|
import { stripTenantColumn, assertTenantOwnership, buildTenantUpdateExtra, enforceTenantFKOnUpdate, } from '../../tenant.js';
|
|
5
|
-
import { runValidation } from '../validate.js';
|
|
5
|
+
import { runValidation, runChildValidation } from '../validate.js';
|
|
6
6
|
import { httpError } from '../../errors.js';
|
|
7
7
|
/**
|
|
8
8
|
* Confirm the row exists — and is visible to this tenant — when the request carries no
|
|
@@ -27,25 +27,32 @@ async function assertRecordExists(tx, tableName, pkCols, pkValues, extraConditio
|
|
|
27
27
|
throw httpError(404, `Record not found`);
|
|
28
28
|
}
|
|
29
29
|
export async function updateEngine(params) {
|
|
30
|
-
const { db, tableConf, dbTables, request, record,
|
|
31
|
-
const
|
|
30
|
+
const { db, tableConf, dbTables, request, record, upsert, delete: toDelete, replace, tenant } = params;
|
|
31
|
+
const children = { upsert, replace };
|
|
32
|
+
const schema = tableConf.schema;
|
|
32
33
|
// Every primary key field/column: composite PKs must match on ALL columns, otherwise an
|
|
33
34
|
// UPDATE keyed on the first column alone would hit every row sharing that value.
|
|
34
35
|
const pkFields = Array.isArray(tableConf.primary) ? tableConf.primary : [tableConf.primary];
|
|
35
36
|
const pkCols = pkFields.map((f) => schema.col(f));
|
|
36
37
|
const pkValues = pkFields.map((f) => record[f]);
|
|
38
|
+
assertWriteJoinAliases(tableConf, { upsert, delete: toDelete, replace });
|
|
37
39
|
const missingIdx = pkValues.findIndex((v) => v == null);
|
|
38
|
-
if (missingIdx !== -1)
|
|
39
|
-
throw httpError(400, `Primary key "${pkFields[missingIdx]}" is required
|
|
40
|
+
if (missingIdx !== -1) {
|
|
41
|
+
throw httpError(400, `Primary key "${pkFields[missingIdx]}" is required`, {
|
|
42
|
+
code: 'required',
|
|
43
|
+
path: `main.${pkFields[missingIdx]}`,
|
|
44
|
+
});
|
|
45
|
+
}
|
|
40
46
|
// 1. Tenant ownership check (indirect) — do it early so user mutations don't run on records they can't access
|
|
41
47
|
await assertTenantOwnership(db, tenant, schema.tableName, pkCols, pkValues);
|
|
42
48
|
// 2. Mutable copy of input in camelCase
|
|
43
49
|
const inputRecord = { ...record };
|
|
44
50
|
// 3. Custom validation (camelCase)
|
|
45
|
-
await runValidation(db, request, tableConf, inputRecord,
|
|
51
|
+
await runValidation(db, request, tableConf, inputRecord, children);
|
|
52
|
+
await runChildValidation({ db, request, tableConf, dbTables }, record, children);
|
|
46
53
|
// 4. beforeUpdate hook (camelCase — user can mutate with schema field names)
|
|
47
54
|
if (tableConf.beforeUpdate) {
|
|
48
|
-
await tableConf.beforeUpdate(db, request, inputRecord);
|
|
55
|
+
await tableConf.beforeUpdate({ db, req: request, record: inputRecord });
|
|
49
56
|
}
|
|
50
57
|
// 5. Drop what the database will not be told about (generated columns, writeExclude).
|
|
51
58
|
// After the hook on purpose: the column refuses a value whoever assigned it.
|
|
@@ -62,8 +69,8 @@ export async function updateEngine(params) {
|
|
|
62
69
|
stripTenantColumn(updateFields, tenant.scope);
|
|
63
70
|
await enforceTenantFKOnUpdate(db, tenant, updateFields);
|
|
64
71
|
}
|
|
65
|
-
// Steps 8-10 are atomic: a failure in
|
|
66
|
-
// update too.
|
|
72
|
+
// Steps 8-10 are atomic: a failure in the child rows rolls back the main
|
|
73
|
+
// update too. An adapter without connect() cannot run this at all (ADR 0023).
|
|
67
74
|
return db.withTransaction(async (tx) => {
|
|
68
75
|
// 8. Update main
|
|
69
76
|
const hasFieldsToUpdate = Object.keys(updateFields).length > 0;
|
|
@@ -80,21 +87,31 @@ export async function updateEngine(params) {
|
|
|
80
87
|
}
|
|
81
88
|
// Build the main response (PK-only — every PK field)
|
|
82
89
|
const mainResult = Object.fromEntries(pkFields.map((f, i) => [f, pkValues[i]]));
|
|
83
|
-
// 9.
|
|
90
|
+
// 9. Child rows to write (`upsert` and `replace`, FK auto-filled — camelCase); a `replace`
|
|
91
|
+
// also removes the child rows the request left out (ADR 0029)
|
|
84
92
|
let secondaryResults;
|
|
85
|
-
|
|
93
|
+
let replaced = {};
|
|
94
|
+
if (hasAliases(upsert, replace)) {
|
|
86
95
|
const mainForFK = { ...inputRecord };
|
|
87
|
-
secondaryResults = await processSecondaries({ db: tx, tableConf, dbTables, mainRecord: mainForFK, tenant, request },
|
|
96
|
+
({ written: secondaryResults, removed: replaced } = await processSecondaries({ db: tx, tableConf, dbTables, mainRecord: mainForFK, tenant, request }, children));
|
|
88
97
|
}
|
|
89
|
-
// 10.
|
|
98
|
+
// 10. Child rows to delete (FK auto-fill from main), then the rows a replace removed
|
|
90
99
|
let deletionResults;
|
|
91
|
-
if (
|
|
100
|
+
if (hasAliases(toDelete)) {
|
|
92
101
|
const mainForFK = { ...inputRecord };
|
|
93
|
-
deletionResults = await processDeletions({ db: tx, tableConf, dbTables, mainRecord: mainForFK, tenant, request },
|
|
102
|
+
deletionResults = await processDeletions({ db: tx, tableConf, dbTables, mainRecord: mainForFK, tenant, request }, toDelete ?? {});
|
|
94
103
|
}
|
|
104
|
+
if (Object.keys(replaced).length > 0)
|
|
105
|
+
deletionResults = { ...deletionResults, ...replaced };
|
|
95
106
|
// 11. afterUpdate hook (inside the transaction: throwing rolls everything back)
|
|
96
107
|
if (tableConf.afterUpdate) {
|
|
97
|
-
await tableConf.afterUpdate(
|
|
108
|
+
await tableConf.afterUpdate({
|
|
109
|
+
db: tx,
|
|
110
|
+
req: request,
|
|
111
|
+
record: inputRecord,
|
|
112
|
+
secondaries: secondaryResults,
|
|
113
|
+
deletions: deletionResults,
|
|
114
|
+
});
|
|
98
115
|
}
|
|
99
116
|
// 12. Return PK-only
|
|
100
117
|
const result = { main: mainResult };
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import { Expression } from 'node-condition-builder';
|
|
11
11
|
import type { QueryClient } from '../../db.js';
|
|
12
12
|
import type { QueryParams } from '../query-params.js';
|
|
13
|
-
import type { DbTables,
|
|
13
|
+
import type { DbTables, TableConfig, JoinGroupRequest, SearchCondition, TenantContext } from '../../../types.js';
|
|
14
14
|
/**
|
|
15
15
|
* One aggregation function, as SQL. `zeroWhenEmpty`: over no rows it means 0 (nothing counted,
|
|
16
16
|
* nothing summed), so the correlated subquery coalesces its NULL to 0. min/max/avg over no rows
|
|
@@ -34,7 +34,7 @@ export declare function aggExpr(fn: AggFn, qualifiedCol: string): string;
|
|
|
34
34
|
* child rows of other tenants, disagreeing with the scoped `result.joinGroup` for the same
|
|
35
35
|
* alias and leaking their existence.
|
|
36
36
|
*/
|
|
37
|
-
export declare function buildAggOrderExpr(db: QueryClient, dbTables: DbTables, tableConf:
|
|
37
|
+
export declare function buildAggOrderExpr(db: QueryClient, dbTables: DbTables, tableConf: TableConfig, alias: string, fn: string, field: string, joinGroup: Record<string, JoinGroupRequest> | undefined, tenant?: TenantContext, at?: string): Expression;
|
|
38
38
|
/** HAVING-style conditions: the dotted `<alias>.<fn>.<field>` entries of `conditions`. */
|
|
39
|
-
export declare function appendAggConditions(params: QueryParams, conditions: SearchCondition[], db: QueryClient, dbTables: DbTables, tableConf:
|
|
39
|
+
export declare function appendAggConditions(params: QueryParams, conditions: SearchCondition[], db: QueryClient, dbTables: DbTables, tableConf: TableConfig, joinGroup: Record<string, JoinGroupRequest> | undefined, tenant?: TenantContext): string;
|
|
40
40
|
//# sourceMappingURL=aggregations.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"aggregations.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/aggregations.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAoB,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"aggregations.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/aggregations.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAoB,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAOtD,OAAO,KAAK,EACV,QAAQ,EACR,WAAW,EACX,gBAAgB,EAChB,eAAe,EACf,aAAa,EACd,MAAM,mBAAmB,CAAC;AAE3B;;;;;GAKG;AACH,MAAM,WAAW,KAAK;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,aAAa,EAAE,OAAO,CAAA;CAAE;AAEjF,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAOxC,CAAC;AAEF,wBAAgB,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM,CAE/D;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,KAAK,EAAE,MAAM,EACb,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,SAAS,EACvD,MAAM,CAAC,EAAE,aAAa,EACtB,EAAE,SAAK,GACN,UAAU,CAoEZ;AAED,0FAA0F;AAC1F,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,WAAW,EACnB,UAAU,EAAE,eAAe,EAAE,EAC7B,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,SAAS,EACvD,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CA0BR"}
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { ConditionBuilder, Expression } from 'node-condition-builder';
|
|
11
11
|
import { ALLOWED_SET } from '../../condition-methods.js';
|
|
12
12
|
import { tenantForTable, buildTenantRowGuard } from '../../tenant.js';
|
|
13
|
+
import { resolveJoinTableConf } from '../../table-helpers.js';
|
|
13
14
|
import { err400, validateSchemaField } from './fields.js';
|
|
14
15
|
import { requireJoin, extractJoinRefs, subqueryAlias } from './joins.js';
|
|
15
16
|
import { buildJoinRefCondition, dispatchConditionMethod } from './conditions.js';
|
|
@@ -34,26 +35,28 @@ export function aggExpr(fn, qualifiedCol) {
|
|
|
34
35
|
* child rows of other tenants, disagreeing with the scoped `result.joinGroup` for the same
|
|
35
36
|
* alias and leaking their existence.
|
|
36
37
|
*/
|
|
37
|
-
export function buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant) {
|
|
38
|
+
export function buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant, at = '') {
|
|
38
39
|
const aggFn = AGG_FN[fn];
|
|
39
40
|
if (!aggFn)
|
|
40
|
-
err400(`Invalid aggregation function: ${fn}`);
|
|
41
|
+
err400('invalid_aggregation', at, `Invalid aggregation function: ${fn}`);
|
|
41
42
|
const groupReq = joinGroup?.[alias];
|
|
42
43
|
if (!groupReq)
|
|
43
|
-
err400(`orderBy/conditions reference undeclared joinGroup: ${alias}`);
|
|
44
|
-
const declaredFields = groupReq
|
|
44
|
+
err400('undeclared_aggregation', at, `orderBy/conditions reference undeclared joinGroup: ${alias}`);
|
|
45
|
+
const declaredFields = groupReq[fn];
|
|
45
46
|
if (!Array.isArray(declaredFields) || !declaredFields.includes(field)) {
|
|
46
|
-
err400(`orderBy/conditions reference undeclared aggregation: ${alias}.${fn}.${field}`);
|
|
47
|
+
err400('undeclared_aggregation', at, `orderBy/conditions reference undeclared aggregation: ${alias}.${fn}.${field}`);
|
|
47
48
|
}
|
|
48
|
-
const joinDef = requireJoin(tableConf, alias, false);
|
|
49
|
+
const joinDef = requireJoin(tableConf, alias, false, at);
|
|
49
50
|
const { joinSchema, joinField } = joinDef;
|
|
50
|
-
if (groupReq.
|
|
51
|
-
|
|
51
|
+
if (groupReq.by && groupReq.by !== joinField) {
|
|
52
|
+
// One value per main row is needed: with `by` on a non-FK column a main row has several.
|
|
53
|
+
const clause = at === 'orderBy' ? 'orderBy' : 'a condition';
|
|
54
|
+
err400('invalid_aggregation', at, `Cannot use aggregation ${alias}.${fn}.${field} in ${clause}: joinGroup '${alias}' groups by the non-FK column '${groupReq.by}', not by the correlation FK '${joinField}'`);
|
|
52
55
|
}
|
|
53
56
|
// Pass the join table's conf: without it validateSchemaField skips the readExclude
|
|
54
57
|
// check, and a HAVING-style condition on a hidden field becomes a 400-vs-200 oracle
|
|
55
58
|
// (executeJoinGroup's own validation is skipped when the main result set is empty).
|
|
56
|
-
const fieldCol = validateSchemaField(field, joinSchema, dbTables
|
|
59
|
+
const fieldCol = validateSchemaField(field, joinSchema, resolveJoinTableConf(dbTables, joinDef), at);
|
|
57
60
|
const refs = extractJoinRefs(db, tableConf, joinDef);
|
|
58
61
|
// The subquery FROM is aliased so the correlation to the outer table survives a
|
|
59
62
|
// self-referencing relation; everything inside references the alias.
|
|
@@ -61,7 +64,7 @@ export function buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joi
|
|
|
61
64
|
const subRef = db.qi(subAlias);
|
|
62
65
|
let filterWhere = '';
|
|
63
66
|
let filterVals = [];
|
|
64
|
-
const joinTableConf = dbTables
|
|
67
|
+
const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
|
|
65
68
|
// Tenant scope first: it is emitted before the request's own filter, so its values must be
|
|
66
69
|
// bound in that order too.
|
|
67
70
|
const guard = buildTenantRowGuard(db, tenantForTable(tenant, joinTableConf), subAlias);
|
|
@@ -73,7 +76,7 @@ export function buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joi
|
|
|
73
76
|
tenantVals.push(...rendered.values);
|
|
74
77
|
}
|
|
75
78
|
if (groupReq.filters || groupReq.conditions?.length) {
|
|
76
|
-
const cb = buildJoinRefCondition(joinTableConf, joinSchema, { filters: groupReq.filters, conditions: groupReq.conditions }, db, subAlias);
|
|
79
|
+
const cb = buildJoinRefCondition(joinTableConf, joinSchema, { filters: groupReq.filters, conditions: groupReq.conditions }, db, subAlias, `joinGroup.${alias}`);
|
|
77
80
|
const fragment = cb.toExpression();
|
|
78
81
|
if (fragment.value) {
|
|
79
82
|
filterWhere = ` AND ${fragment.value}`;
|
|
@@ -88,22 +91,23 @@ export function buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joi
|
|
|
88
91
|
/** HAVING-style conditions: the dotted `<alias>.<fn>.<field>` entries of `conditions`. */
|
|
89
92
|
export function appendAggConditions(params, conditions, db, dbTables, tableConf, joinGroup, tenant) {
|
|
90
93
|
let where = '';
|
|
91
|
-
for (const c of conditions) {
|
|
94
|
+
for (const [i, c] of conditions.entries()) {
|
|
92
95
|
if (!c.field.includes('.'))
|
|
93
96
|
continue;
|
|
97
|
+
const here = `conditions.${i}`;
|
|
94
98
|
if (!ALLOWED_SET.has(c.method)) {
|
|
95
|
-
err400(`Invalid condition method: ${c.method}`);
|
|
99
|
+
err400('invalid_method', `${here}.method`, `Invalid condition method: ${c.method}`);
|
|
96
100
|
}
|
|
97
101
|
const parts = c.field.split('.');
|
|
98
102
|
if (parts.length !== 3) {
|
|
99
|
-
err400(`Invalid dotted field in condition: ${c.field} (expected <alias>.<fn>.<field>)`);
|
|
103
|
+
err400('unknown_field', `${here}.field`, `Invalid dotted field in condition: ${c.field} (expected <alias>.<fn>.<field>)`);
|
|
100
104
|
}
|
|
101
105
|
const [alias, fn, field] = parts;
|
|
102
106
|
// The aggregate carries the values of its own filter; passing it as the left-hand side
|
|
103
107
|
// lets the ConditionBuilder place those and the compared value in one step.
|
|
104
|
-
const expr = buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant);
|
|
108
|
+
const expr = buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant, `${here}.field`);
|
|
105
109
|
const tmpCb = new ConditionBuilder('AND', db.cbDialect);
|
|
106
|
-
dispatchConditionMethod(tmpCb, c.method, expr, c.params);
|
|
110
|
+
dispatchConditionMethod(tmpCb, c.method, expr, c.params, here);
|
|
107
111
|
where += ` AND ${params.emitCondition(tmpCb, db)}`;
|
|
108
112
|
}
|
|
109
113
|
return where;
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { ConditionBuilder, Expression } from 'node-condition-builder';
|
|
9
9
|
import type { QueryClient } from '../../db.js';
|
|
10
|
-
import type { FilterRecord,
|
|
10
|
+
import type { FilterRecord, TableConfig, JoinRefFilter, SchemaDefinition, SearchCondition } from '../../../types.js';
|
|
11
11
|
/**
|
|
12
12
|
* Apply one condition method to a builder, after checking the request actually supplied the
|
|
13
13
|
* operands that method needs.
|
|
@@ -17,15 +17,19 @@ import type { FilterRecord, ITable, JoinRefFilter, SchemaDefinition, SearchCondi
|
|
|
17
17
|
* error handler can only report as a 500. Arity is checked here rather than at the four call
|
|
18
18
|
* sites so no path can skip it.
|
|
19
19
|
*/
|
|
20
|
-
export declare function dispatchConditionMethod(cb: ConditionBuilder, method: string, colOrExpr: string | Expression, params: unknown[] | undefined): void;
|
|
21
|
-
|
|
20
|
+
export declare function dispatchConditionMethod(cb: ConditionBuilder, method: string, colOrExpr: string | Expression, params: unknown[] | undefined, at?: string): void;
|
|
21
|
+
/**
|
|
22
|
+
* The WHERE of a join reference: its equality `filters` (plain, computed) and its operator
|
|
23
|
+
* `conditions`. `at` is the reference's request path (`joinGroup.<alias>`), for the 400s.
|
|
24
|
+
*/
|
|
25
|
+
export declare function buildJoinRefCondition(joinTableConf: TableConfig | undefined, joinSchema: SchemaDefinition, ref: JoinRefFilter, db: QueryClient, qualifier?: string, at?: string): ConditionBuilder;
|
|
22
26
|
/**
|
|
23
27
|
* Apply non-dotted conditions to the main `condition` ConditionBuilder when
|
|
24
28
|
* possible. For schema fields → straight dispatch. For computed fields → return
|
|
25
29
|
* side-channel clauses to be appended to WHERE later (with correct placeholder
|
|
26
30
|
* offsets), since ConditionBuilder cannot bind values for an LHS expression.
|
|
27
31
|
*/
|
|
28
|
-
export declare function applyConditions(condition: ConditionBuilder, conditions: SearchCondition[], schema: SchemaDefinition, tableConf:
|
|
32
|
+
export declare function applyConditions(condition: ConditionBuilder, conditions: SearchCondition[], schema: SchemaDefinition, tableConf: TableConfig, db: QueryClient): void;
|
|
29
33
|
/** Computed-field equality filters on the main table. */
|
|
30
|
-
export declare function applyComputedFilters(condition: ConditionBuilder, filters: FilterRecord, tableConf:
|
|
34
|
+
export declare function applyComputedFilters(condition: ConditionBuilder, filters: FilterRecord, tableConf: TableConfig, db: QueryClient): void;
|
|
31
35
|
//# sourceMappingURL=conditions.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conditions.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/conditions.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"conditions.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/conditions.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACtE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAa/C,OAAO,KAAK,EAEV,YAAY,EACZ,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,eAAe,EAChB,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CACrC,EAAE,EAAE,gBAAgB,EACpB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,GAAG,UAAU,EAC9B,MAAM,EAAE,OAAO,EAAE,GAAG,SAAS,EAC7B,EAAE,SAAK,GACN,IAAI,CA6BN;AA4DD;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,aAAa,EAAE,WAAW,GAAG,SAAS,EACtC,UAAU,EAAE,gBAAgB,EAC5B,GAAG,EAAE,aAAa,EAClB,EAAE,EAAE,WAAW,EACf,SAAS,CAAC,EAAE,MAAM,EAClB,EAAE,SAAK,GACN,gBAAgB,CAuBlB;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,SAAS,EAAE,gBAAgB,EAC3B,UAAU,EAAE,eAAe,EAAE,EAC7B,MAAM,EAAE,gBAAgB,EACxB,SAAS,EAAE,WAAW,EACtB,EAAE,EAAE,WAAW,GACd,IAAI,CAeN;AAED,yDAAyD;AACzD,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,gBAAgB,EAC3B,OAAO,EAAE,YAAY,EACrB,SAAS,EAAE,WAAW,EACtB,EAAE,EAAE,WAAW,GACd,IAAI,CAIN"}
|
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { ConditionBuilder } from 'node-condition-builder';
|
|
9
9
|
import { assertFiltersReadable, ownField } from '../../read-access.js';
|
|
10
|
+
import { buildTableFilters } from '../../table-helpers.js';
|
|
10
11
|
import { ALLOWED_SET, SINGLE_VALUE_SET, BETWEEN_SET, IN_SET, NULL_SET, } from '../../condition-methods.js';
|
|
11
|
-
import { err400, validateSchemaField, evaluateComputedField, resolveFieldRef, } from './fields.js';
|
|
12
|
+
import { err400, subPath, validateSchemaField, evaluateComputedField, resolveFieldRef, } from './fields.js';
|
|
12
13
|
/**
|
|
13
14
|
* Apply one condition method to a builder, after checking the request actually supplied the
|
|
14
15
|
* operands that method needs.
|
|
@@ -18,14 +19,15 @@ import { err400, validateSchemaField, evaluateComputedField, resolveFieldRef, }
|
|
|
18
19
|
* error handler can only report as a 500. Arity is checked here rather than at the four call
|
|
19
20
|
* sites so no path can skip it.
|
|
20
21
|
*/
|
|
21
|
-
export function dispatchConditionMethod(cb, method, colOrExpr, params) {
|
|
22
|
+
export function dispatchConditionMethod(cb, method, colOrExpr, params, at = '') {
|
|
23
|
+
const paramsPath = subPath(at, 'params');
|
|
22
24
|
if (params !== undefined && !Array.isArray(params)) {
|
|
23
|
-
err400(`Condition method '${method}': 'params' must be an array`);
|
|
25
|
+
err400('invalid_params', paramsPath, `Condition method '${method}': 'params' must be an array`);
|
|
24
26
|
}
|
|
25
27
|
const args = params ?? [];
|
|
26
28
|
const require = (n) => {
|
|
27
29
|
if (args.length < n) {
|
|
28
|
-
err400(`Condition method '${method}' requires ${n} param(s), got ${args.length}`);
|
|
30
|
+
err400('invalid_params', paramsPath, `Condition method '${method}' requires ${n} param(s), got ${args.length}`);
|
|
29
31
|
}
|
|
30
32
|
};
|
|
31
33
|
if (SINGLE_VALUE_SET.has(method)) {
|
|
@@ -41,7 +43,7 @@ export function dispatchConditionMethod(cb, method, colOrExpr, params) {
|
|
|
41
43
|
// An explicit `undefined` stays a documented no-op; any other non-array would make the
|
|
42
44
|
// builder iterate a non-iterable.
|
|
43
45
|
if (args[0] !== undefined && !Array.isArray(args[0])) {
|
|
44
|
-
err400(`Condition method '${method}' requires an array as its first param`);
|
|
46
|
+
err400('invalid_params', paramsPath, `Condition method '${method}' requires an array as its first param`);
|
|
45
47
|
}
|
|
46
48
|
cb[method](colOrExpr, args[0]);
|
|
47
49
|
}
|
|
@@ -71,37 +73,45 @@ function applyComputedEqualityFilters(cb, filters, computed, schema, db, qualifi
|
|
|
71
73
|
cb.isEqual(expr, value);
|
|
72
74
|
}
|
|
73
75
|
}
|
|
74
|
-
/**
|
|
75
|
-
|
|
76
|
+
/**
|
|
77
|
+
* Operator conditions on a join reference, against a schema or a computed field. `at` is the
|
|
78
|
+
* request path of the join reference (`joinMultiple.<alias>`), '' when unknown.
|
|
79
|
+
*/
|
|
80
|
+
function applyJoinRefConditions(cb, conditions, joinTableConf, joinSchema, db, colQualifier, at) {
|
|
76
81
|
const computed = joinTableConf?.computedFields;
|
|
77
|
-
for (const c of conditions) {
|
|
82
|
+
for (const [i, c] of conditions.entries()) {
|
|
83
|
+
const here = subPath(subPath(at, 'conditions'), i);
|
|
78
84
|
if (!ALLOWED_SET.has(c.method)) {
|
|
79
|
-
err400(`Invalid condition method: ${c.method}`);
|
|
85
|
+
err400('invalid_method', subPath(here, 'method'), `Invalid condition method: ${c.method}`);
|
|
80
86
|
}
|
|
81
87
|
// Computed fields resolve to an Expression carrying their own bound values, which the
|
|
82
88
|
// ConditionBuilder places together with the compared value.
|
|
83
89
|
const fn = ownField(computed, c.field);
|
|
84
90
|
const operand = fn
|
|
85
91
|
? evaluateComputedField(c.field, fn, joinSchema, db, colQualifier, '', true)
|
|
86
|
-
: `${db.qi(colQualifier)}.${db.qi(validateSchemaField(c.field, joinSchema, joinTableConf))}`;
|
|
87
|
-
dispatchConditionMethod(cb, c.method, operand, c.params ?? []);
|
|
92
|
+
: `${db.qi(colQualifier)}.${db.qi(validateSchemaField(c.field, joinSchema, joinTableConf, subPath(here, 'field')))}`;
|
|
93
|
+
dispatchConditionMethod(cb, c.method, operand, c.params ?? [], here);
|
|
88
94
|
}
|
|
89
95
|
}
|
|
90
|
-
|
|
91
|
-
|
|
96
|
+
/**
|
|
97
|
+
* The WHERE of a join reference: its equality `filters` (plain, computed) and its operator
|
|
98
|
+
* `conditions`. `at` is the reference's request path (`joinGroup.<alias>`), for the 400s.
|
|
99
|
+
*/
|
|
100
|
+
export function buildJoinRefCondition(joinTableConf, joinSchema, ref, db, qualifier, at = '') {
|
|
101
|
+
assertFiltersReadable(ref.filters, joinTableConf, subPath(at, 'filters'));
|
|
92
102
|
// Filter keys are checked by assertJoinFilterKeys, up front in searchEngine — this side
|
|
93
103
|
// query may never run, so it is not a place a request can be rejected from.
|
|
94
104
|
// Bare table name for plain side-queries; the subquery alias when the condition lands
|
|
95
105
|
// inside an aliased, correlated FROM (there the table name would resolve to the outer query).
|
|
96
106
|
const colQualifier = qualifier ?? joinSchema.tableName;
|
|
97
107
|
const cb = (ref.filters && joinTableConf)
|
|
98
|
-
? joinTableConf
|
|
108
|
+
? buildTableFilters(joinTableConf, ref.filters, db.cbDialect, colQualifier)
|
|
99
109
|
: new ConditionBuilder('AND', db.cbDialect);
|
|
100
110
|
if (ref.filters) {
|
|
101
111
|
applyComputedEqualityFilters(cb, ref.filters, joinTableConf?.computedFields, joinSchema, db, colQualifier);
|
|
102
112
|
}
|
|
103
113
|
if (ref.conditions?.length) {
|
|
104
|
-
applyJoinRefConditions(cb, ref.conditions, joinTableConf, joinSchema, db, colQualifier);
|
|
114
|
+
applyJoinRefConditions(cb, ref.conditions, joinTableConf, joinSchema, db, colQualifier, at);
|
|
105
115
|
}
|
|
106
116
|
return cb;
|
|
107
117
|
}
|
|
@@ -112,20 +122,21 @@ export function buildJoinRefCondition(joinTableConf, joinSchema, ref, db, qualif
|
|
|
112
122
|
* offsets), since ConditionBuilder cannot bind values for an LHS expression.
|
|
113
123
|
*/
|
|
114
124
|
export function applyConditions(condition, conditions, schema, tableConf, db) {
|
|
115
|
-
for (const c of conditions) {
|
|
125
|
+
for (const [i, c] of conditions.entries()) {
|
|
116
126
|
// Skip dot-notation fields — those become aggregation conditions processed later
|
|
117
127
|
if (c.field.includes('.'))
|
|
118
128
|
continue;
|
|
129
|
+
const here = `conditions.${i}`;
|
|
119
130
|
if (!ALLOWED_SET.has(c.method)) {
|
|
120
|
-
err400(`Invalid condition method: ${c.method}`);
|
|
131
|
+
err400('invalid_method', `${here}.method`, `Invalid condition method: ${c.method}`);
|
|
121
132
|
}
|
|
122
133
|
// A computed field resolves to an Expression carrying its own bound values; the
|
|
123
134
|
// ConditionBuilder places them, so no placeholder offset is computed here.
|
|
124
|
-
const ref = resolveFieldRef(c.field, schema, tableConf, db);
|
|
125
|
-
dispatchConditionMethod(condition, c.method, ref.expr, c.params);
|
|
135
|
+
const ref = resolveFieldRef(c.field, schema, tableConf, db, undefined, `${here}.field`);
|
|
136
|
+
dispatchConditionMethod(condition, c.method, ref.expr, c.params, here);
|
|
126
137
|
}
|
|
127
138
|
}
|
|
128
139
|
/** Computed-field equality filters on the main table. */
|
|
129
140
|
export function applyComputedFilters(condition, filters, tableConf, db) {
|
|
130
|
-
applyComputedEqualityFilters(condition, filters, tableConf.computedFields, tableConf.
|
|
141
|
+
applyComputedEqualityFilters(condition, filters, tableConf.computedFields, tableConf.schema, db);
|
|
131
142
|
}
|