diff --git a/apps/stock/config/src/config-instance.ts b/apps/stock/config/src/config-instance.ts index b5eda87a..04187ff1 100644 --- a/apps/stock/config/src/config-instance.ts +++ b/apps/stock/config/src/config-instance.ts @@ -13,6 +13,7 @@ const __dirname = path.dirname(__filename); export interface InitializeStockConfigOptions { mongoReadOnly?: boolean; + postgresOnly?: boolean; } /** @@ -33,14 +34,22 @@ export function initializeStockConfig( const rawConfig = configInstance.initialize(stockAppSchema); const config: StockAppConfig = - options?.mongoReadOnly === true + options?.mongoReadOnly === true || options?.postgresOnly === true ? { ...rawConfig, database: { ...rawConfig.database, mongodb: { ...rawConfig.database.mongodb, - readOnly: true, + ...(options?.mongoReadOnly === true ? { readOnly: true } : {}), + ...(options?.postgresOnly === true + ? { + enabled: false, + uri: 'mongodb://disabled', + readUri: undefined, + password: undefined, + } + : {}), }, }, } diff --git a/database/postgres/init/02-master-schema.sql b/database/postgres/init/02-master-schema.sql index 80ba8b3f..818a45da 100644 --- a/database/postgres/init/02-master-schema.sql +++ b/database/postgres/init/02-master-schema.sql @@ -2,7 +2,7 @@ -- Exchanges Table CREATE TABLE IF NOT EXISTS exchanges ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), code VARCHAR(10) UNIQUE NOT NULL, -- NASDAQ, NYSE, TSX, etc. name VARCHAR(255) NOT NULL, -- Full exchange name country CHAR(2) NOT NULL, -- US, CA, GB @@ -14,7 +14,7 @@ CREATE TABLE IF NOT EXISTS exchanges ( -- Symbols Table CREATE TABLE IF NOT EXISTS symbols ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), symbol VARCHAR(20) NOT NULL, -- AAPL, SHOP, etc. exchange_id UUID REFERENCES exchanges(id), company_name VARCHAR(255), @@ -29,7 +29,7 @@ CREATE TABLE IF NOT EXISTS symbols ( -- Provider Symbol Mappings (How each provider refers to our symbols) CREATE TABLE IF NOT EXISTS provider_mappings ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), symbol_id UUID REFERENCES symbols(id), provider VARCHAR(50) NOT NULL, -- 'qm', 'yahoo', 'ib', etc. provider_symbol VARCHAR(100) NOT NULL, -- How provider names it: "AAPL:NASDAQ", "SHOP.TO" @@ -43,7 +43,7 @@ CREATE TABLE IF NOT EXISTS provider_mappings ( -- Simple sync tracking table CREATE TABLE IF NOT EXISTS sync_status ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), provider VARCHAR(50) NOT NULL, data_type VARCHAR(50) NOT NULL, -- 'symbols', 'exchanges' last_sync_at TIMESTAMP, diff --git a/database/postgres/init/04-provider-exchange-mapping-schema.sql b/database/postgres/init/04-provider-exchange-mapping-schema.sql index 66f3f835..4abd9586 100644 --- a/database/postgres/init/04-provider-exchange-mapping-schema.sql +++ b/database/postgres/init/04-provider-exchange-mapping-schema.sql @@ -19,7 +19,7 @@ END $$; -- Provider Exchange Mappings Table -- Maps provider-specific exchange codes to our master exchanges CREATE TABLE IF NOT EXISTS provider_exchange_mappings ( - id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), provider VARCHAR(50) NOT NULL, -- 'qm', 'eod', 'ib', etc. provider_exchange_code VARCHAR(50) NOT NULL, -- Provider's exchange code: 'NYE', 'US', 'NASDAQ' provider_exchange_name VARCHAR(255), -- Provider's exchange name diff --git a/package.json b/package.json index 91ddb4be..0b86adce 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "test:integration": "bun test test/integration/", "test:native": "cargo test -p engine --lib --offline", "test:postgres": "bun run scripts/test-postgres.ts", + "db:migrate": "bun run scripts/db-migrate.ts", "audit:secrets": "bun run scripts/audit-secrets.ts", "test:e2e": "bun run scripts/test-e2e.ts", "test:e2e:install": "playwright install chromium", diff --git a/scripts/db-migrate.ts b/scripts/db-migrate.ts new file mode 100644 index 00000000..c5e2b3e5 --- /dev/null +++ b/scripts/db-migrate.ts @@ -0,0 +1,148 @@ +import { getLogger } from '@stock-bot/logger'; +import { + PostgreSQLClient, + runPostgresMigrations, + type MigrationTrack, + type PostgreSQLClientConfig, +} from '@stock-bot/postgres'; +import { + assertEnvironmentSafety, + initializeStockConfig, + type StockAppConfig, +} from '@stock-bot/stock-config'; + +const VALID_TRACKS = new Set(['master', 'research', 'all']); +const TRACK_USAGE = 'Valid tracks: master|research|all'; + +export interface DbMigrateArgs { + track: MigrationTrack; +} + +export interface MigrationTarget { + clientConfig: PostgreSQLClientConfig; + targetLabel: string; +} + +function isValidTrack(value: string): value is MigrationTrack { + return VALID_TRACKS.has(value as MigrationTrack); +} + +export function parseDbMigrateArgs(argv: readonly string[]): DbMigrateArgs { + let track: MigrationTrack = 'all'; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--track') { + const value = argv[i + 1]; + if (!value || value.startsWith('-')) { + throw new Error(`Missing value for --track. ${TRACK_USAGE}`); + } + if (!isValidTrack(value)) { + throw new Error(`Invalid --track value "${value}". ${TRACK_USAGE}`); + } + track = value; + i += 1; + continue; + } + + if (arg.startsWith('--track=')) { + const value = arg.slice('--track='.length); + if (!isValidTrack(value)) { + throw new Error(`Invalid --track value "${value}". ${TRACK_USAGE}`); + } + track = value; + continue; + } + + throw new Error(`Unknown argument "${arg}". Usage: db:migrate [--track master|research|all]`); + } + + return { track }; +} + +export function loadMigrationConfig(): StockAppConfig { + return initializeStockConfig('dataPipeline', { postgresOnly: true }); +} + +export function resolveMigrationTarget( + config: StockAppConfig, + env: Record = process.env +): MigrationTarget { + const pg = config.database.postgres; + if (!pg.enabled) { + throw new Error('PostgreSQL is disabled in the active configuration.'); + } + + // Never allow the shared dev-on-QA override to bypass the PostgreSQL guard in db:migrate, + // and disable unrelated MongoDB checks so Postgres migrations only enforce PostgreSQL/environment guards. + const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _ignored, ...safeEnv } = env; + assertEnvironmentSafety( + { + ...config, + database: { + ...config.database, + mongodb: { + ...config.database.mongodb, + enabled: false, + uri: 'mongodb://disabled', + readUri: undefined, + password: undefined, + }, + }, + }, + 'dataPipeline', + safeEnv + ); + + const clientConfig: PostgreSQLClientConfig = { + host: pg.host, + port: pg.port, + database: pg.database, + username: pg.user, + password: pg.password, + ssl: { enabled: pg.ssl, rejectUnauthorized: true }, + poolSettings: { + min: 0, + max: pg.poolSize, + idleTimeoutMillis: pg.idleTimeout, + }, + timeouts: { connection: pg.connectionTimeout }, + }; + + return { + clientConfig, + targetLabel: `${pg.host}:${pg.port}/${pg.database}`, + }; +} + +async function main(argv: readonly string[]): Promise { + const { track } = parseDbMigrateArgs(argv); + const config = loadMigrationConfig(); + const { clientConfig, targetLabel } = resolveMigrationTarget(config, process.env); + const logger = getLogger('db-migrate'); + const client = new PostgreSQLClient(clientConfig, logger); + + try { + await client.connect(); + const applied = await runPostgresMigrations(client, { track }); + console.log(`Target: ${targetLabel} (track: ${track})`); + if (applied.length === 0) { + console.log('nothing to apply'); + } else { + console.log(`Applied ${applied.length} migration(s):`); + for (const filename of applied) { + console.log(` - ${filename}`); + } + } + } finally { + await client.disconnect(); + } +} + +if (import.meta.main) { + main(process.argv.slice(2)).catch(error => { + const message = error instanceof Error ? error.message : String(error); + console.error(`db:migrate failed: ${message}`); + process.exit(1); + }); +} diff --git a/scripts/test/db-migrate.test.ts b/scripts/test/db-migrate.test.ts new file mode 100644 index 00000000..37218d5b --- /dev/null +++ b/scripts/test/db-migrate.test.ts @@ -0,0 +1,289 @@ +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; +import { parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const dbMigrateModuleUrl = pathToFileURL(join(root, 'scripts/db-migrate.ts')).href; + +function makeConfig(overrides: { + environment?: StockAppConfig['environment']; + postgres?: Partial; +}): StockAppConfig { + return stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment: overrides.environment ?? 'development', + service: { + name: 'data-pipeline', + port: 2002, + }, + log: {}, + database: { + postgres: { + enabled: true, + host: 'localhost', + port: 5433, + database: 'trading_bot_dev', + user: 'dev_user', + password: 'dev_pass', + ssl: false, + poolSize: 10, + connectionTimeout: 30000, + idleTimeout: 10000, + ...overrides.postgres, + }, + mongodb: { + enabled: true, + uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin', + database: 'stock_dev', + poolSize: 10, + }, + questdb: {}, + dragonfly: {}, + }, + providers: {}, + features: {}, + }); +} + +describe('parseDbMigrateArgs', () => { + test('defaults to track "all" when no arguments are passed', () => { + expect(parseDbMigrateArgs([])).toEqual({ track: 'all' }); + }); + + test('accepts each valid track with space or equals syntax', () => { + for (const track of ['master', 'research', 'all'] as const) { + expect(parseDbMigrateArgs(['--track', track])).toEqual({ track }); + expect(parseDbMigrateArgs([`--track=${track}`])).toEqual({ track }); + } + }); + + test('rejects invalid track values with message listing valid tracks', () => { + expect(() => parseDbMigrateArgs(['--track', 'bogus'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['--track=bogus'])).toThrow(/master\|research\|all/); + }); + + test('rejects missing track value and unknown arguments', () => { + expect(() => parseDbMigrateArgs(['--track'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['--track', '--other'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['--unknown'])).toThrow(/master\|research\|all/); + expect(() => parseDbMigrateArgs(['positional'])).toThrow(/master\|research\|all/); + }); +}); + +describe('resolveMigrationTarget', () => { + test('rejects development targeting QA PostgreSQL on localhost:5432/trading_bot', () => { + const config = makeConfig({ + environment: 'development', + postgres: { host: 'localhost', port: 5432, database: 'trading_bot' }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/QA PostgreSQL/i); + }); + + test('rejects development targeting QA PostgreSQL on 127.0.0.1:5432/trading_bot', () => { + const config = makeConfig({ + environment: 'development', + postgres: { host: '127.0.0.1', port: 5432, database: 'trading_bot' }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/QA PostgreSQL/i); + }); + + test('accepts development targeting isolated dev PostgreSQL on localhost:5433/trading_bot_dev', () => { + const config = makeConfig({ + environment: 'development', + postgres: { + host: 'localhost', + port: 5433, + database: 'trading_bot_dev', + user: 'dev_user', + password: 'dev_pass', + }, + }); + const resolved = resolveMigrationTarget(config, {}); + expect(resolved.targetLabel).toBe('localhost:5433/trading_bot_dev'); + expect(resolved.clientConfig).toEqual({ + host: 'localhost', + port: 5433, + database: 'trading_bot_dev', + username: 'dev_user', + password: 'dev_pass', + ssl: { enabled: false, rejectUnauthorized: true }, + poolSettings: { min: 0, max: 10, idleTimeoutMillis: 10000 }, + timeouts: { connection: 30000 }, + }); + }); + + test('rejects qa targeting a _dev database', () => { + const config = makeConfig({ + environment: 'qa', + postgres: { host: 'localhost', port: 5433, database: 'trading_bot_dev' }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/dev PostgreSQL/i); + }); + + test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true', () => { + const config = makeConfig({ + environment: 'development', + postgres: { host: 'localhost', port: 5432, database: 'trading_bot' }, + }); + expect(() => + resolveMigrationTarget(config, { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true' }) + ).toThrow(/QA PostgreSQL/i); + }); + + test('rejects disabled PostgreSQL configuration', () => { + const config = makeConfig({ + environment: 'development', + postgres: { enabled: false }, + }); + expect(() => resolveMigrationTarget(config, {})).toThrow(/disabled/i); + }); +}); + +function runInitInIsolatedSubprocess( + env: Record, + mode: 'load-and-resolve' | 'load-only' = 'load-and-resolve' +): { exitCode: number; stdout: string; stderr: string } { + const isolatedDir = mkdtempSync(join(tmpdir(), 'stock-bot-db-migrate-env-')); + const script = + mode === 'load-only' + ? `import { loadMigrationConfig } from ${JSON.stringify(dbMigrateModuleUrl)}; +const config = loadMigrationConfig(); +console.log(JSON.stringify({ mongoEnabled: config.database.mongodb.enabled }));` + : `import { loadMigrationConfig, resolveMigrationTarget } from ${JSON.stringify(dbMigrateModuleUrl)}; +const config = loadMigrationConfig(); +const resolved = resolveMigrationTarget(config, process.env); +console.log(JSON.stringify({ mongoEnabled: config.database.mongodb.enabled, targetLabel: resolved.targetLabel }));`; + + try { + const result = Bun.spawnSync([process.execPath, '-e', script], { + cwd: isolatedDir, + env: { + PATH: process.env.PATH ?? '', + HOME: isolatedDir, + ...env, + }, + }); + return { + exitCode: result.exitCode, + stdout: new TextDecoder().decode(result.stdout).trim(), + stderr: new TextDecoder().decode(result.stderr).trim(), + }; + } finally { + rmSync(isolatedDir, { recursive: true, force: true }); + } +} + +describe('loadMigrationConfig (real initialization path, isolated subprocess)', () => { + test('succeeds for dev PostgreSQL even when QA MongoDB admin URI is set without MONGODB_READ_URI', () => { + const result = runInitInIsolatedSubprocess({ + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5433', + POSTGRES_DATABASE: 'trading_bot_dev', + POSTGRES_USERNAME: 'dev_user', + POSTGRES_PASSWORD: 'dev_pass', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5433', + DATABASE_POSTGRES_DATABASE: 'trading_bot_dev', + MONGODB_URI: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', + }); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + mongoEnabled: false, + targetLabel: 'localhost:5433/trading_bot_dev', + }); + }); + + test('rejects development targeting QA PostgreSQL during real config initialization', () => { + const result = runInitInIsolatedSubprocess( + { + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + }, + 'load-only' + ); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toMatch(/QA PostgreSQL/i); + }); + + test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true in real env', () => { + const result = runInitInIsolatedSubprocess({ + NODE_ENV: 'development', + POSTGRES_HOST: 'localhost', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_HOST: 'localhost', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true', + }); + + expect(result.exitCode).not.toBe(0); + expect(result.stderr).toMatch(/QA PostgreSQL/i); + }); + + test('succeeds in production with unused MongoDB placeholder credential while still rejecting dev Postgres password', () => { + const okResult = runInitInIsolatedSubprocess({ + NODE_ENV: 'production', + POSTGRES_HOST: 'pg.prod.internal', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + POSTGRES_USERNAME: 'prod_user', + POSTGRES_PASSWORD: 'strong_prod_pg_secret_987', + DATABASE_POSTGRES_HOST: 'pg.prod.internal', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_PASSWORD: 'strong_prod_pg_secret_987', + MONGODB_URI: 'mongodb://prod:trading_mongo_dev@mongo.internal:27017/stock?authSource=admin', + DRAGONFLY_PASSWORD: 'strong_prod_redis_secret_987', + }); + + expect(okResult.exitCode).toBe(0); + expect(JSON.parse(okResult.stdout)).toEqual({ + mongoEnabled: false, + targetLabel: 'pg.prod.internal:5432/trading_bot', + }); + + const badPgResult = runInitInIsolatedSubprocess({ + NODE_ENV: 'production', + POSTGRES_HOST: 'pg.prod.internal', + POSTGRES_PORT: '5432', + POSTGRES_DATABASE: 'trading_bot', + POSTGRES_USERNAME: 'prod_user', + POSTGRES_PASSWORD: 'trading_pass_dev', + DATABASE_POSTGRES_HOST: 'pg.prod.internal', + DATABASE_POSTGRES_PORT: '5432', + DATABASE_POSTGRES_DATABASE: 'trading_bot', + DATABASE_POSTGRES_PASSWORD: 'trading_pass_dev', + MONGODB_URI: 'mongodb://prod:trading_mongo_dev@mongo.internal:27017/stock?authSource=admin', + DRAGONFLY_PASSWORD: 'strong_prod_redis_secret_987', + }); + + expect(badPgResult.exitCode).not.toBe(0); + expect(badPgResult.stderr).toMatch(/production PostgreSQL password/i); + }); +}); + +describe('db-migrate CLI subprocess', () => { + test('exits non-zero with valid tracks on stderr for --track bogus without connecting to DB', () => { + const result = Bun.spawnSync( + [process.execPath, 'run', 'scripts/db-migrate.ts', '--track', 'bogus'], + { cwd: root } + ); + expect(result.exitCode).not.toBe(0); + const stderr = new TextDecoder().decode(result.stderr); + expect(stderr).toMatch(/master\|research\|all/); + }); +}); diff --git a/test/postgres/fresh-database-schema.test.ts b/test/postgres/fresh-database-schema.test.ts new file mode 100644 index 00000000..d67a2faf --- /dev/null +++ b/test/postgres/fresh-database-schema.test.ts @@ -0,0 +1,220 @@ +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', +]; + +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', +]; + +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-33 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(33); + + 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 [ + // Master tables (02-05) + 'exchanges', + 'symbols', + 'provider_exchange_mappings', + 'provider_mappings', + 'sync_status', + // Research tables (06-33, including representatives from 12, 16, 20, 22, 28, 30) + 'backtests', + 'backtest_results', + 'runs', + 'backtest_datasets', + 'strategies', + 'research_projects', + 'research_experiments', + 'research_agents', + 'paper_deployments', + ]) { + 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 5 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 [ + 'exchanges', + 'symbols', + 'provider_exchange_mappings', + 'provider_mappings', + 'sync_status', + ]) { + expect(createdTables.has(table)).toBe(true); + } + 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 + 09-33 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]; + 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 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([]); + }); +});