sqlstack 3.7.2 → 3.8.0-dev.1
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/testing/builder.d.ts +25 -5
- package/dist/cjs/testing/builder.d.ts.map +1 -1
- package/dist/cjs/testing/builder.js +30 -20
- package/dist/cjs/testing/builder.js.map +1 -1
- package/dist/cjs/testing/index.d.ts +2 -0
- package/dist/cjs/testing/index.d.ts.map +1 -1
- package/dist/cjs/testing/index.js.map +1 -1
- package/dist/cjs/testing/live.d.ts +51 -0
- package/dist/cjs/testing/live.d.ts.map +1 -0
- package/dist/cjs/testing/live.js +270 -0
- package/dist/cjs/testing/live.js.map +1 -0
- package/dist/cjs/testing/postgres/database.d.ts +15 -0
- package/dist/cjs/testing/postgres/database.d.ts.map +1 -1
- package/dist/cjs/testing/postgres/database.js +32 -3
- package/dist/cjs/testing/postgres/database.js.map +1 -1
- package/dist/cjs/testing/postgres/loadData.d.ts +32 -1
- package/dist/cjs/testing/postgres/loadData.d.ts.map +1 -1
- package/dist/cjs/testing/postgres/loadData.js +47 -26
- package/dist/cjs/testing/postgres/loadData.js.map +1 -1
- package/dist/cjs/testing/prepare.d.ts +20 -0
- package/dist/cjs/testing/prepare.d.ts.map +1 -0
- package/dist/cjs/testing/prepare.js +39 -0
- package/dist/cjs/testing/prepare.js.map +1 -0
- package/dist/cjs/testing/schema/normalize.d.ts +6 -1
- package/dist/cjs/testing/schema/normalize.d.ts.map +1 -1
- package/dist/cjs/testing/schema/normalize.js +2 -2
- package/dist/cjs/testing/schema/normalize.js.map +1 -1
- package/dist/cjs/testing/schema/parser.d.ts +2 -1
- package/dist/cjs/testing/schema/parser.d.ts.map +1 -1
- package/dist/cjs/testing/schema/parser.js +6 -6
- package/dist/cjs/testing/schema/parser.js.map +1 -1
- package/dist/cjs/testing/sqlite/builder.d.ts +23 -0
- package/dist/cjs/testing/sqlite/builder.d.ts.map +1 -1
- package/dist/cjs/testing/sqlite/builder.js +34 -12
- package/dist/cjs/testing/sqlite/builder.js.map +1 -1
- package/dist/cjs/testing/sqlite/database.d.ts +6 -0
- package/dist/cjs/testing/sqlite/database.d.ts.map +1 -1
- package/dist/cjs/testing/sqlite/database.js +8 -0
- package/dist/cjs/testing/sqlite/database.js.map +1 -1
- package/dist/cjs/testing/sqlite/loadData.d.ts.map +1 -1
- package/dist/cjs/testing/sqlite/loadData.js +1 -43
- package/dist/cjs/testing/sqlite/loadData.js.map +1 -1
- package/dist/esm/testing/builder.js +30 -20
- package/dist/esm/testing/builder.js.map +1 -1
- package/dist/esm/testing/index.js.map +1 -1
- package/dist/esm/testing/live.js +262 -0
- package/dist/esm/testing/live.js.map +1 -0
- package/dist/esm/testing/postgres/database.js +32 -3
- package/dist/esm/testing/postgres/database.js.map +1 -1
- package/dist/esm/testing/postgres/loadData.js +44 -26
- package/dist/esm/testing/postgres/loadData.js.map +1 -1
- package/dist/esm/testing/prepare.js +34 -0
- package/dist/esm/testing/prepare.js.map +1 -0
- package/dist/esm/testing/schema/normalize.js +2 -2
- package/dist/esm/testing/schema/normalize.js.map +1 -1
- package/dist/esm/testing/schema/parser.js +6 -6
- package/dist/esm/testing/schema/parser.js.map +1 -1
- package/dist/esm/testing/sqlite/builder.js +33 -11
- package/dist/esm/testing/sqlite/builder.js.map +1 -1
- package/dist/esm/testing/sqlite/database.js +8 -0
- package/dist/esm/testing/sqlite/database.js.map +1 -1
- package/dist/esm/testing/sqlite/loadData.js +2 -44
- package/dist/esm/testing/sqlite/loadData.js.map +1 -1
- package/package.json +1 -1
- package/readme.md +21 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../../../src/testing/schema/parser.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAE5E;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,MAAM,GAAG,MAAM,EACtB,OAAO,GAAE,sBAA2B,
|
|
1
|
+
{"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../../../src/testing/schema/parser.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAE5E;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,KAAK,EAAE,MAAM,GAAG,MAAM,EACtB,OAAO,GAAE,sBAA2B,EACpC,QAAQ,GAAE,wBAA6B,GACtC,oBAAoB,CAoBtB;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEvD"}
|
|
@@ -44,9 +44,9 @@ const normalize_1 = require("./normalize");
|
|
|
44
44
|
* file path. When given a file path, relative raw .sql entries resolve
|
|
45
45
|
* against the file's own directory unless options.sourceDir overrides it.
|
|
46
46
|
*/
|
|
47
|
-
function parseTestSchema(input, options = {}) {
|
|
47
|
+
function parseTestSchema(input, options = {}, internal = {}) {
|
|
48
48
|
if (typeof input === 'object') {
|
|
49
|
-
return (0, normalize_1.normalizeTestSchema)(input, options);
|
|
49
|
+
return (0, normalize_1.normalizeTestSchema)(input, options, internal);
|
|
50
50
|
}
|
|
51
51
|
if (isSchemaFilePath(input)) {
|
|
52
52
|
const filePath = path.resolve(input);
|
|
@@ -60,14 +60,14 @@ function parseTestSchema(input, options = {}) {
|
|
|
60
60
|
return parseYamlText(text, {
|
|
61
61
|
sourceDir: options.sourceDir ?? path.dirname(filePath),
|
|
62
62
|
sourceLabel: options.sourceLabel ?? filePath,
|
|
63
|
-
});
|
|
63
|
+
}, internal);
|
|
64
64
|
}
|
|
65
|
-
return parseYamlText(input, options);
|
|
65
|
+
return parseYamlText(input, options, internal);
|
|
66
66
|
}
|
|
67
67
|
function isSchemaFilePath(input) {
|
|
68
68
|
return !input.includes('\n') && /\.ya?ml$/i.test(input.trim());
|
|
69
69
|
}
|
|
70
|
-
function parseYamlText(text, options) {
|
|
70
|
+
function parseYamlText(text, options, internal) {
|
|
71
71
|
let doc;
|
|
72
72
|
try {
|
|
73
73
|
doc = (0, yaml_1.parse)(text);
|
|
@@ -75,6 +75,6 @@ function parseYamlText(text, options) {
|
|
|
75
75
|
catch (err) {
|
|
76
76
|
throw new normalize_1.TestSchemaError(`Failed to parse test schema YAML: ${err.message}`, options.sourceLabel);
|
|
77
77
|
}
|
|
78
|
-
return (0, normalize_1.normalizeTestSchema)(doc, options);
|
|
78
|
+
return (0, normalize_1.normalizeTestSchema)(doc, options, internal);
|
|
79
79
|
}
|
|
80
80
|
//# sourceMappingURL=parser.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parser.js","sourceRoot":"","sources":["../../../../src/testing/schema/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"parser.js","sourceRoot":"","sources":["../../../../src/testing/schema/parser.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,0CAwBC;AAED,4CAEC;AAxCD,2CAA6B;AAC7B,uCAAyB;AACzB,+BAA0C;AAC1C,2CAAmE;AAInE;;;;GAIG;AACH,SAAgB,eAAe,CAC7B,KAAsB,EACtB,UAAkC,EAAE,EACpC,WAAqC,EAAE;IAEvC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,IAAA,+BAAmB,EAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IACvD,CAAC;IACD,IAAI,gBAAgB,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACrC,IAAI,IAAY,CAAC;QACjB,IAAI,CAAC;YACH,IAAI,GAAG,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC3C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,2BAAe,CACvB,iCAAiC,QAAQ,KAAM,GAAa,CAAC,OAAO,GAAG,CACxE,CAAC;QACJ,CAAC;QACD,OAAO,aAAa,CAAC,IAAI,EAAE;YACzB,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC;YACtD,WAAW,EAAE,OAAO,CAAC,WAAW,IAAI,QAAQ;SAC7C,EAAE,QAAQ,CAAC,CAAC;IACf,CAAC;IACD,OAAO,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AACjD,CAAC;AAED,SAAgB,gBAAgB,CAAC,KAAa;IAC5C,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;AACjE,CAAC;AAED,SAAS,aAAa,CACpB,IAAY,EACZ,OAA+B,EAC/B,QAAkC;IAElC,IAAI,GAAY,CAAC;IACjB,IAAI,CAAC;QACH,GAAG,GAAG,IAAA,YAAS,EAAC,IAAI,CAAC,CAAC;IACxB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,2BAAe,CACvB,qCAAsC,GAAa,CAAC,OAAO,EAAE,EAC7D,OAAO,CAAC,WAAW,CACpB,CAAC;IACJ,CAAC;IACD,OAAO,IAAA,+BAAmB,EAAC,GAAG,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AACrD,CAAC","sourcesContent":["import * as path from 'path';\nimport * as fs from 'fs';\nimport { parse as parseYaml } from 'yaml';\nimport { normalizeTestSchema, TestSchemaError } from './normalize';\nimport type { NormalizeInternalOptions } from './normalize';\nimport type { NormalizedTestSchema, ParseTestSchemaOptions } from './types';\n\n/**\n * Parse a test schema from a YAML string, a plain object, or a .yml/.yaml\n * file path. When given a file path, relative raw .sql entries resolve\n * against the file's own directory unless options.sourceDir overrides it.\n */\nexport function parseTestSchema(\n input: string | object,\n options: ParseTestSchemaOptions = {},\n internal: NormalizeInternalOptions = {}\n): NormalizedTestSchema {\n if (typeof input === 'object') {\n return normalizeTestSchema(input, options, internal);\n }\n if (isSchemaFilePath(input)) {\n const filePath = path.resolve(input);\n let text: string;\n try {\n text = fs.readFileSync(filePath, 'utf8');\n } catch (err) {\n throw new TestSchemaError(\n `Cannot read test schema file: ${filePath} (${(err as Error).message})`\n );\n }\n return parseYamlText(text, {\n sourceDir: options.sourceDir ?? path.dirname(filePath),\n sourceLabel: options.sourceLabel ?? filePath,\n }, internal);\n }\n return parseYamlText(input, options, internal);\n}\n\nexport function isSchemaFilePath(input: string): boolean {\n return !input.includes('\\n') && /\\.ya?ml$/i.test(input.trim());\n}\n\nfunction parseYamlText(\n text: string,\n options: ParseTestSchemaOptions,\n internal: NormalizeInternalOptions\n): NormalizedTestSchema {\n let doc: unknown;\n try {\n doc = parseYaml(text);\n } catch (err) {\n throw new TestSchemaError(\n `Failed to parse test schema YAML: ${(err as Error).message}`,\n options.sourceLabel\n );\n }\n return normalizeTestSchema(doc, options, internal);\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { NormalizedTestSchema, ParseTestSchemaOptions } from '../schema/types';
|
|
2
|
+
import { TestPrepareHook } from '../prepare';
|
|
2
3
|
import { TestSqliteDatabase } from './database';
|
|
3
4
|
import { DataOperation, Row } from './loadData';
|
|
4
5
|
export interface TestSqliteOptions extends ParseTestSchemaOptions {
|
|
@@ -17,8 +18,30 @@ export interface TestSqliteOptions extends ParseTestSchemaOptions {
|
|
|
17
18
|
export interface TestSqliteBuilder {
|
|
18
19
|
readonly schema: NormalizedTestSchema;
|
|
19
20
|
readonly ops: readonly DataOperation[];
|
|
21
|
+
/**
|
|
22
|
+
* Returns a NEW derived builder. Without `.prepare()` hooks, rows are
|
|
23
|
+
* validated immediately against the structured schema. With hooks, only
|
|
24
|
+
* the payload shape is checked here; tables, columns and primary keys are
|
|
25
|
+
* validated at `build()` against the live database (PRAGMA) after the hooks
|
|
26
|
+
* ran, and rows are inserted in foreign-key order in one transaction.
|
|
27
|
+
*/
|
|
20
28
|
data(rows: Record<string, Row[]>): TestSqliteBuilder;
|
|
29
|
+
/**
|
|
30
|
+
* Returns a NEW derived builder with `fn` appended to its prepare hooks.
|
|
31
|
+
* Hooks run in order inside `build()`, after structured DDL and raw `sql:`
|
|
32
|
+
* and before `.data()` rows, each receiving the test database handle.
|
|
33
|
+
* Builders with hooks run the hooks with `PRAGMA foreign_keys = OFF` (as the
|
|
34
|
+
* proper CLI does), then turn it ON before `.data()` rows are inserted.
|
|
35
|
+
* If a hook (or the data load) fails, the database is closed and removed.
|
|
36
|
+
*/
|
|
37
|
+
prepare(fn: TestPrepareHook<TestSqliteDatabase>): TestSqliteBuilder;
|
|
21
38
|
build(): Promise<TestSqliteDatabase>;
|
|
22
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Persistent immutable SQLite test database builder. Omit the schema — or
|
|
42
|
+
* pass only options, e.g. `testSqlite({ mode: 'memory' })` — to start from an
|
|
43
|
+
* empty database, typically shaped by `.prepare()` hooks.
|
|
44
|
+
*/
|
|
45
|
+
export declare function testSqlite(options?: TestSqliteOptions): TestSqliteBuilder;
|
|
23
46
|
export declare function testSqlite(schema: string | object, options?: TestSqliteOptions): TestSqliteBuilder;
|
|
24
47
|
//# sourceMappingURL=builder.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../../../../src/testing/sqlite/builder.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../../../../src/testing/sqlite/builder.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AAEpF,OAAO,EAAsD,eAAe,EAAE,MAAM,YAAY,CAAC;AACjG,OAAO,EAAwB,kBAAkB,EAAmB,MAAM,YAAY,CAAC;AACvF,OAAO,EAAe,aAAa,EAAc,GAAG,EAAgB,MAAM,YAAY,CAAC;AAEvF,MAAM,WAAW,iBAAkB,SAAQ,sBAAsB;IAC/D;;;;;OAKG;IACH,IAAI,CAAC,EAAE,QAAQ,GAAG,MAAM,CAAC;IACzB,2DAA2D;IAC3D,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,2DAA2D;IAC3D,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,EAAE,oBAAoB,CAAC;IACtC,QAAQ,CAAC,GAAG,EAAE,SAAS,aAAa,EAAE,CAAC;IACvC;;;;;;OAMG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,iBAAiB,CAAC;IACrD;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,EAAE,eAAe,CAAC,kBAAkB,CAAC,GAAG,iBAAiB,CAAC;IACpE,KAAK,IAAI,OAAO,CAAC,kBAAkB,CAAC,CAAC;CACtC;AA+GD;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,iBAAiB,CAAC;AAC3E,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,iBAAiB,CAAC"}
|
|
@@ -39,6 +39,8 @@ const resource_1 = require("../resource");
|
|
|
39
39
|
const fixture_provenance_1 = require("../fixture-provenance");
|
|
40
40
|
const ddl_1 = require("../schema/ddl");
|
|
41
41
|
const parser_1 = require("../schema/parser");
|
|
42
|
+
const live_1 = require("../live");
|
|
43
|
+
const prepare_1 = require("../prepare");
|
|
42
44
|
const database_1 = require("./database");
|
|
43
45
|
const loadData_1 = require("./loadData");
|
|
44
46
|
function readRawSql(schema) {
|
|
@@ -73,15 +75,24 @@ function makeBuilder(state) {
|
|
|
73
75
|
schema: state.schema,
|
|
74
76
|
ops: state.ops,
|
|
75
77
|
data(rows) {
|
|
78
|
+
if (state.hooks.length > 0) {
|
|
79
|
+
return makeBuilder({ ...state, payloads: [...state.payloads, (0, live_1.checkDataShape)(rows)] });
|
|
80
|
+
}
|
|
76
81
|
return makeBuilder({
|
|
77
82
|
...state,
|
|
78
83
|
ops: [...state.ops, ...(0, loadData_1.toOperations)(state.schema, rows)],
|
|
84
|
+
payloads: [...state.payloads, rows],
|
|
79
85
|
});
|
|
80
86
|
},
|
|
87
|
+
prepare(fn) {
|
|
88
|
+
(0, prepare_1.assertPrepareHook)(fn);
|
|
89
|
+
return makeBuilder({ ...state, hooks: [...state.hooks, fn] });
|
|
90
|
+
},
|
|
81
91
|
async build() {
|
|
92
|
+
const live = state.hooks.length > 0;
|
|
82
93
|
const rawSql = readRawSql(state.schema);
|
|
83
94
|
const ddl = (0, ddl_1.generateDdl)(state.schema);
|
|
84
|
-
const effective = (0, loadData_1.composeRows)(state.schema, state.ops);
|
|
95
|
+
const effective = live ? undefined : (0, loadData_1.composeRows)(state.schema, state.ops);
|
|
85
96
|
const fileBacked = state.options.mode
|
|
86
97
|
? state.options.mode === 'file'
|
|
87
98
|
: state.options.fileBacked !== false && state.options.tempFile !== false;
|
|
@@ -104,7 +115,22 @@ function makeBuilder(state) {
|
|
|
104
115
|
throw new database_1.TestSqliteError(`Failed to apply raw ${entry.label} from ${state.schema.source}: ${err.message}`);
|
|
105
116
|
}
|
|
106
117
|
}
|
|
107
|
-
|
|
118
|
+
if (live) {
|
|
119
|
+
// Hooks (migrations) run with foreign keys OFF, as the proper CLI's
|
|
120
|
+
// sqlite3 connection does and as table-rebuild migrations require.
|
|
121
|
+
// better-sqlite3 opens connections with them ON, so set it explicitly.
|
|
122
|
+
// Only the prepare path touches the pragma; other fixtures keep the
|
|
123
|
+
// driver default.
|
|
124
|
+
await handle.db.query('PRAGMA foreign_keys = OFF', []);
|
|
125
|
+
for (const hook of state.hooks)
|
|
126
|
+
await hook(handle);
|
|
127
|
+
// `.data()` rows and the returned connection are FK-checked.
|
|
128
|
+
await handle.db.query('PRAGMA foreign_keys = ON', []);
|
|
129
|
+
await handle.session((session) => (0, live_1.loadLiveData)(session, state.payloads));
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
await (0, loadData_1.insertRows)((sql, params) => handle.db.query(sql, params), state.schema, effective);
|
|
133
|
+
}
|
|
108
134
|
return (0, resource_1.adoptFixtureResource)(handle);
|
|
109
135
|
}
|
|
110
136
|
catch (err) {
|
|
@@ -119,24 +145,20 @@ function makeBuilder(state) {
|
|
|
119
145
|
},
|
|
120
146
|
};
|
|
121
147
|
}
|
|
122
|
-
function testSqlite(
|
|
123
|
-
const
|
|
148
|
+
function testSqlite(schemaOrOptions, maybeOptions) {
|
|
149
|
+
const { schema, options } = (0, prepare_1.builderArgs)('sqlite', schemaOrOptions, maybeOptions);
|
|
150
|
+
const normalized = (0, prepare_1.isNormalizedSchema)(schema)
|
|
124
151
|
? schema
|
|
125
|
-
: (0, parser_1.parseTestSchema)(schema, options);
|
|
152
|
+
: (0, parser_1.parseTestSchema)(schema, options, { allowEmpty: true });
|
|
126
153
|
if (normalized.dialect !== 'sqlite') {
|
|
127
154
|
throw new database_1.TestSqliteError(`testSqlite requires a schema with dialect: sqlite (received: ${normalized.dialect})`);
|
|
128
155
|
}
|
|
129
156
|
return makeBuilder({
|
|
130
157
|
schema: normalized,
|
|
131
158
|
ops: [],
|
|
159
|
+
payloads: [],
|
|
160
|
+
hooks: [],
|
|
132
161
|
options: Object.freeze({ ...options }),
|
|
133
162
|
});
|
|
134
163
|
}
|
|
135
|
-
function isNormalizedSchema(input) {
|
|
136
|
-
return (!!input &&
|
|
137
|
-
typeof input === 'object' &&
|
|
138
|
-
Array.isArray(input.tables) &&
|
|
139
|
-
Array.isArray(input.sql) &&
|
|
140
|
-
typeof input.source === 'string');
|
|
141
|
-
}
|
|
142
164
|
//# sourceMappingURL=builder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../../src/testing/sqlite/builder.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHA,gCAiBC;AAnID,4CAA8B;AAC9B,0CAA2E;AAC3E,8DAA6D;AAC7D,uCAA4C;AAC5C,6CAAmD;AAEnD,yCAAuF;AACvF,yCAAuF;AA6BvF,SAAS,UAAU,CAAC,MAA4B;IAC9C,OAAO,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAC9B,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC5B,OAAO,EAAE,KAAK,EAAE,cAAc,KAAK,CAAC,KAAK,WAAW,EAAE,GAAG,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC;QACzE,CAAC;QACD,IAAI,CAAC;YACH,IAAA,yCAAoB,EAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACzC,OAAO;gBACL,KAAK,EAAE,cAAc,KAAK,CAAC,KAAK,KAAK,KAAK,CAAC,UAAU,GAAG;gBACxD,GAAG,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,YAAY,EAAE,MAAM,CAAC;aACjD,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,MAAM,IAAI,0BAAe,CACvB,2CAA2C,KAAK,CAAC,KAAK,KAAK,KAAK,CAAC,YAAY,GAAG;gBAC9E,iBAAiB,KAAK,CAAC,UAAU,QAAQ,MAAM,CAAC,MAAM,MAAO,GAAa,CAAC,OAAO,EAAE,CACvF,CAAC;QACJ,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED,KAAK,UAAU,UAAU,CAAC,MAA0B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AgB,UAAU,CACxB,MAAuB,EACvB,UAA6B,EAAE;IAE/B,MAAM,UAAU,GAAG,kBAAkB,CAAC,MAAM,CAAC;QAC3C,CAAC,CAAC,MAAM;QACR,CAAC,CAAC,IAAA,wBAAe,EAAC,MAAyB,EAAE,OAAO,CAAC,CAAC;IACxD,IAAI,UAAU,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;QACpC,MAAM,IAAI,0BAAe,CACvB,gEAAgE,UAAU,CAAC,OAAO,GAAG,CACtF,CAAC;IACJ,CAAC;IACD,OAAO,WAAW,CAAC;QACjB,MAAM,EAAE,UAAU;QAClB,GAAG,EAAE,EAAE;QACP,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC;KACvC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,kBAAkB,CAAC,KAAc;IACxC,OAAO,CACL,CAAC,CAAC,KAAK;QACP,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,CAAC,OAAO,CAAE,KAA8B,CAAC,MAAM,CAAC;QACrD,KAAK,CAAC,OAAO,CAAE,KAA8B,CAAC,GAAG,CAAC;QAClD,OAAQ,KAA8B,CAAC,MAAM,KAAK,QAAQ,CAC3D,CAAC;AACJ,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport { adoptFixtureResource, TestDatabaseBuildError } from '../resource';\nimport { assertFixtureSqlFile } from '../fixture-provenance';\nimport { generateDdl } from '../schema/ddl';\nimport { parseTestSchema } from '../schema/parser';\nimport type { NormalizedTestSchema, ParseTestSchemaOptions } from '../schema/types';\nimport { createDatabaseHandle, TestSqliteDatabase, TestSqliteError } from './database';\nimport { composeRows, DataOperation, insertRows, Row, toOperations } from './loadData';\n\nexport interface TestSqliteOptions extends ParseTestSchemaOptions {\n /**\n * Storage for the test database. Defaults to `'file'`: an owned temporary\n * file, removed on `dispose()`. Pass `'memory'` to opt back into an isolated\n * `:memory:` database — only worth it for a test that opens many databases\n * and never touches restart behavior.\n */\n mode?: 'memory' | 'file';\n /** Legacy alias for `mode`. `false` selects `:memory:`. */\n fileBacked?: boolean;\n /** Legacy alias for `mode`. `false` selects `:memory:`. */\n tempFile?: boolean;\n}\n\nexport interface TestSqliteBuilder {\n readonly schema: NormalizedTestSchema;\n readonly ops: readonly DataOperation[];\n data(rows: Record<string, Row[]>): TestSqliteBuilder;\n build(): Promise<TestSqliteDatabase>;\n}\n\ninterface BuilderState {\n readonly schema: NormalizedTestSchema;\n readonly ops: readonly DataOperation[];\n readonly options: Readonly<TestSqliteOptions>;\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 assertFixtureSqlFile(entry.resolvedPath);\n return {\n label: `sql entry #${entry.index} (${entry.sourcePath})`,\n sql: fs.readFileSync(entry.resolvedPath, 'utf8'),\n };\n } catch (err) {\n throw new TestSqliteError(\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\nasync function executeRaw(handle: TestSqliteDatabase, sql: string): Promise<void> {\n const conn = handle.conn as { exec?: (sql: string) => unknown };\n if (typeof conn?.exec === 'function') {\n await conn.exec(sql);\n } else {\n await handle.db.query(sql, []);\n }\n}\n\nfunction makeBuilder(state: BuilderState): TestSqliteBuilder {\n return {\n schema: state.schema,\n ops: state.ops,\n data(rows: Record<string, Row[]>): TestSqliteBuilder {\n return makeBuilder({\n ...state,\n ops: [...state.ops, ...toOperations(state.schema, rows)],\n });\n },\n async build(): Promise<TestSqliteDatabase> {\n const rawSql = readRawSql(state.schema);\n const ddl = generateDdl(state.schema);\n const effective = composeRows(state.schema, state.ops);\n const fileBacked = state.options.mode\n ? state.options.mode === 'file'\n : state.options.fileBacked !== false && state.options.tempFile !== false;\n const handle = await createDatabaseHandle(fileBacked);\n try {\n for (const statement of ddl) {\n try {\n await handle.db.query(statement, []);\n } catch (err) {\n throw new TestSqliteError(\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 await executeRaw(handle, entry.sql);\n } catch (err) {\n throw new TestSqliteError(\n `Failed to apply raw ${entry.label} from ${state.schema.source}: ${(err as Error).message}`\n );\n }\n }\n await insertRows((sql, params) => handle.db.query(sql, params), state.schema, effective);\n return adoptFixtureResource(handle);\n } catch (err) {\n try { await handle.dispose(); }\n catch (cleanup) { throw new TestDatabaseBuildError('SQLite fixture build and cleanup failed', err, cleanup); }\n throw err;\n }\n },\n };\n}\n\nexport function testSqlite(\n schema: string | object,\n options: TestSqliteOptions = {}\n): TestSqliteBuilder {\n const normalized = isNormalizedSchema(schema)\n ? schema\n : parseTestSchema(schema as string | object, options);\n if (normalized.dialect !== 'sqlite') {\n throw new TestSqliteError(\n `testSqlite requires a schema with dialect: sqlite (received: ${normalized.dialect})`\n );\n }\n return makeBuilder({\n schema: normalized,\n ops: [],\n options: Object.freeze({ ...options }),\n });\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"]}
|
|
1
|
+
{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../../src/testing/sqlite/builder.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoKA,gCAoBC;AAxLD,4CAA8B;AAC9B,0CAA2E;AAC3E,8DAA6D;AAC7D,uCAA4C;AAC5C,6CAAmD;AAEnD,kCAAuD;AACvD,wCAAiG;AACjG,yCAAuF;AACvF,yCAAuF;AAgDvF,SAAS,UAAU,CAAC,MAA4B;IAC9C,OAAO,MAAM,CAAC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AO,WAAW,CAAC;QACjB,MAAM,EAAE,UAAU;QAClB,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,EAAE;QACZ,KAAK,EAAE,EAAE;QACT,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC;KACvC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport { adoptFixtureResource, TestDatabaseBuildError } from '../resource';\nimport { assertFixtureSqlFile } from '../fixture-provenance';\nimport { generateDdl } from '../schema/ddl';\nimport { parseTestSchema } from '../schema/parser';\nimport type { NormalizedTestSchema, ParseTestSchemaOptions } from '../schema/types';\nimport { checkDataShape, loadLiveData } from '../live';\nimport { assertPrepareHook, builderArgs, isNormalizedSchema, TestPrepareHook } from '../prepare';\nimport { createDatabaseHandle, TestSqliteDatabase, TestSqliteError } from './database';\nimport { composeRows, DataOperation, insertRows, Row, toOperations } from './loadData';\n\nexport interface TestSqliteOptions extends ParseTestSchemaOptions {\n /**\n * Storage for the test database. Defaults to `'file'`: an owned temporary\n * file, removed on `dispose()`. Pass `'memory'` to opt back into an isolated\n * `:memory:` database — only worth it for a test that opens many databases\n * and never touches restart behavior.\n */\n mode?: 'memory' | 'file';\n /** Legacy alias for `mode`. `false` selects `:memory:`. */\n fileBacked?: boolean;\n /** Legacy alias for `mode`. `false` selects `:memory:`. */\n tempFile?: boolean;\n}\n\nexport interface TestSqliteBuilder {\n readonly schema: NormalizedTestSchema;\n readonly ops: readonly DataOperation[];\n /**\n * Returns a NEW derived builder. Without `.prepare()` hooks, rows are\n * validated immediately against the structured schema. With hooks, only\n * the payload shape is checked here; tables, columns and primary keys are\n * validated at `build()` against the live database (PRAGMA) after the hooks\n * ran, and rows are inserted in foreign-key order in one transaction.\n */\n data(rows: Record<string, Row[]>): TestSqliteBuilder;\n /**\n * Returns a NEW derived builder with `fn` appended to its prepare hooks.\n * Hooks run in order inside `build()`, after structured DDL and raw `sql:`\n * and before `.data()` rows, each receiving the test database handle.\n * Builders with hooks run the hooks with `PRAGMA foreign_keys = OFF` (as the\n * proper CLI does), then turn it ON before `.data()` rows are inserted.\n * If a hook (or the data load) fails, the database is closed and removed.\n */\n prepare(fn: TestPrepareHook<TestSqliteDatabase>): TestSqliteBuilder;\n build(): Promise<TestSqliteDatabase>;\n}\n\ninterface BuilderState {\n readonly schema: NormalizedTestSchema;\n readonly ops: readonly DataOperation[];\n /** Every `.data()` payload in call order (the live path inserts these). */\n readonly payloads: readonly Record<string, Row[]>[];\n readonly hooks: readonly TestPrepareHook<TestSqliteDatabase>[];\n readonly options: Readonly<TestSqliteOptions>;\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 assertFixtureSqlFile(entry.resolvedPath);\n return {\n label: `sql entry #${entry.index} (${entry.sourcePath})`,\n sql: fs.readFileSync(entry.resolvedPath, 'utf8'),\n };\n } catch (err) {\n throw new TestSqliteError(\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\nasync function executeRaw(handle: TestSqliteDatabase, sql: string): Promise<void> {\n const conn = handle.conn as { exec?: (sql: string) => unknown };\n if (typeof conn?.exec === 'function') {\n await conn.exec(sql);\n } else {\n await handle.db.query(sql, []);\n }\n}\n\nfunction makeBuilder(state: BuilderState): TestSqliteBuilder {\n return {\n schema: state.schema,\n ops: state.ops,\n data(rows: Record<string, Row[]>): TestSqliteBuilder {\n if (state.hooks.length > 0) {\n return makeBuilder({ ...state, payloads: [...state.payloads, checkDataShape(rows)] });\n }\n return makeBuilder({\n ...state,\n ops: [...state.ops, ...toOperations(state.schema, rows)],\n payloads: [...state.payloads, rows],\n });\n },\n prepare(fn: TestPrepareHook<TestSqliteDatabase>): TestSqliteBuilder {\n assertPrepareHook(fn);\n return makeBuilder({ ...state, hooks: [...state.hooks, fn] });\n },\n async build(): Promise<TestSqliteDatabase> {\n const live = state.hooks.length > 0;\n const rawSql = readRawSql(state.schema);\n const ddl = generateDdl(state.schema);\n const effective = live ? undefined : composeRows(state.schema, state.ops);\n const fileBacked = state.options.mode\n ? state.options.mode === 'file'\n : state.options.fileBacked !== false && state.options.tempFile !== false;\n const handle = await createDatabaseHandle(fileBacked);\n try {\n for (const statement of ddl) {\n try {\n await handle.db.query(statement, []);\n } catch (err) {\n throw new TestSqliteError(\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 await executeRaw(handle, entry.sql);\n } catch (err) {\n throw new TestSqliteError(\n `Failed to apply raw ${entry.label} from ${state.schema.source}: ${(err as Error).message}`\n );\n }\n }\n if (live) {\n // Hooks (migrations) run with foreign keys OFF, as the proper CLI's\n // sqlite3 connection does and as table-rebuild migrations require.\n // better-sqlite3 opens connections with them ON, so set it explicitly.\n // Only the prepare path touches the pragma; other fixtures keep the\n // driver default.\n await handle.db.query('PRAGMA foreign_keys = OFF', []);\n for (const hook of state.hooks) await hook(handle);\n // `.data()` rows and the returned connection are FK-checked.\n await handle.db.query('PRAGMA foreign_keys = ON', []);\n await handle.session((session) => loadLiveData(session, state.payloads));\n } else {\n await insertRows((sql, params) => handle.db.query(sql, params), state.schema, effective!);\n }\n return adoptFixtureResource(handle);\n } catch (err) {\n try { await handle.dispose(); }\n catch (cleanup) { throw new TestDatabaseBuildError('SQLite fixture build and cleanup failed', err, cleanup); }\n throw err;\n }\n },\n };\n}\n\n/**\n * Persistent immutable SQLite test database builder. Omit the schema — or\n * pass only options, e.g. `testSqlite({ mode: 'memory' })` — to start from an\n * empty database, typically shaped by `.prepare()` hooks.\n */\nexport function testSqlite(options?: TestSqliteOptions): TestSqliteBuilder;\nexport function testSqlite(schema: string | object, options?: TestSqliteOptions): TestSqliteBuilder;\nexport function testSqlite(\n schemaOrOptions?: string | object,\n maybeOptions?: TestSqliteOptions\n): TestSqliteBuilder {\n const { schema, options } = builderArgs<TestSqliteOptions>('sqlite', schemaOrOptions, maybeOptions);\n const normalized = isNormalizedSchema(schema)\n ? schema\n : parseTestSchema(schema as string | object, options, { allowEmpty: true });\n if (normalized.dialect !== 'sqlite') {\n throw new TestSqliteError(\n `testSqlite requires a schema with dialect: sqlite (received: ${normalized.dialect})`\n );\n }\n return makeBuilder({\n schema: normalized,\n ops: [],\n payloads: [],\n hooks: [],\n options: Object.freeze({ ...options }),\n });\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SqlStackError } from '../../core/errors';
|
|
2
2
|
import type { Database } from '../../registry';
|
|
3
|
+
import type { TestDatabaseSession } from '../live';
|
|
3
4
|
export declare class TestSqliteError extends SqlStackError {
|
|
4
5
|
constructor(message: string);
|
|
5
6
|
}
|
|
@@ -17,6 +18,11 @@ export interface TestSqliteDatabase {
|
|
|
17
18
|
/** Absolute database path in file mode; undefined for :memory:. */
|
|
18
19
|
readonly path?: string;
|
|
19
20
|
query(sql: string, params?: readonly unknown[]): Promise<unknown>;
|
|
21
|
+
/**
|
|
22
|
+
* Run `fn` on the fixture's single connection as one pinned session (the
|
|
23
|
+
* structural twin of the PostgreSQL handle's `session`).
|
|
24
|
+
*/
|
|
25
|
+
session<T>(fn: (session: TestDatabaseSession) => Promise<T>): Promise<T>;
|
|
20
26
|
/**
|
|
21
27
|
* Close the connection and remove owned temporary files. Idempotent:
|
|
22
28
|
* concurrent and repeated calls share one outcome. Every cleanup step is
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../../../src/testing/sqlite/database.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"database.d.ts","sourceRoot":"","sources":["../../../../src/testing/sqlite/database.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAEnD,qBAAa,eAAgB,SAAQ,aAAa;gBACpC,OAAO,EAAE,MAAM;CAI5B;AAED,MAAM,WAAW,kBAAkB;IACjC,0EAA0E;IAC1E,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;IAC1B,sEAAsE;IACtE,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,EAAE,QAAQ,GAAG,MAAM,CAAC;IACpC,uEAAuE;IACvE,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC;IACtB,6DAA6D;IAC7D,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;IACvB,mEAAmE;IACnE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAClE;;;OAGG;IACH,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,mBAAmB,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACzE;;;;OAIG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAgCD,wBAAsB,oBAAoB,CACxC,UAAU,EAAE,OAAO,GAClB,OAAO,CAAC,kBAAkB,CAAC,CA6D7B"}
|
|
@@ -120,6 +120,14 @@ async function createDatabaseHandle(fileBacked) {
|
|
|
120
120
|
throw new TestSqliteError('Test SQLite database has been disposed.');
|
|
121
121
|
return db.query(sql, [...params]);
|
|
122
122
|
},
|
|
123
|
+
async session(fn) {
|
|
124
|
+
if (disposal)
|
|
125
|
+
throw new TestSqliteError('Test SQLite database has been disposed.');
|
|
126
|
+
return fn(Object.freeze({
|
|
127
|
+
engine: 'sqlite',
|
|
128
|
+
query: (sql, params = []) => db.query(sql, [...params]),
|
|
129
|
+
}));
|
|
130
|
+
},
|
|
123
131
|
dispose() {
|
|
124
132
|
if (!disposal) {
|
|
125
133
|
(0, resource_1.retireResource)(handle);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database.js","sourceRoot":"","sources":["../../../../src/testing/sqlite/database.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"database.js","sourceRoot":"","sources":["../../../../src/testing/sqlite/database.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyEA,oDA+DC;AAxID,4CAA8B;AAC9B,4CAA8B;AAC9B,gDAAkC;AAClC,kDAAuD;AACvD,8CAAkD;AAElD,0CAA0H;AAG1H,MAAa,eAAgB,SAAQ,sBAAa;IAChD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;IAChC,CAAC;CACF;AALD,0CAKC;AA6BD;;;;GAIG;AACH,MAAM,oBAAoB,GAAG,IAAI,GAAG,EAAU,CAAC;AAC/C,IAAI,qBAAqB,GAAG,KAAK,CAAC;AAElC,SAAS,cAAc,CAAC,SAAiB;IACvC,oBAAoB,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACpC,IAAI,qBAAqB;QAAE,OAAO;IAClC,qBAAqB,GAAG,IAAI,CAAC;IAC7B,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE;QACxB,KAAK,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;YACvC,IAAI,CAAC;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C;aACpF,CAAC,CAAC,CAAC;QACN,CAAC;QACD,OAAO;YACL,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACd,IAAA,yBAAc,EAAC,MAAM,CAAC,CAAC;gBACvB,MAAM,KAAK,GAAmC,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC;gBACjE,IAAI,cAAc;oBAAE,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,oBAAoB,CAAC,cAAc,CAAC,CAAC,CAAC;gBAC3E,QAAQ,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAA,0BAAe,EAAC,yBAAyB,OAAO,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;YACvG,CAAC;YACD,OAAO,QAAQ,CAAC;QAClB,CAAC;KACF,CAAC;IACF,IAAA,2BAAgB,EAAC,MAAM,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC,CAAC;IACpE,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { createSqliteDb } from '../../adapters/sqlite';\nimport { SqlStackError } from '../../core/errors';\nimport type { Database } from '../../registry';\nimport { mintResourceId, registerResource, retireResource, runCleanupSteps, TestDatabaseDisposeError } from '../resource';\nimport type { TestDatabaseSession } from '../live';\n\nexport class TestSqliteError extends SqlStackError {\n constructor(message: string) {\n super(message);\n this.name = 'TestSqliteError';\n }\n}\n\nexport interface TestSqliteDatabase {\n /** Engine discriminator for SQLStack-minted disposable test databases. */\n readonly engine: 'sqlite';\n /** Fresh per-allocation identifier; never reused within a process. */\n readonly resourceId: string;\n /** Explicit storage: an owned temporary file, or an isolated `:memory:` db. */\n readonly storage: 'memory' | 'file';\n /** The live sqlstack SQLite adapter, suitable for direct injection. */\n readonly db: Database;\n /** The underlying better-sqlite3 (or sqlite3) connection. */\n readonly conn: unknown;\n /** Absolute database path in file mode; undefined for :memory:. */\n readonly path?: string;\n query(sql: string, params?: readonly unknown[]): Promise<unknown>;\n /**\n * Run `fn` on the fixture's single connection as one pinned session (the\n * structural twin of the PostgreSQL handle's `session`).\n */\n session<T>(fn: (session: TestDatabaseSession) => Promise<T>): Promise<T>;\n /**\n * Close the connection and remove owned temporary files. Idempotent:\n * concurrent and repeated calls share one outcome. Every cleanup step is\n * attempted; failures are aggregated into a `TestDatabaseDisposeError`.\n */\n dispose(): Promise<void>;\n}\n\n/**\n * Temp directories for file-backed handles that were never disposed. Tests are\n * expected to call `dispose()`, but a failed assertion can skip it; this keeps\n * an abandoned directory from outliving the worker process.\n */\nconst abandonedDirectories = new Set<string>();\nlet exitCleanupRegistered = false;\n\nfunction trackDirectory(directory: string): void {\n abandonedDirectories.add(directory);\n if (exitCleanupRegistered) return;\n exitCleanupRegistered = true;\n process.once('exit', () => {\n for (const dir of abandonedDirectories) {\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n } catch {\n /* best-effort cleanup */\n }\n }\n });\n}\n\n/** Remove exactly the SQLStack-owned temp directory; never a caller path. */\nfunction removeOwnedDirectory(directory: string): void {\n fs.rmSync(directory, { recursive: true, force: true });\n // Keep failed paths in the owned inventory for the exit cleanup retry.\n abandonedDirectories.delete(directory);\n}\n\nexport async function createDatabaseHandle(\n fileBacked: boolean\n): Promise<TestSqliteDatabase> {\n let directory: string | undefined;\n let filename = ':memory:';\n if (fileBacked) {\n directory = fs.mkdtempSync(path.join(os.tmpdir(), 'sqlstack-test-'));\n filename = path.join(directory, 'database.sqlite');\n trackDirectory(directory);\n }\n\n let db: Database;\n try {\n db = await createSqliteDb(filename);\n } catch (err) {\n if (directory) {\n try { removeOwnedDirectory(directory); }\n catch (cleanup) {\n throw Object.assign(new TestDatabaseDisposeError('SQLite test allocation failed and owned cleanup failed', [err, cleanup]), { cause: err });\n }\n }\n const message = (err as Error).message;\n if (message.includes('No SQLite driver available')) {\n throw new TestSqliteError('testSqlite requires the optional peer \"better-sqlite3\".');\n }\n throw new TestSqliteError(`Failed to create SQLite test database: ${message}`);\n }\n\n const storage: 'memory' | 'file' = fileBacked ? 'file' : 'memory';\n const resourceId = mintResourceId('sqlite');\n const ownedDirectory = directory;\n let disposal: Promise<void> | undefined;\n\n const handle: TestSqliteDatabase = {\n engine: 'sqlite',\n resourceId,\n storage,\n db,\n conn: db.conn,\n path: fileBacked ? filename : undefined,\n async query(sql: string, params: readonly unknown[] = []) {\n if (disposal) throw new TestSqliteError('Test SQLite database has been disposed.');\n return db.query(sql, [...params]);\n },\n async session<T>(fn: (session: TestDatabaseSession) => Promise<T>): Promise<T> {\n if (disposal) throw new TestSqliteError('Test SQLite database has been disposed.');\n return fn(Object.freeze({\n engine: 'sqlite' as const,\n query: (sql: string, params: readonly unknown[] = []) => db.query(sql, [...params]),\n }));\n },\n dispose() {\n if (!disposal) {\n retireResource(handle);\n const steps: (() => Promise<void> | void)[] = [() => db.close()];\n if (ownedDirectory) steps.push(() => removeOwnedDirectory(ownedDirectory));\n disposal = Promise.resolve().then(() => runCleanupSteps(`Test SQLite database (${storage})`, steps));\n }\n return disposal;\n },\n };\n registerResource(handle, { engine: 'sqlite', resourceId, storage });\n return handle;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadData.d.ts","sourceRoot":"","sources":["../../../../src/testing/sqlite/loadData.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"loadData.d.ts","sourceRoot":"","sources":["../../../../src/testing/sqlite/loadData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC5D,OAAO,EACL,aAAa,EACb,WAAW,EAEX,eAAe,EAEf,YAAY,EACb,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,sBAAsB,CAAC;AAE/D,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,eAAe,EAAE,YAAY,EAAE,CAAC;AACrE,YAAY,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC;AAEnC,wBAAsB,UAAU,CAC9B,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,EAC3D,MAAM,EAAE,oBAAoB,EAC5B,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,GAC5B,OAAO,CAAC,IAAI,CAAC,CAEf"}
|
|
@@ -2,54 +2,12 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.toOperations = exports.planInsertOrder = exports.composeRows = exports.TestDataError = void 0;
|
|
4
4
|
exports.insertRows = insertRows;
|
|
5
|
-
const ddl_1 = require("../schema/ddl");
|
|
6
5
|
const loadData_1 = require("../postgres/loadData");
|
|
7
6
|
Object.defineProperty(exports, "TestDataError", { enumerable: true, get: function () { return loadData_1.TestDataError; } });
|
|
8
7
|
Object.defineProperty(exports, "composeRows", { enumerable: true, get: function () { return loadData_1.composeRows; } });
|
|
9
8
|
Object.defineProperty(exports, "planInsertOrder", { enumerable: true, get: function () { return loadData_1.planInsertOrder; } });
|
|
10
9
|
Object.defineProperty(exports, "toOperations", { enumerable: true, get: function () { return loadData_1.toOperations; } });
|
|
11
10
|
async function insertRows(query, schema, effective) {
|
|
12
|
-
|
|
13
|
-
const declared = new Map(schema.tables.map((table) => [
|
|
14
|
-
table.name,
|
|
15
|
-
table.columns.map((column) => column.name),
|
|
16
|
-
]));
|
|
17
|
-
for (const tableName of order) {
|
|
18
|
-
const rows = effective.get(tableName);
|
|
19
|
-
const columnOrder = declared.get(tableName);
|
|
20
|
-
const batches = new Map();
|
|
21
|
-
for (const row of rows) {
|
|
22
|
-
const columns = columnOrder.filter((column) => row[column] !== undefined);
|
|
23
|
-
const signature = columns.join(',');
|
|
24
|
-
const batch = batches.get(signature) ?? { columns, rows: [] };
|
|
25
|
-
batch.rows.push(row);
|
|
26
|
-
batches.set(signature, batch);
|
|
27
|
-
}
|
|
28
|
-
for (const { columns, rows: batchRows } of batches.values()) {
|
|
29
|
-
if (columns.length === 0) {
|
|
30
|
-
for (let i = 0; i < batchRows.length; i++) {
|
|
31
|
-
await run(query, tableName, `INSERT INTO ${(0, ddl_1.quoteIdent)(tableName)} DEFAULT VALUES`, []);
|
|
32
|
-
}
|
|
33
|
-
continue;
|
|
34
|
-
}
|
|
35
|
-
const params = [];
|
|
36
|
-
const tuples = batchRows.map((row) => {
|
|
37
|
-
const placeholders = columns.map((column) => {
|
|
38
|
-
params.push(row[column]);
|
|
39
|
-
return '?';
|
|
40
|
-
});
|
|
41
|
-
return `(${placeholders.join(', ')})`;
|
|
42
|
-
});
|
|
43
|
-
await run(query, tableName, `INSERT INTO ${(0, ddl_1.quoteIdent)(tableName)} (${columns.map(ddl_1.quoteIdent).join(', ')}) VALUES ${tuples.join(', ')}`, params);
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
async function run(query, tableName, sql, params) {
|
|
48
|
-
try {
|
|
49
|
-
await query(sql, params);
|
|
50
|
-
}
|
|
51
|
-
catch (err) {
|
|
52
|
-
throw new loadData_1.TestDataError(`Failed to insert scenario rows into table "${tableName}": ${err.message}`);
|
|
53
|
-
}
|
|
11
|
+
await (0, loadData_1.insertPlannedRows)(query, (0, loadData_1.structuredInsertPlan)(schema, effective), effective, () => '?');
|
|
54
12
|
}
|
|
55
13
|
//# sourceMappingURL=loadData.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loadData.js","sourceRoot":"","sources":["../../../../src/testing/sqlite/loadData.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"loadData.js","sourceRoot":"","sources":["../../../../src/testing/sqlite/loadData.ts"],"names":[],"mappings":";;;AAcA,gCAMC;AAnBD,mDAO8B;AAGrB,8FATP,wBAAa,OASO;AAAE,4FARtB,sBAAW,OAQsB;AAAE,gGANnC,0BAAe,OAMmC;AAAE,6FAJpD,uBAAY,OAIoD;AAG3D,KAAK,UAAU,UAAU,CAC9B,KAA2D,EAC3D,MAA4B,EAC5B,SAA6B;IAE7B,MAAM,IAAA,4BAAiB,EAAC,KAAK,EAAE,IAAA,+BAAoB,EAAC,MAAM,EAAE,SAAS,CAAC,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC;AAChG,CAAC","sourcesContent":["import type { NormalizedTestSchema } from '../schema/types';\nimport {\n TestDataError,\n composeRows,\n insertPlannedRows,\n planInsertOrder,\n structuredInsertPlan,\n toOperations,\n} from '../postgres/loadData';\nimport type { DataOperation, Row } from '../postgres/loadData';\n\nexport { TestDataError, composeRows, planInsertOrder, toOperations };\nexport type { DataOperation, Row };\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 await insertPlannedRows(query, structuredInsertPlan(schema, effective), effective, () => '?');\n}\n"]}
|
|
@@ -8,6 +8,8 @@ import { createDatabaseHandle } from './postgres/database.js';
|
|
|
8
8
|
import { dropDatabase } from './postgres/allocator.js';
|
|
9
9
|
import { TestPostgresServerError } from './postgres/server.js';
|
|
10
10
|
import { composeRows, insertRows, toOperations } from './postgres/loadData.js';
|
|
11
|
+
import { checkDataShape, loadLiveData } from './live.js';
|
|
12
|
+
import { assertPrepareHook, builderArgs, isNormalizedSchema } from './prepare.js';
|
|
11
13
|
function readRawSql(schema) {
|
|
12
14
|
return schema.sql.map((entry) => {
|
|
13
15
|
if (entry.kind === 'inline') {
|
|
@@ -31,15 +33,23 @@ function makeBuilder(state) {
|
|
|
31
33
|
schema: state.schema,
|
|
32
34
|
ops: state.ops,
|
|
33
35
|
data(rows) {
|
|
36
|
+
if (state.hooks.length > 0) {
|
|
37
|
+
return makeBuilder({ ...state, payloads: [...state.payloads, checkDataShape(rows)] });
|
|
38
|
+
}
|
|
34
39
|
const newOps = toOperations(state.schema, rows);
|
|
35
|
-
return makeBuilder({ ...state, ops: [...state.ops, ...newOps] });
|
|
40
|
+
return makeBuilder({ ...state, ops: [...state.ops, ...newOps], payloads: [...state.payloads, rows] });
|
|
41
|
+
},
|
|
42
|
+
prepare(fn) {
|
|
43
|
+
assertPrepareHook(fn);
|
|
44
|
+
return makeBuilder({ ...state, hooks: [...state.hooks, fn] });
|
|
36
45
|
},
|
|
37
46
|
async build() {
|
|
47
|
+
const live = state.hooks.length > 0;
|
|
38
48
|
// Fail on pure planning errors (cycles, raw SQL file readability)
|
|
39
49
|
// before touching the server where possible.
|
|
40
50
|
const rawSql = readRawSql(state.schema);
|
|
41
51
|
const ddl = generateDdl(state.schema);
|
|
42
|
-
const effective = composeRows(state.schema, state.ops);
|
|
52
|
+
const effective = live ? undefined : composeRows(state.schema, state.ops);
|
|
43
53
|
const allocated = await allocateDatabase(state.options);
|
|
44
54
|
let handle;
|
|
45
55
|
try {
|
|
@@ -63,7 +73,14 @@ function makeBuilder(state) {
|
|
|
63
73
|
throw new TestPostgresServerError(`Failed to apply raw ${entry.label} from ${state.schema.source}: ${err.message}`);
|
|
64
74
|
}
|
|
65
75
|
}
|
|
66
|
-
|
|
76
|
+
if (live) {
|
|
77
|
+
for (const hook of state.hooks)
|
|
78
|
+
await hook(handle);
|
|
79
|
+
await handle.session((session) => loadLiveData(session, state.payloads));
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
await insertRows((sql, params) => handle._pool.query(sql, params), state.schema, effective);
|
|
83
|
+
}
|
|
67
84
|
return adoptFixtureResource(handle);
|
|
68
85
|
}
|
|
69
86
|
catch (err) {
|
|
@@ -83,22 +100,15 @@ function makeBuilder(state) {
|
|
|
83
100
|
},
|
|
84
101
|
};
|
|
85
102
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
function isNormalizedSchema(input) {
|
|
98
|
-
return (!!input &&
|
|
99
|
-
typeof input === 'object' &&
|
|
100
|
-
Array.isArray(input.tables) &&
|
|
101
|
-
Array.isArray(input.sql) &&
|
|
102
|
-
typeof input.source === 'string');
|
|
103
|
+
export function testPostgres(schemaOrOptions, maybeOptions) {
|
|
104
|
+
const { schema, options } = builderArgs('postgres', schemaOrOptions, maybeOptions);
|
|
105
|
+
const normalized = isNormalizedSchema(schema) ? schema : parseTestSchema(schema, options, { allowEmpty: true });
|
|
106
|
+
return makeBuilder({
|
|
107
|
+
schema: normalized,
|
|
108
|
+
ops: [],
|
|
109
|
+
payloads: [],
|
|
110
|
+
hooks: [],
|
|
111
|
+
options: Object.freeze({ ...options }),
|
|
112
|
+
});
|
|
103
113
|
}
|
|
104
114
|
//# sourceMappingURL=builder.js.map
|
|
@@ -1 +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,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,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,OAAO,EAAE,WAAW,EAAiB,UAAU,EAAO,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAyBhG,SAAS,UAA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as fs from 'fs';\nimport { adoptFixtureResource, TestDatabaseBuildError } from './resource';\nimport { assertFixtureSqlFile } from './fixture-provenance';\nimport { parseTestSchema } 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 assertFixtureSqlFile(entry.resolvedPath);\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 adoptFixtureResource(handle);\n } catch (err) {\n // Use the handle's all-steps disposer and retire its provenance even\n // after failed DDL/data. Preserve allocation and every cleanup failure.\n try {\n if (handle) await handle.dispose();\n else await dropDatabase(allocated.name, state.options);\n } catch (cleanup) {\n throw new TestDatabaseBuildError('PostgreSQL fixture build and cleanup failed', err, cleanup);\n }\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"]}
|
|
1
|
+
{"version":3,"file":"builder.js","sourceRoot":"","sources":["../../../src/testing/builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,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,OAAO,EAAE,WAAW,EAAiB,UAAU,EAAO,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAChG,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,kBAAkB,EAAmB,MAAM,WAAW,CAAC;AA4ChG,SAAS,UAAU,CAAC,MAA4B;IAC9C,OAAO,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAC9B,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC5B,OAAO,EAAE,KAAK,EAAE,cAAc,KAAK,CAAC,KAAK,WAAW,EAAE,GAAG,EAA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,CAAC;AAaD,MAAM,UAAU,YAAY,CAC1B,eAAiC,EACjC,YAAkC;IAElC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,WAAW,CAAsB,UAAU,EAAE,eAAe,EAAE,YAAY,CAAC,CAAC;IACxG,MAAM,UAAU,GACd,kBAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,eAAe,CAAC,MAAyB,EAAE,OAAO,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;IAClH,OAAO,WAAW,CAAC;QACjB,MAAM,EAAE,UAAU;QAClB,GAAG,EAAE,EAAE;QACP,QAAQ,EAAE,EAAE;QACZ,KAAK,EAAE,EAAE;QACT,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,OAAO,EAAE,CAAC;KACvC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as fs from 'fs';\nimport { adoptFixtureResource, TestDatabaseBuildError } from './resource';\nimport { assertFixtureSqlFile } from './fixture-provenance';\nimport { parseTestSchema } 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';\nimport { checkDataShape, loadLiveData } from './live';\nimport { assertPrepareHook, builderArgs, isNormalizedSchema, TestPrepareHook } from './prepare';\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 /**\n * Returns a NEW derived builder; this builder is unchanged.\n *\n * Without `.prepare()` hooks, rows are validated immediately against the\n * structured schema. With hooks, only the payload shape is checked here;\n * tables, columns and primary keys are validated at `build()` against the\n * live database after the hooks ran, and rows are inserted in foreign-key\n * order in one transaction on one pinned connection.\n */\n data(rows: Record<string, Row[]>): TestPostgresBuilder;\n /**\n * Returns a NEW derived builder with `fn` appended to its prepare hooks.\n * Hooks run in order inside `build()`, after structured DDL and raw `sql:`\n * and before `.data()` rows, each receiving the test database handle. If a\n * hook (or the data load) fails, the database is closed and dropped.\n */\n prepare(fn: TestPrepareHook<TestPostgresDatabase>): TestPostgresBuilder;\n /**\n * Create a fresh isolated PostgreSQL database, apply DDL + raw SQL, run\n * prepare hooks, insert effective scenario rows, and return the handle.\n * Does not consume the builder: building twice yields two independent\n * databases.\n */\n build(): Promise<TestPostgresDatabase>;\n}\n\ninterface BuilderState {\n readonly schema: NormalizedTestSchema;\n readonly ops: readonly DataOperation[];\n /** Every `.data()` payload in call order (the live path inserts these). */\n readonly payloads: readonly Record<string, Row[]>[];\n readonly hooks: readonly TestPrepareHook<TestPostgresDatabase>[];\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 assertFixtureSqlFile(entry.resolvedPath);\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 if (state.hooks.length > 0) {\n return makeBuilder({ ...state, payloads: [...state.payloads, checkDataShape(rows)] });\n }\n const newOps = toOperations(state.schema, rows);\n return makeBuilder({ ...state, ops: [...state.ops, ...newOps], payloads: [...state.payloads, rows] });\n },\n prepare(fn: TestPrepareHook<TestPostgresDatabase>): TestPostgresBuilder {\n assertPrepareHook(fn);\n return makeBuilder({ ...state, hooks: [...state.hooks, fn] });\n },\n async build(): Promise<TestPostgresDatabase> {\n const live = state.hooks.length > 0;\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 = live ? undefined : 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 if (live) {\n for (const hook of state.hooks) await hook(handle);\n await handle.session((session) => loadLiveData(session, state.payloads));\n } else {\n await insertRows((sql, params) => handle!._pool.query(sql, params), state.schema, effective!);\n }\n return adoptFixtureResource(handle);\n } catch (err) {\n // Use the handle's all-steps disposer and retire its provenance even\n // after failed DDL/data. Preserve allocation and every cleanup failure.\n try {\n if (handle) await handle.dispose();\n else await dropDatabase(allocated.name, state.options);\n } catch (cleanup) {\n throw new TestDatabaseBuildError('PostgreSQL fixture build and cleanup failed', err, cleanup);\n }\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). Omit it — or pass only\n * options, e.g. `testPostgres({ adminUrl })` — to start from an empty\n * database, typically shaped by `.prepare()` hooks such as real migrations.\n */\nexport function testPostgres(options?: TestPostgresOptions): TestPostgresBuilder;\nexport function testPostgres(schema: string | object, options?: TestPostgresOptions): TestPostgresBuilder;\nexport function testPostgres(\n schemaOrOptions?: string | object,\n maybeOptions?: TestPostgresOptions\n): TestPostgresBuilder {\n const { schema, options } = builderArgs<TestPostgresOptions>('postgres', schemaOrOptions, maybeOptions);\n const normalized =\n isNormalizedSchema(schema) ? schema : parseTestSchema(schema as string | object, options, { allowEmpty: true });\n return makeBuilder({\n schema: normalized,\n ops: [],\n payloads: [],\n hooks: [],\n options: Object.freeze({ ...options }),\n });\n}\n"]}
|
|
@@ -1 +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,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;
|
|
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,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAIpD,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAExG,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 { testSqlite } from './sqlite/builder';\nexport type { TestSqliteBuilder, TestSqliteOptions } from './sqlite/builder';\nexport { TestSqliteError } from './sqlite/database';\nexport type { TestSqliteDatabase } from './sqlite/database';\nexport type { TestPrepareHook } from './prepare';\nexport type { TestDatabaseSession } from './live';\nexport { isDisposableTestDatabase, TestDatabaseDisposeError, TestDatabaseBuildError } from './resource';\nexport type { DisposableTestDatabase } from './resource';\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"]}
|