@geekmidas/testkit 9.0.2 → 10.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/{Factory-CUM2767q.d.cts → Factory-C6W78ulZ.d.mts} +2 -2
  2. package/dist/{Factory-ClyZLRsO.d.mts.map → Factory-C6W78ulZ.d.mts.map} +1 -1
  3. package/dist/{Factory-ClyZLRsO.d.mts → Factory-DSEADOaF.d.cts} +2 -2
  4. package/dist/{Factory-CUM2767q.d.cts.map → Factory-DSEADOaF.d.cts.map} +1 -1
  5. package/dist/Factory.d.cts +2 -2
  6. package/dist/Factory.d.mts +2 -2
  7. package/dist/{KyselyFactory-OMwcuAX_.d.cts → KyselyFactory-Cc2UmOJk.d.mts} +3 -3
  8. package/dist/{KyselyFactory-CTZmiGI9.d.mts.map → KyselyFactory-Cc2UmOJk.d.mts.map} +1 -1
  9. package/dist/{KyselyFactory-CTZmiGI9.d.mts → KyselyFactory-DzH0N1zr.d.cts} +3 -3
  10. package/dist/{KyselyFactory-OMwcuAX_.d.cts.map → KyselyFactory-DzH0N1zr.d.cts.map} +1 -1
  11. package/dist/KyselyFactory.d.cts +3 -3
  12. package/dist/KyselyFactory.d.mts +3 -3
  13. package/dist/{ObjectionFactory-DDrKwAoO.d.mts → ObjectionFactory-BYnPr9ZP.d.mts} +3 -3
  14. package/dist/{ObjectionFactory-DDrKwAoO.d.mts.map → ObjectionFactory-BYnPr9ZP.d.mts.map} +1 -1
  15. package/dist/{ObjectionFactory-DvmZVHhe.d.cts → ObjectionFactory-BmKdG0nT.d.cts} +3 -3
  16. package/dist/{ObjectionFactory-DvmZVHhe.d.cts.map → ObjectionFactory-BmKdG0nT.d.cts.map} +1 -1
  17. package/dist/ObjectionFactory.d.cts +3 -3
  18. package/dist/ObjectionFactory.d.mts +3 -3
  19. package/dist/{VitestKyselyTransactionIsolator-CfSMOFlN.mjs → VitestKyselyTransactionIsolator-1Saieke7.mjs} +10 -3
  20. package/dist/VitestKyselyTransactionIsolator-1Saieke7.mjs.map +1 -0
  21. package/dist/{VitestKyselyTransactionIsolator-0CqOsuc9.cjs → VitestKyselyTransactionIsolator-BjJSXryR.cjs} +10 -3
  22. package/dist/VitestKyselyTransactionIsolator-BjJSXryR.cjs.map +1 -0
  23. package/dist/{VitestKyselyTransactionIsolator-CduJlHoT.d.cts → VitestKyselyTransactionIsolator-CwlTo6yf.d.mts} +8 -3
  24. package/dist/VitestKyselyTransactionIsolator-CwlTo6yf.d.mts.map +1 -0
  25. package/dist/{VitestKyselyTransactionIsolator-Cswnnj0k.d.mts → VitestKyselyTransactionIsolator-DJasVuIZ.d.cts} +8 -3
  26. package/dist/VitestKyselyTransactionIsolator-DJasVuIZ.d.cts.map +1 -0
  27. package/dist/VitestKyselyTransactionIsolator.cjs +2 -2
  28. package/dist/VitestKyselyTransactionIsolator.d.cts +2 -2
  29. package/dist/VitestKyselyTransactionIsolator.d.mts +2 -2
  30. package/dist/VitestKyselyTransactionIsolator.mjs +2 -2
  31. package/dist/{VitestObjectionTransactionIsolator-CNo40EdC.mjs → VitestObjectionTransactionIsolator-B_VSWFum.mjs} +2 -2
  32. package/dist/{VitestObjectionTransactionIsolator-CNo40EdC.mjs.map → VitestObjectionTransactionIsolator-B_VSWFum.mjs.map} +1 -1
  33. package/dist/{VitestObjectionTransactionIsolator-BXoR6xdG.d.cts → VitestObjectionTransactionIsolator-CTTjvTPO.d.cts} +2 -2
  34. package/dist/{VitestObjectionTransactionIsolator-BXoR6xdG.d.cts.map → VitestObjectionTransactionIsolator-CTTjvTPO.d.cts.map} +1 -1
  35. package/dist/{VitestObjectionTransactionIsolator-x6hY5j4u.d.mts → VitestObjectionTransactionIsolator-CyZG6nq4.d.mts} +2 -2
  36. package/dist/{VitestObjectionTransactionIsolator-x6hY5j4u.d.mts.map → VitestObjectionTransactionIsolator-CyZG6nq4.d.mts.map} +1 -1
  37. package/dist/{VitestObjectionTransactionIsolator-B5J9jjKq.cjs → VitestObjectionTransactionIsolator-DDoJTu7e.cjs} +2 -2
  38. package/dist/{VitestObjectionTransactionIsolator-B5J9jjKq.cjs.map → VitestObjectionTransactionIsolator-DDoJTu7e.cjs.map} +1 -1
  39. package/dist/VitestObjectionTransactionIsolator.cjs +2 -2
  40. package/dist/VitestObjectionTransactionIsolator.d.cts +2 -2
  41. package/dist/VitestObjectionTransactionIsolator.d.mts +2 -2
  42. package/dist/VitestObjectionTransactionIsolator.mjs +2 -2
  43. package/dist/{VitestTransactionIsolator-BNWJqh9f.d.mts → VitestTransactionIsolator-BLaw80cx.d.mts} +20 -4
  44. package/dist/VitestTransactionIsolator-BLaw80cx.d.mts.map +1 -0
  45. package/dist/{VitestTransactionIsolator-D6ZxLWys.mjs → VitestTransactionIsolator-CvwPecpl.mjs} +17 -4
  46. package/dist/VitestTransactionIsolator-CvwPecpl.mjs.map +1 -0
  47. package/dist/{VitestTransactionIsolator-CtZaOUjH.cjs → VitestTransactionIsolator-DyiX-QtK.cjs} +17 -4
  48. package/dist/VitestTransactionIsolator-DyiX-QtK.cjs.map +1 -0
  49. package/dist/{VitestTransactionIsolator-CSroc7Df.d.cts → VitestTransactionIsolator-glcxyS_R.d.cts} +20 -4
  50. package/dist/VitestTransactionIsolator-glcxyS_R.d.cts.map +1 -0
  51. package/dist/VitestTransactionIsolator.cjs +1 -1
  52. package/dist/VitestTransactionIsolator.d.cts +2 -2
  53. package/dist/VitestTransactionIsolator.d.mts +2 -2
  54. package/dist/VitestTransactionIsolator.mjs +1 -1
  55. package/dist/better-auth.d.cts +2 -2
  56. package/dist/better-auth.d.mts +2 -2
  57. package/dist/{faker-BcjUfHxx.d.mts → faker-D9gz7KjY.d.mts} +3 -3
  58. package/dist/{faker-BcjUfHxx.d.mts.map → faker-D9gz7KjY.d.mts.map} +1 -1
  59. package/dist/{faker-zVCm31nU.d.cts → faker-km9UhOS6.d.cts} +3 -3
  60. package/dist/{faker-zVCm31nU.d.cts.map → faker-km9UhOS6.d.cts.map} +1 -1
  61. package/dist/faker.d.cts +1 -1
  62. package/dist/faker.d.mts +1 -1
  63. package/dist/kysely.cjs +2 -2
  64. package/dist/kysely.d.cts +5 -5
  65. package/dist/kysely.d.mts +5 -5
  66. package/dist/kysely.mjs +2 -2
  67. package/dist/objection.cjs +2 -2
  68. package/dist/objection.d.cts +5 -5
  69. package/dist/objection.d.mts +5 -5
  70. package/dist/objection.mjs +2 -2
  71. package/dist/requestContext.cjs +1 -1
  72. package/dist/requestContext.d.cts +1 -1
  73. package/dist/requestContext.d.mts +1 -1
  74. package/dist/requestContext.mjs +1 -1
  75. package/package.json +10 -7
  76. package/CHANGELOG.md +0 -151
  77. package/dist/VitestKyselyTransactionIsolator-0CqOsuc9.cjs.map +0 -1
  78. package/dist/VitestKyselyTransactionIsolator-CduJlHoT.d.cts.map +0 -1
  79. package/dist/VitestKyselyTransactionIsolator-CfSMOFlN.mjs.map +0 -1
  80. package/dist/VitestKyselyTransactionIsolator-Cswnnj0k.d.mts.map +0 -1
  81. package/dist/VitestTransactionIsolator-BNWJqh9f.d.mts.map +0 -1
  82. package/dist/VitestTransactionIsolator-CSroc7Df.d.cts.map +0 -1
  83. package/dist/VitestTransactionIsolator-CtZaOUjH.cjs.map +0 -1
  84. package/dist/VitestTransactionIsolator-D6ZxLWys.mjs.map +0 -1
  85. package/src/Factory.ts +0 -174
  86. package/src/KyselyFactory.ts +0 -391
  87. package/src/ObjectionFactory.ts +0 -412
  88. package/src/PostgresKyselyMigrator.ts +0 -104
  89. package/src/PostgresMigrator.ts +0 -193
  90. package/src/PostgresObjectionMigrator.ts +0 -138
  91. package/src/VitestKyselyTransactionIsolator.ts +0 -72
  92. package/src/VitestObjectionTransactionIsolator.ts +0 -75
  93. package/src/VitestTransactionIsolator.ts +0 -348
  94. package/src/__tests__/Factory.spec.ts +0 -178
  95. package/src/__tests__/KyselyFactory.spec.ts +0 -458
  96. package/src/__tests__/ObjectionFactory.spec.ts +0 -586
  97. package/src/__tests__/PostgresKyselyMigrator.spec.ts +0 -794
  98. package/src/__tests__/PostgresMigrator.spec.ts +0 -471
  99. package/src/__tests__/PostgresObjectionMigrator.spec.ts +0 -634
  100. package/src/__tests__/VitestObjectionTransactionIsolator.spec.ts +0 -138
  101. package/src/__tests__/benchmark.spec.ts +0 -140
  102. package/src/__tests__/better-auth.spec.ts +0 -21
  103. package/src/__tests__/faker.spec.ts +0 -231
  104. package/src/__tests__/initScript.spec.ts +0 -332
  105. package/src/__tests__/integration.spec.ts +0 -610
  106. package/src/__tests__/requestContext.spec.ts +0 -113
  107. package/src/__tests__/utilities.spec.ts +0 -211
  108. package/src/aws.ts +0 -131
  109. package/src/benchmark.ts +0 -48
  110. package/src/better-auth.ts +0 -310
  111. package/src/faker.ts +0 -349
  112. package/src/helpers.ts +0 -45
  113. package/src/initScript.ts +0 -122
  114. package/src/kysely.ts +0 -166
  115. package/src/logger.ts +0 -18
  116. package/src/objection.ts +0 -157
  117. package/src/os/directory.ts +0 -26
  118. package/src/os/index.ts +0 -1
  119. package/src/requestContext.ts +0 -119
  120. package/src/timer.ts +0 -3
  121. package/test/globalSetup.ts +0 -54
  122. package/test/helpers.ts +0 -268
  123. package/test/migrations/1749664623372_user.ts +0 -22
  124. package/tsconfig.json +0 -9
  125. package/vitest.config.ts +0 -8
@@ -1,794 +0,0 @@
1
- import { Kysely, type MigrationProvider, PostgresDialect, sql } from 'kysely';
2
- import { Client, Pool } from 'pg';
3
- import {
4
- afterAll,
5
- afterEach,
6
- beforeAll,
7
- beforeEach,
8
- describe,
9
- expect,
10
- it,
11
- vi,
12
- } from 'vitest';
13
- import { createTestDatabase } from '../../test/helpers';
14
- import { PostgresKyselyMigrator } from '../PostgresKyselyMigrator';
15
- import { PostgresMigrator } from '../PostgresMigrator';
16
-
17
- // Test database schema
18
- interface TestSchema {
19
- users: {
20
- id: number;
21
- name: string;
22
- email: string;
23
- created_at: Date;
24
- };
25
- posts: {
26
- id: number;
27
- title: string;
28
- content: string;
29
- user_id: number;
30
- created_at: Date;
31
- };
32
- }
33
-
34
- // Test migration provider
35
- class TestMigrationProvider implements MigrationProvider {
36
- private migrations: Record<string, any> = {};
37
- private shouldError = false;
38
-
39
- addMigration(
40
- name: string,
41
- migration: {
42
- up: (db: Kysely<any>) => Promise<void>;
43
- down?: (db: Kysely<any>) => Promise<void>;
44
- },
45
- ) {
46
- this.migrations[name] = migration;
47
- }
48
-
49
- setError(shouldError: boolean) {
50
- this.shouldError = shouldError;
51
- }
52
-
53
- async getMigrations() {
54
- if (this.shouldError) {
55
- throw new Error('Failed to load migrations');
56
- }
57
- return this.migrations;
58
- }
59
- }
60
-
61
- describe('PostgresKyselyMigrator', () => {
62
- let testDbName: string;
63
- let cleanupDb: () => Promise<void>;
64
- let consoleSpy: any;
65
- let consoleErrorSpy: any;
66
-
67
- beforeAll(async () => {
68
- // Create a unique test database for each test run
69
- testDbName = `test_kysely_migrator_${Date.now()}`;
70
- cleanupDb = await createTestDatabase(testDbName);
71
- });
72
-
73
- beforeEach(() => {
74
- consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
75
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
76
- });
77
-
78
- afterEach(() => {
79
- consoleSpy.mockRestore();
80
- consoleErrorSpy.mockRestore();
81
- });
82
-
83
- afterAll(async () => {
84
- await cleanupDb();
85
- });
86
-
87
- describe('constructor', () => {
88
- it('should create a PostgresKyselyMigrator instance', () => {
89
- const db = new Kysely<TestSchema>({
90
- dialect: new PostgresDialect({
91
- pool: new Pool({
92
- host: 'localhost',
93
- port: 5432,
94
- user: 'geekmidas',
95
- password: 'geekmidas',
96
- database: testDbName,
97
- }),
98
- }),
99
- });
100
-
101
- const provider = new TestMigrationProvider();
102
- const migrator = new PostgresKyselyMigrator({
103
- uri: `postgresql://geekmidas:geekmidas@localhost:5432/${testDbName}`,
104
- db,
105
- provider,
106
- });
107
-
108
- expect(migrator).toBeInstanceOf(PostgresKyselyMigrator);
109
- expect(migrator).toBeInstanceOf(PostgresMigrator);
110
- });
111
- });
112
-
113
- describe('migrate method', () => {
114
- it('should apply migrations successfully', async () => {
115
- const newDbName = `test_migrate_${Date.now()}`;
116
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${newDbName}`;
117
-
118
- const db = new Kysely<TestSchema>({
119
- dialect: new PostgresDialect({
120
- pool: new Pool({
121
- host: 'localhost',
122
- port: 5432,
123
- user: 'geekmidas',
124
- password: 'geekmidas',
125
- database: newDbName,
126
- }),
127
- }),
128
- });
129
-
130
- const provider = new TestMigrationProvider();
131
-
132
- // Add test migrations
133
- provider.addMigration('001_create_users', {
134
- up: async (db) => {
135
- await db.schema
136
- .createTable('users')
137
- .addColumn('id', 'serial', (col) => col.primaryKey())
138
- .addColumn('name', 'varchar', (col) => col.notNull())
139
- .addColumn('email', 'varchar', (col) => col.notNull().unique())
140
- .addColumn('created_at', 'timestamp', (col) =>
141
- col.defaultTo(sql`now()`).notNull(),
142
- )
143
- .execute();
144
- },
145
- down: async (db) => {
146
- await db.schema.dropTable('users').execute();
147
- },
148
- });
149
-
150
- provider.addMigration('002_create_posts', {
151
- up: async (db) => {
152
- await db.schema
153
- .createTable('posts')
154
- .addColumn('id', 'serial', (col) => col.primaryKey())
155
- .addColumn('title', 'varchar', (col) => col.notNull())
156
- .addColumn('content', 'text', (col) => col.notNull())
157
- .addColumn('user_id', 'integer', (col) =>
158
- col.notNull().references('users.id').onDelete('cascade'),
159
- )
160
- .addColumn('created_at', 'timestamp', (col) =>
161
- col.defaultTo(sql`now()`).notNull(),
162
- )
163
- .execute();
164
- },
165
- down: async (db) => {
166
- await db.schema.dropTable('posts').execute();
167
- },
168
- });
169
-
170
- const migrator = new PostgresKyselyMigrator({
171
- uri,
172
- db,
173
- provider,
174
- });
175
-
176
- // Start the migrator (creates database and runs migrations)
177
- const cleanup = await migrator.start();
178
-
179
- expect(consoleSpy).toHaveBeenCalledWith(
180
- expect.stringContaining('Applied 2 migrations successfully'),
181
- );
182
-
183
- // Verify tables were created
184
- const client = new Client({
185
- host: 'localhost',
186
- port: 5432,
187
- user: 'geekmidas',
188
- password: 'geekmidas',
189
- database: newDbName,
190
- });
191
-
192
- try {
193
- await client.connect();
194
- const tablesResult = await client.query(`
195
- SELECT table_name FROM information_schema.tables
196
- WHERE table_schema = 'public'
197
- AND table_name IN ('users', 'posts')
198
- ORDER BY table_name
199
- `);
200
-
201
- expect(tablesResult.rowCount).toBe(2);
202
- expect(tablesResult.rows).toEqual([
203
- { table_name: 'posts' },
204
- { table_name: 'users' },
205
- ]);
206
- } finally {
207
- await client.end();
208
- }
209
-
210
- // Cleanup
211
- await cleanup();
212
- });
213
-
214
- it('should handle migration errors', async () => {
215
- const errorDbName = `test_migrate_error_${Date.now()}`;
216
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${errorDbName}`;
217
-
218
- const db = new Kysely<TestSchema>({
219
- dialect: new PostgresDialect({
220
- pool: new Pool({
221
- host: 'localhost',
222
- port: 5432,
223
- user: 'geekmidas',
224
- password: 'geekmidas',
225
- database: errorDbName,
226
- }),
227
- }),
228
- });
229
-
230
- const provider = new TestMigrationProvider();
231
-
232
- // Add a migration that will fail
233
- provider.addMigration('001_failing_migration', {
234
- up: async () => {
235
- throw new Error('Migration failed intentionally');
236
- },
237
- });
238
-
239
- const migrator = new PostgresKyselyMigrator({
240
- uri,
241
- db,
242
- provider,
243
- });
244
-
245
- // Expect the start method to throw
246
- await expect(migrator.start()).rejects.toThrow(
247
- 'Migration failed intentionally',
248
- );
249
-
250
- expect(consoleErrorSpy).toHaveBeenCalledWith(
251
- expect.any(Error),
252
- 'Failed to apply migrations',
253
- );
254
-
255
- // Ensure db is closed before cleanup
256
- await db.destroy();
257
-
258
- // Cleanup the created database
259
- const cleanupClient = new Client({
260
- host: 'localhost',
261
- port: 5432,
262
- user: 'geekmidas',
263
- password: 'geekmidas',
264
- database: 'postgres',
265
- });
266
- try {
267
- await cleanupClient.connect();
268
- // Force disconnect any existing connections
269
- await cleanupClient.query(`
270
- SELECT pg_terminate_backend(pg_stat_activity.pid)
271
- FROM pg_stat_activity
272
- WHERE pg_stat_activity.datname = '${errorDbName}'
273
- AND pid <> pg_backend_pid()
274
- `);
275
- await cleanupClient.query(`DROP DATABASE IF EXISTS "${errorDbName}"`);
276
- } finally {
277
- await cleanupClient.end();
278
- }
279
- });
280
-
281
- it('should destroy database connection after migrations', async () => {
282
- const destroyDbName = `test_destroy_${Date.now()}`;
283
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${destroyDbName}`;
284
-
285
- const db = new Kysely<TestSchema>({
286
- dialect: new PostgresDialect({
287
- pool: new Pool({
288
- host: 'localhost',
289
- port: 5432,
290
- user: 'geekmidas',
291
- password: 'geekmidas',
292
- database: destroyDbName,
293
- }),
294
- }),
295
- });
296
-
297
- const destroySpy = vi.spyOn(db, 'destroy');
298
- const provider = new TestMigrationProvider();
299
-
300
- provider.addMigration('001_simple', {
301
- up: async (db) => {
302
- await db.schema
303
- .createTable('test')
304
- .addColumn('id', 'serial', (col) => col.primaryKey())
305
- .execute();
306
- },
307
- });
308
-
309
- const migrator = new PostgresKyselyMigrator({
310
- uri,
311
- db,
312
- provider,
313
- });
314
-
315
- const cleanup = await migrator.start();
316
-
317
- // Verify destroy was called after migrations
318
- expect(destroySpy).toHaveBeenCalled();
319
-
320
- // Cleanup
321
- await cleanup();
322
- });
323
- });
324
-
325
- describe('integration with PostgresMigrator', () => {
326
- it('should work with complete workflow', async () => {
327
- const integrationDbName = `test_integration_${Date.now()}`;
328
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${integrationDbName}`;
329
-
330
- const db = new Kysely<TestSchema>({
331
- dialect: new PostgresDialect({
332
- pool: new Pool({
333
- host: 'localhost',
334
- port: 5432,
335
- user: 'geekmidas',
336
- password: 'geekmidas',
337
- database: integrationDbName,
338
- }),
339
- }),
340
- });
341
-
342
- const provider = new TestMigrationProvider();
343
-
344
- // Add comprehensive migrations
345
- provider.addMigration('001_initial_schema', {
346
- up: async (db) => {
347
- // Users table
348
- await db.schema
349
- .createTable('users')
350
- .addColumn('id', 'serial', (col) => col.primaryKey())
351
- .addColumn('name', 'varchar', (col) => col.notNull())
352
- .addColumn('email', 'varchar', (col) => col.notNull().unique())
353
- .addColumn('created_at', 'timestamp', (col) =>
354
- col.defaultTo(sql`now()`).notNull(),
355
- )
356
- .execute();
357
-
358
- // Posts table
359
- await db.schema
360
- .createTable('posts')
361
- .addColumn('id', 'serial', (col) => col.primaryKey())
362
- .addColumn('title', 'varchar', (col) => col.notNull())
363
- .addColumn('content', 'text', (col) => col.notNull())
364
- .addColumn('user_id', 'integer', (col) =>
365
- col.notNull().references('users.id').onDelete('cascade'),
366
- )
367
- .addColumn('created_at', 'timestamp', (col) =>
368
- col.defaultTo(sql`now()`).notNull(),
369
- )
370
- .execute();
371
-
372
- // Add index
373
- await db.schema
374
- .createIndex('idx_posts_user_id')
375
- .on('posts')
376
- .column('user_id')
377
- .execute();
378
- },
379
- });
380
-
381
- provider.addMigration('002_add_updated_at', {
382
- up: async (db) => {
383
- await db.schema
384
- .alterTable('users')
385
- .addColumn('updated_at', 'timestamp', (col) =>
386
- col.defaultTo(sql`now()`).notNull(),
387
- )
388
- .execute();
389
-
390
- await db.schema
391
- .alterTable('posts')
392
- .addColumn('updated_at', 'timestamp', (col) =>
393
- col.defaultTo(sql`now()`).notNull(),
394
- )
395
- .execute();
396
- },
397
- });
398
-
399
- const migrator = new PostgresKyselyMigrator({
400
- uri,
401
- db,
402
- provider,
403
- });
404
-
405
- const cleanup = await migrator.start();
406
-
407
- expect(consoleSpy).toHaveBeenCalledWith(
408
- `Migrating database: ${integrationDbName}`,
409
- );
410
- expect(consoleSpy).toHaveBeenCalledWith(
411
- 'Applied 2 migrations successfully',
412
- );
413
-
414
- // Verify final schema
415
- const verifyClient = new Client({
416
- host: 'localhost',
417
- port: 5432,
418
- user: 'geekmidas',
419
- password: 'geekmidas',
420
- database: integrationDbName,
421
- });
422
-
423
- try {
424
- await verifyClient.connect();
425
-
426
- // Check columns exist
427
- const columnsResult = await verifyClient.query(`
428
- SELECT table_name, column_name
429
- FROM information_schema.columns
430
- WHERE table_schema = 'public'
431
- AND table_name IN ('users', 'posts')
432
- AND column_name = 'updated_at'
433
- ORDER BY table_name
434
- `);
435
-
436
- expect(columnsResult.rowCount).toBe(2);
437
-
438
- // Check index exists
439
- const indexResult = await verifyClient.query(`
440
- SELECT indexname FROM pg_indexes
441
- WHERE schemaname = 'public'
442
- AND indexname = 'idx_posts_user_id'
443
- `);
444
-
445
- expect(indexResult.rowCount).toBe(1);
446
- } finally {
447
- await verifyClient.end();
448
- }
449
-
450
- // Cleanup
451
- await cleanup();
452
- });
453
-
454
- it('should handle empty migrations', async () => {
455
- const emptyDbName = `test_empty_${Date.now()}`;
456
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${emptyDbName}`;
457
-
458
- const db = new Kysely<TestSchema>({
459
- dialect: new PostgresDialect({
460
- pool: new Pool({
461
- host: 'localhost',
462
- port: 5432,
463
- user: 'geekmidas',
464
- password: 'geekmidas',
465
- database: emptyDbName,
466
- }),
467
- }),
468
- });
469
-
470
- const provider = new TestMigrationProvider();
471
- // No migrations added
472
-
473
- const migrator = new PostgresKyselyMigrator({
474
- uri,
475
- db,
476
- provider,
477
- });
478
-
479
- const cleanup = await migrator.start();
480
-
481
- expect(consoleSpy).toHaveBeenCalledWith(
482
- 'Applied 0 migrations successfully',
483
- );
484
-
485
- await cleanup();
486
- });
487
-
488
- it('should work with FileMigrationProvider pattern', async () => {
489
- const fileProviderDbName = `test_file_provider_${Date.now()}`;
490
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${fileProviderDbName}`;
491
-
492
- const db = new Kysely<TestSchema>({
493
- dialect: new PostgresDialect({
494
- pool: new Pool({
495
- host: 'localhost',
496
- port: 5432,
497
- user: 'geekmidas',
498
- password: 'geekmidas',
499
- database: fileProviderDbName,
500
- }),
501
- }),
502
- });
503
-
504
- // Simulate a file-based migration provider
505
- const migrations = {
506
- '2024_01_01_000001_create_users': {
507
- up: async (db: Kysely<any>) => {
508
- await db.schema
509
- .createTable('users')
510
- .addColumn('id', 'serial', (col) => col.primaryKey())
511
- .addColumn('username', 'varchar', (col) => col.notNull().unique())
512
- .execute();
513
- },
514
- down: async (db: Kysely<any>) => {
515
- await db.schema.dropTable('users').execute();
516
- },
517
- },
518
- '2024_01_02_000001_create_sessions': {
519
- up: async (db: Kysely<any>) => {
520
- await db.schema
521
- .createTable('sessions')
522
- .addColumn('id', 'serial', (col) => col.primaryKey())
523
- .addColumn('user_id', 'integer', (col) =>
524
- col.notNull().references('users.id'),
525
- )
526
- .addColumn('token', 'varchar', (col) => col.notNull())
527
- .execute();
528
- },
529
- down: async (db: Kysely<any>) => {
530
- await db.schema.dropTable('sessions').execute();
531
- },
532
- },
533
- };
534
-
535
- const provider: MigrationProvider = {
536
- async getMigrations() {
537
- return migrations;
538
- },
539
- };
540
-
541
- const migrator = new PostgresKyselyMigrator({
542
- uri,
543
- db,
544
- provider,
545
- });
546
-
547
- const cleanup = await migrator.start();
548
-
549
- expect(consoleSpy).toHaveBeenCalledWith(
550
- 'Applied 2 migrations successfully',
551
- );
552
-
553
- // Verify both tables exist
554
- const verifyClient = new Client({
555
- host: 'localhost',
556
- port: 5432,
557
- user: 'geekmidas',
558
- password: 'geekmidas',
559
- database: fileProviderDbName,
560
- });
561
-
562
- try {
563
- await verifyClient.connect();
564
- const tablesResult = await verifyClient.query(`
565
- SELECT table_name FROM information_schema.tables
566
- WHERE table_schema = 'public'
567
- AND table_name IN ('users', 'sessions')
568
- ORDER BY table_name
569
- `);
570
-
571
- expect(tablesResult.rowCount).toBe(2);
572
- } finally {
573
- await verifyClient.end();
574
- }
575
-
576
- await cleanup();
577
- });
578
- });
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
-
684
- describe('error scenarios', () => {
685
- it('should handle provider errors', async () => {
686
- const providerErrorDbName = `test_provider_error_${Date.now()}`;
687
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${providerErrorDbName}`;
688
-
689
- const db = new Kysely<TestSchema>({
690
- dialect: new PostgresDialect({
691
- pool: new Pool({
692
- host: 'localhost',
693
- port: 5432,
694
- user: 'geekmidas',
695
- password: 'geekmidas',
696
- database: providerErrorDbName,
697
- }),
698
- }),
699
- });
700
-
701
- const provider = new TestMigrationProvider();
702
- provider.setError(true);
703
-
704
- const migrator = new PostgresKyselyMigrator({
705
- uri,
706
- db,
707
- provider,
708
- });
709
-
710
- await expect(migrator.start()).rejects.toThrow(
711
- 'Failed to load migrations',
712
- );
713
-
714
- // Ensure db is closed
715
- await db.destroy();
716
-
717
- // Cleanup
718
- const cleanupClient = new Client({
719
- host: 'localhost',
720
- port: 5432,
721
- user: 'geekmidas',
722
- password: 'geekmidas',
723
- database: 'postgres',
724
- });
725
- try {
726
- await cleanupClient.connect();
727
- await cleanupClient.query(
728
- `DROP DATABASE IF EXISTS "${providerErrorDbName}"`,
729
- );
730
- } finally {
731
- await cleanupClient.end();
732
- }
733
- }, 10000);
734
-
735
- it('should handle invalid SQL in migrations', async () => {
736
- const invalidSqlDbName = `test_invalid_sql_${Date.now()}`;
737
- const uri = `postgresql://geekmidas:geekmidas@localhost:5432/${invalidSqlDbName}`;
738
-
739
- const db = new Kysely<TestSchema>({
740
- dialect: new PostgresDialect({
741
- pool: new Pool({
742
- host: 'localhost',
743
- port: 5432,
744
- user: 'geekmidas',
745
- password: 'geekmidas',
746
- database: invalidSqlDbName,
747
- }),
748
- }),
749
- });
750
-
751
- const provider = new TestMigrationProvider();
752
- provider.addMigration('001_invalid_sql', {
753
- up: async (db) => {
754
- // Try to reference non-existent table
755
- await db.schema
756
- .createTable('posts')
757
- .addColumn('id', 'serial', (col) => col.primaryKey())
758
- .addColumn('user_id', 'integer', (col) =>
759
- col.notNull().references('non_existent_table.id'),
760
- )
761
- .execute();
762
- },
763
- });
764
-
765
- const migrator = new PostgresKyselyMigrator({
766
- uri,
767
- db,
768
- provider,
769
- });
770
-
771
- await expect(migrator.start()).rejects.toThrow();
772
-
773
- // Ensure db is closed
774
- await db.destroy();
775
-
776
- // Cleanup
777
- const cleanupClient = new Client({
778
- host: 'localhost',
779
- port: 5432,
780
- user: 'geekmidas',
781
- password: 'geekmidas',
782
- database: 'postgres',
783
- });
784
- try {
785
- await cleanupClient.connect();
786
- await cleanupClient.query(
787
- `DROP DATABASE IF EXISTS "${invalidSqlDbName}"`,
788
- );
789
- } finally {
790
- await cleanupClient.end();
791
- }
792
- }, 10000);
793
- });
794
- });