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,14 +1,14 @@
1
1
  import type { ApiRequest } from '../types/request.js';
2
- import type { QueryClient } from './db.js';
3
- import { ConditionBuilder, type ConditionValue, type ConditionValueOrUndefined } from 'node-condition-builder';
4
- import type { ITable, SqlApiPluginOptions, TenantId, TenantScope, TenantScopeDirect, TenantScopeIndirect, TenantScopeAnyOf, TenantContext } from '../types.js';
2
+ import { type QueryClient } from './db.js';
3
+ import { ConditionBuilder, type ConditionValue } from 'node-condition-builder';
4
+ import type { TableConfig, SqlApiPluginOptions, TenantId, TenantScope, TenantScopeDirect, TenantScopeIndirect, TenantScopeAnyOf, TenantContext } from '../types.js';
5
5
  /**
6
6
  * The columns of a scoped table that the engine fills or validates on insert, i.e. the ones a
7
7
  * write body must offer without requiring: the own column of a direct scope, every column of an
8
8
  * `anyOf` scope. An indirect scope names no column of its own — its FK is an ordinary field.
9
9
  */
10
10
  export declare function tenantOwnColumns(scope: TenantScope | undefined): string[];
11
- export declare function resolveTenant(options: SqlApiPluginOptions, tableConf: ITable, request: ApiRequest): Promise<TenantContext | undefined>;
11
+ export declare function resolveTenant(options: SqlApiPluginOptions, tableConf: TableConfig, request: ApiRequest): Promise<TenantContext | undefined>;
12
12
  /**
13
13
  * The read predicate for a scope, as a fragment every caller appends to its own WHERE.
14
14
  *
@@ -25,12 +25,14 @@ export declare function buildTenantCondition(db: QueryClient, scope: TenantScope
25
25
  * Returns undefined for the two cases that must stay unscoped — no tenant context (admin) and
26
26
  * a table that declares no scope — mirroring `appendJoinTenantScope` on the read side.
27
27
  */
28
- export declare function tenantForTable(tenant: TenantContext | undefined, tableConf: ITable | undefined): TenantContext | undefined;
28
+ export declare function tenantForTable(tenant: TenantContext | undefined, tableConf: TableConfig | undefined): TenantContext | undefined;
29
29
  /**
30
30
  * Tenant guard as a self-contained boolean fragment, for the positions where the scope cannot
31
- * be expressed as an extra INNER JOIN: a child DELETE, a LEFT JOIN's ON clause, and the
32
- * correlated subquery of an aggregation. A direct scope compares the table's own column; an
33
- * indirect one tests the through table with a correlated EXISTS rather than a join.
31
+ * be expressed as an extra INNER JOIN: a DELETE (of the addressed table or of a child), a LEFT
32
+ * JOIN's ON clause, and the correlated subquery of an aggregation. A direct scope compares the
33
+ * table's own column; an indirect one tests the through table with a correlated EXISTS rather
34
+ * than a join — which also keeps a DELETE from reading the table it deletes from, a statement
35
+ * MySQL and MariaDB refuse (error 1093).
34
36
  *
35
37
  * `tableRef` is the name the scoped rows go by in that statement — the table name in a DELETE,
36
38
  * the join alias in an ON clause, the subquery alias inside a correlated SELECT. Returns
@@ -59,15 +61,6 @@ export declare function injectTenantValue(record: Record<string, unknown>, scope
59
61
  * @testonly Exported only so unit tests can exercise it directly.
60
62
  */
61
63
  export declare function validateTenantFK(db: QueryClient, scope: TenantScopeIndirect, tenantIds: TenantId[], fkValues: unknown[]): Promise<void>;
62
- /**
63
- * Build WHERE clause for DELETE with tenant filtering.
64
- * Handles both direct (simple AND) and indirect (subquery via JOIN) scopes; a tenant whose
65
- * addressed table declares no scope yields the plain primary-key clause.
66
- */
67
- export declare function buildTenantDeleteWhere(db: QueryClient, tableName: string, pkCol: string, pkValue: ConditionValueOrUndefined | ConditionValue[], tenant: TenantContext): {
68
- where: string;
69
- values: unknown[];
70
- };
71
64
  /**
72
65
  * Guard the conflict target of an UPSERT (INSERT … ON CONFLICT / ON DUPLICATE KEY) on a
73
66
  * tenant-scoped table. Without this, an upsert whose conflict key matches a row owned by
@@ -129,10 +122,11 @@ export declare function buildTenantUpdateExtra(db: QueryClient, tenant: TenantCo
129
122
  */
130
123
  export declare function assertTenantOwnership(db: QueryClient, tenant: TenantContext | undefined, tableName: string, pkCol: string | string[], pkValue: ConditionValue | ConditionValue[]): Promise<void>;
