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 +1 @@
1
- {"version":3,"file":"pg-adapter.d.ts","sourceRoot":"","sources":["../../../src/lib/adapters/pg-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmC,MAAM,gBAAgB,CAAC;AAEjF,MAAM,WAAW,WAAW;IAC1B,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC;QAAE,IAAI,EAAE,CAAC,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAC;IACnD,iFAAiF;IACjF,OAAO,CAAC,IAAI,OAAO,CAAC,WAAW,GAAG;QAAE,OAAO,IAAI,IAAI,CAAA;KAAE,CAAC,CAAC;CACxD;AAeD,wBAAgB,WAAW,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,CAc1D"}
1
+ {"version":3,"file":"pg-adapter.d.ts","sourceRoot":"","sources":["../../../src/lib/adapters/pg-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAmC,MAAM,gBAAgB,CAAC;AAEjF,MAAM,WAAW,WAAW;IAC1B,KAAK,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC;QAAE,IAAI,EAAE,CAAC,EAAE,CAAC;QAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC,CAAC;IACnD;;;OAGG;IACH,OAAO,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG;QAAE,OAAO,IAAI,IAAI,CAAA;KAAE,CAAC,CAAC;CACvE;AAeD,wBAAgB,WAAW,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,CAc1D"}
@@ -1,5 +1,5 @@
1
- import type { DbTables, ITable, TableOperation } from '../../types.js';
2
- interface ManifestField {
1
+ import type { DbTables, TableConfig, TableOperation } from '../../types.js';
2
+ export interface ManifestField {
3
3
  type: string;
4
4
  /** Present (true) when the field must be sent on insert. */
5
5
  required?: boolean;
@@ -10,11 +10,16 @@ interface ManifestField {
10
10
  /** Present (true) when the field is returned by reads but refused by every write. */
11
11
  readOnly?: boolean;
12
12
  }
13
- interface ManifestJoin {
13
+ export interface ManifestJoin {
14
14
  alias: string;
15
15
  table: string;
16
16
  /** '1:N' → usable in joinMustExist/joinMultiple/joinGroup; 'N:1' → usable in joinLeft. */
17
17
  kind: '1:N' | 'N:1';
18
+ /**
19
+ * On a write join: the key its child rows upsert on. Present, the alias also takes `replace`
20
+ * — the complete set of child rows, the ones left out deleted (ADR 0029).
21
+ */
22
+ upsertKey?: string[];
18
23
  }
19
24
  export interface ManifestTable {
20
25
  /** URL segment for this table's routes. */
@@ -24,12 +29,18 @@ export interface ManifestTable {
24
29
  fields: Record<string, ManifestField>;
25
30
  /** Fields stripped from client input on insert (server-generated: PKs, timestamps). */
26
31
  serverGenerated?: string[];
27
- /** Computed (virtual) fields: usable in filters/conditions/orderBy/selectComputed. */
32
+ /**
33
+ * The key insert and bulkUpsert upsert on: a row carrying it updates the row it names.
34
+ * Every row must carry it (400 `missing_key`), except a serverGenerated key: absent, the row
35
+ * is inserted; present, it must name an existing row (400 `not_found`, ADR 0031).
36
+ */
37
+ upsertKey?: string[];
38
+ /** Computed (virtual) fields: usable in filters/conditions/orderBy/compute and listed in select (next to '*' for every readable field). */
28
39
  computed?: Record<string, string>;
29
40
  /** Extra filter names accepted in `filters` beyond schema fields. */
30
41
  extraFilters?: Record<string, string>;
31
42
  readJoins?: ManifestJoin[];
32
- /** Aliases accepted as `secondaries`/`deletions` keys in writes. */
43
+ /** Aliases accepted under `upsert`/`delete` in writes, and under `replace` when they carry an `upsertKey`. */
33
44
  writeJoins?: ManifestJoin[];
34
45
  /** Present (true) when rows are automatically scoped to the caller's tenant. */
35
46
  tenantScoped?: boolean;
@@ -38,20 +49,26 @@ export interface ManifestTable {
38
49
  export interface AgentManifest {
39
50
  tables: Record<string, ManifestTable>;
40
51
  }
41
- export declare function tableOperations(tableConf: ITable): TableOperation[];
52
+ /**
53
+ * The operations a table exposes: its own `operations` (all when omitted), within `allowed`
54
+ * — the registration's `operations` — when given, minus the single-PK ones on a composite PK.
55
+ */
56
+ export declare function tableOperations(tableConf: TableConfig, allowed?: readonly TableOperation[]): TableOperation[];
42
57
  /**
43
58
  * Build the machine-readable description of every table exposed by this deployment:
44
59
  * fields (type/required/nullable), enabled operations, join aliases, computed fields,
45
- * extra filters, tenant scoping. Derived entirely from `DbTables`, so it is always in
60
+ * extra filters, tenant scoping. Derived entirely from `dbTables`, so it is always in
46
61
  * sync with the running configuration. Pairs with AGENTS_FRONTEND.md (the request grammar)
47
- * to give an LLM client everything it needs to drive the API.
62
+ * to give an LLM client everything it needs to drive the API. `operations` is the
63
+ * registration's own, when it narrows what the tables expose.
48
64
  */
49
- export declare function buildAgentManifest(dbTables: DbTables): AgentManifest;
65
+ export declare function buildAgentManifest(dbTables: DbTables, options?: {
66
+ operations?: readonly TableOperation[];
67
+ }): AgentManifest;
50
68
  /**
51
69
  * Compact markdown rendering of the manifest, designed for an LLM system prompt.
52
70
  * Notation: `!` required on insert, `?` nullable, `(writeOnly)` never returned by reads,
53
71
  * `(readOnly)` returned by reads and refused by every write.
54
72
  */
55
73
  export declare function renderAgentManifestMd(manifest: AgentManifest): string;
56
- export {};
57
74
  //# sourceMappingURL=manifest.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../../src/lib/agent/manifest.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAkB,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAQvF,UAAU,aAAa;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,mDAAmD;IACnD,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,2FAA2F;IAC3F,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,qFAAqF;IACrF,QAAQ,CAAC,EAAE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C5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CACvC;AAiCD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,SAAS,cAAc,EAAE,GAAG,cAAc,EAAE,CAK7G;AA+DD;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,QAAQ,EAClB,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,SAAS,cAAc,EAAE,CAAA;CAAO,GACvD,aAAa,CAMf;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,CAuBrE"}
@@ -1,9 +1,7 @@
1
- import { isCompositePrimary } from '../../types.js';
2
- import { writeExcludedFields } from '../write-access.js';
3
- const ALL_OPERATIONS = [
4
- 'search', 'get', 'insert', 'update', 'delete', 'bulkUpsert', 'bulkDelete',
5
- ];
6
- const SINGLE_PK_OPERATIONS = new Set(['get', 'delete', 'bulkDelete']);
1
+ import { isCompositePrimary, TABLE_OPERATIONS } from '../../types.js';
2
+ import { extraFilterFields } from '../read-access.js';
3
+ import { writeExcludedFields, insertExcludedFields } from '../write-access.js';
4
+ const SINGLE_PK_OPERATIONS = new Set(['get', 'delete']);
7
5
  function shortType(schema) {
8
6
  if (!schema)
9
7
  return 'any';
@@ -14,7 +12,9 @@ function shortType(schema) {
14
12
  return types[0] ?? 'any';
15
13
  }
16
14
  function isNullable(schema) {
17
- const t = schema?.type;
15
+ if (!schema)
16
+ return false;
17
+ const t = schema.type;
18
18
  return Array.isArray(t) && t.includes('null');
19
19
  }
20
20
  function computedTypes(tableConf) {
@@ -35,15 +35,20 @@ function computedTypes(tableConf) {
35
35
  }
36
36
  return Object.keys(out).length ? out : undefined;
37
37
  }
38
- export function tableOperations(tableConf) {
39
- const requested = tableConf.operations ?? ALL_OPERATIONS;
38
+ /**
39
+ * The operations a table exposes: its own `operations` (all when omitted), within `allowed`
40
+ * — the registration's `operations` — when given, minus the single-PK ones on a composite PK.
41
+ */
42
+ export function tableOperations(tableConf, allowed) {
43
+ const requested = (tableConf.operations ?? TABLE_OPERATIONS)
44
+ .filter((op) => !allowed || allowed.includes(op));
40
45
  if (!isCompositePrimary(tableConf.primary))
41
- return [...requested];
46
+ return requested;
42
47
  return requested.filter((op) => !SINGLE_PK_OPERATIONS.has(op));
43
48
  }
44
49
  /** Field descriptors: type, plus the flags an agent needs to build a valid payload. */
45
50
  function manifestFields(tableConf) {
46
- const schema = tableConf.Schema;
51
+ const schema = tableConf.schema;
47
52
  const required = new Set((schema.validation.required) ?? []);
48
53
  const readExcluded = new Set(tableConf.readExclude ?? []);
49
54
  const writeExcluded = writeExcludedFields(tableConf, schema);
@@ -67,28 +72,32 @@ function manifestJoins(joins) {
67
72
  alias: j.alias,
68
73
  table: j.joinSchema.tableName,
69
74
  kind: j.unique ? 'N:1' : '1:N',
75
+ ...(j.upsertKey ? { upsertKey: [...j.upsertKey] } : {}),
70
76
  }));
71
77
  }
72
78
  function manifestExtraFilters(tableConf) {
73
- const entries = Object.entries(tableConf.extraFilters ?? {});
79
+ const entries = Object.entries(extraFilterFields(tableConf));
74
80
  if (entries.length === 0)
75
81
  return undefined;
76
82
  return Object.fromEntries(entries.map(([n, s]) => [n, shortType(s)]));
77
83
  }
78
84
  /** One table's entry. Optional keys are omitted entirely when empty, to keep the prompt small. */
79
- function manifestTable(tableConf) {
85
+ function manifestTable(tableConf, allowed) {
80
86
  const entry = {
81
- table: tableConf.Schema.tableName,
87
+ table: tableConf.schema.tableName,
82
88
  primary: tableConf.primary,
83
- operations: tableOperations(tableConf),
89
+ operations: tableOperations(tableConf, allowed),
84
90
  fields: manifestFields(tableConf),
85
91
  };
86
92
  const computed = computedTypes(tableConf);
87
93
  const extraFilters = manifestExtraFilters(tableConf);
88
- const readJoins = manifestJoins(tableConf.allowedReadJoins);
89
- const writeJoins = manifestJoins(tableConf.allowedWriteJoins);
90
- if (tableConf.excludeFromCreation?.length)
91
- entry.serverGenerated = [...tableConf.excludeFromCreation];
94
+ const readJoins = manifestJoins(tableConf.readJoins);
95
+ const writeJoins = manifestJoins(tableConf.writeJoins);
96
+ const serverGenerated = insertExcludedFields(tableConf);
97
+ if (serverGenerated.length)
98
+ entry.serverGenerated = [...serverGenerated];
99
+ if (tableConf.upsertKey)
100
+ entry.upsertKey = [...tableConf.upsertKey];
92
101
  if (computed)
93
102
  entry.computed = computed;
94
103
  if (extraFilters)
@@ -106,14 +115,15 @@ function manifestTable(tableConf) {
106
115
  /**
107
116
  * Build the machine-readable description of every table exposed by this deployment:
108
117
  * fields (type/required/nullable), enabled operations, join aliases, computed fields,
109
- * extra filters, tenant scoping. Derived entirely from `DbTables`, so it is always in
118
+ * extra filters, tenant scoping. Derived entirely from `dbTables`, so it is always in
110
119
  * sync with the running configuration. Pairs with AGENTS_FRONTEND.md (the request grammar)
111
- * to give an LLM client everything it needs to drive the API.
120
+ * to give an LLM client everything it needs to drive the API. `operations` is the
121
+ * registration's own, when it narrows what the tables expose.
112
122
  */
113
- export function buildAgentManifest(dbTables) {
123
+ export function buildAgentManifest(dbTables, options = {}) {
114
124
  const tables = {};
115
125
  for (const [key, tableConf] of Object.entries(dbTables)) {
116
- tables[key] = manifestTable(tableConf);
126
+ tables[key] = manifestTable(tableConf, options.operations);
117
127
  }
118
128
  return { tables };
119
129
  }
@@ -128,9 +138,13 @@ export function renderAgentManifestMd(manifest) {
128
138
  '',
129
139
  'Notation: `!`=required on insert, `?`=nullable, `(writeOnly)`=writable, never in reads, ' +
130
140
  '`(readOnly)`=returned by reads, refused by every write (omit it from write payloads).',
131
- 'serverGenerated fields: omit on insert (values from client are ignored).',
141
+ 'serverGenerated fields: omit on insert (values from client are ignored), except in the upsertKey.',
142
+ 'upsertKey: insert and bulkUpsert update the row with that key; every row must carry it ' +
143
+ '(400 missing_key), except a serverGenerated key: absent → new row, present → must name an ' +
144
+ 'existing row (400 not_found).',
132
145
  'readJoins aliases: `1:N` → joinMustExist/joinMultiple/joinGroup; `N:1` → joinLeft.',
133
- 'writeJoins aliases: keys for `secondaries`/`deletions` in writes.',
146
+ 'writeJoins aliases: keys for `upsert`/`delete` in writes. `[key]`: the upsert key; such an ' +
147
+ 'alias also takes `replace`, the complete set of child rows (a row left out is deleted).',
134
148
  'filters: unknown keys are rejected (400), never ignored. extraFilters do not apply ' +
135
149
  'under joinLeft — use joinMustExist on the same relation.',
136
150
  '',
@@ -170,6 +184,8 @@ function renderTableMd(t) {
170
184
  lines.push(`fields: ${fieldParts.join(', ')}`);
171
185
  if (t.serverGenerated)
172
186
  lines.push(`serverGenerated: ${t.serverGenerated.join(', ')}`);
187
+ if (t.upsertKey)
188
+ lines.push(`upsertKey: ${t.upsertKey.join(', ')}`);
173
189
  if (t.computed)
174
190
  lines.push(`computed: ${namedTypes(t.computed)}`);
175
191
  if (t.extraFilters)
@@ -179,7 +195,8 @@ function renderTableMd(t) {
179
195
  lines.push(`readJoins: ${readJoins.join(', ')}`);
180
196
  }
181
197
  if (t.writeJoins) {
182
- const writeJoins = t.writeJoins.map((j) => `${j.alias}→${j.table}`);
198
+ const keyOf = (j) => (j.upsertKey ? '[' + j.upsertKey.join('+') + ']' : '');
199
+ const writeJoins = t.writeJoins.map((j) => `${j.alias}→${j.table}${keyOf(j)}`);
183
200
  lines.push(`writeJoins: ${writeJoins.join(', ')}`);
184
201
  }
185
202
  if (t.defaultOrder)
@@ -1,9 +1,8 @@
1
- import type { DbTables } from '../../types.js';
1
+ import type { DbTables, TableOperation } from '../../types.js';
2
2
  export interface AgentToolSchemas {
3
- /** POST /search/{table}: `body` + `querystring` (orderBy/page/itemsPerPage/compute*). */
3
+ /** POST /search/{table}: the whole request, `orderBy`/`paginator`/`compute` included. */
4
4
  search?: {
5
5
  body: object;
6
- querystring: object;
7
6
  };
8
7
  insert?: {
9
8
  body: object;
@@ -22,7 +21,8 @@ export interface AgentToolSchemas {
22
21
  * Ready-to-use JSON Schemas for exposing a table's operations as strict LLM tools —
23
22
  * the same TypeBox schemas the HTTP routes validate with (TypeBox objects ARE plain
24
23
  * JSON Schema). Only the operations actually enabled for the table are included
25
- * (`operations` whitelist, composite-PK rules). `get` and `delete` take a single PK
24
+ * (`operations` whitelist, composite-PK rules). `opts` mirrors the plugin options of the
25
+ * registration the tools call: its caps and its `operations`. `get` and `delete` take a single PK
26
26
  * path param and need no schema.
27
27
  *
28
28
  * Strict tools trade prompt size for provider-side validation; the lighter
@@ -32,5 +32,6 @@ export interface AgentToolSchemas {
32
32
  export declare function agentToolSchemas(dbTables: DbTables, tableName: string, opts?: {
33
33
  maxItemsPerPage?: number;
34
34
  maxBulkItems?: number;
35
+ operations?: TableOperation[];
35
36
  }): AgentToolSchemas;
36
37
  //# sourceMappingURL=tool-schemas.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-schemas.d.ts","sourceRoot":"","sources":["../../../src/lib/agent/tool-schemas.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C,MAAM,WAAW,gBAAgB;IAC/B,yFAAyF;IACzF,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC;IAC/C,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9B,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CAC/B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,EACjB,IAAI,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,GACzD,gBAAgB,CA6BlB"}
1
+ {"version":3,"file":"tool-schemas.d.ts","sourceRoot":"","sources":["../../../src/lib/agent/tool-schemas.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAE/D,MAAM,WAAW,gBAAgB;IAC/B,yFAAyF;IACzF,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,MAAM,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1B,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9B,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CAC/B;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,EACjB,IAAI,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,cAAc,EAAE,CAAA;CAAE,GACxF,gBAAgB,CA4BlB"}
@@ -1,4 +1,4 @@
1
- import { SearchTableBodyPost, SearchTableQuery } from '../schema/search.js';
1
+ import { SearchTableBodyPost } from '../schema/search.js';
2
2
  import { InsertTableBody } from '../schema/insert.js';
3
3
  import { UpdateTableBody } from '../schema/update.js';
4
4
  import { BulkUpsertTableBody } from '../schema/bulk-upsert.js';
@@ -9,7 +9,8 @@ import { DEFAULT_MAX_ITEMS_PER_PAGE, DEFAULT_MAX_BULK_ITEMS } from '../../types.
9
9
  * Ready-to-use JSON Schemas for exposing a table's operations as strict LLM tools —
10
10
  * the same TypeBox schemas the HTTP routes validate with (TypeBox objects ARE plain
11
11
  * JSON Schema). Only the operations actually enabled for the table are included
12
- * (`operations` whitelist, composite-PK rules). `get` and `delete` take a single PK
12
+ * (`operations` whitelist, composite-PK rules). `opts` mirrors the plugin options of the
13
+ * registration the tools call: its caps and its `operations`. `get` and `delete` take a single PK
13
14
  * path param and need no schema.
14
15
  *
15
16
  * Strict tools trade prompt size for provider-side validation; the lighter
@@ -21,12 +22,11 @@ export function agentToolSchemas(dbTables, tableName, opts) {
21
22
  if (!tableConf) {
22
23
  throw new Error(`Unknown table "${tableName}". Available: ${Object.keys(dbTables).join(', ')}`);
23
24
  }
24
- const ops = new Set(tableOperations(tableConf));
25
+ const ops = new Set(tableOperations(tableConf, opts?.operations));
25
26
  const out = {};
26
27
  if (ops.has('search')) {
27
28
  out.search = {
28
- body: SearchTableBodyPost(dbTables, tableName),
29
- querystring: SearchTableQuery(opts?.maxItemsPerPage ?? DEFAULT_MAX_ITEMS_PER_PAGE),
29
+ body: SearchTableBodyPost(dbTables, tableName, opts?.maxItemsPerPage ?? DEFAULT_MAX_ITEMS_PER_PAGE),
30
30
  };
31
31
  }
32
32
  if (ops.has('insert'))
@@ -1,3 +1,38 @@
1
- import type { SqlApiConfig } from '../../types.js';
2
- export declare function loadConfig(): Promise<SqlApiConfig>;
1
+ import type { CliConfig, DialectName } from '../../types.js';
2
+ /** The configuration the CLI runs with: the user's over the defaults. */
3
+ type ResolvedCliConfig = CliConfig & {
4
+ outputDir: string;
5
+ schema: string;
6
+ };
7
+ /**
8
+ * Load the CLI configuration of the project in `cwd`.
9
+ *
10
+ * The project's `.env` is read first, so the config can name the variables it holds
11
+ * (`connection: process.env.SHOP_DB_URL`); a variable already set in the environment wins over
12
+ * the file. A config that fails to load, or that carries a key the CLI does not know, is an
13
+ * error: run on a half-read config, the generator would introspect the wrong database or write
14
+ * where nobody looks.
15
+ */
16
+ export declare function loadConfig(cwd?: string): Promise<ResolvedCliConfig>;
17
+ /** The database the CLI introspects: its URL, and the dialect its scheme names. */
18
+ export interface DbConnection {
19
+ dialect: DialectName;
20
+ url: string;
21
+ }
22
+ /**
23
+ * Pick the connection URL: `--url` first, then `connection` in the config, then `DATABASE_URL`.
24
+ * There is no default database: with none of the three the CLI stops and says how to give one.
25
+ *
26
+ * A `connection` key present in the config but empty is an error of its own rather than a fall
27
+ * back to `DATABASE_URL`: it is how `connection: process.env.SHOP_DB_URL` reads when that
28
+ * variable is missing, and falling back would introspect another database without a word.
29
+ */
30
+ export declare function resolveConnection(input: {
31
+ url?: string;
32
+ config: Pick<CliConfig, 'connection'>;
33
+ env: NodeJS.ProcessEnv;
34
+ }): DbConnection;
35
+ /** A URL `resolveConnection` accepted, with its password replaced by `***`, for output. */
36
+ export declare function maskPassword(url: string): string;
37
+ export {};
3
38
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/lib/cli/config.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAOnD,wBAAsB,UAAU,IAAI,OAAO,CAAC,YAAY,CAAC,CAyBxD"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../../src/lib/cli/config.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7D,yEAAyE;AACzE,KAAK,iBAAiB,GAAG,SAAS,GAAG;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAsB3E;;;;;;;;GAQG;AACH,wBAAsB,UAAU,CAAC,GAAG,GAAE,MAAsB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAiBxF;AAeD,mFAAmF;AACnF,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,WAAW,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;CACb;AASD;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;IACtC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;CACxB,GAAG,YAAY,CAwBf;AAwBD,2FAA2F;AAC3F,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAKhD"}
@@ -5,25 +5,115 @@ const DEFAULTS = {
5
5
  outputDir: './src/db',
6
6
  schema: 'public',
7
7
  };
8
- export async function loadConfig() {
9
- const candidates = ['sqlapi.config.ts', 'sqlapi.config.mjs', 'sqlapi.config.js'];
10
- const configPath = candidates
11
- .map((f) => resolve(process.cwd(), f))
12
- .find((p) => existsSync(p)) ?? null;
13
- if (!configPath) {
8
+ const CONFIG_FILES = ['sqlapi.config.ts', 'sqlapi.config.mjs', 'sqlapi.config.js'];
9
+ /** Every key `CliConfig` has: anything else in the file is a typo the CLI would otherwise ignore. */
10
+ const KNOWN_KEYS = new Set([
11
+ 'connection', 'outputDir', 'schema', 'excludeTables', 'excludeColumns',
12
+ ]);
13
+ /** Keys retired in 1.0, each with what replaces it. */
14
+ const RETIRED_KEYS = {
15
+ dialect: 'the dialect is the scheme of the connection URL (postgres://, mysql://, mariadb://)',
16
+ envFile: "a .env in the current directory is read before the config; for another file, call " +
17
+ "process.loadEnvFile('<file>') at the top of the config",
18
+ };
19
+ /**
20
+ * Load the CLI configuration of the project in `cwd`.
21
+ *
22
+ * The project's `.env` is read first, so the config can name the variables it holds
23
+ * (`connection: process.env.SHOP_DB_URL`); a variable already set in the environment wins over
24
+ * the file. A config that fails to load, or that carries a key the CLI does not know, is an
25
+ * error: run on a half-read config, the generator would introspect the wrong database or write
26
+ * where nobody looks.
27
+ */
28
+ export async function loadConfig(cwd = process.cwd()) {
29
+ const envPath = resolve(cwd, '.env');
30
+ if (existsSync(envPath))
31
+ process.loadEnvFile(envPath);
32
+ const configPath = CONFIG_FILES.map((f) => resolve(cwd, f)).find((p) => existsSync(p));
33
+ if (!configPath)
14
34
  return { ...DEFAULTS };
15
- }
35
+ let userConfig;
16
36
  try {
17
- const configUrl = pathToFileURL(configPath).href;
18
- const mod = await import(configUrl);
19
- const userConfig = mod.default ?? mod;
20
- return {
21
- ...DEFAULTS,
22
- ...userConfig,
23
- };
37
+ const mod = await import(pathToFileURL(configPath).href);
38
+ userConfig = mod.default ?? mod;
24
39
  }
25
40
  catch (err) {
26
- console.warn(`Warning: failed to load ${configPath}, using defaults. Error: ${err.message}`);
27
- return { ...DEFAULTS };
41
+ throw new Error(`failed to load ${configPath}: ${err.message}`, { cause: err });
42
+ }
43
+ checkConfigKeys(userConfig, configPath);
44
+ return { ...DEFAULTS, ...userConfig };
45
+ }
46
+ function checkConfigKeys(userConfig, configPath) {
47
+ for (const key of Object.keys(userConfig)) {
48
+ if (Object.hasOwn(RETIRED_KEYS, key)) {
49
+ throw new Error(`${configPath}: '${key}' was removed in 1.0: ${RETIRED_KEYS[key]}`);
50
+ }
51
+ if (!KNOWN_KEYS.has(key)) {
52
+ throw new Error(`${configPath}: unknown key '${key}'. Known keys: ${[...KNOWN_KEYS].join(', ')}`);
53
+ }
54
+ }
55
+ }
56
+ const SCHEME_DIALECTS = {
57
+ 'postgres:': 'postgres',
58
+ 'postgresql:': 'postgres',
59
+ 'mysql:': 'mysql',
60
+ 'mariadb:': 'mariadb',
61
+ };
62
+ /**
63
+ * Pick the connection URL: `--url` first, then `connection` in the config, then `DATABASE_URL`.
64
+ * There is no default database: with none of the three the CLI stops and says how to give one.
65
+ *
66
+ * A `connection` key present in the config but empty is an error of its own rather than a fall
67
+ * back to `DATABASE_URL`: it is how `connection: process.env.SHOP_DB_URL` reads when that
68
+ * variable is missing, and falling back would introspect another database without a word.
69
+ */
70
+ export function resolveConnection(input) {
71
+ const { url, config, env } = input;
72
+ let chosen;
73
+ if (url) {
74
+ chosen = url;
75
+ }
76
+ else if (Object.hasOwn(config, 'connection')) {
77
+ if (!config.connection) {
78
+ throw new Error("sqlapi.config: 'connection' is empty: is the environment variable it reads set " +
79
+ '(in the environment or in the .env of the current directory)?');
80
+ }
81
+ chosen = config.connection;
28
82
  }
83
+ else {
84
+ chosen = env.DATABASE_URL;
85
+ }
86
+ if (!chosen) {
87
+ throw new Error('no database to introspect: pass --url <url>, set `connection` in sqlapi.config.ts, ' +
88
+ 'or set DATABASE_URL (in the environment or in the .env of the current directory)');
89
+ }
90
+ return { dialect: dialectOfUrl(chosen), url: chosen };
91
+ }
92
+ /** `scheme://`: without it `host:5432` would parse as a URL whose scheme is `host:`. */
93
+ const URL_SHAPE = /^[a-z][a-z0-9+.-]*:\/\//i;
94
+ function dialectOfUrl(url) {
95
+ let protocol;
96
+ try {
97
+ if (!URL_SHAPE.test(url))
98
+ throw new TypeError('no scheme');
99
+ protocol = new URL(url).protocol;
100
+ }
101
+ catch {
102
+ // The input is not echoed: it may carry a password, and it cannot be parsed to mask it.
103
+ throw new Error('the connection is not a valid connection URL (e.g. postgres://user:pass@host:5432/db)');
104
+ }
105
+ const dialect = SCHEME_DIALECTS[protocol];
106
+ if (!dialect) {
107
+ throw new Error(`unsupported connection URL scheme '${protocol}': use ` +
108
+ Object.keys(SCHEME_DIALECTS).map((s) => `${s}//`).join(', '));
109
+ }
110
+ return dialect;
111
+ }
112
+ /** A URL `resolveConnection` accepted, with its password replaced by `***`, for output. */
113
+ export function maskPassword(url) {
114
+ const parsed = new URL(url);
115
+ if (!parsed.password)
116
+ return url;
117
+ parsed.password = '***';
118
+ return parsed.href;
29
119
  }
@@ -27,7 +27,12 @@ interface MysqlColumnRow {
27
27
  TABLE_TYPE?: string;
28
28
  table_type?: string;
29
29
  }
30
- export declare function buildMysqlConnectionConfig(): MysqlConnectionConfig;
30
+ /**
31
+ * The driver config of a `mysql://` or `mariadb://` URL. Credentials are percent-decoded, as a
32
+ * URL carries a password holding `@` or `/` encoded. The database is required: it is also the
33
+ * schema MySQL introspects.
34
+ */
35
+ export declare function buildMysqlConnectionConfig(connectionUrl: string): MysqlConnectionConfig;
31
36
  /**
32
37
  * One `information_schema.columns` row as the generator sees it.
33
38
  *
@@ -1 +1 @@
1
- {"version":3,"file":"mysql-introspect.d.ts","sourceRoot":"","sources":["../../../src/lib/cli/mysql-introspect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAyBD,oFAAoF;AACpF,UAAU,cAAc;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qBAAqB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,qBAAqB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,wBAAgB,0BAA0B,IAAI,qBAAqB,CAmBlE;AAyED;;;;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AC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,aAAa,EAAE,MAAM,GAAG,qBAAqB,CAavF;AAyED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,cAAc,GAAG,UAAU,CAejE;AAED,wBAAsB,qBAAqB,CACzC,gBAAgB,EAAE,qBAAqB,EACvC,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,UAAU,EAAE,CAAC,CA+CvB"}
@@ -1,21 +1,21 @@
1
1
  import { loadOptionalDependency } from './load-dependency.js';
2
- export function buildMysqlConnectionConfig() {
3
- if (process.env.DATABASE_URL) {
4
- const url = new URL(process.env.DATABASE_URL);
5
- return {
6
- host: url.hostname,
7
- port: parseInt(url.port || '3306', 10),
8
- user: url.username,
9
- password: url.password,
10
- database: url.pathname.replace('/', ''),
11
- };
2
+ /**
3
+ * The driver config of a `mysql://` or `mariadb://` URL. Credentials are percent-decoded, as a
4
+ * URL carries a password holding `@` or `/` encoded. The database is required: it is also the
5
+ * schema MySQL introspects.
6
+ */
7
+ export function buildMysqlConnectionConfig(connectionUrl) {
8
+ const url = new URL(connectionUrl);
9
+ const database = decodeURIComponent(url.pathname.replace(/^\//, ''));
10
+ if (!database) {
11
+ throw new Error('the MySQL/MariaDB connection URL names no database (…@host:3306/<database>)');
12
12
  }
13
13
  return {
14
- host: process.env.MYSQL_HOST || '127.0.0.1',
15
- port: parseInt(process.env.MYSQL_PORT || '3306', 10),
16
- user: process.env.MYSQL_USER || 'test',
17
- password: process.env.MYSQL_PASSWORD || 'test',
18
- database: process.env.MYSQL_DB || 'testdb',
14
+ host: url.hostname,
15
+ port: parseInt(url.port || '3306', 10),
16
+ user: decodeURIComponent(url.username),
17
+ password: decodeURIComponent(url.password),
18
+ database,
19
19
  };
20
20
  }
21
21
  // Map MySQL DATA_TYPE to equivalent PG udt_name for schema-codegen compatibility
@@ -1,4 +1,3 @@
1
1
  import type { ColumnInfo } from '../../types.js';
2
- export declare function buildConnectionString(): string;
3
2
  export declare function introspectTables(connectionString: string, schema: string): Promise<ColumnInfo[]>;
4
3
  //# sourceMappingURL=pg-introspect.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pg-introspect.d.ts","sourceRoot":"","sources":["../../../src/lib/cli/pg-introspect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAmBjD,wBAAgB,qBAAqB,IAAI,MAAM,CAY9C;AAgBD,wBAAsB,gBAAgB,CACpC,gBAAgB,EAAE,MAAM,EACxB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,UAAU,EAAE,CAAC,CAsFvB"}
1
+ {"version":3,"file":"pg-introspect.d.ts","sourceRoot":"","sources":["../../../src/lib/cli/pg-introspect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAiCjD,wBAAsB,gBAAgB,CACpC,gBAAgB,EAAE,MAAM,EACxB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,UAAU,EAAE,CAAC,CAsFvB"}
@@ -1,15 +1,4 @@
1
1
  import { loadOptionalDependency } from './load-dependency.js';
2
- export function buildConnectionString() {
3
- if (process.env.DATABASE_URL) {
4
- return process.env.DATABASE_URL;
5
- }
6
- const host = process.env.POSTGRES_HOST || '127.0.0.1';
7
- const port = process.env.POSTGRES_PORT || '5433';
8
- const user = process.env.POSTGRES_USER || 'test';
9
- const password = process.env.POSTGRES_PASSWORD || 'test';
10
- const db = process.env.POSTGRES_DB || 'testdb';
11
- return `postgres://${user}:${password}@${host}:${port}/${db}`;
12
- }
13
2
  export async function introspectTables(connectionString, schema) {
14
3
  const pg = loadOptionalDependency('pg', 'npm install pg');
15
4
  const client = new pg.Client({ connectionString });
@@ -17,8 +6,8 @@ export async function introspectTables(connectionString, schema) {
17
6
  await client.connect();
18
7
  const result = await client.query(
19
8
  // The UNION picks up materialized views, which `information_schema` does not describe at
20
- // all: they live only in `pg_catalog`, and without this half they were silently absent
21
- // from every generation run. Their columns are cast to the same shapes the standard view
9
+ // all: they live only in `pg_catalog`, and without this half they would be silently
10
+ // absent from every generation run. Their columns are cast to the same shapes the standard view
22
11
  // returns, so the two halves stay union-compatible.
23
12
  `SELECT * FROM (
24
13
  SELECT c.table_name::text, c.column_name::text, c.udt_name::text,
@@ -23,9 +23,5 @@ export declare function parseSchemaFile(content: string): ParsedSchema | null;
23
23
  export declare function detectRelations(schemas: ParsedSchema[]): DetectedRelation[];
24
24
  export declare function generateSingleTableFile(schema: ParsedSchema, allSchemas: ParsedSchema[]): string;
25
25
  export declare function generateDbTablesIndex(schemas: ParsedSchema[]): string;
26
- /** Legacy single-file DbTables generator.
27
- * @testonly Exported only so unit tests can exercise it directly.
28
- */
29
- export declare function generateTablesFile(schemas: ParsedSchema[]): string;
30
26
  export {};
31
27
  //# sourceMappingURL=tables-codegen.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tables-codegen.d.ts","sourceRoot":"","sources":["../../../src/lib/cli/tables-codegen.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,YAAY;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACnC,0FAA0F;IAC1F,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,uFAAuF;IACvF,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,kFAAkF;IAClF,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,UAAU,gBAAgB;IACxB,gBAAgB,EAAE,MAAM,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;CACpB;AAID,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,YAA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