sqlstack 1.0.25 → 3.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/dist/cjs/adapters/mysql.d.ts.map +1 -1
- package/dist/cjs/adapters/mysql.js +3 -3
- package/dist/cjs/adapters/mysql.js.map +1 -1
- package/dist/cjs/adapters/pg.d.ts.map +1 -1
- package/dist/cjs/adapters/pg.js +3 -3
- package/dist/cjs/adapters/pg.js.map +1 -1
- package/dist/cjs/codegen/cli.d.ts +3 -0
- package/dist/cjs/codegen/cli.d.ts.map +1 -0
- package/dist/cjs/codegen/cli.js +50 -0
- package/dist/cjs/codegen/cli.js.map +1 -0
- package/dist/cjs/codegen/generateManifest.d.ts +72 -0
- package/dist/cjs/codegen/generateManifest.d.ts.map +1 -0
- package/dist/cjs/codegen/generateManifest.js +191 -0
- package/dist/cjs/codegen/generateManifest.js.map +1 -0
- package/dist/cjs/core/loadNodeModule.d.ts +17 -0
- package/dist/cjs/core/loadNodeModule.d.ts.map +1 -0
- package/dist/cjs/core/loadNodeModule.js +36 -0
- package/dist/cjs/core/loadNodeModule.js.map +1 -0
- package/dist/cjs/core/resolver.d.ts +94 -0
- package/dist/cjs/core/resolver.d.ts.map +1 -0
- package/dist/cjs/core/resolver.js +145 -0
- package/dist/cjs/core/resolver.js.map +1 -0
- package/dist/cjs/core/sourceScanResolver.d.ts +25 -0
- package/dist/cjs/core/sourceScanResolver.d.ts.map +1 -0
- package/dist/cjs/core/sourceScanResolver.js +56 -0
- package/dist/cjs/core/sourceScanResolver.js.map +1 -0
- package/dist/cjs/decorators/query.d.ts.map +1 -1
- package/dist/cjs/decorators/query.js +42 -14
- package/dist/cjs/decorators/query.js.map +1 -1
- package/dist/cjs/families/sqliteFamily.d.ts +26 -0
- package/dist/cjs/families/sqliteFamily.d.ts.map +1 -0
- package/dist/cjs/families/sqliteFamily.js +187 -0
- package/dist/cjs/families/sqliteFamily.js.map +1 -0
- package/dist/cjs/family.d.ts +69 -0
- package/dist/cjs/family.d.ts.map +1 -0
- package/dist/cjs/family.js +206 -0
- package/dist/cjs/family.js.map +1 -0
- package/dist/cjs/familyBinding.d.ts +22 -0
- package/dist/cjs/familyBinding.d.ts.map +1 -0
- package/dist/cjs/familyBinding.js +22 -0
- package/dist/cjs/familyBinding.js.map +1 -0
- package/dist/cjs/index.d.ts +10 -0
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +18 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/ioc.d.ts +22 -0
- package/dist/cjs/ioc.d.ts.map +1 -0
- package/dist/cjs/ioc.js +35 -0
- package/dist/cjs/ioc.js.map +1 -0
- package/dist/cjs/runtime.d.ts +25 -0
- package/dist/cjs/runtime.d.ts.map +1 -0
- package/dist/cjs/runtime.js +133 -0
- package/dist/cjs/runtime.js.map +1 -0
- package/dist/cjs/stack.d.ts +101 -0
- package/dist/cjs/stack.d.ts.map +1 -0
- package/dist/cjs/stack.js +288 -0
- package/dist/cjs/stack.js.map +1 -0
- package/dist/cjs/testing/builder.d.ts +29 -0
- package/dist/cjs/testing/builder.d.ts.map +1 -0
- package/dist/cjs/testing/builder.js +131 -0
- package/dist/cjs/testing/builder.js.map +1 -0
- package/dist/cjs/testing/index.d.ts +10 -0
- package/dist/cjs/testing/index.d.ts.map +1 -0
- package/dist/cjs/testing/index.js +18 -0
- package/dist/cjs/testing/index.js.map +1 -0
- package/dist/cjs/testing/postgres/allocator.d.ts +17 -0
- package/dist/cjs/testing/postgres/allocator.d.ts.map +1 -0
- package/dist/cjs/testing/postgres/allocator.js +54 -0
- package/dist/cjs/testing/postgres/allocator.js.map +1 -0
- package/dist/cjs/testing/postgres/database.d.ts +21 -0
- package/dist/cjs/testing/postgres/database.d.ts.map +1 -0
- package/dist/cjs/testing/postgres/database.js +39 -0
- package/dist/cjs/testing/postgres/database.js.map +1 -0
- package/dist/cjs/testing/postgres/loadData.d.ts +31 -0
- package/dist/cjs/testing/postgres/loadData.d.ts.map +1 -0
- package/dist/cjs/testing/postgres/loadData.js +184 -0
- package/dist/cjs/testing/postgres/loadData.js.map +1 -0
- package/dist/cjs/testing/postgres/server.d.ts +19 -0
- package/dist/cjs/testing/postgres/server.d.ts.map +1 -0
- package/dist/cjs/testing/postgres/server.js +78 -0
- package/dist/cjs/testing/postgres/server.js.map +1 -0
- package/dist/cjs/testing/schema/ddl.d.ts +14 -0
- package/dist/cjs/testing/schema/ddl.d.ts.map +1 -0
- package/dist/cjs/testing/schema/ddl.js +54 -0
- package/dist/cjs/testing/schema/ddl.js.map +1 -0
- package/dist/cjs/testing/schema/normalize.d.ts +7 -0
- package/dist/cjs/testing/schema/normalize.d.ts.map +1 -0
- package/dist/cjs/testing/schema/normalize.js +202 -0
- package/dist/cjs/testing/schema/normalize.js.map +1 -0
- package/dist/cjs/testing/schema/parser.d.ts +9 -0
- package/dist/cjs/testing/schema/parser.d.ts.map +1 -0
- package/dist/cjs/testing/schema/parser.js +80 -0
- package/dist/cjs/testing/schema/parser.js.map +1 -0
- package/dist/cjs/testing/schema/types.d.ts +82 -0
- package/dist/cjs/testing/schema/types.d.ts.map +1 -0
- package/dist/cjs/testing/schema/types.js +10 -0
- package/dist/cjs/testing/schema/types.js.map +1 -0
- package/dist/cjs/transactions.d.ts +14 -5
- package/dist/cjs/transactions.d.ts.map +1 -1
- package/dist/cjs/transactions.js +40 -24
- package/dist/cjs/transactions.js.map +1 -1
- package/dist/esm/adapters/mysql.js +3 -3
- package/dist/esm/adapters/mysql.js.map +1 -1
- package/dist/esm/adapters/pg.js +3 -3
- package/dist/esm/adapters/pg.js.map +1 -1
- package/dist/esm/codegen/cli.js +48 -0
- package/dist/esm/codegen/cli.js.map +1 -0
- package/dist/esm/codegen/generateManifest.js +183 -0
- package/dist/esm/codegen/generateManifest.js.map +1 -0
- package/dist/esm/core/loadNodeModule.js +33 -0
- package/dist/esm/core/loadNodeModule.js.map +1 -0
- package/dist/esm/core/resolver.js +132 -0
- package/dist/esm/core/resolver.js.map +1 -0
- package/dist/esm/core/sourceScanResolver.js +51 -0
- package/dist/esm/core/sourceScanResolver.js.map +1 -0
- package/dist/esm/decorators/query.js +43 -15
- package/dist/esm/decorators/query.js.map +1 -1
- package/dist/esm/families/sqliteFamily.js +151 -0
- package/dist/esm/families/sqliteFamily.js.map +1 -0
- package/dist/esm/family.js +202 -0
- package/dist/esm/family.js.map +1 -0
- package/dist/esm/familyBinding.js +18 -0
- package/dist/esm/familyBinding.js.map +1 -0
- package/dist/esm/index.js +8 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/ioc.js +32 -0
- package/dist/esm/ioc.js.map +1 -0
- package/dist/esm/runtime.js +94 -0
- package/dist/esm/runtime.js.map +1 -0
- package/dist/esm/stack.js +251 -0
- package/dist/esm/stack.js.map +1 -0
- package/dist/esm/testing/builder.js +95 -0
- package/dist/esm/testing/builder.js.map +1 -0
- package/dist/esm/testing/index.js +7 -0
- package/dist/esm/testing/index.js.map +1 -0
- package/dist/esm/testing/postgres/allocator.js +49 -0
- package/dist/esm/testing/postgres/allocator.js.map +1 -0
- package/dist/esm/testing/postgres/database.js +36 -0
- package/dist/esm/testing/postgres/database.js.map +1 -0
- package/dist/esm/testing/postgres/loadData.js +176 -0
- package/dist/esm/testing/postgres/loadData.js.map +1 -0
- package/dist/esm/testing/postgres/server.js +69 -0
- package/dist/esm/testing/postgres/server.js.map +1 -0
- package/dist/esm/testing/schema/ddl.js +49 -0
- package/dist/esm/testing/schema/ddl.js.map +1 -0
- package/dist/esm/testing/schema/normalize.js +164 -0
- package/dist/esm/testing/schema/normalize.js.map +1 -0
- package/dist/esm/testing/schema/parser.js +43 -0
- package/dist/esm/testing/schema/parser.js.map +1 -0
- package/dist/esm/testing/schema/types.js +9 -0
- package/dist/esm/testing/schema/types.js.map +1 -0
- package/dist/esm/transactions.js +39 -24
- package/dist/esm/transactions.js.map +1 -1
- package/package.json +29 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file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AE,UAA6B,EAAE;IAC9E,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,gCAAuB,CAC/B,8BAA8B,IAAI,qDAAqD,WAAW,GAAG,CACtG,CAAC;IACJ,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,IAAA,qBAAY,EAAC,OAAO,CAAC,CAAC;IAC1C,IAAI,CAAC;QACH,+EAA+E;QAC/E,MAAM,KAAK,CAAC,KAAK,CAAC,4BAA4B,IAAI,gBAAgB,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,gCAAuB,CAC/B,iCAAiC,IAAI,QAAQ,IAAA,eAAM,EAAC,IAAA,wBAAe,EAAC,OAAO,CAAC,CAAC,KAAM,GAAa,CAAC,OAAO,EAAE,CAC3G,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC","sourcesContent":["import { randomBytes } from 'crypto';\nimport {\n connectAdmin,\n redact,\n resolveAdminUrl,\n TestPostgresServerError,\n TestServerOptions,\n withDatabase,\n} from './server';\n\nconst NAME_PREFIX = 'sqlstack_test_';\nlet counter = 0;\n\n/**\n * Unique, safe, bounded-length database name. Randomness plus a process\n * counter keeps parallel builds (including across worker processes)\n * collision-free. Always well under PostgreSQL's 63-byte identifier limit.\n */\nexport function nextDatabaseName(): string {\n counter += 1;\n return `${NAME_PREFIX}${randomBytes(4).toString('hex')}_${counter}`;\n}\n\nexport interface AllocatedDatabase {\n readonly name: string;\n readonly url: string;\n readonly adminUrl: string;\n}\n\n/** Create a fresh uniquely named database on the configured test server. */\nexport async function allocateDatabase(options: TestServerOptions = {}): Promise<AllocatedDatabase> {\n const adminUrl = resolveAdminUrl(options);\n const name = nextDatabaseName();\n const admin = await connectAdmin(options);\n try {\n await admin.query(`CREATE DATABASE \"${name}\"`);\n } catch (err) {\n throw new TestPostgresServerError(\n `Failed to create test database \"${name}\" on ${redact(adminUrl)}: ${(err as Error).message}\\n` +\n `The admin connection must have CREATE DATABASE privilege ` +\n `(set SQLSTACK_TEST_PG_URL or options.adminUrl; start the bundled server with npm run db:pg:up).`\n );\n } finally {\n await admin.end().catch(() => undefined);\n }\n return { name, url: withDatabase(adminUrl, name), adminUrl };\n}\n\n/** Drop exactly the named database. Safe to call for an already-dropped db. */\nexport async function dropDatabase(name: string, options: TestServerOptions = {}): Promise<void> {\n if (!name.startsWith(NAME_PREFIX)) {\n throw new TestPostgresServerError(\n `Refusing to drop database \"${name}\": not an sqlstack test database (expected prefix ${NAME_PREFIX})`\n );\n }\n const admin = await connectAdmin(options);\n try {\n // FORCE (PG 13+) terminates lingering sessions so parallel teardown is robust.\n await admin.query(`DROP DATABASE IF EXISTS \"${name}\" WITH (FORCE)`);\n } catch (err) {\n throw new TestPostgresServerError(\n `Failed to drop test database \"${name}\" on ${redact(resolveAdminUrl(options))}: ${(err as Error).message}`\n );\n } finally {\n await admin.end().catch(() => undefined);\n }\n}\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { TestServerOptions } from './server';
|
|
2
|
+
/** The built test database handle. */
|
|
3
|
+
export interface TestPostgresDatabase {
|
|
4
|
+
/** Normal PostgreSQL connection string identifying only this database. */
|
|
5
|
+
readonly url: string;
|
|
6
|
+
query(sql: string, params?: readonly unknown[]): Promise<unknown>;
|
|
7
|
+
/** Close helper connections and drop the owned database. Idempotent. */
|
|
8
|
+
dispose(): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export interface OwnedDatabase {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly url: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Connect a helper pool to an allocated database and produce the handle.
|
|
16
|
+
* The handle owns exactly this database and drops it on dispose.
|
|
17
|
+
*/
|
|
18
|
+
export declare function createDatabaseHandle(owned: OwnedDatabase, options?: TestServerOptions): Promise<TestPostgresDatabase & {
|
|
19
|
+
_pool: any;
|
|
20
|
+
}>;
|
|
21
|
+
//# sourceMappingURL=database.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../../../src/testing/postgres/database.ts"],"names":[],"mappings":"AACA,OAAO,EAAmC,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAE9E,sCAAsC;AACtC,MAAM,WAAW,oBAAoB;IACnC,0EAA0E;IAC1E,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAClE,wEAAwE;IACxE,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,aAAa,EACpB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,oBAAoB,GAAG;IAAE,KAAK,EAAE,GAAG,CAAA;CAAE,CAAC,CA4BhD"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createDatabaseHandle = createDatabaseHandle;
|
|
4
|
+
const allocator_1 = require("./allocator");
|
|
5
|
+
const server_1 = require("./server");
|
|
6
|
+
/**
|
|
7
|
+
* Connect a helper pool to an allocated database and produce the handle.
|
|
8
|
+
* The handle owns exactly this database and drops it on dispose.
|
|
9
|
+
*/
|
|
10
|
+
async function createDatabaseHandle(owned, options = {}) {
|
|
11
|
+
const pg = await (0, server_1.loadPg)();
|
|
12
|
+
const Pool = pg.Pool ?? pg.default?.Pool;
|
|
13
|
+
const pool = new Pool({ connectionString: owned.url, max: 4 });
|
|
14
|
+
let disposed = false;
|
|
15
|
+
return {
|
|
16
|
+
url: owned.url,
|
|
17
|
+
_pool: pool,
|
|
18
|
+
async query(sql, params = []) {
|
|
19
|
+
if (disposed) {
|
|
20
|
+
throw new server_1.TestPostgresServerError(`Test database "${owned.name}" has been disposed; no further queries are possible.`);
|
|
21
|
+
}
|
|
22
|
+
const res = await pool.query(sql, params);
|
|
23
|
+
return res.rows;
|
|
24
|
+
},
|
|
25
|
+
async dispose() {
|
|
26
|
+
if (disposed)
|
|
27
|
+
return;
|
|
28
|
+
disposed = true;
|
|
29
|
+
try {
|
|
30
|
+
await pool.end();
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
/* pool may already be closed */
|
|
34
|
+
}
|
|
35
|
+
await (0, allocator_1.dropDatabase)(owned.name, options);
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
//# sourceMappingURL=database.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.js","sourceRoot":"","sources":["../../../../src/testing/postgres/database.ts"],"names":[],"mappings":";;AAqBA,oDA+BC;AApDD,2CAA2C;AAC3C,qCAA8E;AAgB9E;;;GAGG;AACI,KAAK,UAAU,oBAAoB,CACxC,KAAoB,EACpB,UAA6B,EAAE;IAE/B,MAAM,EAAE,GAAG,MAAM,IAAA,eAAM,GAAE,CAAC;IAC1B,MAAM,IAAI,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC;IACzC,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,EAAE,gBAAgB,EAAE,KAAK,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;IAC/D,IAAI,QAAQ,GAAG,KAAK,CAAC;IACrB,OAAO;QACL,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,KAAK,EAAE,IAAI;QACX,KAAK,CAAC,KAAK,CAAC,GAAW,EAAE,SAA6B,EAAE;YACtD,IAAI,QAAQ,EAAE,CAAC;gBACb,MAAM,IAAI,gCAAuB,CAC/B,kBAAkB,KAAK,CAAC,IAAI,uDAAuD,CACpF,CAAC;YACJ,CAAC;YACD,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,MAAmB,CAAC,CAAC;YACvD,OAAO,GAAG,CAAC,IAAI,CAAC;QAClB,CAAC;QACD,KAAK,CAAC,OAAO;YACX,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,IAAI,CAAC;gBACH,MAAM,IAAI,CAAC,GAAG,EAAE,CAAC;YACnB,CAAC;YAAC,MAAM,CAAC;gBACP,gCAAgC;YAClC,CAAC;YACD,MAAM,IAAA,wBAAY,EAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC1C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { dropDatabase } from './allocator';\nimport { loadPg, TestPostgresServerError, TestServerOptions } from './server';\n\n/** The built test database handle. */\nexport interface TestPostgresDatabase {\n /** Normal PostgreSQL connection string identifying only this database. */\n readonly url: string;\n query(sql: string, params?: readonly unknown[]): Promise<unknown>;\n /** Close helper connections and drop the owned database. Idempotent. */\n dispose(): Promise<void>;\n}\n\nexport interface OwnedDatabase {\n readonly name: string;\n readonly url: string;\n}\n\n/**\n * Connect a helper pool to an allocated database and produce the handle.\n * The handle owns exactly this database and drops it on dispose.\n */\nexport async function createDatabaseHandle(\n owned: OwnedDatabase,\n options: TestServerOptions = {}\n): Promise<TestPostgresDatabase & { _pool: any }> {\n const pg = await loadPg();\n const Pool = pg.Pool ?? pg.default?.Pool;\n const pool = new Pool({ connectionString: owned.url, max: 4 });\n let disposed = false;\n return {\n url: owned.url,\n _pool: pool,\n async query(sql: string, params: readonly unknown[] = []) {\n if (disposed) {\n throw new TestPostgresServerError(\n `Test database \"${owned.name}\" has been disposed; no further queries are possible.`\n );\n }\n const res = await pool.query(sql, params as unknown[]);\n return res.rows;\n },\n async dispose() {\n if (disposed) return;\n disposed = true;\n try {\n await pool.end();\n } catch {\n /* pool may already be closed */\n }\n await dropDatabase(owned.name, options);\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { SqlStackError } from '../../core/errors';
|
|
2
|
+
import type { NormalizedTestSchema } from '../schema/types';
|
|
3
|
+
export declare class TestDataError extends SqlStackError {
|
|
4
|
+
constructor(message: string);
|
|
5
|
+
}
|
|
6
|
+
export type Row = Record<string, unknown>;
|
|
7
|
+
export interface DataOperation {
|
|
8
|
+
readonly table: string;
|
|
9
|
+
readonly row: Readonly<Row>;
|
|
10
|
+
}
|
|
11
|
+
/** Validate one `.data()` payload against the structured schema (fail-fast). */
|
|
12
|
+
export declare function toOperations(schema: NormalizedTestSchema, data: Record<string, Row[]>): DataOperation[];
|
|
13
|
+
/**
|
|
14
|
+
* Compose row operations into effective rows per table.
|
|
15
|
+
* PK tables: identity = ordered PK values; later writes replace, first
|
|
16
|
+
* occurrence keeps its position. No-PK tables: append in authored order.
|
|
17
|
+
*/
|
|
18
|
+
export declare function composeRows(schema: NormalizedTestSchema, ops: readonly DataOperation[]): Map<string, Row[]>;
|
|
19
|
+
/**
|
|
20
|
+
* Deterministic insertion order for the tables that actually have rows,
|
|
21
|
+
* topologically sorted by declared references between those tables.
|
|
22
|
+
* Cycles fail with actionable guidance.
|
|
23
|
+
*/
|
|
24
|
+
export declare function planInsertOrder(schema: NormalizedTestSchema, tablesWithRows: readonly string[]): string[];
|
|
25
|
+
/**
|
|
26
|
+
* Insert effective rows. Parameterized and batched per table by column
|
|
27
|
+
* signature; missing columns are omitted from the INSERT so PostgreSQL
|
|
28
|
+
* defaults apply, while explicit null is sent as NULL.
|
|
29
|
+
*/
|
|
30
|
+
export declare function insertRows(query: (sql: string, params: unknown[]) => Promise<unknown>, schema: NormalizedTestSchema, effective: Map<string, Row[]>): Promise<void>;
|
|
31
|
+
//# sourceMappingURL=loadData.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loadData.d.ts","sourceRoot":"","sources":["../../../../src/testing/postgres/loadData.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAE5D,qBAAa,aAAc,SAAQ,aAAa;gBAClC,OAAO,EAAE,MAAM;CAI5B;AAED,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE1C,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,GAAG,CAAC,CAAC;CAC7B;AAED,gFAAgF;AAChF,wBAAgB,YAAY,CAAC,MAAM,EAAE,oBAAoB,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,aAAa,EAAE,CAwCvG;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,oBAAoB,EAC5B,GAAG,EAAE,SAAS,aAAa,EAAE,GAC5B,GAAG,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,CA8BpB;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,oBAAoB,EAAE,cAAc,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAqCzG;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAC9B,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,EAC3D,MAAM,EAAE,oBAAoB,EAC5B,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAC5B,OAAO,CAAC,IAAI,CAAC,CAuCf"}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TestDataError = void 0;
|
|
4
|
+
exports.toOperations = toOperations;
|
|
5
|
+
exports.composeRows = composeRows;
|
|
6
|
+
exports.planInsertOrder = planInsertOrder;
|
|
7
|
+
exports.insertRows = insertRows;
|
|
8
|
+
const errors_1 = require("../../core/errors");
|
|
9
|
+
const ddl_1 = require("../schema/ddl");
|
|
10
|
+
class TestDataError extends errors_1.SqlStackError {
|
|
11
|
+
constructor(message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = 'TestDataError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.TestDataError = TestDataError;
|
|
17
|
+
/** Validate one `.data()` payload against the structured schema (fail-fast). */
|
|
18
|
+
function toOperations(schema, data) {
|
|
19
|
+
const ops = [];
|
|
20
|
+
const tables = new Map(schema.tables.map((t) => [t.name, t]));
|
|
21
|
+
for (const [tableName, rows] of Object.entries(data)) {
|
|
22
|
+
const table = tables.get(tableName);
|
|
23
|
+
if (!table) {
|
|
24
|
+
const known = schema.tables.map((t) => t.name).join(', ') || '(none)';
|
|
25
|
+
throw new TestDataError(`.data(): unknown table "${tableName}". Structured tables declared in ${schema.source}: ${known}. ` +
|
|
26
|
+
`Tables created only through raw SQL cannot receive .data() rows; insert them via raw SQL instead.`);
|
|
27
|
+
}
|
|
28
|
+
if (!Array.isArray(rows)) {
|
|
29
|
+
throw new TestDataError(`.data(): rows for table "${tableName}" must be an array`);
|
|
30
|
+
}
|
|
31
|
+
const columnNames = new Set(table.columns.map((c) => c.name));
|
|
32
|
+
rows.forEach((row, i) => {
|
|
33
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) {
|
|
34
|
+
throw new TestDataError(`.data(): row #${i} for table "${tableName}" must be an object`);
|
|
35
|
+
}
|
|
36
|
+
for (const key of Object.keys(row)) {
|
|
37
|
+
if (!columnNames.has(key)) {
|
|
38
|
+
throw new TestDataError(`.data(): unknown column "${key}" in row #${i} for table "${tableName}" ` +
|
|
39
|
+
`(declared columns: ${[...columnNames].join(', ')})`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
for (const pk of table.primaryKey) {
|
|
43
|
+
if (row[pk] === undefined) {
|
|
44
|
+
throw new TestDataError(`.data(): row #${i} for table "${tableName}" is missing primary-key column "${pk}" ` +
|
|
45
|
+
`(primary key: ${table.primaryKey.join(', ')})`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
ops.push({ table: tableName, row });
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return ops;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Compose row operations into effective rows per table.
|
|
55
|
+
* PK tables: identity = ordered PK values; later writes replace, first
|
|
56
|
+
* occurrence keeps its position. No-PK tables: append in authored order.
|
|
57
|
+
*/
|
|
58
|
+
function composeRows(schema, ops) {
|
|
59
|
+
const tables = new Map(schema.tables.map((t) => [t.name, t]));
|
|
60
|
+
const result = new Map();
|
|
61
|
+
const identityIndex = new Map();
|
|
62
|
+
for (const op of ops) {
|
|
63
|
+
const table = tables.get(op.table);
|
|
64
|
+
let rows = result.get(op.table);
|
|
65
|
+
if (!rows) {
|
|
66
|
+
rows = [];
|
|
67
|
+
result.set(op.table, rows);
|
|
68
|
+
}
|
|
69
|
+
if (table.primaryKey.length === 0) {
|
|
70
|
+
rows.push(op.row);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const identity = JSON.stringify(table.primaryKey.map((pk) => op.row[pk]));
|
|
74
|
+
let index = identityIndex.get(op.table);
|
|
75
|
+
if (!index) {
|
|
76
|
+
index = new Map();
|
|
77
|
+
identityIndex.set(op.table, index);
|
|
78
|
+
}
|
|
79
|
+
const existing = index.get(identity);
|
|
80
|
+
if (existing === undefined) {
|
|
81
|
+
index.set(identity, rows.length);
|
|
82
|
+
rows.push(op.row);
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
rows[existing] = op.row;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Deterministic insertion order for the tables that actually have rows,
|
|
92
|
+
* topologically sorted by declared references between those tables.
|
|
93
|
+
* Cycles fail with actionable guidance.
|
|
94
|
+
*/
|
|
95
|
+
function planInsertOrder(schema, tablesWithRows) {
|
|
96
|
+
const inPlan = new Set(tablesWithRows);
|
|
97
|
+
const tables = schema.tables.filter((t) => inPlan.has(t.name));
|
|
98
|
+
// deps[t] = set of tables (with rows) that must be inserted before t
|
|
99
|
+
const deps = new Map();
|
|
100
|
+
for (const t of tables) {
|
|
101
|
+
const set = new Set();
|
|
102
|
+
for (const c of t.columns) {
|
|
103
|
+
if (c.references && c.references.table !== t.name && inPlan.has(c.references.table)) {
|
|
104
|
+
set.add(c.references.table);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
deps.set(t.name, set);
|
|
108
|
+
}
|
|
109
|
+
const order = [];
|
|
110
|
+
const done = new Set();
|
|
111
|
+
let progressed = true;
|
|
112
|
+
while (progressed && order.length < tables.length) {
|
|
113
|
+
progressed = false;
|
|
114
|
+
for (const t of tables) {
|
|
115
|
+
if (done.has(t.name))
|
|
116
|
+
continue;
|
|
117
|
+
const pending = [...deps.get(t.name)].filter((d) => !done.has(d));
|
|
118
|
+
if (pending.length === 0) {
|
|
119
|
+
order.push(t.name);
|
|
120
|
+
done.add(t.name);
|
|
121
|
+
progressed = true;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (order.length < tables.length) {
|
|
126
|
+
const cycle = tables.filter((t) => !done.has(t.name)).map((t) => t.name);
|
|
127
|
+
throw new TestDataError(`Cannot derive an insertion order: declared references between tables [${cycle.join(', ')}] form a cycle. ` +
|
|
128
|
+
`Insert this data via a raw "sql" entry (e.g. with deferred constraints), or restructure the references.`);
|
|
129
|
+
}
|
|
130
|
+
return order;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Insert effective rows. Parameterized and batched per table by column
|
|
134
|
+
* signature; missing columns are omitted from the INSERT so PostgreSQL
|
|
135
|
+
* defaults apply, while explicit null is sent as NULL.
|
|
136
|
+
*/
|
|
137
|
+
async function insertRows(query, schema, effective) {
|
|
138
|
+
const order = planInsertOrder(schema, [...effective.keys()]);
|
|
139
|
+
const declared = new Map(schema.tables.map((t) => [t.name, t.columns.map((c) => c.name)]));
|
|
140
|
+
for (const tableName of order) {
|
|
141
|
+
const rows = effective.get(tableName);
|
|
142
|
+
const columnOrder = declared.get(tableName);
|
|
143
|
+
// Group consecutive-compatible rows into batches sharing a column signature.
|
|
144
|
+
const batches = new Map();
|
|
145
|
+
for (const row of rows) {
|
|
146
|
+
const columns = columnOrder.filter((c) => row[c] !== undefined);
|
|
147
|
+
const sig = columns.join(',');
|
|
148
|
+
let batch = batches.get(sig);
|
|
149
|
+
if (!batch) {
|
|
150
|
+
batch = { columns, rows: [] };
|
|
151
|
+
batches.set(sig, batch);
|
|
152
|
+
}
|
|
153
|
+
batch.rows.push(row);
|
|
154
|
+
}
|
|
155
|
+
for (const { columns, rows: batchRows } of batches.values()) {
|
|
156
|
+
if (columns.length === 0) {
|
|
157
|
+
for (let i = 0; i < batchRows.length; i++) {
|
|
158
|
+
await run(query, tableName, `INSERT INTO ${(0, ddl_1.quoteIdent)(tableName)} DEFAULT VALUES`, []);
|
|
159
|
+
}
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
const params = [];
|
|
163
|
+
const tuples = batchRows.map((row) => {
|
|
164
|
+
const placeholders = columns.map((c) => {
|
|
165
|
+
params.push(row[c]);
|
|
166
|
+
return `$${params.length}`;
|
|
167
|
+
});
|
|
168
|
+
return `(${placeholders.join(', ')})`;
|
|
169
|
+
});
|
|
170
|
+
const sql = `INSERT INTO ${(0, ddl_1.quoteIdent)(tableName)} (${columns.map(ddl_1.quoteIdent).join(', ')}) ` +
|
|
171
|
+
`VALUES ${tuples.join(', ')}`;
|
|
172
|
+
await run(query, tableName, sql, params);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async function run(query, tableName, sql, params) {
|
|
177
|
+
try {
|
|
178
|
+
await query(sql, params);
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
throw new TestDataError(`Failed to insert scenario rows into table "${tableName}": ${err.message}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
//# sourceMappingURL=loadData.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loadData.js","sourceRoot":"","sources":["../../../../src/testing/postgres/loadData.ts"],"names":[],"mappings":";;;AAmBA,oCAwCC;AAOD,kCAiCC;AAOD,0CAqCC;AAOD,gCA2CC;AAjMD,8CAAkD;AAClD,uCAA2C;AAG3C,MAAa,aAAc,SAAQ,sBAAa;IAC9C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AALD,sCAKC;AASD,gFAAgF;AAChF,SAAgB,YAAY,CAAC,MAA4B,EAAE,IAA2B;IACpF,MAAM,GAAG,GAAoB,EAAE,CAAC;IAChC,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9D,KAAK,MAAM,CAAC,SAAS,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;QACrD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,EAAE,CAAC;Y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xC,CAAC,CAAC,CAAC;YACH,MAAM,GAAG,GACP,eAAe,IAAA,gBAAU,EAAC,SAAS,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,gBAAU,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI;gBAC/E,UAAU,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAChC,MAAM,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;QAC3C,CAAC;IACH,CAAC;AACH,CAAC;AAED,KAAK,UAAU,GAAG,CAChB,KAA2D,EAC3D,SAAiB,EACjB,GAAW,EACX,MAAiB;IAEjB,IAAI,CAAC;QACH,MAAM,KAAK,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAC3B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,aAAa,CACrB,8CAA8C,SAAS,MAAO,GAAa,CAAC,OAAO,EAAE,CACtF,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { SqlStackError } from '../../core/errors';\nimport { quoteIdent } from '../schema/ddl';\nimport type { NormalizedTestSchema } from '../schema/types';\n\nexport class TestDataError extends SqlStackError {\n constructor(message: string) {\n super(message);\n this.name = 'TestDataError';\n }\n}\n\nexport type Row = Record<string, unknown>;\n\nexport interface DataOperation {\n readonly table: string;\n readonly row: Readonly<Row>;\n}\n\n/** Validate one `.data()` payload against the structured schema (fail-fast). */\nexport function toOperations(schema: NormalizedTestSchema, data: Record<string, Row[]>): DataOperation[] {\n const ops: DataOperation[] = [];\n const tables = new Map(schema.tables.map((t) => [t.name, t]));\n for (const [tableName, rows] of Object.entries(data)) {\n const table = tables.get(tableName);\n if (!table) {\n const known = schema.tables.map((t) => t.name).join(', ') || '(none)';\n throw new TestDataError(\n `.data(): unknown table \"${tableName}\". Structured tables declared in ${schema.source}: ${known}. ` +\n `Tables created only through raw SQL cannot receive .data() rows; insert them via raw SQL instead.`\n );\n }\n if (!Array.isArray(rows)) {\n throw new TestDataError(`.data(): rows for table \"${tableName}\" must be an array`);\n }\n const columnNames = new Set(table.columns.map((c) => c.name));\n rows.forEach((row, i) => {\n if (!row || typeof row !== 'object' || Array.isArray(row)) {\n throw new TestDataError(`.data(): row #${i} for table \"${tableName}\" must be an object`);\n }\n for (const key of Object.keys(row)) {\n if (!columnNames.has(key)) {\n throw new TestDataError(\n `.data(): unknown column \"${key}\" in row #${i} for table \"${tableName}\" ` +\n `(declared columns: ${[...columnNames].join(', ')})`\n );\n }\n }\n for (const pk of table.primaryKey) {\n if (row[pk] === undefined) {\n throw new TestDataError(\n `.data(): row #${i} for table \"${tableName}\" is missing primary-key column \"${pk}\" ` +\n `(primary key: ${table.primaryKey.join(', ')})`\n );\n }\n }\n ops.push({ table: tableName, row });\n });\n }\n return ops;\n}\n\n/**\n * Compose row operations into effective rows per table.\n * PK tables: identity = ordered PK values; later writes replace, first\n * occurrence keeps its position. No-PK tables: append in authored order.\n */\nexport function composeRows(\n schema: NormalizedTestSchema,\n ops: readonly DataOperation[]\n): Map<string, Row[]> {\n const tables = new Map(schema.tables.map((t) => [t.name, t]));\n const result = new Map<string, Row[]>();\n const identityIndex = new Map<string, Map<string, number>>();\n for (const op of ops) {\n const table = tables.get(op.table)!;\n let rows = result.get(op.table);\n if (!rows) {\n rows = [];\n result.set(op.table, rows);\n }\n if (table.primaryKey.length === 0) {\n rows.push(op.row);\n continue;\n }\n const identity = JSON.stringify(table.primaryKey.map((pk) => op.row[pk]));\n let index = identityIndex.get(op.table);\n if (!index) {\n index = new Map();\n identityIndex.set(op.table, index);\n }\n const existing = index.get(identity);\n if (existing === undefined) {\n index.set(identity, rows.length);\n rows.push(op.row);\n } else {\n rows[existing] = op.row;\n }\n }\n return result;\n}\n\n/**\n * Deterministic insertion order for the tables that actually have rows,\n * topologically sorted by declared references between those tables.\n * Cycles fail with actionable guidance.\n */\nexport function planInsertOrder(schema: NormalizedTestSchema, tablesWithRows: readonly string[]): string[] {\n const inPlan = new Set(tablesWithRows);\n const tables = schema.tables.filter((t) => inPlan.has(t.name));\n // deps[t] = set of tables (with rows) that must be inserted before t\n const deps = new Map<string, Set<string>>();\n for (const t of tables) {\n const set = new Set<string>();\n for (const c of t.columns) {\n if (c.references && c.references.table !== t.name && inPlan.has(c.references.table)) {\n set.add(c.references.table);\n }\n }\n deps.set(t.name, set);\n }\n const order: string[] = [];\n const done = new Set<string>();\n let progressed = true;\n while (progressed && order.length < tables.length) {\n progressed = false;\n for (const t of tables) {\n if (done.has(t.name)) continue;\n const pending = [...deps.get(t.name)!].filter((d) => !done.has(d));\n if (pending.length === 0) {\n order.push(t.name);\n done.add(t.name);\n progressed = true;\n }\n }\n }\n if (order.length < tables.length) {\n const cycle = tables.filter((t) => !done.has(t.name)).map((t) => t.name);\n throw new TestDataError(\n `Cannot derive an insertion order: declared references between tables [${cycle.join(', ')}] form a cycle. ` +\n `Insert this data via a raw \"sql\" entry (e.g. with deferred constraints), or restructure the references.`\n );\n }\n return order;\n}\n\n/**\n * Insert effective rows. Parameterized and batched per table by column\n * signature; missing columns are omitted from the INSERT so PostgreSQL\n * defaults apply, while explicit null is sent as NULL.\n */\nexport async function insertRows(\n query: (sql: string, params: unknown[]) => Promise<unknown>,\n schema: NormalizedTestSchema,\n effective: Map<string, Row[]>\n): Promise<void> {\n const order = planInsertOrder(schema, [...effective.keys()]);\n const declared = new Map(schema.tables.map((t) => [t.name, t.columns.map((c) => c.name)]));\n for (const tableName of order) {\n const rows = effective.get(tableName)!;\n const columnOrder = declared.get(tableName)!;\n // Group consecutive-compatible rows into batches sharing a column signature.\n const batches = new Map<string, { columns: string[]; rows: Row[] }>();\n for (const row of rows) {\n const columns = columnOrder.filter((c) => row[c] !== undefined);\n const sig = columns.join(',');\n let batch = batches.get(sig);\n if (!batch) {\n batch = { columns, rows: [] };\n batches.set(sig, batch);\n }\n batch.rows.push(row);\n }\n for (const { columns, rows: batchRows } of batches.values()) {\n if (columns.length === 0) {\n for (let i = 0; i < batchRows.length; i++) {\n await run(query, tableName, `INSERT INTO ${quoteIdent(tableName)} DEFAULT VALUES`, []);\n }\n continue;\n }\n const params: unknown[] = [];\n const tuples = batchRows.map((row) => {\n const placeholders = columns.map((c) => {\n params.push(row[c]);\n return `$${params.length}`;\n });\n return `(${placeholders.join(', ')})`;\n });\n const sql =\n `INSERT INTO ${quoteIdent(tableName)} (${columns.map(quoteIdent).join(', ')}) ` +\n `VALUES ${tuples.join(', ')}`;\n await run(query, tableName, sql, params);\n }\n }\n}\n\nasync function run(\n query: (sql: string, params: unknown[]) => Promise<unknown>,\n tableName: string,\n sql: string,\n params: unknown[]\n): Promise<void> {\n try {\n await query(sql, params);\n } catch (err) {\n throw new TestDataError(\n `Failed to insert scenario rows into table \"${tableName}\": ${(err as Error).message}`\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { SqlStackError } from '../../core/errors';
|
|
2
|
+
/** Default matches docker/docker-compose.pg.yml (npm run db:pg:up). */
|
|
3
|
+
export declare const DEFAULT_ADMIN_URL = "postgres://postgres:postgres@127.0.0.1:55432/postgres";
|
|
4
|
+
export declare class TestPostgresServerError extends SqlStackError {
|
|
5
|
+
constructor(message: string);
|
|
6
|
+
}
|
|
7
|
+
export interface TestServerOptions {
|
|
8
|
+
/** Admin connection URL with CREATE/DROP DATABASE privilege. */
|
|
9
|
+
adminUrl?: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function resolveAdminUrl(options?: TestServerOptions): string;
|
|
12
|
+
export declare function loadPg(): Promise<any>;
|
|
13
|
+
/** Create a connected admin client, with an actionable diagnostic on failure. */
|
|
14
|
+
export declare function connectAdmin(options?: TestServerOptions): Promise<any>;
|
|
15
|
+
/** Hide password in URLs used inside diagnostics. */
|
|
16
|
+
export declare function redact(url: string): string;
|
|
17
|
+
/** Replace the database segment of a postgres URL. */
|
|
18
|
+
export declare function withDatabase(url: string, dbName: string): string;
|
|
19
|
+
//# sourceMappingURL=server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../../../src/testing/postgres/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,uEAAuE;AACvE,eAAO,MAAM,iBAAiB,0DAA0D,CAAC;AAEzF,qBAAa,uBAAwB,SAAQ,aAAa;gBAC5C,OAAO,EAAE,MAAM;CAI5B;AAED,MAAM,WAAW,iBAAiB;IAChC,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,eAAe,CAAC,OAAO,GAAE,iBAAsB,GAAG,MAAM,CAEvE;AAUD,wBAAsB,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,CAc3C;AAED,iFAAiF;AACjF,wBAAsB,YAAY,CAAC,OAAO,GAAE,iBAAsB,GAAG,OAAO,CAAC,GAAG,CAAC,CAqBhF;AAED,qDAAqD;AACrD,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE1C;AAED,sDAAsD;AACtD,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAIhE"}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TestPostgresServerError = exports.DEFAULT_ADMIN_URL = void 0;
|
|
4
|
+
exports.resolveAdminUrl = resolveAdminUrl;
|
|
5
|
+
exports.loadPg = loadPg;
|
|
6
|
+
exports.connectAdmin = connectAdmin;
|
|
7
|
+
exports.redact = redact;
|
|
8
|
+
exports.withDatabase = withDatabase;
|
|
9
|
+
const errors_1 = require("../../core/errors");
|
|
10
|
+
/** Default matches docker/docker-compose.pg.yml (npm run db:pg:up). */
|
|
11
|
+
exports.DEFAULT_ADMIN_URL = 'postgres://postgres:postgres@127.0.0.1:55432/postgres';
|
|
12
|
+
class TestPostgresServerError extends errors_1.SqlStackError {
|
|
13
|
+
constructor(message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = 'TestPostgresServerError';
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
exports.TestPostgresServerError = TestPostgresServerError;
|
|
19
|
+
function resolveAdminUrl(options = {}) {
|
|
20
|
+
return options.adminUrl ?? process.env.SQLSTACK_TEST_PG_URL ?? exports.DEFAULT_ADMIN_URL;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Load the `pg` driver lazily so browser/Worker bundles that never import
|
|
24
|
+
* sqlstack/testing do not see it. Testing is Node-only.
|
|
25
|
+
*/
|
|
26
|
+
const dynamicImport =
|
|
27
|
+
// Indirect so neither tsc's CJS downlevel nor bundlers statically link "pg".
|
|
28
|
+
new Function('specifier', 'return import(specifier)');
|
|
29
|
+
async function loadPg() {
|
|
30
|
+
// CJS path first (also covers jest's VM, where dynamic import is unavailable).
|
|
31
|
+
try {
|
|
32
|
+
if (typeof require === 'function')
|
|
33
|
+
return require('pg');
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
/* fall through to dynamic import */
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
return await dynamicImport('pg');
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw new TestPostgresServerError(`sqlstack/testing requires the optional "pg" package. Install it in your project (npm i -D pg).`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Create a connected admin client, with an actionable diagnostic on failure. */
|
|
46
|
+
async function connectAdmin(options = {}) {
|
|
47
|
+
const url = resolveAdminUrl(options);
|
|
48
|
+
const pg = await loadPg();
|
|
49
|
+
const Client = pg.Client ?? pg.default?.Client;
|
|
50
|
+
const client = new Client({ connectionString: url });
|
|
51
|
+
try {
|
|
52
|
+
await client.connect();
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
try {
|
|
56
|
+
await client.end();
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
/* ignore */
|
|
60
|
+
}
|
|
61
|
+
throw new TestPostgresServerError(`Cannot connect to the test PostgreSQL server at ${redact(url)}: ${err.message}\n` +
|
|
62
|
+
`- If you use the bundled docker server, start it with: npm run db:pg:up\n` +
|
|
63
|
+
`- Otherwise set SQLSTACK_TEST_PG_URL (or pass options.adminUrl) to an admin URL with ` +
|
|
64
|
+
`permission to CREATE/DROP DATABASE.`);
|
|
65
|
+
}
|
|
66
|
+
return client;
|
|
67
|
+
}
|
|
68
|
+
/** Hide password in URLs used inside diagnostics. */
|
|
69
|
+
function redact(url) {
|
|
70
|
+
return url.replace(/\/\/([^:@/]+):[^@/]+@/, '//$1:***@');
|
|
71
|
+
}
|
|
72
|
+
/** Replace the database segment of a postgres URL. */
|
|
73
|
+
function withDatabase(url, dbName) {
|
|
74
|
+
const u = new URL(url);
|
|
75
|
+
u.pathname = `/${dbName}`;
|
|
76
|
+
return u.toString();
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../src/testing/postgres/server.ts"],"names":[],"mappings":";;;AAiBA,0CAEC;AAUD,wBAcC;AAGD,oCAqBC;AAGD,wBAEC;AAGD,oCAIC;AA/ED,8CAAkD;AAElD,uEAAuE;AAC1D,QAAA,iBAAiB,GAAG,uDAAuD,CAAC;AAEzF,MAAa,uBAAwB,SAAQ,sBAAa;IACxD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AALD,0DAKC;AAOD,SAAgB,eAAe,CAAC,UAA6B,EAAE;IAC7D,OAAO,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,yBAAiB,CAAC;AACnF,CAAC;AAED;;;GAGG;AACH,MAAM,aAAa;AAC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O,GAAG,CAAC,OAAO,CAAC,uBAAuB,EAAE,WAAW,CAAC,CAAC;AAC3D,CAAC;AAED,sDAAsD;AACtD,SAAgB,YAAY,CAAC,GAAW,EAAE,MAAc;IACtD,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IACvB,CAAC,CAAC,QAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;IAC1B,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import { SqlStackError } from '../../core/errors';\n\n/** Default matches docker/docker-compose.pg.yml (npm run db:pg:up). */\nexport const DEFAULT_ADMIN_URL = 'postgres://postgres:postgres@127.0.0.1:55432/postgres';\n\nexport class TestPostgresServerError extends SqlStackError {\n constructor(message: string) {\n super(message);\n this.name = 'TestPostgresServerError';\n }\n}\n\nexport interface TestServerOptions {\n /** Admin connection URL with CREATE/DROP DATABASE privilege. */\n adminUrl?: string;\n}\n\nexport function resolveAdminUrl(options: TestServerOptions = {}): string {\n return options.adminUrl ?? process.env.SQLSTACK_TEST_PG_URL ?? DEFAULT_ADMIN_URL;\n}\n\n/**\n * Load the `pg` driver lazily so browser/Worker bundles that never import\n * sqlstack/testing do not see it. Testing is Node-only.\n */\nconst dynamicImport: (specifier: string) => Promise<any> =\n // Indirect so neither tsc's CJS downlevel nor bundlers statically link \"pg\".\n new Function('specifier', 'return import(specifier)') as any;\n\nexport async function loadPg(): Promise<any> {\n // CJS path first (also covers jest's VM, where dynamic import is unavailable).\n try {\n if (typeof require === 'function') return require('pg');\n } catch {\n /* fall through to dynamic import */\n }\n try {\n return await dynamicImport('pg');\n } catch {\n throw new TestPostgresServerError(\n `sqlstack/testing requires the optional \"pg\" package. Install it in your project (npm i -D pg).`\n );\n }\n}\n\n/** Create a connected admin client, with an actionable diagnostic on failure. */\nexport async function connectAdmin(options: TestServerOptions = {}): Promise<any> {\n const url = resolveAdminUrl(options);\n const pg = await loadPg();\n const Client = pg.Client ?? pg.default?.Client;\n const client = new Client({ connectionString: url });\n try {\n await client.connect();\n } catch (err) {\n try {\n await client.end();\n } catch {\n /* ignore */\n }\n throw new TestPostgresServerError(\n `Cannot connect to the test PostgreSQL server at ${redact(url)}: ${(err as Error).message}\\n` +\n `- If you use the bundled docker server, start it with: npm run db:pg:up\\n` +\n `- Otherwise set SQLSTACK_TEST_PG_URL (or pass options.adminUrl) to an admin URL with ` +\n `permission to CREATE/DROP DATABASE.`\n );\n }\n return client;\n}\n\n/** Hide password in URLs used inside diagnostics. */\nexport function redact(url: string): string {\n return url.replace(/\\/\\/([^:@/]+):[^@/]+@/, '//$1:***@');\n}\n\n/** Replace the database segment of a postgres URL. */\nexport function withDatabase(url: string, dbName: string): string {\n const u = new URL(url);\n u.pathname = `/${dbName}`;\n return u.toString();\n}\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { NormalizedTable, NormalizedTestSchema } from './types';
|
|
2
|
+
/** Quote a (pre-validated) identifier for PostgreSQL. */
|
|
3
|
+
export declare function quoteIdent(name: string): string;
|
|
4
|
+
export declare function generateTableDdl(table: NormalizedTable): string;
|
|
5
|
+
/**
|
|
6
|
+
* Deterministic DDL for the structured tables.
|
|
7
|
+
*
|
|
8
|
+
* Tables are created in authored order without inline foreign keys; declared
|
|
9
|
+
* references are then added as ALTER TABLE statements so authored table
|
|
10
|
+
* order never has to match dependency order. Raw SQL entries are applied by
|
|
11
|
+
* the builder after these statements, in authored order.
|
|
12
|
+
*/
|
|
13
|
+
export declare function generateDdl(schema: NormalizedTestSchema): string[];
|
|
14
|
+
//# sourceMappingURL=ddl.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ddl.d.ts","sourceRoot":"","sources":["../../../../src/testing/schema/ddl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAErE,yDAAyD;AACzD,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AASD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAa/D;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,oBAAoB,GAAG,MAAM,EAAE,CAgBlE"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.quoteIdent = quoteIdent;
|
|
4
|
+
exports.generateTableDdl = generateTableDdl;
|
|
5
|
+
exports.generateDdl = generateDdl;
|
|
6
|
+
/** Quote a (pre-validated) identifier for PostgreSQL. */
|
|
7
|
+
function quoteIdent(name) {
|
|
8
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
9
|
+
}
|
|
10
|
+
function renderDefault(value) {
|
|
11
|
+
// String defaults are raw SQL expressions (e.g. now(), 'active', gen_random_uuid()).
|
|
12
|
+
if (typeof value === 'string')
|
|
13
|
+
return value;
|
|
14
|
+
if (typeof value === 'boolean')
|
|
15
|
+
return value ? 'TRUE' : 'FALSE';
|
|
16
|
+
return String(value);
|
|
17
|
+
}
|
|
18
|
+
function generateTableDdl(table) {
|
|
19
|
+
const lines = [];
|
|
20
|
+
for (const col of table.columns) {
|
|
21
|
+
let line = ` ${quoteIdent(col.name)} ${col.type}`;
|
|
22
|
+
if (!col.nullable && !col.primary)
|
|
23
|
+
line += ' NOT NULL';
|
|
24
|
+
if (col.unique && !col.primary)
|
|
25
|
+
line += ' UNIQUE';
|
|
26
|
+
if (col.hasDefault)
|
|
27
|
+
line += ` DEFAULT ${renderDefault(col.default)}`;
|
|
28
|
+
lines.push(line);
|
|
29
|
+
}
|
|
30
|
+
if (table.primaryKey.length > 0) {
|
|
31
|
+
lines.push(` PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(', ')})`);
|
|
32
|
+
}
|
|
33
|
+
return `CREATE TABLE ${quoteIdent(table.name)} (\n${lines.join(',\n')}\n)`;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Deterministic DDL for the structured tables.
|
|
37
|
+
*
|
|
38
|
+
* Tables are created in authored order without inline foreign keys; declared
|
|
39
|
+
* references are then added as ALTER TABLE statements so authored table
|
|
40
|
+
* order never has to match dependency order. Raw SQL entries are applied by
|
|
41
|
+
* the builder after these statements, in authored order.
|
|
42
|
+
*/
|
|
43
|
+
function generateDdl(schema) {
|
|
44
|
+
const statements = schema.tables.map(generateTableDdl);
|
|
45
|
+
for (const table of schema.tables) {
|
|
46
|
+
for (const col of table.columns) {
|
|
47
|
+
if (col.references) {
|
|
48
|
+
statements.push(`ALTER TABLE ${quoteIdent(table.name)} ADD CONSTRAINT ${quoteIdent(`fk_${table.name}_${col.name}`)} FOREIGN KEY (${quoteIdent(col.name)}) REFERENCES ${quoteIdent(col.references.table)} (${quoteIdent(col.references.column)})`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return statements;
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=ddl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ddl.js","sourceRoot":"","sources":["../../../../src/testing/schema/ddl.ts"],"names":[],"mappings":";;AAGA,gCAEC;AASD,4CAaC;AAUD,kCAgBC;AAnDD,yDAAyD;AACzD,SAAgB,UAAU,CAAC,IAAY;IACrC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC;AACzC,CAAC;AAED,SAAS,aAAa,CAAC,KAAgC;IACrD,qFAAqF;IACrF,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IAChE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;AACvB,CAAC;AAED,SAAgB,gBAAg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AAU,CAAC,KAAK,CAAC,IAAI,CAAC,mBAAmB,UAAU,CAChE,MAAM,KAAK,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,EAAE,CAC/B,iBAAiB,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,gBAAgB,UAAU,CAC9D,GAAG,CAAC,UAAU,CAAC,KAAK,CACrB,KAAK,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,CAC3C,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import type { NormalizedTable, NormalizedTestSchema } from './types';\n\n/** Quote a (pre-validated) identifier for PostgreSQL. */\nexport function quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction renderDefault(value: string | number | boolean): string {\n // String defaults are raw SQL expressions (e.g. now(), 'active', gen_random_uuid()).\n if (typeof value === 'string') return value;\n if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE';\n return String(value);\n}\n\nexport function generateTableDdl(table: NormalizedTable): string {\n const lines: string[] = [];\n for (const col of table.columns) {\n let line = ` ${quoteIdent(col.name)} ${col.type}`;\n if (!col.nullable && !col.primary) line += ' NOT NULL';\n if (col.unique && !col.primary) line += ' UNIQUE';\n if (col.hasDefault) line += ` DEFAULT ${renderDefault(col.default!)}`;\n lines.push(line);\n }\n if (table.primaryKey.length > 0) {\n lines.push(` PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(', ')})`);\n }\n return `CREATE TABLE ${quoteIdent(table.name)} (\\n${lines.join(',\\n')}\\n)`;\n}\n\n/**\n * Deterministic DDL for the structured tables.\n *\n * Tables are created in authored order without inline foreign keys; declared\n * references are then added as ALTER TABLE statements so authored table\n * order never has to match dependency order. Raw SQL entries are applied by\n * the builder after these statements, in authored order.\n */\nexport function generateDdl(schema: NormalizedTestSchema): string[] {\n const statements = schema.tables.map(generateTableDdl);\n for (const table of schema.tables) {\n for (const col of table.columns) {\n if (col.references) {\n statements.push(\n `ALTER TABLE ${quoteIdent(table.name)} ADD CONSTRAINT ${quoteIdent(\n `fk_${table.name}_${col.name}`\n )} FOREIGN KEY (${quoteIdent(col.name)}) REFERENCES ${quoteIdent(\n col.references.table\n )} (${quoteIdent(col.references.column)})`\n );\n }\n }\n }\n return statements;\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { SqlStackError } from '../../core/errors';
|
|
2
|
+
import type { NormalizedTestSchema, ParseTestSchemaOptions } from './types';
|
|
3
|
+
export declare class TestSchemaError extends SqlStackError {
|
|
4
|
+
constructor(message: string, source?: string);
|
|
5
|
+
}
|
|
6
|
+
export declare function normalizeTestSchema(doc: unknown, options?: ParseTestSchemaOptions): NormalizedTestSchema;
|
|
7
|
+
//# sourceMappingURL=normalize.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalize.d.ts","sourceRoot":"","sources":["../../../../src/testing/schema/normalize.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAIV,oBAAoB,EACpB,sBAAsB,EAEvB,MAAM,SAAS,CAAC;AAEjB,qBAAa,eAAgB,SAAQ,aAAa;gBACpC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;CAI7C;AAkID,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,OAAO,EACZ,OAAO,GAAE,sBAA2B,GACnC,oBAAoB,CAsEtB"}
|