|
| 1 | +import * as path from 'path'; |
| 2 | + |
| 3 | +import * as fs from '../util/fs'; |
| 4 | +import { log } from '../util/logger'; |
| 5 | +import { interpolate } from '../util/string'; |
| 6 | +import { getTimestampString } from '../util/ts'; |
| 7 | +import Configuration from '../domain/Configuration'; |
| 8 | +import { getMigrationPath } from '../migration/service/knexMigrator'; |
| 9 | + |
| 10 | +const MIGRATION_TEMPLATE_PATH = path.resolve(__dirname, '../../assets/templates/migration'); |
| 11 | +const CREATE_TABLE_CONVENTION = /create_(\w+)_table/; |
| 12 | + |
| 13 | +/** |
| 14 | + * Generate migration file(s). |
| 15 | + * |
| 16 | + * @param {string} filename |
| 17 | + * @returns {Promise<string[]>} |
| 18 | + */ |
| 19 | +export async function makeMigration(config: Configuration, filename: string): Promise<string[]> { |
| 20 | + if (config.migration.sourceType !== 'sql') { |
| 21 | + // TODO: We'll need to support different types of migrations eg both sql & js |
| 22 | + // For instance migrations in JS would have different context like JavaScriptMigrationContext. |
| 23 | + throw new Error(`Unsupported migration.sourceType value "${config.migration.sourceType}".`); |
| 24 | + } |
| 25 | + |
| 26 | + let createUpTemplate = ''; |
| 27 | + let createDownTemplate = ''; |
| 28 | + |
| 29 | + const migrationPath = getMigrationPath(config); |
| 30 | + const migrationPathExists = await fs.exists(migrationPath); |
| 31 | + |
| 32 | + if (!migrationPathExists) { |
| 33 | + log(`Migration path does not exist, creating ${migrationPath}`); |
| 34 | + |
| 35 | + await fs.mkdir(migrationPath, { recursive: true }); |
| 36 | + } |
| 37 | + |
| 38 | + const timestamp = getTimestampString(); |
| 39 | + const upFilename = path.join(migrationPath, `${timestamp}_${filename}.up.sql`); |
| 40 | + const downFilename = path.join(migrationPath, `${timestamp}_${filename}.down.sql`); |
| 41 | + |
| 42 | + // Use the create migration template if the filename follows the pattern: create_<table>_table.sql |
| 43 | + const createTableMatched = filename.match(CREATE_TABLE_CONVENTION); |
| 44 | + |
| 45 | + if (createTableMatched) { |
| 46 | + const table = createTableMatched[1]; |
| 47 | + |
| 48 | + log(`Create migration for table: ${table}`); |
| 49 | + |
| 50 | + createUpTemplate = await fs |
| 51 | + .read(path.join(MIGRATION_TEMPLATE_PATH, 'create_up.sql')) |
| 52 | + .then(template => interpolate(template, { table })); |
| 53 | + createDownTemplate = await fs |
| 54 | + .read(path.join(MIGRATION_TEMPLATE_PATH, 'create_down.sql')) |
| 55 | + .then(template => interpolate(template, { table })); |
| 56 | + } |
| 57 | + |
| 58 | + await fs.write(upFilename, createUpTemplate); |
| 59 | + await fs.write(downFilename, createDownTemplate); |
| 60 | + |
| 61 | + return [upFilename, downFilename]; |
| 62 | +} |
0 commit comments