T-78: M1.1j — Persist Pass 3/5/6 results into the security master: idempotent PostgreSQL loader with permanent listing_ids and override precedence
This commit is contained in:
parent
7a8e83d22c
commit
d65d3f00d5
5 changed files with 3248 additions and 0 deletions
634
test/unit/security-master-persist.test.ts
Normal file
634
test/unit/security-master-persist.test.ts
Normal file
|
|
@ -0,0 +1,634 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
canonicalizeJsonValue,
|
||||
DEFAULT_VALID_FROM,
|
||||
formatListingNaturalKey,
|
||||
MAX_PERSIST_CHUNK_SIZE,
|
||||
persistSecurityMaster,
|
||||
PROVIDER_MAPPING_CONFIDENCE,
|
||||
SECURITY_MASTER_PERSIST_LOCK_NAMESPACE,
|
||||
stableJsonStringify,
|
||||
type DelistingChainResult,
|
||||
type PersistSecurityMasterInput,
|
||||
type SecurityMasterQueryable,
|
||||
type SecurityMasterQueryResult,
|
||||
type SecurityType,
|
||||
type StageAMatchResult,
|
||||
type StageBMatchResult,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
|
||||
interface RecordedQuery {
|
||||
text: string;
|
||||
values: readonly unknown[] | undefined;
|
||||
}
|
||||
|
||||
function emptyStageA(): StageAMatchResult {
|
||||
return {
|
||||
instruments: [],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalInputRecords: 0,
|
||||
totalInstruments: 0,
|
||||
bySource: {
|
||||
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function emptyStageB(): StageBMatchResult {
|
||||
return {
|
||||
listings: [],
|
||||
providerMappings: [],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalListings: 0,
|
||||
totalProviderMappings: 0,
|
||||
listingsWithIbConid: 0,
|
||||
excludedFunds: 0,
|
||||
bySource: {
|
||||
eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createMockClient(
|
||||
handler?: (
|
||||
text: string,
|
||||
values: readonly unknown[] | undefined,
|
||||
index: number
|
||||
) => SecurityMasterQueryResult | Promise<SecurityMasterQueryResult>
|
||||
): { client: SecurityMasterQueryable; queries: RecordedQuery[] } {
|
||||
const queries: RecordedQuery[] = [];
|
||||
let nextInstrumentId = 100;
|
||||
let nextListingId = 1000;
|
||||
|
||||
const client: SecurityMasterQueryable = {
|
||||
release: () => undefined,
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
values?: readonly unknown[]
|
||||
): Promise<SecurityMasterQueryResult<Row>> {
|
||||
const index = queries.length;
|
||||
queries.push({ text, values });
|
||||
if (handler) {
|
||||
return (await handler(text, values, index)) as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
|
||||
if (text.startsWith('SELECT mic FROM exchange')) {
|
||||
return {
|
||||
rows: [{ mic: 'XNAS' }, { mic: 'XNYS' }, { mic: 'XTSE' }, { mic: 'OTCM' }],
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument (')) {
|
||||
const isins = (values?.[0] as string[]) ?? [];
|
||||
return {
|
||||
rows: isins.map(isin => ({
|
||||
instrument_id: nextInstrumentId++,
|
||||
primary_isin: isin,
|
||||
})),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.startsWith('INSERT INTO instrument_identifier_history')) {
|
||||
const ids = (values?.[0] as number[]) ?? [];
|
||||
return {
|
||||
rows: ids.map(() => ({ inserted: 1 })),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.startsWith('INSERT INTO listing (')) {
|
||||
const instrumentIds = (values?.[0] as number[]) ?? [];
|
||||
const mics = (values?.[1] as string[]) ?? [];
|
||||
const roots = (values?.[2] as string[]) ?? [];
|
||||
const suffixes = (values?.[3] as string[]) ?? [];
|
||||
const currencies = (values?.[4] as string[]) ?? [];
|
||||
return {
|
||||
rows: instrumentIds.map((instrumentId, i) => ({
|
||||
listing_id: nextListingId++,
|
||||
instrument_id: instrumentId,
|
||||
mic: mics[i],
|
||||
ticker_root: roots[i],
|
||||
class_suffix: suffixes[i],
|
||||
currency: currencies[i],
|
||||
})),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (
|
||||
text.startsWith('INSERT INTO listing_symbol_history') ||
|
||||
text.startsWith('INSERT INTO provider_mapping') ||
|
||||
text.startsWith('INSERT INTO corporate_action_continuity')
|
||||
) {
|
||||
const firstCol = (values?.[0] as unknown[]) ?? [];
|
||||
return {
|
||||
rows: firstCol.map(() => ({ inserted: true })),
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
if (text.includes('WITH enforced AS')) {
|
||||
return {
|
||||
rows: [{ total_overrides: 0, inserted_overrides: 0, updated_overrides: 0 }],
|
||||
} as unknown as SecurityMasterQueryResult<Row>;
|
||||
}
|
||||
return { rows: [] } as SecurityMasterQueryResult<Row>;
|
||||
},
|
||||
};
|
||||
|
||||
return { client, queries };
|
||||
}
|
||||
|
||||
describe('persistSecurityMaster unit tests', () => {
|
||||
test('rejects a pg.Pool-shaped object and non-queryable inputs', async () => {
|
||||
const fakePool = {
|
||||
totalCount: 1,
|
||||
idleCount: 1,
|
||||
waitingCount: 0,
|
||||
query: async () => ({ rows: [] }),
|
||||
} as unknown as SecurityMasterQueryable;
|
||||
|
||||
const emptyInput: PersistSecurityMasterInput = {
|
||||
stageA: emptyStageA(),
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map(),
|
||||
};
|
||||
|
||||
await expect(persistSecurityMaster(fakePool, emptyInput)).rejects.toThrow(/PoolClient/);
|
||||
await expect(
|
||||
persistSecurityMaster(null as unknown as SecurityMasterQueryable, emptyInput)
|
||||
).rejects.toThrow(/query\(\)/);
|
||||
});
|
||||
|
||||
test('validates chunkSize bounds', async () => {
|
||||
const { client } = createMockClient();
|
||||
const emptyInput: PersistSecurityMasterInput = {
|
||||
stageA: emptyStageA(),
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map(),
|
||||
};
|
||||
|
||||
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 0 })).rejects.toThrow(
|
||||
RangeError
|
||||
);
|
||||
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: -5 })).rejects.toThrow(
|
||||
RangeError
|
||||
);
|
||||
await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 1.5 })).rejects.toThrow(
|
||||
RangeError
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, emptyInput, { chunkSize: MAX_PERSIST_CHUNK_SIZE + 1 })
|
||||
).rejects.toThrow(RangeError);
|
||||
});
|
||||
|
||||
test('empty input fast path runs only BEGIN, advisory lock, override CTE, and COMMIT', async () => {
|
||||
const { client, queries } = createMockClient();
|
||||
const result = await persistSecurityMaster(client, {
|
||||
stageA: emptyStageA(),
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map(),
|
||||
});
|
||||
|
||||
expect(queries.map(q => q.text.trim().split('\n')[0])).toEqual([
|
||||
'BEGIN',
|
||||
'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))',
|
||||
'WITH enforced AS (',
|
||||
'COMMIT',
|
||||
]);
|
||||
expect(queries[1]?.values).toEqual([SECURITY_MASTER_PERSIST_LOCK_NAMESPACE]);
|
||||
expect(result.instrumentsInserted).toBe(0);
|
||||
expect(result.listingsInserted).toBe(0);
|
||||
expect(result.providerMappingsInserted).toBe(0);
|
||||
expect(result.overridesApplied).toBe(0);
|
||||
});
|
||||
|
||||
test('parameterizes all SQL values and never interpolates untrusted strings into SQL text', async () => {
|
||||
const { client, queries } = createMockClient();
|
||||
const hostileName = "O'Brien Corp; DROP TABLE instrument; --";
|
||||
const hostileSourceId = "BAD'ID;DELETE";
|
||||
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: hostileName,
|
||||
members: [{ source: 'ib', sourceId: hostileSourceId, currency: 'USD', method: 'tier1_isin' }],
|
||||
});
|
||||
stageA.conflicts.push({
|
||||
source: 'eod',
|
||||
sourceId: hostileSourceId,
|
||||
conflictKind: 'isin_cusip_mismatch',
|
||||
detail: {
|
||||
isin: 'US0378331005',
|
||||
cusip: '037833100',
|
||||
country: 'US',
|
||||
derivedIsin: null,
|
||||
},
|
||||
});
|
||||
|
||||
const stageB = emptyStageB();
|
||||
const key = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
stageB.listings.push({
|
||||
...key,
|
||||
ibConid: 265598,
|
||||
ibPrimaryExchange: 'NASDAQ',
|
||||
listedFrom: '1980-12-12',
|
||||
listedTo: null,
|
||||
});
|
||||
stageB.providerMappings.push({
|
||||
source: 'ib',
|
||||
sourceId: hostileSourceId,
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
});
|
||||
|
||||
await persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB,
|
||||
securityTypeByIsin: new Map<string, SecurityType>([['US0378331005', 'common']]),
|
||||
});
|
||||
|
||||
for (const q of queries) {
|
||||
expect(q.text).not.toContain(hostileName);
|
||||
expect(q.text).not.toContain(hostileSourceId);
|
||||
expect(q.text).not.toContain('US0378331005');
|
||||
}
|
||||
|
||||
const mappingInsert = queries.find(q => q.text.startsWith('INSERT INTO provider_mapping'));
|
||||
expect(mappingInsert?.values?.[2]).toEqual([DEFAULT_VALID_FROM]);
|
||||
expect(mappingInsert?.values?.[6]).toEqual([
|
||||
PROVIDER_MAPPING_CONFIDENCE.tier1_isin.toFixed(3),
|
||||
]);
|
||||
});
|
||||
|
||||
test('statement count scales with O(ceil(N / chunkSize)) rather than O(N)', async () => {
|
||||
const count = 600;
|
||||
const chunkSize = 200;
|
||||
const stageA = emptyStageA();
|
||||
const stageB = emptyStageB();
|
||||
const securityTypeByIsin = new Map<string, SecurityType>();
|
||||
|
||||
for (let i = 0; i < count; i++) {
|
||||
const isin = `US${String(i).padStart(9, '0')}0`;
|
||||
const cusip = String(i).padStart(9, '0');
|
||||
stageA.instruments.push({
|
||||
primaryIsin: isin,
|
||||
primaryCusip: cusip,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: `Corp ${i}`,
|
||||
members: [{ source: 'eod', sourceId: `T${i}.US`, currency: 'USD', method: 'tier1_isin' }],
|
||||
});
|
||||
securityTypeByIsin.set(isin, 'common');
|
||||
const key = {
|
||||
primaryIsin: isin,
|
||||
mic: 'XNAS',
|
||||
tickerRoot: `T${i}`,
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
stageB.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: '2020-01-01',
|
||||
listedTo: null,
|
||||
});
|
||||
stageB.providerMappings.push({
|
||||
source: 'eod',
|
||||
sourceId: `T${i}.US`,
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
});
|
||||
stageB.providerMappings.push({
|
||||
source: 'qm',
|
||||
sourceId: `T${i}:US`,
|
||||
listingKey: key,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: '2020-01-01',
|
||||
validTo: null,
|
||||
});
|
||||
}
|
||||
|
||||
const { client, queries } = createMockClient();
|
||||
const result = await persistSecurityMaster(
|
||||
client,
|
||||
{ stageA, stageB, securityTypeByIsin },
|
||||
{ chunkSize }
|
||||
);
|
||||
|
||||
expect(result.instrumentsInserted).toBe(count);
|
||||
expect(result.listingsInserted).toBe(count);
|
||||
expect(result.providerMappingsInserted).toBe(count * 2);
|
||||
// 3 chunks for instruments (select+insert), 6 for id_history (ISIN+CUSIP),
|
||||
// 1 exchange select, 3+3+3 for listings (select+insert+symbol_history),
|
||||
// 6 for provider_mapping, plus BEGIN/lock/override/COMMIT = 31 queries total << 600 rows.
|
||||
expect(queries.length).toBeLessThan(40);
|
||||
});
|
||||
|
||||
test('canonicalizes JSONB keys deterministically regardless of property insertion order', () => {
|
||||
const a = { z: 1, a: { d: 2, b: [3, undefined, { y: true, x: false }] }, dropMe: undefined };
|
||||
const b = { a: { b: [3, null, { x: false, y: true }], d: 2 }, z: 1 };
|
||||
|
||||
expect(stableJsonStringify(a)).toBe(stableJsonStringify(b));
|
||||
expect(canonicalizeJsonValue(Number.NaN)).toBeNull();
|
||||
});
|
||||
|
||||
test('selects best member source for instrument_identifier_history (tier1_isin > tier2_cusip, ib > eod)', async () => {
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push(
|
||||
{
|
||||
primaryIsin: 'US0000000010',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Tier1 IB wins over EOD',
|
||||
members: [
|
||||
{ source: 'eod', sourceId: 'A.US', currency: 'USD', method: 'tier1_isin' },
|
||||
{ source: 'ib', sourceId: '1', currency: 'USD', method: 'tier1_isin' },
|
||||
],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US0000000020',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Tier1 EOD wins over Tier2 IB',
|
||||
members: [
|
||||
{ source: 'ib', sourceId: '2', currency: 'USD', method: 'tier2_cusip' },
|
||||
{ source: 'eod', sourceId: 'B.US', currency: 'USD', method: 'tier1_isin' },
|
||||
],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US0000000030',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Empty members falls back to eod',
|
||||
members: [],
|
||||
}
|
||||
);
|
||||
|
||||
const { client, queries } = createMockClient();
|
||||
await persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map<string, SecurityType>([
|
||||
['US0000000010', 'common'],
|
||||
['US0000000020', 'common'],
|
||||
['US0000000030', 'common'],
|
||||
]),
|
||||
});
|
||||
|
||||
const idHistoryQuery = queries.find(q =>
|
||||
q.text.startsWith('INSERT INTO instrument_identifier_history')
|
||||
);
|
||||
expect(idHistoryQuery?.values?.[4]).toEqual(['ib', 'eod', 'eod']);
|
||||
});
|
||||
|
||||
test('rejects duplicate input natural keys and duplicate DB listing rows', async () => {
|
||||
const { client } = createMockClient();
|
||||
|
||||
// 1. Duplicate primaryIsin
|
||||
const dupIsin = emptyStageA();
|
||||
dupIsin.instruments.push(
|
||||
{
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple',
|
||||
members: [],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Dup',
|
||||
members: [],
|
||||
}
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA: dupIsin,
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate primaryIsin/);
|
||||
|
||||
// 2. Duplicate listing natural key
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple',
|
||||
members: [],
|
||||
});
|
||||
const dupListing = emptyStageB();
|
||||
const key = {
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
};
|
||||
dupListing.listings.push(
|
||||
{ ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: null, listedTo: null },
|
||||
{ ...key, ibConid: 1, ibPrimaryExchange: 'NASDAQ', listedFrom: null, listedTo: null }
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: dupListing,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate listing natural key/);
|
||||
|
||||
// 3. Duplicate provider_mapping PK
|
||||
const dupMapping = emptyStageB();
|
||||
dupMapping.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: null,
|
||||
listedTo: null,
|
||||
});
|
||||
dupMapping.providerMappings.push(
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: null,
|
||||
validTo: null,
|
||||
},
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'AAPL.US',
|
||||
listingKey: key,
|
||||
method: 'tier1_isin',
|
||||
validFrom: DEFAULT_VALID_FROM,
|
||||
validTo: null,
|
||||
}
|
||||
);
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: dupMapping,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate provider_mapping primary key/);
|
||||
|
||||
// 4. Duplicate Pass 6 listing outcome
|
||||
const dupPass6: DelistingChainResult = {
|
||||
continuities: [],
|
||||
listingOutcomes: [
|
||||
{ listingKey: key, delistReason: 'active', terminalReturn: null },
|
||||
{ listingKey: key, delistReason: 'unknown_involuntary', terminalReturn: -0.3 },
|
||||
],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalInputListings: 1,
|
||||
processedListings: 1,
|
||||
skippedMalformedEntries: 0,
|
||||
skippedInvalidDates: 0,
|
||||
skippedDuplicateKeys: 0,
|
||||
continuitiesCreated: 0,
|
||||
conflictsDetected: 0,
|
||||
byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 0 },
|
||||
},
|
||||
};
|
||||
const singleStageB = emptyStageB();
|
||||
singleStageB.listings.push({
|
||||
...key,
|
||||
ibConid: null,
|
||||
ibPrimaryExchange: null,
|
||||
listedFrom: null,
|
||||
listedTo: null,
|
||||
});
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: singleStageB,
|
||||
pass6: dupPass6,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/Duplicate listing outcome key/);
|
||||
|
||||
// 5. Duplicate existing DB listing rows for incoming natural key
|
||||
const { client: dupDbClient, queries: dupDbQueries } = createMockClient(text => {
|
||||
if (text.startsWith('SELECT') && text.includes('FROM instrument')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
instrument_id: 7,
|
||||
primary_isin: 'US0378331005',
|
||||
primary_cusip: '037833100',
|
||||
canonical_name: 'Apple',
|
||||
security_type: 'common',
|
||||
issuer_country: 'US',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (text.startsWith('SELECT mic FROM exchange')) {
|
||||
return { rows: [{ mic: 'XNAS' }] };
|
||||
}
|
||||
if (text.startsWith('SELECT') && text.includes('FROM listing')) {
|
||||
return {
|
||||
rows: [
|
||||
{
|
||||
listing_id: 1,
|
||||
instrument_id: 7,
|
||||
mic: 'XNAS',
|
||||
ticker_root: 'AAPL',
|
||||
class_suffix: '',
|
||||
currency: 'USD',
|
||||
ib_conid: null,
|
||||
ib_primary_exchange: null,
|
||||
listed_from: null,
|
||||
listed_to: null,
|
||||
delist_reason: null,
|
||||
terminal_return: null,
|
||||
},
|
||||
{
|
||||
listing_id: 2,
|
||||
instrument_id: 7,
|
||||
mic: 'XNAS',
|
||||
ticker_root: 'AAPL',
|
||||
class_suffix: '',
|
||||
currency: 'USD',
|
||||
ib_conid: null,
|
||||
ib_primary_exchange: null,
|
||||
listed_from: '2020-01-01',
|
||||
listed_to: null,
|
||||
delist_reason: null,
|
||||
terminal_return: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
await expect(
|
||||
persistSecurityMaster(dupDbClient, {
|
||||
stageA,
|
||||
stageB: singleStageB,
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toThrow(/duplicate rows for natural key/);
|
||||
expect(dupDbQueries.at(-1)?.text).toBe('ROLLBACK');
|
||||
});
|
||||
|
||||
test('executes ROLLBACK and rethrows original error on mid-run failure (even if ROLLBACK fails)', async () => {
|
||||
const boom = new Error('injected check violation');
|
||||
const { client, queries } = createMockClient(text => {
|
||||
if (text.startsWith('INSERT INTO instrument (')) {
|
||||
throw boom;
|
||||
}
|
||||
if (text === 'ROLLBACK') {
|
||||
throw new Error('rollback also failed');
|
||||
}
|
||||
return { rows: [] };
|
||||
});
|
||||
|
||||
const stageA = emptyStageA();
|
||||
stageA.instruments.push({
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Inc.',
|
||||
members: [],
|
||||
});
|
||||
|
||||
await expect(
|
||||
persistSecurityMaster(client, {
|
||||
stageA,
|
||||
stageB: emptyStageB(),
|
||||
securityTypeByIsin: new Map([['US0378331005', 'common']]),
|
||||
})
|
||||
).rejects.toBe(boom);
|
||||
|
||||
expect(queries.some(q => q.text === 'BEGIN')).toBe(true);
|
||||
expect(queries.some(q => q.text === 'ROLLBACK')).toBe(true);
|
||||
expect(queries.some(q => q.text === 'COMMIT')).toBe(false);
|
||||
expect(formatListingNaturalKey({
|
||||
primaryIsin: 'US0378331005',
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
classSuffix: '',
|
||||
currency: 'USD',
|
||||
})).toBe('US0378331005\u0000XNAS\u0000AAPL\u0000\u0000USD');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue