116 lines
3.6 KiB
TypeScript
116 lines
3.6 KiB
TypeScript
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
import { dirname, join } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { getLogger } from '@stock-bot/logger';
|
|
import type { PostgreSQLClient } from './client';
|
|
|
|
const logger = getLogger('postgres-migrations');
|
|
|
|
export type MigrationTrack = 'master' | 'research' | 'all';
|
|
|
|
const MASTER_FILES = new Set([
|
|
'01-init-database.sql',
|
|
'02-master-schema.sql',
|
|
'03-initial-data.sql',
|
|
'04-provider-exchange-mapping-schema.sql',
|
|
'05-add-visible-column.sql',
|
|
'34-security-master.sql',
|
|
'35-security-master-exchange-seed.sql',
|
|
]);
|
|
|
|
const RESEARCH_FILES = new Set([
|
|
'09-backtest-run-contract.sql',
|
|
'10-durable-backtest-dispatch.sql',
|
|
'11-simulation-execution-ledger.sql',
|
|
'12-historical-datasets.sql',
|
|
'13-strategy-recovery.sql',
|
|
'14-backtest-submission.sql',
|
|
'15-canonical-paper-intents.sql',
|
|
'16-strategy-catalog.sql',
|
|
'17-research-retention.sql',
|
|
'18-backtest-strategy-versions.sql',
|
|
'19-canonical-research.sql',
|
|
'20-research-workspace.sql',
|
|
'21-run-reproduction.sql',
|
|
'22-experiments.sql',
|
|
'23-experiment-retries.sql',
|
|
'24-chronological-validation.sql',
|
|
'25-walk-forward.sql',
|
|
'26-cost-sensitivity.sql',
|
|
'27-research-evidence-sources.sql',
|
|
'28-research-agents.sql',
|
|
'29-isolated-candidates.sql',
|
|
'30-paper-deployments.sql',
|
|
'31-research-agent-project-links.sql',
|
|
'32-candidate-parameter-defaults.sql',
|
|
'33-candidate-decimal-normalization.sql',
|
|
'36-trial-ledger.sql',
|
|
]);
|
|
|
|
function locateMigrationsDir(): string {
|
|
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 (database/postgres/init)');
|
|
}
|
|
directory = parent;
|
|
}
|
|
return join(directory, 'database', 'postgres', 'init');
|
|
}
|
|
|
|
function matchesTrack(file: string, track: MigrationTrack): boolean {
|
|
if (!file.endsWith('.sql')) {
|
|
return false;
|
|
}
|
|
const inMaster = MASTER_FILES.has(file);
|
|
const inResearch = file.startsWith('001_') || RESEARCH_FILES.has(file);
|
|
if (track === 'master') {
|
|
return inMaster;
|
|
}
|
|
if (track === 'research') {
|
|
return inResearch;
|
|
}
|
|
return inMaster || inResearch;
|
|
}
|
|
|
|
export async function runPostgresMigrations(
|
|
postgres: Pick<PostgreSQLClient, 'transaction'>,
|
|
options: { track?: MigrationTrack; migrationsDir?: string } = {}
|
|
): Promise<string[]> {
|
|
const track = options.track ?? 'research';
|
|
const applied: string[] = [];
|
|
|
|
await postgres.transaction(async client => {
|
|
await client.query('SELECT pg_advisory_xact_lock($1, $2)', [0x53544254, 1]);
|
|
|
|
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()
|
|
)
|
|
`);
|
|
|
|
const migrationsDir = options.migrationsDir ?? locateMigrationsDir();
|
|
const files = readdirSync(migrationsDir)
|
|
.filter(f => matchesTrack(f, track))
|
|
.sort();
|
|
|
|
for (const file of files) {
|
|
const result = await client.query('SELECT 1 FROM migrations WHERE filename = $1', [file]);
|
|
if (result.rows.length === 0) {
|
|
logger.info(`Running migration: ${file}`);
|
|
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]
|
|
);
|
|
applied.push(file);
|
|
}
|
|
}
|
|
});
|
|
|
|
return applied;
|
|
}
|