import { readdirSync, readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; import { setLoggerConfig } from '@stock-bot/logger'; import { runPostgresMigrations, type MigrationTrack } from '@stock-bot/postgres'; // Static contract checks for 34-security-master.sql. These need no database, so they run in the // sandbox as well as in Studio's unsandboxed run. setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); const sqlPath = `${initDir}34-security-master.sql`; const docPath = fileURLToPath(new URL('../../design/DATA-CONTRACTS.md', import.meta.url)); const TABLES_IN_DEPENDENCY_ORDER = [ 'exchange', 'exchange_source_map', 'instrument', 'instrument_identifier_history', 'listing', 'corporate_action_continuity', 'listing_symbol_history', 'provider_mapping', 'resolution_conflict', 'override', 'golden_field_audit', ]; // Column lines of the first 8 tables, frozen from design/DATA-CONTRACTS.md §2 as it stood before // T-36 (comments stripped). The migration may only add CHECK constraints on continuation lines. const ORIGINAL_CONTRACT_COLUMNS: Record = { exchange: [ 'mic VARCHAR(10) PRIMARY KEY', 'operating_mic VARCHAR(10) NOT NULL', 'name TEXT NOT NULL', 'country_iso CHAR(2) NOT NULL', 'currency CHAR(3) NOT NULL', 'timezone TEXT NOT NULL', 'calendar_code VARCHAR(16) NOT NULL', "board_lot_policy VARCHAR(16) NOT NULL DEFAULT 'us_100'", 'created_at TIMESTAMPTZ NOT NULL DEFAULT now()', ], exchange_source_map: [ 'source VARCHAR(16) NOT NULL', 'source_code VARCHAR(32) NOT NULL', 'role VARCHAR(20) NOT NULL', 'mic VARCHAR(10) REFERENCES exchange(mic)', 'country_iso CHAR(2)', 'method VARCHAR(32) NOT NULL', 'reviewed_by TEXT', 'PRIMARY KEY (source, source_code)', ], instrument: [ 'instrument_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY', 'primary_isin CHAR(12) UNIQUE', 'primary_cusip CHAR(9)', 'canonical_name TEXT NOT NULL', 'security_type VARCHAR(16) NOT NULL', 'issuer_country CHAR(2)', 'created_at TIMESTAMPTZ NOT NULL DEFAULT now()', ], instrument_identifier_history: [ 'instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id)', 'id_type VARCHAR(8) NOT NULL', 'id_value VARCHAR(16) NOT NULL', 'valid_from DATE NOT NULL', 'valid_to DATE', 'source VARCHAR(16) NOT NULL', 'PRIMARY KEY (id_type, id_value, valid_from)', ], listing: [ 'listing_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY', 'instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id)', 'mic VARCHAR(10) NOT NULL REFERENCES exchange(mic)', 'ticker_root VARCHAR(24) NOT NULL', "class_suffix VARCHAR(12) NOT NULL DEFAULT ''", 'currency CHAR(3) NOT NULL', 'ib_conid BIGINT', 'ib_primary_exchange VARCHAR(16)', 'listed_from DATE', 'listed_to DATE', 'delist_reason VARCHAR(24)', 'terminal_return NUMERIC(10, 6)', 'created_at TIMESTAMPTZ NOT NULL DEFAULT now()', ], corporate_action_continuity: [ 'from_listing_id INTEGER NOT NULL REFERENCES listing(listing_id)', 'to_listing_id INTEGER NOT NULL REFERENCES listing(listing_id)', 'effective_date DATE NOT NULL', 'kind VARCHAR(24) NOT NULL', 'PRIMARY KEY (from_listing_id, effective_date)', ], listing_symbol_history: [ 'listing_id INTEGER NOT NULL REFERENCES listing(listing_id)', 'ticker VARCHAR(32) NOT NULL', 'valid_from DATE NOT NULL', 'valid_to DATE', 'source VARCHAR(16) NOT NULL', 'PRIMARY KEY (listing_id, ticker, valid_from)', ], provider_mapping: [ 'source VARCHAR(16) NOT NULL', 'source_id VARCHAR(64) NOT NULL', "valid_from DATE NOT NULL DEFAULT '1900-01-01'", 'valid_to DATE', 'listing_id INTEGER NOT NULL REFERENCES listing(listing_id)', 'method VARCHAR(24) NOT NULL', 'confidence NUMERIC(4, 3) NOT NULL', 'price_corr NUMERIC(5, 4)', 'PRIMARY KEY (source, source_id, valid_from)', ], }; const readSql = () => readFileSync(sqlPath, 'utf8'); function stripComments(sql: string): string { return sql .split('\n') .map(line => line.replace(/--.*$/, '').trimEnd()) .join('\n'); } // Returns the column/constraint lines of a CREATE TABLE body, excluding CHECK continuation lines. function tableDefinitionLines(sql: string, table: string): string[] { const match = new RegExp(`CREATE TABLE IF NOT EXISTS ${table} \\(\\n([\\s\\S]*?)\\n\\);`).exec( stripComments(sql) ); if (!match?.[1]) { throw new Error(`CREATE TABLE ${table} not found`); } return match[1] .split('\n') .map(line => line.trim().replace(/,$/, '').replace(/\s+/g, ' ')) .filter(line => line.length > 0 && !line.startsWith('CHECK (')); } function securityMasterDocBlock(): string { const doc = readFileSync(docPath, 'utf8'); const tableStart = doc.indexOf('CREATE TABLE IF NOT EXISTS exchange ('); expect(tableStart).toBeGreaterThan(-1); const fenceStart = doc.lastIndexOf('```sql', tableStart); const fenceEnd = doc.indexOf('```', tableStart); return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim(); } function recordingClient() { const ran: string[] = []; const postgres = { transaction: async ( callback: (client: { query: (sql: string, values?: unknown[]) => unknown }) => Promise ) => callback({ query: async (sql: string) => { ran.push(sql); return { rows: [] }; }, }), }; return { postgres, ran }; } async function filesForTrack(track: MigrationTrack): Promise { const { postgres } = recordingClient(); return runPostgresMigrations(postgres as never, { track }); } describe('34-security-master.sql static contract', () => { test('creates exactly the 11 security master tables in dependency order with IF NOT EXISTS', () => { const sql = stripComments(readSql()); const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)]; expect(created.map(m => m[2])).toEqual(TABLES_IN_DEPENDENCY_ORDER); expect(created.every(m => m[1] !== undefined)).toBe(true); // Each FK target must already be created earlier in the file. const createdSoFar = new Set(); for (const table of TABLES_IN_DEPENDENCY_ORDER) { for (const ref of tableDefinitionLines(sql, table) .join('\n') .matchAll(/REFERENCES (\w+)\(/g)) { expect(createdSoFar.has(ref[1]!)).toBe(true); } createdSoFar.add(table); } }); test('creates the 5 lookup indexes with IF NOT EXISTS on the expected columns', () => { const sql = stripComments(readSql()).replace(/\s+/g, ' '); const indexes = [...sql.matchAll(/CREATE INDEX (IF NOT EXISTS )?(\w+) ON ([^;]+);/g)]; expect(indexes.every(m => m[1] !== undefined)).toBe(true); expect(Object.fromEntries(indexes.map(m => [m[2], m[3]!.trim()]))).toEqual({ idx_listing_instrument_id: 'listing (instrument_id)', idx_listing_mic_ticker: 'listing (mic, ticker_root, class_suffix)', idx_listing_ib_conid: 'listing (ib_conid) WHERE ib_conid IS NOT NULL', idx_provider_mapping_listing_id: 'provider_mapping (listing_id)', idx_instrument_identifier_history_instrument_id: 'instrument_identifier_history (instrument_id)', }); }); test('contains no CREATE DATABASE, \\c, schema qualifiers, data, or legacy-table statements', () => { const sql = stripComments(readSql()); expect(sql).not.toMatch(/CREATE\s+DATABASE/i); expect(sql).not.toMatch(/^\s*\\c\b/m); expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|REFERENCES|ON)\s+"?\w+"?\."?\w+/i); expect(sql).not.toMatch(/\b(?:INSERT|UPDATE|DELETE|DROP|ALTER|TRUNCATE|SET\s+search_path)\b/i); expect(sql).not.toMatch( /\b(?:exchanges|symbols|provider_mappings|provider_exchange_mappings|sync_status)\b/ ); }); test('first 8 tables keep the original contract columns, types, defaults, PKs and FKs', () => { const sql = readSql(); for (const [table, columns] of Object.entries(ORIGINAL_CONTRACT_COLUMNS)) { expect({ table, columns: tableDefinitionLines(sql, table) }).toEqual({ table, columns }); } }); test('CHECK constraints list the contract enums, with unknown_involuntary typo fixed', () => { const sql = stripComments(readSql()).replace(/\s+/g, ' '); for (const check of [ "CHECK (board_lot_policy IN ('us_100', 'tsx_tiered', 'fx'))", "CHECK (role IN ('primary_venue', 'composite', 'ats_routing', 'forex', 'excluded_fund'))", "CHECK (security_type IN ('common', 'preferred', 'unit', 'warrant', 'right', 'etf', 'cdr', 'fx'))", "CHECK (id_type IN ('ISIN', 'CUSIP'))", "CHECK (delist_reason IN ('active', 'merger_cash', 'moved_to_otc', 'bankruptcy_cancelled', 'unknown_involuntary'))", "CHECK (kind IN ('otc_delist_transfer', 'venue_uplisting', 'reorg_continuation'))", "CHECK (method IN ('tier1_isin', 'tier2_cusip', 'tier3_ticker_span', 'tier4_name', 'override'))", 'CHECK (confidence BETWEEN 0 AND 1)', "CHECK (entity_type IN ('instrument', 'listing'))", ]) { expect(sql).toContain(check); } expect(readSql()).not.toContain('unknown_ involuntary'); expect(readFileSync(docPath, 'utf8')).not.toContain('unknown_ involuntary'); }); test('open-to-revision tables keep conflict_kind and status free of enum CHECKs', () => { const lines = tableDefinitionLines(readSql(), 'resolution_conflict'); expect(lines).toContain('conflict_kind VARCHAR(32) NOT NULL'); expect(lines).toContain("status VARCHAR(16) NOT NULL DEFAULT 'open'"); const block = /CREATE TABLE IF NOT EXISTS resolution_conflict \(([\s\S]*?)\);/.exec(readSql()); expect(block?.[1]).not.toContain('CHECK'); }); test('DATA-CONTRACTS.md §2 SQL block is identical to the migration body', () => { const sql = readSql(); const body = sql.slice(sql.indexOf('CREATE TABLE')).trim(); expect(securityMasterDocBlock()).toBe(body); }); }); describe('34-security-master.sql track registration', () => { test('master track runs 01-05 then 34-35, and nothing else', async () => { expect(await filesForTrack('master')).toEqual([ '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', ]); }); test('research track (web-api startup default) never runs 34-security-master.sql or 35-security-master-exchange-seed.sql', async () => { const research = await filesForTrack('research'); expect(research).not.toContain('34-security-master.sql'); expect(research).not.toContain('35-security-master-exchange-seed.sql'); expect(research.length).toBeGreaterThan(0); const { postgres } = recordingClient(); expect(await runPostgresMigrations(postgres as never)).toEqual(research); }); test('all track runs 33, 34, 35, 36 last in exact order and skips 06-08', async () => { const all = await filesForTrack('all'); expect(all.at(-4)).toBe('33-candidate-decimal-normalization.sql'); expect(all.at(-3)).toBe('34-security-master.sql'); expect(all.at(-2)).toBe('35-security-master-exchange-seed.sql'); expect(all.at(-1)).toBe('36-trial-ledger.sql'); for (const bootstrap of [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', '08-create-runs-table.sql', ]) { expect(all).not.toContain(bootstrap); } }); test('every init SQL file is either on a track or a known bootstrap script', async () => { const all = new Set(await filesForTrack('all')); const unassigned = readdirSync(initDir) .filter(file => file.endsWith('.sql') && !all.has(file)) .sort(); expect(unassigned).toEqual([ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', '08-create-runs-table.sql', ]); }); });