T-36: tests
This commit is contained in:
parent
8326d24957
commit
abf51ad2df
2 changed files with 685 additions and 0 deletions
386
test/postgres/security-master-catalog.test.ts
Normal file
386
test/postgres/security-master-catalog.test.ts
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
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';
|
||||
|
||||
// Verifies the live PostgreSQL catalog produced by the master track (column types, nullability,
|
||||
// PK/FK/UNIQUE definitions) and the implicit behaviours a static read of the DDL can miss.
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('security-master-catalog-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
|
||||
type Column = [name: string, type: string, notNull: boolean];
|
||||
|
||||
const EXPECTED_COLUMNS: Record<string, Column[]> = {
|
||||
exchange: [
|
||||
['mic', 'character varying(10)', true],
|
||||
['operating_mic', 'character varying(10)', true],
|
||||
['name', 'text', true],
|
||||
['country_iso', 'character(2)', true],
|
||||
['currency', 'character(3)', true],
|
||||
['timezone', 'text', true],
|
||||
['calendar_code', 'character varying(16)', true],
|
||||
['board_lot_policy', 'character varying(16)', true],
|
||||
['created_at', 'timestamp with time zone', true],
|
||||
],
|
||||
exchange_source_map: [
|
||||
['source', 'character varying(16)', true],
|
||||
['source_code', 'character varying(32)', true],
|
||||
['role', 'character varying(20)', true],
|
||||
['mic', 'character varying(10)', false],
|
||||
['country_iso', 'character(2)', false],
|
||||
['method', 'character varying(32)', true],
|
||||
['reviewed_by', 'text', false],
|
||||
],
|
||||
instrument: [
|
||||
['instrument_id', 'integer', true],
|
||||
['primary_isin', 'character(12)', false],
|
||||
['primary_cusip', 'character(9)', false],
|
||||
['canonical_name', 'text', true],
|
||||
['security_type', 'character varying(16)', true],
|
||||
['issuer_country', 'character(2)', false],
|
||||
['created_at', 'timestamp with time zone', true],
|
||||
],
|
||||
instrument_identifier_history: [
|
||||
['instrument_id', 'integer', true],
|
||||
['id_type', 'character varying(8)', true],
|
||||
['id_value', 'character varying(16)', true],
|
||||
// Declared nullable in the contract, but PRIMARY KEY membership forces NOT NULL.
|
||||
['valid_from', 'date', true],
|
||||
['valid_to', 'date', false],
|
||||
['source', 'character varying(16)', true],
|
||||
],
|
||||
listing: [
|
||||
['listing_id', 'integer', true],
|
||||
['instrument_id', 'integer', true],
|
||||
['mic', 'character varying(10)', true],
|
||||
['ticker_root', 'character varying(24)', true],
|
||||
['class_suffix', 'character varying(12)', true],
|
||||
['currency', 'character(3)', true],
|
||||
['ib_conid', 'bigint', false],
|
||||
['ib_primary_exchange', 'character varying(16)', false],
|
||||
['listed_from', 'date', false],
|
||||
['listed_to', 'date', false],
|
||||
['delist_reason', 'character varying(24)', false],
|
||||
['terminal_return', 'numeric(10,6)', false],
|
||||
['created_at', 'timestamp with time zone', true],
|
||||
],
|
||||
corporate_action_continuity: [
|
||||
['from_listing_id', 'integer', true],
|
||||
['to_listing_id', 'integer', true],
|
||||
['effective_date', 'date', true],
|
||||
['kind', 'character varying(24)', true],
|
||||
],
|
||||
listing_symbol_history: [
|
||||
['listing_id', 'integer', true],
|
||||
['ticker', 'character varying(32)', true],
|
||||
['valid_from', 'date', true],
|
||||
['valid_to', 'date', false],
|
||||
['source', 'character varying(16)', true],
|
||||
],
|
||||
provider_mapping: [
|
||||
['source', 'character varying(16)', true],
|
||||
['source_id', 'character varying(64)', true],
|
||||
['valid_from', 'date', true],
|
||||
['valid_to', 'date', false],
|
||||
['listing_id', 'integer', true],
|
||||
['method', 'character varying(24)', true],
|
||||
['confidence', 'numeric(4,3)', true],
|
||||
['price_corr', 'numeric(5,4)', false],
|
||||
],
|
||||
resolution_conflict: [
|
||||
['conflict_id', 'integer', true],
|
||||
['source', 'character varying(16)', true],
|
||||
['source_id', 'character varying(64)', true],
|
||||
['conflict_kind', 'character varying(32)', true],
|
||||
['candidate_listing_id', 'integer', false],
|
||||
['existing_listing_id', 'integer', false],
|
||||
['detail', 'jsonb', true],
|
||||
['status', 'character varying(16)', true],
|
||||
['created_at', 'timestamp with time zone', true],
|
||||
['resolved_at', 'timestamp with time zone', false],
|
||||
],
|
||||
override: [
|
||||
['source', 'character varying(16)', true],
|
||||
['source_id', 'character varying(64)', true],
|
||||
['valid_from', 'date', true],
|
||||
['valid_to', 'date', false],
|
||||
['listing_id', 'integer', true],
|
||||
['reason', 'text', true],
|
||||
['created_by', 'text', true],
|
||||
['created_at', 'timestamp with time zone', true],
|
||||
],
|
||||
golden_field_audit: [
|
||||
['audit_id', 'integer', true],
|
||||
['entity_type', 'character varying(16)', true],
|
||||
['entity_id', 'integer', true],
|
||||
['field_name', 'text', true],
|
||||
['chosen_value', 'text', false],
|
||||
['chosen_source', 'character varying(16)', true],
|
||||
['candidates', 'jsonb', true],
|
||||
['decided_at', 'timestamp with time zone', true],
|
||||
],
|
||||
};
|
||||
|
||||
const EXPECTED_KEYS: Record<string, string[]> = {
|
||||
exchange: ['PRIMARY KEY (mic)'],
|
||||
exchange_source_map: [
|
||||
'FOREIGN KEY (mic) REFERENCES exchange(mic)',
|
||||
'PRIMARY KEY (source, source_code)',
|
||||
],
|
||||
instrument: ['PRIMARY KEY (instrument_id)', 'UNIQUE (primary_isin)'],
|
||||
instrument_identifier_history: [
|
||||
'FOREIGN KEY (instrument_id) REFERENCES instrument(instrument_id)',
|
||||
'PRIMARY KEY (id_type, id_value, valid_from)',
|
||||
],
|
||||
listing: [
|
||||
'FOREIGN KEY (instrument_id) REFERENCES instrument(instrument_id)',
|
||||
'FOREIGN KEY (mic) REFERENCES exchange(mic)',
|
||||
'PRIMARY KEY (listing_id)',
|
||||
],
|
||||
corporate_action_continuity: [
|
||||
'FOREIGN KEY (from_listing_id) REFERENCES listing(listing_id)',
|
||||
'FOREIGN KEY (to_listing_id) REFERENCES listing(listing_id)',
|
||||
'PRIMARY KEY (from_listing_id, effective_date)',
|
||||
],
|
||||
listing_symbol_history: [
|
||||
'FOREIGN KEY (listing_id) REFERENCES listing(listing_id)',
|
||||
'PRIMARY KEY (listing_id, ticker, valid_from)',
|
||||
],
|
||||
provider_mapping: [
|
||||
'FOREIGN KEY (listing_id) REFERENCES listing(listing_id)',
|
||||
'PRIMARY KEY (source, source_id, valid_from)',
|
||||
],
|
||||
resolution_conflict: [
|
||||
'FOREIGN KEY (candidate_listing_id) REFERENCES listing(listing_id)',
|
||||
'FOREIGN KEY (existing_listing_id) REFERENCES listing(listing_id)',
|
||||
'PRIMARY KEY (conflict_id)',
|
||||
],
|
||||
override: [
|
||||
'FOREIGN KEY (listing_id) REFERENCES listing(listing_id)',
|
||||
'PRIMARY KEY (source, source_id, valid_from)',
|
||||
],
|
||||
golden_field_audit: ['PRIMARY KEY (audit_id)'],
|
||||
};
|
||||
|
||||
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() }),
|
||||
});
|
||||
await runPostgresMigrations(postgres, { track: 'master' });
|
||||
|
||||
return { pool, schema };
|
||||
}
|
||||
|
||||
async function expectPgErrorCode(operation: Promise<unknown>, expectedCode: string): Promise<void> {
|
||||
let code: string | undefined;
|
||||
try {
|
||||
await operation;
|
||||
} catch (error) {
|
||||
code = (error as { code?: string } | null)?.code ?? 'no-code';
|
||||
}
|
||||
expect(code).toBe(expectedCode);
|
||||
}
|
||||
|
||||
async function seedListing(pool: Pool) {
|
||||
await 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')`
|
||||
);
|
||||
const instrumentId = (
|
||||
await pool.query(
|
||||
`INSERT INTO instrument (canonical_name, security_type)
|
||||
VALUES ('Catalog Test Corp', 'common') RETURNING instrument_id`
|
||||
)
|
||||
).rows[0].instrument_id as number;
|
||||
const listingId = (
|
||||
await pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, currency)
|
||||
VALUES ($1, 'XNYS', 'CAT', 'USD') RETURNING listing_id`,
|
||||
[instrumentId]
|
||||
)
|
||||
).rows[0].listing_id as number;
|
||||
return { instrumentId, listingId };
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('security master PostgreSQL catalog', () => {
|
||||
test('master track creates the 11 tables in the connection schema with contract column types', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const placement = await f.pool.query(
|
||||
`SELECT table_schema, count(*)::int AS n FROM information_schema.tables
|
||||
WHERE table_name = ANY($1) AND table_schema = current_schema()
|
||||
GROUP BY table_schema`,
|
||||
[Object.keys(EXPECTED_COLUMNS)]
|
||||
);
|
||||
expect(placement.rows).toEqual([{ table_schema: f.schema, n: 11 }]);
|
||||
|
||||
for (const [table, expected] of Object.entries(EXPECTED_COLUMNS)) {
|
||||
const actual = (
|
||||
await f.pool.query(
|
||||
`SELECT attname, format_type(atttypid, atttypmod) AS type, attnotnull
|
||||
FROM pg_attribute
|
||||
WHERE attrelid = $1::regclass AND attnum > 0 AND NOT attisdropped
|
||||
ORDER BY attnum`,
|
||||
[table]
|
||||
)
|
||||
).rows.map(row => [row.attname, row.type, row.attnotnull]);
|
||||
expect({ table, columns: actual }).toEqual({ table, columns: expected });
|
||||
}
|
||||
});
|
||||
|
||||
test('PK, FK and UNIQUE constraints match the contract, with no cascading deletes', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
for (const [table, expected] of Object.entries(EXPECTED_KEYS)) {
|
||||
const actual = (
|
||||
await f.pool.query(
|
||||
`SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint
|
||||
WHERE conrelid = $1::regclass AND contype IN ('p', 'f', 'u')`,
|
||||
[table]
|
||||
)
|
||||
).rows
|
||||
.map(row => row.def as string)
|
||||
.sort();
|
||||
expect({ table, keys: actual }).toEqual({ table, keys: [...expected].sort() });
|
||||
}
|
||||
});
|
||||
|
||||
test('identity keys reject caller-supplied ids (GENERATED ALWAYS)', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const { instrumentId } = await seedListing(f.pool);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO instrument (instrument_id, canonical_name, security_type)
|
||||
VALUES (424242, 'Explicit Id', 'common')`
|
||||
),
|
||||
'428C9'
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO listing (listing_id, instrument_id, mic, ticker_root, currency)
|
||||
VALUES (424242, $1, 'XNYS', 'EXP', 'USD')`,
|
||||
[instrumentId]
|
||||
),
|
||||
'428C9'
|
||||
);
|
||||
});
|
||||
|
||||
test('NOT NULL columns reject NULL, including PK-implied instrument_identifier_history.valid_from', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const { instrumentId, listingId } = await seedListing(f.pool);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO instrument_identifier_history (instrument_id, id_type, id_value, valid_from, source)
|
||||
VALUES ($1, 'ISIN', 'US0000000001', NULL, 'ib')`,
|
||||
[instrumentId]
|
||||
),
|
||||
'23502'
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence)
|
||||
VALUES ('eod', 'NULLCONF.US', $1, 'tier1_isin', NULL)`,
|
||||
[listingId]
|
||||
),
|
||||
'23502'
|
||||
);
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO override (source, source_id, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'NULLREASON.US', $1, NULL, 'tester')`,
|
||||
[listingId]
|
||||
),
|
||||
'23502'
|
||||
);
|
||||
});
|
||||
|
||||
test('referenced listings and exchanges cannot be deleted while mappings point at them', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const { listingId } = await seedListing(f.pool);
|
||||
await f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence)
|
||||
VALUES ('eod', 'CAT.US', $1, 'tier1_isin', 1.000)`,
|
||||
[listingId]
|
||||
);
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query('DELETE FROM listing WHERE listing_id = $1', [listingId]),
|
||||
'23503'
|
||||
);
|
||||
await expectPgErrorCode(f.pool.query(`DELETE FROM exchange WHERE mic = 'XNYS'`), '23503');
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM provider_mapping')).rows[0].n).toBe(
|
||||
1
|
||||
);
|
||||
});
|
||||
|
||||
test('confidence is stored at NUMERIC(4,3): 0.9995 rounds to 1.000 and passes the CHECK', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const { listingId } = await seedListing(f.pool);
|
||||
|
||||
const row = (
|
||||
await f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence)
|
||||
VALUES ('eod', 'ROUND.US', $1, 'tier3_ticker_span', 0.9995)
|
||||
RETURNING confidence::text AS confidence`,
|
||||
[listingId]
|
||||
)
|
||||
).rows[0];
|
||||
expect(row.confidence).toBe('1.000');
|
||||
|
||||
await expectPgErrorCode(
|
||||
f.pool.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence)
|
||||
VALUES ('eod', 'ROUND_HI.US', $1, 'tier3_ticker_span', 1.0005)`,
|
||||
[listingId]
|
||||
),
|
||||
'23514'
|
||||
);
|
||||
});
|
||||
|
||||
test('re-running the master track after data exists applies nothing and keeps the rows', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
await seedListing(f.pool);
|
||||
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({ connect: () => f.pool.connect() }),
|
||||
});
|
||||
expect(await runPostgresMigrations(postgres, { track: 'master' })).toEqual([]);
|
||||
expect((await f.pool.query('SELECT count(*)::int AS n FROM listing')).rows[0].n).toBe(1);
|
||||
});
|
||||
});
|
||||
299
test/postgres/security-master-contract.test.ts
Normal file
299
test/postgres/security-master-contract.test.ts
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
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<string, string[]> = {
|
||||
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',
|
||||
'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 <T>(
|
||||
callback: (client: { query: (sql: string, values?: unknown[]) => unknown }) => Promise<T>
|
||||
) =>
|
||||
callback({
|
||||
query: async (sql: string) => {
|
||||
ran.push(sql);
|
||||
return { rows: [] };
|
||||
},
|
||||
}),
|
||||
};
|
||||
return { postgres, ran };
|
||||
}
|
||||
|
||||
async function filesForTrack(track: MigrationTrack): Promise<string[]> {
|
||||
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<string>();
|
||||
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, 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',
|
||||
]);
|
||||
});
|
||||
|
||||
test('research track (web-api startup default) never runs 34-security-master.sql', async () => {
|
||||
const research = await filesForTrack('research');
|
||||
expect(research).not.toContain('34-security-master.sql');
|
||||
expect(research.length).toBeGreaterThan(0);
|
||||
|
||||
const { postgres } = recordingClient();
|
||||
expect(await runPostgresMigrations(postgres as never)).toEqual(research);
|
||||
});
|
||||
|
||||
test('all track runs 34-security-master.sql last, after research 09-33, and skips 06-08', async () => {
|
||||
const all = await filesForTrack('all');
|
||||
expect(all.at(-1)).toBe('34-security-master.sql');
|
||||
expect(all.indexOf('33-candidate-decimal-normalization.sql')).toBe(all.length - 2);
|
||||
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',
|
||||
]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue