fastify-auto-sqlapi 0.5.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +246 -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 +93 -27
  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 -64
  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 +25 -16
  91. package/dist/lib/read-access.d.ts.map +1 -1
  92. package/dist/lib/read-access.js +33 -17
  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,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,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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;;;;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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eAAe,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,gBAAgB,EAAE,CAwB3E;AAgID,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,MAAM,CAiFhG;AAID,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,MAAM,CAqBrE"}
@@ -70,7 +70,7 @@ function detectPrimaryKey(schema) {
70
70
  ? { pk: 'id', autoIncrement: false, source: 'inferred' }
71
71
  : { pk: PK_PLACEHOLDER, autoIncrement: false, source: 'unresolved' };
72
72
  }
73
- // Heuristic fallback for hand-written/legacy schema files without primaryKey.
73
+ // Heuristic fallback for a schema file without primaryKey (written by hand).
74
74
  if (schema.fields.includes('id')) {
75
75
  return {
76
76
  pk: 'id',
@@ -192,13 +192,13 @@ function schemaOverridesLine(schema, pk) {
192
192
  function tenantScopeLine(childRels) {
193
193
  const rel = childRels[0];
194
194
  if (!rel)
195
- return ` // tenantScope: { column: 'tenant_col' },`;
196
- return ` // tenantScope: { column: 'tenant_col', through: { schema: ${rel.parentSchemaName}, localField: '${rel.childField}', foreignField: '${rel.parentField}' } },`;
195
+ return ` // tenantScope: { column: 'organizationId' },`;
196
+ return ` // tenantScope: { column: 'organizationId', through: { schema: ${rel.parentSchemaName}, localField: '${rel.childField}', foreignField: '${rel.parentField}' } },`;
197
197
  }
198
- function allowedReadJoinsLines(parentRels) {
198
+ function readJoinsLines(parentRels) {
199
199
  if (parentRels.length === 0)
200
- return [` // allowedReadJoins: [],`];
201
- const lines = [` // allowedReadJoins: [`];
200
+ return [` // readJoins: [],`];
201
+ const lines = [` // readJoins: [`];
202
202
  for (const rel of parentRels) {
203
203
  lines.push(` // buildRelation(${rel.parentSchemaName}, '${rel.parentField}', ${rel.childSchemaName}, '${rel.childField}'),`);
204
204
  }
@@ -253,8 +253,8 @@ export function generateSingleTableFile(schema, allSchemas) {
253
253
  const relatedSchemas = collectRelatedSchemas(schema.schemaName, parentRels, childRels);
254
254
  const lines = [];
255
255
  // Imports
256
- lines.push(`import {defineTable, exportTableInfo, Type} from 'fastify-auto-sqlapi';`);
257
- lines.push(`import type {ValidationError} from 'fastify-auto-sqlapi';`);
256
+ lines.push(`import {defineTable, Type} from 'fastify-auto-sqlapi';`);
257
+ lines.push(`import type {ValidatorResult} from 'fastify-auto-sqlapi';`);
258
258
  lines.push(`import {${schema.schemaName} as Schema} from '../schemas/${schema.schemaName}.js';`);
259
259
  // Commented imports for related schemas
260
260
  for (const relSchema of relatedSchemas) {
@@ -262,54 +262,48 @@ export function generateSingleTableFile(schema, allSchemas) {
262
262
  }
263
263
  lines.push(``);
264
264
  // Extra filters placeholder
265
- lines.push(`// const extraFiltersValidation = Type.Object({`);
266
- lines.push(`// q: Type.String(),`);
267
- lines.push(`// });`);
268
265
  // Table definition
269
266
  lines.push(``);
270
267
  lines.push(...viewNotice(schema, source));
271
268
  lines.push(`// Fields: ${schema.fields.join(', ')}`);
272
269
  lines.push(`export const ${tableVarName} = defineTable({`);
273
270
  lines.push(` primary: ${formatPrimary(pk)},`);
274
- lines.push(` ...exportTableInfo(Schema),`);
271
+ lines.push(` schema: Schema,`);
275
272
  // Commented example with extraFilters + extendedCondition
276
- lines.push(` // ...exportTableInfo(`);
277
- lines.push(` // Schema,`);
278
- lines.push(` // extraFiltersValidation,`);
279
- lines.push(` // (condition, filters) => {`);
280
- lines.push(` // // Prefix columns with the table name: the query may carry joins, and a`);
281
- lines.push(` // // bare column shared with a joined table would be ambiguous.`);
282
- lines.push(` // if (filters.q) condition.isILike(\`\${Schema.tableName}.\${Schema.col('${schema.fields.includes('name') ? 'name' : schema.fields[0]}')}\`, \`%\${filters.q}%\`);`);
283
- lines.push(` // }`);
284
- lines.push(` // ),`);
273
+ lines.push(` // extraFilters: { q: Type.String() },`);
274
+ lines.push(` // extendedCondition: (condition, filters) => {`);
275
+ lines.push(` // // Prefix columns with the table name: the query may carry joins, and a`);
276
+ lines.push(` // // bare column shared with a joined table would be ambiguous.`);
277
+ lines.push(` // if (filters.q) condition.isILike(\`\${Schema.tableName}.\${Schema.col('${schema.fields.includes('name') ? 'name' : schema.fields[0]}')}\`, \`%\${filters.q}%\`);`);
278
+ lines.push(` // },`);
285
279
  lines.push(` defaultOrder: '${defaultOrderField(schema, pk, source)}',`);
286
280
  lines.push(...viewOperationsLine(schema, source));
287
281
  // A view is never inserted into by the auto routes as generated, so the creation whitelist
288
282
  // would be a line about an operation that is not exposed.
289
283
  if (!schema.isView) {
290
284
  if (autoIncrement) {
291
- lines.push(` excludeFromCreation: ['${pkFirst(pk)}'],`);
285
+ lines.push(` insertExclude: ['${pkFirst(pk)}'],`);
292
286
  }
293
287
  else {
294
- lines.push(` // excludeFromCreation: [],`);
288
+ lines.push(` // insertExclude: [],`);
295
289
  }
296
290
  }
297
291
  // Hide columns from every read (writes still accept them, e.g. a password hash)
298
292
  lines.push(` // readExclude: [],`);
299
293
  lines.push(...writeExcludeLines(schema));
300
- lines.push(...allowedReadJoinsLines(parentRels));
294
+ lines.push(...readJoinsLines(parentRels));
301
295
  const upsertPk = pkFields(pk).map((p) => `'${p}'`).join(', ');
302
- lines.push(` // upsertMap: buildUpsertRules(buildUpsertRule(Schema, [${upsertPk}])),`);
296
+ lines.push(` // upsertKey: [${upsertPk}],`);
303
297
  lines.push(schemaOverridesLine(schema, pk));
304
298
  // validate: use first non-PK field for example
305
299
  const exampleField = schema.fields.find(f => !pkFields(pk).includes(f)) || schema.fields[0];
306
- lines.push(` validate: async (db, req, main, secondaries) => {`);
307
- lines.push(` const errors: ValidationError[] = [];`);
308
- lines.push(` // if (!main.${exampleField}) errors.push(['${exampleField}', 'required']);`);
300
+ lines.push(` validate: async ({ db, req, main, upsert, replace }) => {`);
301
+ lines.push(` const errors: ValidatorResult = [];`);
302
+ lines.push(` // if (!main.${exampleField}) errors.push({ path: 'main.${exampleField}', code: 'required' });`);
309
303
  lines.push(` return errors;`);
310
304
  lines.push(` },`);
311
- lines.push(` // beforeInsert: async (db, req, record) => {},`);
312
- lines.push(` // beforeUpdate: async (db, req, fields) => {},`);
305
+ lines.push(` // beforeInsert: async ({ db, req, record }) => {},`);
306
+ lines.push(` // beforeUpdate: async ({ db, req, record }) => {},`);
313
307
  lines.push(tenantScopeLine(childRels));
314
308
  lines.push(`});`);
315
309
  lines.push(``);
@@ -334,60 +328,3 @@ export function generateDbTablesIndex(schemas) {
334
328
  lines.push(``);
335
329
  return lines.join('\n');
336
330
  }
337
- // ─── Code Generation (legacy) ───────────────────────────────
338
- /** One `defineTable({...})` block for the legacy single-file generator. */
339
- function legacyTableBlock(schema, parentRels, childRels) {
340
- const { pk, autoIncrement, source } = detectPrimaryKey(schema);
341
- const tableVarName = 'Table' + schema.schemaName.replace(/^Schema/, '');
342
- const upsertPk = pkFields(pk).map((p) => `'${p}'`).join(', ');
343
- const exampleField = schema.fields.find((f) => !pkFields(pk).includes(f)) || schema.fields[0];
344
- const lines = [
345
- ``,
346
- `// ─── ${schema.tableName} ──────────────────────────────`,
347
- ...viewNotice(schema, source),
348
- `// Fields: ${schema.fields.join(', ')}`,
349
- `const ${tableVarName} = defineTable({`,
350
- ` primary: ${formatPrimary(pk)},`,
351
- ` ...exportTableInfo(${schema.schemaName}),`,
352
- ` defaultOrder: '${defaultOrderField(schema, pk, source)}',`,
353
- ...viewOperationsLine(schema, source),
354
- ];
355
- if (!schema.isView) {
356
- lines.push(autoIncrement
357
- ? ` excludeFromCreation: ['${pkFirst(pk)}'],`
358
- : ` // excludeFromCreation: [],`);
359
- }
360
- lines.push(...allowedReadJoinsLines(parentRels));
361
- lines.push(` // upsertMap: buildUpsertRules(buildUpsertRule(${schema.schemaName}, [${upsertPk}])),`, ` // schemaOverrides: {},`, ` validate: async (db, req, main, secondaries) => {`, ` const errors: ValidationError[] = [];`, ` // if (!main.${exampleField}) errors.push(['${exampleField}', 'required']);`, ` return errors;`, ` },`, ` // beforeInsert: async (db, req, record) => {},`, ` // beforeUpdate: async (db, req, fields) => {},`, tenantScopeLine(childRels), `});`);
362
- return lines;
363
- }
364
- /** Legacy single-file DbTables generator.
365
- * @testonly Exported only so unit tests can exercise it directly.
366
- */
367
- export function generateTablesFile(schemas) {
368
- const { byParent, byChild } = indexRelations(detectRelations(schemas));
369
- const lines = [];
370
- // Imports
371
- lines.push(`import {defineTable, exportTableInfo, Type} from 'fastify-auto-sqlapi';`);
372
- lines.push(`import type { DbTables, ValidationError } from 'fastify-auto-sqlapi';`);
373
- lines.push(``);
374
- // Schema imports
375
- for (const schema of schemas) {
376
- lines.push(`import {${schema.schemaName}} from './${schema.schemaName}.js';`);
377
- }
378
- // Table definitions
379
- for (const schema of schemas) {
380
- lines.push(...legacyTableBlock(schema, byParent.get(schema.schemaName) ?? [], byChild.get(schema.schemaName) ?? []));
381
- }
382
- // DbTables export
383
- lines.push(``);
384
- lines.push(`// ─── DbTables ──────────────────────────────────────`);
385
- lines.push(`export const dbTables: DbTables = {`);
386
- for (const schema of schemas) {
387
- const tableVarName = 'Table' + schema.schemaName.replace(/^Schema/, '');
388
- lines.push(` ${schema.tableName}: ${tableVarName},`);
389
- }
390
- lines.push(`};`);
391
- lines.push(``);
392
- return lines.join('\n');
393
- }
package/dist/lib/db.d.ts CHANGED
@@ -1,15 +1,22 @@
1
- import { Expression } from 'node-condition-builder';
2
- import type { ConditionBuilder } from 'node-condition-builder';
3
- import type { Queryable, SqlResult, DbRecord, SelectOptions } from '../types.js';
1
+ import { Expression, ConditionBuilder } from 'node-condition-builder';
2
+ import type { ConditionValue } from 'node-condition-builder';
3
+ import type { Queryable, SqlResult, DbRecord, SelectOptions, WrittenRow } from '../types/db.js';
4
4
  import type { SqlDialect } from './dialect.js';
5
- /** @deprecated Use db.qi() instead */
6
- export declare const escapeIdent: (f: string) => string;
5
+ /** The options of {@link QueryClient.bulkUpsert}. */
6
+ export interface BulkUpsertOptions {
7
+ chunkSize?: number;
8
+ immutableCols?: string[];
9
+ }
7
10
  export declare class QueryClient {
8
11
  #private;
9
12
  private client;
10
13
  private dialect;
11
14
  private debug;
12
- constructor(client: Queryable, dialect?: SqlDialect);
15
+ /** True on the client `withTransaction` hands its callback: it wraps the transaction's connection. */
16
+ private readonly inTransaction;
17
+ constructor(client: Queryable, dialect?: SqlDialect, inTransaction?: boolean);
18
+ /** Whether `withTransaction` can run: the Queryable has `connect()`, or this client already is a transaction. */
19
+ get supportsTransactions(): boolean;
13
20
  get qi(): (id: string) => string;
14
21
  get ph(): (i: number) => string;
15
22
  get dialectName(): string;
@@ -25,27 +32,45 @@ export declare class QueryClient {
25
32
  query<T = Record<string, unknown>>(text: string, values?: unknown[]): Promise<SqlResult<T>>;
26
33
  /**
27
34
  * Run `fn` inside a DB transaction on a dedicated connection (BEGIN/COMMIT, with
28
- * ROLLBACK + rethrow on error). Requires the underlying Queryable to expose
29
- * `connect()`; when it does not (legacy custom adapters), `fn` runs directly on
30
- * this client without transactional guarantees.
35
+ * ROLLBACK + rethrow on error). Requires the underlying Queryable to expose `connect()`.
36
+ *
37
+ * Without it the call fails, and nothing runs: a write that asked for atomicity — a main
38
+ * row with its secondaries, deletions and after-hooks — must not be executed as separate
39
+ * autocommitted statements because the adapter cannot do better: a custom adapter without
40
+ * `connect()` would otherwise lose the guarantee in silence (ADR 0023).
31
41
  *
32
- * Nested calls join the outer transaction: the tx QueryClient wraps a dedicated
33
- * connection that has no `connect()`, so an inner `withTransaction` is a no-op
34
- * wrapper around the same connection.
42
+ * Nested calls join the outer transaction: the tx QueryClient wraps the dedicated
43
+ * connection, which has no `connect()` either, so an inner `withTransaction` runs `fn` on
44
+ * the same connection. That is the one case where a missing `connect()` is not an error.
35
45
  */
36
46
  withTransaction<T>(fn: (tx: QueryClient) => Promise<T>): Promise<T>;
37
47
  insert(table: string, record: DbRecord, pkCol: string | string[]): Promise<Record<string, unknown>>;
38
- insertOrUpdate(table: string, record: DbRecord, conflictKeys: string[], pkCol: string | string[]): Promise<Record<string, unknown>>;
48
+ /**
49
+ * Insert `record`, or update the row its `conflictKeys` already name: `{ pk, action }`, the
50
+ * row's primary key and whether it was inserted or updated. The conflict keys are never in
51
+ * the update set. They must be a unique key the database enforces (ADR 0021).
52
+ */
53
+ upsert(table: string, record: DbRecord, conflictKeys: string[], pkCol: string | string[]): Promise<WrittenRow>;
39
54
  bulkInsert(table: string, records: DbRecord[], pkCol: string | string[], chunkSize?: number): Promise<Record<string, unknown>[]>;
40
55
  /**
41
- * `immutableCols` are written when the row is inserted but left untouched when the statement
42
- * lands on an existing row — like the conflict keys, which are never in the update set either.
43
- * Used by tenant isolation to keep an upsert from re-assigning a row's owner.
56
+ * `upsert` for every record, in chunks: `{ pk, action }` per record, in input order. Each
57
+ * record writes only its own fields (ADR 0003).
58
+ *
59
+ * - `chunkSize`: records per statement (default {@link DEFAULT_CHUNK_SIZE}).
60
+ * - `immutableCols`: written when the row is inserted, left untouched when the statement
61
+ * lands on an existing row — like the conflict keys. Tenant isolation uses it to keep an
62
+ * upsert from re-assigning a row's owner.
44
63
  */
45
- bulkInsertOrUpdate(table: string, records: DbRecord[], conflictKeys: string[], pkCol: string | string[], chunkSize?: number, immutableCols?: string[]): Promise<Record<string, unknown>[]>;
64
+ bulkUpsert(table: string, records: DbRecord[], conflictKeys: string[], pkCol: string | string[], options?: BulkUpsertOptions): Promise<WrittenRow[]>;
46
65
  update(table: string, record: DbRecord, where: DbRecord, extraCondition?: ConditionBuilder): Promise<number>;
47
66
  delete(table: string, where: DbRecord, extraCondition?: ConditionBuilder): Promise<number>;
48
67
  select<T = Record<string, unknown>>({ tableName, columns, where, values, limit, orderBy, joins, distinct, }: SelectOptions): Promise<T[]>;
49
68
  }
69
+ /**
70
+ * The predicate matching a set of rows by their keys: `col IN (…)` for a single column, and for
71
+ * several an OR of one {@link buildKeyEquals} group per key, so each key binds all of its columns
72
+ * together — never one column alone, which would reach every row sharing that value.
73
+ */
74
+ export declare function buildKeyMatch(db: QueryClient, cols: string[], keys: ConditionValue[][]): ConditionBuilder;
50
75
  export declare function createQueryClient(pool: Queryable, d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