95 lines
3.7 KiB
TypeScript
95 lines
3.7 KiB
TypeScript
import { existsSync, readdirSync, readFileSync } from 'fs';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { dirname, join } from 'path';
|
|
import type { IServiceContainer } from '@stock-bot/handlers';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
|
|
const logger = getLogger('migration-runner');
|
|
|
|
export async function runMigrations(container: IServiceContainer): Promise<void> {
|
|
logger.info('Migration runner called');
|
|
logger.info('Container type', { type: typeof container });
|
|
logger.info('Container postgres available', { available: !!container.postgres });
|
|
|
|
if (!container.postgres) {
|
|
logger.warn('PostgreSQL not available, skipping migrations');
|
|
logger.info('Container keys:', Object.keys(container));
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await container.postgres.transaction(async client => {
|
|
// All startup migrations share one database-scoped lock on this transaction's client.
|
|
// PostgreSQL releases it on commit/rollback, including when startup fails.
|
|
await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]);
|
|
|
|
// Create migrations table if it doesn't exist
|
|
await client.query(`
|
|
CREATE TABLE IF NOT EXISTS migrations (
|
|
id SERIAL PRIMARY KEY,
|
|
filename VARCHAR(255) NOT NULL UNIQUE,
|
|
executed_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
|
)
|
|
`);
|
|
|
|
// Get list of migration files from database/postgres/init while holding the lock.
|
|
let directory = dirname(fileURLToPath(import.meta.url));
|
|
while (!existsSync(join(directory, 'database', 'postgres', 'init'))) {
|
|
const parent = dirname(directory);
|
|
if (parent === directory) {
|
|
throw new Error('Cannot locate PostgreSQL migrations');
|
|
}
|
|
directory = parent;
|
|
}
|
|
const migrationsDir = join(directory, 'database', 'postgres', 'init');
|
|
logger.info('Looking for migrations', { directory: migrationsDir });
|
|
|
|
const files = readdirSync(migrationsDir)
|
|
.filter(
|
|
f =>
|
|
f.endsWith('.sql') &&
|
|
(f.startsWith('001_') ||
|
|
f === '09-backtest-run-contract.sql' ||
|
|
f === '10-durable-backtest-dispatch.sql' ||
|
|
f === '11-simulation-execution-ledger.sql' ||
|
|
f === '12-historical-datasets.sql' ||
|
|
f === '13-strategy-recovery.sql' ||
|
|
f === '14-backtest-submission.sql' ||
|
|
f === '15-canonical-paper-intents.sql' ||
|
|
f === '16-strategy-catalog.sql' ||
|
|
f === '17-research-retention.sql' ||
|
|
f === '18-backtest-strategy-versions.sql' ||
|
|
f === '19-canonical-research.sql')
|
|
) // Explicit additive migration allowlist; never replay destructive init migrations
|
|
.sort();
|
|
|
|
logger.info('Found migration files:', files);
|
|
|
|
for (const file of files) {
|
|
// Check and apply using the same locked client, not another pooled connection.
|
|
const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]);
|
|
|
|
if (result.rows.length === 0) {
|
|
logger.info(`Running migration: ${file}`);
|
|
|
|
// Read and execute migration
|
|
const sql = readFileSync(join(migrationsDir, file), 'utf8');
|
|
await client.query(sql);
|
|
await client.query(
|
|
'INSERT INTO migrations (filename) VALUES ($1) ON CONFLICT (filename) DO NOTHING',
|
|
[file]
|
|
);
|
|
|
|
logger.info(`Migration applied: ${file}`);
|
|
} else {
|
|
logger.debug(`Migration already executed: ${file}`);
|
|
}
|
|
}
|
|
});
|
|
|
|
logger.info('All migrations completed successfully');
|
|
} catch (error) {
|
|
logger.error('Migration failed', { error });
|
|
throw error;
|
|
}
|
|
}
|