131
124
  /**
132
- * Assert that EVERY pk in `ids` exists and belongs to the tenant, for both direct and indirect
133
- * scopes. Throws 404 if any id is missing or not owned. No-op when `tenant` is undefined or `ids`
134
- * is empty. Used by the delete engines to enforce tenant ownership BEFORE running a `beforeDelete`/
135
- * `beforeBulkDelete` hook, so user code never runs against rows the caller cannot access.
125
+ * Assert that EVERY key in `keys` exists and belongs to the tenant, for both direct and indirect
126
+ * scopes. Throws 404 if any key is missing or not owned. No-op when `tenant` is undefined or
127
+ * `keys` is empty. Used by the delete engines to enforce tenant ownership BEFORE running a
128
+ * `beforeDelete`/`beforeBulkDelete` hook, so user code never runs against rows the caller cannot
129
+ * access. `keys` holds one value per column of `pkCols` for each row (see `buildKeyMatch`).
136
130
  */
137
- export declare function assertTenantOwnsAll(db: QueryClient, tenant: TenantContext | undefined, tableName: string, pkCol: string, ids: ConditionValue[]): Promise<void>;
131
+ export declare function assertTenantOwnsAll(db: QueryClient, tenant: TenantContext | undefined, tableName: string, pkCols: string[], keys: ConditionValue[][]): Promise<void>;
138
132
  //# sourceMappingURL=tenant.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tenant.d.ts","sourceRoot":"","sources":["../../src/lib/tenant.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,KAAK,cAAc,EAAE,KAAK,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AAE/G,OAAO,KAAK,EAEV,MAAM,EACN,mBAAmB,EACnB,QAAQ,EACR,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACd,MAAM,aAAa,CAAC;AAmBrB;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,EAAE,CAGzE;AAuBD,wBAAsB,aAAa,CACjC,OAAO,EAAE,mBAAmB,EAC5B,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,UAAU,GAClB,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAiBpC;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,WAAW,EACf,KAAK,EAAE,WAAW,EAClB,SAAS,EAAE,QAAQ,EAAE,EACrB,QAAQ,EAAE,MAAM,GACf,gBAAgB,CAgBlB;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,aAAa,GAAG,SAAS,EACj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,EAAE,WAAW,GACjB,IAAI,CAGN;AAED;;;;;GAKG;AACH,wBAAsB,qBAAqB,CACzC,EAAE,EAAE,WAAW,EACf,MAAM,EAAE,aAAa,GAAG,SAAS,EACjC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GACjC,OAAO,CAAC,IAAI,CAAC,CAaf;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,aAAa,GAAG,SAAS,GAAG,MAAM,EAAE,CAGlF;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CACpC,EAAE,EAAE,WAAW,EACf,MAAM,EAAE,aAAa,GAAG,SAAS,GAChC,gBAAgB,GAAG,SAAS,CAY9B;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,EAAE,EAAE,WAAW,EACf,MAAM,EAAE,aAAa,GAAG,SAAS,EACjC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,EACxB,OAAO,EAAE,cAAc,GAAG,cAAc,EAAE,GACzC,OAAO,CAAC,IAAI,CAAC,CAaf;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACvC,EAAE,EAAE,WAAW,EACf,MAAM,EAAE,aAAa,GAAG,SAAS,EACjC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EAAE,EAChB,IAAI,EAAE,cAAc,EAAE,EAAE,GACvB,OAAO,CAAC,IAAI,CAAC,CAiBf"}
@@ -1,5 +1,8 @@
1
+ import { buildKeyMatch } from './db.js';
1
2
  import { ConditionBuilder } from 'node-condition-builder';
2
3
  import { httpError } from './errors.js';
4
+ import { resolveJoinTableConf, resolvedTenantScope } from './table-helpers.js';
5
+ import { TENANT_ADMIN } from '../types.js';
3
6
  function isIndirect(scope) {
4
7
  return 'through' in scope;
5
8
  }
