sqlstack 2.0.0 → 3.1.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/codegen/generateManifest.d.ts +12 -0
- package/dist/cjs/codegen/generateManifest.d.ts.map +1 -1
- package/dist/cjs/codegen/generateManifest.js +21 -11
- package/dist/cjs/codegen/generateManifest.js.map +1 -1
- package/dist/cjs/core/resolver.d.ts +25 -12
- package/dist/cjs/core/resolver.d.ts.map +1 -1
- package/dist/cjs/core/resolver.js +66 -20
- package/dist/cjs/core/resolver.js.map +1 -1
- 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 +276 -245
- 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 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +17 -2
- 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/run.d.ts +29 -0
- package/dist/cjs/run.d.ts.map +1 -0
- package/dist/cjs/run.js +38 -0
- package/dist/cjs/run.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 +14 -0
- package/dist/cjs/testing/index.d.ts.map +1 -0
- package/dist/cjs/testing/index.js +22 -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 +5 -0
- package/dist/cjs/testing/schema/ddl.d.ts.map +1 -0
- package/dist/cjs/testing/schema/ddl.js +70 -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 +63 -0
- package/dist/cjs/testing/schema/types.d.ts.map +1 -0
- package/dist/cjs/testing/schema/types.js +6 -0
- package/dist/cjs/testing/schema/types.js.map +1 -0
- package/dist/cjs/testing/sqlite/builder.d.ts +24 -0
- package/dist/cjs/testing/sqlite/builder.d.ts.map +1 -0
- package/dist/cjs/testing/sqlite/builder.js +134 -0
- package/dist/cjs/testing/sqlite/builder.js.map +1 -0
- package/dist/cjs/testing/sqlite/database.d.ts +18 -0
- package/dist/cjs/testing/sqlite/database.d.ts.map +1 -0
- package/dist/cjs/testing/sqlite/database.js +123 -0
- package/dist/cjs/testing/sqlite/database.js.map +1 -0
- package/dist/cjs/testing/sqlite/loadData.d.ts +7 -0
- package/dist/cjs/testing/sqlite/loadData.d.ts.map +1 -0
- package/dist/cjs/testing/sqlite/loadData.js +55 -0
- package/dist/cjs/testing/sqlite/loadData.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/codegen/generateManifest.js +20 -11
- package/dist/esm/codegen/generateManifest.js.map +1 -1
- package/dist/esm/core/resolver.js +59 -19
- package/dist/esm/core/resolver.js.map +1 -1
- package/dist/esm/core/sourceScanResolver.js +51 -0
- package/dist/esm/core/sourceScanResolver.js.map +1 -0
- package/dist/esm/decorators/query.js +278 -247
- 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 +10 -1
- 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/run.js +34 -0
- package/dist/esm/run.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 +9 -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 +65 -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 +5 -0
- package/dist/esm/testing/schema/types.js.map +1 -0
- package/dist/esm/testing/sqlite/builder.js +98 -0
- package/dist/esm/testing/sqlite/builder.js.map +1 -0
- package/dist/esm/testing/sqlite/database.js +85 -0
- package/dist/esm/testing/sqlite/database.js.map +1 -0
- package/dist/esm/testing/sqlite/loadData.js +48 -0
- package/dist/esm/testing/sqlite/loadData.js.map +1 -0
- package/dist/esm/transactions.js +39 -24
- package/dist/esm/transactions.js.map +1 -1
- package/package.json +19 -2
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { randomBytes } from 'crypto';
|
|
2
|
+
import { connectAdmin, redact, resolveAdminUrl, TestPostgresServerError, withDatabase, } from './server.js';
|
|
3
|
+
const NAME_PREFIX = 'sqlstack_test_';
|
|
4
|
+
let counter = 0;
|
|
5
|
+
/**
|
|
6
|
+
* Unique, safe, bounded-length database name. Randomness plus a process
|
|
7
|
+
* counter keeps parallel builds (including across worker processes)
|
|
8
|
+
* collision-free. Always well under PostgreSQL's 63-byte identifier limit.
|
|
9
|
+
*/
|
|
10
|
+
export function nextDatabaseName() {
|
|
11
|
+
counter += 1;
|
|
12
|
+
return `${NAME_PREFIX}${randomBytes(4).toString('hex')}_${counter}`;
|
|
13
|
+
}
|
|
14
|
+
/** Create a fresh uniquely named database on the configured test server. */
|
|
15
|
+
export async function allocateDatabase(options = {}) {
|
|
16
|
+
const adminUrl = resolveAdminUrl(options);
|
|
17
|
+
const name = nextDatabaseName();
|
|
18
|
+
const admin = await connectAdmin(options);
|
|
19
|
+
try {
|
|
20
|
+
await admin.query(`CREATE DATABASE "${name}"`);
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
throw new TestPostgresServerError(`Failed to create test database "${name}" on ${redact(adminUrl)}: ${err.message}\n` +
|
|
24
|
+
`The admin connection must have CREATE DATABASE privilege ` +
|
|
25
|
+
`(set SQLSTACK_TEST_PG_URL or options.adminUrl; start the bundled server with npm run db:pg:up).`);
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await admin.end().catch(() => undefined);
|
|
29
|
+
}
|
|
30
|
+
return { name, url: withDatabase(adminUrl, name), adminUrl };
|
|
31
|
+
}
|
|
32
|
+
/** Drop exactly the named database. Safe to call for an already-dropped db. */
|
|
33
|
+
export async function dropDatabase(name, options = {}) {
|
|
34
|
+
if (!name.startsWith(NAME_PREFIX)) {
|
|
35
|
+
throw new TestPostgresServerError(`Refusing to drop database "${name}": not an sqlstack test database (expected prefix ${NAME_PREFIX})`);
|
|
36
|
+
}
|
|
37
|
+
const admin = await connectAdmin(options);
|
|
38
|
+
try {
|
|
39
|
+
// FORCE (PG 13+) terminates lingering sessions so parallel teardown is robust.
|
|
40
|
+
await admin.query(`DROP DATABASE IF EXISTS "${name}" WITH (FORCE)`);
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
throw new TestPostgresServerError(`Failed to drop test database "${name}" on ${redact(resolveAdminUrl(options))}: ${err.message}`);
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
await admin.end().catch(() => undefined);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=allocator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"allocator.js","sourceRoot":"","sources":["../../../../src/testing/postgres/allocator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,QAAQ,CAAC;AACrC,OAAO,EACL,YAAY,EACZ,MAAM,EACN,eAAe,EACf,uBAAuB,EAEvB,YAAY,GACb,MAAM,UAAU,CAAC;AAElB,MAAM,WAAW,GAAG,gBAAgB,CAAC;AACrC,IAAI,OAAO,GAAG,CAAC,CAAC;AAEhB;;;;GAIG;AACH,MAAM,UAAU,gBAAgB;IAC9B,OAAO,IAAI,CAAC,CAAC;IACb,OAAO,GAAG,WAAW,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,EAAE,CAAC;AACtE,CAAC;AAQD,4EAA4E;AAC5E,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,UAA6B,EAAE;IACpE,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;IAC1C,MAAM,IAAI,GAAG,gBAAgB,EAAE,CAAC;IAChC,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,OAAO,CAAC,CAAC;IAC1C,IA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,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,36 @@
|
|
|
1
|
+
import { dropDatabase } from './allocator.js';
|
|
2
|
+
import { loadPg, TestPostgresServerError } from './server.js';
|
|
3
|
+
/**
|
|
4
|
+
* Connect a helper pool to an allocated database and produce the handle.
|
|
5
|
+
* The handle owns exactly this database and drops it on dispose.
|
|
6
|
+
*/
|
|
7
|
+
export async function createDatabaseHandle(owned, options = {}) {
|
|
8
|
+
const pg = await loadPg();
|
|
9
|
+
const Pool = pg.Pool ?? pg.default?.Pool;
|
|
10
|
+
const pool = new Pool({ connectionString: owned.url, max: 4 });
|
|
11
|
+
let disposed = false;
|
|
12
|
+
return {
|
|
13
|
+
url: owned.url,
|
|
14
|
+
_pool: pool,
|
|
15
|
+
async query(sql, params = []) {
|
|
16
|
+
if (disposed) {
|
|
17
|
+
throw new TestPostgresServerError(`Test database "${owned.name}" has been disposed; no further queries are possible.`);
|
|
18
|
+
}
|
|
19
|
+
const res = await pool.query(sql, params);
|
|
20
|
+
return res.rows;
|
|
21
|
+
},
|
|
22
|
+
async dispose() {
|
|
23
|
+
if (disposed)
|
|
24
|
+
return;
|
|
25
|
+
disposed = true;
|
|
26
|
+
try {
|
|
27
|
+
await pool.end();
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
/* pool may already be closed */
|
|
31
|
+
}
|
|
32
|
+
await dropDatabase(owned.name, options);
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=database.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"database.js","sourceRoot":"","sources":["../../../../src/testing/postgres/database.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,MAAM,EAAE,uBAAuB,EAAqB,MAAM,UAAU,CAAC;AAgB9E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,KAAoB,EACpB,UAA6B,EAAE;IAE/B,MAAM,EAAE,GAAG,MAAM,MAAM,EAAE,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,uBAAuB,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,YAAY,CAAC,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,176 @@
|
|
|
1
|
+
import { SqlStackError } from '../../core/errors.js';
|
|
2
|
+
import { quoteIdent } from '../schema/ddl.js';
|
|
3
|
+
export class TestDataError extends SqlStackError {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'TestDataError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Validate one `.data()` payload against the structured schema (fail-fast). */
|
|
10
|
+
export function toOperations(schema, data) {
|
|
11
|
+
const ops = [];
|
|
12
|
+
const tables = new Map(schema.tables.map((t) => [t.name, t]));
|
|
13
|
+
for (const [tableName, rows] of Object.entries(data)) {
|
|
14
|
+
const table = tables.get(tableName);
|
|
15
|
+
if (!table) {
|
|
16
|
+
const known = schema.tables.map((t) => t.name).join(', ') || '(none)';
|
|
17
|
+
throw new TestDataError(`.data(): unknown table "${tableName}". Structured tables declared in ${schema.source}: ${known}. ` +
|
|
18
|
+
`Tables created only through raw SQL cannot receive .data() rows; insert them via raw SQL instead.`);
|
|
19
|
+
}
|
|
20
|
+
if (!Array.isArray(rows)) {
|
|
21
|
+
throw new TestDataError(`.data(): rows for table "${tableName}" must be an array`);
|
|
22
|
+
}
|
|
23
|
+
const columnNames = new Set(table.columns.map((c) => c.name));
|
|
24
|
+
rows.forEach((row, i) => {
|
|
25
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) {
|
|
26
|
+
throw new TestDataError(`.data(): row #${i} for table "${tableName}" must be an object`);
|
|
27
|
+
}
|
|
28
|
+
for (const key of Object.keys(row)) {
|
|
29
|
+
if (!columnNames.has(key)) {
|
|
30
|
+
throw new TestDataError(`.data(): unknown column "${key}" in row #${i} for table "${tableName}" ` +
|
|
31
|
+
`(declared columns: ${[...columnNames].join(', ')})`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
for (const pk of table.primaryKey) {
|
|
35
|
+
if (row[pk] === undefined) {
|
|
36
|
+
throw new TestDataError(`.data(): row #${i} for table "${tableName}" is missing primary-key column "${pk}" ` +
|
|
37
|
+
`(primary key: ${table.primaryKey.join(', ')})`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
ops.push({ table: tableName, row });
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return ops;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Compose row operations into effective rows per table.
|
|
47
|
+
* PK tables: identity = ordered PK values; later writes replace, first
|
|
48
|
+
* occurrence keeps its position. No-PK tables: append in authored order.
|
|
49
|
+
*/
|
|
50
|
+
export function composeRows(schema, ops) {
|
|
51
|
+
const tables = new Map(schema.tables.map((t) => [t.name, t]));
|
|
52
|
+
const result = new Map();
|
|
53
|
+
const identityIndex = new Map();
|
|
54
|
+
for (const op of ops) {
|
|
55
|
+
const table = tables.get(op.table);
|
|
56
|
+
let rows = result.get(op.table);
|
|
57
|
+
if (!rows) {
|
|
58
|
+
rows = [];
|
|
59
|
+
result.set(op.table, rows);
|
|
60
|
+
}
|
|
61
|
+
if (table.primaryKey.length === 0) {
|
|
62
|
+
rows.push(op.row);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const identity = JSON.stringify(table.primaryKey.map((pk) => op.row[pk]));
|
|
66
|
+
let index = identityIndex.get(op.table);
|
|
67
|
+
if (!index) {
|
|
68
|
+
index = new Map();
|
|
69
|
+
identityIndex.set(op.table, index);
|
|
70
|
+
}
|
|
71
|
+
const existing = index.get(identity);
|
|
72
|
+
if (existing === undefined) {
|
|
73
|
+
index.set(identity, rows.length);
|
|
74
|
+
rows.push(op.row);
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
rows[existing] = op.row;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return result;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Deterministic insertion order for the tables that actually have rows,
|
|
84
|
+
* topologically sorted by declared references between those tables.
|
|
85
|
+
* Cycles fail with actionable guidance.
|
|
86
|
+
*/
|
|
87
|
+
export function planInsertOrder(schema, tablesWithRows) {
|
|
88
|
+
const inPlan = new Set(tablesWithRows);
|
|
89
|
+
const tables = schema.tables.filter((t) => inPlan.has(t.name));
|
|
90
|
+
// deps[t] = set of tables (with rows) that must be inserted before t
|
|
91
|
+
const deps = new Map();
|
|
92
|
+
for (const t of tables) {
|
|
93
|
+
const set = new Set();
|
|
94
|
+
for (const c of t.columns) {
|
|
95
|
+
if (c.references && c.references.table !== t.name && inPlan.has(c.references.table)) {
|
|
96
|
+
set.add(c.references.table);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
deps.set(t.name, set);
|
|
100
|
+
}
|
|
101
|
+
const order = [];
|
|
102
|
+
const done = new Set();
|
|
103
|
+
let progressed = true;
|
|
104
|
+
while (progressed && order.length < tables.length) {
|
|
105
|
+
progressed = false;
|
|
106
|
+
for (const t of tables) {
|
|
107
|
+
if (done.has(t.name))
|
|
108
|
+
continue;
|
|
109
|
+
const pending = [...deps.get(t.name)].filter((d) => !done.has(d));
|
|
110
|
+
if (pending.length === 0) {
|
|
111
|
+
order.push(t.name);
|
|
112
|
+
done.add(t.name);
|
|
113
|
+
progressed = true;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (order.length < tables.length) {
|
|
118
|
+
const cycle = tables.filter((t) => !done.has(t.name)).map((t) => t.name);
|
|
119
|
+
throw new TestDataError(`Cannot derive an insertion order: declared references between tables [${cycle.join(', ')}] form a cycle. ` +
|
|
120
|
+
`Insert this data via a raw "sql" entry (e.g. with deferred constraints), or restructure the references.`);
|
|
121
|
+
}
|
|
122
|
+
return order;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Insert effective rows. Parameterized and batched per table by column
|
|
126
|
+
* signature; missing columns are omitted from the INSERT so PostgreSQL
|
|
127
|
+
* defaults apply, while explicit null is sent as NULL.
|
|
128
|
+
*/
|
|
129
|
+
export async function insertRows(query, schema, effective) {
|
|
130
|
+
const order = planInsertOrder(schema, [...effective.keys()]);
|
|
131
|
+
const declared = new Map(schema.tables.map((t) => [t.name, t.columns.map((c) => c.name)]));
|
|
132
|
+
for (const tableName of order) {
|
|
133
|
+
const rows = effective.get(tableName);
|
|
134
|
+
const columnOrder = declared.get(tableName);
|
|
135
|
+
// Group consecutive-compatible rows into batches sharing a column signature.
|
|
136
|
+
const batches = new Map();
|
|
137
|
+
for (const row of rows) {
|
|
138
|
+
const columns = columnOrder.filter((c) => row[c] !== undefined);
|
|
139
|
+
const sig = columns.join(',');
|
|
140
|
+
let batch = batches.get(sig);
|
|
141
|
+
if (!batch) {
|
|
142
|
+
batch = { columns, rows: [] };
|
|
143
|
+
batches.set(sig, batch);
|
|
144
|
+
}
|
|
145
|
+
batch.rows.push(row);
|
|
146
|
+
}
|
|
147
|
+
for (const { columns, rows: batchRows } of batches.values()) {
|
|
148
|
+
if (columns.length === 0) {
|
|
149
|
+
for (let i = 0; i < batchRows.length; i++) {
|
|
150
|
+
await run(query, tableName, `INSERT INTO ${quoteIdent(tableName)} DEFAULT VALUES`, []);
|
|
151
|
+
}
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const params = [];
|
|
155
|
+
const tuples = batchRows.map((row) => {
|
|
156
|
+
const placeholders = columns.map((c) => {
|
|
157
|
+
params.push(row[c]);
|
|
158
|
+
return `$${params.length}`;
|
|
159
|
+
});
|
|
160
|
+
return `(${placeholders.join(', ')})`;
|
|
161
|
+
});
|
|
162
|
+
const sql = `INSERT INTO ${quoteIdent(tableName)} (${columns.map(quoteIdent).join(', ')}) ` +
|
|
163
|
+
`VALUES ${tuples.join(', ')}`;
|
|
164
|
+
await run(query, tableName, sql, params);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
async function run(query, tableName, sql, params) {
|
|
169
|
+
try {
|
|
170
|
+
await query(sql, params);
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
throw new TestDataError(`Failed to insert scenario rows into table "${tableName}": ${err.message}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
//# sourceMappingURL=loadData.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loadData.js","sourceRoot":"","sources":["../../../../src/testing/postgres/loadData.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAG3C,MAAM,OAAO,aAAc,SAAQ,aAAa;IAC9C,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AASD,gFAAgF;AAChF,MAAM,UAAU,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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ACnC,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;oBACrC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;oBACpB,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;gBAC7B,CAAC,CAAC,CAAC;gBACH,OAAO,IAAI,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;YACxC,CAAC,CAAC,CAAC;YACH,MAAM,GAAG,GACP,eAAe,UAAU,CAAC,SAAS,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,UAAU,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,69 @@
|
|
|
1
|
+
import { SqlStackError } from '../../core/errors.js';
|
|
2
|
+
/** Default matches docker/docker-compose.pg.yml (npm run db:pg:up). */
|
|
3
|
+
export const DEFAULT_ADMIN_URL = 'postgres://postgres:postgres@127.0.0.1:55432/postgres';
|
|
4
|
+
export class TestPostgresServerError extends SqlStackError {
|
|
5
|
+
constructor(message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'TestPostgresServerError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function resolveAdminUrl(options = {}) {
|
|
11
|
+
return options.adminUrl ?? process.env.SQLSTACK_TEST_PG_URL ?? DEFAULT_ADMIN_URL;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Load the `pg` driver lazily so browser/Worker bundles that never import
|
|
15
|
+
* sqlstack/testing do not see it. Testing is Node-only.
|
|
16
|
+
*/
|
|
17
|
+
const dynamicImport =
|
|
18
|
+
// Indirect so neither tsc's CJS downlevel nor bundlers statically link "pg".
|
|
19
|
+
new Function('specifier', 'return import(specifier)');
|
|
20
|
+
export async function loadPg() {
|
|
21
|
+
// CJS path first (also covers jest's VM, where dynamic import is unavailable).
|
|
22
|
+
try {
|
|
23
|
+
if (typeof require === 'function')
|
|
24
|
+
return require('pg');
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
/* fall through to dynamic import */
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
return await dynamicImport('pg');
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
throw new TestPostgresServerError(`sqlstack/testing requires the optional "pg" package. Install it in your project (npm i -D pg).`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** Create a connected admin client, with an actionable diagnostic on failure. */
|
|
37
|
+
export async function connectAdmin(options = {}) {
|
|
38
|
+
const url = resolveAdminUrl(options);
|
|
39
|
+
const pg = await loadPg();
|
|
40
|
+
const Client = pg.Client ?? pg.default?.Client;
|
|
41
|
+
const client = new Client({ connectionString: url });
|
|
42
|
+
try {
|
|
43
|
+
await client.connect();
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
try {
|
|
47
|
+
await client.end();
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
/* ignore */
|
|
51
|
+
}
|
|
52
|
+
throw new TestPostgresServerError(`Cannot connect to the test PostgreSQL server at ${redact(url)}: ${err.message}\n` +
|
|
53
|
+
`- If you use the bundled docker server, start it with: npm run db:pg:up\n` +
|
|
54
|
+
`- Otherwise set SQLSTACK_TEST_PG_URL (or pass options.adminUrl) to an admin URL with ` +
|
|
55
|
+
`permission to CREATE/DROP DATABASE.`);
|
|
56
|
+
}
|
|
57
|
+
return client;
|
|
58
|
+
}
|
|
59
|
+
/** Hide password in URLs used inside diagnostics. */
|
|
60
|
+
export function redact(url) {
|
|
61
|
+
return url.replace(/\/\/([^:@/]+):[^@/]+@/, '//$1:***@');
|
|
62
|
+
}
|
|
63
|
+
/** Replace the database segment of a postgres URL. */
|
|
64
|
+
export function withDatabase(url, dbName) {
|
|
65
|
+
const u = new URL(url);
|
|
66
|
+
u.pathname = `/${dbName}`;
|
|
67
|
+
return u.toString();
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../../../src/testing/postgres/server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAElD,uEAAuE;AACvE,MAAM,CAAC,MAAM,iBAAiB,GAAG,uDAAuD,CAAC;AAEzF,MAAM,OAAO,uBAAwB,SAAQ,aAAa;IACxD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACxC,CAAC;CACF;AAOD,MAAM,UAAU,eAAe,CAAC,UAA6B,EAAE;IAC7D,OAAO,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,oBAAoB,IAAI,iBAAiB,CAAC;AACnF,CAAC;AAED;;;GAGG;AACH,MAAM,aAAa;AACjB,6EAA6E;AAC7E,IAAI,QAAQ,CAAC,WAAW,EAAE,0BAA0B,CAAQ,CAAC;AAE/D,MAAM,CAAC,KAAK,UAAU,MAAM;IAC1B,+EAA+E;IAC/E,IAAI,CAAC;QACH,IAAI,OAAO,OAAO,KAAK,UAAU;YAAE,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1D,CAAC;IAAC,MAAM,CAAC;QACP,oCAAoC;IACtC,CAAC;IACD,IAAI,CAAC;QACH,OAAO,MAAM,aAAa,CAAC,IAA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,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,65 @@
|
|
|
1
|
+
export function quoteIdent(name) {
|
|
2
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
3
|
+
}
|
|
4
|
+
function renderDefault(value) {
|
|
5
|
+
if (typeof value === 'string')
|
|
6
|
+
return value;
|
|
7
|
+
if (typeof value === 'boolean')
|
|
8
|
+
return value ? 'TRUE' : 'FALSE';
|
|
9
|
+
return String(value);
|
|
10
|
+
}
|
|
11
|
+
function sqliteType(type) {
|
|
12
|
+
const normalized = type.trim().toLowerCase();
|
|
13
|
+
if (normalized === 'uuid')
|
|
14
|
+
return 'TEXT';
|
|
15
|
+
if (/^(timestamp|timestamptz)(\s+with(out)?\s+time\s+zone)?$/.test(normalized))
|
|
16
|
+
return 'TEXT';
|
|
17
|
+
if (normalized === 'json' || normalized === 'jsonb')
|
|
18
|
+
return 'TEXT';
|
|
19
|
+
if (normalized === 'boolean' || normalized === 'bool')
|
|
20
|
+
return 'INTEGER';
|
|
21
|
+
if (normalized === 'citext')
|
|
22
|
+
return 'TEXT COLLATE NOCASE';
|
|
23
|
+
if (/^(serial|bigserial|smallserial)$/.test(normalized))
|
|
24
|
+
return 'INTEGER';
|
|
25
|
+
if (/^(bytea)$/.test(normalized))
|
|
26
|
+
return 'BLOB';
|
|
27
|
+
if (/^(double precision|real|float[48]?)$/.test(normalized))
|
|
28
|
+
return 'REAL';
|
|
29
|
+
return type;
|
|
30
|
+
}
|
|
31
|
+
export function generateTableDdl(table, dialect = 'postgres') {
|
|
32
|
+
const lines = [];
|
|
33
|
+
for (const col of table.columns) {
|
|
34
|
+
const type = dialect === 'sqlite' ? sqliteType(col.type) : col.type;
|
|
35
|
+
let line = ` ${quoteIdent(col.name)} ${type}`;
|
|
36
|
+
if (!col.nullable && !col.primary)
|
|
37
|
+
line += ' NOT NULL';
|
|
38
|
+
if (col.unique && !col.primary)
|
|
39
|
+
line += ' UNIQUE';
|
|
40
|
+
if (col.hasDefault)
|
|
41
|
+
line += ` DEFAULT ${renderDefault(col.default)}`;
|
|
42
|
+
if (dialect === 'sqlite' && col.references) {
|
|
43
|
+
line += ` REFERENCES ${quoteIdent(col.references.table)} (${quoteIdent(col.references.column)})`;
|
|
44
|
+
}
|
|
45
|
+
lines.push(line);
|
|
46
|
+
}
|
|
47
|
+
if (table.primaryKey.length > 0) {
|
|
48
|
+
lines.push(` PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(', ')})`);
|
|
49
|
+
}
|
|
50
|
+
return `CREATE TABLE ${quoteIdent(table.name)} (\n${lines.join(',\n')}\n)`;
|
|
51
|
+
}
|
|
52
|
+
export function generateDdl(schema) {
|
|
53
|
+
const statements = schema.tables.map((table) => generateTableDdl(table, schema.dialect));
|
|
54
|
+
if (schema.dialect === 'sqlite')
|
|
55
|
+
return statements;
|
|
56
|
+
for (const table of schema.tables) {
|
|
57
|
+
for (const col of table.columns) {
|
|
58
|
+
if (col.references) {
|
|
59
|
+
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)})`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return statements;
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=ddl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ddl.js","sourceRoot":"","sources":["../../../../src/testing/schema/ddl.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,OAAO,IAAI,IAAI,CAAC,OAAO,C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AM,CAAC,OAAO,CAAC,CAAC,CAAC;IACzF,IAAI,MAAM,CAAC,OAAO,KAAK,QAAQ;QAAE,OAAO,UAAU,CAAC;IACnD,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAClC,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;YAChC,IAAI,GAAG,CAAC,UAAU,EAAE,CAAC;gBACnB,UAAU,CAAC,IAAI,CACb,eAAe,UAAU,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\nexport function quoteIdent(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction renderDefault(value: string | number | boolean): string {\n if (typeof value === 'string') return value;\n if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE';\n return String(value);\n}\n\nfunction sqliteType(type: string): string {\n const normalized = type.trim().toLowerCase();\n if (normalized === 'uuid') return 'TEXT';\n if (/^(timestamp|timestamptz)(\\s+with(out)?\\s+time\\s+zone)?$/.test(normalized)) return 'TEXT';\n if (normalized === 'json' || normalized === 'jsonb') return 'TEXT';\n if (normalized === 'boolean' || normalized === 'bool') return 'INTEGER';\n if (normalized === 'citext') return 'TEXT COLLATE NOCASE';\n if (/^(serial|bigserial|smallserial)$/.test(normalized)) return 'INTEGER';\n if (/^(bytea)$/.test(normalized)) return 'BLOB';\n if (/^(double precision|real|float[48]?)$/.test(normalized)) return 'REAL';\n return type;\n}\n\nexport function generateTableDdl(\n table: NormalizedTable,\n dialect: 'postgres' | 'sqlite' = 'postgres'\n): string {\n const lines: string[] = [];\n for (const col of table.columns) {\n const type = dialect === 'sqlite' ? sqliteType(col.type) : col.type;\n let line = ` ${quoteIdent(col.name)} ${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 if (dialect === 'sqlite' && col.references) {\n line += ` REFERENCES ${quoteIdent(col.references.table)} (${quoteIdent(col.references.column)})`;\n }\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\nexport function generateDdl(schema: NormalizedTestSchema): string[] {\n const statements = schema.tables.map((table) => generateTableDdl(table, schema.dialect));\n if (schema.dialect === 'sqlite') return statements;\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,164 @@
|
|
|
1
|
+
import * as path from 'path';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import { SqlStackError } from '../../core/errors.js';
|
|
4
|
+
export class TestSchemaError extends SqlStackError {
|
|
5
|
+
constructor(message, source) {
|
|
6
|
+
super(source ? `${message} (schema source: ${source})` : message);
|
|
7
|
+
this.name = 'TestSchemaError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
11
|
+
function assertIdentifier(kind, name, source) {
|
|
12
|
+
if (!IDENT.test(name)) {
|
|
13
|
+
throw new TestSchemaError(`Invalid ${kind} name ${JSON.stringify(name)}: names must match /^[A-Za-z_][A-Za-z0-9_]*$/`, source);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function parseReference(raw, where, source) {
|
|
17
|
+
if (typeof raw !== 'string') {
|
|
18
|
+
throw new TestSchemaError(`Invalid "references" at ${where}: expected a string like "table.column"`, source);
|
|
19
|
+
}
|
|
20
|
+
// Accept "table.column" or "table(column)".
|
|
21
|
+
let m = /^([A-Za-z_][A-Za-z0-9_]*)\.([A-Za-z_][A-Za-z0-9_]*)$/.exec(raw);
|
|
22
|
+
if (!m)
|
|
23
|
+
m = /^([A-Za-z_][A-Za-z0-9_]*)\(([A-Za-z_][A-Za-z0-9_]*)\)$/.exec(raw);
|
|
24
|
+
if (!m) {
|
|
25
|
+
throw new TestSchemaError(`Invalid "references" syntax ${JSON.stringify(raw)} at ${where}: use "table.column" or "table(column)"`, source);
|
|
26
|
+
}
|
|
27
|
+
return { table: m[1], column: m[2] };
|
|
28
|
+
}
|
|
29
|
+
const COLUMN_KEYS = new Set(['type', 'nullable', 'primary', 'unique', 'default', 'references']);
|
|
30
|
+
function normalizeColumn(tableName, name, decl, source) {
|
|
31
|
+
const where = `${tableName}.${name}`;
|
|
32
|
+
assertIdentifier('column', name, source);
|
|
33
|
+
let obj;
|
|
34
|
+
if (typeof decl === 'string') {
|
|
35
|
+
obj = { type: decl };
|
|
36
|
+
}
|
|
37
|
+
else if (decl && typeof decl === 'object' && !Array.isArray(decl)) {
|
|
38
|
+
obj = decl;
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
throw new TestSchemaError(`Malformed column declaration at ${where}: expected a type string or an object`, source);
|
|
42
|
+
}
|
|
43
|
+
for (const key of Object.keys(obj)) {
|
|
44
|
+
if (!COLUMN_KEYS.has(key)) {
|
|
45
|
+
throw new TestSchemaError(`Unknown column property ${JSON.stringify(key)} at ${where}: supported properties are ${[...COLUMN_KEYS].join(', ')}`, source);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const type = obj.type;
|
|
49
|
+
if (typeof type !== 'string' || type.trim() === '') {
|
|
50
|
+
throw new TestSchemaError(`Missing or invalid "type" at ${where}: a non-empty string is required`, source);
|
|
51
|
+
}
|
|
52
|
+
for (const flag of ['nullable', 'primary', 'unique']) {
|
|
53
|
+
if (obj[flag] !== undefined && typeof obj[flag] !== 'boolean') {
|
|
54
|
+
throw new TestSchemaError(`Invalid "${flag}" at ${where}: expected a boolean`, source);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const def = obj.default;
|
|
58
|
+
if (def !== undefined && !['string', 'number', 'boolean'].includes(typeof def)) {
|
|
59
|
+
throw new TestSchemaError(`Invalid "default" at ${where}: expected a string, number, or boolean`, source);
|
|
60
|
+
}
|
|
61
|
+
const primary = obj.primary === true;
|
|
62
|
+
return {
|
|
63
|
+
name,
|
|
64
|
+
type: type.trim(),
|
|
65
|
+
nullable: obj.nullable === undefined ? !primary : obj.nullable,
|
|
66
|
+
primary,
|
|
67
|
+
unique: obj.unique === true,
|
|
68
|
+
hasDefault: def !== undefined,
|
|
69
|
+
default: def,
|
|
70
|
+
references: obj.references === undefined ? undefined : parseReference(obj.references, where, source),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function normalizeTable(name, decl, source) {
|
|
74
|
+
assertIdentifier('table', name, source);
|
|
75
|
+
if (!decl || typeof decl !== 'object' || Array.isArray(decl)) {
|
|
76
|
+
throw new TestSchemaError(`Malformed table declaration "${name}": expected an object with "columns"`, source);
|
|
77
|
+
}
|
|
78
|
+
const columnsDecl = decl.columns;
|
|
79
|
+
if (!columnsDecl || typeof columnsDecl !== 'object' || Array.isArray(columnsDecl)) {
|
|
80
|
+
throw new TestSchemaError(`Table "${name}" is missing a "columns" map`, source);
|
|
81
|
+
}
|
|
82
|
+
const columns = Object.entries(columnsDecl).map(([colName, colDecl]) => normalizeColumn(name, colName, colDecl, source));
|
|
83
|
+
if (columns.length === 0) {
|
|
84
|
+
throw new TestSchemaError(`Table "${name}" declares no columns`, source);
|
|
85
|
+
}
|
|
86
|
+
const primaryKey = columns.filter((c) => c.primary).map((c) => c.name);
|
|
87
|
+
return { name, columns: Object.freeze(columns), primaryKey: Object.freeze(primaryKey) };
|
|
88
|
+
}
|
|
89
|
+
function normalizeSqlEntry(raw, index, options, source) {
|
|
90
|
+
if (typeof raw !== 'string' || raw.trim() === '') {
|
|
91
|
+
throw new TestSchemaError(`Invalid sql entry #${index}: expected a non-empty string`, source);
|
|
92
|
+
}
|
|
93
|
+
const looksLikeFile = !raw.includes('\n') && /\.sql$/i.test(raw.trim());
|
|
94
|
+
if (!looksLikeFile) {
|
|
95
|
+
return { kind: 'inline', index, sql: raw };
|
|
96
|
+
}
|
|
97
|
+
const authored = raw.trim();
|
|
98
|
+
if (!options.sourceDir) {
|
|
99
|
+
throw new TestSchemaError(`sql entry #${index} references file "${authored}" but no sourceDir is available. ` +
|
|
100
|
+
`Pass the schema as a file path, or provide { sourceDir } so relative .sql paths can be resolved ` +
|
|
101
|
+
`(paths are never resolved against process.cwd() implicitly).`, source);
|
|
102
|
+
}
|
|
103
|
+
const resolvedPath = path.resolve(options.sourceDir, authored);
|
|
104
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
105
|
+
throw new TestSchemaError(`sql entry #${index}: file not found: ${authored} (resolved to ${resolvedPath})`, source);
|
|
106
|
+
}
|
|
107
|
+
return { kind: 'file', index, sourcePath: authored, resolvedPath };
|
|
108
|
+
}
|
|
109
|
+
export function normalizeTestSchema(doc, options = {}) {
|
|
110
|
+
const source = options.sourceLabel ?? '<inline schema>';
|
|
111
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
|
|
112
|
+
throw new TestSchemaError('Test schema must be a YAML mapping / object', source);
|
|
113
|
+
}
|
|
114
|
+
const root = doc;
|
|
115
|
+
if (root.version !== 1) {
|
|
116
|
+
throw new TestSchemaError(`Unsupported test schema version: ${JSON.stringify(root.version)} (expected: version: 1)`, source);
|
|
117
|
+
}
|
|
118
|
+
if (root.dialect !== 'postgres' && root.dialect !== 'sqlite') {
|
|
119
|
+
throw new TestSchemaError(`Unsupported test schema dialect: ${JSON.stringify(root.dialect)} (expected: dialect: postgres or sqlite)`, source);
|
|
120
|
+
}
|
|
121
|
+
for (const key of Object.keys(root)) {
|
|
122
|
+
if (!['version', 'dialect', 'tables', 'sql'].includes(key)) {
|
|
123
|
+
throw new TestSchemaError(`Unknown top-level key ${JSON.stringify(key)} in test schema`, source);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
let tables = [];
|
|
127
|
+
if (root.tables !== undefined) {
|
|
128
|
+
if (!root.tables || typeof root.tables !== 'object' || Array.isArray(root.tables)) {
|
|
129
|
+
throw new TestSchemaError('"tables" must be a mapping of table name to declaration', source);
|
|
130
|
+
}
|
|
131
|
+
tables = Object.entries(root.tables).map(([name, decl]) => normalizeTable(name, decl, source));
|
|
132
|
+
}
|
|
133
|
+
// Validate references that point at structured tables.
|
|
134
|
+
const byName = new Map(tables.map((t) => [t.name, t]));
|
|
135
|
+
for (const t of tables) {
|
|
136
|
+
for (const c of t.columns) {
|
|
137
|
+
const ref = c.references;
|
|
138
|
+
if (ref && byName.has(ref.table)) {
|
|
139
|
+
const target = byName.get(ref.table);
|
|
140
|
+
if (!target.columns.some((tc) => tc.name === ref.column)) {
|
|
141
|
+
throw new TestSchemaError(`Column ${t.name}.${c.name} references ${ref.table}.${ref.column}, but table "${ref.table}" declares no column "${ref.column}"`, source);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
let sql = [];
|
|
147
|
+
if (root.sql !== undefined) {
|
|
148
|
+
if (!Array.isArray(root.sql)) {
|
|
149
|
+
throw new TestSchemaError('"sql" must be a list of inline SQL strings or .sql file paths', source);
|
|
150
|
+
}
|
|
151
|
+
sql = root.sql.map((entry, i) => normalizeSqlEntry(entry, i, options, source));
|
|
152
|
+
}
|
|
153
|
+
if (tables.length === 0 && sql.length === 0) {
|
|
154
|
+
throw new TestSchemaError('Test schema declares no tables and no sql entries', source);
|
|
155
|
+
}
|
|
156
|
+
return Object.freeze({
|
|
157
|
+
version: 1,
|
|
158
|
+
dialect: root.dialect,
|
|
159
|
+
tables: Object.freeze(tables),
|
|
160
|
+
sql: Object.freeze(sql),
|
|
161
|
+
source,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
//# sourceMappingURL=normalize.js.map
|