|
| 1 | +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { Command, Flags } from '@oclif/core'; |
| 4 | +import chalk from 'chalk'; |
| 5 | +import { createInterface } from 'node:readline'; |
| 6 | +import { |
| 7 | + printHeader, |
| 8 | + printSuccess, |
| 9 | + printWarning, |
| 10 | + printError, |
| 11 | + printInfo, |
| 12 | + printStep, |
| 13 | + createTimer, |
| 14 | +} from '../../utils/format.js'; |
| 15 | +import { |
| 16 | + bootSchemaStack, |
| 17 | + renderPlan, |
| 18 | + summarize, |
| 19 | + groupByCategory, |
| 20 | +} from '../../utils/schema-migrate.js'; |
| 21 | + |
| 22 | +async function confirm(question: string): Promise<boolean> { |
| 23 | + if (!process.stdin.isTTY) return false; // non-interactive → require --yes |
| 24 | + const rl = createInterface({ input: process.stdin, output: process.stdout }); |
| 25 | + try { |
| 26 | + const answer: string = await new Promise((resolve) => rl.question(question, resolve)); |
| 27 | + return /^y(es)?$/i.test(answer.trim()); |
| 28 | + } finally { |
| 29 | + rl.close(); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * `os migrate apply` — reconcile the physical database to metadata (#2186). |
| 35 | + * Applies safe (loosening) + needs-confirm changes by default; destructive |
| 36 | + * changes (drop column, tighten NOT NULL, narrow type) require |
| 37 | + * `--allow-destructive`. |
| 38 | + */ |
| 39 | +export default class MigrateApply extends Command { |
| 40 | + static override description = |
| 41 | + 'Reconcile the physical database to metadata (safe by default; destructive changes need --allow-destructive)'; |
| 42 | + |
| 43 | + static override examples = [ |
| 44 | + '$ os migrate apply', |
| 45 | + '$ os migrate apply --yes', |
| 46 | + '$ os migrate apply --allow-destructive --yes', |
| 47 | + '$ os migrate apply --json', |
| 48 | + ]; |
| 49 | + |
| 50 | + static override flags = { |
| 51 | + 'database-url': Flags.string({ |
| 52 | + description: 'Database URL to reconcile (defaults to $OS_DATABASE_URL / the project DB)', |
| 53 | + env: 'OS_DATABASE_URL', |
| 54 | + }), |
| 55 | + 'allow-destructive': Flags.boolean({ |
| 56 | + description: 'Also apply destructive changes (drop column, tighten NOT NULL, narrow type)', |
| 57 | + default: false, |
| 58 | + }), |
| 59 | + yes: Flags.boolean({ char: 'y', description: 'Skip the confirmation prompt', default: false }), |
| 60 | + json: Flags.boolean({ description: 'Output as JSON (implies non-interactive; requires --yes to mutate)' }), |
| 61 | + }; |
| 62 | + |
| 63 | + async run(): Promise<void> { |
| 64 | + const { flags } = await this.parse(MigrateApply); |
| 65 | + const timer = createTimer(); |
| 66 | + const allowDestructive = flags['allow-destructive']; |
| 67 | + |
| 68 | + if (!flags.json) { |
| 69 | + printHeader('Migrate · apply'); |
| 70 | + printStep('Booting schema stack…'); |
| 71 | + } |
| 72 | + |
| 73 | + let stack; |
| 74 | + try { |
| 75 | + stack = await bootSchemaStack({ databaseUrl: flags['database-url'] }); |
| 76 | + } catch (error: any) { |
| 77 | + if (flags.json) { console.log(JSON.stringify({ error: error.message })); this.exit(1); } |
| 78 | + printError(error.message || String(error)); |
| 79 | + this.exit(1); |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + try { |
| 84 | + if (!stack.driver) { |
| 85 | + if (flags.json) { console.log(JSON.stringify({ error: 'no_sql_driver' })); return; } |
| 86 | + printWarning('Schema migration is only supported on SQL drivers (SQLite / Postgres). No SQL driver is active.'); |
| 87 | + return; |
| 88 | + } |
| 89 | + |
| 90 | + const drift = await stack.driver.detectManagedDrift(); |
| 91 | + const grouped = groupByCategory(drift); |
| 92 | + |
| 93 | + if (drift.length === 0) { |
| 94 | + if (flags.json) { console.log(JSON.stringify({ applied: [], skipped: [], message: 'in_sync' })); return; } |
| 95 | + printSuccess('Physical schema is already in sync with metadata — nothing to apply.'); |
| 96 | + return; |
| 97 | + } |
| 98 | + |
| 99 | + // Entries we intend to apply this run. |
| 100 | + const intended = drift.filter((d) => d.category !== 'destructive' || allowDestructive); |
| 101 | + const deferred = drift.filter((d) => d.category === 'destructive' && !allowDestructive); |
| 102 | + |
| 103 | + if (!flags.json) { |
| 104 | + printInfo(`Database: ${chalk.white(stack.dbLabel)}`); |
| 105 | + console.log(''); |
| 106 | + renderPlan(drift); |
| 107 | + printInfo(summarize(drift)); |
| 108 | + if (deferred.length > 0) { |
| 109 | + printWarning(`${deferred.length} destructive change(s) will be SKIPPED (re-run with --allow-destructive to include them).`); |
| 110 | + } |
| 111 | + if (allowDestructive && grouped.destructive.length > 0) { |
| 112 | + printWarning('Destructive changes assume your full app/plugin set is loaded. A column that looks "orphaned" here may belong to a plugin that is not part of this build.'); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + if (intended.length === 0) { |
| 117 | + if (flags.json) { console.log(JSON.stringify({ applied: [], skipped: deferred, message: 'nothing_safe_to_apply' })); return; } |
| 118 | + printWarning('No changes to apply without --allow-destructive.'); |
| 119 | + return; |
| 120 | + } |
| 121 | + |
| 122 | + // Confirmation gate. |
| 123 | + if (!flags.yes) { |
| 124 | + if (flags.json || !process.stdin.isTTY) { |
| 125 | + if (flags.json) { console.log(JSON.stringify({ applied: [], skipped: drift, message: 'confirmation_required', hint: 'pass --yes' })); return; } |
| 126 | + printWarning('Confirmation required. Re-run with --yes to apply, or use "os migrate plan" to preview.'); |
| 127 | + return; |
| 128 | + } |
| 129 | + const ok = await confirm(chalk.bold(`\nApply ${intended.length} change(s) to ${stack.dbLabel}? [y/N] `)); |
| 130 | + if (!ok) { printInfo('Aborted — no changes made.'); return; } |
| 131 | + } |
| 132 | + |
| 133 | + const { applied, skipped } = await stack.driver.applyMigrationEntries(drift, { allowDestructive }); |
| 134 | + |
| 135 | + if (flags.json) { |
| 136 | + console.log(JSON.stringify({ |
| 137 | + database: stack.dbLabel, |
| 138 | + applied, |
| 139 | + skipped, |
| 140 | + duration: timer.elapsed(), |
| 141 | + }, null, 2)); |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + console.log(''); |
| 146 | + printSuccess(`Applied ${applied.length} change(s).`); |
| 147 | + if (skipped.length > 0) { |
| 148 | + printWarning(`Skipped ${skipped.length} change(s) (destructive without --allow-destructive, or unsupported on this dialect).`); |
| 149 | + } |
| 150 | + console.log(chalk.dim(` ${timer.display()}`)); |
| 151 | + console.log(''); |
| 152 | + } catch (error: any) { |
| 153 | + if (flags.json) { console.log(JSON.stringify({ error: error.message })); this.exit(1); } |
| 154 | + printError(error.message || String(error)); |
| 155 | + this.exit(1); |
| 156 | + } finally { |
| 157 | + await stack.shutdown(); |
| 158 | + } |
| 159 | + } |
| 160 | +} |
0 commit comments