fastify-auto-sqlapi 0.5.1 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +5 -5
- package/AGENTS_BACKEND.md +166 -130
- package/AGENTS_FRONTEND.md +60 -38
- package/BREAKING_CHANGES.md +9 -893
- package/CHANGELOG.md +246 -15
- package/README.md +71 -45
- package/dist/bin/generate-schema.js +12 -12
- package/dist/bin/generate-tables.js +1 -2
- package/dist/bin/utils.d.ts +2 -6
- package/dist/bin/utils.d.ts.map +1 -1
- package/dist/bin/utils.js +13 -33
- package/dist/index.d.ts +13 -33
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -37
- package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
- package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
- package/dist/lib/adapters/pg-adapter.d.ts +5 -2
- package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
- package/dist/lib/agent/manifest.d.ts +27 -10
- package/dist/lib/agent/manifest.d.ts.map +1 -1
- package/dist/lib/agent/manifest.js +43 -26
- package/dist/lib/agent/tool-schemas.d.ts +5 -4
- package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
- package/dist/lib/agent/tool-schemas.js +5 -5
- package/dist/lib/cli/config.d.ts +37 -2
- package/dist/lib/cli/config.d.ts.map +1 -1
- package/dist/lib/cli/config.js +106 -16
- package/dist/lib/cli/mysql-introspect.d.ts +6 -1
- package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
- package/dist/lib/cli/mysql-introspect.js +15 -15
- package/dist/lib/cli/pg-introspect.d.ts +0 -1
- package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
- package/dist/lib/cli/pg-introspect.js +2 -13
- package/dist/lib/cli/tables-codegen.d.ts +0 -4
- package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
- package/dist/lib/cli/tables-codegen.js +24 -87
- package/dist/lib/db.d.ts +42 -17
- package/dist/lib/db.d.ts.map +1 -1
- package/dist/lib/db.js +114 -40
- package/dist/lib/dialect.d.ts +5 -0
- package/dist/lib/dialect.d.ts.map +1 -1
- package/dist/lib/dialect.js +3 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
- package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-delete.js +66 -30
- package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
- package/dist/lib/engine/read-hooks.d.ts +3 -3
- package/dist/lib/engine/read-hooks.d.ts.map +1 -1
- package/dist/lib/engine/read-hooks.js +3 -3
- package/dist/lib/engine/rest/delete.d.ts.map +1 -1
- package/dist/lib/engine/rest/delete.js +12 -18
- package/dist/lib/engine/rest/get.js +8 -8
- package/dist/lib/engine/rest/insert.d.ts.map +1 -1
- package/dist/lib/engine/rest/insert.js +31 -18
- package/dist/lib/engine/rest/update.d.ts.map +1 -1
- package/dist/lib/engine/rest/update.js +34 -17
- package/dist/lib/engine/search/aggregations.d.ts +3 -3
- package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
- package/dist/lib/engine/search/aggregations.js +20 -16
- package/dist/lib/engine/search/conditions.d.ts +9 -5
- package/dist/lib/engine/search/conditions.d.ts.map +1 -1
- package/dist/lib/engine/search/conditions.js +31 -20
- package/dist/lib/engine/search/fields.d.ts +44 -11
- package/dist/lib/engine/search/fields.d.ts.map +1 -1
- package/dist/lib/engine/search/fields.js +93 -27
- package/dist/lib/engine/search/join-families.d.ts +7 -7
- package/dist/lib/engine/search/join-families.d.ts.map +1 -1
- package/dist/lib/engine/search/join-families.js +84 -75
- package/dist/lib/engine/search/joins.d.ts +15 -7
- package/dist/lib/engine/search/joins.d.ts.map +1 -1
- package/dist/lib/engine/search/joins.js +23 -13
- package/dist/lib/engine/search/order-by.d.ts +11 -12
- package/dist/lib/engine/search/order-by.d.ts.map +1 -1
- package/dist/lib/engine/search/order-by.js +24 -28
- package/dist/lib/engine/search/search.d.ts.map +1 -1
- package/dist/lib/engine/search/search.js +111 -64
- package/dist/lib/engine/validate.d.ts +21 -3
- package/dist/lib/engine/validate.d.ts.map +1 -1
- package/dist/lib/engine/validate.js +106 -16
- package/dist/lib/engine/write-helpers.d.ts +69 -16
- package/dist/lib/engine/write-helpers.d.ts.map +1 -1
- package/dist/lib/engine/write-helpers.js +257 -105
- package/dist/lib/errors.d.ts +42 -10
- package/dist/lib/errors.d.ts.map +1 -1
- package/dist/lib/errors.js +69 -15
- package/dist/lib/nullable.d.ts +3 -2
- package/dist/lib/nullable.d.ts.map +1 -1
- package/dist/lib/nullable.js +14 -5
- package/dist/lib/read-access.d.ts +25 -16
- package/dist/lib/read-access.d.ts.map +1 -1
- package/dist/lib/read-access.js +33 -17
- package/dist/lib/schema/bulk-delete.d.ts +13 -7
- package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
- package/dist/lib/schema/bulk-delete.js +18 -8
- package/dist/lib/schema/bulk-upsert.d.ts +3 -3
- package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
- package/dist/lib/schema/bulk-upsert.js +9 -14
- package/dist/lib/schema/get.d.ts +1 -1
- package/dist/lib/schema/get.d.ts.map +1 -1
- package/dist/lib/schema/get.js +2 -2
- package/dist/lib/schema/helpers.d.ts +41 -23
- package/dist/lib/schema/helpers.d.ts.map +1 -1
- package/dist/lib/schema/helpers.js +80 -33
- package/dist/lib/schema/insert.d.ts +1 -1
- package/dist/lib/schema/insert.d.ts.map +1 -1
- package/dist/lib/schema/insert.js +12 -20
- package/dist/lib/schema/search.d.ts +2 -13
- package/dist/lib/schema/search.d.ts.map +1 -1
- package/dist/lib/schema/search.js +64 -61
- package/dist/lib/schema/update.d.ts +1 -1
- package/dist/lib/schema/update.d.ts.map +1 -1
- package/dist/lib/schema/update.js +6 -13
- package/dist/lib/sql-api.d.ts +47 -25
- package/dist/lib/sql-api.d.ts.map +1 -1
- package/dist/lib/sql-api.js +70 -27
- package/dist/lib/table-helpers.d.ts +92 -14
- package/dist/lib/table-helpers.d.ts.map +1 -1
- package/dist/lib/table-helpers.js +367 -128
- package/dist/lib/tenant.d.ts +16 -22
- package/dist/lib/tenant.d.ts.map +1 -1
- package/dist/lib/tenant.js +38 -54
- package/dist/lib/write-access.d.ts +15 -9
- package/dist/lib/write-access.d.ts.map +1 -1
- package/dist/lib/write-access.js +12 -4
- package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
- package/dist/routes/auto/agent-manifest.routes.js +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-delete.routes.js +1 -7
- package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
- package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
- package/dist/routes/auto/bulk-upsert.routes.js +2 -2
- package/dist/routes/auto/delete.routes.d.ts +2 -2
- package/dist/routes/auto/delete.routes.d.ts.map +1 -1
- package/dist/routes/auto/delete.routes.js +8 -10
- package/dist/routes/auto/get.routes.d.ts +2 -2
- package/dist/routes/auto/get.routes.d.ts.map +1 -1
- package/dist/routes/auto/get.routes.js +5 -5
- package/dist/routes/auto/insert.routes.d.ts +2 -2
- package/dist/routes/auto/insert.routes.d.ts.map +1 -1
- package/dist/routes/auto/insert.routes.js +1 -7
- package/dist/routes/auto/plugin.d.ts +6 -0
- package/dist/routes/auto/plugin.d.ts.map +1 -1
- package/dist/routes/auto/plugin.js +60 -36
- package/dist/routes/auto/route-helpers.d.ts +26 -12
- package/dist/routes/auto/route-helpers.d.ts.map +1 -1
- package/dist/routes/auto/route-helpers.js +50 -19
- package/dist/routes/auto/search.routes.d.ts +2 -2
- package/dist/routes/auto/search.routes.d.ts.map +1 -1
- package/dist/routes/auto/search.routes.js +36 -24
- package/dist/routes/auto/update.routes.d.ts +2 -2
- package/dist/routes/auto/update.routes.d.ts.map +1 -1
- package/dist/routes/auto/update.routes.js +1 -8
- package/dist/routes/sql-api-decorator.d.ts +30 -12
- package/dist/routes/sql-api-decorator.d.ts.map +1 -1
- package/dist/routes/sql-api-decorator.js +44 -27
- package/dist/types/cli.d.ts +17 -6
- package/dist/types/cli.d.ts.map +1 -1
- package/dist/types/computed.d.ts +1 -1
- package/dist/types/computed.d.ts.map +1 -1
- package/dist/types/conditions.d.ts +3 -1
- package/dist/types/conditions.d.ts.map +1 -1
- package/dist/types/db.d.ts +44 -4
- package/dist/types/db.d.ts.map +1 -1
- package/dist/types/dml.d.ts +26 -17
- package/dist/types/dml.d.ts.map +1 -1
- package/dist/types/hooks.d.ts +62 -0
- package/dist/types/hooks.d.ts.map +1 -0
- package/dist/types/hooks.js +1 -0
- package/dist/types/join.d.ts +25 -8
- package/dist/types/join.d.ts.map +1 -1
- package/dist/types/plugin.d.ts +58 -19
- package/dist/types/plugin.d.ts.map +1 -1
- package/dist/types/plugin.js +2 -0
- package/dist/types/request.d.ts +2 -2
- package/dist/types/schema.d.ts +3 -3
- package/dist/types/schema.d.ts.map +1 -1
- package/dist/types/search.d.ts +28 -13
- package/dist/types/search.d.ts.map +1 -1
- package/dist/types/search.js +2 -1
- package/dist/types/table.d.ts +109 -94
- package/dist/types/table.d.ts.map +1 -1
- package/dist/types/table.js +7 -2
- package/dist/types/tenant.d.ts +28 -2
- package/dist/types/tenant.d.ts.map +1 -1
- package/dist/types/tenant.js +7 -1
- package/dist/types/validation.d.ts +69 -13
- package/dist/types/validation.d.ts.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -0
- package/docs/GLOSSARY.md +11 -5
- package/docs/adr/0003-bulk-not-transactional.md +2 -1
- package/docs/adr/0006-raw-db-errors.md +2 -1
- package/docs/adr/0013-sanitized-db-errors.md +2 -1
- package/docs/adr/0014-what-follows-a-write-join.md +1 -1
- package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
- package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
- package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
- package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
- package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
- package/docs/adr/0027-the-1-0-contract.md +74 -0
- package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
- package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
- package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
- package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
- package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
- package/docs/adr/README.md +12 -1
- package/docs/upgrading/0.x.md +906 -0
- package/docs/upgrading/1.0.md +628 -0
- package/package.json +4 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SearchTableBodyPost
|
|
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). `
|
|
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'))
|
package/dist/lib/cli/config.d.ts
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
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,
|
|
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"}
|
package/dist/lib/cli/config.js
CHANGED
|
@@ -5,25 +5,115 @@ const DEFAULTS = {
|
|
|
5
5
|
outputDir: './src/db',
|
|
6
6
|
schema: 'public',
|
|
7
7
|
};
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
|
18
|
-
|
|
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
|
-
|
|
27
|
-
|
|
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
|
-
|
|
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,
|
|
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;;;;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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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:
|
|
15
|
-
port: parseInt(
|
|
16
|
-
user:
|
|
17
|
-
password:
|
|
18
|
-
database
|
|
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 +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;
|
|
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
|
|
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,YAAY,GAAG,IAAI,CAoCpE;AA4GD;;GAEG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,gBAAgB,EAAE,CAwB3E;AAgID,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,GAAG,MAAM,
|
|
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,YAAY,GAAG,IAAI,CAoCpE;AA4GD;;GAEG;AACH,wBAAgB,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
|
|
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: '
|
|
196
|
-
return ` // tenantScope: { column: '
|
|
195
|
+
return ` // tenantScope: { column: 'organizationId' },`;
|
|
196
|
+
return ` // tenantScope: { column: 'organizationId', through: { schema: ${rel.parentSchemaName}, localField: '${rel.childField}', foreignField: '${rel.parentField}' } },`;
|
|
197
197
|
}
|
|
198
|
-
function
|
|
198
|
+
function readJoinsLines(parentRels) {
|
|
199
199
|
if (parentRels.length === 0)
|
|
200
|
-
return [` //
|
|
201
|
-
const lines = [` //
|
|
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,
|
|
257
|
-
lines.push(`import type {
|
|
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(`
|
|
271
|
+
lines.push(` schema: Schema,`);
|
|
275
272
|
// Commented example with extraFilters + extendedCondition
|
|
276
|
-
lines.push(` //
|
|
277
|
-
lines.push(` //
|
|
278
|
-
lines.push(` //
|
|
279
|
-
lines.push(` //
|
|
280
|
-
lines.push(` //
|
|
281
|
-
lines.push(` //
|
|
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(`
|
|
285
|
+
lines.push(` insertExclude: ['${pkFirst(pk)}'],`);
|
|
292
286
|
}
|
|
293
287
|
else {
|
|
294
|
-
lines.push(` //
|
|
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(...
|
|
294
|
+
lines.push(...readJoinsLines(parentRels));
|
|
301
295
|
const upsertPk = pkFields(pk).map((p) => `'${p}'`).join(', ');
|
|
302
|
-
lines.push(` //
|
|
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,
|
|
307
|
-
lines.push(` const errors:
|
|
308
|
-
lines.push(` // if (!main.${exampleField}) errors.push(
|
|
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,
|
|
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 {
|
|
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
|
-
/** @
|
|
6
|
-
export
|
|
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
|
-
|
|
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
|
-
*
|
|
30
|
-
*
|
|
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
|
|
33
|
-
* connection
|
|
34
|
-
*
|
|
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
|
-
|
|
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
|
-
* `
|
|
42
|
-
*
|
|
43
|
-
*
|
|
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
|
-
|
|
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, dialectName?: string): QueryClient;
|
|
51
76
|
//# sourceMappingURL=db.d.ts.map
|
package/dist/lib/db.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"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"}
|