T-36: M1.1a — Security master DDL migration (11 tables on the master track)
This commit is contained in:
parent
3e1f108c6f
commit
8326d24957
6 changed files with 914 additions and 27 deletions
152
database/postgres/init/34-security-master.sql
Normal file
152
database/postgres/init/34-security-master.sql
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
-- Security master schema (M1.1a)
|
||||
-- Master track migration: creates the 11 normalized security master tables and
|
||||
-- lookup indexes in the active search_path without modifying legacy tables.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exchange (
|
||||
mic VARCHAR(10) PRIMARY KEY, -- ISO 10383 (e.g. XNYS, XNAS, XTSE, XTSX, XCNQ, NEOE, OTCM)
|
||||
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, -- e.g. 'America/New_York', 'America/Toronto'
|
||||
calendar_code VARCHAR(16) NOT NULL,
|
||||
board_lot_policy VARCHAR(16) NOT NULL DEFAULT 'us_100'
|
||||
CHECK (board_lot_policy IN ('us_100', 'tsx_tiered', 'fx')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exchange_source_map (
|
||||
source VARCHAR(16) NOT NULL, -- 'eod' | 'qm' | 'ib' | 'ceo'
|
||||
source_code VARCHAR(32) NOT NULL,
|
||||
role VARCHAR(20) NOT NULL
|
||||
CHECK (role IN ('primary_venue', 'composite', 'ats_routing', 'forex', 'excluded_fund')),
|
||||
mic VARCHAR(10) REFERENCES exchange(mic),
|
||||
country_iso CHAR(2),
|
||||
method VARCHAR(32) NOT NULL,
|
||||
reviewed_by TEXT,
|
||||
PRIMARY KEY (source, source_code)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS 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
|
||||
CHECK (security_type IN ('common', 'preferred', 'unit', 'warrant', 'right', 'etf', 'cdr', 'fx')),
|
||||
issuer_country CHAR(2),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS instrument_identifier_history (
|
||||
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
|
||||
id_type VARCHAR(8) NOT NULL
|
||||
CHECK (id_type IN ('ISIN', 'CUSIP')),
|
||||
id_value VARCHAR(16) NOT NULL,
|
||||
valid_from DATE,
|
||||
valid_to DATE,
|
||||
source VARCHAR(16) NOT NULL,
|
||||
PRIMARY KEY (id_type, id_value, valid_from)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS 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), -- e.g. 'NYSE', 'NASDAQ', 'TSE', 'VENTURE'
|
||||
listed_from DATE,
|
||||
listed_to DATE,
|
||||
delist_reason VARCHAR(24)
|
||||
CHECK (delist_reason IN ('active', 'merger_cash', 'moved_to_otc', 'bankruptcy_cancelled', 'unknown_involuntary')),
|
||||
terminal_return NUMERIC(10, 6), -- e.g. -0.300000 or -1.000000 when no post-delist OTC bar exists
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS 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
|
||||
CHECK (kind IN ('otc_delist_transfer', 'venue_uplisting', 'reorg_continuation')),
|
||||
PRIMARY KEY (from_listing_id, effective_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS 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)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_mapping (
|
||||
source VARCHAR(16) NOT NULL,
|
||||
source_id VARCHAR(64) NOT NULL, -- eodSearchCode, qmSearchCode, ib conid/id, ceoId
|
||||
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
|
||||
CHECK (method IN ('tier1_isin', 'tier2_cusip', 'tier3_ticker_span', 'tier4_name', 'override')),
|
||||
confidence NUMERIC(4, 3) NOT NULL
|
||||
CHECK (confidence BETWEEN 0 AND 1),
|
||||
price_corr NUMERIC(5, 4),
|
||||
PRIMARY KEY (source, source_id, valid_from)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS resolution_conflict (
|
||||
conflict_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
source VARCHAR(16) NOT NULL,
|
||||
source_id VARCHAR(64) NOT NULL,
|
||||
conflict_kind VARCHAR(32) NOT NULL,
|
||||
candidate_listing_id INTEGER REFERENCES listing(listing_id),
|
||||
existing_listing_id INTEGER REFERENCES listing(listing_id),
|
||||
detail JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'open',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
resolved_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS override (
|
||||
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),
|
||||
reason TEXT NOT NULL,
|
||||
created_by TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (source, source_id, valid_from)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS golden_field_audit (
|
||||
audit_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
entity_type VARCHAR(16) NOT NULL
|
||||
CHECK (entity_type IN ('instrument', 'listing')),
|
||||
entity_id INTEGER NOT NULL,
|
||||
field_name TEXT NOT NULL,
|
||||
chosen_value TEXT,
|
||||
chosen_source VARCHAR(16) NOT NULL,
|
||||
candidates JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
decided_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_listing_instrument_id
|
||||
ON listing (instrument_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_listing_mic_ticker
|
||||
ON listing (mic, ticker_root, class_suffix);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_listing_ib_conid
|
||||
ON listing (ib_conid)
|
||||
WHERE ib_conid IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_mapping_listing_id
|
||||
ON provider_mapping (listing_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_instrument_identifier_history_instrument_id
|
||||
ON instrument_identifier_history (instrument_id);
|
||||
|
|
@ -40,14 +40,16 @@ CREATE TABLE IF NOT EXISTS exchange (
|
|||
currency CHAR(3) NOT NULL,
|
||||
timezone TEXT NOT NULL, -- e.g. 'America/New_York', 'America/Toronto'
|
||||
calendar_code VARCHAR(16) NOT NULL,
|
||||
board_lot_policy VARCHAR(16) NOT NULL DEFAULT 'us_100', -- 'us_100' | 'tsx_tiered' | 'fx'
|
||||
board_lot_policy VARCHAR(16) NOT NULL DEFAULT 'us_100'
|
||||
CHECK (board_lot_policy IN ('us_100', 'tsx_tiered', 'fx')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exchange_source_map (
|
||||
source VARCHAR(16) NOT NULL, -- 'eod' | 'qm' | 'ib' | 'ceo'
|
||||
source_code VARCHAR(32) NOT NULL,
|
||||
role VARCHAR(20) NOT NULL, -- 'primary_venue' | 'composite' | 'ats_routing' | 'forex' | 'excluded_fund'
|
||||
role VARCHAR(20) NOT NULL
|
||||
CHECK (role IN ('primary_venue', 'composite', 'ats_routing', 'forex', 'excluded_fund')),
|
||||
mic VARCHAR(10) REFERENCES exchange(mic),
|
||||
country_iso CHAR(2),
|
||||
method VARCHAR(32) NOT NULL,
|
||||
|
|
@ -60,14 +62,16 @@ CREATE TABLE IF NOT EXISTS instrument (
|
|||
primary_isin CHAR(12) UNIQUE,
|
||||
primary_cusip CHAR(9),
|
||||
canonical_name TEXT NOT NULL,
|
||||
security_type VARCHAR(16) NOT NULL, -- 'common'|'preferred'|'unit'|'warrant'|'right'|'etf'|'cdr'|'fx'
|
||||
security_type VARCHAR(16) NOT NULL
|
||||
CHECK (security_type IN ('common', 'preferred', 'unit', 'warrant', 'right', 'etf', 'cdr', 'fx')),
|
||||
issuer_country CHAR(2),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS instrument_identifier_history (
|
||||
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
|
||||
id_type VARCHAR(8) NOT NULL, -- 'ISIN' | 'CUSIP'
|
||||
id_type VARCHAR(8) NOT NULL
|
||||
CHECK (id_type IN ('ISIN', 'CUSIP')),
|
||||
id_value VARCHAR(16) NOT NULL,
|
||||
valid_from DATE,
|
||||
valid_to DATE,
|
||||
|
|
@ -86,7 +90,8 @@ CREATE TABLE IF NOT EXISTS listing (
|
|||
ib_primary_exchange VARCHAR(16), -- e.g. 'NYSE', 'NASDAQ', 'TSE', 'VENTURE'
|
||||
listed_from DATE,
|
||||
listed_to DATE,
|
||||
delist_reason VARCHAR(24), -- 'active'|'merger_cash'|'moved_to_otc'|'bankruptcy_cancelled'|'unknown_ involuntary'
|
||||
delist_reason VARCHAR(24)
|
||||
CHECK (delist_reason IN ('active', 'merger_cash', 'moved_to_otc', 'bankruptcy_cancelled', 'unknown_involuntary')),
|
||||
terminal_return NUMERIC(10, 6), -- e.g. -0.300000 or -1.000000 when no post-delist OTC bar exists
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
|
@ -95,7 +100,8 @@ CREATE TABLE IF NOT EXISTS 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, -- 'otc_delist_transfer' | 'venue_uplisting' | 'reorg_continuation'
|
||||
kind VARCHAR(24) NOT NULL
|
||||
CHECK (kind IN ('otc_delist_transfer', 'venue_uplisting', 'reorg_continuation')),
|
||||
PRIMARY KEY (from_listing_id, effective_date)
|
||||
);
|
||||
|
||||
|
|
@ -114,14 +120,69 @@ CREATE TABLE IF NOT EXISTS provider_mapping (
|
|||
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, -- 'tier1_isin'|'tier2_cusip'|'tier3_ticker_span'|'tier4_name'|'override'
|
||||
confidence NUMERIC(4, 3) NOT NULL,
|
||||
method VARCHAR(24) NOT NULL
|
||||
CHECK (method IN ('tier1_isin', 'tier2_cusip', 'tier3_ticker_span', 'tier4_name', 'override')),
|
||||
confidence NUMERIC(4, 3) NOT NULL
|
||||
CHECK (confidence BETWEEN 0 AND 1),
|
||||
price_corr NUMERIC(5, 4),
|
||||
PRIMARY KEY (source, source_id, valid_from)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS resolution_conflict (
|
||||
conflict_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
source VARCHAR(16) NOT NULL,
|
||||
source_id VARCHAR(64) NOT NULL,
|
||||
conflict_kind VARCHAR(32) NOT NULL,
|
||||
candidate_listing_id INTEGER REFERENCES listing(listing_id),
|
||||
existing_listing_id INTEGER REFERENCES listing(listing_id),
|
||||
detail JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'open',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
resolved_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS override (
|
||||
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),
|
||||
reason TEXT NOT NULL,
|
||||
created_by TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (source, source_id, valid_from)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS golden_field_audit (
|
||||
audit_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
entity_type VARCHAR(16) NOT NULL
|
||||
CHECK (entity_type IN ('instrument', 'listing')),
|
||||
entity_id INTEGER NOT NULL,
|
||||
field_name TEXT NOT NULL,
|
||||
chosen_value TEXT,
|
||||
chosen_source VARCHAR(16) NOT NULL,
|
||||
candidates JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
decided_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_listing_instrument_id
|
||||
ON listing (instrument_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_listing_mic_ticker
|
||||
ON listing (mic, ticker_root, class_suffix);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_listing_ib_conid
|
||||
ON listing (ib_conid)
|
||||
WHERE ib_conid IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_mapping_listing_id
|
||||
ON provider_mapping (listing_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_instrument_identifier_history_instrument_id
|
||||
ON instrument_identifier_history (instrument_id);
|
||||
```
|
||||
|
||||
Plus `resolution_conflict`, `override` (keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`), and `golden_field_audit`.
|
||||
`override` is keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`. The minimal definitions for `resolution_conflict`, `override`, and `golden_field_audit` above are open to revision as M1 Passes 1–6 are built.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ const MASTER_FILES = new Set([
|
|||
'03-initial-data.sql',
|
||||
'04-provider-exchange-mapping-schema.sql',
|
||||
'05-add-visible-column.sql',
|
||||
'34-security-master.sql',
|
||||
]);
|
||||
|
||||
const RESEARCH_FILES = new Set([
|
||||
|
|
|
|||
|
|
@ -19,6 +19,29 @@ const MASTER_FILES = [
|
|||
'03-initial-data.sql',
|
||||
'04-provider-exchange-mapping-schema.sql',
|
||||
'05-add-visible-column.sql',
|
||||
'34-security-master.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 = [
|
||||
|
|
@ -113,13 +136,13 @@ async function createIsolatedFixture() {
|
|||
}
|
||||
|
||||
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 () => {
|
||||
test('Case A: init SQL 01-34 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);
|
||||
expect(sqlFiles.length).toBeGreaterThanOrEqual(34);
|
||||
|
||||
for (const file of sqlFiles) {
|
||||
const sql = readFileSync(join(initDir, file), 'utf8');
|
||||
|
|
@ -130,12 +153,10 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
|
||||
const createdTables = new Set(await f.tables());
|
||||
for (const expectedTable of [
|
||||
// Master tables (02-05)
|
||||
'exchanges',
|
||||
'symbols',
|
||||
'provider_exchange_mappings',
|
||||
'provider_mappings',
|
||||
'sync_status',
|
||||
// Legacy master tables (02-05)
|
||||
...LEGACY_MASTER_TABLES,
|
||||
// Security master tables (34)
|
||||
...SECURITY_MASTER_TABLES,
|
||||
// Research tables (06-33, including representatives from 12, 16, 20, 22, 28, 30)
|
||||
'backtests',
|
||||
'backtest_results',
|
||||
|
|
@ -155,7 +176,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
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 () => {
|
||||
test('Case B: master track creates master tables, records exact 6 files, and is idempotent', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const first = await runPostgresMigrations(f.postgres, { track: 'master' });
|
||||
|
|
@ -163,13 +184,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
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',
|
||||
]) {
|
||||
for (const table of [...LEGACY_MASTER_TABLES, ...SECURITY_MASTER_TABLES]) {
|
||||
expect(createdTables.has(table)).toBe(true);
|
||||
}
|
||||
expect(await f.hasColumn('exchanges', 'visible')).toBe(true);
|
||||
|
|
@ -186,7 +201,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
await f.pool.query(readFileSync(join(initDir, file), 'utf8'));
|
||||
}
|
||||
|
||||
const expected = [...MASTER_FILES, ...RESEARCH_FILES];
|
||||
const expected = [...MASTER_FILES, ...RESEARCH_FILES].sort();
|
||||
const first = await runPostgresMigrations(f.postgres, { track: 'all' });
|
||||
expect(first).toEqual(expected);
|
||||
|
||||
|
|
@ -196,6 +211,11 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
|||
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);
|
||||
}
|
||||
|
||||
const second = await runPostgresMigrations(f.postgres, { track: 'all' });
|
||||
expect(second).toEqual([]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { afterEach, describe, expect, test } from 'bun:test';
|
|||
import type { PoolClient } from 'pg';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import { runMigrations } from '../../apps/stock/web-api/src/migrations/migration-runner';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
|
@ -133,6 +133,7 @@ async function fixture() {
|
|||
return {
|
||||
queries,
|
||||
run: () => runMigrations({ postgres, logger }),
|
||||
runTrack: (track: 'master' | 'research' | 'all') => runPostgresMigrations(postgres, { track }),
|
||||
};
|
||||
};
|
||||
const recorded = async () =>
|
||||
|
|
@ -365,4 +366,62 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
|
|||
.rows[0].count
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
test('34-security-master.sql is applied on master and all tracks, excluded from research, and idempotent', async () => {
|
||||
const securityMasterTables = [
|
||||
'exchange',
|
||||
'exchange_source_map',
|
||||
'instrument',
|
||||
'instrument_identifier_history',
|
||||
'listing',
|
||||
'corporate_action_continuity',
|
||||
'listing_symbol_history',
|
||||
'provider_mapping',
|
||||
'resolution_conflict',
|
||||
'override',
|
||||
'golden_field_audit',
|
||||
];
|
||||
|
||||
// 1. research track must NOT apply 34-security-master.sql or create any of its 11 tables;
|
||||
// master track applies it and is idempotent on re-run.
|
||||
const f1 = await fixture();
|
||||
const runner1 = f1.startup();
|
||||
const researchApplied = await runner1.runTrack('research');
|
||||
expect(researchApplied).not.toContain('34-security-master.sql');
|
||||
expect(await f1.recorded()).not.toContain('34-security-master.sql');
|
||||
|
||||
const tablesAfterResearch = new Set(await f1.relations());
|
||||
for (const table of securityMasterTables) {
|
||||
expect(tablesAfterResearch.has(table)).toBe(false);
|
||||
}
|
||||
|
||||
const masterApplied = await runner1.runTrack('master');
|
||||
expect(masterApplied).toContain('34-security-master.sql');
|
||||
expect(await f1.recorded()).toContain('34-security-master.sql');
|
||||
|
||||
const tablesAfterMaster = new Set(await f1.relations());
|
||||
for (const table of securityMasterTables) {
|
||||
expect(tablesAfterMaster.has(table)).toBe(true);
|
||||
}
|
||||
|
||||
expect(await runner1.runTrack('master')).toEqual([]);
|
||||
|
||||
// 2. all track applies 34-security-master.sql alongside 01-05 and 09-33 and is idempotent.
|
||||
const f2 = await fixture();
|
||||
const runner2 = f2.startup();
|
||||
const allApplied = await runner2.runTrack('all');
|
||||
expect(allApplied).toContain('01-init-database.sql');
|
||||
expect(allApplied).toContain('05-add-visible-column.sql');
|
||||
expect(allApplied).toContain('09-backtest-run-contract.sql');
|
||||
expect(allApplied).toContain('33-candidate-decimal-normalization.sql');
|
||||
expect(allApplied).toContain('34-security-master.sql');
|
||||
expect(await f2.recorded()).toContain('34-security-master.sql');
|
||||
|
||||
const tablesAfterAll = new Set(await f2.relations());
|
||||
for (const table of securityMasterTables) {
|
||||
expect(tablesAfterAll.has(table)).toBe(true);
|
||||
}
|
||||
|
||||
expect(await runner2.runTrack('all')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
594
test/postgres/security-master-schema.test.ts
Normal file
594
test/postgres/security-master-schema.test.ts
Normal file
|
|
@ -0,0 +1,594 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { readFileSync } from 'node:fs';
|
||||
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('security-master-schema-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const securityMasterSqlPath = fileURLToPath(
|
||||
new URL('../../database/postgres/init/34-security-master.sql', import.meta.url)
|
||||
);
|
||||
|
||||
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 SECURITY_MASTER_INDEXES = [
|
||||
'idx_listing_instrument_id',
|
||||
'idx_listing_mic_ticker',
|
||||
'idx_listing_ib_conid',
|
||||
'idx_provider_mapping_listing_id',
|
||||
'idx_instrument_identifier_history_instrument_id',
|
||||
];
|
||||
|
||||
const cleanup: (() => Promise<void> | 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(),
|
||||
}),
|
||||
});
|
||||
|
||||
await runPostgresMigrations(postgres, { track: 'master' });
|
||||
|
||||
return { pool, schema, postgres };
|
||||
}
|
||||
|
||||
async function expectPgErrorCode(operation: Promise<unknown>, expectedCode: string): Promise<void> {
|
||||
try {
|
||||
await operation;
|
||||
} catch (error) {
|
||||
const code = (error as { code?: string } | null)?.code;
|
||||
expect(code).toBe(expectedCode);
|
||||
return;
|
||||
}
|
||||
throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`);
|
||||
}
|
||||
|
||||
async function seedExchange(
|
||||
pool: Pool,
|
||||
mic: string,
|
||||
overrides: {
|
||||
operatingMic?: string;
|
||||
name?: string;
|
||||
countryIso?: string;
|
||||
currency?: string;
|
||||
timezone?: string;
|
||||
calendarCode?: string;
|
||||
boardLotPolicy?: string;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
await pool.query(
|
||||
`INSERT INTO exchange (
|
||||
mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
[
|
||||
mic,
|
||||
overrides.operatingMic ?? mic,
|
||||
overrides.name ?? `${mic} Exchange`,
|
||||
overrides.countryIso ?? 'US',
|
||||
overrides.currency ?? 'USD',
|
||||
overrides.timezone ?? 'America/New_York',
|
||||
overrides.calendarCode ?? mic,
|
||||
overrides.boardLotPolicy ?? 'us_100',
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('security master PostgreSQL schema', () => {
|
||||
test('creates all 11 tables and 5 lookup indexes and is idempotent on raw SQL re-run', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const tables = new Set(
|
||||
(
|
||||
await f.pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [f.schema])
|
||||
).rows.map(row => row.tablename as string)
|
||||
);
|
||||
for (const table of SECURITY_MASTER_TABLES) {
|
||||
expect(tables.has(table)).toBe(true);
|
||||
}
|
||||
|
||||
const indexes = new Set(
|
||||
(
|
||||
await f.pool.query('SELECT indexname FROM pg_indexes WHERE schemaname = $1', [f.schema])
|
||||
).rows.map(row => row.indexname as string)
|
||||
);
|
||||
for (const index of SECURITY_MASTER_INDEXES) {
|
||||
expect(indexes.has(index)).toBe(true);
|
||||
}
|
||||
|
||||
const rawSql = readFileSync(securityMasterSqlPath, 'utf8');
|
||||
await f.pool.query(rawSql);
|
||||
});
|
||||
|
||||
test('accepts valid insert chain across all 11 tables and populates defaults', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
// 1. exchange (omitting board_lot_policy to verify default 'us_100')
|
||||
const exchangeRow = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code)
|
||||
VALUES ('XNYS', 'XNYS', 'New York Stock Exchange', 'US', 'USD', 'America/New_York', 'XNYS')
|
||||
RETURNING board_lot_policy`
|
||||
)
|
||||
).rows[0];
|
||||
expect(exchangeRow.board_lot_policy).toBe('us_100');
|
||||
|
||||
await seedExchange(f.pool, 'OTCM', { name: 'OTC Markets' });
|
||||
|
||||
// 2. exchange_source_map (primary_venue with mic, and composite with NULL mic)
|
||||
await f.pool.query(
|
||||
`INSERT INTO exchange_source_map (source, source_code, role, mic, country_iso, method)
|
||||
VALUES
|
||||
('eod', 'NYSE', 'primary_venue', 'XNYS', 'US', 'manual_seed'),
|
||||
('eod', 'US', 'composite', NULL, 'US', 'manual_seed')`
|
||||
);
|
||||
|
||||
// 3. instrument
|
||||
const instrumentId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country)
|
||||
VALUES ('US0378331005', '037833100', 'Apple Inc.', 'common', 'US')
|
||||
RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
|
||||
// 4. instrument_identifier_history
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument_identifier_history (instrument_id, id_type, id_value, valid_from, source)
|
||||
VALUES
|
||||
($1, 'ISIN', 'US0378331005', '1980-12-12', 'ib'),
|
||||
($1, 'CUSIP', '037833100', '1980-12-12', 'ib')`,
|
||||
[instrumentId]
|
||||
);
|
||||
|
||||
// 5. listing (omitting class_suffix to verify default ''; testing NULL and 'unknown_involuntary' delist_reason)
|
||||
const primaryListing = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency, ib_conid, ib_primary_exchange, listed_from, delist_reason)
|
||||
VALUES ($1, 'XNYS', 'AAPL', 'USD', 265598, 'NYSE', '1980-12-12', NULL)
|
||||
RETURNING listing_id, class_suffix`,
|
||||
[instrumentId]
|
||||
)
|
||||
).rows[0];
|
||||
const primaryListingId = primaryListing.listing_id as number;
|
||||
expect(primaryListing.class_suffix).toBe('');
|
||||
|
||||
const otcListingId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency, delist_reason, terminal_return)
|
||||
VALUES ($1, 'OTCM', 'AAPLQ', 'USD', 'unknown_involuntary', -0.300000)
|
||||
RETURNING listing_id`,
|
||||
[instrumentId]
|
||||
)
|
||||
).rows[0].listing_id as number;
|
||||
|
||||
// 6. listing_symbol_history
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, source)
|
||||
VALUES ($1, 'AAPL', '1980-12-12', 'eod')`,
|
||||
[primaryListingId]
|
||||
);
|
||||
|
||||
// 7. corporate_action_continuity
|
||||
await f.pool.query(
|
||||
`INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind)
|
||||
VALUES ($1, $2, '2025-01-15', 'otc_delist_transfer')`,
|
||||
[primaryListingId, otcListingId]
|
||||
);
|
||||
|
||||
// 8. provider_mapping (omitting valid_from to verify default '1900-01-01')
|
||||
const mappingRow = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence, price_corr)
|
||||
VALUES ('eod', 'AAPL.US', $1, 'tier1_isin', 1.000, 0.9995)
|
||||
RETURNING to_char(valid_from, 'YYYY-MM-DD') AS valid_from`,
|
||||
[primaryListingId]
|
||||
)
|
||||
).rows[0];
|
||||
expect(mappingRow.valid_from).toBe('1900-01-01');
|
||||
|
||||
// 9. resolution_conflict (omitting detail and status to verify defaults)
|
||||
const conflictRow = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO resolution_conflict (source, source_id, conflict_kind, candidate_listing_id, existing_listing_id)
|
||||
VALUES ('qm', 'AAPL:US', 'ambiguous_ticker', $1, $2)
|
||||
RETURNING detail, status`,
|
||||
[primaryListingId, otcListingId]
|
||||
)
|
||||
).rows[0];
|
||||
expect(conflictRow.detail).toEqual({});
|
||||
expect(conflictRow.status).toBe('open');
|
||||
|
||||
// 10. override (omitting valid_from to verify default '1900-01-01')
|
||||
const overrideRow = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO override (source, source_id, listing_id, reason, created_by)
|
||||
VALUES ('qm', 'AAPL:US', $1, 'Verified against EDGAR CIK', 'operator')
|
||||
RETURNING to_char(valid_from, 'YYYY-MM-DD') AS valid_from`,
|
||||
[primaryListingId]
|
||||
)
|
||||
).rows[0];
|
||||
expect(overrideRow.valid_from).toBe('1900-01-01');
|
||||
|
||||
// 11. golden_field_audit (both 'instrument' and 'listing')
|
||||
const auditRows = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO golden_field_audit (entity_type, entity_id, field_name, chosen_value, chosen_source)
|
||||
VALUES
|
||||
('instrument', $1, 'canonical_name', 'Apple Inc.', 'ib'),
|
||||
('listing', $2, 'ticker_root', 'AAPL', 'eod')
|
||||
RETURNING entity_type, candidates`,
|
||||
[instrumentId, primaryListingId]
|
||||
)
|
||||
).rows;
|
||||
expect(auditRows).toHaveLength(2);
|
||||
expect(auditRows[0].candidates).toEqual({});
|
||||
expect(auditRows[1].candidates).toEqual({});
|
||||
});
|
||||
|
||||
test('rejects foreign key violations (23503)', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await seedExchange(f.pool, 'XNYS');
|
||||
const instrumentId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (canonical_name, security_type)
|
||||
VALUES ('Test Corp', 'common')
|
||||
RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency)
|
||||
VALUES ($1, 'NOPE', 'TEST', 'USD')`,
|
||||
[instrumentId]
|
||||
),
|
||||
'23503'
|
||||
);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency)
|
||||
VALUES (999999, 'XNYS', 'TEST', 'USD')`
|
||||
),
|
||||
'23503'
|
||||
);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence)
|
||||
VALUES ('eod', 'TEST.US', 999999, 'tier3_ticker_span', 0.850)`
|
||||
),
|
||||
'23503'
|
||||
);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO override (source, source_id, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'TEST.US', 999999, 'Invalid listing test', 'tester')`
|
||||
),
|
||||
'23503'
|
||||
);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO resolution_conflict (source, source_id, conflict_kind, candidate_listing_id)
|
||||
VALUES ('eod', 'TEST.US', 'missing_listing', 999999)`
|
||||
),
|
||||
'23503'
|
||||
);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO resolution_conflict (source, source_id, conflict_kind, existing_listing_id)
|
||||
VALUES ('eod', 'TEST.US', 'missing_listing', 999999)`
|
||||
),
|
||||
'23503'
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects unique and primary key violations (23505) while allowing distinct dates and NULL ISINs', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await seedExchange(f.pool, 'XNYS');
|
||||
|
||||
const instrumentId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (primary_isin, canonical_name, security_type)
|
||||
VALUES ('US5949181045', 'Microsoft Corp', 'common')
|
||||
RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
|
||||
// Duplicate primary_isin rejected
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO instrument (primary_isin, canonical_name, security_type)
|
||||
VALUES ('US5949181045', 'Microsoft Duplicate', 'common')`
|
||||
),
|
||||
'23505'
|
||||
);
|
||||
|
||||
// Multiple NULL primary_isin instruments allowed
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (primary_isin, canonical_name, security_type)
|
||||
VALUES
|
||||
(NULL, 'Unlisted Co A', 'common'),
|
||||
(NULL, 'Unlisted Co B', 'common')`
|
||||
);
|
||||
|
||||
const listingId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency)
|
||||
VALUES ($1, 'XNYS', 'MSFT', 'USD')
|
||||
RETURNING listing_id`,
|
||||
[instrumentId]
|
||||
)
|
||||
).rows[0].listing_id as number;
|
||||
|
||||
// Duplicate provider_mapping PK rejected; distinct valid_from allowed
|
||||
await f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence)
|
||||
VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'tier1_isin', 1.000)`,
|
||||
[listingId]
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence)
|
||||
VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'tier2_cusip', 0.950)`,
|
||||
[listingId]
|
||||
),
|
||||
'23505'
|
||||
);
|
||||
await f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence)
|
||||
VALUES ('eod', 'MSFT.US', '2020-01-01', $1, 'tier1_isin', 1.000)`,
|
||||
[listingId]
|
||||
);
|
||||
|
||||
// Duplicate override PK rejected; distinct valid_from allowed
|
||||
await f.pool.query(
|
||||
`INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'Initial override', 'tester')`,
|
||||
[listingId]
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'Duplicate override', 'tester')`,
|
||||
[listingId]
|
||||
),
|
||||
'23505'
|
||||
);
|
||||
await f.pool.query(
|
||||
`INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'MSFT.US', '2020-01-01', $1, 'Later override', 'tester')`,
|
||||
[listingId]
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects CHECK constraint violations (23514) and accepts valid boundary values', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await seedExchange(f.pool, 'XNYS');
|
||||
const instrumentId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (canonical_name, security_type)
|
||||
VALUES ('Check Test Corp', 'common')
|
||||
RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
const listingId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency)
|
||||
VALUES ($1, 'XNYS', 'CHK', 'USD')
|
||||
RETURNING listing_id`,
|
||||
[instrumentId]
|
||||
)
|
||||
).rows[0].listing_id as number;
|
||||
|
||||
// exchange.board_lot_policy
|
||||
await expectPgErrorCode(seedExchange(f.pool, 'XBAD', { boardLotPolicy: 'odd_lot' }), '23514');
|
||||
|
||||
// exchange_source_map.role
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO exchange_source_map (source, source_code, role, mic, method)
|
||||
VALUES ('eod', 'BAD', 'not_a_role', 'XNYS', 'manual')`
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
|
||||
// instrument.security_type
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO instrument (canonical_name, security_type)
|
||||
VALUES ('Bad Type', 'crypto')`
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
|
||||
// instrument_identifier_history.id_type
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO instrument_identifier_history (instrument_id, id_type, id_value, valid_from, source)
|
||||
VALUES ($1, 'SEDOL', '2046251', '2020-01-01', 'ib')`,
|
||||
[instrumentId]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
|
||||
// listing.delist_reason: old stray-space typo must fail; 'unknown_involuntary' and NULL succeed
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency, delist_reason)
|
||||
VALUES ($1, 'XNYS', 'TYPO', 'USD', 'unknown_ involuntary')`,
|
||||
[instrumentId]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency, delist_reason)
|
||||
VALUES
|
||||
($1, 'XNYS', 'OK1', 'USD', 'unknown_involuntary'),
|
||||
($1, 'XNYS', 'OK2', 'USD', NULL)`,
|
||||
[instrumentId]
|
||||
);
|
||||
|
||||
// corporate_action_continuity.kind
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind)
|
||||
VALUES ($1, $1, '2024-01-01', 'reverse_split')`,
|
||||
[listingId]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
|
||||
// provider_mapping.method
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence)
|
||||
VALUES ('eod', 'CHK.US', $1, 'tier5_guess', 0.500)`,
|
||||
[listingId]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
|
||||
// provider_mapping.confidence out of [0, 1] fails; 0 and 1 succeed
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence)
|
||||
VALUES ('eod', 'CHK_HI', '2020-01-01', $1, 'tier1_isin', 1.500)`,
|
||||
[listingId]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence)
|
||||
VALUES ('eod', 'CHK_LO', '2020-01-01', $1, 'tier1_isin', -0.001)`,
|
||||
[listingId]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
await f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence)
|
||||
VALUES
|
||||
('eod', 'CHK_ZERO', '2020-01-01', $1, 'tier4_name', 0.000),
|
||||
('eod', 'CHK_ONE', '2020-01-01', $1, 'override', 1.000)`,
|
||||
[listingId]
|
||||
);
|
||||
|
||||
// golden_field_audit.entity_type
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO golden_field_audit (entity_type, entity_id, field_name, chosen_value, chosen_source)
|
||||
VALUES ('exchange', 1, 'name', 'NYSE', 'manual')`
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
});
|
||||
|
||||
test('allows interlisted listings on different mics and ticker reuse across distinct instruments', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await seedExchange(f.pool, 'XTSE', {
|
||||
name: 'Toronto Stock Exchange',
|
||||
countryIso: 'CA',
|
||||
currency: 'CAD',
|
||||
timezone: 'America/Toronto',
|
||||
boardLotPolicy: 'tsx_tiered',
|
||||
});
|
||||
await seedExchange(f.pool, 'XNYS');
|
||||
await seedExchange(f.pool, 'XNAS', { name: 'NASDAQ' });
|
||||
|
||||
// Interlisted Shopify: one instrument, two listings on XTSE (CAD) and XNYS (USD)
|
||||
const shopInstrumentId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (primary_isin, canonical_name, security_type, issuer_country)
|
||||
VALUES ('CA82509L1076', 'Shopify Inc.', 'common', 'CA')
|
||||
RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
|
||||
const shopListings = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency)
|
||||
VALUES
|
||||
($1, 'XTSE', 'SHOP', 'CAD'),
|
||||
($1, 'XNYS', 'SHOP', 'USD')
|
||||
RETURNING listing_id, mic, currency`,
|
||||
[shopInstrumentId]
|
||||
)
|
||||
).rows;
|
||||
expect(shopListings).toHaveLength(2);
|
||||
|
||||
// Ticker reuse across distinct instruments: Meta Platforms (2012-2022 FB) vs ProShares ETF (2025 FB)
|
||||
const metaInstrumentId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (canonical_name, security_type, issuer_country)
|
||||
VALUES ('Meta Platforms Inc.', 'common', 'US')
|
||||
RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
const fbEtfInstrumentId = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO instrument (canonical_name, security_type, issuer_country)
|
||||
VALUES ('ProShares FB ETF', 'etf', 'US')
|
||||
RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
|
||||
const fbListings = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency, listed_from, listed_to)
|
||||
VALUES
|
||||
($1, 'XNAS', 'FB', '', 'USD', '2012-05-18', '2022-06-08'),
|
||||
($2, 'XNAS', 'FB', '', 'USD', '2025-01-10', NULL)
|
||||
RETURNING listing_id, instrument_id`,
|
||||
[metaInstrumentId, fbEtfInstrumentId]
|
||||
)
|
||||
).rows;
|
||||
expect(fbListings).toHaveLength(2);
|
||||
expect(fbListings[0].instrument_id).not.toBe(fbListings[1].instrument_id);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue