@contember/database-migrations 2.2.0-alpha.17 → 2.2.0-alpha.19

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 (44) hide show
  1. package/dist/development/index.cjs +3 -1
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +3 -1
  4. package/dist/development/index.js.map +1 -1
  5. package/dist/development/src/Migration.cjs.map +1 -1
  6. package/dist/development/src/Migration.js.map +1 -1
  7. package/dist/development/src/MigrationBuilder.cjs +267 -0
  8. package/dist/development/src/MigrationBuilder.cjs.map +1 -0
  9. package/dist/development/src/MigrationBuilder.js +267 -0
  10. package/dist/development/src/MigrationBuilder.js.map +1 -0
  11. package/dist/development/src/helpers.cjs +3 -16
  12. package/dist/development/src/helpers.cjs.map +1 -1
  13. package/dist/development/src/helpers.js +3 -15
  14. package/dist/development/src/helpers.js.map +1 -1
  15. package/dist/production/index.cjs +3 -1
  16. package/dist/production/index.cjs.map +1 -1
  17. package/dist/production/index.js +3 -1
  18. package/dist/production/index.js.map +1 -1
  19. package/dist/production/src/Migration.cjs.map +1 -1
  20. package/dist/production/src/Migration.js.map +1 -1
  21. package/dist/production/src/MigrationBuilder.cjs +267 -0
  22. package/dist/production/src/MigrationBuilder.cjs.map +1 -0
  23. package/dist/production/src/MigrationBuilder.js +267 -0
  24. package/dist/production/src/MigrationBuilder.js.map +1 -0
  25. package/dist/production/src/helpers.cjs +3 -16
  26. package/dist/production/src/helpers.cjs.map +1 -1
  27. package/dist/production/src/helpers.js +3 -15
  28. package/dist/production/src/helpers.js.map +1 -1
  29. package/dist/types/Migration.d.ts +1 -1
  30. package/dist/types/Migration.d.ts.map +1 -1
  31. package/dist/types/MigrationBuilder.d.ts +90 -0
  32. package/dist/types/MigrationBuilder.d.ts.map +1 -0
  33. package/dist/types/helpers.d.ts +3 -6
  34. package/dist/types/helpers.d.ts.map +1 -1
  35. package/dist/types/index.d.ts +2 -1
  36. package/dist/types/index.d.ts.map +1 -1
  37. package/dist/types/tsconfig.tsbuildinfo +1 -1
  38. package/package.json +2 -3
  39. package/readme.md +1 -1
  40. package/src/Migration.ts +1 -1
  41. package/src/MigrationBuilder.ts +379 -0
  42. package/src/helpers.ts +4 -17
  43. package/src/index.ts +2 -1
  44. package/tests/cases/unit/migrationBuilder.test.ts +439 -0
@@ -0,0 +1,439 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { createMigrationBuilder, escapeValue, MigrationBuilder } from '../../../src/index.js'
3
+
4
+ // Engine and content migrations are recorded by name or by their JSON modifications, never by SQL, and their SQL is
5
+ // generated when they run. These pin the exact SQL of every builder helper the engine uses, in its main shapes, so a
6
+ // builder upgrade cannot change what a not-yet-run migration executes on an existing database.
7
+ const lines = (...parts: string[]): string => parts.join('\n')
8
+
9
+ const sqlOf = (build: (builder: MigrationBuilder) => void): string[] => {
10
+ const builder = createMigrationBuilder()
11
+ build(builder)
12
+ return builder.getSqlSteps()
13
+ }
14
+
15
+ describe('migration builder SQL', () => {
16
+ test('sql passes the statement through', () => {
17
+ expect(sqlOf(b => b.sql('SELECT 1'))).toEqual([
18
+ 'SELECT 1;',
19
+ ])
20
+ })
21
+
22
+ test('getSql joins the steps', () => {
23
+ const builder = createMigrationBuilder()
24
+ builder.sql('SELECT 1')
25
+ builder.sql('SELECT 2')
26
+ expect(builder.getSql()).toEqual(lines(
27
+ 'SELECT 1;',
28
+ 'SELECT 2;',
29
+ '',
30
+ ))
31
+ })
32
+
33
+ test('createTable with a primary key', () => {
34
+ expect(sqlOf(b => b.createTable('article', { id: { primaryKey: true, type: 'uuid', notNull: true } }))).toEqual([
35
+ lines(
36
+ 'CREATE TABLE "article" (',
37
+ ' "id" uuid PRIMARY KEY NOT NULL',
38
+ ');',
39
+ ),
40
+ ])
41
+ })
42
+
43
+ test('createTable with references', () => {
44
+ expect(sqlOf(b =>
45
+ b.createTable('article_tags', {
46
+ article_id: { type: 'uuid', notNull: true, references: '"article"("id")', onDelete: 'CASCADE' },
47
+ tag_id: { type: 'uuid', notNull: true, references: '"tag"("id")', onDelete: 'CASCADE' },
48
+ })
49
+ )).toEqual([
50
+ lines(
51
+ 'CREATE TABLE "article_tags" (',
52
+ ' "article_id" uuid NOT NULL REFERENCES "article"("id") ON DELETE CASCADE,',
53
+ ' "tag_id" uuid NOT NULL REFERENCES "tag"("id") ON DELETE CASCADE',
54
+ ');',
55
+ ),
56
+ ])
57
+ })
58
+
59
+ test('createTable with unique columns and a default', () => {
60
+ expect(sqlOf(b =>
61
+ b.createTable({ name: 'schema_migration' }, {
62
+ id: { notNull: true, type: 'SERIAL4' },
63
+ version: { notNull: true, type: 'varchar(20)', unique: true },
64
+ migration: { notNull: true, type: 'json' },
65
+ executed_at: { notNull: true, type: 'timestamp', default: 'now()' },
66
+ })
67
+ )).toEqual([
68
+ lines(
69
+ 'CREATE TABLE "schema_migration" (',
70
+ ' "id" SERIAL4 NOT NULL,',
71
+ ' "version" varchar(20) UNIQUE NOT NULL,',
72
+ ' "migration" json NOT NULL,',
73
+ ' "executed_at" timestamp DEFAULT $pga$now()$pga$ NOT NULL',
74
+ ');',
75
+ ),
76
+ ])
77
+ })
78
+
79
+ test('createTable in a schema', () => {
80
+ expect(sqlOf(b => b.createTable({ schema: 'system', name: 'stage' }, { id: { primaryKey: true, type: 'uuid' } }))).toEqual([
81
+ lines(
82
+ 'CREATE TABLE "system"."stage" (',
83
+ ' "id" uuid PRIMARY KEY',
84
+ ');',
85
+ ),
86
+ ])
87
+ })
88
+
89
+ test('identity columns', () => {
90
+ expect(sqlOf(b => {
91
+ b.createTable('counter', { id: { primaryKey: true, type: 'integer', notNull: true, sequenceGenerated: { precedence: 'BY DEFAULT', start: 10 } } })
92
+ b.addColumn('counter', { position: { type: 'integer', notNull: true, sequenceGenerated: { precedence: 'ALWAYS' } } })
93
+ b.alterColumn('counter', 'position', { notNull: true, sequenceGenerated: { precedence: 'BY DEFAULT', start: 1 } })
94
+ b.alterColumn('counter', 'position', { sequenceGenerated: false })
95
+ })).toEqual([
96
+ lines(
97
+ 'CREATE TABLE "counter" (',
98
+ ' "id" integer PRIMARY KEY NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 10)',
99
+ ');',
100
+ ),
101
+ lines(
102
+ 'ALTER TABLE "counter"',
103
+ ' ADD "position" integer NOT NULL GENERATED ALWAYS AS IDENTITY;',
104
+ ),
105
+ lines(
106
+ 'ALTER TABLE "counter"',
107
+ ' ALTER "position" SET NOT NULL,',
108
+ ' ALTER "position" ADD GENERATED BY DEFAULT AS IDENTITY (START WITH 1);',
109
+ ),
110
+ lines(
111
+ 'ALTER TABLE "counter"',
112
+ ' ALTER "position" DROP IDENTITY;',
113
+ ),
114
+ ])
115
+ })
116
+
117
+ test('addColumn with a collation', () => {
118
+ expect(sqlOf(b => b.addColumn('article', { title: { type: 'text', notNull: false, collation: '"und-x-icu"' } }))).toEqual([
119
+ lines(
120
+ 'ALTER TABLE "article"',
121
+ ' ADD "title" text COLLATE "und-x-icu";',
122
+ ),
123
+ ])
124
+ })
125
+
126
+ test('addColumn', () => {
127
+ expect(sqlOf(b => {
128
+ b.addColumn('article', { title: { type: 'text', notNull: false } })
129
+ b.addColumn('task', { status: { type: '"TaskStatus"', notNull: true } })
130
+ })).toEqual([
131
+ lines(
132
+ 'ALTER TABLE "article"',
133
+ ' ADD "title" text;',
134
+ ),
135
+ lines(
136
+ 'ALTER TABLE "task"',
137
+ ' ADD "status" "TaskStatus" NOT NULL;',
138
+ ),
139
+ ])
140
+ })
141
+
142
+ test('alterColumn', () => {
143
+ expect(sqlOf(b => {
144
+ b.alterColumn('article', 'locked', { notNull: true })
145
+ b.alterColumn('article', 'title', { notNull: false })
146
+ b.alterColumn('article', 'locked', { type: 'boolean', using: 'false' })
147
+ b.alterColumn('note', 'created_at', { notNull: true, type: 'timestamptz', using: '$pga$now$pga$' })
148
+ b.alterColumn('article', 'title', { collation: '"und-x-icu"', type: 'text' })
149
+ })).toEqual([
150
+ lines(
151
+ 'ALTER TABLE "article"',
152
+ ' ALTER "locked" SET NOT NULL;',
153
+ ),
154
+ lines(
155
+ 'ALTER TABLE "article"',
156
+ ' ALTER "title" DROP NOT NULL;',
157
+ ),
158
+ lines(
159
+ 'ALTER TABLE "article"',
160
+ ' ALTER "locked" SET DATA TYPE boolean USING false;',
161
+ ),
162
+ lines(
163
+ 'ALTER TABLE "note"',
164
+ ' ALTER "created_at" SET DATA TYPE timestamptz USING $pga$now$pga$,',
165
+ ' ALTER "created_at" SET NOT NULL;',
166
+ ),
167
+ lines(
168
+ 'ALTER TABLE "article"',
169
+ ' ALTER "title" SET DATA TYPE text COLLATE "und-x-icu";',
170
+ ),
171
+ ])
172
+ })
173
+
174
+ test('renameColumn, dropColumn, renameTable and dropTable', () => {
175
+ expect(sqlOf(b => {
176
+ b.renameColumn('article', 'title', 'headline')
177
+ b.dropColumn('file', 'duration')
178
+ b.renameTable('article', 'post')
179
+ b.dropTable('legacy')
180
+ })).toEqual([
181
+ 'ALTER TABLE "article" RENAME "title" TO "headline";',
182
+ lines(
183
+ 'ALTER TABLE "file"',
184
+ ' DROP "duration";',
185
+ ),
186
+ 'ALTER TABLE "article" RENAME TO "post";',
187
+ 'DROP TABLE "legacy";',
188
+ ])
189
+ })
190
+
191
+ test('createDomain, renameDomain and dropDomain', () => {
192
+ expect(sqlOf(b => {
193
+ b.createDomain('TaskStatus', 'text', { check: `VALUE IN('todo','done')`, constraintName: 'taskstatus_check' })
194
+ b.renameDomain('TaskStatus', 'TaskStatus__old')
195
+ b.dropDomain('TaskStatus__old')
196
+ })).toEqual([
197
+ 'CREATE DOMAIN "TaskStatus" AS text CONSTRAINT "taskstatus_check" CHECK (VALUE IN(\'todo\',\'done\'));',
198
+ 'ALTER DOMAIN "TaskStatus" RENAME TO "TaskStatus__old";',
199
+ 'DROP DOMAIN "TaskStatus__old";',
200
+ ])
201
+ })
202
+
203
+ test('views and materialized views', () => {
204
+ expect(sqlOf(b => {
205
+ b.createView('author', {}, `SELECT null as id, 'John' AS name`)
206
+ b.createView('author', { replace: true }, `SELECT null as id, 'Jack' AS name`)
207
+ b.renameView('author', 'writer')
208
+ b.dropView('writer')
209
+ b.createMaterializedView('mat_author', { data: true }, `SELECT null as id, 'Jack' AS name`)
210
+ b.dropMaterializedView('mat_author')
211
+ })).toEqual([
212
+ 'CREATE VIEW "author" AS SELECT null as id, \'John\' AS name;',
213
+ 'CREATE OR REPLACE VIEW "author" AS SELECT null as id, \'Jack\' AS name;',
214
+ 'ALTER VIEW "author" RENAME TO "writer";',
215
+ 'DROP VIEW "writer";',
216
+ 'CREATE MATERIALIZED VIEW "mat_author" AS SELECT null as id, \'Jack\' AS name WITH DATA;',
217
+ 'DROP MATERIALIZED VIEW "mat_author";',
218
+ ])
219
+ })
220
+
221
+ test('createTrigger, dropTrigger and dropFunction', () => {
222
+ expect(sqlOf(b => {
223
+ b.createTrigger('article', 'log_event', {
224
+ when: 'AFTER',
225
+ operation: ['INSERT', 'UPDATE', 'DELETE'],
226
+ level: 'ROW',
227
+ function: { schema: 'system', name: 'trigger_event' },
228
+ functionParams: ['id'],
229
+ })
230
+ b.createTrigger('article', 'log_event_trx', {
231
+ when: 'AFTER',
232
+ operation: ['INSERT', 'UPDATE', 'DELETE'],
233
+ level: 'ROW',
234
+ constraint: true,
235
+ deferrable: true,
236
+ deferred: true,
237
+ function: { schema: 'system', name: 'trigger_event_commit' },
238
+ })
239
+ b.dropTrigger({ schema: 'stage_live', name: 'article' }, 'log_event')
240
+ b.dropTrigger({ schema: 'stage_live', name: 'article_tags' }, 'log_event_trx', { ifExists: true })
241
+ b.dropFunction({ name: 'make_diff' }, [{ name: 'old', type: 'jsonb' }, { name: 'new', type: 'jsonb' }])
242
+ })).toEqual([
243
+ lines(
244
+ 'CREATE TRIGGER "log_event"',
245
+ ' AFTER INSERT OR UPDATE OR DELETE ON "article"',
246
+ ' FOR EACH ROW',
247
+ ' EXECUTE PROCEDURE "system"."trigger_event"($pga$id$pga$);',
248
+ ),
249
+ lines(
250
+ 'CREATE CONSTRAINT TRIGGER "log_event_trx"',
251
+ ' AFTER INSERT OR UPDATE OR DELETE ON "article"',
252
+ ' DEFERRABLE INITIALLY DEFERRED',
253
+ ' FOR EACH ROW',
254
+ ' EXECUTE PROCEDURE "system"."trigger_event_commit"();',
255
+ ),
256
+ 'DROP TRIGGER "log_event" ON "stage_live"."article";',
257
+ 'DROP TRIGGER IF EXISTS "log_event_trx" ON "stage_live"."article_tags";',
258
+ 'DROP FUNCTION "make_diff"("old" jsonb, "new" jsonb);',
259
+ ])
260
+ })
261
+
262
+ test('createIndex', () => {
263
+ expect(sqlOf(b => b.createIndex({ name: 'schema_migration' }, ['version'], { name: 'system_schema_migration_version' }))).toEqual([
264
+ 'CREATE INDEX "system_schema_migration_version" ON "schema_migration" ("version");',
265
+ ])
266
+ })
267
+
268
+ test('dropConstraint and an unnamed primary key constraint', () => {
269
+ expect(sqlOf(b => {
270
+ b.dropConstraint({ schema: 'stage_live', name: 'article_tags' }, 'article_tags_uniq_article_id_tag_id')
271
+ b.addConstraint({ schema: 'stage_live', name: 'article_tags' }, null, { primaryKey: ['article_id', 'tag_id'] })
272
+ })).toEqual([
273
+ 'ALTER TABLE "stage_live"."article_tags" DROP CONSTRAINT "article_tags_uniq_article_id_tag_id";',
274
+ lines(
275
+ 'ALTER TABLE "stage_live"."article_tags"',
276
+ ' ADD CONSTRAINT "article_tags_pkey" PRIMARY KEY ("article_id", "tag_id");',
277
+ ),
278
+ ])
279
+ })
280
+ })
281
+
282
+ describe('migration builder edge cases', () => {
283
+ test('sql does not double a trailing semicolon', () => {
284
+ expect(sqlOf(b => {
285
+ b.sql('SELECT 1;')
286
+ b.sql('SELECT 1; ')
287
+ })).toEqual([
288
+ 'SELECT 1;',
289
+ 'SELECT 1; ;',
290
+ ])
291
+ })
292
+
293
+ test('alterColumn without actions records an empty step', () => {
294
+ expect(sqlOf(b => {
295
+ b.alterColumn('article', 'title', {})
296
+ b.sql('SELECT 1')
297
+ })).toEqual([
298
+ '',
299
+ 'SELECT 1;',
300
+ ])
301
+ })
302
+
303
+ test('line formatting collapses newlines inside a clause', () => {
304
+ expect(sqlOf(b => b.alterColumn('article', 'title', { type: 'text', using: '$pga$a\nb$pga$' }))).toEqual([
305
+ lines(
306
+ 'ALTER TABLE "article"',
307
+ ' ALTER "title" SET DATA TYPE text USING $pga$a b$pga$;',
308
+ ),
309
+ ])
310
+ })
311
+
312
+ test('type aliases and the id shorthand', () => {
313
+ expect(sqlOf(b => {
314
+ b.createTable('t', {
315
+ id: { type: 'id' },
316
+ a: { type: 'int' },
317
+ b: { type: 'string' },
318
+ c: { type: 'float' },
319
+ d: { type: 'double' },
320
+ e: { type: 'datetime' },
321
+ f: { type: 'bool' },
322
+ })
323
+ b.alterColumn('t', 'a', { type: 'int' })
324
+ })).toEqual([
325
+ lines(
326
+ 'CREATE TABLE "t" (',
327
+ ' "id" serial PRIMARY KEY,',
328
+ ' "a" integer,',
329
+ ' "b" text,',
330
+ ' "c" real,',
331
+ ' "d" double precision,',
332
+ ' "e" timestamp,',
333
+ ' "f" boolean',
334
+ ');',
335
+ ),
336
+ lines(
337
+ 'ALTER TABLE "t"',
338
+ ' ALTER "a" SET DATA TYPE integer;',
339
+ ),
340
+ ])
341
+ })
342
+
343
+ test('every identity sequence option', () => {
344
+ expect(sqlOf(b =>
345
+ b.addColumn('t', {
346
+ id: {
347
+ type: 'integer',
348
+ notNull: true,
349
+ sequenceGenerated: {
350
+ precedence: 'ALWAYS',
351
+ type: 'int',
352
+ increment: 2,
353
+ minvalue: null,
354
+ maxvalue: 99,
355
+ start: 5,
356
+ cache: 3,
357
+ cycle: false,
358
+ owner: null,
359
+ },
360
+ },
361
+ })
362
+ )).toEqual([
363
+ lines(
364
+ 'ALTER TABLE "t"',
365
+ ' ADD "id" integer NOT NULL GENERATED ALWAYS AS IDENTITY (AS integer INCREMENT BY 2 NO MINVALUE MAXVALUE 99 START WITH 5 CACHE 3 NO CYCLE OWNED BY NONE);',
366
+ ),
367
+ ])
368
+ })
369
+
370
+ test('an empty index name or domain check falls back like node-pg-migrate', () => {
371
+ expect(sqlOf(b => {
372
+ b.createIndex({ schema: 's', name: 't' }, ['a', 'b'], { name: '' })
373
+ b.createDomain('d', 'text', { check: '', constraintName: 'c' })
374
+ })).toEqual([
375
+ 'CREATE INDEX "t_a_b_index" ON "s"."t" ("a", "b");',
376
+ 'CREATE DOMAIN "d" AS text;',
377
+ ])
378
+ })
379
+
380
+ test('createTrigger rejects a missing function before a missing operation', () => {
381
+ expect(() => sqlOf(b => b.createTrigger('t', 'tr', { when: 'AFTER', operation: [], function: '' }))).toThrow("Can't determine function name")
382
+ expect(() => sqlOf(b => b.createTrigger('t', 'tr', { when: 'AFTER', operation: [], function: 'f' }))).toThrow(
383
+ '"operation" (INSERT/UPDATE[ OF ...]/DELETE/TRUNCATE) have to be specified',
384
+ )
385
+ })
386
+
387
+ test('getSqlSteps returns a snapshot', () => {
388
+ const builder = createMigrationBuilder()
389
+ builder.sql('SELECT 1')
390
+ const steps = builder.getSqlSteps()
391
+ builder.sql('SELECT 2')
392
+ expect(steps).toEqual(['SELECT 1;'])
393
+ })
394
+ })
395
+
396
+ describe('escapeValue', () => {
397
+ test('scalars', () => {
398
+ expect([escapeValue(null), escapeValue(true), escapeValue(false), escapeValue(42), escapeValue(1.5)]).toEqual([
399
+ 'NULL',
400
+ 'true',
401
+ 'false',
402
+ 42,
403
+ 1.5,
404
+ ])
405
+ })
406
+
407
+ test('strings with quotes, backslashes and the dollar-quote tag', () => {
408
+ expect([escapeValue(`it's`), escapeValue('back\\slash'), escapeValue('a $pga$ b'), escapeValue('{"a":"b"}')]).toEqual([
409
+ "$pga$it's$pga$",
410
+ '$pga$back\\slash$pga$',
411
+ '$pgb$a $pga$ b$pgb$',
412
+ '$pga${"a":"b"}$pga$',
413
+ ])
414
+ })
415
+
416
+ test('arrays', () => {
417
+ expect([escapeValue(['a', 'b']), escapeValue([[1, 2], [3]]), escapeValue([])]).toEqual([
418
+ 'ARRAY[$pga$a$pga$,$pga$b$pga$]',
419
+ 'ARRAY[[1,2],[3]]',
420
+ 'ARRAY[]',
421
+ ])
422
+ })
423
+
424
+ test('literal objects pass through and other objects become empty', () => {
425
+ // Migration JSON (fill values, column defaults) reaches escapeValue unparsed.
426
+ expect([
427
+ escapeValue({ literal: true, value: 'now()' }),
428
+ escapeValue({ literal: true, value: 3 }),
429
+ escapeValue({ literal: false, value: 'x' }),
430
+ escapeValue({}),
431
+ ])
432
+ .toEqual([
433
+ 'now()',
434
+ 3,
435
+ '',
436
+ '',
437
+ ])
438
+ })
439
+ })