fastify-auto-sqlapi 0.5.0 → 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.
Files changed (212) hide show
  1. package/AGENTS.md +5 -5
  2. package/AGENTS_BACKEND.md +166 -130
  3. package/AGENTS_FRONTEND.md +60 -38
  4. package/BREAKING_CHANGES.md +9 -893
  5. package/CHANGELOG.md +258 -15
  6. package/README.md +71 -45
  7. package/dist/bin/generate-schema.js +12 -12
  8. package/dist/bin/generate-tables.js +1 -2
  9. package/dist/bin/utils.d.ts +2 -6
  10. package/dist/bin/utils.d.ts.map +1 -1
  11. package/dist/bin/utils.js +13 -33
  12. package/dist/index.d.ts +13 -33
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +6 -37
  15. package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
  16. package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
  17. package/dist/lib/adapters/pg-adapter.d.ts +5 -2
  18. package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
  19. package/dist/lib/agent/manifest.d.ts +27 -10
  20. package/dist/lib/agent/manifest.d.ts.map +1 -1
  21. package/dist/lib/agent/manifest.js +43 -26
  22. package/dist/lib/agent/tool-schemas.d.ts +5 -4
  23. package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
  24. package/dist/lib/agent/tool-schemas.js +5 -5
  25. package/dist/lib/cli/config.d.ts +37 -2
  26. package/dist/lib/cli/config.d.ts.map +1 -1
  27. package/dist/lib/cli/config.js +106 -16
  28. package/dist/lib/cli/mysql-introspect.d.ts +6 -1
  29. package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
  30. package/dist/lib/cli/mysql-introspect.js +15 -15
  31. package/dist/lib/cli/pg-introspect.d.ts +0 -1
  32. package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
  33. package/dist/lib/cli/pg-introspect.js +2 -13
  34. package/dist/lib/cli/tables-codegen.d.ts +0 -4
  35. package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
  36. package/dist/lib/cli/tables-codegen.js +24 -87
  37. package/dist/lib/db.d.ts +42 -17
  38. package/dist/lib/db.d.ts.map +1 -1
  39. package/dist/lib/db.js +114 -40
  40. package/dist/lib/dialect.d.ts +5 -0
  41. package/dist/lib/dialect.d.ts.map +1 -1
  42. package/dist/lib/dialect.js +3 -0
  43. package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
  44. package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
  45. package/dist/lib/engine/bulk/bulk-delete.js +66 -30
  46. package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
  47. package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
  48. package/dist/lib/engine/read-hooks.d.ts +3 -3
  49. package/dist/lib/engine/read-hooks.d.ts.map +1 -1
  50. package/dist/lib/engine/read-hooks.js +3 -3
  51. package/dist/lib/engine/rest/delete.d.ts.map +1 -1
  52. package/dist/lib/engine/rest/delete.js +12 -18
  53. package/dist/lib/engine/rest/get.js +8 -8
  54. package/dist/lib/engine/rest/insert.d.ts.map +1 -1
  55. package/dist/lib/engine/rest/insert.js +31 -18
  56. package/dist/lib/engine/rest/update.d.ts.map +1 -1
  57. package/dist/lib/engine/rest/update.js +34 -17
  58. package/dist/lib/engine/search/aggregations.d.ts +3 -3
  59. package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
  60. package/dist/lib/engine/search/aggregations.js +20 -16
  61. package/dist/lib/engine/search/conditions.d.ts +9 -5
  62. package/dist/lib/engine/search/conditions.d.ts.map +1 -1
  63. package/dist/lib/engine/search/conditions.js +31 -20
  64. package/dist/lib/engine/search/fields.d.ts +44 -11
  65. package/dist/lib/engine/search/fields.d.ts.map +1 -1
  66. package/dist/lib/engine/search/fields.js +94 -28
  67. package/dist/lib/engine/search/join-families.d.ts +7 -7
  68. package/dist/lib/engine/search/join-families.d.ts.map +1 -1
  69. package/dist/lib/engine/search/join-families.js +84 -75
  70. package/dist/lib/engine/search/joins.d.ts +15 -7
  71. package/dist/lib/engine/search/joins.d.ts.map +1 -1
  72. package/dist/lib/engine/search/joins.js +23 -13
  73. package/dist/lib/engine/search/order-by.d.ts +11 -12
  74. package/dist/lib/engine/search/order-by.d.ts.map +1 -1
  75. package/dist/lib/engine/search/order-by.js +24 -28
  76. package/dist/lib/engine/search/search.d.ts.map +1 -1
  77. package/dist/lib/engine/search/search.js +111 -62
  78. package/dist/lib/engine/validate.d.ts +21 -3
  79. package/dist/lib/engine/validate.d.ts.map +1 -1
  80. package/dist/lib/engine/validate.js +106 -16
  81. package/dist/lib/engine/write-helpers.d.ts +69 -16
  82. package/dist/lib/engine/write-helpers.d.ts.map +1 -1
  83. package/dist/lib/engine/write-helpers.js +257 -105
  84. package/dist/lib/errors.d.ts +42 -10
  85. package/dist/lib/errors.d.ts.map +1 -1
  86. package/dist/lib/errors.js +69 -15
  87. package/dist/lib/nullable.d.ts +3 -2
  88. package/dist/lib/nullable.d.ts.map +1 -1
  89. package/dist/lib/nullable.js +14 -5
  90. package/dist/lib/read-access.d.ts +33 -21
  91. package/dist/lib/read-access.d.ts.map +1 -1
  92. package/dist/lib/read-access.js +42 -23
  93. package/dist/lib/schema/bulk-delete.d.ts +13 -7
  94. package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
  95. package/dist/lib/schema/bulk-delete.js +18 -8
  96. package/dist/lib/schema/bulk-upsert.d.ts +3 -3
  97. package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
  98. package/dist/lib/schema/bulk-upsert.js +9 -14
  99. package/dist/lib/schema/get.d.ts +1 -1
  100. package/dist/lib/schema/get.d.ts.map +1 -1
  101. package/dist/lib/schema/get.js +2 -2
  102. package/dist/lib/schema/helpers.d.ts +41 -23
  103. package/dist/lib/schema/helpers.d.ts.map +1 -1
  104. package/dist/lib/schema/helpers.js +80 -33
  105. package/dist/lib/schema/insert.d.ts +1 -1
  106. package/dist/lib/schema/insert.d.ts.map +1 -1
  107. package/dist/lib/schema/insert.js +12 -20
  108. package/dist/lib/schema/search.d.ts +2 -13
  109. package/dist/lib/schema/search.d.ts.map +1 -1
  110. package/dist/lib/schema/search.js +64 -61
  111. package/dist/lib/schema/update.d.ts +1 -1
  112. package/dist/lib/schema/update.d.ts.map +1 -1
  113. package/dist/lib/schema/update.js +6 -13
  114. package/dist/lib/sql-api.d.ts +47 -25
  115. package/dist/lib/sql-api.d.ts.map +1 -1
  116. package/dist/lib/sql-api.js +70 -27
  117. package/dist/lib/table-helpers.d.ts +92 -14
  118. package/dist/lib/table-helpers.d.ts.map +1 -1
  119. package/dist/lib/table-helpers.js +367 -128
  120. package/dist/lib/tenant.d.ts +16 -22
  121. package/dist/lib/tenant.d.ts.map +1 -1
  122. package/dist/lib/tenant.js +38 -54
  123. package/dist/lib/write-access.d.ts +15 -9
  124. package/dist/lib/write-access.d.ts.map +1 -1
  125. package/dist/lib/write-access.js +12 -4
  126. package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
  127. package/dist/routes/auto/agent-manifest.routes.js +2 -2
  128. package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
  129. package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
  130. package/dist/routes/auto/bulk-delete.routes.js +1 -7
  131. package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
  132. package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
  133. package/dist/routes/auto/bulk-upsert.routes.js +2 -2
  134. package/dist/routes/auto/delete.routes.d.ts +2 -2
  135. package/dist/routes/auto/delete.routes.d.ts.map +1 -1
  136. package/dist/routes/auto/delete.routes.js +8 -10
  137. package/dist/routes/auto/get.routes.d.ts +2 -2
  138. package/dist/routes/auto/get.routes.d.ts.map +1 -1
  139. package/dist/routes/auto/get.routes.js +5 -5
  140. package/dist/routes/auto/insert.routes.d.ts +2 -2
  141. package/dist/routes/auto/insert.routes.d.ts.map +1 -1
  142. package/dist/routes/auto/insert.routes.js +1 -7
  143. package/dist/routes/auto/plugin.d.ts +6 -0
  144. package/dist/routes/auto/plugin.d.ts.map +1 -1
  145. package/dist/routes/auto/plugin.js +60 -36
  146. package/dist/routes/auto/route-helpers.d.ts +26 -12
  147. package/dist/routes/auto/route-helpers.d.ts.map +1 -1
  148. package/dist/routes/auto/route-helpers.js +50 -19
  149. package/dist/routes/auto/search.routes.d.ts +2 -2
  150. package/dist/routes/auto/search.routes.d.ts.map +1 -1
  151. package/dist/routes/auto/search.routes.js +36 -24
  152. package/dist/routes/auto/update.routes.d.ts +2 -2
  153. package/dist/routes/auto/update.routes.d.ts.map +1 -1
  154. package/dist/routes/auto/update.routes.js +1 -8
  155. package/dist/routes/sql-api-decorator.d.ts +30 -12
  156. package/dist/routes/sql-api-decorator.d.ts.map +1 -1
  157. package/dist/routes/sql-api-decorator.js +44 -27
  158. package/dist/types/cli.d.ts +17 -6
  159. package/dist/types/cli.d.ts.map +1 -1
  160. package/dist/types/computed.d.ts +1 -1
  161. package/dist/types/computed.d.ts.map +1 -1
  162. package/dist/types/conditions.d.ts +3 -1
  163. package/dist/types/conditions.d.ts.map +1 -1
  164. package/dist/types/db.d.ts +44 -4
  165. package/dist/types/db.d.ts.map +1 -1
  166. package/dist/types/dml.d.ts +26 -17
  167. package/dist/types/dml.d.ts.map +1 -1
  168. package/dist/types/hooks.d.ts +62 -0
  169. package/dist/types/hooks.d.ts.map +1 -0
  170. package/dist/types/hooks.js +1 -0
  171. package/dist/types/join.d.ts +25 -8
  172. package/dist/types/join.d.ts.map +1 -1
  173. package/dist/types/plugin.d.ts +58 -19
  174. package/dist/types/plugin.d.ts.map +1 -1
  175. package/dist/types/plugin.js +2 -0
  176. package/dist/types/request.d.ts +2 -2
  177. package/dist/types/schema.d.ts +3 -3
  178. package/dist/types/schema.d.ts.map +1 -1
  179. package/dist/types/search.d.ts +28 -13
  180. package/dist/types/search.d.ts.map +1 -1
  181. package/dist/types/search.js +2 -1
  182. package/dist/types/table.d.ts +109 -94
  183. package/dist/types/table.d.ts.map +1 -1
  184. package/dist/types/table.js +7 -2
  185. package/dist/types/tenant.d.ts +28 -2
  186. package/dist/types/tenant.d.ts.map +1 -1
  187. package/dist/types/tenant.js +7 -1
  188. package/dist/types/validation.d.ts +69 -13
  189. package/dist/types/validation.d.ts.map +1 -1
  190. package/dist/types.d.ts +1 -0
  191. package/dist/types.d.ts.map +1 -1
  192. package/dist/types.js +1 -0
  193. package/docs/GLOSSARY.md +11 -5
  194. package/docs/adr/0003-bulk-not-transactional.md +2 -1
  195. package/docs/adr/0006-raw-db-errors.md +2 -1
  196. package/docs/adr/0013-sanitized-db-errors.md +2 -1
  197. package/docs/adr/0014-what-follows-a-write-join.md +1 -1
  198. package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
  199. package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
  200. package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
  201. package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
  202. package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
  203. package/docs/adr/0027-the-1-0-contract.md +74 -0
  204. package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
  205. package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
  206. package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
  207. package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
  208. package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
  209. package/docs/adr/README.md +12 -1
  210. package/docs/upgrading/0.x.md +906 -0
  211. package/docs/upgrading/1.0.md +628 -0
  212. package/package.json +4 -5
