import { randomUUID } from 'node:crypto'; import { copyFileSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; import { Pool } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('fresh-database-schema-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const initDir = fileURLToPath(new URL('../../database/postgres/init', import.meta.url)); const MASTER_FILES = [ '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 LEGACY_MASTER_TABLES = [ 'exchanges', 'symbols', 'provider_exchange_mappings', 'provider_mappings', 'sync_status', ]; const SECURITY_MASTER_TABLES = [ 'exchange', 'exchange_source_map', 'instrument', 'instrument_identifier_history', 'listing', 'corporate_action_continuity', 'listing_symbol_history', 'provider_mapping', 'resolution_conflict', 'override', 'golden_field_audit', ]; const BOOTSTRAP_FILES = [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', '08-create-runs-table.sql', ]; const RESEARCH_FILES = [ '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', ]; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function createIsolatedFixture() { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('Dedicated stock_bot_safety database required'); } const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); const pool = new Pool({ connectionString: url, options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, }); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => ({ connect: () => pool.connect(), }), }); const tables = async () => ( await pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1 ORDER BY tablename', [ schema, ]) ).rows.map(row => row.tablename as string); const recorded = async () => (await pool.query('SELECT filename FROM migrations ORDER BY filename')).rows.map( row => row.filename as string ); const hasColumn = async (tableName: string, columnName: string) => ( await pool.query( 'SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = $3', [schema, tableName, columnName] ) ).rowCount === 1; return { pool, schema, postgres, tables, recorded, hasColumn }; } describe.skipIf(!url)('fresh PostgreSQL database schema', () => { test('Case A: init SQL 01-36 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { const f = await createIsolatedFixture(); const sqlFiles = readdirSync(initDir) .filter(file => file.endsWith('.sql')) .sort(); expect(sqlFiles.length).toBeGreaterThanOrEqual(36); for (const file of sqlFiles) { const sql = readFileSync(join(initDir, file), 'utf8'); expect(sql).not.toMatch(/\bCREATE\s+DATABASE\b/i); expect(sql).not.toMatch(/^\s*\\c(?:\s|$)/m); await f.pool.query(sql); } const createdTables = new Set(await f.tables()); for (const expectedTable of [ // Legacy master tables (02-05) ...LEGACY_MASTER_TABLES, // Security master tables (34) ...SECURITY_MASTER_TABLES, // Research tables (06-33, 36, including representatives from 12, 16, 20, 22, 28, 30, 36) 'backtests', 'backtest_results', 'runs', 'backtest_datasets', 'strategies', 'research_projects', 'research_experiments', 'research_agents', 'paper_deployments', 'trial_ledger', 'vault_evaluations', ]) { expect(createdTables.has(expectedTable)).toBe(true); } // 05-add-visible-column.sql & 19-canonical-research.sql add columns to existing tables expect(await f.hasColumn('exchanges', 'visible')).toBe(true); expect(await f.hasColumn('backtest_results', 'canonical_result')).toBe(true); }); test('Case B: master track creates master tables, records exact 7 files, and is idempotent', async () => { const f = await createIsolatedFixture(); const first = await runPostgresMigrations(f.postgres, { track: 'master' }); expect(first).toEqual(MASTER_FILES); expect(await f.recorded()).toEqual(MASTER_FILES); const createdTables = new Set(await f.tables()); for (const table of [...LEGACY_MASTER_TABLES, ...SECURITY_MASTER_TABLES]) { expect(createdTables.has(table)).toBe(true); } expect(createdTables.has('trial_ledger')).toBe(false); expect(createdTables.has('vault_evaluations')).toBe(false); expect(await f.hasColumn('exchanges', 'visible')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'master' }); expect(second).toEqual([]); expect(await f.recorded()).toEqual(MASTER_FILES); }); test('Case C: all track with 06-08 pre-applied records master + research (including 36) and never records 06-08', async () => { const f = await createIsolatedFixture(); for (const file of BOOTSTRAP_FILES) { await f.pool.query(readFileSync(join(initDir, file), 'utf8')); } const expected = [...MASTER_FILES, ...RESEARCH_FILES].sort(); const first = await runPostgresMigrations(f.postgres, { track: 'all' }); expect(first).toEqual(expected); const recorded = await f.recorded(); expect(recorded).toEqual(expected); for (const excluded of BOOTSTRAP_FILES) { expect(recorded).not.toContain(excluded); } const createdTables = new Set(await f.tables()); for (const table of [...LEGACY_MASTER_TABLES, ...SECURITY_MASTER_TABLES]) { expect(createdTables.has(table)).toBe(true); } expect(createdTables.has('trial_ledger')).toBe(true); expect(createdTables.has('vault_evaluations')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'all' }); expect(second).toEqual([]); }); test('Case D: failing master migration rolls back all DDL and leaves no migrations row', async () => { const f = await createIsolatedFixture(); const tempDir = mkdtempSync(join(tmpdir(), 'stock-bot-migrate-fail-')); cleanup.push(() => { rmSync(tempDir, { recursive: true, force: true }); }); copyFileSync(join(initDir, '01-init-database.sql'), join(tempDir, '01-init-database.sql')); copyFileSync(join(initDir, '02-master-schema.sql'), join(tempDir, '02-master-schema.sql')); writeFileSync(join(tempDir, '03-initial-data.sql'), 'SELECT 1 / 0;\n', 'utf8'); await expect( runPostgresMigrations(f.postgres, { track: 'master', migrationsDir: tempDir }) ).rejects.toThrow(/division by zero/i); expect(await f.tables()).toEqual([]); }); });