@geekmidas/testkit 1.0.3 → 1.0.5
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/CHANGELOG.md +12 -0
- package/dist/{Factory-BOX312yd.d.cts → Factory-CUM2767q.d.cts} +2 -2
- package/dist/{Factory-BOX312yd.d.cts.map → Factory-CUM2767q.d.cts.map} +1 -1
- package/dist/{Factory-CVR3GdkW.d.mts → Factory-SFupxRC2.d.mts} +2 -2
- package/dist/{Factory-CVR3GdkW.d.mts.map → Factory-SFupxRC2.d.mts.map} +1 -1
- package/dist/Factory.d.cts +2 -2
- package/dist/Factory.d.mts +2 -2
- package/dist/{KyselyFactory-DRlMv-WT.d.mts → KyselyFactory-OMwcuAX_.d.cts} +3 -3
- package/dist/{KyselyFactory-DRlMv-WT.d.mts.map → KyselyFactory-OMwcuAX_.d.cts.map} +1 -1
- package/dist/{KyselyFactory-Dy5zzV4B.d.cts → KyselyFactory-vAxYodck.d.mts} +3 -3
- package/dist/{KyselyFactory-Dy5zzV4B.d.cts.map → KyselyFactory-vAxYodck.d.mts.map} +1 -1
- package/dist/KyselyFactory.d.cts +3 -3
- package/dist/KyselyFactory.d.mts +3 -3
- package/dist/{ObjectionFactory-CD-WFuMJ.d.cts → ObjectionFactory-BWjB49-i.d.mts} +3 -3
- package/dist/{ObjectionFactory-CD-WFuMJ.d.cts.map → ObjectionFactory-BWjB49-i.d.mts.map} +1 -1
- package/dist/{ObjectionFactory-DkJUf-uM.d.mts → ObjectionFactory-DvmZVHhe.d.cts} +3 -3
- package/dist/{ObjectionFactory-DkJUf-uM.d.mts.map → ObjectionFactory-DvmZVHhe.d.cts.map} +1 -1
- package/dist/ObjectionFactory.d.cts +3 -3
- package/dist/ObjectionFactory.d.mts +3 -3
- package/dist/{PostgresKyselyMigrator-B4pScubb.mjs → PostgresKyselyMigrator-BIKd7G5C.mjs} +16 -3
- package/dist/PostgresKyselyMigrator-BIKd7G5C.mjs.map +1 -0
- package/dist/{PostgresKyselyMigrator-CBltSOq5.d.cts → PostgresKyselyMigrator-CTNftoZK.d.cts} +16 -2
- package/dist/PostgresKyselyMigrator-CTNftoZK.d.cts.map +1 -0
- package/dist/{PostgresKyselyMigrator-C7ljZYvq.cjs → PostgresKyselyMigrator-CqNs3qX8.cjs} +16 -3
- package/dist/PostgresKyselyMigrator-CqNs3qX8.cjs.map +1 -0
- package/dist/{PostgresKyselyMigrator-DrVWncqd.d.mts → PostgresKyselyMigrator-x0uvWs3U.d.mts} +16 -2
- package/dist/PostgresKyselyMigrator-x0uvWs3U.d.mts.map +1 -0
- package/dist/PostgresKyselyMigrator.cjs +2 -2
- package/dist/PostgresKyselyMigrator.d.cts +2 -2
- package/dist/PostgresKyselyMigrator.d.mts +2 -2
- package/dist/PostgresKyselyMigrator.mjs +2 -2
- package/dist/{PostgresMigrator-Bres0U6E.d.cts → PostgresMigrator-C_QQ6q35.d.mts} +15 -2
- package/dist/PostgresMigrator-C_QQ6q35.d.mts.map +1 -0
- package/dist/{PostgresMigrator-S-YYosAC.d.mts → PostgresMigrator-CeYy-eHF.d.cts} +15 -2
- package/dist/PostgresMigrator-CeYy-eHF.d.cts.map +1 -0
- package/dist/{PostgresMigrator-DcP1o-T6.mjs → PostgresMigrator-DVAY04qN.mjs} +16 -2
- package/dist/PostgresMigrator-DVAY04qN.mjs.map +1 -0
- package/dist/{PostgresMigrator-CHiBYEg_.cjs → PostgresMigrator-M9jpzOvN.cjs} +16 -2
- package/dist/PostgresMigrator-M9jpzOvN.cjs.map +1 -0
- package/dist/PostgresMigrator.cjs +1 -1
- package/dist/PostgresMigrator.d.cts +1 -1
- package/dist/PostgresMigrator.d.mts +1 -1
- package/dist/PostgresMigrator.mjs +1 -1
- package/dist/{PostgresObjectionMigrator-CPfBAP7r.d.cts → PostgresObjectionMigrator-1j6YIB1c.d.mts} +2 -2
- package/dist/{PostgresObjectionMigrator-CPfBAP7r.d.cts.map → PostgresObjectionMigrator-1j6YIB1c.d.mts.map} +1 -1
- package/dist/{PostgresObjectionMigrator-DVEqB5tp.d.mts → PostgresObjectionMigrator-DHVC9h_P.d.cts} +2 -2
- package/dist/{PostgresObjectionMigrator-DVEqB5tp.d.mts.map → PostgresObjectionMigrator-DHVC9h_P.d.cts.map} +1 -1
- package/dist/{PostgresObjectionMigrator-BXLAVVwm.cjs → PostgresObjectionMigrator-DSaPhwjY.cjs} +2 -2
- package/dist/{PostgresObjectionMigrator-BXLAVVwm.cjs.map → PostgresObjectionMigrator-DSaPhwjY.cjs.map} +1 -1
- package/dist/{PostgresObjectionMigrator-BJ5X48U8.mjs → PostgresObjectionMigrator-DjPKdUbm.mjs} +2 -2
- package/dist/{PostgresObjectionMigrator-BJ5X48U8.mjs.map → PostgresObjectionMigrator-DjPKdUbm.mjs.map} +1 -1
- package/dist/PostgresObjectionMigrator.cjs +2 -2
- package/dist/PostgresObjectionMigrator.d.cts +2 -2
- package/dist/PostgresObjectionMigrator.d.mts +2 -2
- package/dist/PostgresObjectionMigrator.mjs +2 -2
- package/dist/better-auth.d.cts +2 -2
- package/dist/better-auth.d.mts +2 -2
- package/dist/{directory-DGOcVlKD.d.cts → directory-CYXmolu1.d.mts} +3 -3
- package/dist/{directory-DGOcVlKD.d.cts.map → directory-CYXmolu1.d.mts.map} +1 -1
- package/dist/{directory-YzQUGC5g.d.mts → directory-DAnMWi50.d.cts} +3 -3
- package/dist/{directory-YzQUGC5g.d.mts.map → directory-DAnMWi50.d.cts.map} +1 -1
- package/dist/{faker-DsYCplsG.d.mts → faker-DHh7xs4u.d.mts} +3 -3
- package/dist/{faker-DsYCplsG.d.mts.map → faker-DHh7xs4u.d.mts.map} +1 -1
- package/dist/{faker-Cg76aFNO.d.cts → faker-zVCm31nU.d.cts} +3 -3
- package/dist/{faker-Cg76aFNO.d.cts.map → faker-zVCm31nU.d.cts.map} +1 -1
- package/dist/faker.d.cts +1 -1
- package/dist/faker.d.mts +1 -1
- package/dist/initScript.cjs +1 -0
- package/dist/initScript.cjs.map +1 -1
- package/dist/initScript.d.cts.map +1 -1
- package/dist/initScript.d.mts.map +1 -1
- package/dist/initScript.mjs +1 -0
- package/dist/initScript.mjs.map +1 -1
- package/dist/kysely.cjs +2 -2
- package/dist/kysely.d.cts +5 -5
- package/dist/kysely.d.mts +5 -5
- package/dist/kysely.mjs +2 -2
- package/dist/objection.cjs +2 -2
- package/dist/objection.d.cts +5 -5
- package/dist/objection.d.mts +5 -5
- package/dist/objection.mjs +2 -2
- package/dist/os/directory.d.cts +1 -1
- package/dist/os/directory.d.mts +1 -1
- package/dist/os/index.d.cts +1 -1
- package/dist/os/index.d.mts +1 -1
- package/package.json +3 -3
- package/src/PostgresKyselyMigrator.ts +15 -1
- package/src/PostgresMigrator.ts +19 -2
- package/src/__tests__/PostgresKyselyMigrator.spec.ts +104 -0
- package/src/__tests__/PostgresMigrator.spec.ts +109 -0
- package/src/__tests__/initScript.spec.ts +24 -0
- package/src/initScript.ts +3 -0
- package/dist/PostgresKyselyMigrator-B4pScubb.mjs.map +0 -1
- package/dist/PostgresKyselyMigrator-C7ljZYvq.cjs.map +0 -1
- package/dist/PostgresKyselyMigrator-CBltSOq5.d.cts.map +0 -1
- package/dist/PostgresKyselyMigrator-DrVWncqd.d.mts.map +0 -1
- package/dist/PostgresMigrator-Bres0U6E.d.cts.map +0 -1
- package/dist/PostgresMigrator-CHiBYEg_.cjs.map +0 -1
- package/dist/PostgresMigrator-DcP1o-T6.mjs.map +0 -1
- package/dist/PostgresMigrator-S-YYosAC.d.mts.map +0 -1
package/dist/os/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { itWithDir } from "../directory-
|
|
1
|
+
import { itWithDir } from "../directory-CYXmolu1.mjs";
|
|
2
2
|
export { itWithDir };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geekmidas/testkit",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -80,8 +80,8 @@
|
|
|
80
80
|
"vitest": "~3.2.4",
|
|
81
81
|
"@types/aws-lambda": ">=8.10.92",
|
|
82
82
|
"better-auth": ">=1.3.34",
|
|
83
|
-
"@geekmidas/
|
|
84
|
-
"@geekmidas/
|
|
83
|
+
"@geekmidas/envkit": "^1.0.3",
|
|
84
|
+
"@geekmidas/logger": "^1.0.0"
|
|
85
85
|
},
|
|
86
86
|
"peerDependenciesMeta": {
|
|
87
87
|
"@geekmidas/envkit": {
|
|
@@ -40,6 +40,18 @@ const logger = console;
|
|
|
40
40
|
* const cleanup = await migrator.start();
|
|
41
41
|
* // Run tests...
|
|
42
42
|
* await cleanup();
|
|
43
|
+
*
|
|
44
|
+
* // With afterCreate hook to create per-app users
|
|
45
|
+
* import { runInitScript } from '@geekmidas/testkit/postgres';
|
|
46
|
+
*
|
|
47
|
+
* const migrator = new PostgresKyselyMigrator({
|
|
48
|
+
* uri: 'postgresql://localhost:5432/test_db',
|
|
49
|
+
* db,
|
|
50
|
+
* provider,
|
|
51
|
+
* afterCreate: async (uri) => {
|
|
52
|
+
* await runInitScript('docker/postgres/init.sh', uri, env);
|
|
53
|
+
* },
|
|
54
|
+
* });
|
|
43
55
|
* ```
|
|
44
56
|
*/
|
|
45
57
|
export class PostgresKyselyMigrator extends PostgresMigrator {
|
|
@@ -50,15 +62,17 @@ export class PostgresKyselyMigrator extends PostgresMigrator {
|
|
|
50
62
|
* @param options.uri - PostgreSQL connection URI
|
|
51
63
|
* @param options.db - Kysely database instance
|
|
52
64
|
* @param options.provider - Migration provider for locating migration files
|
|
65
|
+
* @param options.afterCreate - Optional hook called after database creation but before migrations
|
|
53
66
|
*/
|
|
54
67
|
constructor(
|
|
55
68
|
private options: {
|
|
56
69
|
uri: string;
|
|
57
70
|
db: Kysely<any>;
|
|
58
71
|
provider: MigrationProvider;
|
|
72
|
+
afterCreate?: (uri: string) => Promise<void>;
|
|
59
73
|
},
|
|
60
74
|
) {
|
|
61
|
-
super(options.uri);
|
|
75
|
+
super(options.uri, options.afterCreate);
|
|
62
76
|
}
|
|
63
77
|
|
|
64
78
|
/**
|
package/src/PostgresMigrator.ts
CHANGED
|
@@ -57,6 +57,17 @@ const logger = console;
|
|
|
57
57
|
* const migrator = new MyMigrator('postgresql://localhost:5432/test_db');
|
|
58
58
|
* const cleanup = await migrator.start();
|
|
59
59
|
*
|
|
60
|
+
* // With afterCreate hook (e.g. run init script to create per-app users)
|
|
61
|
+
* import { runInitScript } from '@geekmidas/testkit/postgres';
|
|
62
|
+
*
|
|
63
|
+
* const migrator = new MyMigrator(
|
|
64
|
+
* 'postgresql://localhost:5432/test_db',
|
|
65
|
+
* async (uri) => {
|
|
66
|
+
* await runInitScript('docker/postgres/init.sh', uri, env);
|
|
67
|
+
* },
|
|
68
|
+
* );
|
|
69
|
+
* const cleanup = await migrator.start();
|
|
70
|
+
*
|
|
60
71
|
* // Run tests...
|
|
61
72
|
*
|
|
62
73
|
* // Clean up
|
|
@@ -68,8 +79,12 @@ export abstract class PostgresMigrator {
|
|
|
68
79
|
* Creates a new PostgresMigrator instance.
|
|
69
80
|
*
|
|
70
81
|
* @param uri - PostgreSQL connection URI
|
|
82
|
+
* @param afterCreate - Optional hook called after database creation but before migrations
|
|
71
83
|
*/
|
|
72
|
-
constructor(
|
|
84
|
+
constructor(
|
|
85
|
+
private uri: string,
|
|
86
|
+
private afterCreate?: (uri: string) => Promise<void>,
|
|
87
|
+
) {}
|
|
73
88
|
|
|
74
89
|
/**
|
|
75
90
|
* Abstract method to be implemented by subclasses.
|
|
@@ -161,7 +176,9 @@ export abstract class PostgresMigrator {
|
|
|
161
176
|
const { database, db } = await setupClient(this.uri);
|
|
162
177
|
try {
|
|
163
178
|
await PostgresMigrator.create(this.uri);
|
|
164
|
-
|
|
179
|
+
if (this.afterCreate) {
|
|
180
|
+
await this.afterCreate(this.uri);
|
|
181
|
+
}
|
|
165
182
|
await this.migrate();
|
|
166
183
|
logger.log(`Migrating database: ${database}`);
|
|
167
184
|
// Example: await db.query('CREATE TABLE example (id SERIAL PRIMARY KEY)');
|
|
@@ -577,6 +577,110 @@ describe('PostgresKyselyMigrator', () => {
|
|
|
577
577
|
});
|
|
578
578
|
});
|
|
579
579
|
|
|
580
|
+
describe('afterCreate hook', () => {
|
|
581
|
+
it('should call afterCreate before migrations run', async () => {
|
|
582
|
+
const hookDbName = `test_kysely_hook_${Date.now()}`;
|
|
583
|
+
const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${hookDbName}`;
|
|
584
|
+
const callOrder: string[] = [];
|
|
585
|
+
|
|
586
|
+
const db = new Kysely<TestSchema>({
|
|
587
|
+
dialect: new PostgresDialect({
|
|
588
|
+
pool: new Pool({
|
|
589
|
+
host: 'localhost',
|
|
590
|
+
port: 5432,
|
|
591
|
+
user: 'geekmidas',
|
|
592
|
+
password: 'geekmidas',
|
|
593
|
+
database: hookDbName,
|
|
594
|
+
}),
|
|
595
|
+
}),
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
const provider = new TestMigrationProvider();
|
|
599
|
+
provider.addMigration('001_create_table', {
|
|
600
|
+
up: async (db) => {
|
|
601
|
+
callOrder.push('migrate');
|
|
602
|
+
await db.schema
|
|
603
|
+
.createTable('items')
|
|
604
|
+
.addColumn('id', 'serial', (col) => col.primaryKey())
|
|
605
|
+
.execute();
|
|
606
|
+
},
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
const migrator = new PostgresKyselyMigrator({
|
|
610
|
+
uri,
|
|
611
|
+
db,
|
|
612
|
+
provider,
|
|
613
|
+
afterCreate: async (receivedUri) => {
|
|
614
|
+
callOrder.push('afterCreate');
|
|
615
|
+
expect(receivedUri).toBe(uri);
|
|
616
|
+
},
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
const cleanup = await migrator.start();
|
|
620
|
+
|
|
621
|
+
expect(callOrder).toEqual(['afterCreate', 'migrate']);
|
|
622
|
+
|
|
623
|
+
await cleanup();
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
it('should allow creating users and schemas before migrations', async () => {
|
|
627
|
+
const schemaDbName = `test_kysely_schema_hook_${Date.now()}`;
|
|
628
|
+
const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${schemaDbName}`;
|
|
629
|
+
|
|
630
|
+
const db = new Kysely<TestSchema>({
|
|
631
|
+
dialect: new PostgresDialect({
|
|
632
|
+
pool: new Pool({
|
|
633
|
+
host: 'localhost',
|
|
634
|
+
port: 5432,
|
|
635
|
+
user: 'geekmidas',
|
|
636
|
+
password: 'geekmidas',
|
|
637
|
+
database: schemaDbName,
|
|
638
|
+
}),
|
|
639
|
+
}),
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
const provider = new TestMigrationProvider();
|
|
643
|
+
provider.addMigration('001_use_schema', {
|
|
644
|
+
up: async (db) => {
|
|
645
|
+
// Verify schema exists (created by afterCreate)
|
|
646
|
+
const result =
|
|
647
|
+
await sql`SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'app'`.execute(
|
|
648
|
+
db,
|
|
649
|
+
);
|
|
650
|
+
if (result.rows.length === 0) {
|
|
651
|
+
throw new Error('Expected app schema to exist');
|
|
652
|
+
}
|
|
653
|
+
await db.schema
|
|
654
|
+
.createTable('items')
|
|
655
|
+
.addColumn('id', 'serial', (col) => col.primaryKey())
|
|
656
|
+
.execute();
|
|
657
|
+
},
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
const migrator = new PostgresKyselyMigrator({
|
|
661
|
+
uri,
|
|
662
|
+
db,
|
|
663
|
+
provider,
|
|
664
|
+
afterCreate: async () => {
|
|
665
|
+
const client = new Client({
|
|
666
|
+
host: 'localhost',
|
|
667
|
+
port: 5432,
|
|
668
|
+
user: 'geekmidas',
|
|
669
|
+
password: 'geekmidas',
|
|
670
|
+
database: schemaDbName,
|
|
671
|
+
});
|
|
672
|
+
await client.connect();
|
|
673
|
+
await client.query('CREATE SCHEMA IF NOT EXISTS app');
|
|
674
|
+
await client.end();
|
|
675
|
+
},
|
|
676
|
+
});
|
|
677
|
+
|
|
678
|
+
const cleanup = await migrator.start();
|
|
679
|
+
|
|
680
|
+
await cleanup();
|
|
681
|
+
});
|
|
682
|
+
});
|
|
683
|
+
|
|
580
684
|
describe('error scenarios', () => {
|
|
581
685
|
it('should handle provider errors', async () => {
|
|
582
686
|
const providerErrorDbName = `test_provider_error_${Date.now()}`;
|
|
@@ -18,6 +18,10 @@ class TestPostgresMigrator extends PostgresMigrator {
|
|
|
18
18
|
public migrateError?: Error;
|
|
19
19
|
public customMigrations: Array<() => Promise<void>> = [];
|
|
20
20
|
|
|
21
|
+
constructor(uri: string, afterCreate?: (uri: string) => Promise<void>) {
|
|
22
|
+
super(uri, afterCreate);
|
|
23
|
+
}
|
|
24
|
+
|
|
21
25
|
async migrate(): Promise<void> {
|
|
22
26
|
this.migrateCalled = true;
|
|
23
27
|
if (this.migrateError) {
|
|
@@ -285,6 +289,111 @@ describe('PostgresMigrator', () => {
|
|
|
285
289
|
});
|
|
286
290
|
});
|
|
287
291
|
|
|
292
|
+
describe('afterCreate hook', () => {
|
|
293
|
+
it('should call afterCreate after database creation and before migrate', async () => {
|
|
294
|
+
const hookDbName = `test_after_create_${Date.now()}`;
|
|
295
|
+
const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${hookDbName}`;
|
|
296
|
+
const callOrder: string[] = [];
|
|
297
|
+
|
|
298
|
+
const migrator = new TestPostgresMigrator(uri, async (receivedUri) => {
|
|
299
|
+
callOrder.push('afterCreate');
|
|
300
|
+
expect(receivedUri).toBe(uri);
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
migrator.addMigration(async () => {
|
|
304
|
+
callOrder.push('migrate');
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
const cleanup = await migrator.start();
|
|
308
|
+
|
|
309
|
+
expect(callOrder).toEqual(['afterCreate', 'migrate']);
|
|
310
|
+
|
|
311
|
+
await cleanup();
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
it('should skip afterCreate when not provided', async () => {
|
|
315
|
+
const noHookDbName = `test_no_hook_${Date.now()}`;
|
|
316
|
+
const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${noHookDbName}`;
|
|
317
|
+
const migrator = new TestPostgresMigrator(uri);
|
|
318
|
+
|
|
319
|
+
const cleanup = await migrator.start();
|
|
320
|
+
|
|
321
|
+
expect(migrator.migrateCalled).toBe(true);
|
|
322
|
+
|
|
323
|
+
await cleanup();
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it('should propagate afterCreate errors and not run migrate', async () => {
|
|
327
|
+
const errorHookDbName = `test_hook_error_${Date.now()}`;
|
|
328
|
+
const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${errorHookDbName}`;
|
|
329
|
+
|
|
330
|
+
const migrator = new TestPostgresMigrator(uri, async () => {
|
|
331
|
+
throw new Error('afterCreate failed');
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
await expect(migrator.start()).rejects.toThrow('afterCreate failed');
|
|
335
|
+
expect(migrator.migrateCalled).toBe(false);
|
|
336
|
+
|
|
337
|
+
// Cleanup the created database
|
|
338
|
+
const cleanupClient = new Client({
|
|
339
|
+
host: 'localhost',
|
|
340
|
+
port: 5432,
|
|
341
|
+
user: 'geekmidas',
|
|
342
|
+
password: 'geekmidas',
|
|
343
|
+
database: 'postgres',
|
|
344
|
+
});
|
|
345
|
+
try {
|
|
346
|
+
await cleanupClient.connect();
|
|
347
|
+
await cleanupClient.query(
|
|
348
|
+
`DROP DATABASE IF EXISTS "${errorHookDbName}"`,
|
|
349
|
+
);
|
|
350
|
+
} finally {
|
|
351
|
+
await cleanupClient.end();
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it('should allow afterCreate to set up database objects before migrations', async () => {
|
|
356
|
+
const setupDbName = `test_hook_setup_${Date.now()}`;
|
|
357
|
+
const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${setupDbName}`;
|
|
358
|
+
|
|
359
|
+
const migrator = new TestPostgresMigrator(uri, async () => {
|
|
360
|
+
const client = new Client({
|
|
361
|
+
host: 'localhost',
|
|
362
|
+
port: 5432,
|
|
363
|
+
user: 'geekmidas',
|
|
364
|
+
password: 'geekmidas',
|
|
365
|
+
database: setupDbName,
|
|
366
|
+
});
|
|
367
|
+
await client.connect();
|
|
368
|
+
await client.query(
|
|
369
|
+
"CREATE SCHEMA IF NOT EXISTS app; COMMENT ON SCHEMA app IS 'Created by afterCreate hook';",
|
|
370
|
+
);
|
|
371
|
+
await client.end();
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
migrator.addMigration(async () => {
|
|
375
|
+
// Verify schema exists during migration
|
|
376
|
+
const client = new Client({
|
|
377
|
+
host: 'localhost',
|
|
378
|
+
port: 5432,
|
|
379
|
+
user: 'geekmidas',
|
|
380
|
+
password: 'geekmidas',
|
|
381
|
+
database: setupDbName,
|
|
382
|
+
});
|
|
383
|
+
await client.connect();
|
|
384
|
+
const result = await client.query(
|
|
385
|
+
"SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'app'",
|
|
386
|
+
);
|
|
387
|
+
expect(result.rowCount).toBe(1);
|
|
388
|
+
await client.end();
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
const cleanup = await migrator.start();
|
|
392
|
+
|
|
393
|
+
await cleanup();
|
|
394
|
+
});
|
|
395
|
+
});
|
|
396
|
+
|
|
288
397
|
describe('abstract method', () => {
|
|
289
398
|
it('should require concrete implementation of migrate method', () => {
|
|
290
399
|
// TypeScript ensures abstract methods are implemented
|
|
@@ -92,6 +92,30 @@ EOSQL`;
|
|
|
92
92
|
expect(blocks[0]).toContain("CREATE USER api WITH PASSWORD ''");
|
|
93
93
|
});
|
|
94
94
|
|
|
95
|
+
it('should unescape bash-escaped dollar signs for PL/pgSQL blocks', () => {
|
|
96
|
+
const script = `psql <<-EOSQL
|
|
97
|
+
DO \\$\\$
|
|
98
|
+
BEGIN
|
|
99
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'api') THEN
|
|
100
|
+
CREATE USER api WITH PASSWORD '$API_DB_PASSWORD';
|
|
101
|
+
ELSE
|
|
102
|
+
ALTER USER api WITH PASSWORD '$API_DB_PASSWORD';
|
|
103
|
+
END IF;
|
|
104
|
+
END
|
|
105
|
+
\\$\\$;
|
|
106
|
+
EOSQL`;
|
|
107
|
+
|
|
108
|
+
const blocks = parseInitScript(script, {
|
|
109
|
+
API_DB_PASSWORD: 'secret',
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
expect(blocks).toHaveLength(1);
|
|
113
|
+
expect(blocks[0]).toContain('DO $$');
|
|
114
|
+
expect(blocks[0]).toContain('END\n $$;');
|
|
115
|
+
expect(blocks[0]).toContain("CREATE USER api WITH PASSWORD 'secret'");
|
|
116
|
+
expect(blocks[0]).not.toContain('\\$');
|
|
117
|
+
});
|
|
118
|
+
|
|
95
119
|
it('should return empty array for script with no heredocs', () => {
|
|
96
120
|
const script = `#!/bin/bash
|
|
97
121
|
echo "Hello world"
|
package/src/initScript.ts
CHANGED
|
@@ -54,6 +54,9 @@ function substituteEnvVars(sql: string, env: Record<string, string>): string {
|
|
|
54
54
|
let result = sql.replace(/\$\{(\w+)\}/g, (_, name) => env[name] ?? '');
|
|
55
55
|
// Replace $VAR_NAME syntax (word boundary after)
|
|
56
56
|
result = result.replace(/\$(\w+)/g, (_, name) => env[name] ?? '');
|
|
57
|
+
// Unescape bash-escaped dollar signs (\$ → $) AFTER variable substitution
|
|
58
|
+
// This handles PL/pgSQL dollar-quoting like DO \$\$ ... END \$\$;
|
|
59
|
+
result = result.replace(/\\\$/g, '$');
|
|
57
60
|
return result;
|
|
58
61
|
}
|
|
59
62
|
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresKyselyMigrator-B4pScubb.mjs","names":["options: {\n\t\t\turi: string;\n\t\t\tdb: Kysely<any>;\n\t\t\tprovider: MigrationProvider;\n\t\t}"],"sources":["../src/PostgresKyselyMigrator.ts"],"sourcesContent":["import { type Kysely, type MigrationProvider, Migrator } from 'kysely';\nimport { PostgresMigrator } from './PostgresMigrator';\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * PostgreSQL migrator implementation for Kysely ORM.\n * Extends PostgresMigrator to provide Kysely-specific migration functionality.\n * Automatically creates test databases and applies migrations for testing environments.\n *\n * @example\n * ```typescript\n * import { FileMigrationProvider } from 'kysely';\n * import { PostgresKyselyMigrator } from '@geekmidas/testkit';\n *\n * // Create migration provider\n * const provider = new FileMigrationProvider({\n * fs: require('fs'),\n * path: require('path'),\n * migrationFolder: path.join(__dirname, 'migrations')\n * });\n *\n * // Create Kysely instance\n * const db = new Kysely<Database>({\n * dialect: new PostgresDialect({\n * pool: new Pool({ connectionString: uri })\n * })\n * });\n *\n * // Create and use migrator\n * const migrator = new PostgresKyselyMigrator({\n * uri: 'postgresql://localhost:5432/test_db',\n * db,\n * provider\n * });\n *\n * const cleanup = await migrator.start();\n * // Run tests...\n * await cleanup();\n * ```\n */\nexport class PostgresKyselyMigrator extends PostgresMigrator {\n\t/**\n\t * Creates a new PostgresKyselyMigrator instance.\n\t *\n\t * @param options - Configuration options\n\t * @param options.uri - PostgreSQL connection URI\n\t * @param options.db - Kysely database instance\n\t * @param options.provider - Migration provider for locating migration files\n\t */\n\tconstructor(\n\t\tprivate options: {\n\t\t\turi: string;\n\t\t\tdb: Kysely<any>;\n\t\t\tprovider: MigrationProvider;\n\t\t},\n\t) {\n\t\tsuper(options.uri);\n\t}\n\n\t/**\n\t * Executes Kysely migrations to the latest version.\n\t * Implements the abstract migrate() method from PostgresMigrator.\n\t *\n\t * @throws Error if migrations fail to apply\n\t * @returns Promise that resolves when all migrations are applied\n\t */\n\tasync migrate(): Promise<void> {\n\t\tconst migrator = new Migrator({\n\t\t\tdb: this.options.db,\n\t\t\tprovider: this.options.provider,\n\t\t});\n\t\tconst migrations = await migrator.migrateToLatest();\n\n\t\tif (migrations.error) {\n\t\t\tlogger.error(migrations.error, `Failed to apply migrations`);\n\t\t\tthrow migrations.error;\n\t\t}\n\n\t\tawait this.options.db.destroy();\n\n\t\tlogger.log(`Applied ${migrations.results?.length} migrations successfully`);\n\t}\n}\n"],"mappings":";;;;;;;AAMA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCf,IAAa,yBAAb,cAA4C,iBAAiB;;;;;;;;;CAS5D,YACSA,SAKP;AACD,QAAM,QAAQ,IAAI;EANV;CAOR;;;;;;;;CASD,MAAM,UAAyB;EAC9B,MAAM,WAAW,IAAI,SAAS;GAC7B,IAAI,KAAK,QAAQ;GACjB,UAAU,KAAK,QAAQ;EACvB;EACD,MAAM,aAAa,MAAM,SAAS,iBAAiB;AAEnD,MAAI,WAAW,OAAO;AACrB,UAAO,MAAM,WAAW,QAAQ,4BAA4B;AAC5D,SAAM,WAAW;EACjB;AAED,QAAM,KAAK,QAAQ,GAAG,SAAS;AAE/B,SAAO,KAAK,UAAU,WAAW,SAAS,OAAO,0BAA0B;CAC3E;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresKyselyMigrator-C7ljZYvq.cjs","names":["PostgresMigrator","options: {\n\t\t\turi: string;\n\t\t\tdb: Kysely<any>;\n\t\t\tprovider: MigrationProvider;\n\t\t}","Migrator"],"sources":["../src/PostgresKyselyMigrator.ts"],"sourcesContent":["import { type Kysely, type MigrationProvider, Migrator } from 'kysely';\nimport { PostgresMigrator } from './PostgresMigrator';\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * PostgreSQL migrator implementation for Kysely ORM.\n * Extends PostgresMigrator to provide Kysely-specific migration functionality.\n * Automatically creates test databases and applies migrations for testing environments.\n *\n * @example\n * ```typescript\n * import { FileMigrationProvider } from 'kysely';\n * import { PostgresKyselyMigrator } from '@geekmidas/testkit';\n *\n * // Create migration provider\n * const provider = new FileMigrationProvider({\n * fs: require('fs'),\n * path: require('path'),\n * migrationFolder: path.join(__dirname, 'migrations')\n * });\n *\n * // Create Kysely instance\n * const db = new Kysely<Database>({\n * dialect: new PostgresDialect({\n * pool: new Pool({ connectionString: uri })\n * })\n * });\n *\n * // Create and use migrator\n * const migrator = new PostgresKyselyMigrator({\n * uri: 'postgresql://localhost:5432/test_db',\n * db,\n * provider\n * });\n *\n * const cleanup = await migrator.start();\n * // Run tests...\n * await cleanup();\n * ```\n */\nexport class PostgresKyselyMigrator extends PostgresMigrator {\n\t/**\n\t * Creates a new PostgresKyselyMigrator instance.\n\t *\n\t * @param options - Configuration options\n\t * @param options.uri - PostgreSQL connection URI\n\t * @param options.db - Kysely database instance\n\t * @param options.provider - Migration provider for locating migration files\n\t */\n\tconstructor(\n\t\tprivate options: {\n\t\t\turi: string;\n\t\t\tdb: Kysely<any>;\n\t\t\tprovider: MigrationProvider;\n\t\t},\n\t) {\n\t\tsuper(options.uri);\n\t}\n\n\t/**\n\t * Executes Kysely migrations to the latest version.\n\t * Implements the abstract migrate() method from PostgresMigrator.\n\t *\n\t * @throws Error if migrations fail to apply\n\t * @returns Promise that resolves when all migrations are applied\n\t */\n\tasync migrate(): Promise<void> {\n\t\tconst migrator = new Migrator({\n\t\t\tdb: this.options.db,\n\t\t\tprovider: this.options.provider,\n\t\t});\n\t\tconst migrations = await migrator.migrateToLatest();\n\n\t\tif (migrations.error) {\n\t\t\tlogger.error(migrations.error, `Failed to apply migrations`);\n\t\t\tthrow migrations.error;\n\t\t}\n\n\t\tawait this.options.db.destroy();\n\n\t\tlogger.log(`Applied ${migrations.results?.length} migrations successfully`);\n\t}\n}\n"],"mappings":";;;;;;;;AAMA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCf,IAAa,yBAAb,cAA4CA,0CAAiB;;;;;;;;;CAS5D,YACSC,SAKP;AACD,QAAM,QAAQ,IAAI;EANV;CAOR;;;;;;;;CASD,MAAM,UAAyB;EAC9B,MAAM,WAAW,IAAIC,gBAAS;GAC7B,IAAI,KAAK,QAAQ;GACjB,UAAU,KAAK,QAAQ;EACvB;EACD,MAAM,aAAa,MAAM,SAAS,iBAAiB;AAEnD,MAAI,WAAW,OAAO;AACrB,UAAO,MAAM,WAAW,QAAQ,4BAA4B;AAC5D,SAAM,WAAW;EACjB;AAED,QAAM,KAAK,QAAQ,GAAG,SAAS;AAE/B,SAAO,KAAK,UAAU,WAAW,SAAS,OAAO,0BAA0B;CAC3E;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresKyselyMigrator-CBltSOq5.d.cts","names":[],"sources":["../src/PostgresKyselyMigrator.ts"],"sourcesContent":[],"mappings":";;;;;;;AA4CA;;;;;;AAA4D;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAA/C,sBAAA,SAA+B,gBAAA;;;;;;;;;;;;QAYrC;cACM;;;;;;;;;aAaK"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresKyselyMigrator-DrVWncqd.d.mts","names":[],"sources":["../src/PostgresKyselyMigrator.ts"],"sourcesContent":[],"mappings":";;;;;;;AA4CA;;;;;;AAA4D;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAA/C,sBAAA,SAA+B,gBAAA;;;;;;;;;;;;QAYrC;cACM;;;;;;;;;aAaK"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresMigrator-Bres0U6E.d.cts","names":[],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":[],"mappings":";;AAiEA;;;;;AA8FY;;;;;;;;;;;;;;;;;;uBA9FU,gBAAA;;;;;;;;;;;;;;sBAcD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAgFT,cAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresMigrator-CHiBYEg_.cjs","names":["uri: string","error: any"],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":["import pg from 'pg';\n\nconst { Client } = pg;\n\n/**\n * Creates a PostgreSQL client connected to the 'postgres' database.\n * Extracts connection details from the provided URI.\n *\n * @param uri - PostgreSQL connection URI\n * @returns Object containing the target database name and client instance\n *\n * @example\n * ```typescript\n * const { database, db } = await setupClient('postgresql://user:pass@localhost:5432/mydb');\n * // database = 'mydb'\n * // db = Client instance connected to 'postgres' database\n * ```\n */\nasync function setupClient(uri: string) {\n\tconst url = new URL(uri);\n\n\tconst db = new Client({\n\t\tuser: url.username,\n\t\tpassword: url.password,\n\t\thost: url.hostname,\n\t\tport: parseInt(url.port, 10),\n\t\tdatabase: 'postgres',\n\t});\n\n\tlet database = url.pathname.slice(1);\n\tif (database.includes('?')) {\n\t\tdatabase = database.substring(0, database.indexOf('?'));\n\t}\n\treturn { database, db };\n}\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * Abstract base class for PostgreSQL database migration utilities.\n * Provides database creation, migration, and cleanup functionality for testing.\n * Subclasses must implement the migrate() method to define migration logic.\n *\n * @example\n * ```typescript\n * class MyMigrator extends PostgresMigrator {\n * async migrate(): Promise<void> {\n * // Run your migrations here\n * await this.runMigrations();\n * }\n * }\n *\n * // Use in tests\n * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n * const cleanup = await migrator.start();\n *\n * // Run tests...\n *\n * // Clean up\n * await cleanup();\n * ```\n */\nexport abstract class PostgresMigrator {\n\t/**\n\t * Creates a new PostgresMigrator instance.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t */\n\tconstructor(private uri: string) {}\n\n\t/**\n\t * Abstract method to be implemented by subclasses.\n\t * Should contain the migration logic for setting up database schema.\n\t *\n\t * @returns Promise that resolves when migrations are complete\n\t */\n\tabstract migrate(): Promise<void>;\n\n\t/**\n\t * Creates a PostgreSQL database if it doesn't already exist.\n\t * Connects to the 'postgres' database to check and create the target database.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @returns Object indicating whether the database already existed\n\t * @private\n\t */\n\tprivate static async create(\n\t\turi: string,\n\t): Promise<{ alreadyExisted: boolean }> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT * FROM pg_catalog.pg_database WHERE datname = '${database}'`,\n\t\t\t);\n\n\t\t\tif (result.rowCount === 0) {\n\t\t\t\ttry {\n\t\t\t\t\tawait db.query(`CREATE DATABASE \"${database}\"`);\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\t// 42P04 = duplicate_database — another process created it between our check and create\n\t\t\t\t\tif (error?.code === '42P04') {\n\t\t\t\t\t\treturn { alreadyExisted: true };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\talreadyExisted: result.rowCount ? result.rowCount > 0 : false,\n\t\t\t};\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Drops a PostgreSQL database.\n\t * Used for cleanup after tests are complete.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @throws Error if database cannot be dropped\n\t * @private\n\t */\n\tprivate static async drop(uri: string): Promise<void> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tawait db.query(`DROP DATABASE \"${database}\"`);\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Starts the migration process by creating the database and running migrations.\n\t * Returns a cleanup function that will drop the database when called.\n\t *\n\t * @returns Async cleanup function that drops the created database\n\t *\n\t * @example\n\t * ```typescript\n\t * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n\t *\n\t * // Start migrations and get cleanup function\n\t * const cleanup = await migrator.start();\n\t *\n\t * try {\n\t * // Run your tests here\n\t * await runTests();\n\t * } finally {\n\t * // Always clean up\n\t * await cleanup();\n\t * }\n\t * ```\n\t */\n\tasync start() {\n\t\tconst { database, db } = await setupClient(this.uri);\n\t\ttry {\n\t\t\tawait PostgresMigrator.create(this.uri);\n\t\t\t// Implement migration logic here\n\t\t\tawait this.migrate();\n\t\t\tlogger.log(`Migrating database: ${database}`);\n\t\t\t// Example: await db.query('CREATE TABLE example (id SERIAL PRIMARY KEY)');\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\n\t\treturn async () => {\n\t\t\tawait PostgresMigrator.drop(this.uri);\n\t\t};\n\t}\n}\n"],"mappings":";;;;AAEA,MAAM,EAAE,QAAQ,GAAG;;;;;;;;;;;;;;;AAgBnB,eAAe,YAAYA,KAAa;CACvC,MAAM,MAAM,IAAI,IAAI;CAEpB,MAAM,KAAK,IAAI,OAAO;EACrB,MAAM,IAAI;EACV,UAAU,IAAI;EACd,MAAM,IAAI;EACV,MAAM,SAAS,IAAI,MAAM,GAAG;EAC5B,UAAU;CACV;CAED,IAAI,WAAW,IAAI,SAAS,MAAM,EAAE;AACpC,KAAI,SAAS,SAAS,IAAI,CACzB,YAAW,SAAS,UAAU,GAAG,SAAS,QAAQ,IAAI,CAAC;AAExD,QAAO;EAAE;EAAU;CAAI;AACvB;;;;AAKD,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;AA0Bf,IAAsB,mBAAtB,MAAsB,iBAAiB;;;;;;CAMtC,YAAoBA,KAAa;EAAb;CAAe;;;;;;;;;CAkBnC,aAAqB,OACpBA,KACuC;EACvC,MAAM,EAAE,UAAU,IAAI,GAAG,MAAM,YAAY,IAAI;AAC/C,MAAI;AACH,SAAM,GAAG,SAAS;GAClB,MAAM,SAAS,MAAM,GAAG,OACtB,wDAAwD,SAAS,GAClE;AAED,OAAI,OAAO,aAAa,EACvB,KAAI;AACH,UAAM,GAAG,OAAO,mBAAmB,SAAS,GAAG;GAC/C,SAAQC,OAAY;AAEpB,QAAI,OAAO,SAAS,QACnB,QAAO,EAAE,gBAAgB,KAAM;AAEhC,UAAM;GACN;AAGF,UAAO,EACN,gBAAgB,OAAO,WAAW,OAAO,WAAW,IAAI,MACxD;EACD,UAAS;AACT,SAAM,GAAG,KAAK;EACd;CACD;;;;;;;;;CAUD,aAAqB,KAAKD,KAA4B;EACrD,MAAM,EAAE,UAAU,IAAI,GAAG,MAAM,YAAY,IAAI;AAC/C,MAAI;AACH,SAAM,GAAG,SAAS;AAClB,SAAM,GAAG,OAAO,iBAAiB,SAAS,GAAG;EAC7C,UAAS;AACT,SAAM,GAAG,KAAK;EACd;CACD;;;;;;;;;;;;;;;;;;;;;;;CAwBD,MAAM,QAAQ;EACb,MAAM,EAAE,UAAU,IAAI,GAAG,MAAM,YAAY,KAAK,IAAI;AACpD,MAAI;AACH,SAAM,iBAAiB,OAAO,KAAK,IAAI;AAEvC,SAAM,KAAK,SAAS;AACpB,UAAO,KAAK,sBAAsB,SAAS,EAAE;EAE7C,UAAS;AACT,SAAM,GAAG,KAAK;EACd;AAED,SAAO,YAAY;AAClB,SAAM,iBAAiB,KAAK,KAAK,IAAI;EACrC;CACD;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresMigrator-DcP1o-T6.mjs","names":["uri: string","error: any"],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":["import pg from 'pg';\n\nconst { Client } = pg;\n\n/**\n * Creates a PostgreSQL client connected to the 'postgres' database.\n * Extracts connection details from the provided URI.\n *\n * @param uri - PostgreSQL connection URI\n * @returns Object containing the target database name and client instance\n *\n * @example\n * ```typescript\n * const { database, db } = await setupClient('postgresql://user:pass@localhost:5432/mydb');\n * // database = 'mydb'\n * // db = Client instance connected to 'postgres' database\n * ```\n */\nasync function setupClient(uri: string) {\n\tconst url = new URL(uri);\n\n\tconst db = new Client({\n\t\tuser: url.username,\n\t\tpassword: url.password,\n\t\thost: url.hostname,\n\t\tport: parseInt(url.port, 10),\n\t\tdatabase: 'postgres',\n\t});\n\n\tlet database = url.pathname.slice(1);\n\tif (database.includes('?')) {\n\t\tdatabase = database.substring(0, database.indexOf('?'));\n\t}\n\treturn { database, db };\n}\n\n/**\n * Default logger instance for migration operations.\n */\nconst logger = console;\n\n/**\n * Abstract base class for PostgreSQL database migration utilities.\n * Provides database creation, migration, and cleanup functionality for testing.\n * Subclasses must implement the migrate() method to define migration logic.\n *\n * @example\n * ```typescript\n * class MyMigrator extends PostgresMigrator {\n * async migrate(): Promise<void> {\n * // Run your migrations here\n * await this.runMigrations();\n * }\n * }\n *\n * // Use in tests\n * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n * const cleanup = await migrator.start();\n *\n * // Run tests...\n *\n * // Clean up\n * await cleanup();\n * ```\n */\nexport abstract class PostgresMigrator {\n\t/**\n\t * Creates a new PostgresMigrator instance.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t */\n\tconstructor(private uri: string) {}\n\n\t/**\n\t * Abstract method to be implemented by subclasses.\n\t * Should contain the migration logic for setting up database schema.\n\t *\n\t * @returns Promise that resolves when migrations are complete\n\t */\n\tabstract migrate(): Promise<void>;\n\n\t/**\n\t * Creates a PostgreSQL database if it doesn't already exist.\n\t * Connects to the 'postgres' database to check and create the target database.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @returns Object indicating whether the database already existed\n\t * @private\n\t */\n\tprivate static async create(\n\t\turi: string,\n\t): Promise<{ alreadyExisted: boolean }> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tconst result = await db.query(\n\t\t\t\t`SELECT * FROM pg_catalog.pg_database WHERE datname = '${database}'`,\n\t\t\t);\n\n\t\t\tif (result.rowCount === 0) {\n\t\t\t\ttry {\n\t\t\t\t\tawait db.query(`CREATE DATABASE \"${database}\"`);\n\t\t\t\t} catch (error: any) {\n\t\t\t\t\t// 42P04 = duplicate_database — another process created it between our check and create\n\t\t\t\t\tif (error?.code === '42P04') {\n\t\t\t\t\t\treturn { alreadyExisted: true };\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\talreadyExisted: result.rowCount ? result.rowCount > 0 : false,\n\t\t\t};\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Drops a PostgreSQL database.\n\t * Used for cleanup after tests are complete.\n\t *\n\t * @param uri - PostgreSQL connection URI\n\t * @throws Error if database cannot be dropped\n\t * @private\n\t */\n\tprivate static async drop(uri: string): Promise<void> {\n\t\tconst { database, db } = await setupClient(uri);\n\t\ttry {\n\t\t\tawait db.connect();\n\t\t\tawait db.query(`DROP DATABASE \"${database}\"`);\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\t}\n\n\t/**\n\t * Starts the migration process by creating the database and running migrations.\n\t * Returns a cleanup function that will drop the database when called.\n\t *\n\t * @returns Async cleanup function that drops the created database\n\t *\n\t * @example\n\t * ```typescript\n\t * const migrator = new MyMigrator('postgresql://localhost:5432/test_db');\n\t *\n\t * // Start migrations and get cleanup function\n\t * const cleanup = await migrator.start();\n\t *\n\t * try {\n\t * // Run your tests here\n\t * await runTests();\n\t * } finally {\n\t * // Always clean up\n\t * await cleanup();\n\t * }\n\t * ```\n\t */\n\tasync start() {\n\t\tconst { database, db } = await setupClient(this.uri);\n\t\ttry {\n\t\t\tawait PostgresMigrator.create(this.uri);\n\t\t\t// Implement migration logic here\n\t\t\tawait this.migrate();\n\t\t\tlogger.log(`Migrating database: ${database}`);\n\t\t\t// Example: await db.query('CREATE TABLE example (id SERIAL PRIMARY KEY)');\n\t\t} finally {\n\t\t\tawait db.end();\n\t\t}\n\n\t\treturn async () => {\n\t\t\tawait PostgresMigrator.drop(this.uri);\n\t\t};\n\t}\n}\n"],"mappings":";;;AAEA,MAAM,EAAE,QAAQ,GAAG;;;;;;;;;;;;;;;AAgBnB,eAAe,YAAYA,KAAa;CACvC,MAAM,MAAM,IAAI,IAAI;CAEpB,MAAM,KAAK,IAAI,OAAO;EACrB,MAAM,IAAI;EACV,UAAU,IAAI;EACd,MAAM,IAAI;EACV,MAAM,SAAS,IAAI,MAAM,GAAG;EAC5B,UAAU;CACV;CAED,IAAI,WAAW,IAAI,SAAS,MAAM,EAAE;AACpC,KAAI,SAAS,SAAS,IAAI,CACzB,YAAW,SAAS,UAAU,GAAG,SAAS,QAAQ,IAAI,CAAC;AAExD,QAAO;EAAE;EAAU;CAAI;AACvB;;;;AAKD,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;AA0Bf,IAAsB,mBAAtB,MAAsB,iBAAiB;;;;;;CAMtC,YAAoBA,KAAa;EAAb;CAAe;;;;;;;;;CAkBnC,aAAqB,OACpBA,KACuC;EACvC,MAAM,EAAE,UAAU,IAAI,GAAG,MAAM,YAAY,IAAI;AAC/C,MAAI;AACH,SAAM,GAAG,SAAS;GAClB,MAAM,SAAS,MAAM,GAAG,OACtB,wDAAwD,SAAS,GAClE;AAED,OAAI,OAAO,aAAa,EACvB,KAAI;AACH,UAAM,GAAG,OAAO,mBAAmB,SAAS,GAAG;GAC/C,SAAQC,OAAY;AAEpB,QAAI,OAAO,SAAS,QACnB,QAAO,EAAE,gBAAgB,KAAM;AAEhC,UAAM;GACN;AAGF,UAAO,EACN,gBAAgB,OAAO,WAAW,OAAO,WAAW,IAAI,MACxD;EACD,UAAS;AACT,SAAM,GAAG,KAAK;EACd;CACD;;;;;;;;;CAUD,aAAqB,KAAKD,KAA4B;EACrD,MAAM,EAAE,UAAU,IAAI,GAAG,MAAM,YAAY,IAAI;AAC/C,MAAI;AACH,SAAM,GAAG,SAAS;AAClB,SAAM,GAAG,OAAO,iBAAiB,SAAS,GAAG;EAC7C,UAAS;AACT,SAAM,GAAG,KAAK;EACd;CACD;;;;;;;;;;;;;;;;;;;;;;;CAwBD,MAAM,QAAQ;EACb,MAAM,EAAE,UAAU,IAAI,GAAG,MAAM,YAAY,KAAK,IAAI;AACpD,MAAI;AACH,SAAM,iBAAiB,OAAO,KAAK,IAAI;AAEvC,SAAM,KAAK,SAAS;AACpB,UAAO,KAAK,sBAAsB,SAAS,EAAE;EAE7C,UAAS;AACT,SAAM,GAAG,KAAK;EACd;AAED,SAAO,YAAY;AAClB,SAAM,iBAAiB,KAAK,KAAK,IAAI;EACrC;CACD;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PostgresMigrator-S-YYosAC.d.mts","names":[],"sources":["../src/PostgresMigrator.ts"],"sourcesContent":[],"mappings":";;AAiEA;;;;;AA8FY;;;;;;;;;;;;;;;;;;uBA9FU,gBAAA;;;;;;;;;;;;;;sBAcD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;WAgFT,cAAA"}
|