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,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { ConditionBuilder } from 'node-condition-builder';
|
|
9
9
|
import type { QueryClient } from '../../db.js';
|
|
10
|
-
import type { DbTables, FilterRecord,
|
|
10
|
+
import type { DbTables, FilterRecord, TableConfig, JoinDefinition, TenantContext } from '../../../types.js';
|
|
11
11
|
/**
|
|
12
12
|
* Tenant-scope a join side-query. When the joined table declares its own `tenantScope`,
|
|
13
13
|
* appends the tenant condition to `cb` (direct: `col IN ids`; indirect: condition on the
|
|
@@ -17,14 +17,14 @@ import type { DbTables, FilterRecord, ITable, JoinDefinition, TenantContext } fr
|
|
|
17
17
|
* `joinTableRef` is the raw name the join table goes by in the statement: its table name
|
|
18
18
|
* in plain side-queries, or the subquery alias inside an aliased, correlated EXISTS.
|
|
19
19
|
*/
|
|
20
|
-
export declare function appendJoinTenantScope(db: QueryClient, joinTableConf:
|
|
20
|
+
export declare function appendJoinTenantScope(db: QueryClient, joinTableConf: TableConfig | undefined, tenant: TenantContext | undefined, joinTableRef: string, cb: ConditionBuilder, joins?: string[]): void;
|
|
21
21
|
/**
|
|
22
22
|
* Alias for the FROM of a correlated subquery (EXISTS, aggregate). The subquery must not
|
|
23
23
|
* say `FROM <table>` bare: on a self-referencing relation the inner table would shadow the
|
|
24
24
|
* outer one and the correlation would silently compare each row with itself. The request
|
|
25
25
|
* alias is used, suffixed when it would itself collide with the outer table's name.
|
|
26
26
|
*/
|
|
27
|
-
export declare function subqueryAlias(alias: string, tableConf:
|
|
27
|
+
export declare function subqueryAlias(alias: string, tableConf: TableConfig): string;
|
|
28
28
|
/**
|
|
29
29
|
* Validate the filter keys of every join reference in a request map.
|
|
30
30
|
*
|
|
@@ -33,11 +33,19 @@ export declare function subqueryAlias(alias: string, tableConf: ITable): string;
|
|
|
33
33
|
* same request answer 400 or 200 depending on the data it happens to match.
|
|
34
34
|
*
|
|
35
35
|
* Unknown aliases are left to `requireJoin`, which reports them with its own message.
|
|
36
|
+
*
|
|
37
|
+
* `family` is the request key the map came from (`joinMultiple`, …): a rejected filter is
|
|
38
|
+
* reported at `<family>.<alias>.filters.<key>`.
|
|
36
39
|
*/
|
|
37
|
-
export declare function assertJoinFilterKeys(dbTables: DbTables, tableConf:
|
|
40
|
+
export declare function assertJoinFilterKeys(dbTables: DbTables, tableConf: TableConfig, refs: Record<string, {
|
|
38
41
|
filters?: FilterRecord;
|
|
39
|
-
}> | undefined, allowExtraFilters: boolean): void;
|
|
40
|
-
|
|
42
|
+
}> | undefined, allowExtraFilters: boolean, family: string): void;
|
|
43
|
+
/**
|
|
44
|
+
* The relation a request names by alias, or a 400 when the host declares no such alias or
|
|
45
|
+
* declares it for the other join direction. `at` is the request path naming the alias
|
|
46
|
+
* (`joinLeft.<alias>`, `orderBy`), '' when unknown.
|
|
47
|
+
*/
|
|
48
|
+
export declare function requireJoin(tableConf: TableConfig, alias: string, requireUnique: boolean, at?: string): JoinDefinition;
|
|
41
49
|
export interface JoinRefs {
|
|
42
50
|
mainColName: string;
|
|
43
51
|
/** db.qi'd column reference on main side (FK or PK) */
|
|
@@ -51,5 +59,5 @@ export interface JoinRefs {
|
|
|
51
59
|
}
|
|
52
60
|
/** Extract quoted identifiers for a join reference. Used by joinMustExist, joinLeft and joinGroup
|
|
53
61
|
* SQL builders to avoid the 4-line FK/PK destructuring boilerplate at every call site. */
|
|
54
|
-
export declare function extractJoinRefs(db: QueryClient, tableConf:
|
|
62
|
+
export declare function extractJoinRefs(db: QueryClient, tableConf: TableConfig, joinDef: JoinDefinition): JoinRefs;
|
|
55
63
|
//# sourceMappingURL=joins.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"joins.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/joins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"joins.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/joins.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAK/C,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,cAAc,EACd,aAAa,EACd,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,WAAW,EACf,aAAa,EAAE,WAAW,GAAG,SAAS,EACtC,MAAM,EAAE,aAAa,GAAG,SAAS,EACjC,YAAY,EAAE,MAAM,EACpB,EAAE,EAAE,gBAAgB,EACpB,KAAK,CAAC,EAAE,MAAM,EAAE,GACf,IAAI,CAON;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,GAAG,MAAM,CAE3E;AAMD;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,WAAW,EACtB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE;IAAE,OAAO,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC,GAAG,SAAS,EAC5D,iBAAiB,EAAE,OAAO,EAC1B,MAAM,EAAE,MAAM,GACb,IAAI,CAWN;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,SAAS,EAAE,WAAW,EACtB,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,OAAO,EACtB,EAAE,SAAK,GACN,cAAc,CAYhB;AAED,MAAM,WAAW,QAAQ;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,uDAAuD;IACvD,OAAO,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;CACf;AAED;0FAC0F;AAC1F,wBAAgB,eAAe,CAC7B,EAAE,EAAE,WAAW,EACf,SAAS,EAAE,WAAW,EACtB,OAAO,EAAE,cAAc,GACtB,QAAQ,CAUV"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { buildTenantCondition, buildTenantJoin } from '../../tenant.js';
|
|
2
2
|
import { assertFiltersReadable, assertKnownFilterKeys } from '../../read-access.js';
|
|
3
|
+
import { resolveJoinTableConf, resolvedTenantScope } from '../../table-helpers.js';
|
|
3
4
|
import { err400 } from './fields.js';
|
|
4
5
|
/**
|
|
5
6
|
* Tenant-scope a join side-query. When the joined table declares its own `tenantScope`,
|
|
@@ -11,7 +12,7 @@ import { err400 } from './fields.js';
|
|
|
11
12
|
* in plain side-queries, or the subquery alias inside an aliased, correlated EXISTS.
|
|
12
13
|
*/
|
|
13
14
|
export function appendJoinTenantScope(db, joinTableConf, tenant, joinTableRef, cb, joins) {
|
|
14
|
-
const scope = joinTableConf
|
|
15
|
+
const scope = resolvedTenantScope(joinTableConf);
|
|
15
16
|
if (!tenant || !scope)
|
|
16
17
|
return;
|
|
17
18
|
cb.append(buildTenantCondition(db, scope, tenant.ids, joinTableRef));
|
|
@@ -26,10 +27,10 @@ export function appendJoinTenantScope(db, joinTableConf, tenant, joinTableRef, c
|
|
|
26
27
|
* alias is used, suffixed when it would itself collide with the outer table's name.
|
|
27
28
|
*/
|
|
28
29
|
export function subqueryAlias(alias, tableConf) {
|
|
29
|
-
return alias === tableConf.
|
|
30
|
+
return alias === tableConf.schema.tableName ? `${alias}_sub` : alias;
|
|
30
31
|
}
|
|
31
32
|
function findJoinByAlias(tableConf, alias) {
|
|
32
|
-
return tableConf.
|
|
33
|
+
return tableConf.readJoins?.find((j) => j.alias === alias);
|
|
33
34
|
}
|
|
34
35
|
/**
|
|
35
36
|
* Validate the filter keys of every join reference in a request map.
|
|
@@ -39,30 +40,39 @@ function findJoinByAlias(tableConf, alias) {
|
|
|
39
40
|
* same request answer 400 or 200 depending on the data it happens to match.
|
|
40
41
|
*
|
|
41
42
|
* Unknown aliases are left to `requireJoin`, which reports them with its own message.
|
|
43
|
+
*
|
|
44
|
+
* `family` is the request key the map came from (`joinMultiple`, …): a rejected filter is
|
|
45
|
+
* reported at `<family>.<alias>.filters.<key>`.
|
|
42
46
|
*/
|
|
43
|
-
export function assertJoinFilterKeys(dbTables, tableConf, refs, allowExtraFilters) {
|
|
47
|
+
export function assertJoinFilterKeys(dbTables, tableConf, refs, allowExtraFilters, family) {
|
|
44
48
|
if (!refs)
|
|
45
49
|
return;
|
|
46
50
|
for (const [alias, ref] of Object.entries(refs)) {
|
|
47
51
|
const joinDef = findJoinByAlias(tableConf, alias);
|
|
48
52
|
if (!joinDef)
|
|
49
53
|
continue;
|
|
50
|
-
const joinTableConf = dbTables
|
|
54
|
+
const joinTableConf = resolveJoinTableConf(dbTables, joinDef);
|
|
51
55
|
const filters = ref?.filters;
|
|
52
|
-
|
|
53
|
-
|
|
56
|
+
const at = `${family}.${alias}.filters`;
|
|
57
|
+
assertFiltersReadable(filters, joinTableConf, at);
|
|
58
|
+
assertKnownFilterKeys(filters, joinDef.joinSchema, joinTableConf, allowExtraFilters, at);
|
|
54
59
|
}
|
|
55
60
|
}
|
|
56
|
-
|
|
61
|
+
/**
|
|
62
|
+
* The relation a request names by alias, or a 400 when the host declares no such alias or
|
|
63
|
+
* declares it for the other join direction. `at` is the request path naming the alias
|
|
64
|
+
* (`joinLeft.<alias>`, `orderBy`), '' when unknown.
|
|
65
|
+
*/
|
|
66
|
+
export function requireJoin(tableConf, alias, requireUnique, at = '') {
|
|
57
67
|
const joinDef = findJoinByAlias(tableConf, alias);
|
|
58
68
|
if (!joinDef) {
|
|
59
|
-
err400(`Unknown join alias: ${alias}`);
|
|
69
|
+
err400('unknown_alias', at, `Unknown join alias: ${alias}`);
|
|
60
70
|
}
|
|
61
71
|
if (requireUnique && !joinDef.unique) {
|
|
62
|
-
err400(`Join alias '${alias}' is not declared with unique:true; use joinMultiple/joinMustExist/joinGroup instead`);
|
|
72
|
+
err400('wrong_join_family', at, `Join alias '${alias}' is not declared with unique:true; use joinMultiple/joinMustExist/joinGroup instead`);
|
|
63
73
|
}
|
|
64
74
|
if (!requireUnique && joinDef.unique) {
|
|
65
|
-
err400(`Join alias '${alias}' is declared with unique:true; use joinLeft instead`);
|
|
75
|
+
err400('wrong_join_family', at, `Join alias '${alias}' is declared with unique:true; use joinLeft instead`);
|
|
66
76
|
}
|
|
67
77
|
return joinDef;
|
|
68
78
|
}
|
|
@@ -73,8 +83,8 @@ export function extractJoinRefs(db, tableConf, joinDef) {
|
|
|
73
83
|
const mainColName = Array.isArray(mainField) ? mainField[0] : mainField;
|
|
74
84
|
return {
|
|
75
85
|
mainColName,
|
|
76
|
-
mainCol: db.qi(tableConf.
|
|
77
|
-
mainTable: db.qi(tableConf.
|
|
86
|
+
mainCol: db.qi(tableConf.schema.col(mainColName)),
|
|
87
|
+
mainTable: db.qi(tableConf.schema.tableName),
|
|
78
88
|
joinTable: db.qi(joinSchema.tableName),
|
|
79
89
|
fkCol: db.qi(joinSchema.col(joinField)),
|
|
80
90
|
};
|
|
@@ -4,11 +4,11 @@
|
|
|
4
4
|
* 2-part `alias.field` a joinLeft parent field, via a real LEFT JOIN
|
|
5
5
|
* 3-part `alias.fn.field` a joinGroup aggregation, via a correlated subquery
|
|
6
6
|
*
|
|
7
|
-
* The request `orderBy` is validated
|
|
8
|
-
*
|
|
7
|
+
* The request `orderBy` is validated here per request; `defaultOrder` from the table config has
|
|
8
|
+
* the 1-part grammar only, checked by `defineTable` — see `convertConfiguredOrder`.
|
|
9
9
|
*/
|
|
10
10
|
import type { QueryClient } from '../../db.js';
|
|
11
|
-
import type { DbTables,
|
|
11
|
+
import type { DbTables, TableConfig, JoinGroupRequest, TenantContext } from '../../../types.js';
|
|
12
12
|
export interface OrderByResult {
|
|
13
13
|
sql: string;
|
|
14
14
|
values: unknown[];
|
|
@@ -19,17 +19,16 @@ export interface OrderByResult {
|
|
|
19
19
|
* Pre-scan `orderBy` for the joinLeft aliases referenced in 2-part notation (`<alias>.<field>`).
|
|
20
20
|
* Needed BEFORE building the LEFT JOIN clauses (which must know their aliases) while the actual
|
|
21
21
|
* orderBy SQL — with its parameter placeholders — is only baked later, once the LEFT JOIN value
|
|
22
|
-
* count is known. Validates each alias against `
|
|
22
|
+
* count is known. Validates each alias against `readJoins` (throws 400), mirroring
|
|
23
23
|
* `validateOrderBy`; 3-part aggregation entries are ignored (they use joinGroup, not a LEFT JOIN).
|
|
24
24
|
*/
|
|
25
|
-
export declare function collectOrderByLeftAliases(orderBy: string, tableConf:
|
|
26
|
-
export declare function validateOrderBy(orderBy: string, tableConf:
|
|
25
|
+
export declare function collectOrderByLeftAliases(orderBy: string, tableConf: TableConfig): Set<string>;
|
|
26
|
+
export declare function validateOrderBy(orderBy: string, tableConf: TableConfig, db: QueryClient, dbTables: DbTables, joinGroup: Record<string, JoinGroupRequest> | undefined, startIdx: number, tenant?: TenantContext): OrderByResult;
|
|
27
27
|
/**
|
|
28
|
-
* Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
* to their expression, and anything else passes through unchanged as raw SQL.
|
|
28
|
+
* Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL: each
|
|
29
|
+
* `field [ASC|DESC]` term becomes the table-qualified column, or the expression of a computed
|
|
30
|
+
* field (without bound values). `defineTable` has already refused anything else; a config
|
|
31
|
+
* written by hand past it fails here, as a programming error, rather than reaching the SQL.
|
|
33
32
|
*/
|
|
34
|
-
export declare function convertConfiguredOrder(order: string, tableConf:
|
|
33
|
+
export declare function convertConfiguredOrder(order: string, tableConf: TableConfig, db: QueryClient): string;
|
|
35
34
|
//# sourceMappingURL=order-by.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"order-by.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/order-by.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"order-by.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/order-by.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAa/C,OAAO,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEhG,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,OAAO,EAAE,CAAC;IAClB,2EAA2E;IAC3E,eAAe,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,GAAG,GAAG,CAAC,MAAM,CAAC,CAa9F;AAED,wBAAgB,eAAe,CAC7B,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,WAAW,EACtB,EAAE,EAAE,WAAW,EACf,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAAG,SAAS,EACvD,QAAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,aAAa,GACrB,aAAa,CAuDf;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,WAAW,EACtB,EAAE,EAAE,WAAW,GACd,MAAM,CAmBR"}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { err400, validateSchemaField, resolveFieldRef, refValues, renderRef, evaluateComputedField, } from './fields.js';
|
|
2
2
|
import { requireJoin } from './joins.js';
|
|
3
|
+
import { resolveJoinTableConf, PLAIN_ORDER_TERM, defaultOrderTermProblem, defaultOrderError } from '../../table-helpers.js';
|
|
3
4
|
import { hasOwnField, ownField } from '../../read-access.js';
|
|
4
5
|
import { buildAggOrderExpr } from './aggregations.js';
|
|
5
6
|
/**
|
|
6
7
|
* Pre-scan `orderBy` for the joinLeft aliases referenced in 2-part notation (`<alias>.<field>`).
|
|
7
8
|
* Needed BEFORE building the LEFT JOIN clauses (which must know their aliases) while the actual
|
|
8
9
|
* orderBy SQL — with its parameter placeholders — is only baked later, once the LEFT JOIN value
|
|
9
|
-
* count is known. Validates each alias against `
|
|
10
|
+
* count is known. Validates each alias against `readJoins` (throws 400), mirroring
|
|
10
11
|
* `validateOrderBy`; 3-part aggregation entries are ignored (they use joinGroup, not a LEFT JOIN).
|
|
11
12
|
*/
|
|
12
13
|
export function collectOrderByLeftAliases(orderBy, tableConf) {
|
|
@@ -18,7 +19,7 @@ export function collectOrderByLeftAliases(orderBy, tableConf) {
|
|
|
18
19
|
const m = /^(\w+)\.(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
|
|
19
20
|
if (m) {
|
|
20
21
|
const alias = m[1];
|
|
21
|
-
requireJoin(tableConf, alias, true);
|
|
22
|
+
requireJoin(tableConf, alias, true, 'orderBy');
|
|
22
23
|
aliases.add(alias);
|
|
23
24
|
}
|
|
24
25
|
}
|
|
@@ -36,10 +37,10 @@ export function validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, sta
|
|
|
36
37
|
const dotted3 = /^(\w+)\.(\w+)\.(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
|
|
37
38
|
if (dotted3) {
|
|
38
39
|
if (tableConf.distinctResults) {
|
|
39
|
-
err400('Cannot combine distinctResults with aggregation orderBy');
|
|
40
|
+
err400('invalid_order_by', 'orderBy', 'Cannot combine distinctResults with aggregation orderBy');
|
|
40
41
|
}
|
|
41
42
|
const [, alias, fn, field, dir] = dotted3;
|
|
42
|
-
const expr = buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant);
|
|
43
|
+
const expr = buildAggOrderExpr(db, dbTables, tableConf, alias, fn, field, joinGroup, tenant, 'orderBy');
|
|
43
44
|
const aggVals = [...expr.values];
|
|
44
45
|
outParts.push(`${renderRef(expr, currentIdx, db)} ${(dir || 'ASC').toUpperCase()}`);
|
|
45
46
|
outValues.push(...aggVals);
|
|
@@ -50,20 +51,20 @@ export function validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, sta
|
|
|
50
51
|
const dotted2 = /^(\w+)\.(\w+)(?:\s+(ASC|DESC))?$/i.exec(trimmed);
|
|
51
52
|
if (dotted2) {
|
|
52
53
|
const [, alias, field, dir] = dotted2;
|
|
53
|
-
const joinDef = requireJoin(tableConf, alias, true);
|
|
54
|
-
const col = validateSchemaField(field, joinDef.joinSchema, dbTables
|
|
54
|
+
const joinDef = requireJoin(tableConf, alias, true, 'orderBy');
|
|
55
|
+
const col = validateSchemaField(field, joinDef.joinSchema, resolveJoinTableConf(dbTables, joinDef), 'orderBy');
|
|
55
56
|
// Reference the LEFT JOIN'd table via its alias (SQL identifier).
|
|
56
57
|
outParts.push(`${db.qi(alias)}.${db.qi(col)} ${(dir || 'ASC').toUpperCase()}`);
|
|
57
58
|
leftJoinAliases.add(alias);
|
|
58
59
|
continue;
|
|
59
60
|
}
|
|
60
61
|
// 1-part: <field> [ASC|DESC] — schema field or computed
|
|
61
|
-
const plain =
|
|
62
|
+
const plain = PLAIN_ORDER_TERM.exec(trimmed);
|
|
62
63
|
if (!plain) {
|
|
63
|
-
err400(`Invalid orderBy: ${trimmed}`);
|
|
64
|
+
err400('invalid_order_by', 'orderBy', `Invalid orderBy: ${trimmed}`);
|
|
64
65
|
}
|
|
65
66
|
const [, field, dir] = plain;
|
|
66
|
-
const ref = resolveFieldRef(field, tableConf.
|
|
67
|
+
const ref = resolveFieldRef(field, tableConf.schema, tableConf, db, undefined, 'orderBy');
|
|
67
68
|
// A computed field binds its own values here: ORDER BY is emitted after the WHERE, so
|
|
68
69
|
// its placeholders continue from `currentIdx`.
|
|
69
70
|
const refVals = refValues(ref.expr);
|
|
@@ -74,31 +75,26 @@ export function validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, sta
|
|
|
74
75
|
return { sql: outParts.join(', '), values: outValues, leftJoinAliases };
|
|
75
76
|
}
|
|
76
77
|
/**
|
|
77
|
-
* Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
* to their expression, and anything else passes through unchanged as raw SQL.
|
|
78
|
+
* Converts a configured order (`defaultOrder` or the primary-key fallback) to SQL: each
|
|
79
|
+
* `field [ASC|DESC]` term becomes the table-qualified column, or the expression of a computed
|
|
80
|
+
* field (without bound values). `defineTable` has already refused anything else; a config
|
|
81
|
+
* written by hand past it fails here, as a programming error, rather than reaching the SQL.
|
|
82
82
|
*/
|
|
83
83
|
export function convertConfiguredOrder(order, tableConf, db) {
|
|
84
84
|
return order
|
|
85
85
|
.split(',')
|
|
86
86
|
.map((part) => {
|
|
87
|
-
const
|
|
88
|
-
const
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
}
|
|
95
|
-
const computed = ownField(tableConf.computedFields, field);
|
|
96
|
-
if (computed) {
|
|
97
|
-
const ev = evaluateComputedField(field, computed, tableConf.Schema, db, undefined, `Computed field '${field}' with bound values cannot be used in defaultOrder`);
|
|
98
|
-
return `${ev.value}${suffix}`;
|
|
99
|
-
}
|
|
87
|
+
const term = part.trim();
|
|
88
|
+
const problem = defaultOrderTermProblem(term, tableConf);
|
|
89
|
+
if (problem)
|
|
90
|
+
throw defaultOrderError('search', term, tableConf, problem);
|
|
91
|
+
const [, field, dir] = PLAIN_ORDER_TERM.exec(term);
|
|
92
|
+
const suffix = dir ? ` ${dir.toUpperCase()}` : '';
|
|
93
|
+
if (hasOwnField(tableConf.schema.fields, field)) {
|
|
94
|
+
return `${db.qi(tableConf.schema.tableName)}.${db.qi(tableConf.schema.col(field))}${suffix}`;
|
|
100
95
|
}
|
|
101
|
-
|
|
96
|
+
const ev = evaluateComputedField(field, ownField(tableConf.computedFields, field), tableConf.schema, db, undefined, `Computed field '${field}' with bound values cannot be used in defaultOrder`);
|
|
97
|
+
return `${ev.value}${suffix}`;
|
|
102
98
|
})
|
|
103
99
|
.join(', ');
|
|
104
100
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/search.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../../../src/lib/engine/search/search.ts"],"names":[],"mappings":"AAqCA,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,YAAY,EAGb,MAAM,mBAAmB,CAAC;AA+S3B,wBAAsB,YAAY,CAChC,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,YAAY,CAAC,CAmGvB"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
|
+
import { buildTableFilters, PLAIN_ORDER_TERM } from '../../table-helpers.js';
|
|
1
2
|
import { QueryParams } from '../query-params.js';
|
|
2
3
|
import { buildTenantCondition, buildTenantJoin } from '../../tenant.js';
|
|
3
|
-
import { assertFiltersReadable, assertKnownFilterKeys, readableSelectColumns, ownField, } from '../../read-access.js';
|
|
4
|
+
import { assertFiltersReadable, assertKnownFilterKeys, readableSelectColumns, hasOwnField, ownField, } from '../../read-access.js';
|
|
4
5
|
import { MAX_CONDITIONS, MAX_ORDER_BY_PARTS } from '../../condition-methods.js';
|
|
5
|
-
import { primaryAsString } from '../../../types.js';
|
|
6
|
-
import { err400, resolveFieldRef, evaluateComputedField, refValues, renderRef, mapRowsToCamelCase, } from './fields.js';
|
|
6
|
+
import { primaryAsString, COMPUTE_FNS } from '../../../types.js';
|
|
7
|
+
import { err400, resolveFieldRef, evaluateComputedField, refValues, renderRef, mapRowsToCamelCase, buildMainSelectColumns, rejectRetiredSearchKeys, } from './fields.js';
|
|
7
8
|
import { assertJoinFilterKeys, requireJoin } from './joins.js';
|
|
8
9
|
import { runAfterRead } from '../read-hooks.js';
|
|
9
10
|
import { collectOrderByLeftAliases, validateOrderBy, convertConfiguredOrder } from './order-by.js';
|
|
10
11
|
import { applyConditions, applyComputedFilters } from './conditions.js';
|
|
11
|
-
import { appendAggConditions } from './aggregations.js';
|
|
12
|
+
import { appendAggConditions, AGG_FN, aggExpr } from './aggregations.js';
|
|
12
13
|
import { buildLeftJoinOnClauses, buildLeftJoinFilters, executeJoinMultiple, executeJoinLeft, executeJoinGroup, buildJoinMustExistClauses, } from './join-families.js';
|
|
13
14
|
/**
|
|
14
15
|
* Guard the request shapes that reach SQL as text rather than as bound values.
|
|
@@ -26,46 +27,48 @@ function assertRequestWithinLimits(params) {
|
|
|
26
27
|
for (const key of ['page', 'itemsPerPage']) {
|
|
27
28
|
const value = paginator[key];
|
|
28
29
|
if (!Number.isInteger(value) || value < 1) {
|
|
29
|
-
err400(`Invalid paginator: '${key}' must be an integer >= 1`);
|
|
30
|
+
err400('invalid_paginator', `paginator.${key}`, `Invalid paginator: '${key}' must be an integer >= 1`);
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
33
|
}
|
|
33
34
|
if (conditions && conditions.length > MAX_CONDITIONS) {
|
|
34
|
-
err400(`Too many conditions: ${conditions.length} (max ${MAX_CONDITIONS})`);
|
|
35
|
+
err400('limit_exceeded', 'conditions', `Too many conditions: ${conditions.length} (max ${MAX_CONDITIONS})`);
|
|
35
36
|
}
|
|
36
37
|
if (orderBy && orderBy.split(',').length > MAX_ORDER_BY_PARTS) {
|
|
37
|
-
err400(`Too many orderBy parts: max ${MAX_ORDER_BY_PARTS}`);
|
|
38
|
+
err400('limit_exceeded', 'orderBy', `Too many orderBy parts: max ${MAX_ORDER_BY_PARTS}`);
|
|
38
39
|
}
|
|
39
40
|
}
|
|
40
41
|
// ─── Main query execution ───────────────────────────────────
|
|
41
|
-
async function executeMainQuery(db, tableConf, where, values, orderBy, paginator, extraJoins = [],
|
|
42
|
-
const tableName = tableConf.
|
|
43
|
-
// Request orderBy arrives already validated and mapped by validateOrderBy;
|
|
44
|
-
//
|
|
42
|
+
async function executeMainQuery(db, tableConf, where, values, orderBy, paginator, extraJoins = [], projection, maxRows) {
|
|
43
|
+
const tableName = tableConf.schema.tableName;
|
|
44
|
+
// Request orderBy arrives already validated and mapped by validateOrderBy; the configured
|
|
45
|
+
// fallbacks (defaultOrder / primary key) are converted here, with the same 1-part grammar.
|
|
45
46
|
const order = orderBy || convertConfiguredOrder(tableConf.defaultOrder || primaryAsString(tableConf.primary), tableConf, db);
|
|
46
47
|
// With a paginator, the page size governs the LIMIT. Without one, apply `maxRows` (if set) so an
|
|
47
48
|
// unbounded search cannot dump the whole table; a plain integer is a safe, non-injectable LIMIT.
|
|
48
49
|
const limit = paginator
|
|
49
50
|
? `${paginator.itemsPerPage} OFFSET ${(paginator.page - 1) * paginator.itemsPerPage}`
|
|
50
51
|
: (maxRows != null ? String(maxRows) : null);
|
|
51
|
-
// Base projection: the
|
|
52
|
-
//
|
|
53
|
-
//
|
|
54
|
-
|
|
55
|
-
|
|
52
|
+
// Base projection: the request's `select` plus what the query needs; otherwise the main
|
|
53
|
+
// table's own columns, qualified ("hour".* or the readable list). Never a bare `*`: the
|
|
54
|
+
// statement may carry a LEFT JOIN (filtered/ordered joinLeft) or the tenant's INNER JOIN,
|
|
55
|
+
// and a bare `*` would hand the joined table's columns to the row.
|
|
56
|
+
const readableColumns = projection
|
|
57
|
+
? buildMainSelectColumns(projection.select, projection.required, tableConf, db)
|
|
58
|
+
: readableSelectColumns(tableConf, tableConf.schema, db);
|
|
59
|
+
// Computed fields listed in `select` — bound values, if any, are NOT yet supported
|
|
56
60
|
// here (would require placeholder-aware composition with WHERE values).
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
columns = projections.join(', ');
|
|
61
|
+
const projections = [readableColumns];
|
|
62
|
+
const computedNames = [];
|
|
63
|
+
for (const [i, name] of (projection?.select ?? []).entries()) {
|
|
64
|
+
const fn = ownField(tableConf.computedFields, name);
|
|
65
|
+
if (!fn || computedNames.includes(name))
|
|
66
|
+
continue;
|
|
67
|
+
const out = evaluateComputedField(name, fn, tableConf.schema, db, undefined, `Computed field '${name}' with bound values cannot be used in select`, false, `select.${i}`);
|
|
68
|
+
projections.push(`${out.value} AS ${db.qi(name)}`);
|
|
69
|
+
computedNames.push(name);
|
|
68
70
|
}
|
|
71
|
+
const columns = projections.join(', ');
|
|
69
72
|
const rows = await db.select({
|
|
70
73
|
tableName,
|
|
71
74
|
columns,
|
|
@@ -76,38 +79,74 @@ async function executeMainQuery(db, tableConf, where, values, orderBy, paginator
|
|
|
76
79
|
distinct: tableConf.distinctResults,
|
|
77
80
|
joins: extraJoins.length > 0 ? extraJoins : undefined,
|
|
78
81
|
});
|
|
79
|
-
return mapRowsToCamelCase(rows, tableConf.
|
|
82
|
+
return mapRowsToCamelCase(rows, tableConf.schema, computedNames);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The fields a `select` must carry even when the request leaves them out:
|
|
86
|
+
* - the primary key, which identifies each row;
|
|
87
|
+
* - the main-side key of every requested join family that runs a side query, which
|
|
88
|
+
* correlates the child or parent rows (`joinMustExist` is an EXISTS: nothing to project);
|
|
89
|
+
* - with `distinctResults`, the plain fields the result is ordered by — the database
|
|
90
|
+
* requires `SELECT DISTINCT` to list its ORDER BY expressions.
|
|
91
|
+
*/
|
|
92
|
+
function requiredProjection(params) {
|
|
93
|
+
const { tableConf, joinMultiple, joinLeft, joinGroup, orderBy } = params;
|
|
94
|
+
const required = Array.isArray(tableConf.primary) ? [...tableConf.primary] : [tableConf.primary];
|
|
95
|
+
const families = [
|
|
96
|
+
[joinMultiple, 'joinMultiple', false],
|
|
97
|
+
[joinLeft, 'joinLeft', true],
|
|
98
|
+
[joinGroup, 'joinGroup', false],
|
|
99
|
+
];
|
|
100
|
+
for (const [requests, family, unique] of families) {
|
|
101
|
+
for (const alias of Object.keys(requests ?? {})) {
|
|
102
|
+
const { mainField } = requireJoin(tableConf, alias, unique, `${family}.${alias}`);
|
|
103
|
+
required.push(...(Array.isArray(mainField) ? mainField : [mainField]));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (tableConf.distinctResults) {
|
|
107
|
+
const order = orderBy || tableConf.defaultOrder || primaryAsString(tableConf.primary);
|
|
108
|
+
for (const part of order.split(',')) {
|
|
109
|
+
const plain = PLAIN_ORDER_TERM.exec(part.trim());
|
|
110
|
+
if (plain && hasOwnField(tableConf.schema.fields, plain[1]))
|
|
111
|
+
required.push(plain[1]);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return required;
|
|
80
115
|
}
|
|
81
|
-
async function buildPagination(db, tableConf, where, values, paginator, extraJoins = []
|
|
82
|
-
const tableName = tableConf.
|
|
116
|
+
async function buildPagination(db, tableConf, where, values, paginator, extraJoins = []) {
|
|
117
|
+
const tableName = tableConf.schema.tableName;
|
|
83
118
|
const joinClause = extraJoins.length > 0 ? ' ' + extraJoins.join(' ') : '';
|
|
84
119
|
const countResult = await db.query(`SELECT COUNT(*) as total FROM ${db.qi(tableName)}${joinClause} WHERE ${where}`, values);
|
|
85
120
|
const total = parseInt(countResult.rows[0].total, 10);
|
|
121
|
+
return { total, pages: Math.ceil(total / paginator.itemsPerPage), paginator };
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* `result.computed`: the requested aggregates over every row the WHERE matches, with no LIMIT,
|
|
125
|
+
* so the value does not depend on the page — nor on whether the search is paginated at all.
|
|
126
|
+
*
|
|
127
|
+
* One statement per (function, field), in a fixed order; errors are reported at the body path
|
|
128
|
+
* `compute.<fn>.<i>`. The functions are joinGroup's, rendered by the same `aggExpr`.
|
|
129
|
+
*/
|
|
130
|
+
async function buildComputed(db, tableConf, where, values, extraJoins, compute) {
|
|
131
|
+
const tableName = tableConf.schema.tableName;
|
|
132
|
+
const joinClause = extraJoins.length > 0 ? ' ' + extraJoins.join(' ') : '';
|
|
86
133
|
const computed = {};
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
{ key: 'avg', field: computeAvg, fn: 'AVG' },
|
|
92
|
-
];
|
|
93
|
-
for (const { key, field, fn } of computations) {
|
|
94
|
-
if (field) {
|
|
95
|
-
const ref = resolveFieldRef(field, tableConf.Schema, tableConf, db);
|
|
134
|
+
for (const fn of COMPUTE_FNS) {
|
|
135
|
+
for (const [i, field] of (compute[fn] ?? []).entries()) {
|
|
136
|
+
const at = `compute.${fn}.${i}`;
|
|
137
|
+
const ref = resolveFieldRef(field, tableConf.schema, tableConf, db, undefined, at);
|
|
96
138
|
// The aggregate sits in the SELECT list, before the WHERE values: a computed that
|
|
97
139
|
// binds parameters cannot be placed here.
|
|
98
140
|
if (refValues(ref.expr).length > 0) {
|
|
99
|
-
err400(`Computed field '${field}' with bound values cannot be used in compute
|
|
141
|
+
err400('bound_values_not_allowed', at, `Computed field '${field}' with bound values cannot be used in compute.${fn}`);
|
|
100
142
|
}
|
|
101
|
-
const result = await db.query(`SELECT ${fn
|
|
102
|
-
|
|
143
|
+
const result = await db.query(`SELECT ${aggExpr(AGG_FN[fn], renderRef(ref.expr, 1, db))} as value FROM ${db.qi(tableName)}${joinClause} WHERE ${where}`, values);
|
|
144
|
+
const byField = computed[fn] ?? {};
|
|
145
|
+
byField[field] = result.rows[0].value;
|
|
146
|
+
computed[fn] = byField;
|
|
103
147
|
}
|
|
104
148
|
}
|
|
105
|
-
return
|
|
106
|
-
total,
|
|
107
|
-
pages: Math.ceil(total / paginator.itemsPerPage),
|
|
108
|
-
...(Object.keys(computed).length > 0 ? { computed } : {}),
|
|
109
|
-
paginator,
|
|
110
|
-
};
|
|
149
|
+
return Object.keys(computed).length > 0 ? computed : undefined;
|
|
111
150
|
}
|
|
112
151
|
// ─── searchEngine entrypoint ────────────────────────────────
|
|
113
152
|
/**
|
|
@@ -122,20 +161,20 @@ function assertJoinRequestsAllowed(dbTables, params) {
|
|
|
122
161
|
const { tableConf, joinMustExist, joinMultiple, joinGroup, joinLeft } = params;
|
|
123
162
|
if (joinMustExist)
|
|
124
163
|
for (const a of Object.keys(joinMustExist))
|
|
125
|
-
requireJoin(tableConf, a, false);
|
|
164
|
+
requireJoin(tableConf, a, false, `joinMustExist.${a}`);
|
|
126
165
|
if (joinMultiple)
|
|
127
166
|
for (const a of Object.keys(joinMultiple))
|
|
128
|
-
requireJoin(tableConf, a, false);
|
|
167
|
+
requireJoin(tableConf, a, false, `joinMultiple.${a}`);
|
|
129
168
|
if (joinGroup)
|
|
130
169
|
for (const a of Object.keys(joinGroup))
|
|
131
|
-
requireJoin(tableConf, a, false);
|
|
170
|
+
requireJoin(tableConf, a, false, `joinGroup.${a}`);
|
|
132
171
|
if (joinLeft)
|
|
133
172
|
for (const a of Object.keys(joinLeft))
|
|
134
|
-
requireJoin(tableConf, a, true);
|
|
135
|
-
assertJoinFilterKeys(dbTables, tableConf, joinMustExist, true);
|
|
136
|
-
assertJoinFilterKeys(dbTables, tableConf, joinMultiple, true);
|
|
137
|
-
assertJoinFilterKeys(dbTables, tableConf, joinGroup, true);
|
|
138
|
-
assertJoinFilterKeys(dbTables, tableConf, joinLeft, false);
|
|
173
|
+
requireJoin(tableConf, a, true, `joinLeft.${a}`);
|
|
174
|
+
assertJoinFilterKeys(dbTables, tableConf, joinMustExist, true, 'joinMustExist');
|
|
175
|
+
assertJoinFilterKeys(dbTables, tableConf, joinMultiple, true, 'joinMultiple');
|
|
176
|
+
assertJoinFilterKeys(dbTables, tableConf, joinGroup, true, 'joinGroup');
|
|
177
|
+
assertJoinFilterKeys(dbTables, tableConf, joinLeft, false, 'joinLeft');
|
|
139
178
|
}
|
|
140
179
|
/**
|
|
141
180
|
* The main table's WHERE builder, plus any JOIN the tenant scope needs.
|
|
@@ -147,20 +186,20 @@ function assertJoinRequestsAllowed(dbTables, params) {
|
|
|
147
186
|
function buildMainCondition(params) {
|
|
148
187
|
const { db, tableConf, filters, conditions, tenant } = params;
|
|
149
188
|
assertFiltersReadable(filters, tableConf);
|
|
150
|
-
assertKnownFilterKeys(filters, tableConf.
|
|
151
|
-
const condition = tableConf
|
|
189
|
+
assertKnownFilterKeys(filters, tableConf.schema, tableConf);
|
|
190
|
+
const condition = buildTableFilters(tableConf, filters || {}, db.cbDialect);
|
|
152
191
|
if (filters && tableConf.computedFields) {
|
|
153
192
|
applyComputedFilters(condition, filters, tableConf, db);
|
|
154
193
|
}
|
|
155
194
|
if (conditions?.length) {
|
|
156
|
-
applyConditions(condition, conditions, tableConf.
|
|
195
|
+
applyConditions(condition, conditions, tableConf.schema, tableConf, db);
|
|
157
196
|
}
|
|
158
197
|
const tenantJoins = [];
|
|
159
198
|
if (tenant?.scope) {
|
|
160
199
|
const scope = tenant.scope;
|
|
161
|
-
condition.append(buildTenantCondition(db, scope, tenant.ids, tableConf.
|
|
200
|
+
condition.append(buildTenantCondition(db, scope, tenant.ids, tableConf.schema.tableName));
|
|
162
201
|
if ('through' in scope) {
|
|
163
|
-
tenantJoins.push(buildTenantJoin(db, scope, tableConf.
|
|
202
|
+
tenantJoins.push(buildTenantJoin(db, scope, tableConf.schema.tableName));
|
|
164
203
|
}
|
|
165
204
|
}
|
|
166
205
|
return { condition, tenantJoins };
|
|
@@ -202,7 +241,8 @@ async function attachJoinResults(result, dbTables, params, main) {
|
|
|
202
241
|
}
|
|
203
242
|
}
|
|
204
243
|
export async function searchEngine(dbTables, params) {
|
|
205
|
-
const { db, tableConf, conditions, joinMustExist, joinGroup, joinLeft, orderBy, paginator,
|
|
244
|
+
const { db, tableConf, conditions, joinMustExist, joinGroup, joinLeft, orderBy, paginator, tenant, } = params;
|
|
245
|
+
rejectRetiredSearchKeys(params);
|
|
206
246
|
assertRequestWithinLimits(params);
|
|
207
247
|
assertJoinRequestsAllowed(dbTables, params);
|
|
208
248
|
const { condition, tenantJoins } = buildMainCondition(params);
|
|
@@ -244,11 +284,15 @@ export async function searchEngine(dbTables, params) {
|
|
|
244
284
|
safeOrderBy = bound.emit((startIndex) => validateOrderBy(orderBy, tableConf, db, dbTables, joinGroup, startIndex, tenant)).sql;
|
|
245
285
|
}
|
|
246
286
|
const mainValues = bound.snapshot();
|
|
247
|
-
const
|
|
287
|
+
const projection = params.select
|
|
288
|
+
? { select: params.select, required: requiredProjection(params) }
|
|
289
|
+
: undefined;
|
|
290
|
+
const main = await executeMainQuery(db, tableConf, where, mainValues, safeOrderBy, paginator, extraJoinClauses, projection, params.maxRows);
|
|
248
291
|
let pagination;
|
|
249
292
|
if (paginator) {
|
|
250
|
-
pagination = await buildPagination(db, tableConf, where, whereAndJoinValues, paginator, extraJoinClauses
|
|
293
|
+
pagination = await buildPagination(db, tableConf, where, whereAndJoinValues, paginator, extraJoinClauses);
|
|
251
294
|
}
|
|
295
|
+
const computed = await buildComputed(db, tableConf, where, whereAndJoinValues, extraJoinClauses, params.compute ?? {});
|
|
252
296
|
const result = { main };
|
|
253
297
|
await attachJoinResults(result, dbTables, params, main);
|
|
254
298
|
// After the joins, not before: they correlate to the main rows by the values the DB
|
|
@@ -256,6 +300,9 @@ export async function searchEngine(dbTables, params) {
|
|
|
256
300
|
// have them look for a value no child row carries. `main` is the same array either way,
|
|
257
301
|
// so the response still carries the hook's mutations.
|
|
258
302
|
await runAfterRead(db, params.request, main, tableConf, 'search');
|
|
303
|
+
if (computed) {
|
|
304
|
+
result.computed = computed;
|
|
305
|
+
}
|
|
259
306
|
if (pagination) {
|
|
260
307
|
result.pagination = pagination;
|
|
261
308
|
}
|