@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,379 @@
1
+ /*
2
+ The SQL generation in this file is ported from the migration builder of node-pg-migrate. (https://github.com/salsita/node-pg-migrate)
3
+
4
+ The MIT License (MIT)
5
+
6
+ Copyright (c) 2016-2020 Salsita Software <jando@salsitasoft.com>
7
+
8
+ Copyright (c) 2014-2016 Theo Ephraim
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ */
28
+
29
+ // Collects the SQL of engine and content migrations. The output reproduces node-pg-migrate 5 byte for byte for the
30
+ // operations and options below, because not-yet-run migrations on existing databases must execute the same SQL.
31
+
32
+ export type Name = string | { schema?: string; name: string }
33
+
34
+ export type Value = null | boolean | string | number | readonly Value[]
35
+
36
+ export interface SequenceOptions {
37
+ precedence: 'ALWAYS' | 'BY DEFAULT'
38
+ type?: string
39
+ increment?: number
40
+ minvalue?: number | null | false
41
+ maxvalue?: number | null | false
42
+ start?: number
43
+ cache?: number
44
+ cycle?: boolean
45
+ owner?: string | null | false
46
+ }
47
+
48
+ export interface ColumnDefinition {
49
+ type: string
50
+ collation?: string
51
+ default?: Value
52
+ unique?: boolean
53
+ primaryKey?: boolean
54
+ notNull?: boolean
55
+ references?: Name
56
+ onDelete?: string
57
+ sequenceGenerated?: SequenceOptions
58
+ }
59
+
60
+ export interface AlterColumnOptions {
61
+ type?: string
62
+ collation?: string
63
+ using?: string
64
+ notNull?: boolean
65
+ sequenceGenerated?: SequenceOptions | false
66
+ }
67
+
68
+ export interface TriggerOptions {
69
+ when: 'BEFORE' | 'AFTER'
70
+ operation: string | readonly string[]
71
+ level?: 'ROW' | 'STATEMENT'
72
+ function: Name
73
+ functionParams?: readonly Value[]
74
+ constraint?: boolean
75
+ deferrable?: boolean
76
+ deferred?: boolean
77
+ }
78
+
79
+ export interface FunctionParam {
80
+ name: string
81
+ type: string
82
+ }
83
+
84
+ const quote = (identifier: string): string => `"${identifier}"`
85
+
86
+ const literal = (name: Name): string => typeof name === 'object' ? (name.schema ? `${quote(name.schema)}.` : '') + quote(name.name) : quote(name)
87
+
88
+ const nextDollarTag = function*(): Generator<string> {
89
+ const chars = 'abcdefghijklmnopqrstuvwxyz'
90
+ const ids = [0]
91
+ while (true) {
92
+ yield `$pg${ids.map(id => chars[id]).join('')}$`
93
+ let i = ids.length - 1
94
+ for (; i >= 0; i--) {
95
+ ids[i] += 1
96
+ if (ids[i] < chars.length) {
97
+ break
98
+ }
99
+ ids[i] = 0
100
+ }
101
+ if (i < 0) {
102
+ ids.unshift(0)
103
+ }
104
+ }
105
+ }
106
+
107
+ export const escapeValue = (value: unknown): string | number => {
108
+ if (value === null) {
109
+ return 'NULL'
110
+ }
111
+ if (typeof value === 'boolean') {
112
+ return value.toString()
113
+ }
114
+ if (typeof value === 'string') {
115
+ for (const tag of nextDollarTag()) {
116
+ if (!value.includes(tag)) {
117
+ return `${tag}${value}${tag}`
118
+ }
119
+ }
120
+ }
121
+ if (typeof value === 'number') {
122
+ return value
123
+ }
124
+ if (Array.isArray(value)) {
125
+ return `ARRAY[${value.map(escapeValue).join(',').replace(/ARRAY/g, '')}]`
126
+ }
127
+ // node-pg-migrate's PgLiteral shape; migration JSON (e.g. a fill value or column default) can carry it.
128
+ if (typeof value === 'object' && 'literal' in value && value.literal === true && 'value' in value) {
129
+ return typeof value.value === 'number' ? value.value : `${value.value}`
130
+ }
131
+ return ''
132
+ }
133
+
134
+ const typeAdapters: Record<string, string> = {
135
+ int: 'integer',
136
+ string: 'text',
137
+ float: 'real',
138
+ double: 'double precision',
139
+ datetime: 'timestamp',
140
+ bool: 'boolean',
141
+ }
142
+
143
+ const adaptType = (type: string): string => typeAdapters[type] ?? type
144
+
145
+ // `id` is node-pg-migrate's only default type shorthand; on columns it also implies a primary key.
146
+ const resolveType = (type: string): string => type === 'id' ? 'serial' : adaptType(type)
147
+
148
+ const applyColumnShorthand = (column: ColumnDefinition): ColumnDefinition =>
149
+ column.type === 'id' ? { primaryKey: true, ...column, type: 'serial' } : { ...column, type: adaptType(column.type) }
150
+
151
+ const formatLines = (lines: readonly string[], prefix = ' ', separator = ','): string =>
152
+ lines
153
+ .map(line => line.replace(/(?:\r\n|\r|\n)+/g, ' '))
154
+ .join(`${separator}\n`)
155
+ .replace(/^/gm, prefix)
156
+
157
+ // Sequence options arrive unparsed from migration JSON, so every option node-pg-migrate rendered is kept.
158
+ const sequenceClause = (sequence: SequenceOptions): string => {
159
+ const { type, increment, minvalue, maxvalue, start, cache, cycle, owner } = sequence
160
+ const clauses: string[] = []
161
+ if (type) {
162
+ clauses.push(`AS ${resolveType(type)}`)
163
+ }
164
+ if (increment) {
165
+ clauses.push(`INCREMENT BY ${increment}`)
166
+ }
167
+ if (minvalue) {
168
+ clauses.push(`MINVALUE ${minvalue}`)
169
+ } else if (minvalue === null || minvalue === false) {
170
+ clauses.push('NO MINVALUE')
171
+ }
172
+ if (maxvalue) {
173
+ clauses.push(`MAXVALUE ${maxvalue}`)
174
+ } else if (maxvalue === null || maxvalue === false) {
175
+ clauses.push('NO MAXVALUE')
176
+ }
177
+ if (start) {
178
+ clauses.push(`START WITH ${start}`)
179
+ }
180
+ if (cache) {
181
+ clauses.push(`CACHE ${cache}`)
182
+ }
183
+ if (cycle) {
184
+ clauses.push('CYCLE')
185
+ } else if (cycle === false) {
186
+ clauses.push('NO CYCLE')
187
+ }
188
+ if (owner) {
189
+ clauses.push(`OWNED BY ${owner}`)
190
+ } else if (owner === null || owner === false) {
191
+ clauses.push('OWNED BY NONE')
192
+ }
193
+ return `GENERATED ${sequence.precedence} AS IDENTITY${clauses.length ? ` (${clauses.join(' ')})` : ''}`
194
+ }
195
+
196
+ const referencesClause = (column: ColumnDefinition & { references: Name }): string => {
197
+ const { references, onDelete } = column
198
+ const target = typeof references === 'string' && (references.startsWith('"') || references.endsWith(')')) ? references : literal(references)
199
+ return `REFERENCES ${target}${onDelete ? ` ON DELETE ${onDelete}` : ''}`
200
+ }
201
+
202
+ const columnLines = (columns: Record<string, ColumnDefinition>): { lines: string[]; primaryKey: string[] } => {
203
+ const applied = Object.entries(columns).map(([name, column]) => [name, applyColumnShorthand(column)] as const)
204
+ const primaryKey = applied.filter(([, column]) => column.primaryKey).map(([name]) => name)
205
+ const lines = applied.map(([name, column]) => {
206
+ const constraints: string[] = []
207
+ if (column.collation) {
208
+ constraints.push(`COLLATE ${column.collation}`)
209
+ }
210
+ if (column.default !== undefined) {
211
+ constraints.push(`DEFAULT ${escapeValue(column.default)}`)
212
+ }
213
+ if (column.unique) {
214
+ constraints.push('UNIQUE')
215
+ }
216
+ if (column.primaryKey && primaryKey.length === 1) {
217
+ constraints.push('PRIMARY KEY')
218
+ }
219
+ if (column.notNull) {
220
+ constraints.push('NOT NULL')
221
+ }
222
+ if (column.references) {
223
+ constraints.push(referencesClause({ ...column, references: column.references }))
224
+ }
225
+ if (column.sequenceGenerated) {
226
+ constraints.push(sequenceClause(column.sequenceGenerated))
227
+ }
228
+ return `${literal(name)} ${column.type}${constraints.length ? ` ${constraints.join(' ')}` : ''}`
229
+ })
230
+ return { lines, primaryKey: primaryKey.length > 1 ? primaryKey : [] }
231
+ }
232
+
233
+ const tableNameOf = (table: Name): string => typeof table === 'object' ? table.name : table
234
+
235
+ export class MigrationBuilder {
236
+ private readonly steps: string[] = []
237
+
238
+ getSqlSteps(): string[] {
239
+ return [...this.steps]
240
+ }
241
+
242
+ getSql(): string {
243
+ return `${this.steps.join('\n')}\n`
244
+ }
245
+
246
+ sql(sql: string): void {
247
+ this.steps.push(sql.lastIndexOf(';') !== sql.length - 1 ? `${sql};` : sql)
248
+ }
249
+
250
+ createTable(table: Name, columns: Record<string, ColumnDefinition>): void {
251
+ const { lines, primaryKey } = columnLines(columns)
252
+ const definition = primaryKey.length > 0
253
+ ? [...lines, `CONSTRAINT ${literal(`${tableNameOf(table)}_pkey`)} PRIMARY KEY (${primaryKey.map(name => literal(name)).join(', ')})`]
254
+ : lines
255
+ this.steps.push(`CREATE TABLE ${literal(table)} (\n${formatLines(definition)}\n);`)
256
+ }
257
+
258
+ dropTable(table: Name): void {
259
+ this.steps.push(`DROP TABLE ${literal(table)};`)
260
+ }
261
+
262
+ renameTable(table: Name, newName: Name): void {
263
+ this.steps.push(`ALTER TABLE ${literal(table)} RENAME TO ${literal(newName)};`)
264
+ }
265
+
266
+ addColumn(table: Name, columns: Record<string, ColumnDefinition>): void {
267
+ this.steps.push(`ALTER TABLE ${literal(table)}\n${formatLines(columnLines(columns).lines, ' ADD ')};`)
268
+ }
269
+
270
+ dropColumn(table: Name, column: string): void {
271
+ this.steps.push(`ALTER TABLE ${literal(table)}\n${formatLines([literal(column)], ' DROP ')};`)
272
+ }
273
+
274
+ renameColumn(table: Name, column: string, newName: string): void {
275
+ this.steps.push(`ALTER TABLE ${literal(table)} RENAME ${literal(column)} TO ${literal(newName)};`)
276
+ }
277
+
278
+ alterColumn(table: Name, column: string, options: AlterColumnOptions): void {
279
+ const actions: string[] = []
280
+ if (options.type) {
281
+ const collation = options.collation ? ` COLLATE ${options.collation}` : ''
282
+ const using = options.using ? ` USING ${options.using}` : ''
283
+ actions.push(`SET DATA TYPE ${adaptType(options.type)}${collation}${using}`)
284
+ }
285
+ if (options.notNull) {
286
+ actions.push('SET NOT NULL')
287
+ } else if (options.notNull === false) {
288
+ actions.push('DROP NOT NULL')
289
+ }
290
+ if (options.sequenceGenerated !== undefined) {
291
+ actions.push(options.sequenceGenerated ? `ADD ${sequenceClause(options.sequenceGenerated)}` : 'DROP IDENTITY')
292
+ }
293
+ if (actions.length > 0) {
294
+ this.steps.push(`ALTER TABLE ${literal(table)}\n${formatLines(actions, ` ALTER ${literal(column)} `)};`)
295
+ } else {
296
+ this.steps.push('')
297
+ }
298
+ }
299
+
300
+ addConstraint(table: Name, constraintName: string | null, options: { primaryKey: readonly string[] }): void {
301
+ const name = literal(constraintName || `${tableNameOf(table)}_pkey`)
302
+ const constraint = `CONSTRAINT ${name} PRIMARY KEY (${options.primaryKey.map(column => literal(column)).join(', ')})`
303
+ this.steps.push(`ALTER TABLE ${literal(table)}\n${formatLines([constraint], ' ADD ')};`)
304
+ }
305
+
306
+ dropConstraint(table: Name, constraintName: string): void {
307
+ this.steps.push(`ALTER TABLE ${literal(table)} DROP CONSTRAINT ${literal(constraintName)};`)
308
+ }
309
+
310
+ createIndex(table: Name, columns: readonly string[], options: { name: string }): void {
311
+ const columnsSql = columns.map(column => /[. ()]/.test(column) ? column : literal(column)).join(', ')
312
+ const name = options.name || `${tableNameOf(table)}_${columns.join('_')}_index`
313
+ this.steps.push(`CREATE INDEX ${literal(name)} ON ${literal(table)} (${columnsSql});`)
314
+ }
315
+
316
+ createDomain(domain: Name, type: string, options: { check: string; constraintName?: string }): void {
317
+ const constraintName = options.constraintName ? ` CONSTRAINT ${literal(options.constraintName)}` : ''
318
+ const check = options.check ? `${constraintName} CHECK (${options.check})` : ''
319
+ this.steps.push(`CREATE DOMAIN ${literal(domain)} AS ${resolveType(type)}${check};`)
320
+ }
321
+
322
+ renameDomain(domain: Name, newName: Name): void {
323
+ this.steps.push(`ALTER DOMAIN ${literal(domain)} RENAME TO ${literal(newName)};`)
324
+ }
325
+
326
+ dropDomain(domain: Name): void {
327
+ this.steps.push(`DROP DOMAIN ${literal(domain)};`)
328
+ }
329
+
330
+ createView(view: Name, options: { replace?: boolean }, definition: string): void {
331
+ this.steps.push(`CREATE${options.replace ? ' OR REPLACE' : ''} VIEW ${literal(view)} AS ${definition};`)
332
+ }
333
+
334
+ renameView(view: Name, newName: Name): void {
335
+ this.steps.push(`ALTER VIEW ${literal(view)} RENAME TO ${literal(newName)};`)
336
+ }
337
+
338
+ dropView(view: Name): void {
339
+ this.steps.push(`DROP VIEW ${literal(view)};`)
340
+ }
341
+
342
+ createMaterializedView(view: Name, options: { data?: boolean }, definition: string): void {
343
+ const data = options.data !== undefined ? ` WITH${options.data ? '' : ' NO'} DATA` : ''
344
+ this.steps.push(`CREATE MATERIALIZED VIEW ${literal(view)} AS ${definition}${data};`)
345
+ }
346
+
347
+ dropMaterializedView(view: Name): void {
348
+ this.steps.push(`DROP MATERIALIZED VIEW ${literal(view)};`)
349
+ }
350
+
351
+ createTrigger(table: Name, trigger: string, options: TriggerOptions): void {
352
+ const { constraint, deferrable, deferred, functionParams = [], level = 'STATEMENT' } = options
353
+ const when = constraint ? 'AFTER' : options.when
354
+ const operations = typeof options.operation === 'string' ? options.operation : options.operation.join(' OR ')
355
+ if (!options.function) {
356
+ throw new Error("Can't determine function name")
357
+ }
358
+ if (!operations) {
359
+ throw new Error('"operation" (INSERT/UPDATE[ OF ...]/DELETE/TRUNCATE) have to be specified')
360
+ }
361
+ const defer = constraint ? `${deferrable ? `DEFERRABLE INITIALLY ${deferred ? 'DEFERRED' : 'IMMEDIATE'}` : 'NOT DEFERRABLE'}\n ` : ''
362
+ this.steps.push(
363
+ `CREATE${constraint ? ' CONSTRAINT' : ''} TRIGGER ${literal(trigger)}\n`
364
+ + ` ${when} ${operations} ON ${literal(table)}\n`
365
+ + ` ${defer}FOR EACH ${level}\n`
366
+ + ` EXECUTE PROCEDURE ${literal(options.function)}(${functionParams.map(escapeValue).join(', ')});`,
367
+ )
368
+ }
369
+
370
+ dropTrigger(table: Name, trigger: string, options: { ifExists?: boolean } = {}): void {
371
+ this.steps.push(`DROP TRIGGER${options.ifExists ? ' IF EXISTS' : ''} ${literal(trigger)} ON ${literal(table)};`)
372
+ }
373
+
374
+ dropFunction(fn: Name, params: readonly FunctionParam[]): void {
375
+ const paramsSql = params.map(param => [param.name ? literal(param.name) : '', param.type ? resolveType(param.type) : ''].filter(Boolean).join(' '))
376
+ .join(', ')
377
+ this.steps.push(`DROP FUNCTION ${literal(fn)}(${paramsSql});`)
378
+ }
379
+ }
package/src/helpers.ts CHANGED
@@ -1,23 +1,10 @@
1
- import { MigrationBuilder } from 'node-pg-migrate'
2
1
  import { Migration, RunMigration } from './Migration.js'
