File size: 6,088 Bytes
dcedb25 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | import '../../env.js';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import type { Db } from '../types.js';
import { connectDb } from '../index.js';
import { getMigrationStatuses, runMigrations } from './runner.js';
type Command = 'up' | 'down' | 'fresh' | 'status' | 'create';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const MIGRATIONS_DIR = path.resolve(__dirname, '../migrations');
const TEMPLATE_PATH = path.resolve(__dirname, 'TEMPLATE.ts');
const DEFAULTS_PATH = path.resolve(__dirname, 'defaults.ts');
async function main(): Promise<void> {
const command = process.argv[2] as Command | undefined;
if (command === 'create') {
createMigrationFile();
return;
}
const db = connectDb();
switch (command) {
case 'up':
await runMigrations(db, 'up');
return;
case 'down':
await runMigrations(db, 'down');
return;
case 'fresh':
await runFresh(db);
return;
case 'status':
printStatus(db);
return;
default:
console.error('Usage: tsx src/db/migrate/cli.ts <up|down|fresh|status|create>');
process.exit(1);
}
}
async function runFresh(db: Db): Promise<void> {
if (process.env.NODE_ENV === 'production') {
console.error('db:migration:fresh is not allowed in production');
process.exit(1);
}
dropAllUserTables(db);
await runMigrations(db, 'up');
}
function printStatus(db: Db): void {
const statuses = getMigrationStatuses(db);
console.table(statuses.map(status => ({
filename: status.filename,
status: status.status,
applied_at: status.appliedAt ?? '',
})));
}
function createMigrationFile(): void {
const rawName = getMigrationName();
if (!rawName) {
console.error('Error: --name is required. Usage: npm run db:migration:create --name=<description>');
process.exit(1);
}
const sanitisedName = sanitiseMigrationName(rawName);
if (!sanitisedName) {
console.error('Error: --name must contain at least one letter or digit');
process.exit(1);
}
const now = new Date();
const filename = `${formatTimestamp(now)}_${sanitisedName}.ts`;
const outputPath = path.join(MIGRATIONS_DIR, filename);
const relativeOutputPath = toPosixPath(path.relative(process.cwd(), outputPath));
if (!fs.existsSync(TEMPLATE_PATH)) {
console.error(`Error: migration template not found at ${toPosixPath(TEMPLATE_PATH)}`);
process.exit(1);
}
if (fs.existsSync(outputPath)) {
console.error(`Error: migration already exists at ${relativeOutputPath}`);
process.exit(1);
}
fs.mkdirSync(MIGRATIONS_DIR, { recursive: true });
const template = fs.readFileSync(TEMPLATE_PATH, 'utf8');
const content = template
.replaceAll('<short description>', rawName)
.replaceAll('<YYYY-MM-DD>', formatDate(now));
fs.writeFileSync(outputPath, content, { flag: 'wx' });
updateDefaultMigrationRegistry(filename);
console.log(`Created ${relativeOutputPath}`);
}
function updateDefaultMigrationRegistry(filename: string): void {
if (!fs.existsSync(DEFAULTS_PATH)) {
console.error(`Error: migration registry not found at ${toPosixPath(DEFAULTS_PATH)}`);
process.exit(1);
}
const bindingName = toMigrationBindingName(filename);
const importPath = `../migrations/${filename.replace(/\.ts$/, '.js')}`;
const importLine = `import * as ${bindingName} from '${importPath}';`;
const entryLine = ` { filename: '${filename}', module: ${bindingName} },`;
const registry = fs.readFileSync(DEFAULTS_PATH, 'utf8');
if (registry.includes(importLine) || registry.includes(entryLine)) return;
const withImport = registry.replace(
'\nexport interface MigrationModule',
`\n${importLine}\n\nexport interface MigrationModule`,
);
if (withImport === registry) {
console.error('Error: could not update migration registry imports');
process.exit(1);
}
const withEntry = withImport.replace(
/\n\];\s*$/,
`\n${entryLine}\n];\n`,
);
if (withEntry === withImport) {
console.error('Error: could not update migration registry entries');
process.exit(1);
}
fs.writeFileSync(DEFAULTS_PATH, withEntry);
}
function getMigrationName(): string | undefined {
const argvName = process.argv
.map(arg => arg.match(/^--name=(.+)$/)?.[1]?.trim())
.find((name): name is string => Boolean(name));
return argvName || process.env.npm_config_name?.trim();
}
function sanitiseMigrationName(name: string): string {
return name
.toLowerCase()
.replace(/[ -]+/g, '_')
.replace(/[^a-z0-9_]/g, '')
.replace(/_+/g, '_')
.replace(/^_+|_+$/g, '');
}
function formatTimestamp(date: Date): string {
return [
date.getUTCFullYear(),
pad(date.getUTCMonth() + 1),
pad(date.getUTCDate()),
'_',
pad(date.getUTCHours()),
pad(date.getUTCMinutes()),
pad(date.getUTCSeconds()),
].join('');
}
function formatDate(date: Date): string {
return [
date.getUTCFullYear(),
pad(date.getUTCMonth() + 1),
pad(date.getUTCDate()),
].join('-');
}
function pad(value: number): string {
return String(value).padStart(2, '0');
}
function toMigrationBindingName(filename: string): string {
return `migration${filename.replace(/\.ts$/, '').replace(/[^a-zA-Z0-9_]/g, '_')}`;
}
function dropAllUserTables(db: Db): void {
const tables = db.prepare(`
SELECT name
FROM sqlite_master
WHERE type = 'table'
AND name NOT LIKE 'sqlite_%'
ORDER BY name ASC
`).all() as { name: string }[];
db.pragma('foreign_keys = OFF');
try {
const dropTables = db.transaction(() => {
for (const { name } of tables) {
db.exec(`DROP TABLE IF EXISTS ${quoteIdentifier(name)}`);
}
});
dropTables();
} finally {
db.pragma('foreign_keys = ON');
}
}
function quoteIdentifier(identifier: string): string {
return `"${identifier.replaceAll('"', '""')}"`;
}
function toPosixPath(value: string): string {
return value.replaceAll(path.sep, '/');
}
main().catch((err: unknown) => {
console.error(err);
process.exit(1);
});
|