sqlstack 2.0.0 → 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/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 +29 -16
- 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 +9 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +14 -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/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/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 +31 -18
- 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 -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/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 +18 -2
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import { parseTestSchema } from './schema/parser.js';
|
|
3
|
+
import { generateDdl } from './schema/ddl.js';
|
|
4
|
+
import { allocateDatabase } from './postgres/allocator.js';
|
|
5
|
+
import { createDatabaseHandle } from './postgres/database.js';
|
|
6
|
+
import { dropDatabase } from './postgres/allocator.js';
|
|
7
|
+
import { TestPostgresServerError } from './postgres/server.js';
|
|
8
|
+
import { composeRows, insertRows, toOperations } from './postgres/loadData.js';
|
|
9
|
+
function readRawSql(schema) {
|
|
10
|
+
return schema.sql.map((entry) => {
|
|
11
|
+
if (entry.kind === 'inline') {
|
|
12
|
+
return { label: `sql entry #${entry.index} (inline)`, sql: entry.sql };
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
return {
|
|
16
|
+
label: `sql entry #${entry.index} (${entry.sourcePath})`,
|
|
17
|
+
sql: fs.readFileSync(entry.resolvedPath, 'utf8'),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
catch (err) {
|
|
21
|
+
throw new TestPostgresServerError(`Cannot read raw SQL file for sql entry #${entry.index}: ${entry.resolvedPath} ` +
|
|
22
|
+
`(authored as "${entry.sourcePath}" in ${schema.source}): ${err.message}`);
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
function makeBuilder(state) {
|
|
27
|
+
return {
|
|
28
|
+
schema: state.schema,
|
|
29
|
+
ops: state.ops,
|
|
30
|
+
data(rows) {
|
|
31
|
+
const newOps = toOperations(state.schema, rows);
|
|
32
|
+
return makeBuilder({ ...state, ops: [...state.ops, ...newOps] });
|
|
33
|
+
},
|
|
34
|
+
async build() {
|
|
35
|
+
// Fail on pure planning errors (cycles, raw SQL file readability)
|
|
36
|
+
// before touching the server where possible.
|
|
37
|
+
const rawSql = readRawSql(state.schema);
|
|
38
|
+
const ddl = generateDdl(state.schema);
|
|
39
|
+
const effective = composeRows(state.schema, state.ops);
|
|
40
|
+
const allocated = await allocateDatabase(state.options);
|
|
41
|
+
let handle;
|
|
42
|
+
try {
|
|
43
|
+
handle = await createDatabaseHandle(allocated, state.options);
|
|
44
|
+
for (const statement of ddl) {
|
|
45
|
+
try {
|
|
46
|
+
await handle._pool.query(statement);
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
throw new TestPostgresServerError(`Failed to apply structured DDL from ${state.schema.source}: ${err.message}\n` +
|
|
50
|
+
`Statement:\n${statement}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
for (const entry of rawSql) {
|
|
54
|
+
try {
|
|
55
|
+
// Simple-query protocol: the pg driver executes multi-statement
|
|
56
|
+
// scripts directly when no parameters are passed.
|
|
57
|
+
await handle._pool.query(entry.sql);
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
throw new TestPostgresServerError(`Failed to apply raw ${entry.label} from ${state.schema.source}: ${err.message}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
await insertRows((sql, params) => handle._pool.query(sql, params), state.schema, effective);
|
|
64
|
+
return handle;
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
// Clean up partially created owned resources.
|
|
68
|
+
if (handle) {
|
|
69
|
+
await handle._pool.end().catch(() => undefined);
|
|
70
|
+
}
|
|
71
|
+
await dropDatabase(allocated.name, state.options).catch(() => undefined);
|
|
72
|
+
throw err;
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Persistent immutable test database builder.
|
|
79
|
+
*
|
|
80
|
+
* `schema` may be a parsed schema object, a YAML string, or a path to a
|
|
81
|
+
* .yml/.yaml file (raw .sql entries then resolve relative to that file's
|
|
82
|
+
* directory unless options.sourceDir overrides it).
|
|
83
|
+
*/
|
|
84
|
+
export function testPostgres(schema, options = {}) {
|
|
85
|
+
const normalized = isNormalizedSchema(schema) ? schema : parseTestSchema(schema, options);
|
|
86
|
+
return makeBuilder({ schema: normalized, ops: [], options: Object.freeze({ ...options }) });
|
|
87
|
+
}
|
|
88
|
+
function isNormalizedSchema(input) {
|
|
89
|
+
return (!!input &&
|
|
90
|
+
typeof input === 'object' &&
|
|
91
|
+
Array.isArray(input.tables) &&
|
|
92
|
+
Array.isArray(input.sql) &&
|
|
93
|
+
typeof input.source === 'string');
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=builder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../src/testing/builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAE,oBAAoB,EAAwB,MAAM,qBAAqB,CAAC;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,uBAAuB,EAAqB,MAAM,mBAAmB,CAAC;AAC/E,OA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ema } from './schema/parser';\nimport { generateDdl } from './schema/ddl';\nimport type { NormalizedTestSchema, ParseTestSchemaOptions } from './schema/types';\nimport { allocateDatabase } from './postgres/allocator';\nimport { createDatabaseHandle, TestPostgresDatabase } from './postgres/database';\nimport { dropDatabase } from './postgres/allocator';\nimport { TestPostgresServerError, TestServerOptions } from './postgres/server';\nimport { composeRows, DataOperation, insertRows, Row, toOperations } from './postgres/loadData';\n\nexport interface TestPostgresOptions extends TestServerOptions, ParseTestSchemaOptions {}\n\nexport interface TestPostgresBuilder {\n /** The normalized immutable schema (useful for assertions/diagnostics). */\n readonly schema: NormalizedTestSchema;\n /** @internal Accumulated row operations (exposed for pure tests). */\n readonly ops: readonly DataOperation[];\n /** Returns a NEW derived builder; this builder is unchanged. */\n data(rows: Record<string, Row[]>): TestPostgresBuilder;\n /**\n * Create a fresh isolated PostgreSQL database, apply DDL + raw SQL,\n * insert effective scenario rows, and return the handle. Does not\n * consume the builder: building twice yields two independent databases.\n */\n build(): Promise<TestPostgresDatabase>;\n}\n\ninterface BuilderState {\n readonly schema: NormalizedTestSchema;\n readonly ops: readonly DataOperation[];\n readonly options: Readonly<TestPostgresOptions>;\n}\n\nfunction readRawSql(schema: NormalizedTestSchema): { label: string; sql: string }[] {\n return schema.sql.map((entry) => {\n if (entry.kind === 'inline') {\n return { label: `sql entry #${entry.index} (inline)`, sql: entry.sql };\n }\n try {\n return {\n label: `sql entry #${entry.index} (${entry.sourcePath})`,\n sql: fs.readFileSync(entry.resolvedPath, 'utf8'),\n };\n } catch (err) {\n throw new TestPostgresServerError(\n `Cannot read raw SQL file for sql entry #${entry.index}: ${entry.resolvedPath} ` +\n `(authored as \"${entry.sourcePath}\" in ${schema.source}): ${(err as Error).message}`\n );\n }\n });\n}\n\nfunction makeBuilder(state: BuilderState): TestPostgresBuilder {\n return {\n schema: state.schema,\n ops: state.ops,\n data(rows: Record<string, Row[]>): TestPostgresBuilder {\n const newOps = toOperations(state.schema, rows);\n return makeBuilder({ ...state, ops: [...state.ops, ...newOps] });\n },\n async build(): Promise<TestPostgresDatabase> {\n // Fail on pure planning errors (cycles, raw SQL file readability)\n // before touching the server where possible.\n const rawSql = readRawSql(state.schema);\n const ddl = generateDdl(state.schema);\n const effective = composeRows(state.schema, state.ops);\n\n const allocated = await allocateDatabase(state.options);\n let handle: (TestPostgresDatabase & { _pool: any }) | undefined;\n try {\n handle = await createDatabaseHandle(allocated, state.options);\n for (const statement of ddl) {\n try {\n await handle._pool.query(statement);\n } catch (err) {\n throw new TestPostgresServerError(\n `Failed to apply structured DDL from ${state.schema.source}: ${(err as Error).message}\\n` +\n `Statement:\\n${statement}`\n );\n }\n }\n for (const entry of rawSql) {\n try {\n // Simple-query protocol: the pg driver executes multi-statement\n // scripts directly when no parameters are passed.\n await handle._pool.query(entry.sql);\n } catch (err) {\n throw new TestPostgresServerError(\n `Failed to apply raw ${entry.label} from ${state.schema.source}: ${(err as Error).message}`\n );\n }\n }\n await insertRows((sql, params) => handle!._pool.query(sql, params), state.schema, effective);\n return handle;\n } catch (err) {\n // Clean up partially created owned resources.\n if (handle) {\n await handle._pool.end().catch(() => undefined);\n }\n await dropDatabase(allocated.name, state.options).catch(() => undefined);\n throw err;\n }\n },\n };\n}\n\n/**\n * Persistent immutable test database builder.\n *\n * `schema` may be a parsed schema object, a YAML string, or a path to a\n * .yml/.yaml file (raw .sql entries then resolve relative to that file's\n * directory unless options.sourceDir overrides it).\n */\nexport function testPostgres(\n schema: string | object,\n options: TestPostgresOptions = {}\n): TestPostgresBuilder {\n const normalized =\n isNormalizedSchema(schema) ? schema : parseTestSchema(schema as string | object, options);\n return makeBuilder({ schema: normalized, ops: [], options: Object.freeze({ ...options }) });\n}\n\nfunction isNormalizedSchema(input: unknown): input is NormalizedTestSchema {\n return (\n !!input &&\n typeof input === 'object' &&\n Array.isArray((input as NormalizedTestSchema).tables) &&\n Array.isArray((input as NormalizedTestSchema).sql) &&\n typeof (input as NormalizedTestSchema).source === 'string'\n );\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { testPostgres } from './builder.js';
|
|
2
|
+
export { parseTestSchema } from './schema/parser.js';
|
|
3
|
+
export { normalizeTestSchema, TestSchemaError } from './schema/normalize.js';
|
|
4
|
+
export { generateDdl } from './schema/ddl.js';
|
|
5
|
+
export { TestDataError } from './postgres/loadData.js';
|
|
6
|
+
export { TestPostgresServerError, DEFAULT_ADMIN_URL } from './postgres/server.js';
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/testing/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAGzC,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC","sourcesContent":["export { testPostgres } from './builder';\nexport type { TestPostgresBuilder, TestPostgresOptions } from './builder';\nexport type { TestPostgresDatabase } from './postgres/database';\nexport { parseTestSchema } from './schema/parser';\nexport { normalizeTestSchema, TestSchemaError } from './schema/normalize';\nexport { generateDdl } from './schema/ddl';\nexport { TestDataError } from './postgres/loadData';\nexport { TestPostgresServerError, DEFAULT_ADMIN_URL } from './postgres/server';\nexport type {\n NormalizedTestSchema,\n NormalizedTable,\n NormalizedColumn,\n RawSqlEntry,\n ParseTestSchemaOptions,\n} from './schema/types';\n"]}
|
|
@@ -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,IAAI,CAAC;QACH,MAAM,KAAK,CAAC,KAAK,CAAC,oBAAoB,IAAI,GAAG,CAAC,CAAC;IACjD,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,uBAAuB,CAC/B,mCAAmC,IAAI,QAAQ,MAAM,CAAC,QAAQ,CAAC,KAAM,GAAa,CAAC,OAAO,IAAI;YAC5F,2DAA2D;YAC3D,iGAAiG,CACpG,CAAC;IACJ,CAAC;YAAS,CAAC;QACT,MAAM,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,YAAY,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,QAAQ,EAAE,CAAC;AAC/D,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,IAAY,EAAE,UAA6B,EAAE;IAC9E,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,uBAAuB,CAC/B,8BAA8B,IAAI,qDAAqD,WAAW,GAAG,CACtG,CAAC;IACJ,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,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,uBAAuB,CAC/B,iCAAiC,IAAI,QAAQ,MAAM,CAAC,eAAe,CAAC,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,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,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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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,IAAI,CAAC,CAAC;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAC/B,gGAAgG,CACjG,CAAC;IACJ,CAAC;AACH,CAAC;AAED,iFAAiF;AACjF,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,UAA6B,EAAE;IAChE,MAAM,GAAG,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;IACrC,MAAM,EAAE,GAAG,MAAM,MAAM,EAAE,CAAC;IAC1B,MAAM,MAAM,GAAG,EAAE,CAAC,MAAM,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC;IAC/C,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,gBAAgB,EAAE,GAAG,EAAE,CAAC,CAAC;IACrD,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,CAAC;YACH,MAAM,MAAM,CAAC,GAAG,EAAE,CAAC;QACrB,CAAC;QAAC,MAAM,CAAC;YACP,YAAY;QACd,CAAC;QACD,MAAM,IAAI,uBAAuB,CAC/B,mDAAmD,MAAM,CAAC,GAAG,CAAC,KAAM,GAAa,CAAC,OAAO,IAAI;YAC3F,2EAA2E;YAC3E,uFAAuF;YACvF,qCAAqC,CACxC,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,qDAAqD;AACrD,MAAM,UAAU,MAAM,CAAC,GAAW;IAChC,OAAO,GAAG,CAAC,OAAO,CAAC,uBAAuB,EAAE,WAAW,CAAC,CAAC;AAC3D,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,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,49 @@
|
|
|
1
|
+
/** Quote a (pre-validated) identifier for PostgreSQL. */
|
|
2
|
+
export function quoteIdent(name) {
|
|
3
|
+
return `"${name.replace(/"/g, '""')}"`;
|
|
4
|
+
}
|
|
5
|
+
function renderDefault(value) {
|
|
6
|
+
// String defaults are raw SQL expressions (e.g. now(), 'active', gen_random_uuid()).
|
|
7
|
+
if (typeof value === 'string')
|
|
8
|
+
return value;
|
|
9
|
+
if (typeof value === 'boolean')
|
|
10
|
+
return value ? 'TRUE' : 'FALSE';
|
|
11
|
+
return String(value);
|
|
12
|
+
}
|
|
13
|
+
export function generateTableDdl(table) {
|
|
14
|
+
const lines = [];
|
|
15
|
+
for (const col of table.columns) {
|
|
16
|
+
let line = ` ${quoteIdent(col.name)} ${col.type}`;
|
|
17
|
+
if (!col.nullable && !col.primary)
|
|
18
|
+
line += ' NOT NULL';
|
|
19
|
+
if (col.unique && !col.primary)
|
|
20
|
+
line += ' UNIQUE';
|
|
21
|
+
if (col.hasDefault)
|
|
22
|
+
line += ` DEFAULT ${renderDefault(col.default)}`;
|
|
23
|
+
lines.push(line);
|
|
24
|
+
}
|
|
25
|
+
if (table.primaryKey.length > 0) {
|
|
26
|
+
lines.push(` PRIMARY KEY (${table.primaryKey.map(quoteIdent).join(', ')})`);
|
|
27
|
+
}
|
|
28
|
+
return `CREATE TABLE ${quoteIdent(table.name)} (\n${lines.join(',\n')}\n)`;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Deterministic DDL for the structured tables.
|
|
32
|
+
*
|
|
33
|
+
* Tables are created in authored order without inline foreign keys; declared
|
|
34
|
+
* references are then added as ALTER TABLE statements so authored table
|
|
35
|
+
* order never has to match dependency order. Raw SQL entries are applied by
|
|
36
|
+
* the builder after these statements, in authored order.
|
|
37
|
+
*/
|
|
38
|
+
export function generateDdl(schema) {
|
|
39
|
+
const statements = schema.tables.map(generateTableDdl);
|
|
40
|
+
for (const table of schema.tables) {
|
|
41
|
+
for (const col of table.columns) {
|
|
42
|
+
if (col.references) {
|
|
43
|
+
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)})`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return statements;
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=ddl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ddl.js","sourceRoot":"","sources":["../../../../src/testing/schema/ddl.ts"],"names":[],"mappings":"AAEA,yDAAyD;AACzD,MAAM,UAAU,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,MAAM,UAAU,gBAAgB,CAAC,KAAsB;IACrD,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;QAChC,IAAI,IAAI,GAAG,KAAK,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC;QACnD,IAAI,CAAC,GAAG,CAAC,QAAQ,IAAI,CAAC,GAAG,CAAC,OAAO;YAAE,IAAI,IAAI,WAAW,CAAC;QACvD,IAAI,GAAG,CAAC,MAAM,IAAI,C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AC;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"]}
|