@@ -1,16 +1,28 @@
1
1
  import type { ApiRequest } from './request.js';
2
2
  import type { QueryClient } from '../lib/db.js';
3
- import type { ITable, FilterRecord } from './table.js';
3
+ import type { TableConfig } from './table.js';
4
4
  import type { TenantContext } from './tenant.js';
5
5
  import type { JoinFetchRequest, JoinGroupRequest, JoinRefFilter } from './join.js';
6
- import type { SearchCondition } from './conditions.js';
6
+ import type { RowsByAlias } from './db.js';
7
+ import type { FilterRecord, SearchCondition } from './conditions.js';
7
8
  export interface Paginator {
8
9
  page: number;
9
10
  itemsPerPage: number;
10
11
  }
12
+ /** The aggregate functions a search may compute over all matching rows: those of joinGroup. */
13
+ export declare const COMPUTE_FNS: readonly ["min", "max", "sum", "avg", "count", "distinctCount"];
14
+ export type ComputeFn = (typeof COMPUTE_FNS)[number];
15
+ /**
16
+ * Aggregates over ALL rows matching the search, whatever page is returned, by function:
17
+ * `{ sum: ['total'], count: ['id'] }`. Each lands in `result.computed.<fn>.<field>`; no
18
+ * paginator is needed.
19
+ */
20
+ export type ComputeRequest = Partial<Record<ComputeFn, string[]>>;
21
+ /** `result.computed`: one value per requested function and field. */
22
+ export type ComputedResult = Partial<Record<ComputeFn, Record<string, unknown>>>;
11
23
  export interface SearchParams {
12
24
  db: QueryClient;
13
- tableConf: ITable;
25
+ tableConf: TableConfig;
14
26
  filters?: FilterRecord;
15
27
  conditions?: SearchCondition[];
16
28
  joinMustExist?: Record<string, JoinRefFilter>;
@@ -19,15 +31,17 @@ export interface SearchParams {
19
31
  joinLeft?: Record<string, JoinFetchRequest>;
20
32
  orderBy?: string;
21
33
  paginator?: Paginator;
22
- computeMin?: string;
23
- computeMax?: string;
24
- computeSum?: string;
25
- computeAvg?: string;
34
+ /** Aggregates over all matching rows; see `ComputeRequest`. */
35
+ compute?: ComputeRequest;
26
36
  /**
27
- * Names of computed fields (declared on `tableConf.computedFields`) to project
28
- * into the main response. Each becomes an extra column on each `main[i]` row.
37
+ * Fields to project into `main` rows: schema fields and computed fields alike. Omitted,
38
+ * every readable schema field is returned and no computed field. The primary key, the
39
+ * fields the requested joins correlate on and, with `distinctResults`, the ORDER BY fields
40
+ * are always projected: the response and the side queries need them. An unknown or
41
+ * `readExclude`d name is a 400 at `select.<i>`. `'*'` stands for the default projection, so
42
+ * `['*', 'fullName']` is every readable field plus that computed field.
29
43
  */
30
- selectComputed?: string[];
44
+ select?: string[];
31
45
  tenant?: TenantContext;
32
46
  /**
33
47
  * Row cap applied to the main query when no `paginator` is supplied, bounding an otherwise
@@ -42,14 +56,15 @@ export interface SearchParams {
42
56
  export interface PaginationResult {
43
57
  total: number;
44
58
  pages: number;
45
- computed?: Record<string, Record<string, unknown>>;
46
59
  paginator: Paginator;
47
60
  }
48
61
  export interface SearchResult {
49
62
  main: Record<string, unknown>[];
50
- joinMultiple?: Record<string, Record<string, unknown>[]>;
51
- joinLeft?: Record<string, Record<string, unknown>[]>;
63
+ joinMultiple?: RowsByAlias;
64
+ joinLeft?: RowsByAlias;
52
65
  joinGroup?: Record<string, Record<string, unknown>>;
66
+ /** Present when `compute` was requested: aggregates over every matching row. */
67
+ computed?: ComputedResult;
53
68
  pagination?: PaginationResult;
54
69
  }
55
70
  //# sourceMappingURL=search.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/types/search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACnF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEvD,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,WAAW,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,UAAU,CAAC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IACvB,UAAU,CAAC,EAAE,eAAe,EAAE,CAAC;IAC/B,aAAa,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;IAC9C,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IAChD,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IAC7C,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;IAC5C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,+DAA+D;IAC/D,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB;;;;;;;OAOG;IACH,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,8FAA8F;IAC9F,OAAO,CAAC,EAAE,UAAU,CAAC;CACtB;AAED,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,SAAS,CAAC;CACtB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IAChC,YAAY,CAAC,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,EAAE,WAAW,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IACpD,gFAAgF;IAChF,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,UAAU,CAAC,EAAE,gBAAgB,CAAC;CAC/B"}
@@ -1 +1,2 @@
1
- export {};
1
+ /** The aggregate functions a search may compute over all matching rows: those of joinGroup. */
2
+ export const COMPUTE_FNS = ['min', 'max', 'sum', 'avg', 'count', 'distinctCount'];
@@ -1,54 +1,66 @@
1
- import type { Expression, ConditionBuilder, ConditionValueOrUndefined, DialectName as CbDialect } from 'node-condition-builder';
2
- import type { TSchema, Static } from '@sinclair/typebox';
1
+ import type { ConditionBuilder } from 'node-condition-builder';
2
+ import type { TSchema, TObject } from 'typebox';
3
3
  import type { ApiRequest, ApiReply } from './request.js';
4
- import type { QueryClient } from '../lib/db.js';
5
4
  import type { SchemaDefinition } from './schema.js';
5
+ import type { FilterRecord } from './conditions.js';
6
6
  import type { ComputedFieldFn } from './computed.js';
7
7
  import type { JoinDefinition } from './join.js';
8
8
  import type { TenantScope } from './tenant.js';
9
9
  import type { ValidatorFn, BulkValidatorFn } from './validation.js';
10
- /** Auto-generated HTTP operations that can be enabled per table via `ITable.operations`. */
10
+ import type { WriteHookContext, AfterInsertContext, AfterUpdateContext, AfterReadContext, DeleteHookContext, BulkDeleteHookContext } from './hooks.js';
11
+ /** Auto-generated HTTP operations that can be enabled per table via `TableConfig.operations`. */
11
12
  export type TableOperation = 'search' | 'get' | 'insert' | 'update' | 'delete' | 'bulkUpsert' | 'bulkDelete';
12
- export type FilterRecord = Record<string, ConditionValueOrUndefined>;
13
- export type ExtendedConditionFn = (condition: ConditionBuilder, filters: FilterRecord) => void;
14
- /**
15
- * Builds the WHERE ConditionBuilder for a table from filter values. The optional
16
- * `dialect` selects identifier quoting and builder behavior per call (the engines pass
17
- * the dialect of the QueryClient that runs the query); when omitted, the global
18
- * `ConditionBuilder.DIALECT` is used.
19
- *
20
- * `qualifier` is the raw (unquoted) table name or alias to prefix columns with; it
21
- * defaults to the table's own name. The engines pass an alias when the condition lands
22
- * inside a correlated subquery whose FROM is aliased — there the bare table name would
23
- * resolve against the OUTER query.
24
- */
25
- export type TableFilterFn = (filters: FilterRecord, dialect?: CbDialect, qualifier?: string) => ConditionBuilder;
26
- /** Which read path produced the rows an `afterRead` hook is handed. */
27
- export type ReadSource = 'get' | 'search' | 'joinMultiple' | 'joinLeft';
28
- /** Where the rows an `afterRead` hook receives came from. */
29
- export interface AfterReadContext {
30
- source: ReadSource;
31
- /** The relation's alias, on the two join sources; absent on `get` and `search`. */
32
- alias?: string;
13
+ /** Every {@link TableOperation}, in route order. */
14
+ export declare const TABLE_OPERATIONS: readonly TableOperation[];
15
+ /** The third argument of `extendedCondition`. */
16
+ export interface ExtendedConditionContext<F extends Record<string, TSchema> = Record<string, TSchema>> {
17
+ /**
18
+ * The column of a schema field, quoted for the dialect and qualified the way the statement the
19
+ * condition lands in needs: the table name in the main search and in a side query, the alias
20
+ * inside a correlated subquery. A name that is not a field of the schema throws.
21
+ */
22
+ col(field: string & keyof F): string;
33
23
  }
34
- export interface ITable<F extends Record<string, TSchema> = Record<string, TSchema>> {
24
+ export type ExtendedConditionFn = (condition: ConditionBuilder, filters: FilterRecord, ctx: ExtendedConditionContext) => void;
25
+ export interface TableConfig<F extends Record<string, TSchema> = Record<string, TSchema>> {
35
26
  primary: (string & keyof F) | (string & keyof F)[];
36
- Schema: SchemaDefinition<F>;
37
- filters: TableFilterFn;
38
- extraFilters: Record<string, TSchema>;
27
+ /** The table's generated Schema: columns, their types, the table name. */
28
+ schema: SchemaDefinition<F>;
29
+ /**
30
+ * Search filters that are not columns, as a record of fields or a `Type.Object`. They are
31
+ * validated like column filters and reach `extendedCondition`, which alone gives them a
32
+ * meaning: nothing else turns them into SQL.
33
+ */
34
+ extraFilters?: Record<string, TSchema> | TObject;
35
+ /**
36
+ * Add to the search WHERE: receives the ConditionBuilder already holding the column
37
+ * equality filters, every filter value — columns and `extraFilters` alike — and `{ col }`.
38
+ * Name every column with `col(field)`: the same condition runs in the main search and inside
39
+ * join subqueries, where only `col` knows the qualifier.
40
+ */
41
+ extendedCondition?: ExtendedConditionFn;
39
42
  /**
40
43
  * Virtual fields produced by a SQL expression. Usable like schema fields in
41
44
  * `filters`, `conditions` (non-dotted), `orderBy` (1-part),
42
- * `computeMin/Max/Sum/Avg`, and (opt-in) in `selectComputed` for the main
45
+ * `compute`, and (opt-in, when listed) in `select` for the main
43
46
  * response. Each entry MUST declare `type` for Swagger and validation.
44
47
  *
45
48
  * Naming clashes with `Schema.fields` or `extraFilters` keys throw at
46
49
  * `defineTable` time.
47
50
  */
48
51
  computedFields?: Record<string, ComputedFieldFn>;
49
- allowedReadJoins?: JoinDefinition[];
50
- allowedWriteJoins?: JoinDefinition[];
51
- upsertMap?: Map<SchemaDefinition, string[]>;
52
+ readJoins?: JoinDefinition[];
53
+ writeJoins?: JoinDefinition[];
54
+ /**
55
+ * Upsert the main row on this key: an insert (`POST /rest`, `sqlApi.insert`) and every bulk
56
+ * upsert item becomes `INSERT … ON CONFLICT (<key>) DO UPDATE`. Fields (camelCase), exactly
57
+ * the schema's primary key or one of its `uniqueKeys`, checked at startup (ADR 0021).
58
+ * Absent, those writes are plain INSERTs.
59
+ *
60
+ * The main row only: the secondaries a write join carries upsert on the `upsertKey` of that
61
+ * relation (`buildRelation(…, { upsertKey })`).
62
+ */
63
+ upsertKey?: (string & keyof F)[];
52
64
  /**
53
65
  * Narrow a field's generated type where the DB could only describe it loosely: a column
54
66
  * Postgres calls `text` is an email, a UUID, a URL; an `integer` has a range. The generated
@@ -71,30 +83,36 @@ export interface ITable<F extends Record<string, TSchema> = Record<string, TSche
71
83
  * API is what `afterRead` (out) and `beforeInsert`/`beforeUpdate` (in) are for.
72
84
  */
73
85
  schemaOverrides?: Partial<Record<string & keyof F, TSchema>>;
86
+ /** Business validation of an insert/update: `{ db, req, main, upsert, replace }` → errors (any → 400, nothing written). */
74
87
  validate?: ValidatorFn<F>;
88
+ /** Bulk upsert validation, called once with every item: `{ db, req, items }`. When set, per-item `validate` is skipped in bulk. */
75
89
  validateBulk?: BulkValidatorFn<F>;
76
- beforeInsert?: (db: QueryClient, req: ApiRequest, record: {
77
- [K in keyof F]?: Static<F[K]> | Expression | null;
78
- }) => Promise<void>;
79
- beforeUpdate?: (db: QueryClient, req: ApiRequest, fields: {
80
- [K in keyof F]?: Static<F[K]> | Expression | null;
81
- }, secondaryFieldsFetcher?: unknown) => void | Promise<void>;
82
- afterInsert?: (db: QueryClient, req: ApiRequest, record: {
83
- [K in keyof F]?: Static<F[K]>;
84
- }, secondaryRecords?: unknown) => Promise<void>;
85
- /**
86
- * Runs after a successful update, inside the same transaction as the UPDATE +
87
- * secondaries + deletions: throwing here rolls back the whole operation (when the
88
- * adapter supports transactions). Receives the camelCase input record (including the
89
- * PK) plus the secondaries/deletions results, mirroring `afterInsert`.
90
- */
91
- afterUpdate?: (db: QueryClient, req: ApiRequest, record: {
92
- [K in keyof F]?: Static<F[K]> | Expression | null;
93
- }, secondaryRecords?: unknown, deletionRecords?: unknown) => void | Promise<void>;
94
- /**
95
- * Runs on the rows a read returned, once per result set, before they become the response.
96
- * The read-side counterpart of `beforeInsert`/`beforeUpdate`: the place to turn a stored
97
- * representation back into the API one (decrypting a column, unpacking a blob).
90
+ /** Before the INSERT, after `insertExclude` stripped the client payload (ADR 0005): mutate `ctx.record` in place. */
91
+ beforeInsert?: (ctx: WriteHookContext<F>) => void | Promise<void>;
92
+ /** Before the UPDATE: mutate `ctx.record` in place. The PK is present but never written. */
93
+ beforeUpdate?: (ctx: WriteHookContext<F>) => void | Promise<void>;
94
+ /**
95
+ * Runs after a successful insert: `{ db, req, record, secondaries, deletions }`, the camelCase
96
+ * input record merged with the generated primary key, the child rows written with it and
97
+ * those a `replace` removed, keyed by alias (absent when there were none).
98
+ *
99
+ * On an insert it runs inside the transaction of the INSERT and its child rows, so throwing
100
+ * rolls them back. On a bulk upsert it runs once per item, outside any transaction (ADR 0003)
101
+ * — except for an item with a `replace`, whose child rows and hook share one (ADR 0029).
102
+ */
103
+ afterInsert?: (ctx: AfterInsertContext<F>) => void | Promise<void>;
104
+ /**
105
+ * Runs after a successful update, inside the same transaction as the UPDATE and its child
106
+ * rows: throwing here rolls back the whole operation. `{ db, req, record, secondaries,
107
+ * deletions }`: the camelCase input record (including the PK) plus the child rows written and
108
+ * deleted, by alias.
109
+ */
110
+ afterUpdate?: (ctx: AfterUpdateContext<F>) => void | Promise<void>;
111
+ /**
112
+ * Runs on the rows a read returned, once per result set, before they become the response:
113
+ * `{ db, req, rows, source, alias }`. The read-side counterpart of `beforeInsert`/
114
+ * `beforeUpdate`: the place to turn a stored representation back into the API one
115
+ * (decrypting a column, unpacking a blob).
98
116
  *
99
117
  * `rows` are camelCase records and are mutated **in place** — the return value is ignored.
100
118
  * Rows cannot be added or removed: the pagination `COUNT` has already run, so a hook that
@@ -104,53 +122,39 @@ export interface ITable<F extends Record<string, TSchema> = Record<string, TSche
104
122
  *
105
123
  * Declared on the table that OWNS the column, and it follows a join: the hook runs whenever
106
124
  * that table's rows surface, including through a `joinMultiple` or `joinLeft` declared on
107
- * another table (`ctx.source` and `ctx.alias` say which). It does not run on `joinGroup`,
108
- * whose rows are aggregates rather than table rows.
125
+ * another table (`source` and `alias` say which). It does not run on `joinGroup`, whose rows
126
+ * are aggregates rather than table rows.
109
127
  *
110
128
  * Not called when the read returned no rows. Whatever the hook writes is serialized against
111
129
  * the response schema, so a transform that changes a field's JSON type needs a matching
112
130
  * `schemaOverrides` entry — without it `fast-json-stringify` coerces the value silently.
113
- *
114
- * `req` is the request that triggered the read. Same caveat as `beforeDelete`:
115
- * present through the auto-generated HTTP routes, `undefined` when a programmatic caller
116
- * invokes `sqlApi.search()`/`sqlApi.get()` without passing one.
117
131
  */
118
- afterRead?: (db: QueryClient, req: ApiRequest | undefined, rows: Record<string, unknown>[], ctx: AfterReadContext) => void | Promise<void>;
132
+ afterRead?: (ctx: AfterReadContext) => void | Promise<void>;
119
133
  /**
120
- * Runs before a single record is deleted (DELETE /rest/:id). Throw to abort the
121
- * deletion (the thrown error's `statusCode`/`message` are surfaced to the client).
134
+ * Runs before a single record is deleted (DELETE /rest/:id): `{ db, req, id }`. Throw to
135
+ * abort the deletion (the thrown error's `statusCode`/`message` are surfaced to the client).
122
136
  * Use it to enforce referential or business rules the DB cascade would otherwise hide.
123
137
  *
124
138
  * For tenant-scoped tables the hook only runs once ownership has been verified, so it
125
139
  * never fires for rows the caller cannot access.
126
- *
127
- * `req` is the request that triggered the operation. It is always present when
128
- * the delete comes through the auto-generated HTTP route. It is `undefined` only if you
129
- * call `sqlApi.delete(table, id)` programmatically without passing a request — in that
130
- * case any hook that reads request context (e.g. `req.user`) must guard for it.
131
- */
132
- beforeDelete?: (db: QueryClient, req: ApiRequest, id: string | number) => void | Promise<void>;
133
- /**
134
- * Runs after a single record has been deleted (DELETE /rest/:id). Not called when the
135
- * record was not found (404). Same `req` caveat as `beforeDelete`.
136
140
  */
137
- afterDelete?: (db: QueryClient, req: ApiRequest, id: string | number) => void | Promise<void>;
141
+ beforeDelete?: (ctx: DeleteHookContext) => void | Promise<void>;
142
+ /** Runs after a single record has been deleted: `{ db, req, id }`. Not called when the record was not found (404). */
143
+ afterDelete?: (ctx: DeleteHookContext) => void | Promise<void>;
138
144
  /**
139
145
  * Bulk counterpart of `beforeDelete`, invoked ONCE with all ids before a bulk delete
140
- * (POST /bulk/:table/delete). Called once — not per id — to preserve the single-query
141
- * optimization. Throw to abort the whole batch. `beforeDelete` is NOT called for bulk
142
- * deletes; configure this hook if you need a guard there.
143
- *
144
- * Same `req` caveat as `beforeDelete`: present via the HTTP route, `undefined` only when
145
- * `sqlApi.bulkDelete(table, ids)` is called programmatically without a request.
146
+ * (POST /bulk/:table/delete): `{ db, req, ids }`, the ids as the request sent them — values,
147
+ * or `{ <field>: value }` objects on a composite primary key. Called once — not per id — to preserve the
148
+ * single-query optimization. Throw to abort the whole batch. `beforeDelete` is NOT called
149
+ * for bulk deletes; configure this hook if you need a guard there.
146
150
  */
147
- beforeBulkDelete?: (db: QueryClient, req: ApiRequest, ids: (string | number)[]) => void | Promise<void>;
151
+ beforeBulkDelete?: (ctx: BulkDeleteHookContext) => void | Promise<void>;
148
152
  /**
149
- * Bulk counterpart of `afterDelete`, invoked ONCE after a bulk delete with the ids that
150
- * were ACTUALLY deleted (which may be a subset of the requested ids). Not called when
151
- * nothing was deleted. Same `req` caveat as `beforeBulkDelete`.
153
+ * Bulk counterpart of `afterDelete`, invoked ONCE after a bulk delete with the ids that were
154
+ * ACTUALLY deleted (a subset of the requested ones when some rows did not exist):
155
+ * `{ db, req, ids }`. Not called when nothing was deleted.
152
156
  */
153
- afterBulkDelete?: (db: QueryClient, req: ApiRequest, deletedIds: (string | number)[]) => void | Promise<void>;
157
+ afterBulkDelete?: (ctx: BulkDeleteHookContext) => void | Promise<void>;
154
158
  /**
155
159
  * Whitelist of auto-generated HTTP routes for this table. When omitted, ALL operations
156
160
  * are exposed (search, get, insert, update, delete, bulkUpsert, bulkDelete) — the
@@ -163,11 +167,11 @@ export interface ITable<F extends Record<string, TSchema> = Record<string, TSche
163
167
  operations?: TableOperation[];
164
168
  /**
165
169
  * Fields hidden from every read: they are not projected by search/get, not included
166
- * in the read response schemas, and omitted from this table's default join selection
170
+ * in the read response schemas, and omitted from this table's default join projection
167
171
  * when it is the target of a join.
168
172
  *
169
173
  * Referencing an excluded field from filters, conditions, orderBy, aggregations or an
170
- * explicit join selection is rejected with 400 — hiding a field from the output while
174
+ * explicit join `select` is rejected with 400 — hiding a field from the output while
171
175
  * letting it be filtered would still leak its value by bisection.
172
176
  *
173
177
  * Write paths are NOT affected: a field can be writable but never readable (e.g. a
@@ -187,24 +191,35 @@ export interface ITable<F extends Record<string, TSchema> = Record<string, TSche
187
191
  *
188
192
  * Not a per-caller permission: it is static and applies to everyone, admins included.
189
193
  * Field-level rules that depend on who is asking belong in `beforeUpdate` (silent strip) or
190
- * `validate` (loud 400). Not `excludeFromCreation` either — that one whitelists client input
191
- * on insert only, and deliberately lets a hook assign the field afterwards.
194
+ * `validate` (loud 400). Not `insertExclude` either — that one whitelists client input on
195
+ * insert only, and deliberately lets a hook assign the field afterwards.
192
196
  *
193
197
  * The primary key cannot be excluded: the update body identifies the row with it.
194
198
  */
195
199
  writeExclude?: (string & keyof F)[];
200
+ /**
201
+ * Fields a client may not send on insert: their value is dropped from the client payload,
202
+ * and they are Optional in the insert body. The server still may set them — `beforeInsert`
203
+ * runs after the drop, and the FK of a secondary is auto-filled after it too (ADR 0005).
204
+ * The generator lists auto-increment and identity primary keys here.
205
+ *
206
+ * Insert only, and client input only: every field stays updatable (ADR 0004), and it applies
207
+ * to the rows this table receives as secondaries of another table as well. For a column no
208
+ * write may carry, whoever sets it, use `writeExclude`.
209
+ */
210
+ insertExclude?: (string & keyof F)[];
196
211
  defaultOrder?: string;
197
- excludeFromCreation?: (string & keyof F)[];
198
212
  distinctResults?: boolean;
199
213
  onRequests?: ((request: ApiRequest, reply: ApiReply) => Promise<void | ApiReply>)[];
200
214
  tenantScope?: TenantScope;
201
215
  }
202
- export type DbTables = Record<string, ITable<any>>;
216
+ export type DbTables = Record<string, TableConfig<any>>;
203
217
  export declare function primaryAsString(pk: string | string[]): string;
204
218
  /**
205
219
  * True when the primary key spans more than one column. Operations that address a
206
- * record by a single PK value (get, delete, bulkDelete) cannot work on such tables:
207
- * matching on the first column alone would hit every row sharing that value.
220
+ * record by a single PK value in the path (get, delete) cannot work on such tables:
221
+ * matching on the first column alone would hit every row sharing that value. Bulk delete
222
+ * takes one object per key instead.
208
223
  */
209
224
  export declare function isCompositePrimary(pk: string | string[]): boolean;
210
225
  export declare function primaryAsCols(pk: string | string[], colFn: (f: string) => string): string | string[];
@@ -1 +1 @@
1
- {"version":3,"file":"table.d.ts","sourceRoot":"","sources":["../../src/types/table.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,WAAW,IAAI,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAChI,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAA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AC,EAAE,CAAC;IACpC;;;;;;;;;OASG;IACH,aAAa,CAAC,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,UAAU,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,KAAK,OAAO,CAAC,IAAI,GAAG,QAAQ,CAAC,CAAC,EAAE,CAAC;IACpF,WAAW,CAAC,EAAE,WAAW,CAAC;CAC3B;AAGD,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;AAGxD,wBAAgB,eAAe,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,MAAM,CAE7D;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,OAAO,CAEjE;AAED,wBAAgB,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,CAEpG"}
@@ -1,11 +1,16 @@
1
+ /** Every {@link TableOperation}, in route order. */
2
+ export const TABLE_OPERATIONS = [
3
+ 'search', 'get', 'insert', 'update', 'delete', 'bulkUpsert', 'bulkDelete',
4
+ ];
1
5
  // Primary key helpers
2
6
  export function primaryAsString(pk) {
3
7
  return Array.isArray(pk) ? pk[0] : pk;
4
8
  }
5
9
  /**
6
10
  * True when the primary key spans more than one column. Operations that address a
7
- * record by a single PK value (get, delete, bulkDelete) cannot work on such tables:
8
- * matching on the first column alone would hit every row sharing that value.
11
+ * record by a single PK value in the path (get, delete) cannot work on such tables:
12
+ * matching on the first column alone would hit every row sharing that value. Bulk delete
13
+ * takes one object per key instead.
9
14
  */
10
15
  export function isCompositePrimary(pk) {
11
16
  return Array.isArray(pk) && pk.length > 1;
@@ -1,13 +1,39 @@
1
1
  import type { SchemaDefinition } from './schema.js';
2
+ import type { ApiRequest } from './request.js';
2
3
  export type TenantId = string | number;
4
+ /**
5
+ * The value `getTenantId` returns for a caller allowed to see every tenant's rows. Admin is
6
+ * declared, never inferred: an absent tenant (`null`/`undefined`) is a 401 on any scoped
7
+ * table, so an auth hook that failed to run cannot open the data. A registry symbol, so two
8
+ * copies of the package agree on it and no real tenant id can collide with it.
9
+ */
10
+ export declare const TENANT_ADMIN: unique symbol;
11
+ export type TenantAdmin = typeof TENANT_ADMIN;
12
+ /**
13
+ * What `getTenantId` resolves a request to: one tenant id, several (a caller who belongs to
14
+ * more than one tenant), `TENANT_ADMIN` for no filtering, or nothing — which is refused with
15
+ * 401 as soon as a scoped table is in reach. `[]` is a caller with no tenant at all: 403.
16
+ */
17
+ export type TenantResolution = TenantId | TenantId[] | TenantAdmin | null | undefined;
18
+ export type GetTenantId = (request: ApiRequest) => TenantResolution | Promise<TenantResolution>;
19
+ /**
20
+ * The names of a scope are schema fields, like every other key of a table config, each resolved
21
+ * to its column through the schema of the table it lives on. The column of a field is accepted as
22
+ * written; any other name is refused by `defineTable` (ADR 0032).
23
+ */
3
24
  export interface TenantScopeDirect {
25
+ /** The tenant field of this table. */
4
26
  column: string;
5
27
  }
6
28
  export interface TenantScopeIndirect {
29
+ /** The tenant field of the parent table, `through.schema`. */
7
30
  column: string;
8
31
  through: {
32
+ /** The parent table's schema. */
9
33
  schema: SchemaDefinition;
34
+ /** The FK field of this table that names the parent row. */
10
35
  localField: string;
36
+ /** The field of the parent table the FK points at. */
11
37
  foreignField: string;
12
38
  };
13
39
  }
@@ -18,7 +44,7 @@ export interface TenantScopeIndirect {
18
44
  *
19
45
  * Writes cannot auto-inject a tenant the way a single-column scope does — the plugin has no way
20
46
  * to know which party the caller is meant to be — so the payload must anchor the row itself:
21
- * see `assertTenantAnchor`. Columns are DB column names, like `TenantScopeDirect.column`.
47
+ * see `assertTenantAnchor`. The entries are fields of this table, like `TenantScopeDirect.column`.
22
48
  *
23
49
  * Not combinable with `column`/`through`: an entry reached through a parent FK would need its
24
50
  * own join per entry, and is rejected at `defineTable` time rather than half-supported.
@@ -34,7 +60,7 @@ export type TenantScope = TenantScopeDirect | TenantScopeIndirect | TenantScopeA
34
60
  * the request touches. `scope` is table-level and therefore **optional**: the addressed table may
35
61
  * declare no scope of its own while a table it reaches through a relation does. Absent `scope`
36
62
  * means "no filtering on this table", never "no tenant" — `tenantForTable` re-targets the same
37
- * ids onto a related table's own scope.
63
+ * ids onto a related table's own scope. Its names are already resolved to columns.
38
64
  */
39
65
  export interface TenantContext {
40
66
  ids: TenantId[];
@@ -1 +1 @@
1
- {"version":3,"file":"tenant.d.ts","sourceRoot":"","sources":["../../src/types/tenant.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEpD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAC;AAEvC,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE;QACP,MAAM,EAAE,gBAAgB,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;QACnB,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC;CACH;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,MAAM,MAAM,WAAW,GAAG,iBAAiB,GAAG,mBAAmB,GAAG,gBAAgB,CAAC;AAErF;;;;;;;;GAQG;AACH,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,QAAQ,EAAE,CAAC;IAChB,KAAK,CAAC,EAAE,WAAW,CAAC;CACrB"}
1
+ {"version":3,"file":"tenant.d.ts","sourceRoot":"","sources":["../../src/types/tenant.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,MAAM,CAAC;AAEvC;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,OAAO,MAAuD,CAAC;AAC1F,MAAM,MAAM,WAAW,GAAG,OAAO,YAAY,CAAC;AAE9C;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG,QAAQ,GAAG,QAAQ,EAAE,GAAG,WAAW,GAAG,IAAI,GAAG,SAAS,CAAC;AACtF,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,EAAE,UAAU,KAAK,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;AAEhG;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,sCAAsC;IACtC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,mBAAmB;IAClC,8DAA8D;IAC9D,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE;QACP,iCAAiC;QACjC,MAAM,EAAE,gBAAgB,CAAC;QACzB,4DAA4D;QAC5D,UAAU,EAAE,MAAM,CAAC;QACnB,sDAAsD;QACtD,YAAY,EAAE,MAAM,CAAC;KACtB,CAAC;CACH;AAED;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,EAAE,CAAC;CACjB;AAED,MAAM,MAAM,WAAW,GAAG,iBAAiB,GAAG,mBAAmB,GAAG,gBAAgB,CAAC;AAErF;;;;;;;;GAQG;AACH,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,QAAQ,EAAE,CAAC;IAChB,KAAK,CAAC,EAAE,WAAW,CAAC;CACrB"}
@@ -1 +1,7 @@
1
- export {};
1
+ /**
2
+ * The value `getTenantId` returns for a caller allowed to see every tenant's rows. Admin is
3
+ * declared, never inferred: an absent tenant (`null`/`undefined`) is a 401 on any scoped
4
+ * table, so an auth hook that failed to run cannot open the data. A registry symbol, so two
5
+ * copies of the package agree on it and no real tenant id can collide with it.
6
+ */
7
+ export const TENANT_ADMIN = Symbol.for('fastify-auto-sqlapi.tenant.admin');
@@ -1,21 +1,77 @@
1
- import type { TSchema, Static } from '@sinclair/typebox';
2
- import type { ApiRequest } from './request.js';
3
- import type { QueryClient } from '../lib/db.js';
1
+ import type { TSchema, Static } from 'typebox';
2
+ import type { RowsByAlias } from './db.js';
3
+ import type { HookContext } from './hooks.js';
4
4
  /**
5
- * Validation error tuple: [field, code] or [field, code, message].
6
- * - field: the field path (e.g. 'name', 'session_period[1].startDate')
7
- * - code: machine-readable error code (e.g. 'required', 'overlap', 'unique')
8
- * - message: human-readable description (defaults to code if omitted)
5
+ * One entry of the `fields` array every 400 response carries, whether the error came from
6
+ * the request schema, from a table's `validate`/`validateBulk`, or from the engine.
7
+ *
8
+ * - `path`: dot path of the offending value inside the request — body keys from the root
9
+ * (`main.name`, `upsert.orders.0.total`, `filters.status`, `conditions.2.params`,
10
+ * `joinMultiple.orders.select.1`), querystring and path parameters by name (`orderBy`,
11
+ * `itemsPerPage`, `id`). The empty string when the error is not attributable to one input.
12
+ * - `code`: machine-readable and stable — an Ajv keyword (`required`, `type`, `maximum`…),
13
+ * the code a `validate` hook returned, or one of the engine's codes (`unknown_field`,
14
+ * `not_readable`, `unknown_alias`, `invalid_params`…, see AGENTS_FRONTEND.md).
15
+ * - `message`: Ajv's, the engine's or an `httpError`'s description, for a developer. Absent
16
+ * when there is nothing to say beyond the code: on an entry `validate`/`validateBulk`
17
+ * returned (a hook writes no prose) and on a `dbErrors` answer.
9
18
  */
10
- export type ValidationError = [field: string, code: string] | [field: string, code: string, message: string];
11
- export type ValidatorFn<F extends Record<string, TSchema> = Record<string, TSchema>> = (db: QueryClient, req: ApiRequest, main: {
12
- [K in keyof F]?: Static<F[K]>;
13
- }, secondaries?: Record<string, Record<string, unknown>[]>) => Promise<ValidationError[]> | ValidationError[];
19
+ export interface ValidationField {
20
+ path: string;
21
+ code: string;
22
+ message?: string;
23
+ }
24
+ /**
25
+ * The main row a child row is written with, as the child table's `validate`/`validateBulk` sees
26
+ * it when its rows arrive through another table's write join (ADR 0030): the alias they were
27
+ * sent under and that table's main row, camelCase, as the request sent it.
28
+ */
29
+ export interface ValidateParent {
30
+ alias: string;
31
+ main: Record<string, unknown>;
32
+ }
33
+ /**
34
+ * `validate`: the camelCase main record of an insert or update, and the child rows it writes,
35
+ * by alias, under the request's own section names — so an error's `path` is the request's.
36
+ *
37
+ * When the table's rows arrive as another table's child rows, `main` is one of them — with the
38
+ * FK to that table's main row when the request names its key — and `parent` names that table's
39
+ * main row; on the table's own routes `parent` is absent (ADR 0030).
40
+ */
41
+ export interface ValidateContext<F extends Record<string, TSchema> = Record<string, TSchema>> extends HookContext {
42
+ main: {
43
+ [K in keyof F]?: Static<F[K]>;
44
+ };
45
+ upsert?: RowsByAlias;
46
+ replace?: RowsByAlias;
47
+ parent?: ValidateParent;
48
+ }
49
+ /**
50
+ * What a `validate`/`validateBulk` hook returns: one `{ path, code }` per problem, rendered as
51
+ * a field of the 400 — `path` in the grammar of `ValidationField.path` (`main.name`,
52
+ * `upsert.orders.0.total`; in `validateBulk`, `items.3.main.code`), `code` the stable
53
+ * code the client translates (`required`, `overlap`, `unique`). An empty array lets the write
54
+ * through.
55
+ */
56
+ export type ValidatorResult = Pick<ValidationField, 'path' | 'code'>[];
57
+ export type ValidatorFn<F extends Record<string, TSchema> = Record<string, TSchema>> = (ctx: ValidateContext<F>) => Promise<ValidatorResult> | ValidatorResult;
58
+ /** One item of a bulk upsert, as the request sent it. */
14
59
  export interface BulkValidatorItem<F extends Record<string, TSchema> = Record<string, TSchema>> {
15
60
  main: {
16
61
  [K in keyof F]?: Static<F[K]>;
17
62
  };
18
- secondaries?: Record<string, Record<string, unknown>[]>;
63
+ upsert?: RowsByAlias;
64
+ delete?: RowsByAlias;
65
+ replace?: RowsByAlias;
66
+ }
67
+ /**
68
+ * `validateBulk`: every item of a bulk upsert, once — or, when the table's rows arrive as
69
+ * another table's child rows, the rows of one alias as `{ main }` items, with `parent`
70
+ * (ADR 0030).
71
+ */
72
+ export interface BulkValidateContext<F extends Record<string, TSchema> = Record<string, TSchema>> extends HookContext {
73
+ items: BulkValidatorItem<F>[];
74
+ parent?: ValidateParent;
19
75
  }
20
- export type BulkValidatorFn<F extends Record<string, TSchema> = Record<string, TSchema>> = (db: QueryClient, req: ApiRequest, items: BulkValidatorItem<F>[]) => Promise<ValidationError[]> | ValidationError[];
76
+ export type BulkValidatorFn<F extends Record<string, TSchema> = Record<string, TSchema>> = (ctx: BulkValidateContext<F>) => Promise<ValidatorResult> | ValidatorResult;
21
77
  //# sourceMappingURL=validation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/types/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC/C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD;;;;;GAKG;AACH,MAAM,MAAM,eAAe,GACvB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,GAC7B,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAEnD,MAAM,MAAM,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,CACrF,EAAE,EAAE,WAAW,EACf,GAAG,EAAE,UAAU,EACf,IAAI,EAAE;KAAG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,C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