@@ -31,7 +34,7 @@ export function tenantOwnColumns(scope) {
31
34
  * Relations are what makes the second case necessary — a relation is a read grant on its target
32
35
  * and a write join a write grant, so a deliberately public host must still carry its neighbours'
33
36
  * scopes into the joins and secondaries it drives. One level is the whole reach: joins resolve
34
- * from the addressed table's own `allowedReadJoins`/`allowedWriteJoins` and never chain further.
37
+ * from the addressed table's own `readJoins`/`writeJoins` and never chain further.
35
38
  *
36
39
  * When nothing scoped is in reach, `getTenantId` is not called at all — a request that cannot
37
40
  * read or write a scoped row should not pay for resolving a tenant, and consumer code that
@@ -42,17 +45,23 @@ function scopeInReach(tableConf, dbTables) {
42
45
  return true;
43
46
  if (!dbTables)
44
47
  return false;
45
- const relations = [...(tableConf.allowedReadJoins ?? []), ...(tableConf.allowedWriteJoins ?? [])];
46
- return relations.some((join) => dbTables[join.joinSchema.tableName]?.tenantScope !== undefined);
48
+ const relations = [...(tableConf.readJoins ?? []), ...(tableConf.writeJoins ?? [])];
49
+ return relations.some((join) => resolveJoinTableConf(dbTables, join)?.tenantScope !== undefined);
47
50
  }
48
51
  export async function resolveTenant(options, tableConf, request) {
49
52
  if (!options.getTenantId)
50
53
  return undefined;
51
- if (!scopeInReach(tableConf, options.DbTables))
54
+ if (!scopeInReach(tableConf, options.dbTables))
52
55
  return undefined;
53
56
  const raw = await options.getTenantId(request);
54
- if (raw == null)
55
- return undefined; // admin
57
+ // Admin is declared with the sentinel. An absent tenant is NOT an admin: it is the signature
58
+ // of an auth hook that did not run, a missing claim, a typo in `req.user.<x>` — serving any
59
+ // of them as an admin would hand out every row. Refused before any SQL exists.
60
+ if (raw === TENANT_ADMIN)
61
+ return undefined;
62
+ if (raw == null) {
63
+ throw httpError(401, 'Unauthorized: no tenant for this request (return TENANT_ADMIN from getTenantId for unrestricted access)');
64
+ }
56
65
  const ids = Array.isArray(raw) ? raw : [raw];
57
66
  // An empty list is a caller with no tenant at all — not an admin. Every consumer of `ids`
58
67
  // would emit `IN ()` (a syntax error on both dialects) or, worse, a builder could drop the
@@ -62,7 +71,7 @@ export async function resolveTenant(options, tableConf, request) {
62
71
  }
63
72
  // `scope` stays undefined for an unscoped host: the ids still travel, so the tables it reaches
64
73
  // enforce their own scopes, while the host itself keeps no filter.
65
- return { ids, scope: tableConf.tenantScope };
74
+ return { ids, scope: resolvedTenantScope(tableConf) };
66
75
  }
67
76
  /**
68
77
  * The read predicate for a scope, as a fragment every caller appends to its own WHERE.
@@ -96,16 +105,18 @@ export function buildTenantCondition(db, scope, tenantIds, ownTable) {
96
105
  * a table that declares no scope — mirroring `appendJoinTenantScope` on the read side.
97
106
  */
98
107
  export function tenantForTable(tenant, tableConf) {
99
- const scope = tableConf?.tenantScope;
108
+ const scope = resolvedTenantScope(tableConf);
100
109
  if (!tenant || !scope)
101
110
  return undefined;
102
111
  return { ids: tenant.ids, scope };
103
112
  }
104
113
  /**
105
114
  * Tenant guard as a self-contained boolean fragment, for the positions where the scope cannot
106
- * be expressed as an extra INNER JOIN: a child DELETE, a LEFT JOIN's ON clause, and the
107
- * correlated subquery of an aggregation. A direct scope compares the table's own column; an
108
- * indirect one tests the through table with a correlated EXISTS rather than a join.
115
+ * be expressed as an extra INNER JOIN: a DELETE (of the addressed table or of a child), a LEFT
116
+ * JOIN's ON clause, and the correlated subquery of an aggregation. A direct scope compares the
117
+ * table's own column; an indirect one tests the through table with a correlated EXISTS rather
118
+ * than a join — which also keeps a DELETE from reading the table it deletes from, a statement
119
+ * MySQL and MariaDB refuse (error 1093).
109
120
  *
110
121
  * `tableRef` is the name the scoped rows go by in that statement — the table name in a DELETE,
111
122
  * the join alias in an ON clause, the subquery alias inside a correlated SELECT. Returns
@@ -172,7 +183,7 @@ export function injectTenantValue(record, scope, tenantIds) {
172
183
  record[col] = tenantIds[0];
173
184
  return;
174
185
  }
175
- throw httpError(400, 'Ambiguous tenant: specify the tenant value');
186
+ throw httpError(400, 'Ambiguous tenant: specify the tenant value', { code: 'ambiguous_tenant' });
176
187
  }
177
188
  /** Checks that an indirect-scope FK really belongs to the tenant.
178
189
  * @testonly Exported only so unit tests can exercise it directly.
@@ -198,36 +209,6 @@ export async function validateTenantFK(db, scope, tenantIds, fkValues) {
198
209
  throw httpError(403, 'Access denied: records do not belong to tenant');
199
210
  }
200
211
  }
201
- /**
202
- * Build WHERE clause for DELETE with tenant filtering.
203
- * Handles both direct (simple AND) and indirect (subquery via JOIN) scopes; a tenant whose
204
- * addressed table declares no scope yields the plain primary-key clause.
205
- */
206
- export function buildTenantDeleteWhere(db, tableName, pkCol, pkValue, tenant) {
207
- const scope = tenant.scope;
208
- if (scope && isIndirect(scope)) {
209
- const innerCb = new ConditionBuilder('AND', db.cbDialect);
210
- innerCb.isIn(`${db.qi(tableName)}.${db.qi(pkCol)}`, (Array.isArray(pkValue) ? pkValue : [pkValue]));
211
- innerCb.append(buildTenantCondition(db, scope, tenant.ids, tableName));
212
- const innerWhere = innerCb.build(1, db.ph);
213
- const values = innerCb.getValues();
214
- const joinSql = buildTenantJoin(db, scope, tableName);
215
- const where = `${db.qi(pkCol)} IN (SELECT ${db.qi(tableName)}.${db.qi(pkCol)} FROM ${db.qi(tableName)} ${joinSql} WHERE ${innerWhere})`;
216
- return { where, values };
217
- }
218
- const cb = new ConditionBuilder('AND', db.cbDialect);
219
- if (Array.isArray(pkValue)) {
220
- cb.isIn(db.qi(pkCol), pkValue);
221
- }
222
- else {
223
- cb.isEqual(db.qi(pkCol), pkValue);
224
- }
225
- if (scope)
226
- cb.append(buildTenantCondition(db, scope, tenant.ids, tableName));
227
- const where = cb.build(1, db.ph);
228
- const values = cb.getValues();
229
- return { where, values };
230
- }
231
212
  /**
232
213
  * Guard the conflict target of an UPSERT (INSERT … ON CONFLICT / ON DUPLICATE KEY) on a
233
214
  * tenant-scoped table. Without this, an upsert whose conflict key matches a row owned by
@@ -406,11 +387,13 @@ export function buildTenantUpdateExtra(db, tenant) {
406
387
  return undefined;
407
388
  const cols = ownColumns(scope);
408
389
  const cb = new ConditionBuilder(cols.length > 1 ? 'OR' : 'AND', db.cbDialect);
390
+ // Quoted like every other column the plugin writes: a camelCase tenant column left bare is
391
+ // folded to lowercase by Postgres (`userId` → `userid`), and the UPDATE fails.
409
392
  for (const col of cols) {
410
393
  if (tenant.ids.length === 1)
411
- cb.isEqual(col, tenant.ids[0]);
394
+ cb.isEqual(db.qi(col), tenant.ids[0]);
412
395
  else
413
- cb.isIn(col, tenant.ids);
396
+ cb.isIn(db.qi(col), tenant.ids);
414
397
  }
415
398
  return cb;
416
399
  }
@@ -435,23 +418,24 @@ export async function assertTenantOwnership(db, tenant, tableName, pkCol, pkValu
435
418
  }
436
419
  }
437
420
  /**
438
- * Assert that EVERY pk in `ids` exists and belongs to the tenant, for both direct and indirect
439
- * scopes. Throws 404 if any id is missing or not owned. No-op when `tenant` is undefined or `ids`
440
- * is empty. Used by the delete engines to enforce tenant ownership BEFORE running a `beforeDelete`/
441
- * `beforeBulkDelete` hook, so user code never runs against rows the caller cannot access.
421
+ * Assert that EVERY key in `keys` exists and belongs to the tenant, for both direct and indirect
422
+ * scopes. Throws 404 if any key is missing or not owned. No-op when `tenant` is undefined or
423
+ * `keys` is empty. Used by the delete engines to enforce tenant ownership BEFORE running a
424
+ * `beforeDelete`/`beforeBulkDelete` hook, so user code never runs against rows the caller cannot
425
+ * access. `keys` holds one value per column of `pkCols` for each row (see `buildKeyMatch`).
442
426
  */
443
- export async function assertTenantOwnsAll(db, tenant, tableName, pkCol, ids) {
427
+ export async function assertTenantOwnsAll(db, tenant, tableName, pkCols, keys) {
444
428
  const scope = tenant?.scope;
445
- if (!tenant || !scope || !ids.length)
429
+ if (!tenant || !scope || !keys.length)
446
430
  return;
447
- const qualifiedPk = `${db.qi(tableName)}.${db.qi(pkCol)}`;
431
+ const qualified = pkCols.map((c) => `${db.qi(tableName)}.${db.qi(c)}`);
448
432
  const cb = new ConditionBuilder('AND', db.cbDialect);
449
- cb.isIn(qualifiedPk, ids);
433
+ cb.append(buildKeyMatch(db, qualified, keys));
450
434
  cb.append(buildTenantCondition(db, scope, tenant.ids, tableName));
451
435
  const join = isIndirect(scope) ? ` ${buildTenantJoin(db, scope, tableName)}` : '';
452
- const sql = `SELECT DISTINCT ${qualifiedPk} AS pk FROM ${db.qi(tableName)}${join} WHERE ${cb.build(1, db.ph)}`;
436
+ const sql = `SELECT DISTINCT ${qualified.join(', ')} FROM ${db.qi(tableName)}${join} WHERE ${cb.build(1, db.ph)}`;
453
437
  const r = await db.query(sql, cb.getValues());
454
- const uniqueRequested = new Set(ids.map((v) => String(v))).size;
438
+ const uniqueRequested = new Set(keys.map((k) => k.map(String).join('\0'))).size;
455
439
  if (r.rows.length < uniqueRequested) {
456
440
  throw httpError(404, 'Record not found');
457
441
  }
@@ -1,5 +1,5 @@
1
- import type { TSchema } from '@sinclair/typebox';
2
- import type { ITable, SchemaDefinition } from '../types.js';
1
+ import type { TSchema } from 'typebox';
2
+ import type { TableConfig, SchemaDefinition } from '../types.js';
3
3
  /**
4
4
  * Write visibility — the counterpart of `read-access.ts`.
5
5
  *
@@ -16,21 +16,27 @@ import type { ITable, SchemaDefinition } from '../types.js';
16
16
  * `additionalProperties: false` rather than a driver error — and dropped again in the engines,
17
17
  * which `sqlApi.*` reaches without passing through those schemas.
18
18
  *
19
- * This is not `excludeFromCreation`, which whitelists CLIENT input on insert only and lets a
20
- * hook assign the field afterwards (ADR 0005); nor is it the place for per-caller field rules,
19
+ * This is not `insertExclude`, which whitelists CLIENT input on insert only and lets a hook
20
+ * assign the field afterwards (ADR 0005); nor is it the place for per-caller field rules,
21
21
  * which stay in `beforeUpdate` / `validate` (ADR 0011).
22
22
  */
23
- export declare function writeExcludedFields(tableConf: ITable | undefined, schema: SchemaDefinition | undefined): Set<string>;
23
+ export declare function writeExcludedFields(tableConf: TableConfig | undefined, schema: SchemaDefinition | undefined): Set<string>;
24
24
  /**
25
25
  * A field map minus everything that may not be written. Used to build the write body schemas,
26
26
  * where the removal is what turns a rejected column into a 400 instead of a 500.
27
27
  */
28
- export declare function writableFields(fields: Record<string, TSchema>, tableConf: ITable | undefined, schema: SchemaDefinition | undefined): Record<string, TSchema>;
28
+ export declare function writableFields(fields: Record<string, TSchema>, tableConf: TableConfig | undefined, schema: SchemaDefinition | undefined): Record<string, TSchema>;
29
29
  /**
30
30
  * Drop the non-writable fields from a camelCase record, in place.
31
31
  *
32
- * Call this AFTER the write hooks, unlike `excludeFromCreation`: a hook cannot be allowed to
33
- * put back a value the database will refuse, so the last word has to belong to the exclusion.
32
+ * Call this AFTER the write hooks, unlike `insertExclude`: a hook cannot be allowed to put
33
+ * back a value the database will refuse, so the last word has to belong to the exclusion.
34
34
  */
35
- export declare function removeWriteExcluded(record: Record<string, unknown>, tableConf: ITable | undefined, schema: SchemaDefinition | undefined): void;
35
+ export declare function removeWriteExcluded(record: Record<string, unknown>, tableConf: TableConfig | undefined, schema: SchemaDefinition | undefined): void;
36
+ /**
37
+ * The fields a client may not send on insert (`insertExclude`). Every insert path — the body
38
+ * schema, the engines, the secondaries of another table, the agent manifest — reads them
39
+ * through here.
40
+ */
41
+ export declare function insertExcludedFields(tableConf: TableConfig | undefined): readonly string[];
36
42
  //# sourceMappingURL=write-access.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"write-access.d.ts","sourceRoot":"","sources":["../../src/lib/write-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,GAAG,CAAC,MAAM,CAAC,CAIb;AAUD;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAQzB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,IAAI,CAKN"}
1
+ {"version":3,"file":"write-access.d.ts","sourceRoot":"","sources":["../../src/lib/write-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEjE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,GAAG,CAAC,MAAM,CAAC,CAIb;AAUD;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAQzB;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,IAAI,CAKN;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,WAAW,GAAG,SAAS,GAAG,SAAS,MAAM,EAAE,CAE1F"}
@@ -14,8 +14,8 @@
14
14
  * `additionalProperties: false` rather than a driver error — and dropped again in the engines,
15
15
  * which `sqlApi.*` reaches without passing through those schemas.
16
16
  *
17
- * This is not `excludeFromCreation`, which whitelists CLIENT input on insert only and lets a
18
- * hook assign the field afterwards (ADR 0005); nor is it the place for per-caller field rules,
17
+ * This is not `insertExclude`, which whitelists CLIENT input on insert only and lets a hook
18
+ * assign the field afterwards (ADR 0005); nor is it the place for per-caller field rules,
19
19
  * which stay in `beforeUpdate` / `validate` (ADR 0011).
20
20
  */
21
21
  export function writeExcludedFields(tableConf, schema) {
@@ -46,8 +46,8 @@ export function writableFields(fields, tableConf, schema) {
46
46
  /**
47
47
  * Drop the non-writable fields from a camelCase record, in place.
48
48
  *
49
- * Call this AFTER the write hooks, unlike `excludeFromCreation`: a hook cannot be allowed to
50
- * put back a value the database will refuse, so the last word has to belong to the exclusion.
49
+ * Call this AFTER the write hooks, unlike `insertExclude`: a hook cannot be allowed to put
50
+ * back a value the database will refuse, so the last word has to belong to the exclusion.
51
51
  */
52
52
  export function removeWriteExcluded(record, tableConf, schema) {
53
53
  if (!hasWriteExclusions(tableConf, schema))
@@ -56,3 +56,11 @@ export function removeWriteExcluded(record, tableConf, schema) {
56
56
  delete record[field];
57
57
  }
58
58
  }
59
+ /**
60
+ * The fields a client may not send on insert (`insertExclude`). Every insert path — the body
61
+ * schema, the engines, the secondaries of another table, the agent manifest — reads them
62
+ * through here.
63
+ */
64
+ export function insertExcludedFields(tableConf) {
65
+ return tableConf?.insertExclude ?? [];
66
+ }
@@ -6,7 +6,7 @@ import type { SqlApiPluginOptions } from '../../types.js';
6
6
  *
7
7
  * Opt-in via the `agentManifest` plugin option (like `swagger`). Runs behind the same
8
8
  * global `onRequests` hooks as the data routes. The manifest is built once at startup —
9
- * `DbTables` is static configuration.
9
+ * `dbTables` is static configuration.
10
10
  */
11
11
  export default function agentManifestRoutes(fastify: FastifyInstance, options: SqlApiPluginOptions): Promise<void>;
12
12
  //# sourceMappingURL=agent-manifest.routes.d.ts.map
@@ -5,10 +5,10 @@ import { buildAgentManifest, renderAgentManifestMd } from '../../lib/agent/manif
5
5
  *
6
6
  * Opt-in via the `agentManifest` plugin option (like `swagger`). Runs behind the same
7
7
  * global `onRequests` hooks as the data routes. The manifest is built once at startup —
8
- * `DbTables` is static configuration.
8
+ * `dbTables` is static configuration.
9
9
  */
10
10
  export default async function agentManifestRoutes(fastify, options) {
11
- const manifest = buildAgentManifest(options.DbTables);
11
+ const manifest = buildAgentManifest(options.dbTables, { operations: options.operations });
12
12
  const markdown = renderAgentManifestMd(manifest);
13
13
  const onRequest = options.onRequests?.length ? options.onRequests : undefined;
14
14
  fastify.get('/agent/manifest', {
@@ -1,4 +1,4 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
- import type { SqlApiPluginOptions } from '../../types.js';
3
- export default function bulkDeleteRoutes(fastify: FastifyInstance, options: SqlApiPluginOptions): Promise<void>;
2
+ import type { RegistrationOptions } from '../sql-api-decorator.js';
3
+ export default function bulkDeleteRoutes(fastify: FastifyInstance, options: RegistrationOptions): Promise<void>;
4
4
  //# sourceMappingURL=bulk-delete.routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-delete.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/bulk-delete.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAK/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,wBAA8B,gBAAgB,CAC5C,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAmBf"}
1
+ {"version":3,"file":"bulk-delete.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/bulk-delete.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAG/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAInE,wBAA8B,gBAAgB,CAC5C,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAef"}
@@ -1,11 +1,9 @@
1
1
  import { BulkDeleteTableBody, BulkDeleteTableResponse } from '../../lib/schema/bulk-delete.js';
2
- import { primaryAsString } from '../../types.js';
3
2
  import { registerForAllTables } from './route-helpers.js';
4
3
  import { DEFAULT_MAX_BULK_ITEMS } from '../../types.js';
5
4
  export default async function bulkDeleteRoutes(fastify, options) {
6
5
  await registerForAllTables(fastify, options, {
7
6
  operation: 'bulkDelete',
8
- singlePkOnly: true,
9
7
  method: 'POST',
10
8
  url: (tableName) => `/bulk/${tableName}/delete`,
11
9
  successStatus: 200,
@@ -15,10 +13,6 @@ export default async function bulkDeleteRoutes(fastify, options) {
15
13
  }),
16
14
  summary: 'Bulk delete',
17
15
  description: (name) => `Delete multiple records from ${name} by primary key`,
18
- handle: (fastify, tableName, tc, request) => {
19
- const items = request.body;
20
- const ids = items.map((item) => item[primaryAsString(tc.primary)]);
21
- return fastify.sqlApi.bulkDelete(tableName, ids, request);
22
- },
16
+ handle: (sqlApi, tableName, _tc, request) => sqlApi.bulkDelete(tableName, request.body, request),
23
17
  });
24
18
  }
@@ -1,4 +1,4 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
- import type { SqlApiPluginOptions } from '../../types.js';
3
- export default function bulkUpsertRoutes(fastify: FastifyInstance, options: SqlApiPluginOptions): Promise<void>;
2
+ import type { RegistrationOptions } from '../sql-api-decorator.js';
3
+ export default function bulkUpsertRoutes(fastify: FastifyInstance, options: RegistrationOptions): Promise<void>;
4
4
  //# sourceMappingURL=bulk-upsert.routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-upsert.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/bulk-upsert.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI/C,OAAO,KAAK,EAAE,mBAAmB,EAAkB,MAAM,gBAAgB,CAAC;AAE1E,wBAA8B,gBAAgB,CAC5C,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAiBf"}
1
+ {"version":3,"file":"bulk-upsert.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/bulk-upsert.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAG/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAInE,wBAA8B,gBAAgB,CAC5C,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAiBf"}
@@ -13,9 +13,9 @@ export default async function bulkUpsertRoutes(fastify, options) {
13
13
  }),
14
14
  summary: 'Bulk upsert',
15
15
  description: (name, tc) => buildWriteDescription('Bulk upsert records in', name, tc),
16
- handle: (fastify, tableName, _tc, request) => {
16
+ handle: (sqlApi, tableName, _tc, request) => {
17
17
  const items = request.body;
18
- return fastify.sqlApi.bulkUpsert(tableName, items, request);
18
+ return sqlApi.bulkUpsert(tableName, items, request);
19
19
  },
20
20
  });
21
21
  }
@@ -1,4 +1,4 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
- import type { SqlApiPluginOptions } from '../../types.js';
3
- export default function deleteRoutes(fastify: FastifyInstance, options: SqlApiPluginOptions): Promise<void>;
2
+ import type { RegistrationOptions } from '../sql-api-decorator.js';
3
+ export default function deleteRoutes(fastify: FastifyInstance, options: RegistrationOptions): Promise<void>;
4
4
  //# sourceMappingURL=delete.routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"delete.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/delete.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,wBAA8B,YAAY,CACxC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAqBf"}
1
+ {"version":3,"file":"delete.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/delete.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAK/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,wBAA8B,YAAY,CACxC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAkBf"}
@@ -1,5 +1,6 @@
1
- import { Type } from '@sinclair/typebox';
1
+ import { Type } from 'typebox';
2
2
  import { primaryAsString } from '../../types.js';
3
+ import { pkParams, pkSchema } from '../../lib/schema/helpers.js';
3
4
  import { registerForAllTables } from './route-helpers.js';
4
5
  export default async function deleteRoutes(fastify, options) {
5
6
  await registerForAllTables(fastify, options, {
@@ -8,18 +9,15 @@ export default async function deleteRoutes(fastify, options) {
8
9
  method: 'DELETE',
9
10
  url: (tableName) => `/rest/${tableName}/:id`,
10
11
  successStatus: 200,
11
- schemas: (_db, _table, tc) => {
12
- const pkField = primaryAsString(tc.primary);
13
- return {
14
- params: Type.Object({ id: Type.String() }),
15
- response: Type.Object({ main: Type.Object({ [pkField]: tc.Schema.fields[pkField] }) }),
16
- };
17
- },
12
+ schemas: (_db, _table, tc) => ({
13
+ params: pkParams(tc),
14
+ response: Type.Object({ main: Type.Object(pkSchema(tc, tc.schema, primaryAsString(tc.primary))) }),
15
+ }),
18
16
  summary: 'Delete',
19
17
  description: (name) => `Delete a record from ${name} by primary key`,
20
- handle: (fastify, tableName, _tc, request) => {
18
+ handle: (sqlApi, tableName, _tc, request) => {
21
19
  const { id } = request.params;
22
- return fastify.sqlApi.delete(tableName, id, request);
20
+ return sqlApi.delete(tableName, id, request);
23
21
  },
24
22
  });
25
23
  }
@@ -1,4 +1,4 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
- import type { SqlApiPluginOptions } from '../../types.js';
3
- export default function getRoutes(fastify: FastifyInstance, options: SqlApiPluginOptions): Promise<void>;
2
+ import type { RegistrationOptions } from '../sql-api-decorator.js';
3
+ export default function getRoutes(fastify: FastifyInstance, options: RegistrationOptions): Promise<void>;
4
4
  //# sourceMappingURL=get.routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"get.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/get.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,wBAA8B,SAAS,CACrC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAkBf"}
1
+ {"version":3,"file":"get.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/get.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAEnE,wBAA8B,SAAS,CACrC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAkBf"}
@@ -1,5 +1,5 @@
1
- import { Type } from '@sinclair/typebox';
2
1
  import { GetTableResponse } from '../../lib/schema/get.js';
2
+ import { pkParams } from '../../lib/schema/helpers.js';
3
3
  import { registerForAllTables } from './route-helpers.js';
4
4
  export default async function getRoutes(fastify, options) {
5
5
  await registerForAllTables(fastify, options, {
@@ -8,15 +8,15 @@ export default async function getRoutes(fastify, options) {
8
8
  method: 'GET',
9
9
  url: (tableName) => `/rest/${tableName}/:id`,
10
10
  successStatus: 200,
11
- schemas: (db, table) => ({
12
- params: Type.Object({ id: Type.String() }),
11
+ schemas: (db, table, tc) => ({
12
+ params: pkParams(tc),
13
13
  response: GetTableResponse(db, table),
14
14
  }),
15
15
  summary: 'Get',
16
16
  description: (name) => `Get a record from ${name} by primary key`,
17
- handle: (fastify, tableName, _tc, request) => {
17
+ handle: (sqlApi, tableName, _tc, request) => {
18
18
  const { id } = request.params;
19
- return fastify.sqlApi.get(tableName, id, request);
19
+ return sqlApi.get(tableName, id, request);
20
20
  },
21
21
  });
22
22
  }
@@ -1,4 +1,4 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
- import type { SqlApiPluginOptions } from '../../types.js';
3
- export default function insertRoutes(fastify: FastifyInstance, options: SqlApiPluginOptions): Promise<void>;
2
+ import type { RegistrationOptions } from '../sql-api-decorator.js';
3
+ export default function insertRoutes(fastify: FastifyInstance, options: RegistrationOptions): Promise<void>;
4
4
  //# sourceMappingURL=insert.routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"insert.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/insert.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAG/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,wBAA8B,YAAY,CACxC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAuBf"}
1
+ {"version":3,"file":"insert.routes.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/insert.routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAG/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAGnE,wBAA8B,YAAY,CACxC,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,mBAAmB,GAC3B,OAAO,CAAC,IAAI,CAAC,CAef"}
@@ -12,12 +12,6 @@ export default async function insertRoutes(fastify, options) {
12
12
  }),
13
13
  summary: 'Insert',
14
14
  description: (name, tc) => buildWriteDescription('Insert a record into', name, tc),
15
- handle: (fastify, tableName, _tc, request) => {
16
- const body = request.body;
17
- return fastify.sqlApi.insert(tableName, {
18
- record: body.main,
19
- secondaries: body.secondaries,
20
- }, request);
21
- },
15
+ handle: (sqlApi, tableName, _tc, request) => sqlApi.insert(tableName, request.body, request),
22
16
  });
23
17
  }
@@ -1,5 +1,11 @@
1
1
  import type { FastifyInstance } from 'fastify';
2
+ import type { SqlApi } from '../../lib/sql-api.js';
2
3
  import type { SqlApiPluginOptions } from '../../types.js';
4
+ declare module 'fastify' {
5
+ interface FastifyInstance {
6
+ sqlApi: SqlApi;
7
+ }
8
+ }
3
9
  declare const _default: (fastify: FastifyInstance, options: SqlApiPluginOptions) => Promise<void>;
4
10
  export default _default;
5
11
  //# sourceMappingURL=plugin.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAgB,MAAM,SAAS,CAAC;AAc7D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;kCAuD/C,eAAe,WACf,mBAAmB,KAC3B,OAAO,CAAC,IAAI,CAAC;AAHhB,wBAsEoC"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../src/routes/auto/plugin.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAgB,MAAM,SAAS,CAAC;AAa7D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAWnD,OAAO,KAAK,EAAE,mBAAmB,EAAmB,MAAM,gBAAgB,CAAC;AAK3E,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAU,eAAe;QACvB,MAAM,EAAE,MAAM,CAAC;KAChB;CACF;kCAsEU,eAAe,WACf,mBAAmB,KAC3B,OAAO,CAAC,IAAI,CAAC;AAHhB,wBAwEoC"}