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
|
@@ -7,9 +7,30 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { Expression } from 'node-condition-builder';
|
|
9
9
|
import type { QueryClient } from '../../db.js';
|
|
10
|
-
import type {
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
import type { TableConfig, SchemaDefinition, ComputedFieldFn } from '../../../types.js';
|
|
11
|
+
/**
|
|
12
|
+
* Throw a 400 the client can place: `code` is the stable machine code and `path` the dot path
|
|
13
|
+
* of the offending value in the request ('' when the rejection is not attributable to one
|
|
14
|
+
* input). Both land in the response's `fields`, see `ValidationField`.
|
|
15
|
+
*/
|
|
16
|
+
export declare function err400(code: string, path: string, message: string): never;
|
|
17
|
+
/**
|
|
18
|
+
* Reject a request key retired in 1.0: a client still sending it gets a 400 naming the key
|
|
19
|
+
* instead of a response that silently ignores it.
|
|
20
|
+
*/
|
|
21
|
+
export declare function rejectRetiredKey(input: object | undefined, key: string, at: string, instead: string): void;
|
|
22
|
+
/**
|
|
23
|
+
* Search parameters retired in 1.0, checked at every search entry point: `selectComputed` was
|
|
24
|
+
* folded into `select`, the one-field `computeMin/Max/Sum/Avg` into `compute`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function rejectRetiredSearchKeys(params: object): void;
|
|
27
|
+
/** `at.key`, or '' when `at` is unknown: a child path is only as precise as its parent. */
|
|
28
|
+
export declare function subPath(at: string, key: string | number): string;
|
|
29
|
+
/**
|
|
30
|
+
* The column of a schema field named by the request, or a 400 when the schema has no such
|
|
31
|
+
* field or `tableConf` hides it. `at` is the request path of the reference, for the 400.
|
|
32
|
+
*/
|
|
33
|
+
export declare function validateSchemaField(field: string, schema: SchemaDefinition, tableConf?: TableConfig, at?: string): string;
|
|
13
34
|
/**
|
|
14
35
|
* Resolve a field reference in a request body to a SQL operand. A schema column becomes
|
|
15
36
|
* the quoted column name; a computed field becomes an Expression carrying its own bound
|
|
@@ -19,16 +40,16 @@ export interface ResolvedFieldRef {
|
|
|
19
40
|
expr: string | Expression;
|
|
20
41
|
computed: boolean;
|
|
21
42
|
}
|
|
22
|
-
export declare function resolveFieldRef(field: string, schema: SchemaDefinition, tableConf:
|
|
43
|
+
export declare function resolveFieldRef(field: string, schema: SchemaDefinition, tableConf: TableConfig | undefined, db: QueryClient, alias?: string, at?: string): ResolvedFieldRef;
|
|
23
44
|
/**
|
|
24
45
|
* Evaluate a computed field into an Expression carrying its own bound values.
|
|
25
46
|
*
|
|
26
47
|
* Inside a WHERE clause the ConditionBuilder assigns the placeholder indexes, so bound
|
|
27
48
|
* values are always safe there. `allowBoundValues=false` is for the positions that sit
|
|
28
49
|
* *before* the WHERE values in the parameter order (SELECT projections, aggregations),
|
|
29
|
-
* where they cannot be placed correctly; those still reject with 400
|
|
50
|
+
* where they cannot be placed correctly; those still reject with 400, at request path `at`.
|
|
30
51
|
*/
|
|
31
|
-
export declare function evaluateComputedField(name: string, fn: ComputedFieldFn, schema: SchemaDefinition, db: QueryClient, alias: string | undefined, message: string, allowBoundValues?: boolean): Expression;
|
|
52
|
+
export declare function evaluateComputedField(name: string, fn: ComputedFieldFn, schema: SchemaDefinition, db: QueryClient, alias: string | undefined, message: string, allowBoundValues?: boolean, at?: string): Expression;
|
|
32
53
|
/** Bound values carried by a resolved field reference. */
|
|
33
54
|
export declare function refValues(expr: string | Expression): unknown[];
|
|
34
55
|
/** Render a resolved field reference to SQL, binding any values from `startIndex`. */
|
|
@@ -37,13 +58,25 @@ export declare function renderRef(expr: string | Expression, startIndex: number,
|
|
|
37
58
|
* that are projected by their declared name (skipped by camelcaseObject). */
|
|
38
59
|
export declare function mapRowsToCamelCase(rows: Record<string, unknown>[], schema: SchemaDefinition, computedFieldNames?: Iterable<string>): Record<string, unknown>[];
|
|
39
60
|
/**
|
|
40
|
-
* Build the SELECT columns list for a join fetch:
|
|
41
|
-
*
|
|
42
|
-
*
|
|
61
|
+
* Build the SELECT columns list for a join fetch: the quoted columns of the `select`ed fields,
|
|
62
|
+
* each validated (unknown or `readExclude`d → 400 at `<at>.<i>`). Without a `select`, every
|
|
63
|
+
* readable column of the join table.
|
|
43
64
|
*
|
|
44
|
-
* On a relation narrowed by a `fields` allowlist the
|
|
65
|
+
* On a relation narrowed by a `fields` allowlist the default is always spelled out. Emitting a
|
|
45
66
|
* real `SELECT *` there would fetch the excluded columns and leave them to be dropped by
|
|
46
67
|
* the response serializer — which does not run for a caller of `sqlApi.search()`.
|
|
47
68
|
*/
|
|
48
|
-
export declare function
|
|
69
|
+
export declare function buildJoinSelectColumns(select: string[] | undefined, joinSchema: SchemaDefinition, db: QueryClient, joinTableConf?: TableConfig, restricted?: boolean, at?: string): string;
|
|
70
|
+
/**
|
|
71
|
+
* The main query's column list for a request `select`: the listed schema fields, validated one
|
|
72
|
+
* by one (unknown or `readExclude`d → 400 at `select.<i>`), then `required` ones the request did
|
|
73
|
+
* not list — the primary key, join correlation keys, DISTINCT's ORDER BY fields — when readable.
|
|
74
|
+
* Computed fields in `select` are skipped here: `executeMainQuery` projects them.
|
|
75
|
+
*
|
|
76
|
+
* {@link SELECT_ALL} in the list stands for the default projection — every readable column, as
|
|
77
|
+
* a search without `select` returns — so a client asks for a computed field without copying the
|
|
78
|
+
* readable set: `['*', 'fullName']`. The other names are still validated; a schema field next
|
|
79
|
+
* to it adds nothing. See ADR 0028.
|
|
80
|
+
*/
|
|
81
|
+
export declare function buildMainSelectColumns(select: string[], required: string[], tableConf: TableConfig, db: QueryClient): string;
|
|
49
82
|
//# sourceMappingURL=fields.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/fields.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"fields.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/fields.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAW/C,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAGhB,eAAe,EAChB,MAAM,mBAAmB,CAAC;AAI3B;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,KAAK,CAEzE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAI1G;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAM5D;AAED,2FAA2F;AAC3F,wBAAgB,OAAO,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAEhE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,gBAAgB,EACxB,SAAS,CAAC,EAAE,WAAW,EACvB,EAAE,SAAK,GACN,MAAM,CAMR;AA8BD;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC;IAC1B,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,wBAAgB,eAAe,CAC7B,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,gBAAgB,EACxB,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,EAAE,EAAE,WAAW,EACf,KAAK,CAAC,EAAE,MAAM,EACd,EAAE,SAAK,GACN,gBAAgB,CAiBlB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,eAAe,EACnB,MAAM,EAAE,gBAAgB,EACxB,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,MAAM,GAAG,SAAS,EACzB,OAAO,EAAE,MAAM,EACf,gBAAgB,UAAQ,EACxB,EAAE,SAAK,GACN,UAAU,CAMZ;AA0BD,0DAA0D;AAC1D,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,OAAO,EAAE,CAE9D;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CACvB,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,UAAU,EAAE,MAAM,EAClB,EAAE,EAAE,WAAW,GACd,MAAM,CAER;AAED;6EAC6E;AAC7E,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EAC/B,MAAM,EAAE,gBAAgB,EACxB,kBAAkB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,GACpC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAW3B;AAED;;;;;;;;GAQG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,EAAE,GAAG,SAAS,EAC5B,UAAU,EAAE,gBAAgB,EAC5B,EAAE,EAAE,WAAW,EACf,aAAa,CAAC,EAAE,WAAW,EAC3B,UAAU,UAAQ,EAClB,EAAE,SAAK,GACN,MAAM,CAYR;AAKD;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,EAAE,EAChB,QAAQ,EAAE,MAAM,EAAE,EAClB,SAAS,EAAE,WAAW,EACtB,EAAE,EAAE,WAAW,GACd,MAAM,CAeR"}
|
|
@@ -7,22 +7,52 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { Expression } from 'node-condition-builder';
|
|
9
9
|
import { camelcaseObject } from '../../naming.js';
|
|
10
|
-
import {
|
|
10
|
+
import { httpError } from '../../errors.js';
|
|
11
|
+
import { assertReadable, readableSelectColumns, readableFieldNames, explicitSelectColumns, hasOwnField, ownField, } from '../../read-access.js';
|
|
11
12
|
// ─── Schema field validation ────────────────────────────────
|
|
12
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Throw a 400 the client can place: `code` is the stable machine code and `path` the dot path
|
|
15
|
+
* of the offending value in the request ('' when the rejection is not attributable to one
|
|
16
|
+
* input). Both land in the response's `fields`, see `ValidationField`.
|
|
17
|
+
*/
|
|
18
|
+
export function err400(code, path, message) {
|
|
19
|
+
throw httpError(400, message, { code, path });
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Reject a request key retired in 1.0: a client still sending it gets a 400 naming the key
|
|
23
|
+
* instead of a response that silently ignores it.
|
|
24
|
+
*/
|
|
25
|
+
export function rejectRetiredKey(input, key, at, instead) {
|
|
26
|
+
if (input !== undefined && Object.hasOwn(input, key)) {
|
|
27
|
+
err400('retired_key', at, `'${key}' was removed in 1.0: ${instead}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Search parameters retired in 1.0, checked at every search entry point: `selectComputed` was
|
|
32
|
+
* folded into `select`, the one-field `computeMin/Max/Sum/Avg` into `compute`.
|
|
33
|
+
*/
|
|
34
|
+
export function rejectRetiredSearchKeys(params) {
|
|
35
|
+
rejectRetiredKey(params, 'selectComputed', 'selectComputed', `list computed fields in 'select', next to '*' for every readable field`);
|
|
36
|
+
for (const fn of ['Min', 'Max', 'Sum', 'Avg']) {
|
|
37
|
+
const key = `compute${fn}`;
|
|
38
|
+
rejectRetiredKey(params, key, key, `use 'compute': { ${fn.toLowerCase()}: [field] }`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** `at.key`, or '' when `at` is unknown: a child path is only as precise as its parent. */
|
|
42
|
+
export function subPath(at, key) {
|
|
43
|
+
return at ? `${at}.${key}` : '';
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The column of a schema field named by the request, or a 400 when the schema has no such
|
|
47
|
+
* field or `tableConf` hides it. `at` is the request path of the reference, for the 400.
|
|
48
|
+
*/
|
|
49
|
+
export function validateSchemaField(field, schema, tableConf, at = '') {
|
|
13
50
|
if (!hasOwnField(schema.fields, field)) {
|
|
14
|
-
|
|
15
|
-
err.statusCode = 400;
|
|
16
|
-
throw err;
|
|
51
|
+
err400('unknown_field', at, `Unknown field: ${field}`);
|
|
17
52
|
}
|
|
18
|
-
assertReadable(tableConf, field);
|
|
53
|
+
assertReadable(tableConf, field, at);
|
|
19
54
|
return schema.col(field);
|
|
20
55
|
}
|
|
21
|
-
export function err400(msg) {
|
|
22
|
-
const e = new Error(msg);
|
|
23
|
-
e.statusCode = 400;
|
|
24
|
-
throw e;
|
|
25
|
-
}
|
|
26
56
|
// ─── Computed fields resolution ─────────────────────────────
|
|
27
57
|
/**
|
|
28
58
|
* Build a ComputedFieldContext bound to a specific table/schema. `alias`
|
|
@@ -34,7 +64,8 @@ function buildComputedContext(db, schema, alias) {
|
|
|
34
64
|
db,
|
|
35
65
|
qiCol(field, opts) {
|
|
36
66
|
if (!hasOwnField(schema.fields, field)) {
|
|
37
|
-
|
|
67
|
+
// A table-configuration mistake surfacing at request time: not attributable to an input.
|
|
68
|
+
err400('unknown_field', '', `Unknown field referenced by computed expression: ${field}`);
|
|
38
69
|
}
|
|
39
70
|
const col = db.qi(schema.col(field));
|
|
40
71
|
// Default to the owning table: the statement may carry joins, and a bare
|
|
@@ -44,9 +75,9 @@ function buildComputedContext(db, schema, alias) {
|
|
|
44
75
|
},
|
|
45
76
|
};
|
|
46
77
|
}
|
|
47
|
-
export function resolveFieldRef(field, schema, tableConf, db, alias) {
|
|
78
|
+
export function resolveFieldRef(field, schema, tableConf, db, alias, at = '') {
|
|
48
79
|
if (hasOwnField(schema.fields, field)) {
|
|
49
|
-
assertReadable(tableConf, field);
|
|
80
|
+
assertReadable(tableConf, field, at);
|
|
50
81
|
const col = db.qi(schema.col(field));
|
|
51
82
|
// Qualified with the alias or the owning table — never bare, so the reference
|
|
52
83
|
// stays unambiguous when the statement carries joins.
|
|
@@ -58,7 +89,7 @@ export function resolveFieldRef(field, schema, tableConf, db, alias) {
|
|
|
58
89
|
const ctx = buildComputedContext(db, schema, alias);
|
|
59
90
|
return { expr: computedExpression(field, fn(ctx)), computed: true };
|
|
60
91
|
}
|
|
61
|
-
err400(`Unknown field: ${field}`);
|
|
92
|
+
err400('unknown_field', at, `Unknown field: ${field}`);
|
|
62
93
|
}
|
|
63
94
|
/**
|
|
64
95
|
* Evaluate a computed field into an Expression carrying its own bound values.
|
|
@@ -66,12 +97,12 @@ export function resolveFieldRef(field, schema, tableConf, db, alias) {
|
|
|
66
97
|
* Inside a WHERE clause the ConditionBuilder assigns the placeholder indexes, so bound
|
|
67
98
|
* values are always safe there. `allowBoundValues=false` is for the positions that sit
|
|
68
99
|
* *before* the WHERE values in the parameter order (SELECT projections, aggregations),
|
|
69
|
-
* where they cannot be placed correctly; those still reject with 400
|
|
100
|
+
* where they cannot be placed correctly; those still reject with 400, at request path `at`.
|
|
70
101
|
*/
|
|
71
|
-
export function evaluateComputedField(name, fn, schema, db, alias, message, allowBoundValues = false) {
|
|
102
|
+
export function evaluateComputedField(name, fn, schema, db, alias, message, allowBoundValues = false, at = '') {
|
|
72
103
|
const ev = fn(buildComputedContext(db, schema, alias));
|
|
73
104
|
if (!allowBoundValues && (ev.values?.length ?? 0) > 0) {
|
|
74
|
-
err400(message);
|
|
105
|
+
err400('bound_values_not_allowed', at, message);
|
|
75
106
|
}
|
|
76
107
|
return computedExpression(name, ev);
|
|
77
108
|
}
|
|
@@ -120,23 +151,58 @@ export function mapRowsToCamelCase(rows, schema, computedFieldNames) {
|
|
|
120
151
|
});
|
|
121
152
|
}
|
|
122
153
|
/**
|
|
123
|
-
* Build the SELECT columns list for a join fetch:
|
|
124
|
-
*
|
|
125
|
-
*
|
|
154
|
+
* Build the SELECT columns list for a join fetch: the quoted columns of the `select`ed fields,
|
|
155
|
+
* each validated (unknown or `readExclude`d → 400 at `<at>.<i>`). Without a `select`, every
|
|
156
|
+
* readable column of the join table.
|
|
126
157
|
*
|
|
127
|
-
* On a relation narrowed by a `fields` allowlist the
|
|
158
|
+
* On a relation narrowed by a `fields` allowlist the default is always spelled out. Emitting a
|
|
128
159
|
* real `SELECT *` there would fetch the excluded columns and leave them to be dropped by
|
|
129
160
|
* the response serializer — which does not run for a caller of `sqlApi.search()`.
|
|
130
161
|
*/
|
|
131
|
-
export function
|
|
132
|
-
if (
|
|
162
|
+
export function buildJoinSelectColumns(select, joinSchema, db, joinTableConf, restricted = false, at = '') {
|
|
163
|
+
if (select === undefined) {
|
|
133
164
|
if (restricted)
|
|
134
165
|
return explicitSelectColumns(joinTableConf, joinSchema, db);
|
|
135
166
|
return readableSelectColumns(joinTableConf, joinSchema, db);
|
|
136
167
|
}
|
|
168
|
+
if (!Array.isArray(select)) {
|
|
169
|
+
throw new TypeError(`${at || 'select'}: 'select' is an array of field names`);
|
|
170
|
+
}
|
|
137
171
|
const table = db.qi(joinSchema.tableName);
|
|
138
|
-
return
|
|
139
|
-
.
|
|
140
|
-
.map((c) => `${table}.${db.qi(validateSchemaField(c.trim(), joinSchema, joinTableConf))}`)
|
|
172
|
+
return select
|
|
173
|
+
.map((name, i) => `${table}.${db.qi(validateSchemaField(name, joinSchema, joinTableConf, subPath(at, i)))}`)
|
|
141
174
|
.join(', ');
|
|
142
175
|
}
|
|
176
|
+
/** In the main `select`, the default projection: every readable column. Not a field name. */
|
|
177
|
+
const SELECT_ALL = '*';
|
|
178
|
+
/**
|
|
179
|
+
* The main query's column list for a request `select`: the listed schema fields, validated one
|
|
180
|
+
* by one (unknown or `readExclude`d → 400 at `select.<i>`), then `required` ones the request did
|
|
181
|
+
* not list — the primary key, join correlation keys, DISTINCT's ORDER BY fields — when readable.
|
|
182
|
+
* Computed fields in `select` are skipped here: `executeMainQuery` projects them.
|
|
183
|
+
*
|
|
184
|
+
* {@link SELECT_ALL} in the list stands for the default projection — every readable column, as
|
|
185
|
+
* a search without `select` returns — so a client asks for a computed field without copying the
|
|
186
|
+
* readable set: `['*', 'fullName']`. The other names are still validated; a schema field next
|
|
187
|
+
* to it adds nothing. See ADR 0028.
|
|
188
|
+
*/
|
|
189
|
+
export function buildMainSelectColumns(select, required, tableConf, db) {
|
|
190
|
+
const schema = tableConf.schema;
|
|
191
|
+
const table = db.qi(schema.tableName);
|
|
192
|
+
const fields = [];
|
|
193
|
+
for (const [i, name] of select.entries()) {
|
|
194
|
+
if (name === SELECT_ALL || ownField(tableConf.computedFields, name))
|
|
195
|
+
continue;
|
|
196
|
+
validateSchemaField(name, schema, tableConf, `select.${i}`);
|
|
197
|
+
if (!fields.includes(name))
|
|
198
|
+
fields.push(name);
|
|
199
|
+
}
|
|
200
|
+
if (select.includes(SELECT_ALL))
|
|
201
|
+
return readableSelectColumns(tableConf, schema, db);
|
|
202
|
+
const readable = readableFieldNames(tableConf, schema);
|
|
203
|
+
for (const name of required) {
|
|
204
|
+
if (!fields.includes(name) && readable.includes(name))
|
|
205
|
+
fields.push(name);
|
|
206
|
+
}
|
|
207
|
+
return fields.map((f) => `${table}.${db.qi(schema.col(f))}`).join(', ');
|
|
208
|
+
}
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
import type { ApiRequest } from '../../../types/request.js';
|
|
10
10
|
import type { QueryClient } from '../../db.js';
|
|
11
11
|
import type { QueryParams } from '../query-params.js';
|
|
12
|
-
import type { DbTables,
|
|
12
|
+
import type { DbTables, TableConfig, JoinFetchRequest, JoinGroupRequest, JoinRefFilter, TenantContext, RowsByAlias } from '../../../types.js';
|
|
13
13
|
interface LeftJoinOnBuild {
|
|
14
14
|
joinClauses: string[];
|
|
15
15
|
values: unknown[];
|
|
@@ -31,14 +31,14 @@ interface LeftJoinFilterBuild {
|
|
|
31
31
|
* Emitted before the WHERE fragments because that is where it lands in the statement — MySQL
|
|
32
32
|
* binds `?` positionally.
|
|
33
33
|
*/
|
|
34
|
-
export declare function buildLeftJoinOnClauses(db: QueryClient, dbTables: DbTables, tableConf:
|
|
34
|
+
export declare function buildLeftJoinOnClauses(db: QueryClient, dbTables: DbTables, tableConf: TableConfig, aliasesNeedingJoin: Set<string>, startIdx: number, tenant?: TenantContext): LeftJoinOnBuild;
|
|
35
35
|
/** The WHERE fragments a `joinLeft` request's own filters and conditions contribute. */
|
|
36
|
-
export declare function buildLeftJoinFilters(db: QueryClient, dbTables: DbTables, tableConf:
|
|
36
|
+
export declare function buildLeftJoinFilters(db: QueryClient, dbTables: DbTables, tableConf: TableConfig, aliasesNeedingJoin: Set<string>, joinLeft: Record<string, JoinFetchRequest> | undefined, startIdx: number): LeftJoinFilterBuild;
|
|
37
37
|
/** joinMultiple: 1:N children, returned as rows under `result.joinMultiple.<alias>`. */
|
|
38
|
-
export declare function executeJoinMultiple(db: QueryClient, dbTables: DbTables, tableConf:
|
|
38
|
+
export declare function executeJoinMultiple(db: QueryClient, dbTables: DbTables, tableConf: TableConfig, mainResults: Record<string, unknown>[], joinMultiple: Record<string, JoinFetchRequest>, tenant?: TenantContext, request?: ApiRequest): Promise<RowsByAlias>;
|
|
39
39
|
/** joinLeft: N:1 parents, returned as rows under `result.joinLeft.<alias>`. */
|
|
40
|
-
export declare function executeJoinLeft(db: QueryClient, dbTables: DbTables, tableConf:
|
|
41
|
-
export declare function executeJoinGroup(db: QueryClient, dbTables: DbTables, tableConf:
|
|
42
|
-
export declare function buildJoinMustExistClauses(params: QueryParams, db: QueryClient, dbTables: DbTables, tableConf:
|
|
40
|
+
export declare function executeJoinLeft(db: QueryClient, dbTables: DbTables, tableConf: TableConfig, mainResults: Record<string, unknown>[], joinLeft: Record<string, JoinFetchRequest>, tenant?: TenantContext, request?: ApiRequest): Promise<RowsByAlias>;
|
|
41
|
+
export declare function executeJoinGroup(db: QueryClient, dbTables: DbTables, tableConf: TableConfig, mainResults: Record<string, unknown>[], joinGroup: Record<string, JoinGroupRequest>, tenant?: TenantContext): Promise<Record<string, Record<string, unknown>>>;
|
|
42
|
+
export declare function buildJoinMustExistClauses(params: QueryParams, db: QueryClient, dbTables: DbTables, tableConf: TableConfig, joinMustExist: Record<string, JoinRefFilter>, tenant?: TenantContext): string;
|
|
43
43
|
export {};
|
|
44
44
|
//# sourceMappingURL=join-families.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"join-families.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/join-families.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"join-families.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/join-families.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE5D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAsBtD,OAAO,KAAK,EACV,QAAQ,EAER,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,aAAa,EAGb,aAAa,EAEb,WAAW,EACZ,MAAM,mBAAmB,CAAC;AAI3B,UAAU,eAAe;IACvB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,MAAM,EAAE,OAAO,EAAE,CAAC;CACnB;AAED,UAAU,mBAAmB;IAC3B,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,MAAM,EAAE,OAAO,EAAE,CAAC;CACnB;AAwED;;;;;;;;;;;;GAYG;AACH,wBAAgB,sBAAsB,CACpC,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,kBAAkB,EAAE,GAAG,CAAC,MAAM,CAAC,EAC/B,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,aAAa,GACrB,eAAe,CAgCjB;AAED,wFAAwF;AACxF,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,kBAAkB,EAAE,GAAG,CAAC,MAAM,CAAC,EAC/B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,SAAS,EACtD,QAAQ,EAAE,MAAM,GACf,mBAAmB,CA2CrB;AA4GD,wFAAwF;AACxF,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EACtC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAC9C,MAAM,CAAC,EAAE,aAAa,EACtB,OAAO,CAAC,EAAE,UAAU,GACnB,OAAO,CAAC,WAAW,CAAC,CAMtB;AAED,+EAA+E;AAC/E,wBAAgB,eAAe,CAC7B,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EACtC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAC1C,MAAM,CAAC,EAAE,aAAa,EACtB,OAAO,CAAC,EAAE,UAAU,GACnB,OAAO,CAAC,WAAW,CAAC,CAMtB;AAgHD,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EACtC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAC3C,MAAM,CAAC,EAAE,aAAa,GACrB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAsClD;AAyBD,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,WAAW,EACnB,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,EAC5C,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CA6BR"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { ConditionBuilder, Expression } from 'node-condition-builder';
|
|
2
2
|
import { assertReadable, assertFiltersReadable, hasOwnField, ownField } from '../../read-access.js';
|
|
3
3
|
import { ALLOWED_SET } from '../../condition-methods.js';
|
|
4
|
-
import { err400, validateSchemaField, evaluateComputedField, mapRowsToCamelCase,
|
|
4
|
+
import { err400, validateSchemaField, evaluateComputedField, mapRowsToCamelCase, buildJoinSelectColumns, rejectRetiredKey, } from './fields.js';
|
|
5
5
|
import { runAfterRead } from '../read-hooks.js';
|
|
6
6
|
import { appendJoinTenantScope, subqueryAlias, requireJoin, extractJoinRefs, } from './joins.js';
|
|
7
7
|
import { tenantForTable, buildTenantRowGuard } from '../../tenant.js';
|
|
8
|
+
import { resolveJoinTableConf } from '../../table-helpers.js';
|
|
8
9
|
import { dispatchConditionMethod, buildJoinRefCondition } from './conditions.js';
|
|
9
10
|
import { AGG_FN, aggExpr } from './aggregations.js';
|
|
10
11
|
/**
|
|
@@ -39,20 +40,21 @@ function applyJoinLeftFilters(cb, filters, scope) {
|
|
|
39
40
|
}
|
|
40
41
|
}
|
|
41
42
|
/** `joinLeft.conditions` — operator methods. An unknown field is a 400, not a no-op. */
|
|
42
|
-
function applyJoinLeftConditions(cb, conditions, scope
|
|
43
|
-
for (const c of conditions) {
|
|
43
|
+
function applyJoinLeftConditions(cb, conditions, scope) {
|
|
44
|
+
for (const [i, c] of conditions.entries()) {
|
|
45
|
+
const here = `joinLeft.${scope.alias}.conditions.${i}`;
|
|
44
46
|
if (!ALLOWED_SET.has(c.method)) {
|
|
45
|
-
err400(`Invalid condition method: ${c.method}`);
|
|
47
|
+
err400('invalid_method', `${here}.method`, `Invalid condition method: ${c.method}`);
|
|
46
48
|
}
|
|
47
49
|
if (hasOwnField(scope.joinSchema.fields, c.field)) {
|
|
48
|
-
assertReadable(
|
|
50
|
+
assertReadable(scope.joinTableConf, c.field, `${here}.field`);
|
|
49
51
|
}
|
|
50
52
|
else if (!ownField(scope.computed, c.field)) {
|
|
51
|
-
err400(`Unknown field: ${c.field}`);
|
|
53
|
+
err400('unknown_field', `${here}.field`, `Unknown field: ${c.field}`);
|
|
52
54
|
}
|
|
53
55
|
const ref = resolveJoinLeftField(c.field, scope);
|
|
54
56
|
if (ref !== null)
|
|
55
|
-
dispatchConditionMethod(cb, c.method, ref, c.params ?? []);
|
|
57
|
+
dispatchConditionMethod(cb, c.method, ref, c.params ?? [], here);
|
|
56
58
|
}
|
|
57
59
|
}
|
|
58
60
|
/**
|
|
@@ -73,12 +75,12 @@ export function buildLeftJoinOnClauses(db, dbTables, tableConf, aliasesNeedingJo
|
|
|
73
75
|
const values = [];
|
|
74
76
|
let currentIdx = startIdx;
|
|
75
77
|
for (const alias of aliasesNeedingJoin) {
|
|
76
|
-
const joinDef = requireJoin(tableConf, alias, true);
|
|
78
|
+
const joinDef = requireJoin(tableConf, alias, true, `joinLeft.${alias}`);
|
|
77
79
|
const refs = extractJoinRefs(db, tableConf, joinDef);
|
|
78
80
|
const aliasIdent = db.qi(alias);
|
|
79
81
|
// The guard references the join through its ALIAS: one table may be joined under several
|
|
80
82
|
// aliases, and each predicate must bind to the row this clause produced.
|
|
81
|
-
const guard = buildTenantRowGuard(db, tenantForTable(tenant, dbTables
|
|
83
|
+
const guard = buildTenantRowGuard(db, tenantForTable(tenant, resolveJoinTableConf(dbTables, joinDef)), alias);
|
|
82
84
|
let scoped = '';
|
|
83
85
|
if (guard) {
|
|
84
86
|
scoped = ` AND ${guard.build(currentIdx, db.ph)}`;
|
|
@@ -96,7 +98,7 @@ export function buildLeftJoinFilters(db, dbTables, tableConf, aliasesNeedingJoin
|
|
|
96
98
|
const values = [];
|
|
97
99
|
let currentIdx = startIdx;
|
|
98
100
|
for (const alias of aliasesNeedingJoin) {
|
|
99
|
-
const joinDef = requireJoin(tableConf, alias, true);
|
|
101
|
+
const joinDef = requireJoin(tableConf, alias, true, `joinLeft.${alias}`);
|
|
100
102
|
const { joinSchema } = joinDef;
|
|
101
103
|
const aliasIdent = db.qi(alias);
|
|
102
104
|
const ref = joinLeft?.[alias];
|
|
@@ -107,20 +109,21 @@ export function buildLeftJoinFilters(db, dbTables, tableConf, aliasesNeedingJoin
|
|
|
107
109
|
// `assertJoinFilterKeys` rejects them up front rather than letting them through as a
|
|
108
110
|
// silent no-op, and the generated body schema does not advertise them for unique:true
|
|
109
111
|
// relations.
|
|
110
|
-
const joinTableConf = dbTables
|
|
112
|
+
const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
|
|
111
113
|
const scope = {
|
|
112
114
|
db,
|
|
113
115
|
alias,
|
|
114
116
|
aliasIdent,
|
|
115
117
|
joinSchema,
|
|
118
|
+
joinTableConf,
|
|
116
119
|
computed: joinTableConf?.computedFields,
|
|
117
120
|
};
|
|
118
121
|
const cb = new ConditionBuilder('AND', db.cbDialect);
|
|
119
|
-
assertFiltersReadable(ref.filters, joinTableConf);
|
|
122
|
+
assertFiltersReadable(ref.filters, joinTableConf, `joinLeft.${alias}.filters`);
|
|
120
123
|
if (ref.filters)
|
|
121
124
|
applyJoinLeftFilters(cb, ref.filters, scope);
|
|
122
125
|
if (ref.conditions?.length)
|
|
123
|
-
applyJoinLeftConditions(cb, ref.conditions, scope
|
|
126
|
+
applyJoinLeftConditions(cb, ref.conditions, scope);
|
|
124
127
|
const sql = cb.build(currentIdx, db.ph);
|
|
125
128
|
const vals = cb.getValues();
|
|
126
129
|
if (sql) {
|
|
@@ -148,14 +151,15 @@ function scopeJoinSideQuery(cb, db, joinSchema, joinField, ids, joinTableConf, t
|
|
|
148
151
|
async function fetchJoinRows(db, dbTables, tableConf, mainResults, requests, mode, tenant, request) {
|
|
149
152
|
const result = {};
|
|
150
153
|
for (const [alias, ref] of Object.entries(requests)) {
|
|
151
|
-
const
|
|
152
|
-
const
|
|
153
|
-
const
|
|
154
|
-
|
|
154
|
+
const at = `${mode.source}.${alias}`;
|
|
155
|
+
const joinDef = requireJoin(tableConf, alias, mode.requireUnique, at);
|
|
156
|
+
const { joinSchema, joinField, mainField } = joinDef;
|
|
157
|
+
const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
|
|
158
|
+
// The projection is resolved before the empty-result bail-out: it is validated against
|
|
155
159
|
// the join schema, and that rejection must not depend on whether the main query
|
|
156
160
|
// matched rows.
|
|
157
|
-
|
|
158
|
-
const columns =
|
|
161
|
+
rejectRetiredKey(ref, 'selection', `${at}.selection`, `use 'select', an array of field names`);
|
|
162
|
+
const columns = buildJoinSelectColumns(ref?.select ?? joinDef.select, joinSchema, db, joinTableConf, joinDef.fields !== undefined, `${at}.select`);
|
|
159
163
|
// For joinLeft, mainField on the main table is the FK pointing at joinField (the
|
|
160
164
|
// parent's PK), so the same collect-then-look-up works for both directions.
|
|
161
165
|
const ids = collectIds(mainResults, mainField);
|
|
@@ -164,7 +168,7 @@ async function fetchJoinRows(db, dbTables, tableConf, mainResults, requests, mod
|
|
|
164
168
|
continue;
|
|
165
169
|
}
|
|
166
170
|
const cb = mode.applyRefCondition
|
|
167
|
-
? buildJoinRefCondition(joinTableConf, joinSchema, ref || {}, db)
|
|
171
|
+
? buildJoinRefCondition(joinTableConf, joinSchema, ref || {}, db, undefined, at)
|
|
168
172
|
: new ConditionBuilder('AND', db.cbDialect);
|
|
169
173
|
const { where, values, tenantJoins } = scopeJoinSideQuery(cb, db, joinSchema, joinField, ids, joinTableConf, tenant);
|
|
170
174
|
const rows = await db.select({
|
|
@@ -204,21 +208,21 @@ export function executeJoinLeft(db, dbTables, tableConf, mainResults, joinLeft,
|
|
|
204
208
|
* values supported in this position; reject with 400 if the computed
|
|
205
209
|
* returns values)
|
|
206
210
|
*/
|
|
207
|
-
function buildByExpression(by, joinSchema, joinTableConf, db) {
|
|
211
|
+
function buildByExpression(by, joinSchema, joinTableConf, db, at) {
|
|
208
212
|
if (typeof by !== 'string') {
|
|
209
|
-
err400(`Invalid 'by' specification: expected a field or computed name`);
|
|
213
|
+
err400('invalid_aggregation', at, `Invalid 'by' specification: expected a field or computed name`);
|
|
210
214
|
}
|
|
211
215
|
if (hasOwnField(joinSchema.fields, by)) {
|
|
212
216
|
// validateSchemaField also enforces readExclude: GROUP BY on a hidden field
|
|
213
217
|
// would return its distinct values verbatim in `rows[].by`.
|
|
214
|
-
const col = validateSchemaField(by, joinSchema, joinTableConf);
|
|
218
|
+
const col = validateSchemaField(by, joinSchema, joinTableConf, at);
|
|
215
219
|
return `${db.qi(joinSchema.tableName)}.${db.qi(col)}`;
|
|
216
220
|
}
|
|
217
221
|
const fn = ownField(joinTableConf?.computedFields, by);
|
|
218
222
|
if (fn) {
|
|
219
|
-
return evaluateComputedField(by, fn, joinSchema, db, undefined, `Computed field '${by}' with bound values cannot be used in
|
|
223
|
+
return evaluateComputedField(by, fn, joinSchema, db, undefined, `Computed field '${by}' with bound values cannot be used in joinGroup by`, false, at).value;
|
|
220
224
|
}
|
|
221
|
-
err400(`Unknown field: ${by}`);
|
|
225
|
+
err400('unknown_field', at, `Unknown field: ${by}`);
|
|
222
226
|
}
|
|
223
227
|
// ─── joinGroup (aggregations) ───────────────────────────────
|
|
224
228
|
/**
|
|
@@ -227,77 +231,81 @@ function buildByExpression(by, joinSchema, joinTableConf, db) {
|
|
|
227
231
|
* Every field is validated against the join schema here, so an unknown or unreachable one
|
|
228
232
|
* is a 400 regardless of what the data happens to contain.
|
|
229
233
|
*/
|
|
230
|
-
|
|
234
|
+
const AGG_KINDS = ['distinctCount', 'min', 'max', 'sum', 'avg', 'count'];
|
|
235
|
+
/**
|
|
236
|
+
* SELECT and GROUP BY fragments for one joinGroup alias, plus the column alias → response
|
|
237
|
+
* position map the rows are shaped with.
|
|
238
|
+
*
|
|
239
|
+
* Refuses a request with no aggregate function (a GROUP BY alone computes nothing), and the
|
|
240
|
+
* pre-1.0 `aggregations` wrapper, which a JavaScript caller can still send: ignoring it would
|
|
241
|
+
* answer an empty result instead of saying why.
|
|
242
|
+
*/
|
|
243
|
+
function buildJoinGroupSelect(groupReq, joinSchema, joinTableConf, db, at) {
|
|
244
|
+
if ('aggregations' in groupReq) {
|
|
245
|
+
err400('invalid_aggregation', `${at}.aggregations`, `joinGroup '${at}': 'by' and the aggregate functions go directly in the joinGroup entry, not under 'aggregations'`);
|
|
246
|
+
}
|
|
247
|
+
if (!AGG_KINDS.some((kind) => (groupReq[kind]?.length ?? 0) > 0)) {
|
|
248
|
+
err400('invalid_aggregation', at, `joinGroup '${at}' computes nothing: name at least one of ${AGG_KINDS.join(', ')}`);
|
|
249
|
+
}
|
|
231
250
|
const selectParts = [];
|
|
232
251
|
const groupByParts = [];
|
|
233
|
-
|
|
234
|
-
|
|
252
|
+
// Column alias → [function, field]: the response is shaped from this map, never by
|
|
253
|
+
// splitting the alias, so a field name holding `_` survives the round trip.
|
|
254
|
+
const columns = new Map();
|
|
255
|
+
if (groupReq.by) {
|
|
256
|
+
const byExpr = buildByExpression(groupReq.by, joinSchema, joinTableConf, db, `${at}.by`);
|
|
235
257
|
selectParts.push(`${byExpr} as "by"`);
|
|
236
258
|
groupByParts.push(byExpr);
|
|
237
259
|
}
|
|
238
|
-
const
|
|
239
|
-
if (!fields)
|
|
240
|
-
return;
|
|
260
|
+
for (const kind of AGG_KINDS) {
|
|
241
261
|
const fn = AGG_FN[kind];
|
|
242
|
-
for (const f of
|
|
243
|
-
const col = validateSchemaField(f, joinSchema, joinTableConf);
|
|
262
|
+
for (const [i, f] of (groupReq[kind] ?? []).entries()) {
|
|
263
|
+
const col = validateSchemaField(f, joinSchema, joinTableConf, `${at}.${kind}.${i}`);
|
|
244
264
|
const colRef = `${db.qi(joinSchema.tableName)}.${db.qi(col)}`;
|
|
245
|
-
|
|
265
|
+
const colAlias = `${kind}_${f}`;
|
|
266
|
+
columns.set(colAlias, [kind, f]);
|
|
267
|
+
selectParts.push(`${aggExpr(fn, colRef)} as "${colAlias}"`);
|
|
246
268
|
}
|
|
247
|
-
};
|
|
248
|
-
addAgg('distinctCount', aggregations.distinctCount);
|
|
249
|
-
addAgg('min', aggregations.min);
|
|
250
|
-
addAgg('max', aggregations.max);
|
|
251
|
-
addAgg('sum', aggregations.sum);
|
|
252
|
-
addAgg('avg', aggregations.avg);
|
|
253
|
-
addAgg('count', aggregations.count);
|
|
254
|
-
return { selectParts, groupByParts };
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Shape aggregation rows into the response: a single row without `by` collapses to
|
|
258
|
-
* `{ fn: { field: value } }`; anything else stays a list under `rows`.
|
|
259
|
-
*/
|
|
260
|
-
function formatJoinGroupRows(rows, hasBy) {
|
|
261
|
-
const formatted = {};
|
|
262
|
-
if (rows.length === 0)
|
|
263
|
-
return formatted;
|
|
264
|
-
const row = rows.length === 1 && !hasBy ? rows[0] : rows;
|
|
265
|
-
if (Array.isArray(row)) {
|
|
266
|
-
formatted.rows = row;
|
|
267
|
-
return formatted;
|
|
268
|
-
}
|
|
269
|
-
for (const [key, value] of Object.entries(row)) {
|
|
270
|
-
if (key === 'by')
|
|
271
|
-
continue;
|
|
272
|
-
const [fn, field] = key.split('_');
|
|
273
|
-
if (!formatted[fn])
|
|
274
|
-
formatted[fn] = {};
|
|
275
|
-
formatted[fn][field] = value;
|
|
276
269
|
}
|
|
277
|
-
return
|
|
270
|
+
return { selectParts, groupByParts, columns };
|
|
271
|
+
}
|
|
272
|
+
/** Shape aggregation rows into the response: `{ by?, <fn>: { <field>: value } }` per row. */
|
|
273
|
+
function formatJoinGroupRows(rows, columns) {
|
|
274
|
+
return rows.map((row) => {
|
|
275
|
+
const out = {};
|
|
276
|
+
if ('by' in row)
|
|
277
|
+
out.by = row.by;
|
|
278
|
+
for (const [colAlias, [kind, field]] of columns) {
|
|
279
|
+
if (!out[kind])
|
|
280
|
+
out[kind] = {};
|
|
281
|
+
out[kind][field] = row[colAlias];
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
});
|
|
278
285
|
}
|
|
279
286
|
export async function executeJoinGroup(db, dbTables, tableConf, mainResults, joinGroup, tenant) {
|
|
280
287
|
const result = {};
|
|
281
288
|
for (const [alias, groupReq] of Object.entries(joinGroup)) {
|
|
282
|
-
const
|
|
289
|
+
const at = `joinGroup.${alias}`;
|
|
290
|
+
const joinDef = requireJoin(tableConf, alias, false, at);
|
|
283
291
|
const { joinSchema, joinField, mainField } = joinDef;
|
|
284
|
-
const joinTableConf = dbTables
|
|
292
|
+
const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
|
|
285
293
|
const ids = collectIds(mainResults, mainField);
|
|
286
|
-
const {
|
|
287
|
-
const { selectParts, groupByParts } = buildJoinGroupSelect(
|
|
294
|
+
const { filters: groupFilters, conditions: groupConditions } = groupReq;
|
|
295
|
+
const { selectParts, groupByParts, columns } = buildJoinGroupSelect(groupReq, joinSchema, joinTableConf, db, at);
|
|
288
296
|
// Bail out only here: `by` and every aggregation field have now been validated.
|
|
289
|
-
if (
|
|
290
|
-
result[alias] = {};
|
|
297
|
+
if (ids.length === 0) {
|
|
298
|
+
result[alias] = { rows: [] };
|
|
291
299
|
continue;
|
|
292
300
|
}
|
|
293
301
|
const groupRef = { filters: groupFilters, conditions: groupConditions };
|
|
294
|
-
const cb = buildJoinRefCondition(joinTableConf, joinSchema, groupRef, db);
|
|
302
|
+
const cb = buildJoinRefCondition(joinTableConf, joinSchema, groupRef, db, undefined, at);
|
|
295
303
|
const { where, values, tenantJoins } = scopeJoinSideQuery(cb, db, joinSchema, joinField, ids, joinTableConf, tenant);
|
|
296
304
|
const groupBy = groupByParts.length > 0 ? `GROUP BY ${groupByParts.join(', ')}` : '';
|
|
297
305
|
const fromJoins = tenantJoins.length > 0 ? ` ${tenantJoins.join(' ')}` : '';
|
|
298
306
|
const sql = `SELECT ${selectParts.join(', ')} FROM ${db.qi(joinSchema.tableName)}${fromJoins} WHERE ${where} ${groupBy}`;
|
|
299
307
|
const queryResult = await db.query(sql, values);
|
|
300
|
-
result[alias] = formatJoinGroupRows(queryResult.rows,
|
|
308
|
+
result[alias] = { rows: formatJoinGroupRows(queryResult.rows, columns) };
|
|
301
309
|
}
|
|
302
310
|
return result;
|
|
303
311
|
}
|
|
@@ -321,15 +329,16 @@ function collectIds(mainResults, mainField) {
|
|
|
321
329
|
export function buildJoinMustExistClauses(params, db, dbTables, tableConf, joinMustExist, tenant) {
|
|
322
330
|
let where = '';
|
|
323
331
|
for (const [alias, ref] of Object.entries(joinMustExist)) {
|
|
324
|
-
const
|
|
332
|
+
const at = `joinMustExist.${alias}`;
|
|
333
|
+
const joinDef = requireJoin(tableConf, alias, false, at);
|
|
325
334
|
const { joinSchema } = joinDef;
|
|
326
|
-
const joinTableConf = dbTables
|
|
335
|
+
const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
|
|
327
336
|
const refs = extractJoinRefs(db, tableConf, joinDef);
|
|
328
337
|
// The EXISTS FROM is aliased so the correlation to the outer table survives a
|
|
329
338
|
// self-referencing relation; everything inside references the alias.
|
|
330
339
|
const subAlias = subqueryAlias(alias, tableConf);
|
|
331
340
|
const subRef = db.qi(subAlias);
|
|
332
|
-
const filterCondition = buildJoinRefCondition(joinTableConf, joinSchema, ref, db, subAlias);
|
|
341
|
+
const filterCondition = buildJoinRefCondition(joinTableConf, joinSchema, ref, db, subAlias, at);
|
|
333
342
|
const tenantJoins = [];
|
|
334
343
|
appendJoinTenantScope(db, joinTableConf, tenant, subAlias, filterCondition, tenantJoins);
|
|
335
344
|
const filterWhere = params.emitCondition(filterCondition, db);
|