3
- import MigrationBuilderImpl from 'node-pg-migrate/dist/migration-builder.js'
4
- import { escapeValue as pgEscape } from 'node-pg-migrate/dist/utils.js'
2
+ import { MigrationBuilder } from './MigrationBuilder.js'
5
3
 
6
- export function createMigrationBuilder(): MigrationBuilder & { getSql: () => string; getSqlSteps: () => string[] } {
7
- const impl = 'default' in MigrationBuilderImpl ? (MigrationBuilderImpl as any).default : MigrationBuilderImpl
8
- return new impl(
9
- {
10
- query: null,
11
- select: null,
12
- } as any,
13
- {},
14
- false,
15
- {} as any,
16
- )
17
- }
4
+ export { escapeValue } from './MigrationBuilder.js'
18
5
 
19
- export function escapeValue(value: any): string | number {
20
- return pgEscape(value)
6
+ export function createMigrationBuilder(): MigrationBuilder {
7
+ return new MigrationBuilder()
21
8
  }
22
9
 
23
10
  export const timePrefixLength = 'YYYY-MM-DD-XXXXXX'.length
package/src/index.ts CHANGED
@@ -4,5 +4,6 @@ export * from './SnapshotMigrationResolver.js'
4
4
  export * from './helpers.js'
5
5
  export * from './Migration.js'
6
6
  export * from './MigrationsResolver.js'
7
- export type { MigrationBuilder, Name } from 'node-pg-migrate'
7
+ export { MigrationBuilder } from './MigrationBuilder.js'
8
+ export type { AlterColumnOptions, ColumnDefinition, FunctionParam, Name, SequenceOptions, TriggerOptions, Value } from './MigrationBuilder.js'
8
9
  export type { DatabaseConfig } from '@contember/database'