diff --git a/package-lock.json b/package-lock.json index 4a8cc9ef..00e3ee80 100644 --- a/package-lock.json +++ b/package-lock.json @@ -72,7 +72,8 @@ "node": ">=24" }, "optionalDependencies": { - "koffi": "^3.3.6" + "koffi": "^3.3.6", + "roaring": "^2.7.0" } }, "node_modules/@babel/code-frame": { @@ -1874,6 +1875,78 @@ "integrity": "sha512-BqzK8+iHqxUbPRZV6NBum63CJzE0G6vGG3o+4dqeIzbywdoTg+xHJbksYDkk1P1w3Gj64U20Rgp44HHciLbRzg==", "license": "MIT" }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-2.0.3.tgz", + "integrity": "sha512-uwPAhccfFJlsfCxMYTwOdVfOz3xqyj8xYL3zJj8f0pb30tLohnnFPhLuqp4/qoEz8sNxe4SESZedcBojRefIzg==", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "consola": "^3.2.3", + "detect-libc": "^2.0.0", + "https-proxy-agent": "^7.0.5", + "node-fetch": "^2.6.7", + "nopt": "^8.0.0", + "semver": "^7.5.3", + "tar": "^7.4.0" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/abbrev": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-3.0.1.tgz", + "integrity": "sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg==", + "license": "ISC", + "optional": true, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", + "optional": true, + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/nopt": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-8.1.0.tgz", + "integrity": "sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A==", + "license": "ISC", + "optional": true, + "dependencies": { + "abbrev": "^3.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, "node_modules/@mixmark-io/domino": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz", @@ -4132,6 +4205,16 @@ "dev": true, "license": "MIT" }, + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "license": "MIT", + "optional": true, + "engines": { + "node": "^14.18.0 || >=16.10.0" + } + }, "node_modules/content-disposition": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", @@ -7698,6 +7781,52 @@ "node": ">=20" } }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "license": "MIT", + "optional": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch/node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", + "license": "MIT", + "optional": true + }, + "node_modules/node-fetch/node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", + "license": "BSD-2-Clause", + "optional": true + }, + "node_modules/node-fetch/node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "license": "MIT", + "optional": true, + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, "node_modules/node-gyp": { "version": "12.4.0", "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-12.4.0.tgz", @@ -8797,6 +8926,31 @@ "node": ">=0.10.0" } }, + "node_modules/roaring": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/roaring/-/roaring-2.7.0.tgz", + "integrity": "sha512-gNVeV5H+xb2DB/umdvlPbTrKuCn8zexy6ROkfPL4FcSWxOGWrxfQz0pZeZER+kQLrSoPcz3BolYPM6eFYm96XQ==", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^2.0.3" + }, + "engines": { + "node": ">=18.20.8" + }, + "optionalDependencies": { + "node-gyp": "^12.1.0" + }, + "peerDependencies": { + "node-gyp": "^12.1.0" + }, + "peerDependenciesMeta": { + "node-gyp": { + "optional": true + } + } + }, "node_modules/router": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", diff --git a/package.json b/package.json index 41412a9e..8717fe02 100644 --- a/package.json +++ b/package.json @@ -74,7 +74,8 @@ "yaml": "^2.8.2" }, "optionalDependencies": { - "koffi": "^3.3.6" + "koffi": "^3.3.6", + "roaring": "^2.7.0" }, "devDependencies": { "@types/jest": "^30.0.0", diff --git a/tests/tx/expand-process-selection.test.js b/tests/tx/expand-process-selection.test.js index 0e5cb687..ad8030fd 100644 --- a/tests/tx/expand-process-selection.test.js +++ b/tests/tx/expand-process-selection.test.js @@ -102,7 +102,7 @@ describe('$expand: handing a whole compose to the provider (processSelection)', for (const code of page) { set.add(this.codeSystem.getConceptByCode(code)); } - const total = behaviour === 'no-total' ? -1 : behaviour === 'large' ? 1000000 : all.length; + const total = behaviour === 'no-total' ? -1 : behaviour === 'large' ? 1000000 : behaviour === 'huge' ? 1000001 : all.length; return { sets: [set], total }; })); }, 60000); @@ -231,7 +231,8 @@ describe('$expand: handing a whole compose to the provider (processSelection)', const vs = await expand(app, valueSet({ include: [wholeSystem] }), [{ name: 'limit', valueInteger: 5 }, { name: 'count', valueInteger: 3 }]); expect(codesOf(vs)).toEqual(codes.slice(0, 3)); - expect(vs.expansion.total).toBe(1000000); + // no total: the selection is over the limit, and a paged walk reports none then (#finishIfPageFilled) + expect(vs.expansion.total).toBeUndefined(); }); test('a deep page is not refused: only the page counts against the limit', async () => { @@ -239,9 +240,29 @@ describe('$expand: handing a whole compose to the provider (processSelection)', const vs = await expand(app, valueSet({ include: [wholeSystem] }), [{ name: 'limit', valueInteger: 5 }, { name: 'offset', valueInteger: 4 }, { name: 'count', valueInteger: 3 }]); expect(codesOf(vs)).toEqual(codes.slice(4, 7)); + expect(vs.expansion.total).toBeUndefined(); + }); + + test('a page past the last code: the total, as the walk counts every code when its page never fills', async () => { + behaviour = 'large'; + const vs = await expand(app, valueSet({ include: [wholeSystem] }), + [{ name: 'limit', valueInteger: 5 }, { name: 'offset', valueInteger: 1000000 }, { name: 'count', valueInteger: 3 }]); + expect(codesOf(vs)).toEqual([]); expect(vs.expansion.total).toBe(1000000); }); + test('count=0 of a filter over the walk limit: too costly, as the usual path\'s counting walk; the whole system is counted', async () => { + behaviour = 'huge'; + const filtered = valueSet({ include: [{ system: CS_URL, filter: [{ property: 'group', op: '=', value: 'x' }] }] }); + const res = await request(app).post('/tx/r5/ValueSet/$expand').set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [{ name: 'tx-resource', resource: CS }, { name: 'valueSet', resource: filtered }, + { name: 'count', valueInteger: 0 }] }); + expect(res.status).toBe(422); + expect(res.body.issue[0].details.text).toContain('>1000000'); + const vs = await expand(app, valueSet({ include: [wholeSystem] }), [{ name: 'count', valueInteger: 0 }]); + expect(vs.expansion.total).toBe(1000001); + }); + test('the requested properties are on each code the provider selected', async () => { const vs = await expand(app, valueSet({ include: [wholeSystem] }), [{ name: 'property', valueString: 'grade' }, { name: 'count', valueInteger: 4 }]); @@ -262,6 +283,36 @@ describe('$expand: handing a whole compose to the provider (processSelection)', expect(codesOf(res.body)).toEqual(['c03', 'c04']); }); + // a value set that names a supplement no code system takes (replay: a Belgian SNOMED CT + // supplement for http://snomed.info/sct/11000172109, which no loaded edition is): the usual path + // reports it missing only when its walk gets to the end of the compose; a paged walk that stops + // with the expansion finished (#finishIfPageFilled) never checks. Handed over, the same answer + test.each([ + ['unpaged', [wholeSystem], [], [], 'handle', 422], + ['a full page, the rest over the limit', [wholeSystem], [], [{ name: 'limit', valueInteger: 5 }, { name: 'count', valueInteger: 3 }], 'large', 200], + ['a full page within the limit (the walk takes the size as the total)', [wholeSystem], [], [{ name: 'count', valueInteger: 3 }], 'handle', 200], + ['the last page, exactly full', [wholeSystem], [], [{ name: 'offset', valueInteger: 9 }, { name: 'count', valueInteger: 3 }], 'handle', 200], + ['a page that is never filled', [wholeSystem], [], [{ name: 'count', valueInteger: 50 }], 'handle', 422], + ['a full page within the limit, with an exclude (the walk counts to the end)', [wholeSystem], [excludeTwo], [{ name: 'count', valueInteger: 3 }], 'handle', 422] + ])('a required supplement that is not there, %s: the usual path\'s status and codes', async (_label, include, exclude, extra, handled, status) => { + const vs = valueSet({ include, exclude }); + vs.extension = [{ url: 'http://hl7.org/fhir/StructureDefinition/valueset-supplement', valueCanonical: 'http://example.org/fhir/CodeSystem/no-such-supplement' }]; + const run = async () => request(app).post('/tx/r5/ValueSet/$expand').set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [{ name: 'tx-resource', resource: CS }, { name: 'valueSet', resource: vs }, ...extra] }); + behaviour = 'off'; + const usual = await run(); + behaviour = handled; + const res = await run(); + expect(calls).toHaveLength(1); + expect(usual.status).toBe(status); + expect(res.status).toBe(status); + if (status === 200) { + expect(codesOf(res.body)).toEqual(codesOf(usual.body)); + } else { + expect(res.body.issue[0].details.text).toBe(usual.body.issue[0].details.text); + } + }); + test.each([ ['a text filter', { include: [wholeSystem] }, [{ name: 'filter', valueString: 'c03' }]], ['an enumerated concept list', { include: [{ system: CS_URL, concept: [{ code: 'c03' }, { code: 'c04' }] }] }, []], diff --git a/tests/tx/library-sqlite-v2.test.js b/tests/tx/library-sqlite-v2.test.js new file mode 100644 index 00000000..4d172eea --- /dev/null +++ b/tests/tx/library-sqlite-v2.test.js @@ -0,0 +1,91 @@ +'use strict'; + +// Library: SNOMED CT, LOINC and RxNorm from sqlite-v2 files (snomed-v2:, loinc-v2:, rxnorm-v2: +// source lines). The test file is a SNOMED CT edition built from the RF2 in tx/data/snomed. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { Library } = require('../../tx/library'); +const folders = require('../../library/folder-setup'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +// the terminology-cache name records the file format: a file of an earlier format is not reused +const NAME = 'library-sqlite-v2-tx1-test.db'; + +const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); + +// one snapshot from the test RF2's modules (as tests/tx/sqlite-v2-sct-lookup.test.js) +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +let tmpDir; + +beforeAll(async () => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lib-sqlite-v2-')); + const target = path.join(folders.subDir('terminology-cache'), NAME); + if (!fs.existsSync(target)) { + mergeSnapshot(SRC, path.join(tmpDir, 'Snapshot')); + const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); + await importSnomedV2({ source: path.join(tmpDir, 'Snapshot'), dest: path.join(tmpDir, NAME), edition: '31000003106', version: '20250909', + versionUri: 'http://snomed.info/xsct/31000003106/version/20250909', overwrite: true, log: () => {} }); + fs.copyFileSync(path.join(tmpDir, NAME), target); + } +}); + +afterAll(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +async function load(lines) { + const yamlPath = path.join(tmpDir, 'library.yml'); + fs.writeFileSync(yamlPath, 'base:\n url: https://storage.googleapis.com/tx-fhir-org\nsources:\n' + lines.map(l => ` - ${l}\n`).join('')); + const log = { info: jest.fn(), error: jest.fn(), warn: jest.fn(), debug: jest.fn() }; + const library = new Library(yamlPath, undefined, log, { addStat: jest.fn() }); + await library.load(); + return library; +} + +describe('Library: sqlite-v2 source lines', () => { + test('a library without sqlite-v2 lines loads neither the engine nor roaring', () => { + // in a fresh process: this file's own setup has loaded the importer + const yamlPath = path.join(tmpDir, 'plain.yml'); + fs.writeFileSync(yamlPath, 'base:\n url: https://storage.googleapis.com/tx-fhir-org\nsources:\n - internal:lang\n'); + const script = ` + const { Library } = require(${JSON.stringify(path.resolve(__dirname, '../../tx/library'))}); + const log = { info() {}, error() {}, warn() {}, debug() {} }; + new Library(${JSON.stringify(yamlPath)}, undefined, log, { addStat() {} }).load().then(() => { + const loaded = Object.keys(require.cache).filter(f => f.includes('sqlite-v2') || f.includes('roaring')); + process.stdout.write(JSON.stringify(loaded)); + process.exit(0); + }, (e) => { console.error(e); process.exit(1); });`; + const r = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8', timeout: 60000 }); + expect(r.status).toBe(0); + expect(JSON.parse(r.stdout.trim().split('\n').pop())).toEqual([]); + }); + + test('snomed-v2! registers the file\'s factory as the default SNOMED CT', async () => { + const library = await load([`snomed-v2!:${NAME}`]); + const factory = library.codeSystemFactories.get('http://snomed.info/sct'); + expect(factory.constructor.name).toBe('SnomedV2Factory'); + expect(library.codeSystemFactories.get('http://snomed.info/sct|' + factory.version())).toBe(factory); + }); + + test('a file that holds another code system than the type names stops the load', async () => { + await expect(load([`loinc-v2:${NAME}`])).rejects.toThrow(/holds http:\/\/snomed.info\/sct, not http:\/\/loinc.org/); + }); +}); diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js new file mode 100644 index 00000000..ac1ed66a --- /dev/null +++ b/tests/tx/sqlite-v2-builder.test.js @@ -0,0 +1,395 @@ +'use strict'; + +// The terminology file builder (tx/importers/sqlite-v2/builder.js) and index builder (indexes.js) +// on a small fixture: numbering invariants, items above concepts, the catalog's computed fields, +// stored sets equal to membership recomputed from the facts, the derived display rank, identifiers +// accepted as codes, and the format checks a reader makes before it reads a table. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { RoaringBitmap32 } = require('roaring'); +const { TerminologyBuilder, FORMAT } = require('../../tx/importers/sqlite-v2/builder'); +const { buildIndexes } = require('../../tx/importers/sqlite-v2/indexes'); +const { numberConcepts } = require('../../tx/importers/sqlite-v2/numbering'); +const { SET_KIND } = require('../../tx/importers/sqlite-v2/sets'); +const { openStore } = require('../../tx/sqlite-v2/store'); + +let dir; +beforeAll(() => { dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-')); }); +afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + +// root +// ├── B ── D ─┬─ F +// │ └─ G (also under E: polyhierarchy) +// ├── C ── E ─── G +// │ └──── H (inactive child of active E) +// └── Z (code sorts last, has no children) +// X: inactive, retired; Y: active, no links at all; Q: inactive parent of active R +// R: active, child of inactive Q only; S1: a reference set (record relation) with three members +function buildFixture(dest, { explicitPairs = null } = {}) { + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); + const isa = b.property({ code: 'isa', shape: 'link', subsumption: true }); + const colour = b.property({ code: 'colour', shape: 'literal', fhirType: 'string' }); + const size = b.property({ code: 'size', shape: 'literal', fhirType: 'integer' }); + const site = b.property({ code: 'site', shape: 'link' }); + const note = b.property({ code: 'note', shape: 'literal', fhirType: 'string', filterable: false }); + const inactive = new Set(['H', 'X', 'Q']); + const c = {}; + for (const code of ['X', 'G', 'F', 'Z', 'E', 'D', 'C', 'B', 'root', 'Y', 'H', 'Q', 'R', 'S1']) { + c[code] = b.concept(code, { active: !inactive.has(code), display: `display ${code}` }); + } + const edges = [['B', 'root'], ['C', 'root'], ['Z', 'root'], ['D', 'B'], ['F', 'D'], ['G', 'D'], ['E', 'C'], + ['G', 'E'], ['H', 'E'], ['R', 'Q'], ['S1', 'root']]; + for (const [ch, pa] of edges) b.link(c[ch], isa, c[pa]); + b.link(c.F, isa, c.Z, { active: false }); // history only: not an edge + b.link(c.F, site, c.Y, { group: 1 }); + b.link(c.G, site, c.Y, { group: 2 }); + b.link(c.G, site, c.Y, { group: 3 }); + b.link(c.E, site, c.Z, { active: false }); + b.literal(c.F, colour, 'red'); + b.literal(c.G, colour, 'red'); + b.literal(c.D, colour, 'blue'); + b.literal(c.D, size, '1'); + b.literal(c.E, size, 1); + b.literal(c.X, colour, 'red', { active: false }); + b.literal(c.F, note, 'a note'); + const s1 = b.property({ code: 'S1', shape: 'record', concept: c.S1, fields: [{ name: 'target', type: 's' }] }); + b.record(s1, c.F, { fields: [null] }); + b.record(s1, c.X, { fields: [null] }); + b.record(s1, c.G, { fields: ['T1'] }); + b.item(c.F, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'eff', preferred: true }); + if (explicitPairs) { + const anc = b.property({ code: 'ancestor', shape: 'link', filterable: false }); + b.setClosureFrom(isa, anc); + for (const [d, a] of explicitPairs) b.link(c[d], anc, c[a]); + } + const summary = b.finish(); + return { summary, db: new Database(dest, { readonly: true }) }; +} + +function sets(db) { + const m = new Map(); + for (const r of db.prepare('SELECT kind, property_id, value, card, data FROM ix_set').all()) { + const bm = RoaringBitmap32.deserialize(r.data, 'portable'); + expect(bm.size).toBe(r.card); + m.set(`${r.kind}|${r.property_id}|${typeof r.value}|${r.value}`, Array.from(bm)); + } + return m; +} +const ids = (db, codes) => codes.map(code => db.prepare('SELECT id FROM concept WHERE code = ?').pluck().get(code)).sort((a, b) => a - b); +const pid = (db, code) => db.prepare('SELECT id FROM property WHERE code = ?').pluck().get(code); + +describe('sqlite-v2 numbering', () => { + test('topological, depth-first, children in code order, active prefix', () => { + const codes = ['r', 'a', 'b', 'c', 'x']; + // r -> a, r -> b, a -> c, b -> c ; x inactive + const r = numberConcepts({ + codes, active: Uint8Array.from([1, 1, 1, 1, 0]), + childOf: Int32Array.from([1, 2, 3, 3]), parentOf: Int32Array.from([0, 0, 1, 2]), + }); + expect(Array.from(r.order).map(i => codes[i])).toEqual(['r', 'a', 'b', 'c', 'x']); + expect(r.activeCount).toBe(4); + }); + + test('sort key orders roots and siblings before code', () => { + const codes = ['a', 'b', 'c']; + const r = numberConcepts({ codes, active: Uint8Array.from([1, 1, 1]), childOf: new Int32Array(0), + parentOf: new Int32Array(0), sortKey: Float64Array.from([2, 1, 1]) }); + expect(Array.from(r.order).map(i => codes[i])).toEqual(['b', 'c', 'a']); + }); +}); + +describe('sqlite-v2 terminology file builder', () => { + let db, summary, S; + beforeAll(() => { + ({ db, summary } = buildFixture(path.join(dir, 'fixture.db'))); + S = sets(db); + }); + afterAll(() => db.close()); + + test('active concepts are exactly the prefix 1..active_count; items above every concept', () => { + const cs = db.prepare('SELECT concept_count, active_count FROM code_system WHERE served = 1').get(); + expect(cs).toEqual({ concept_count: 14, active_count: 11 }); + const rows = db.prepare('SELECT id, active FROM concept ORDER BY id').all(); + rows.forEach(r => expect(r.active).toBe(r.id <= cs.active_count ? 1 : 0)); + expect(S.get(`${SET_KIND.active}|0|number|0`)).toEqual(rows.filter(r => r.active).map(r => r.id)); + expect(S.get(`${SET_KIND.all}|0|number|0`)).toEqual(rows.map(r => r.id)); + expect(db.prepare('SELECT min(id) FROM item').pluck().get()).toBe(15); + }); + + test('depth-first order: subtrees follow their root; polyhierarchy child after its last parent', () => { + const order = db.prepare('SELECT code FROM concept ORDER BY id').all().map(r => r.code); + // R's only parent is inactive, so R is a root among the active concepts. + // Roots in code order (R, Y, root); G waits for its second parent E. + expect(order).toEqual(['R', 'Y', 'root', 'B', 'D', 'F', 'C', 'E', 'G', 'S1', 'Z', 'H', 'Q', 'X']); + }); + + test('the catalog\'s computed fields: rows, subject and target kinds, by_target for the hierarchy', () => { + const row = (code) => db.prepare('SELECT shape, subject_kind, target_kind, n_rows, by_target, filterable FROM property WHERE code = ?').get(code); + expect(row('isa')).toEqual({ shape: 'link', subject_kind: 'concept', target_kind: 'concept', n_rows: 12, by_target: 1, filterable: 1 }); + expect(row('colour')).toEqual({ shape: 'literal', subject_kind: 'concept', target_kind: null, n_rows: 4, by_target: 0, filterable: 1 }); + expect(row('S1')).toEqual({ shape: 'record', subject_kind: 'concept', target_kind: null, n_rows: 3, by_target: 0, filterable: 1 }); + }); + + test('descendant sets equal the closure recomputed with a recursive CTE', () => { + const anchors = db.prepare('SELECT id FROM concept').pluck().all(); + const stmt = db.prepare(`WITH RECURSIVE d(id) AS ( + SELECT subject_id FROM link l JOIN property p ON p.id = l.property_id + WHERE p.subsumption = 1 AND l.active = 1 AND l.target_id = ? + UNION SELECT l.subject_id FROM link l JOIN property p ON p.id = l.property_id JOIN d ON l.target_id = d.id + WHERE p.subsumption = 1 AND l.active = 1) + SELECT id FROM d ORDER BY id`); + let stored = 0; + for (const a of anchors) { + const expected = stmt.pluck().all(a); + const got = S.get(`${SET_KIND.descendants}|0|number|${a}`) || []; + expect(got).toEqual(expected); + if (expected.length) stored++; + } + expect(stored).toBe(summary.indexes.sets.descendants.sets); + // spot check: G is under both D and E; the inactive history link F -> Z is not an edge + expect(S.get(`${SET_KIND.descendants}|0|number|${ids(db, ['E'])[0]}`)).toEqual(ids(db, ['G', 'H'])); + expect(S.get(`${SET_KIND.descendants}|0|number|${ids(db, ['Z'])[0]}`)).toBeUndefined(); + }); + + test('leaf = active concepts without descendants', () => { + expect(S.get(`${SET_KIND.leaf}|0|number|0`)).toEqual(ids(db, ['F', 'G', 'R', 'S1', 'Y', 'Z'])); + }); + + test('prop sets (filterable properties only) and has-property sets equal the active fact rows', () => { + const site = pid(db, 'site'), colour = pid(db, 'colour'), size = pid(db, 'size'), note = pid(db, 'note'); + const [y] = ids(db, ['Y']); + expect(S.get(`${SET_KIND.prop}|${site}|number|${y}`)).toEqual(ids(db, ['F', 'G'])); + expect(S.get(`${SET_KIND.prop}|${colour}|string|red`)).toEqual(ids(db, ['F', 'G'])); + expect(S.get(`${SET_KIND.prop}|${colour}|string|blue`)).toEqual(ids(db, ['D'])); + expect(S.get(`${SET_KIND.prop}|${size}|number|1`)).toEqual(ids(db, ['D', 'E'])); // '1' and 1 coerced to integer + expect(S.get(`${SET_KIND.hasProp}|${colour}|number|0`)).toEqual(ids(db, ['D', 'F', 'G'])); + expect(S.get(`${SET_KIND.hasProp}|${site}|number|0`)).toEqual(ids(db, ['F', 'G'])); + // a property no filter can name has its has-property set and no property = value sets + expect(S.get(`${SET_KIND.prop}|${note}|string|a note`)).toBeUndefined(); + expect(S.get(`${SET_KIND.hasProp}|${note}|number|0`)).toEqual(ids(db, ['F'])); + + // generic recomputation for every prop set + for (const [key, members] of S) { + const [kind, prop, type, value] = key.split('|'); + if (Number(kind) !== SET_KIND.prop) continue; + const v = type === 'number' ? Number(value) : value; + const expected = db.prepare(`SELECT subject_id FROM link WHERE active = 1 AND property_id = ? AND target_id = ? + UNION SELECT subject_id FROM literal WHERE active = 1 AND property_id = ? AND value = ? ORDER BY 1`) + .pluck().all(Number(prop), v, Number(prop), v); + expect(members).toEqual(expected); + } + }); + + test('record members are a set (inactive concepts too); rows keep their fields in arrival order', () => { + const s1 = pid(db, 'S1'); + expect(S.get(`${SET_KIND.refset}|${s1}|number|0`)).toEqual(ids(db, ['F', 'G', 'X'])); + const rows = db.prepare('SELECT c.code, r.seq, r.fields FROM record r JOIN concept c ON c.id = r.subject_id WHERE relation_id = ? ORDER BY r.seq').raw().all(s1); + expect(rows).toEqual([['F', 0, '[null]'], ['X', 1, '[null]'], ['G', 2, '["T1"]']]); + }); + + test('items are renumbered in concept order and indexed for search', () => { + const d = db.prepare('SELECT i.id, i.concept_id, i.language, i.text, i.active, i.preferred, u.code AS use FROM item i JOIN item_use u USING (use_id)').all(); + expect(d).toEqual([{ id: 15, concept_id: ids(db, ['F'])[0], language: 'en', text: 'eff', active: 1, preferred: 1, use: 'syn' }]); + expect(db.prepare("SELECT rowid FROM ix_text_item WHERE ix_text_item MATCH 'eff'").pluck().all()).toEqual([15]); + }); + + test('meta: the format, the languages, provenance; PRAGMA user_version 1; a unique code index', () => { + const m = Object.fromEntries(db.prepare('SELECT key, value FROM meta').raw().all()); + expect(m.format).toBe(FORMAT); + expect(FORMAT).toBe('tx-terminology/1'); + expect(JSON.parse(m.languages)).toEqual(['en']); + expect(m['provenance.importer']).toBe('test'); + expect(db.pragma('user_version', { simple: true })).toBe(1); + expect(db.prepare("SELECT sql FROM sqlite_master WHERE name = 'concept_code'").pluck().get()).toMatch(/^CREATE UNIQUE INDEX/); + }); + + test('statistics: sqlite_stat1 only, no sqlite_stat4', () => { + expect(db.prepare("SELECT name FROM sqlite_master WHERE name LIKE 'sqlite_stat%' ORDER BY 1").pluck().all()).toEqual(['sqlite_stat1']); + }); + + test('the index tables are rebuildable from the fact tables', () => { + const copy = path.join(dir, 'rebuilt.db'); + fs.copyFileSync(path.join(dir, 'fixture.db'), copy); + const w = new Database(copy); + const dump = (d) => d.prepare('SELECT kind, property_id, value_kind, value, hex(data) FROM ix_set ORDER BY 1, 2, 3, 4').raw().all(); + const before = dump(w); + buildIndexes(w); + expect(dump(w)).toEqual(before); + w.close(); + }); +}); + +describe('sqlite-v2 display rank from language relations', () => { + test('0 preferred in a display relation, 1 preferred in another, 2 otherwise (only items of the ranked use)', () => { + const dest = path.join(dir, 'rank.db'); + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); + const c = {}; + for (const code of ['A', 'B', 'US', 'GB', 'PREF', 'ACC']) c[code] = b.concept(code, { display: code }); + const lang = (code) => b.property({ code, shape: 'record', role: 'language', concept: c[code], fields: [{ name: 'acceptabilityId', type: 'c', target: true }] }); + const us = lang('US'), gb = lang('GB'); + const syn = { system: 's', code: 'syn' }; + const t = {}; + t.usPref = b.item(c.A, { use: syn, text: 'us preferred' }); + t.gbPref = b.item(c.A, { use: syn, text: 'gb preferred, us acceptable' }); + t.acc = b.item(c.A, { use: syn, text: 'acceptable only' }); + t.fsn = b.item(c.A, { use: { system: 's', code: 'fsn' }, text: 'fsn preferred' }); + t.none = b.item(c.B, { use: syn, text: 'no acceptability' }); + b.record(us, t.usPref, { target: c.PREF }); + b.record(gb, t.usPref, { target: c.ACC }); + b.record(gb, t.gbPref, { target: c.PREF }); + b.record(us, t.gbPref, { target: c.ACC }); + b.record(us, t.acc, { target: c.ACC }); + b.record(us, t.fsn, { target: c.PREF }); + b.setMeta('displayContexts', { relations: ['US'], preferred: 'PREF', use: syn }); + b.finish(); + const db = new Database(dest, { readonly: true }); + expect(db.prepare('SELECT text, rank FROM item ORDER BY id').raw().all()).toEqual([ + ['us preferred', 0], ['gb preferred, us acceptable', 1], ['acceptable only', 2], ['fsn preferred', 2], ['no acceptability', 2]]); + db.close(); + }); +}); + +describe('sqlite-v2 explicit ancestor pairs', () => { + test('descendant sets come from the pairs (closure_from), not the edge closure', () => { + // Path-style hierarchy: G is under E's path only. + const pairs = [['B', 'root'], ['C', 'root'], ['D', 'root'], ['D', 'B'], ['F', 'D'], ['F', 'B'], ['F', 'root'], + ['E', 'C'], ['E', 'root'], ['G', 'E'], ['G', 'C'], ['G', 'root'], ['Z', 'root'], ['S1', 'root']]; + const { db } = buildFixture(path.join(dir, 'pairs.db'), { explicitPairs: pairs }); + const S = sets(db); + expect(S.get(`${SET_KIND.descendants}|0|number|${ids(db, ['D'])[0]}`)).toEqual(ids(db, ['F'])); + expect(S.get(`${SET_KIND.descendants}|0|number|${ids(db, ['E'])[0]}`)).toEqual(ids(db, ['G'])); + // the closure source has no sets of its own + expect([...S.keys()].some((k) => k.startsWith(`${SET_KIND.prop}|${pid(db, 'ancestor')}|`))).toBe(false); + db.close(); + }); +}); + +describe('sqlite-v2 identifiers accepted as codes; definitions; the format check', () => { + let file; + beforeAll(() => { + file = path.join(dir, 'ident.db'); + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/ident', version: '1' }); + const short = b.property({ code: 'short', shape: 'identifier' }); + const form = b.property({ code: 'form', shape: 'identifier' }); + const other = b.property({ code: 'other', shape: 'identifier' }); + const byValue = b.property({ code: 'byValue', shape: 'identifier', bySubject: false }); + const a = b.concept('A-1', { display: 'Alpha' }); + const k = b.concept('K-2', { display: 'Kappa' }); + b.identifier(short, 'A1', a, { resolves: 1 }); // an alias: answered as A-1 + b.identifier(form, '00002', k, { resolves: 2 }); // a code in its own right: answered as written + b.identifier(other, 'X9', a); // not a code + b.identifier(short, 'K-2', a, { resolves: 1 }); // the same value as a concept code: the concept wins + b.identifier(byValue, 'V7', a); // read by value only: not in ix_by_subject + b.item(a, { kind: 1, text: 'a definition with no use', preferred: true }); + b.item(k, { kind: 1, use: { system: 'u', code: 'def' }, text: 'a definition with a use', preferred: true }); + b.finish(); + }); + + test('resolves 1 is answered with the concept\'s code, 2 as written, 0 not at all; a concept code wins', async () => { + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + const p = await f.build(op, []); + const code = async (c) => { const r = await p.locate(c); return r.context ? [await p.code(r.context), await p.display(r.context)] : null; }; + expect(await code('A1')).toEqual(['A-1', 'Alpha']); + expect(await code('00002')).toEqual(['00002', 'Kappa']); + expect(await code('X9')).toBeNull(); + expect(await code('K-2')).toEqual(['K-2', 'Kappa']); + } finally { f.store.close(); } + }); + + test('by_subject: identifier rows read by subject are in ix_by_subject, only for the catalog rows that ask', () => { + const db = new Database(file, { readonly: true }); + try { + expect(db.prepare("SELECT code, by_subject FROM property WHERE shape = 'identifier' ORDER BY id").raw().all()) + .toEqual([['short', 1], ['form', 1], ['other', 1], ['byValue', 0]]); + expect(db.prepare('SELECT p.code, x.value FROM ix_by_subject x JOIN property p ON p.id = x.property_id ORDER BY 1, 2').raw().all()) + .toEqual([['form', '00002'], ['other', 'X9'], ['short', 'A1'], ['short', 'K-2']]); + expect(db.prepare("SELECT count(*) FROM sqlite_master WHERE name = 'identifier_subject'").pluck().get()).toBe(0); + const { Store } = require('../../tx/sqlite-v2/store'); + const S = new Store(file, { db, unregistered: true }); + const a = db.prepare("SELECT id FROM concept WHERE code = 'A-1'").pluck().get(); + expect(S.alternateIdsOf(a).map((r) => [r.scheme, r.identifier])).toEqual([['short', 'A1'], ['short', 'K-2'], ['other', 'X9']]); + // the reader's code probe says resolves > 0, so it reads the partial index identifier_code + expect(S.identifierAsCode('A1').code).toBe('A-1'); + const probe = [...S._stmts.keys()].find((q) => /FROM main\.identifier/.test(q)); + const plan = db.prepare(`EXPLAIN QUERY PLAN ${probe}`).all('A1').map((r) => r.detail).join('; '); + expect(plan).toMatch(/USING INDEX identifier_code/); + } finally { db.close(); } + }); + + test('a definition is a designation only when it has a use; the definition shown either way', () => { + const S = openStore(file, { unregistered: true }); + try { + const rows = S.designationRows([S.idOf('A-1'), S.idOf('K-2')]); + expect(rows.get(S.idOf('A-1')) || []).toEqual([]); + expect(rows.get(S.idOf('K-2')).map((d) => d.term)).toEqual(['a definition with a use']); + expect(S.rowForCode('A-1').definition).toBe('a definition with no use'); + } finally { S.close(); } + }); + + test('a file of the earlier sqlite-v2 schema, or of another format version, is refused with what to do', () => { + const v5 = path.join(dir, 'old-v5.db'); + const d = new Database(v5); + d.exec('CREATE TABLE cs_config (key TEXT, value TEXT); CREATE TABLE concept_set (kind INTEGER); PRAGMA user_version = 5;'); + d.close(); + expect(() => openStore(v5)).toThrow(/earlier version of the sqlite-v2 importers.*re-import it/); + const older = path.join(dir, 'old-format.db'); + fs.copyFileSync(file, older); + const w = new Database(older); + w.exec("UPDATE meta SET value = 'tx-terminology/0.3' WHERE key = 'format'; PRAGMA user_version = 0;"); + w.close(); + expect(() => openStore(older)).toThrow(/format tx-terminology\/0\.3; this server reads tx-terminology\/1: re-import/); + }); + + test('behaviour settings: defaults, the ones a file sets, and an unknown key or value refused at open', () => { + const S = openStore(file, { unregistered: true }); + try { + expect(S.behaviour).toMatchObject({ grammar: null, expansionOrder: 'ids', lookupName: 'name', distinctDesignationTexts: false }); + } finally { S.close(); } + const bad = (key, value, msg) => { + const f = path.join(dir, 'behaviour.db'); + fs.copyFileSync(file, f); + const w = new Database(f); + w.prepare('INSERT INTO meta VALUES (?, ?)').run(key, value); + w.close(); + expect(() => openStore(f)).toThrow(msg); + }; + bad('behaviour.colour', '"red"', /unknown behaviour setting behaviour.colour/); + bad('behaviour.designationUses', '"sometimes"', /behaviour.designationUses = "sometimes" is not a value this server knows/); + bad('behaviour.grammar', 'snomed', /is not JSON/); + bad('behaviour.preferredForLanguage', '"yes"', /behaviour.preferredForLanguage = "yes" is not a value/); + bad('behaviour.aliasLiterals', '{"code-type": 11}', /behaviour.aliasLiterals = .* is not a value/); + bad('behaviour.filters', '[{"code": "kind", "operator": ["like"]}]', /behaviour.filters = .* is not a value/); + bad('behaviour.filters', '[{"code": "kind", "operator": ["="], "values": "product"}]', /behaviour.filters = .* is not a value/); + const good = path.join(dir, 'behaviour-ok.db'); + fs.copyFileSync(file, good); + const w = new Database(good); + w.prepare('INSERT INTO meta VALUES (?, ?)').run('behaviour.preferredForLanguage', 'true'); + w.prepare('INSERT INTO meta VALUES (?, ?)').run('behaviour.aliasLiterals', '{"code-type": "11-digit", "synonym": "{code}"}'); + w.prepare('INSERT INTO meta VALUES (?, ?)').run('behaviour.filters', + '[{"code": "inactive", "operator": ["="], "values": ["true", "false"]}, {"code": "category", "operator": ["=", "in"]}]'); + w.close(); + const G = openStore(good, { unregistered: true }); + try { + expect(G.behaviour.preferredForLanguage).toBe(true); + expect(G.behaviour.aliasLiterals).toEqual({ 'code-type': '11-digit', synonym: '{code}' }); + expect(G.behaviour.filters.map((f) => f.code)).toEqual(['inactive', 'category']); + } finally { G.close(); } + const b = new TerminologyBuilder(path.join(dir, 'never.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/x', version: '1' }); + b.concept('a'); + b.setBehaviour('lookupName', 'nickname'); + expect(() => b.finish()).toThrow(/behaviour.lookupName = "nickname" is not a value/); + }); +}); diff --git a/tests/tx/sqlite-v2-counting-tracer.js b/tests/tx/sqlite-v2-counting-tracer.js new file mode 100644 index 00000000..b56e805a --- /dev/null +++ b/tests/tx/sqlite-v2-counting-tracer.js @@ -0,0 +1,18 @@ +'use strict'; +/** + * A tracer for the sqlite-v2 tests that only counts: the interface the providers and the engine + * call when a request carries one (OperationContext.tracer: stats, span, spanAsync, open, close, + * annotate). stats.statements is the number of SQLite statements run, stats.rows the rows read. + */ +function countingTracer() { + return { + stats: { statements: 0, rows: 0, setsLoaded: 0, setBytes: 0, setLoadUs: 0 }, + span: (label, kind, system, fn) => fn(), + spanAsync: async (label, kind, system, fn) => fn(), + open: () => null, + close: () => {}, + annotate: () => {} + }; +} + +module.exports = { countingTracer }; diff --git a/tests/tx/sqlite-v2-cs-ids.test.js b/tests/tx/sqlite-v2-cs-ids.test.js new file mode 100644 index 00000000..458deeca --- /dev/null +++ b/tests/tx/sqlite-v2-cs-ids.test.js @@ -0,0 +1,135 @@ +'use strict'; + +// The CodeSystem id of each system the sqlite-v2 engine serves natively must be the one main's +// provider gives it (read.js and search.js serve it as CodeSystem/x-, as tx.fhir.org does: +// x-loinc2.82, x-RxNorm-03022026, x-SCT-900000000000207008-20260701). First over the test fixtures, +// both engines loaded from the same release; then main's id() and the engine's over a table of +// versions, each called on a factory that has only its version (and edition) set. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { OperationContext } = require('../../tx/operation-context'); +const { TestUtilities } = require('../test-utilities'); +const { LoincDataMigrator } = require('../../tx/importers/import-loinc.module'); +const { importLoincV2 } = require('../../tx/importers/import-loinc-v2.module'); +const { RxNormImporter } = require('../../tx/importers/import-rxnorm.module'); +const { importRxNormV2 } = require('../../tx/importers/import-rxnorm-v2.module'); +const { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { LoincServicesFactory } = require('../../tx/cs/cs-loinc'); +const { RxNormServicesFactory } = require('../../tx/cs/cs-rxnorm'); +const { SnomedServicesFactory } = require('../../tx/cs/cs-snomed'); +const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); +const { SnomedV2Factory } = require('../../tx/sqlite-v2/snomed'); + +const LOINC = 'http://loinc.org'; +const RXNORM = 'http://www.nlm.nih.gov/research/umls/rxnorm'; +const SCT = 'http://snomed.info/sct'; +const DATA = path.resolve(__dirname, '../../tx/data'); +const LOINC_VERSION = '2.80-test'; +// main's importer writes no RXNVer, so main takes the version from the file name (rxnorm_.db) +const RXNORM_VERSION = '08242025'; + +let dir, op; +const loaded = {}; // system -> { main, v2 } + +// The id needs only the version, so RxNorm comes from the first rows of each fixture file: the +// whole fixture (43 MB) took 12 of this setup's 15 s alone, and over jest's hook limit when the +// tx suites run in parallel. Both importers read the same trimmed copy. +const RXNORM_ROWS = 2000; +function trimmedRxNorm(dest) { + fs.mkdirSync(dest); + for (const f of fs.readdirSync(path.join(DATA, 'rxnorm'))) { + if (!f.endsWith('.RRF')) continue; + const text = fs.readFileSync(path.join(DATA, 'rxnorm', f), 'utf8'); + let end = 0; + for (let k = 0; k < RXNORM_ROWS && end >= 0; k++) end = text.indexOf('\n', end + 1); + fs.writeFileSync(path.join(dest, f), end < 0 ? text : text.slice(0, end + 1)); + } + return dest; +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-cs-ids-')); + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const rxnorm = trimmedRxNorm(path.join(dir, 'rxnorm-src')); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new LoincDataMigrator().migrate(path.join(DATA, 'loinc'), path.join(dir, 'loinc-classic.db'), LOINC_VERSION, { verbose: false, mainOnly: false }); + await new RxNormImporter(rxnorm, path.join(dir, 'rxnorm_' + RXNORM_VERSION + '.db'), RXNORM_VERSION, { verbose: false, createStems: true }).import(); + } finally { quiet.mockRestore(); } + await importLoincV2({ source: path.join(DATA, 'loinc'), dest: path.join(dir, 'loinc.db'), version: LOINC_VERSION, overwrite: true, log: () => {} }); + await importRxNormV2({ source: rxnorm, dest: path.join(dir, 'rxnorm.db'), version: RXNORM_VERSION, overwrite: true, log: () => {} }); + // an old-format cache (no modules, no definition status): enough for the version, which is all + // this needs + await importSnomedV2FromCache({ source: path.join(DATA, 'snomed-testing.cache'), dest: path.join(dir, 'sct.db'), overwrite: true, force: true, log: () => {} }); + + const load = async (f) => { await f.load(); return f; }; + loaded[LOINC] = { main: await load(new LoincServicesFactory(op.i18n, path.join(dir, 'loinc-classic.db'))), v2: await load(new SqliteV2Factory(op.i18n, path.join(dir, 'loinc.db'))) }; + loaded[RXNORM] = { main: await load(new RxNormServicesFactory(op.i18n, path.join(dir, 'rxnorm_' + RXNORM_VERSION + '.db'))), v2: await load(new SqliteV2Factory(op.i18n, path.join(dir, 'rxnorm.db'))) }; + loaded[SCT] = { main: await load(new SnomedServicesFactory(op.i18n, path.join(DATA, 'snomed-testing.cache'))), v2: await load(new SnomedV2Factory(op.i18n, path.join(dir, 'sct.db'))) }; +}, 180000); + +afterAll(() => { + for (const { main, v2 } of Object.values(loaded)) { + for (const f of [main, v2]) { try { if (f.close) f.close(); else if (f.store) f.store.close(); } catch { /* closing only */ } } + } + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +describe('over the test fixtures, the same release on both engines', () => { + test.each([ + [LOINC, 'loinc2.80-test'], + [RXNORM, 'RxNorm-08242025'], + [SCT, 'xSCT-31000003106-20250909'] // the fixture is a test edition (snomed.info/xsct): see SnomedV2Factory.id() + ])('%s', (system, id) => { + const { main, v2 } = loaded[system]; + expect(v2.system()).toBe(main.system()); + expect(v2.version()).toBe(main.version()); + expect(v2.id()).toBe(main.id()); + expect(main.id()).toBe(id); + }); +}); + +describe('main\'s id() and the engine\'s, over a table of versions', () => { + // a factory of each class with only what id() reads: the version, and for RxNorm the name + const mainLoinc = (v) => Object.assign(Object.create(LoincServicesFactory.prototype), { _sharedData: { _version: v } }); + const mainRxNorm = (v) => Object.assign(Object.create(RxNormServicesFactory.prototype), { isNCI: false, _sharedData: { version: v } }); + const mainSct = (v, edition) => Object.assign(Object.create(SnomedServicesFactory.prototype), { _sharedData: { versionUri: v, edition } }); + const v2 = (cls, system, version, cs = {}) => Object.assign(Object.create(cls.prototype), { store: { system, version, cs } }); + + test.each(['2.77', '2.78', '2.81', '2.82', '2.83', '2.80-test'])('LOINC %s', (v) => { + expect(v2(SqliteV2Factory, LOINC, v).id()).toBe(mainLoinc(v).id()); + expect(v2(SqliteV2Factory, LOINC, v).id()).toBe('loinc' + v); + }); + + test.each(['03022026', '11042024', '01012026'])('RxNorm %s', (v) => { + // the file's code system name (the RxNorm importer writes RxNorm) + expect(v2(SqliteV2Factory, RXNORM, v, { name: 'RxNorm' }).id()).toBe(mainRxNorm(v).id()); + expect(v2(SqliteV2Factory, RXNORM, v, { name: 'RxNorm' }).id()).toBe('RxNorm-' + v); + }); + + test.each([ + ['900000000000207008', 'http://snomed.info/sct/900000000000207008/version/20260701'], // International + ['731000124108', 'http://snomed.info/sct/731000124108/version/20250901'], // US + ['83821000000107', 'http://snomed.info/sct/83821000000107/version/20251001'], // UK + ['11000172109', 'http://snomed.info/sct/11000172109/version/20251115'], // Belgium + ['900000000000207008', 'http://snomed.info/sct/900000000000207008'], // no version: no id + ['31000003106', 'http://snomed.info/xsct/31000003106/version/20250909'], // test edition + ['11010000107', 'http://snomed.info/sct/11010000107/version/20261021'], // LOINC extension: not in the edition list + ['900000000000207008', 'http://snomed.info/xsct/900000000000207008/version/20250814'], + ['31000003106', 'http://snomed.info/xsct/31000003106'] // undated test edition: no id, as for sct + ])('SNOMED CT %s %s', (edition, v) => { + const engine = v2(SnomedV2Factory, SCT, v, { edition }); + expect(engine.id()).toBe(mainSct(v, edition).id()); + // the placeholder's name too (search and read show it): 'SCT Unknown Edition' for an unlisted edition + expect(engine.name()).toBe(mainSct(v, edition).name()); + }); + + test('two dated test editions have different ids', () => { + const a = v2(SnomedV2Factory, SCT, 'http://snomed.info/xsct/31000003106/version/20250909', { edition: '31000003106' }); + const b = v2(SnomedV2Factory, SCT, 'http://snomed.info/xsct/31000003106/version/20240909', { edition: '31000003106' }); + expect(a.id()).toBe('xSCT-31000003106-20250909'); + expect(a.id()).not.toBe(b.id()); + }); +}); diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js new file mode 100644 index 00000000..44a26014 --- /dev/null +++ b/tests/tx/sqlite-v2-engine.test.js @@ -0,0 +1,667 @@ +'use strict'; + +// sqlite-v2 query engine and provider on a small fixture built with the file builder: +// compose filters and ECL compile to set algebra over stored sets; results page by position; +// membership by probing; statement counts; supplement layers; RxNorm REL filters. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { TerminologyBuilder } = require('../../tx/importers/sqlite-v2/builder'); +const { openStore } = require('../../tx/sqlite-v2/store'); +const { Engine } = require('../../tx/sqlite-v2/engine/engine'); +const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); +const { dialectFor } = require('../../tx/sqlite-v2/dialects'); +const { countingTracer } = require('./sqlite-v2-counting-tracer'); +const { buildLayer, LayerSet } = require('../../tx/sqlite-v2/layers'); + +let dir; +let store; +let rx; + +// root +// ├── B ── D ─┬─ F (site = Y, colour red) +// │ └─ G (also under E; site = Y in two groups, colour red) +// ├── C ── E ─── G +// │ └──── H (inactive) +// └── Z +// Y: active, no parents; X: inactive +function buildFixture(dest) { + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); + const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); + const colour = b.property({ code: 'colour', shape: 'literal', fhirType: 'string' }); + // attributes: ECL refinements name them + const site = b.property({ code: 'site', shape: 'link', refinable: true, wildcard: true }); + const lat = b.property({ code: 'laterality', shape: 'link', refinable: true, wildcard: true }); + const c = {}; + for (const code of ['root', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'Z', 'Y', 'X', 'L', 'R']) { + c[code] = b.concept(code, { active: !['H', 'X'].includes(code), display: `display ${code}` }); + } + for (const [ch, pa] of [['B', 'root'], ['C', 'root'], ['Z', 'root'], ['D', 'B'], ['F', 'D'], ['G', 'D'], ['E', 'C'], ['G', 'E'], ['H', 'E']]) b.link(c[ch], isa, c[pa]); + b.link(c.F, site, c.Y, { group: 1 }); + b.link(c.F, lat, c.L, { group: 1 }); + b.link(c.G, site, c.Y, { group: 1 }); + b.link(c.G, lat, c.R, { group: 2 }); + b.literal(c.F, colour, 'red'); + b.literal(c.G, colour, 'Red'); + b.literal(c.D, colour, 'blue'); + b.item(c.F, { language: 'en', text: 'effervescent thing' }); + b.finish(); +} + +function buildRx(dest) { + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://www.nlm.nih.gov/research/umls/rxnorm', version: '1' }); + const tty = b.property({ code: 'TTY', shape: 'literal', fhirType: 'code' }); + const hpi = b.property({ code: 'has_precise_ingredient', shape: 'link', wildcard: true }); + const hpiRN = b.property({ code: 'has_precise_ingredient@RN', shape: 'link', filterable: false }); + const hi = b.property({ code: 'has_ingredient', shape: 'link', wildcard: true }); + const c = {}; + for (const code of ['1', '2', '3', '4', '5']) c[code] = b.concept(code, { active: code !== '5', display: 'drug ' + code }); + b.literal(c['2'], tty, 'SCD'); + b.literal(c['3'], tty, 'SCD'); + b.literal(c['5'], tty, 'SCD'); + b.link(c['2'], hpi, c['1']); + b.link(c['2'], hpiRN, c['1']); + b.link(c['3'], hpi, c['1']); // the RO row: not RN + b.link(c['4'], hi, c['1']); + b.link(c['5'], hi, c['1']); + // a REL is the union of the RELAs its rows carry (RELA@REL where a RELA occurs under two RELs) + const rn = b.property({ code: 'RN', shape: 'union' }); + const ro = b.property({ code: 'RO', shape: 'union' }); + b.propertyMember(rn, hpiRN); + b.propertyMember(ro, hi); + b.propertyMember(ro, hpi); + b.finish(); +} + +beforeAll(() => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-engine-')); + buildFixture(path.join(dir, 'cs.db')); + buildRx(path.join(dir, 'rx.db')); + store = openStore(path.join(dir, 'cs.db')); + rx = openStore(path.join(dir, 'rx.db')); +}); +afterAll(() => { + store.close(); + rx.close(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +function codesOf(S, ids) { + const rows = S.conceptRows(ids); + return ids.map((id) => rows.get(id).code); +} + +function expand(S, includes, { excludes = [], activeOnly = false, offset = 0, count = -1, engine, layers } = {}) { + const e = engine || new Engine(S); + const c = new Compiler({ store: S, dialect: dialectFor(S.system), layers }); + const r = e.run(c.selection(includes, excludes, activeOnly), { offset, count }); + return { r, codes: codesOf(S, r.page(offset, count)) }; +} + +const inc = (filter) => ({ system: 'http://example.org/cs', filter }); +const f = (property, op, value) => ({ property, op, value }); + +describe('sqlite-v2 engine: filters as set algebra', () => { + test('hierarchy filters', () => { + expect(expand(store, [inc([f('concept', 'is-a', 'D')])]).codes.sort()).toEqual(['D', 'F', 'G']); + expect(expand(store, [inc([f('concept', 'descendent-of', 'C')])]).codes.sort()).toEqual(['E', 'G', 'H']); + expect(expand(store, [inc([f('concept', 'child-of', 'E')])]).codes.sort()).toEqual(['G', 'H']); + expect(expand(store, [inc([f('concept', 'generalizes', 'G')])]).codes.sort()).toEqual(['B', 'C', 'D', 'E', 'G', 'root']); + expect(expand(store, [inc([f('concept', 'is-not-a', 'B')])]).codes.sort()).toEqual(['C', 'E', 'H', 'L', 'R', 'X', 'Y', 'Z', 'root']); + expect(expand(store, [inc([f('concept', 'descendent-leaf', 'root')])]).codes.sort()).toEqual(['F', 'G', 'Z']); + }); + + test('properties: =, in, not-in, exists, regex, case-insensitive literals', () => { + expect(expand(store, [inc([f('colour', '=', 'red')])]).codes.sort()).toEqual(['F', 'G']); + expect(expand(store, [inc([f('colour', 'in', 'blue,red')])]).codes.sort()).toEqual(['D', 'F', 'G']); + expect(expand(store, [inc([f('site', '=', 'Y')])]).codes.sort()).toEqual(['F', 'G']); + expect(expand(store, [inc([f('site', 'exists', 'true')])]).codes.sort()).toEqual(['F', 'G']); + expect(expand(store, [inc([f('colour', 'regex', 'bl.*')])]).codes).toEqual(['D']); + expect(expand(store, [inc([f('concept', 'is-a', 'root'), f('colour', 'not-in', 'red')])]).codes.sort()).toEqual(['B', 'C', 'D', 'E', 'H', 'Z', 'root']); + // a regex on a concept-valued property matches the target's display + expect(expand(store, [inc([f('laterality', 'regex', 'display L')])]).codes).toEqual(['F']); + }); + + test('R5 generic filters: designation = / regex (display counts), search prefixes', () => { + expect(expand(store, [inc([f('designation', '=', 'effervescent thing')])]).codes).toEqual(['F']); + expect(expand(store, [inc([f('designation', '=', 'display D')])]).codes).toEqual(['D']); + // regex matches the whole term (tx-ecosystem simple-expand-regex, expand-regex-bad) + expect(expand(store, [inc([f('designation', 'regex', 'efferv')])]).codes).toEqual([]); + expect(expand(store, [inc([f('designation', 'regex', 'efferv.*')])]).codes).toEqual(['F']); + expect(expand(store, [inc([f('code', 'regex', '[A-Z]')])]).codes.sort()).toEqual(['B', 'C', 'D', 'E', 'F', 'G', 'H', 'L', 'R', 'X', 'Y', 'Z']); + expect(expand(store, [inc([f('code', 'regex', 'roo')])]).codes).toEqual([]); + }); + + test('planner budget: an estimated cost over maxScanRows is refused before the work', () => { + const { settings } = require('../../tx/sqlite-v2/settings'); + const saved = settings.maxScanRows; + settings.maxScanRows = 3; + try { + expect(() => expand(store, [inc([f('designation', 'regex', 'x')])])).toThrow(/estimated cost/); + } finally { + settings.maxScanRows = saved; + } + }); + + test('includes, excludes and activeOnly', () => { + const { codes, r } = expand(store, [inc([f('concept', 'is-a', 'E')]), inc([f('concept', 'is-a', 'D')])], + { excludes: [inc([f('colour', '=', 'red')])], activeOnly: true }); + expect(codes.sort()).toEqual(['D', 'E']); + expect(r.total).toBe(2); + }); + + test('explicit concepts keep their order; paging is by position across segments', () => { + const e = new Engine(store); + const sel = [{ system: 'http://example.org/cs', concept: [{ code: 'Z' }, { code: 'B' }, { code: 'nope' }] }, inc([f('concept', 'is-a', 'D')])]; + const all = expand(store, sel, { engine: e }).codes; + expect(all).toEqual(['Z', 'B', 'D', 'F', 'G']); + expect(expand(store, sel, { engine: e, offset: 1, count: 3 }).codes).toEqual(['B', 'D', 'F']); + }); + + test('ECL hierarchy operators over the wildcard (tx-ecosystem sct/ecl/*-of-any)', () => { + const ev = (text) => codesOf(store, new Engine(store).evaluate(new Compiler({ store, dialect: {} }).ecl(text)).toArray()).sort(); + const all = ev('*'); + const hasParent = ev('< *'); // an active is-a link up + const hasChild = ev('> *'); // an active concept that is not a leaf + expect(hasParent).toEqual(['B', 'C', 'D', 'E', 'F', 'G', 'H', 'Z']); + expect(hasChild).toEqual(['B', 'C', 'D', 'E', 'root']); + expect(ev('! *')).toEqual(hasChild); + for (const op of ['<<', '<>', '>>!']) expect(ev(op + ' *')).toEqual(all); + expect(ev('!!< *')).toEqual(all.filter((c) => !hasChild.includes(c))); // bottom of the set: no children + expect(ev('!!> *')).toEqual(all.filter((c) => !hasParent.includes(c))); // top of the set: no parents + }); + + test('ECL: refinements, groups, cardinality, reverse, dotted', () => { + const ecl = (text) => { + const c = new Compiler({ store, dialect: {} }); + return codesOf(store, new Engine(store).evaluate(c.ecl(text)).toArray()).sort(); + }; + // the fixture's codes are not SCTIDs; build the AST by hand through the compiler's ECL node API + const n = (code) => ({ type: 'SubExpressionConstraint', operator: null, focus: { type: 'ConceptReference', conceptId: code } }); + const c = new Compiler({ store, dialect: {} }); + const ev = (node) => codesOf(store, new Engine(store).evaluate(node).toArray()).sort(); + const desc = (code) => ({ type: 'SubExpressionConstraint', operator: 'DESCENDANT_OR_SELF_OF', focus: { type: 'ConceptReference', conceptId: code } }); + const attr = (name, value, extra = {}) => ({ type: 'Attribute', cardinality: null, reverse: false, name: { type: 'ConceptReference', conceptId: name }, comparison: { type: 'ExpressionComparison', operator: 'EQUALS', value }, ...extra }); + expect(ev(c.eclNode({ type: 'RefinedExpressionConstraint', base: desc('root'), refinement: attr('site', n('Y')) }))).toEqual(['F', 'G']); + // F has site=Y and laterality=L in one group; G has them in different groups + const group = { type: 'AttributeGroup', cardinality: null, attributes: [attr('site', n('Y')), attr('laterality', { type: 'SubExpressionConstraint', operator: null, focus: { type: 'Wildcard' } })] }; + expect(ev(c.eclNode({ type: 'RefinedExpressionConstraint', base: desc('root'), refinement: group }))).toEqual(['F']); + expect(ev(c.eclNode({ type: 'RefinedExpressionConstraint', base: desc('D'), refinement: attr('laterality', n('L'), { cardinality: { min: 0, max: 0 } }) }))).toEqual(['D', 'G']); + expect(ev(c.eclNode({ type: 'RefinedExpressionConstraint', base: { type: 'SubExpressionConstraint', operator: null, focus: { type: 'Wildcard' } }, refinement: attr('site', desc('D'), { reverse: true }) }))).toEqual(['Y']); + expect(ev(c.eclNode({ type: 'DottedExpressionConstraint', base: desc('D'), attributes: [{ type: 'ConceptReference', conceptId: 'laterality' }] }))).toEqual(['L', 'R']); + // cardinality counts (group, value) occurrences: G has site=Y in group 1 and laterality R in group 2 + const any = { type: 'SubExpressionConstraint', operator: null, focus: { type: 'Wildcard' } }; + expect(ev(c.eclNode({ type: 'RefinedExpressionConstraint', base: desc('root'), refinement: { type: 'AttributeSet', operator: 'OR', attributes: [attr('site', any, { cardinality: { min: 1, max: 1 } })] } }))).toEqual(['F', 'G']); + expect(ev(c.eclNode({ type: 'RefinedExpressionConstraint', base: desc('root'), refinement: { type: 'AttributeGroup', cardinality: { min: 2, max: '*' }, attributes: [attr('laterality', any)] } }))).toEqual([]); + expect(ev(c.eclNode({ type: 'RefinedExpressionConstraint', base: desc('D'), refinement: { type: 'AttributeGroup', cardinality: { min: 0, max: 1 }, attributes: [attr('laterality', any)] } }))).toEqual(['D', 'F', 'G']); + expect(ev(c.eclNode({ type: 'SubExpressionConstraint', operator: 'BOTTOM_OF_SET', focus: { type: 'CompoundExpressionConstraint', operator: 'Disjunction', left: n('B'), right: n('D') } }))).toEqual(['D']); + void ecl; + }); + + test('membership of one code is answered by probing, without materialising a text scan', () => { + const e = new Engine(store); + const c = new Compiler({ store, dialect: {} }); + const node = { t: 'and', items: [c.filter('concept', 'is-a', 'root'), { t: 'text', field: 'display', re: 'display [FG]' }] }; + expect(e.contains(node, store.idOf('F'))).toBe(true); + expect(e.contains(node, store.idOf('D'))).toBe(false); + }); + + test('lazy first page: no total; a full request is complete', () => { + const e = new Engine(store, { lazyMinDriver: 2 }); + const sel = [inc([f('concept', 'is-a', 'root'), f('concept', 'regex', '[A-Z]')])]; + const c = new Compiler({ store, dialect: {} }); + const first = e.run(c.selection(sel, [], false), { offset: 0, count: 2 }); + expect(first.page(0, 2).length).toBe(2); + const all = e.run(c.selection(sel, [], false), { offset: 0, count: -1 }); + expect(all.complete).toBe(true); + expect(codesOf(store, all.page(0, -1)).sort()).toEqual(['B', 'C', 'D', 'E', 'F', 'G', 'H', 'Z']); + }); +}); + +describe('sqlite-v2 engine: value set imports', () => { + test('an include of imported value sets is their intersection; an import is includes minus excludes', () => { + const vsA = { include: [inc([f('concept', 'is-a', 'root')])], exclude: [inc([f('concept', 'is-a', 'C')])] }; + const vsB = { include: [inc([f('colour', 'exists', 'true')])] }; + // G is also under C (polyhierarchy), so the exclude removes it + expect(expand(store, [{ imports: [vsA] }]).codes.sort()).toEqual(['B', 'D', 'F', 'Z', 'root']); + expect(expand(store, [{ imports: [vsA, vsB] }]).codes.sort()).toEqual(['D', 'F']); + expect(expand(store, [{ system: 'http://example.org/cs', filter: [f('colour', '=', 'red')], imports: [vsA] }]).codes.sort()).toEqual(['F']); + }); +}); + +describe('sqlite-v2 supplement layers', () => { + const supp = { + resourceType: 'CodeSystem', url: 'http://example.org/supp', version: '1', content: 'supplement', supplements: 'http://example.org/cs', language: 'fr', + property: [{ code: 'flavour', type: 'code' }], + concept: [ + { code: 'F', display: 'chose F', designation: [{ language: 'fr', value: 'chose effervescente' }], property: [{ code: 'flavour', valueCode: 'sweet' }] }, + { code: 'D', property: [{ code: 'flavour', valueCode: 'sour' }] }, + { code: 'G', property: [{ code: 'flavour', valueCode: 'sweet' }] }, + { code: 'unknown-to-base', display: 'x' } + ] + }; + + test('layer ids are base ids; unknown codes are counted and skipped', () => { + const l = buildLayer(store, supp); + expect(l.info.unknownCodes).toBe(1); + expect(l.info.concepts).toBe(3); + expect(l.store.idOf('F')).toBe(store.idOf('F')); + }); + + test('a supplement property filter combines with base filters', () => { + const layers = new LayerSet([{ json: supp, build: () => ({ layer: buildLayer(store, supp), entry: null }) }]); + expect(expand(store, [inc([f('flavour', '=', 'sweet')])], { layers }).codes.sort()).toEqual(['F', 'G']); + expect(expand(store, [inc([f('flavour', '=', 'sweet'), f('concept', 'child-of', 'E')])], { layers }).codes).toEqual(['G']); + expect(expand(store, [inc([f('concept', 'is-a', 'D'), f('flavour', 'exists', 'false')])], { layers }).codes).toEqual([]); + }); + + describe('the layer cache', () => { + const { SupplementLayers, layerCache } = require('../../tx/sqlite-v2/layers'); + const { settings } = require('../../tx/sqlite-v2/settings'); + const saved = settings.supplementLayerCacheMB; + const factory = () => new SupplementLayers(store); + // one request: a filter on the supplement property, then the request ends + const request = (json, filters = [f('flavour', '=', 'sweet')]) => { + const layers = factory().forSupplements([json]); + try { + const codes = expand(store, [inc(filters)], { layers }).codes.sort(); + return { codes, layer: layers.built[0].layer }; + } finally { + layers.close(); + } + }; + const copy = (o) => JSON.parse(JSON.stringify(o)); + beforeEach(() => { layerCache.clear(); layerCache.stats = { hits: 0, misses: 0, uncached: 0, evictions: 0 }; }); + afterAll(() => { settings.supplementLayerCacheMB = saved; layerCache.clear(); }); + + test('a repeat request hits, with the same results (a tx-resource sent again is a new object)', () => { + const a = request(supp); + const b = request(copy(supp)); + expect(layerCache.stats).toMatchObject({ hits: 1, misses: 1 }); + expect(b.layer).toBe(a.layer); + expect(b.codes).toEqual(a.codes); + expect(b.codes).toEqual(['F', 'G']); + // still open after both requests ended, and read-only + expect(() => b.layer.store.db.prepare('DELETE FROM concept').run()).toThrow(/readonly|read-only|query_only/i); + expect(request(supp).codes).toEqual(['F', 'G']); + }); + + test('a changed supplement misses (same url and version)', () => { + const a = request(supp); + const changed = copy(supp); + changed.concept[1].property[0].valueCode = 'sweet'; + const b = request(changed); + expect(layerCache.stats).toMatchObject({ hits: 0, misses: 2 }); + expect(b.layer).not.toBe(a.layer); + expect(b.codes).toEqual(['D', 'F', 'G']); + expect(request(supp).codes).toEqual(['F', 'G']); + }); + + test('the bound evicts the least recently used; a layer used by a request is closed only when it ends', () => { + const bytes = buildLayer(store, supp).info.bytes; + settings.supplementLayerCacheMB = (2.5 * bytes) / 1048576; // room for two + const v = (n) => ({ ...copy(supp), version: String(n) }); + const s1 = v(1); const s2 = v(2); const s3 = v(3); + request(s1); request(s2); request(s1); // s2 is now the least recently used + const held = factory().forSupplements([s1]); + expand(store, [inc([f('flavour', '=', 'sweet')])], { layers: held }); + request(s3); + expect(layerCache.stats.evictions).toBe(1); + expect(layerCache.entries.size).toBe(2); + expect(layerCache.bytes).toBeLessThanOrEqual(layerCache.maxBytes); + request(s1); request(s3); + expect(layerCache.stats.hits).toBe(4); // s1 twice before, s1 (held), s1, s3 + request(s2); + expect(layerCache.stats.misses).toBe(4); + // s1 was evicted by s2 while `held` still uses it: it stays open until that request ends + const l1 = held.built[0].layer; + expect(layerCache.entries.has(factory().keyOf(s1))).toBe(false); + expect(l1.store.db.open).toBe(true); + held.close(); + expect(l1.store.db.open).toBe(false); + }); + + test('a layer bigger than the whole bound is built per request and not kept', () => { + settings.supplementLayerCacheMB = 0; + const a = request(supp); + const b = request(supp); + expect(layerCache.stats).toMatchObject({ hits: 0, misses: 2, uncached: 2 }); + expect(layerCache.entries.size).toBe(0); + expect(b.codes).toEqual(['F', 'G']); + expect(a.layer.store.db.open).toBe(false); + }); + }); +}); + +describe('sqlite-v2 SNOMED concept in an unknown id', () => { + test('is an error, not an empty set', () => { + const c = new Compiler({ store, dialect: { strictIn: true, unknownConcept: (cc, op, v) => { throw new Error(`The SNOMED CT Concept ${v} is not known`); } } }); + expect(() => c.filter('concept', 'in', 'D,nope')).toThrow('The SNOMED CT Concept nope is not known'); + }); +}); + +describe('sqlite-v2 SNOMED concept in / code in', () => { + // a refset contributes its members, any other concept itself (tx-ecosystem sct/*-concept-in, *-code-in) + let sct; + beforeAll(() => { + const b = new TerminologyBuilder(path.join(dir, 'sct.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://snomed.info/sct', version: 'http://snomed.info/sct/900000000000207008/version/20250201', compositional: true }); + const isa = b.property({ code: '116680003', shape: 'link', subsumption: true }); + const c = {}; + for (const code of ['138875005', '1001001', '1002001', '1003001', '1004001', '9001001']) c[code] = b.concept(code, { active: true, display: 'c ' + code }); + for (const k of ['1001001', '1002001', '1003001', '1004001', '9001001']) b.link(c[k], isa, c['138875005']); + // a simple reference set: a record relation with no columns, defined by its concept + const refset = b.property({ code: '9001001', shape: 'record', concept: c['9001001'], fields: [] }); + b.record(refset, c['1001001']); + b.record(refset, c['1002001']); + b.finish(); + sct = openStore(path.join(dir, 'sct.db')); + }); + afterAll(() => sct.close()); + const sinc = (filter) => ({ system: 'http://snomed.info/sct', filter }); + + test('plain concepts are themselves, a refset its members, code is the same property', () => { + for (const prop of ['concept', 'code']) { + const r = expand(sct, [sinc([f(prop, 'in', '1003001,1004001,1001001')])]); + expect(r.codes.sort()).toEqual(['1001001', '1003001', '1004001']); + expect(r.r.total).toBe(3); + expect(expand(sct, [sinc([f(prop, 'in', '9001001,1004001')])]).codes.sort()).toEqual(['1001001', '1002001', '1004001']); + // not-in is not one of cs-snomed.js's concept operators (SNOMED_CONCEPT_FILTER_OPS) + expect(() => expand(sct, [sinc([f(prop, 'not-in', '1003001')])])).toThrow('not understood or supported'); + } + expect(() => expand(sct, [sinc([f('code', 'in', '1003001,41000147108')])])).toThrow('The SNOMED CT Concept 41000147108 is not known'); + }); +}); + +describe('sqlite-v2 LOINC CLASSTYPE by code or name', () => { + test('a name maps to its code through the value labels (case-insensitive)', () => { + const { Compiler: C } = require('../../tx/sqlite-v2/engine/compile'); + const fake = { store: { ...store, valueLabels: (p) => (p.code === 'colour' ? { red: 'Clinical class' } : null), filterProp: (code) => store.props.get(code), propValues: store.propValues.bind(store), props: store.props, resolveCodes: store.resolveCodes.bind(store), idOf: store.idOf.bind(store), hierarchy: store.hierarchy, system: store.system }, dialect: {} }; + const c = new C(fake); + const n = c.filter('colour', '=', 'clinical CLASS'); + expect(new Engine(store).evaluate(n).size).toBe(2); // 'red' (F) and 'Red' (G): literal values match without case, as upstream + }); +}); + +describe('sqlite-v2 RxNorm REL filters', () => { + const rxinc = (filter) => ({ system: 'http://www.nlm.nih.gov/research/umls/rxnorm', filter }); + test('REL = RN uses the REL-qualified links, RELA its full set; archived concepts are never selected', () => { + expect(expand(rx, [rxinc([f('RN', '=', 'CUI:1')])]).codes).toEqual(['2']); + expect(expand(rx, [rxinc([f('has_precise_ingredient', '=', 'CUI:1')])]).codes.sort()).toEqual(['2', '3']); + expect(expand(rx, [rxinc([f('RO', '=', 'CUI:1')])]).codes.sort()).toEqual(['2', '3', '4']); + expect(expand(rx, [rxinc([f('TTY', '=', 'SCD')])]).codes.sort()).toEqual(['2', '3']); + expect(() => expand(rx, [rxinc([f('XX', '=', 'CUI:1')])])).toThrow('The filter "XX = CUI:1" is not understood or supported'); + expect(expand(rx, [rxinc([f('has_ingredient', 'in', 'CUI:1,CUI:3')])]).codes).toEqual(['4']); + expect(expand(rx, [rxinc([f('concept', 'in', '2,4,5')])]).codes.sort()).toEqual(['2', '4']); + // upstream's set only (cs-rxnorm.js doesFilter): = and in, relationship values CUI: (upstream + // also takes AUI:, over atom-level rows the file doesn't hold: refused here) + // (sqlite-v2-rxnorm-filters.test.js runs each against cs-rxnorm.js) + expect(() => expand(rx, [rxinc([f('tty', 'not-in', 'SCD')])])).toThrow('The filter "tty not-in SCD" is not understood or supported'); + expect(() => expand(rx, [rxinc([f('display', 'regex', 'drug [23]')])])).toThrow('not understood or supported'); + expect(() => expand(rx, [rxinc([f('has_ingredient', '=', '1')])])).toThrow('not understood or supported'); + expect(() => expand(rx, [rxinc([f('has_ingredient', '=', 'AUI:1')])])).toThrow('The filter "has_ingredient = AUI:1" is not understood or supported'); + expect(() => expand(rx, [rxinc([f('has_ingredient', 'in', 'CUI:1,AUI:1')])])).toThrow('not understood or supported'); + }); +}); + +describe('sqlite-v2 provider (cs-api contract)', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { Designations } = require('../../tx/library/designations'); + let factory, op; + + beforeAll(async () => { + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + factory = new SqliteV2Factory(op.i18n, path.join(dir, 'cs.db')); + await factory.load(); + }); + afterAll(() => factory.store.close()); + + test('locate, display, designations, inactive', async () => { + const p = await factory.build(op, []); + const f = await p.locate('F'); + expect(await p.display(f.context)).toBe('display F'); + expect(await p.isInactive((await p.locate('H')).context)).toBe(true); + expect((await p.locate('nope')).context).toBeNull(); + const ds = new Designations(op.i18n.languageDefinitions); + await p.designations(f.context, ds); + expect(ds.designations.map((d) => d.value)).toEqual(expect.arrayContaining(['display F', 'effervescent thing'])); + }); + + test('prefetchCodes: another provider of the file answers from the handle (a batch\'s entries)', async () => { + const t = countingTracer(); + op.tracer = t; + try { + const reader = await factory.build(op, []); + const h = await reader.prefetchCodes(['F', 'G', 'nope'], true); + const after = t.stats.statements; + const p = await factory.build(op, []); + expect(p).not.toBe(reader); + const f = await p.locate('F', h); + const ds = new Designations(op.i18n.languageDefinitions); + await p.designations(f.context, ds); + expect(ds.designations.map((d) => d.value)).toEqual(expect.arrayContaining(['display F', 'effervescent thing'])); + expect(await p.display((await p.locate('G', h)).context)).toBe('display G'); + expect((await p.locate('nope', h)).context).toBeNull(); + expect(t.stats.statements).toBe(after); + // a handle from another file is not used + expect((await p.locate('D', { store: {}, ids: new Map([['D', null]]), concepts: new Map() })).context).not.toBeNull(); + } finally { + op.tracer = null; + } + }); + + test('prefetchCodes: a handle that locate() answers from, without per-code statements', async () => { + const t = countingTracer(); + op.tracer = t; + try { + const p = await factory.build(op, []); + const h = await p.prefetchCodes(['F', 'G', 'nope'], true); + expect(h).toEqual(expect.objectContaining({ store: p.store })); + const after = t.stats.statements; + expect(after).toBe(2); // codes with their rows, designations: one statement each + const ds = new Designations(op.i18n.languageDefinitions); + const f = await p.locate('F', h); + await p.designations(f.context, ds); + expect(ds.designations.map((d) => d.value)).toEqual(expect.arrayContaining(['display F', 'effervescent thing'])); + expect(await p.display((await p.locate('G', h)).context)).toBe('display G'); + expect((await p.locate('nope', h)).context).toBeNull(); + expect(t.stats.statements).toBe(after); + // a code that was not prefetched is still read on demand + expect(await p.display((await p.locate('D', h)).context)).toBe('display D'); + expect(t.stats.statements).toBeGreaterThan(after); + } finally { + op.tracer = null; + } + }); + + test('prefetchCodes: nothing is kept on the provider; without a handle locate reads', async () => { + const t = countingTracer(); + op.tracer = t; + try { + const p = await factory.build(op, []); + const other = await factory.build(op, []); + const h1 = await p.prefetchCodes(['F'], false); + const h2 = await p.prefetchCodes(['G'], false); + const foreign = await other.prefetchCodes(['nope'], false); + let before = t.stats.statements; + // two handles in progress stay apart: each answers its own codes + expect((await p.locate('F', h1)).context.code).toBe('F'); + expect((await p.locate('G', h2)).context.code).toBe('G'); + expect(t.stats.statements).toBe(before); + // no handle: the code is looked up (a statement), and the answer is the same + expect((await p.locate('F')).context.code).toBe('F'); + expect(t.stats.statements).toBeGreaterThan(before); + // another provider's handle of this file (which says 'nope' is not there) answers too + before = t.stats.statements; + expect((await p.locate('nope', foreign)).context).toBeNull(); + expect(t.stats.statements).toBe(before); + expect(await p.prefetchCodes([], false)).toBeNull(); + } finally { + op.tracer = null; + } + }); + + test('subsumes from descendant sets', async () => { + const p = await factory.build(op, []); + expect(await p.subsumesTest('B', 'G')).toBe('subsumes'); + expect(await p.subsumesTest('G', 'C')).toBe('subsumed-by'); + expect(await p.subsumesTest('B', 'E')).toBe('not-subsumed'); + expect(await p.subsumesTest('D', 'D')).toBe('equivalent'); + }); + + test('ancestorsOf agrees with subsumesTest on every pair (CodeSystemProvider.ancestorsOf)', async () => { + const p = await factory.build(op, []); + const codes = ['root', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'Z', 'Y', 'X', 'L', 'R']; + for (const b of codes) { + const anc = await p.ancestorsOf(b); + expect(anc).toBeInstanceOf(Set); + for (const a of codes) { + if (a !== b) expect([a, b, anc.has(a)]).toEqual([a, b, (await p.subsumesTest(a, b)) === 'subsumes']); + } + } + expect([...await p.ancestorsOf('G')].sort()).toEqual(['B', 'C', 'D', 'E', 'root']); + expect(await p.ancestorsOf('root')).toEqual(new Set()); + expect(await p.ancestorsOf('nope')).toBeNull(); + expect(await p.ancestorsOf((await p.locate('G')).context)).toEqual(await p.ancestorsOf('G')); + }); + + test('ancestorsOf: a known RxNorm code sits under nothing (its subsumesTest is flat)', async () => { + const rf = new SqliteV2Factory(op.i18n, path.join(dir, 'rx.db')); + await rf.load(); + try { + const p = await rf.build(op, []); + expect(await p.ancestorsOf('2')).toEqual(new Set()); + expect(await p.subsumesTest('1', '2')).toBe('not-subsumed'); + expect(await p.ancestorsOf('nope')).toBeNull(); + } finally { + rf.store.close(); + } + }); + + test('processSelection: one page, exact total, rows already loaded', async () => { + const p = await factory.build(op, []); + const inc = [{ system: 'http://example.org/cs', filter: [{ property: 'concept', op: 'is-a', value: 'root' }] }]; + const sel = await p.processSelection({}, inc, [], false, 2, 3); + expect(sel.total).toBe(9); // root B C D E F G H Z + expect(sel.notClosed).toBe(false); + const [set] = sel.sets; + const codes = []; + while (await p.filterMore(null, set)) { + const c = await p.filterConcept(null, set); + expect(c.row).toBeTruthy(); + codes.push(await p.code(c)); + } + expect(codes.length).toBe(3); + // unsupported composes are handed back (null) + expect(await p.processSelection({}, [{ system: 'http://example.org/cs', valueSet: ['http://x'] }], [], false, 0, 10)).toBeNull(); + }); + + test('processSelection: a planner refusal is the too-costly Issue naming the value set it was told of', async () => { + const { settings } = require('../../tx/sqlite-v2/settings'); + const p = await factory.build(op, []); + const inc = [{ system: 'http://example.org/cs', filter: [{ property: 'designation', op: 'regex', value: 'x' }] }]; + const saved = settings.maxScanRows; + settings.maxScanRows = 3; + try { + const refuse = (context) => p.processSelection({}, inc, [], false, -1, -1, context).then(() => null, (e) => e); + const e = await refuse({ valueSet: { url: 'http://example.org/vs', version: '2.0' } }); + expect(e.statusCode).toBe(422); + expect(e.cause).toBe('too-costly'); + expect(e.message).toContain("'http://example.org/vs|2.0'"); + expect(e.message).toMatch(/estimated cost/); + // a value set given without url: no name to give + expect((await refuse(undefined)).message).toContain("'??'"); + } finally { + settings.maxScanRows = saved; + } + }); + + test('filter API: iteration and membership without iteration', async () => { + const p = await factory.build(op, []); + const prep = await p.getPrepContext(false); + await p.filter(prep, false, 'colour', '=', 'red'); + const [set] = await p.executeFilters(prep); + expect(await p.filterLocate(prep, set, 'F')).toBeTruthy(); + expect(await p.filterLocate(prep, set, 'D')).toBeNull(); + const it = await p.getPrepContext(true); + await p.filter(it, true, 'concept', 'is-a', 'D'); + const [s2] = await p.executeFilters(it); + expect(await p.filterSize(it, s2)).toBe(3); + await expect(p.filter(it, true, 'nonsense', '=', 'x')).rejects.toThrow('not supported'); + }); + + test('filter API: a chunk\'s designations are read when one of its codes first needs them, in one statement', async () => { + // an import expanded for its codes only (expand.js deferDetails) asks for no designation: + // none are read. The first designations() of the chunk reads the rest of the chunk's too. + const t = countingTracer(); + op.tracer = t; + try { + const p = await factory.build(op, []); + const prep = await p.getPrepContext(true); + await p.filter(prep, true, 'concept', 'is-a', 'root'); + const [set] = await p.executeFilters(prep); + const cs = []; + while (await p.filterMore(prep, set)) cs.push(await p.filterConcept(prep, set)); + expect(cs.length).toBe(9); + expect(cs.every((c) => c.row && c.desigs === null)).toBe(true); + const before = t.stats.statements; + const read = async (prov, c) => { + const ds = new Designations(op.i18n.languageDefinitions); + await prov.designations(c, ds); + return ds.designations.map((d) => [d.value, d.language && d.language.code]); + }; + const got = []; + for (const c of cs) got.push(await read(p, c)); + expect(t.stats.statements).toBe(before + 1); + expect(cs.every((c) => Array.isArray(c.desigs) && c.peers === null)).toBe(true); + // the same designations as a code located on its own + const q = await factory.build(op, []); + for (let i = 0; i < cs.length; i++) expect(got[i]).toEqual(await read(q, (await q.locate(cs[i].code)).context)); + } finally { + op.tracer = null; + } + }); +}); + +// A text filter searches one language (main since #335; CodeSystemProvider.searchLanguage): +// LOINC-style ('display' mode) English searches the display and English designations, another +// language its designations in that language, never RELATEDNAMES2 (#398); SNOMED-style ('designation' mode) designations in it only +describe('text filter in one language (store.searchText)', () => { + let ts; + beforeAll(() => { + const b = new TerminologyBuilder(path.join(dir, 'text.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/text', version: '1' }); + const use = (code) => ({ system: 'http://loinc.org', code, display: code }); + const g = b.concept('G', { active: true, display: 'Glucose [Mass/volume] in Serum' }); + const h = b.concept('H', { active: true, display: 'Hemoglobin in Blood' }); + b.item(g, { language: 'de-DE', use: use('LONG_COMMON_NAME'), text: 'Glucose [Masse/Volumen] in Serum', active: true }); + b.item(h, { language: 'de-DE', use: use('RELATEDNAMES2'), text: 'Volumen; Blut', active: true }); + b.item(h, { language: 'en-US', use: use('SHORTNAME'), text: 'Hgb Bld', active: true }); + b.finish(); + ts = openStore(path.join(dir, 'text.db')); + }); + afterAll(() => ts.close()); + const ids = (bm) => bm.toArray().map((id) => ts.conceptRows([id]).get(id).code).sort(); + + test('display mode: English searches displays, German the German names but not RELATEDNAMES2', () => { + expect(ids(ts.searchText('volumen', null, 'display', 'en'))).toEqual([]); + expect(ids(ts.searchText('volumen', null, 'display', 'de'))).toEqual(['G']); + expect(ids(ts.searchText('glucose', null, 'display', 'en'))).toEqual(['G']); + // #398: every English name (not RELATEDNAMES2), so the short name too + expect(ids(ts.searchText('hgb', null, 'display', 'en'))).toEqual(['H']); + expect(ids(ts.searchText('blut', null, 'display', 'de'))).toEqual([]); + }); + + test('designation mode: only designations in the language', () => { + expect(ids(ts.searchText('volumen', null, 'designation', 'de'))).toEqual(['G', 'H']); + expect(ids(ts.searchText('volumen', null, 'designation', 'en'))).toEqual([]); + expect(ids(ts.searchText('hgb', null, 'designation', 'en'))).toEqual(['H']); + expect(ids(ts.searchText('hgb', null, 'designation', null))).toEqual(['H']); + }); +}); diff --git a/tests/tx/sqlite-v2-filter-text.test.js b/tests/tx/sqlite-v2-filter-text.test.js new file mode 100644 index 00000000..a59e2b33 --- /dev/null +++ b/tests/tx/sqlite-v2-filter-text.test.js @@ -0,0 +1,288 @@ +'use strict'; + +// $expand text filters on sqlite-v2 answer as the built-in providers do, in their order: +// SNOMED CT cs-snomed.js + tx/sct/text-index.js (word prefixes, stems, words spread over a +// concept's descriptions, the filter split as the terms are, short words, ranking, +// the request's language), on the test edition cache and its reverse-loaded file, +// with the stored word index and without it (built in memory, as main does) +// RxNorm cs-rxnorm.js's stem search, on an RRF fixture through both importers + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { SnomedServicesFactory } = require('../../tx/cs/cs-snomed'); +const { RxNormServicesFactory } = require('../../tx/cs/cs-rxnorm'); +const { RxNormImporter } = require('../../tx/importers/import-rxnorm.module'); +const { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { importRxNormV2 } = require('../../tx/importers/import-rxnorm-v2.module'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); +const { OperationContext } = require('../../tx/operation-context'); +const { SearchFilterText } = require('../../tx/library/designations'); +const { Languages } = require('../../library/languages'); +const { TestUtilities } = require('../test-utilities'); + +const { SnomedImporter } = require('../../tx/importers/import-sct.module'); +// main's importer requires the license the edition is distributed under (cache format 21) +const SCT_LICENSE = path.join(__dirname, '../../tx/data/snomed/license.txt'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +let dir, op, langDefs, main, stored, memory, rxMain, rxV2; + +const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +// the test edition is split by module; main's cache importer reads one file of each kind +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +// RXNCONSO: RXCUI|LAT|TS|LUI|STT|SUI|ISPREF|RXAUI|SAUI|SCUI|SDUI|SAB|TTY|CODE|STR|SRL|SUPPRESS|CVF +const conso = (cui, aui, tty, str, sup = 'N', sab = 'RXNORM') => [cui, 'ENG', '', '', '', '', '', aui, '', '', '', sab, tty, cui, str, '', sup, ''].join('|'); +const archive = (cui, aui, tty, str) => [aui, '', str, '', '', '', cui, '', 'ENG', '', '', '', cui, 'RXNORM', tty, ''].join('|'); + +async function buildRxNorm() { + const rrf = path.join(dir, 'rrf'); + fs.mkdirSync(rrf); + const rows = [ + conso('6809', 'A1', 'IN', 'metformin'), + conso('6809', 'A2', 'SY', 'Glucophage generic'), + conso('583192', 'A3', 'BN', 'Metforming'), + conso('861007', 'A4', 'SCD', 'metformin hydrochloride 500 MG Oral Tablet'), + conso('861007', 'A5', 'PSN', 'metFORMIN HCl 500 MG Oral Tablet'), + conso('1043563', 'A6', 'SCD', '24 HR metformin hydrochloride 1000 MG Extended Release Oral Tablet'), + conso('1007411', 'A7', 'MIN', 'chlorpropamide / metformin', 'O'), + conso('70', 'A8', 'SY', 'metformin only a synonym'), + conso('161', 'A9', 'IN', 'acetaminophen'), + conso('202433', 'A10', 'BN', 'Tylenol'), + conso('2', 'A11', 'SCD', 'acetaminophen 325 MG Oral Tablet'), + conso('19', 'A12', 'SCD', 'acetaminophen 500 MG / oxycodone hydrochloride 5 MG Oral Tablet'), + conso('300', 'A13', 'SCD', 'Glucose-6-phosphate 2.5 MG/ML Injectable Solution'), + conso('6809', 'A14', 'BD', 'other source', 'N', 'MMSL'), + ]; + fs.writeFileSync(path.join(rrf, 'RXNCONSO.RRF'), rows.join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNATOMARCHIVE.RRF'), archive('999', 'A99', 'SCD', 'metformin archived') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNREL.RRF'), ''); + fs.writeFileSync(path.join(rrf, 'RXNSTY.RRF'), ['6809', '861007'].map((c) => `${c}|T121|||A|`).join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNSAB.RRF'), ''); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new RxNormImporter(rrf, path.join(dir, 'rx-classic.db'), '01012026', { verbose: false }).import(); + } finally { quiet.mockRestore(); } + await importRxNormV2({ source: rrf, dest: path.join(dir, 'rx-v2.db'), version: '01012026', overwrite: true, log: () => {} }); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-text-')); + langDefs = await TestUtilities.loadLanguageDefinitions(); + op = new OperationContext('en', await TestUtilities.loadTranslations(langDefs)); + // main's cache of the test edition, and the engine's file reverse-loaded from it (the same concepts and order) + const snap = path.join(dir, 'Snapshot'); + mergeSnapshot(SRC, snap); + const cache = path.join(dir, 't.cache'); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new SnomedImporter({ source: snap, dest: cache, edition: '31000003106', version: '20250909', + uri: 'http://snomed.info/sct/31000003106/version/20250909', language: 'en-US', license: SCT_LICENSE, verbose: false, overwrite: true }).run(); + } finally { quiet.mockRestore(); } + main = new SnomedServicesFactory(op.i18n, cache); + await main.load(); + await importSnomedV2FromCache({ source: cache, dest: path.join(dir, 'sct.db'), overwrite: true, log: () => {} }); + fs.copyFileSync(path.join(dir, 'sct.db'), path.join(dir, 'sct-bare.db')); + const bare = new Database(path.join(dir, 'sct-bare.db')); + // without its word index (ix_word, and the rules it was made by, meta ix.ix_word.format) + bare.exec("DELETE FROM ix_word; DELETE FROM meta WHERE key = 'ix.ix_word.format'"); + bare.close(); + stored = await loadSqliteV2Factory(op.i18n, path.join(dir, 'sct.db')); + memory = await loadSqliteV2Factory(op.i18n, path.join(dir, 'sct-bare.db')); + await buildRxNorm(); + rxMain = new RxNormServicesFactory(op.i18n, path.join(dir, 'rx-classic.db')); + await rxMain.load(); + rxV2 = await loadSqliteV2Factory(op.i18n, path.join(dir, 'rx-v2.db')); +}, 180000); + +afterAll(async () => { + for (const f of [stored, memory, rxV2]) if (f) f.store.close(); + if (rxMain && rxMain.close) await rxMain.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +const langs = (header) => (header ? Languages.fromAcceptLanguage(header, langDefs, false) : null); + +/** the codes a provider's text filter selects, in its order (as expand.js walks the first filter set) */ +async function search(factory, text, header = null) { + const p = await factory.build(op, []); + const prep = await p.getPrepContext(true, langs(header)); + await p.searchFilter(prep, new SearchFilterText(text), true); + const sets = await p.executeFilters(prep); + const out = []; + while (await p.filterMore(prep, sets[0])) out.push(await p.code(await p.filterConcept(prep, sets[0]))); + return out; +} + +/** main's answer, and the engine's on the file with the stored index and on the file without it */ +async function both(text, header = null) { + const want = await search(main, text, header); + expect([text, header, await search(stored, text, header)]).toEqual([text, header, want]); + expect([text, header, await search(memory, text, header)]).toEqual([text, header, want]); + return want; +} + +describe('SNOMED CT text filter, as cs-snomed.js', () => { + test('the importer writes the word index', () => { + const db = new Database(path.join(dir, 'sct.db'), { readonly: true }); + try { + expect(db.prepare("SELECT lang FROM ix_word WHERE word = '' ORDER BY lang").pluck().all()).toEqual(['en', 'nl']); + expect(db.prepare("SELECT count(*) FROM ix_word WHERE lang = 'en' AND word = 'liver'").pluck().get()).toBe(1); + } finally { db.close(); } + }); + + test('(2) every word may be the start of a word (#398)', async () => { + for (const f of ['hepat', 'cirrh', 'intrahep', 'liver dis', 'chronic hepat', 'hepat liver', 'chron hepat']) expect((await both(f)).length).toBeGreaterThan(0); + }); + + test('(3) a word matches the other words of its stem', async () => { + const none = []; + for (const f of ['livers', 'tendons', 'infections', 'diseases', 'cysts', 'biopsies']) if (!(await both(f)).length) none.push(f); + expect(none).toEqual([]); + }); + + test('(4) the words must be in one description (#398)', async () => { + // a concept found only through two of its descriptions + const db = new Database(path.join(dir, 'sct.db'), { readonly: true }); + let spread; + try { + spread = db.prepare(`SELECT c.code, a.text AS a, b.text AS b FROM concept c JOIN item a ON a.concept_id = c.id AND a.active = 1 + JOIN item b ON b.concept_id = c.id AND b.active = 1 AND b.id <> a.id + WHERE c.active = 1 AND lower(a.text) LIKE '%hepat%' AND lower(a.text) NOT LIKE '%liver%' AND lower(b.text) LIKE '%liver%' LIMIT 1`).get(); + } finally { db.close(); } + expect(spread).toBeTruthy(); + const words = (t) => t.toLowerCase().match(/[a-z]{4,}/g); + const f = `${words(spread.a).find((w) => w.startsWith('hepat'))} ${words(spread.b).find((w) => w === 'liver')}`; + expect(await both(f)).not.toContain(spread.code); + }); + + test('(5) the filter splits on the same punctuation as the terms', async () => { + const none = []; + for (const f of ['crigler-najjar', 'crigler najjar', "hunter's syndrome", "von gierke's", 'glucose-6-phosphate', 'alpha-1-antitrypsin']) if (!(await both(f)).length) none.push(f); + expect(none).toEqual([]); + }); + + test('(6) quotes and other punctuation are not part of a word', async () => { + expect(await both('"crigler najjar"')).toEqual(await both('crigler najjar')); + expect(await both("'liver'")).toEqual(await both('liver')); + await both('(liver)'); + }); + + test('(7) short words: a single letter or digit is a whole word; stop words; codes', async () => { + for (const f of ['ct', 'ct liver', 'nos', 'type i', 'c', 'r', '2', 'i', '-', 'of', 'of the', 'the liver', 'hepatitis b', 'hepatitis c', + '35566002', '3556', '1', '9', ' 35566 ']) await both(f); + expect((await both('ct')).length).toBeGreaterThan(0); + expect(await both('-')).toEqual([]); + expect((await both('3556'))[0]).toMatch(/^3556/); + expect((await both('35566002'))[0]).toBe('35566002'); + }); + + test('(8) ranking: exact term, then terms starting with the filter, then all words in one term, then the rest', async () => { + for (const f of ['liver', 'hepatitis', 'liver disease', 'chronic hepatitis', 'disorder', 'structure', 'entire liver', 'cirrhosis of liver']) await both(f); + const r = await both('hepatitis'); + expect(r.length).toBeGreaterThan(200); // past RANK_REFINE_LIMIT: the tail keeps concept order + }); + + test('(9) #399: the filter\'s words in its order first (at the start, together, with words between), shorter names first', async () => { + for (const f of ['hepatitis chronic', 'chronic hepatitis', 'liver disease', 'disease liver', 'disease of liver', 'cirrhosis liver', + 'liver cirrhosis', 'entire liver', 'liver entire', 'chr hep', 'hep chr']) await both(f); + }); + + test('(10) the request language: its descriptions only; the first language asked for that the edition has', async () => { + for (const [f, h] of [['hematoom', 'nl'], ['hematoom', 'nl-NL'], ['hematoom', null], ['hematoom', 'en'], ['leverbloeding', 'de, nl;q=0.5'], + ['hematoma', 'nl'], ['hematoma', null], ['lever', 'nl'], ['hemat', 'nl'], ['h', 'nl']]) await both(f, h); + expect(await both('hematoom', 'nl')).toContain('35566002'); + expect(await both('hematoom')).toEqual([]); + }); +}); + +describe('SNOMED CT: the languages a text or display regex filter chooses from', () => { + /** a fresh factory on the file, with the SQL its store prepares from now on */ + async function watched(file) { + const f = await loadSqliteV2Factory(op.i18n, path.join(dir, file)); + const sql = []; + for (const db of [f.store.db]) { + const prepare = db.prepare.bind(db); + db.prepare = (q) => { sql.push(q); return prepare(q); }; + } + return { f, sql, scanned: () => sql.some((q) => /DISTINCT language FROM main\.item/.test(q)) }; + } + async function filterCodes(factory, prop, opName, value) { + const p = await factory.build(op, []); + const prep = await p.getPrepContext(true, null); + await p.filter(prep, true, prop, opName, value); + const sets = await p.executeFilters(prep); + let n = 0; + while (await p.filterMore(prep, sets[0])) n++; + return n; + } + + test('ECL and a property filter do not list the languages; a display regex lists them from the word index', async () => { + for (const file of ['sct.db']) { + const w = await watched(file); + try { + expect(await filterCodes(w.f, 'constraint', '=', '<< 404684003')).toBeGreaterThan(0); + expect(await filterCodes(w.f, 'concept', 'is-a', '404684003')).toBeGreaterThan(0); + expect([file, w.f.store._textLangs, w.scanned()]).toEqual([file, undefined, false]); + expect(await filterCodes(w.f, 'display', 'regex', '.*hepat.*')).toBeGreaterThan(0); + expect([file, [...w.f.store._textLangs].sort(), w.scanned()]).toEqual([file, ['en', 'nl'], false]); + } finally { w.f.store.close(); } + } + }); + + test('a file without a word index reads them from its descriptions: the same languages and answers', async () => { + const w = await watched('sct-bare.db'); + try { + expect(await filterCodes(w.f, 'constraint', '=', '<< 404684003')).toBeGreaterThan(0); + expect(w.f.store._textLangs).toBeUndefined(); + const n = await filterCodes(w.f, 'display', 'regex', '.*hepat.*'); + expect([[...w.f.store._textLangs].sort(), w.scanned()]).toEqual([['en', 'nl'], true]); + expect(n).toBe(await filterCodes(stored, 'display', 'regex', '.*hepat.*')); + } finally { w.f.store.close(); } + expect(await search(memory, 'hematoom', 'nl')).toEqual(await search(stored, 'hematoom', 'nl')); + }); +}); + +describe('RxNorm text filter, as cs-rxnorm.js', () => { + const rx = async (text) => { + const want = await search(rxMain, text); + expect([text, await search(rxV2, text)]).toEqual([text, want]); + return want; + }; + + test('stems, prefixes, numbers; the best name first, then the RXCUI order (as text)', async () => { + // #398: Metforming too (metformin is the start of it); one name has every word. #399: the + // concept named metformin first, then by how closely the best name follows the filter + expect(await rx('metformin')).toEqual(['6809', '583192', '861007', '1007411', '1043563']); + for (const f of ['metf', 'METFORMIN', 'metformin 500', '500 metformin', 'hydrochloride', 'hr', '24 HR', 'acetaminophen / oxycodone', + 'tylenol', 'glucose-6', 'glucophage', 'mg', '2.5', '68', '6809', '1', 'oral tablet metformin', 'glucophage generic', 'metformin hcl']) await rx(f); + }); + + test('#399: ranked by the best name (as RXNTEXT holds it), then the RXCUI order', async () => { + for (const f of ['metformin', 'metformin 500', '500 metformin', 'tablet metformin', 'metformin oral tablet', 'oral tablet', 'mg', + 'hydrochloride metformin', '24 hr', 'hr 24', '68']) await rx(f); + }); + + test('synonym-only and archived concepts are not selected', async () => { + const r = await rx('metformin'); + expect(r).not.toContain('70'); + expect(r).not.toContain('999'); + expect(await rx('archived')).toEqual([]); + }); +}); diff --git a/tests/tx/sqlite-v2-format-cases.test.js b/tests/tx/sqlite-v2-format-cases.test.js new file mode 100644 index 00000000..50f26af5 --- /dev/null +++ b/tests/tx/sqlite-v2-format-cases.test.js @@ -0,0 +1,236 @@ +'use strict'; + +// Cases the terminology file answers through the generic reader paths (catalog shapes), over the +// real router: +// 1. a SNOMED CT description id (item external_id): as a code it is an unknown code, the same +// answer as any other unknown concept id; ECL {{ D id = ... }} selects its concept +// 2. a property with links and literals (shape 'both'): `1142139005 = 1` (main: 500 "Invalid +// concept ID: 1") selects the concepts whose concrete value is 1, `1142139005 = ` the +// concepts linked to that code +// 3. a reference set with members that are descriptions: ^ R and `concept in R` project them to +// their concepts; member filters apply to the description rows +// 4. RxNorm atom-level relationships (importer option atomRelationships): REL / RELA = AUI:x, +// as main's cs-rxnorm.js answers them from the same RRF; refused (422) without them + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); +const { importRxNormV2 } = require('../../tx/importers/import-rxnorm-v2.module'); +const { RxNormImporter } = require('../../tx/importers/import-rxnorm.module'); +const { RxNormServicesFactory } = require('../../tx/cs/cs-rxnorm'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); + +const SCT = 'http://snomed.info/sct'; +const RX = 'http://www.nlm.nih.gov/research/umls/rxnorm'; +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +const COUNT_OF_BASE = '1142139005'; // concrete #1 on 776168003, 329238006, 779430005, 1204474000 (the fixture) +const SOURCE = '329238006', TARGET = '776168003'; +const DESCRIPTION = '3761854015'; // 329238006 |Halibut liver oil 4000 unit oral capsule| +const REFSET = '723264001'; // a simple refset of the fixture (concept members) +let app, tx, dir, sct, rx, rxAtoms, classic; + +const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme|license/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +// RxNorm fixture (as tests/tx/sqlite-v2-rxnorm-filters.test.js) +const conso = (cui, aui, sab, tty, str, sup = 'N') => [cui, 'ENG', '', '', '', '', '', aui, '', '', '', sab, tty, cui, str, '', sup, ''].join('|') + '|'; +const cuiRel = (cui1, rel, cui2, rela, sab = 'RXNORM') => [cui1, '', 'CUI', rel, cui2, '', 'CUI', rela, '', '', sab, '', '', '', 'N', ''].join('|') + '|'; +const auiRel = (aui1, rel, aui2, rela, sab) => ['', aui1, 'AUI', rel, '', aui2, 'AUI', rela, '', '', sab, '', '', '', '', ''].join('|') + '|'; +function buildRrf(rrf) { + fs.mkdirSync(rrf, { recursive: true }); + fs.writeFileSync(path.join(rrf, 'RXNCONSO.RRF'), [ + conso('100', '1001', 'RXNORM', 'SCD', 'drug a 10 MG Oral Tablet'), conso('100', '1003', 'MMSL', 'BD', 'drug a tablet (MMSL)'), + conso('100', '1004', 'RXNORM', 'SY', 'drug a tablet'), + conso('200', '2001', 'RXNORM', 'IN', 'ingredient b'), conso('200', '2002', 'MMSL', 'IN', 'ingredient b (MMSL)'), + conso('300', '3001', 'RXNORM', 'SBD', 'brand c 10 MG Oral Tablet'), conso('300', '3002', 'MTHSPL', 'SU', 'brand c (SPL)'), + conso('400', '4001', 'RXNORM', 'IN', 'ingredient d'), conso('500', '5001', 'MMSL', 'BD', 'not an RxNorm concept'), + conso('90', '9001', 'RXNORM', 'SCD', 'drug e 5 MG Oral Tablet'), conso('600', '6001', 'RXNORM', 'SCD', 'obsolete drug f', 'O'), + ].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNREL.RRF'), [ + cuiRel('200', 'RO', '100', 'has_ingredient'), cuiRel('400', 'RO', '100', 'has_ingredient'), cuiRel('100', 'RB', '300', 'tradename_of'), + auiRel('2002', 'RO', '1003', 'has_ingredient', 'MMSL'), // atom 1003 (concept 100) has_ingredient atom 2002 (of 200) + auiRel('3001', 'SY', '3002', '', 'RXNORM'), // an RxNorm atom-level SY row, no RELA + auiRel('1001', 'SY', '1004', '', 'RXNORM'), // between two RxNorm atoms of 100 + auiRel('2002', 'RO', '3002', 'has_active_ingredient', 'MTHSPL'), + auiRel('2002', 'RO', '5001', 'has_active_ingredient', 'MTHSPL'), // to an atom of a concept RxNorm doesn't have + ].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNSTY.RRF'), ['100|T200|||A|', '200|T121|||A|', '300|T200|||A|', '400|T121|||A|', '90|T200|||A|', '600|T200|||A|'].join('\n') + '\n'); +} + +function use(system, f) { + const p = tx.endpoints[0].provider; + for (const key of [...p.codeSystemFactories.keys()]) if (key === system || key.startsWith(system + '|')) p.codeSystemFactories.delete(key); + p.codeSystemFactories.set(system, f); + p.codeSystemFactories.set(system + '|' + f.version(), f); + for (const e of tx.endpoints) e.expansionCache.clearAll(); +} + +async function expand(system, filters, count = 1000) { + const include = { system, filter: filters.map(([property, op, value]) => ({ property, op, value })) }; + const res = await request(app).post('/tx/r5/ValueSet/$expand').send({ resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [include] } } }, { name: 'count', valueInteger: count }] }); + if (res.status !== 200) return { status: res.status, text: (res.body.issue || []).map((i) => i.details && i.details.text).join(' | ') }; + return { status: 200, codes: (res.body.expansion.contains || []).map((c) => c.code).sort() }; +} + +const ecl = (text) => expand(SCT, [['constraint', '=', text]]); + +beforeAll(async () => { + app = await getTestApp(); + tx = getTxModule(); + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-gaps-')); + const snap = path.join(dir, 'Snapshot'); + mergeSnapshot(SRC, snap); + // 2: an active relationship typed by the concrete attribute (the property has links and literals) + const relFile = walk(snap).find((f) => /sct2_Relationship_Snapshot_/.test(path.basename(f))); + fs.appendFileSync(relFile, ['9990021000003127', '20250909', '1', '31000003106', SOURCE, TARGET, '0', COUNT_OF_BASE, + '900000000000011006', '900000000000451002'].join('\t') + '\n'); + // 3: a description as a member of the simple refset (its other members are concepts) + const simple = walk(snap).find((f) => /der2_Refset_SimpleSnapshot_/.test(path.basename(f))); + fs.appendFileSync(simple, ['e1b5c3d6-0000-4000-8000-000000000001', '20250909', '1', '31000003106', REFSET, DESCRIPTION].join('\t') + '\n'); + await importSnomedV2({ source: snap, dest: path.join(dir, 'sct.db'), edition: '31000003106', version: '20250909', overwrite: true, normalForms: false, log: () => {} }); + sct = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'sct.db')); + // 4: RxNorm, the default build and one with the atom-level relationships + const rrf = path.join(dir, 'rrf'); + buildRrf(rrf); + await importRxNormV2({ source: rrf, dest: path.join(dir, 'rx.db'), version: '01012026', overwrite: true, log: () => {} }); + await importRxNormV2({ source: rrf, dest: path.join(dir, 'rx-atoms.db'), version: '01012026', overwrite: true, atomRelationships: true, log: () => {} }); + rx = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'rx.db')); + rxAtoms = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'rx-atoms.db')); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new RxNormImporter(rrf, path.join(dir, 'rxnorm_01012026.db'), '01012026', { verbose: false, createStems: true }).import(); + } finally { quiet.mockRestore(); } + classic = new RxNormServicesFactory(tx.i18n, path.join(dir, 'rxnorm_01012026.db')); + await classic.load(); + use(SCT, sct); +}, 240000); + +afterAll(async () => { + await shutdownTestApp(); + for (const f of [sct, rx, rxAtoms]) if (f) f.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +describe('1. SNOMED CT description ids', () => { + test('$validate-code and $lookup of a description id: the answer for any unknown concept id', async () => { + use(SCT, sct); + // the same requests with a concept id the edition does not have; main (cs-snomed.js locate) + // gives an unknown concept id no message of its own, whatever the id is + const UNKNOWN = '99999999999'; + const answers = async (code) => { + const cs = await request(app).get(`/tx/r5/CodeSystem/$validate-code?url=${encodeURIComponent(SCT)}&code=${code}`); + const vs = await request(app).post('/tx/r5/ValueSet/$validate-code').send({ resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: SCT }] } } }, + { name: 'coding', valueCoding: { system: SCT, code } }] }); + const l = await request(app).get(`/tx/r5/CodeSystem/$lookup?system=${encodeURIComponent(SCT)}&code=${code}`); + return JSON.stringify([cs.status, cs.body, vs.status, vs.body, l.status, l.body]).split(code).join(''); + }; + const d = await answers(DESCRIPTION); + expect(d).toBe(await answers(UNKNOWN)); + expect(d).not.toContain('description id'); + // a concept id is as before + const c = await request(app).get(`/tx/r5/CodeSystem/$validate-code?url=${encodeURIComponent(SCT)}&code=${SOURCE}`); + expect(c.body.parameter.find((p) => p.name === 'result').valueBoolean).toBe(true); + }); + + test('ECL {{ D id = ... }}: the concept of that description, with the block\'s other filters on the same description', async () => { + expect(await ecl(`* {{ D id = ${DESCRIPTION} }}`)).toEqual({ status: 200, codes: [SOURCE] }); + expect(await ecl(`* {{ D id = ${DESCRIPTION}, term = "halibut" }}`)).toEqual({ status: 200, codes: [SOURCE] }); + // the description is a synonym, not an FSN + expect(await ecl(`* {{ D id = ${DESCRIPTION}, type = fsn }}`)).toEqual({ status: 200, codes: [] }); + expect(await ecl(`* {{ D id = (${DESCRIPTION} 3732533010) }}`)).toEqual({ status: 200, codes: [SOURCE, TARGET].sort() }); + expect(await ecl('* {{ D id = 999999999999019 }}')).toEqual({ status: 200, codes: [] }); + }); +}); + +describe('2. a property with links and literals', () => { + test('the catalog row is shape both', () => { + expect(sct.store.filterProp(COUNT_OF_BASE).shape).toBe('both'); + }); + + test(`${COUNT_OF_BASE} = 1: the concepts whose concrete value is 1 (main: 500 Invalid concept ID: 1)`, async () => { + const r = await expand(SCT, [[COUNT_OF_BASE, '=', '1']]); + expect(r.status).toBe(200); + expect(r.codes).toEqual(expect.arrayContaining([SOURCE, TARGET, '779430005', '1204474000'])); + expect(await expand(SCT, [[COUNT_OF_BASE, '=', '#1']])).toEqual(r); + expect(await expand(SCT, [[COUNT_OF_BASE, '=', '7']])).toEqual({ status: 200, codes: [] }); + }); + + test(`${COUNT_OF_BASE} = : the concepts linked to it`, async () => { + expect(await expand(SCT, [[COUNT_OF_BASE, '=', TARGET]])).toEqual({ status: 200, codes: [SOURCE] }); + }); + + test('ECL: a concrete value and a concept value on the same attribute', async () => { + const lits = await ecl(`* : ${COUNT_OF_BASE} = #1`); + expect(lits.codes).toEqual(expect.arrayContaining([SOURCE, TARGET])); + expect(await ecl(`* : ${COUNT_OF_BASE} = ${TARGET}`)).toEqual({ status: 200, codes: [SOURCE] }); + }); +}); + +describe('3. a reference set with description members', () => { + test('^ R and concept in R: the concept members and the concepts of the description members', async () => { + const members = sct.store.getSet(7, 0, sct.store.idOf(REFSET)); + expect(members.has(sct.store.idOf(SOURCE))).toBe(true); // projected from the description row + const r = await ecl(`^ ${REFSET}`); + expect(r.codes).toContain(SOURCE); + expect(r.codes).toContain('302525009'); // a concept member + expect(await expand(SCT, [['concept', 'in', REFSET]])).toEqual(r); + }); + + test('member filters apply to the description row, then project', async () => { + expect(await ecl(`^ ${REFSET} {{ M moduleId = 31000003106 }}`)).toEqual({ status: 200, codes: [SOURCE] }); + }); +}); + +describe('4. RxNorm atom-level relationships (importer option atomRelationships)', () => { + const AUI = [ + [['has_ingredient', '=', 'AUI:2002']], [['has_ingredient', 'in', 'CUI:400,AUI:2002']], [['RO', '=', 'AUI:2002']], + [['SY', '=', 'AUI:3001']], [['SY', '=', 'AUI:1001']], [['has_active_ingredient', '=', 'AUI:2002']], [['has_ingredient', '=', 'AUI:9999']], + ]; + const run = async (f, filters) => { use(RX, f); try { return await expand(RX, filters); } finally { use(SCT, sct); } }; + + test.each(AUI)('every source\'s atom rows: as main (cs-rxnorm.js) %j', async (...filters) => { + const want = await run(classic, filters); + expect(want.status).toBe(200); + expect(await run(rxAtoms, filters)).toEqual(want); + }); + + test('the statements: value RXAUI1 -> the concept of RXAUI2, one per row under its (REL, RELA) pair; no other source\'s atom is an item', () => { + const db = rxAtoms.store.db; + const rows = db.prepare(`SELECT p.code, i.value, c.code FROM identifier i JOIN property p ON p.id = i.property_id JOIN concept c ON c.id = i.subject_id + ORDER BY 1, 2, 3`).raw().all(); + // 2002 -> 5001 (concept 500, no RxNorm atom) is left out; values are stored as integers + expect(rows).toEqual([['AUI:RO:has_active_ingredient', 2002, '300'], ['AUI:RO:has_ingredient', 2002, '100'], ['AUI:SY:', 1001, '100'], ['AUI:SY:', 3001, '300']]); + const members = db.prepare(`SELECT u.code, group_concat(m.code, ',' ORDER BY m.code) FROM property_member x JOIN property u ON u.id = x.parent_id JOIN property m ON m.id = x.child_id + WHERE u.code LIKE 'AUI:%' GROUP BY u.code ORDER BY u.code`).raw().all(); + expect(members).toEqual([['AUI:RO', 'AUI:RO:has_active_ingredient,AUI:RO:has_ingredient'], ['AUI:SY', 'AUI:SY:'], + ['AUI:has_active_ingredient', 'AUI:RO:has_active_ingredient'], ['AUI:has_ingredient', 'AUI:RO:has_ingredient']]); + expect(db.prepare("SELECT count(*) FROM item WHERE external_id IN ('1003', '2002', '3002')").pluck().get()).toBe(0); + }); + + test('the default build has no atom rows: AUI: values are refused (422), CUI: values answered as main', async () => { + expect(rx.store.hasAtomRelationships).toBe(false); + const r = await run(rx, AUI[0]); + expect(r.status).toBe(422); + expect(await run(rx, [['has_ingredient', '=', 'CUI:200']])).toEqual(await run(classic, [['has_ingredient', '=', 'CUI:200']])); + expect(await run(rxAtoms, [['has_ingredient', '=', 'CUI:200']])).toEqual(await run(classic, [['has_ingredient', '=', 'CUI:200']])); + }); +}); diff --git a/tests/tx/sqlite-v2-loinc-classic.test.js b/tests/tx/sqlite-v2-loinc-classic.test.js new file mode 100644 index 00000000..b0998ab1 --- /dev/null +++ b/tests/tx/sqlite-v2-loinc-classic.test.js @@ -0,0 +1,137 @@ +'use strict'; + +// Reverse loader (FHIRsmith classic LOINC db -> terminology file, import-loinc-v2-classic.module.js): build +// a classic db from the LOINC test fixture in tx/data/loinc with main's importer, reverse-load it, +// and compare with the CSV import of the same release. Every concept, link, literal, item +// and stored set must agree; what a classic file cannot carry is the answers' SequenceNumber (the +// list order stands in for it, so the order of each list agrees). Then the shape of older classic +// files (loinc-2.77-a.db): a blank Answer code '' shared by the externally defined lists, and +// CLASSTYPE stored as its description. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { importLoincV2 } = require('../../tx/importers/import-loinc-v2.module'); +const { importLoincV2FromClassic } = require('../../tx/importers/import-loinc-v2-classic.module'); +const { LoincDataMigrator } = require('../../tx/importers/import-loinc.module'); +const { diffFiles } = require('../../tx/importers/sqlite-v2/diff'); +const { openStore } = require('../../tx/sqlite-v2/store'); + +const SRC = path.resolve(__dirname, '../../tx/data/loinc'); +const VERSION = '2.80-test'; +let dir, report, summary; + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'loinc-from-classic-')); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new LoincDataMigrator().migrate(SRC, path.join(dir, 'classic.db'), VERSION, { verbose: false, mainOnly: false }); + } finally { quiet.mockRestore(); } + await importLoincV2({ source: SRC, dest: path.join(dir, 'csv.db'), version: VERSION, overwrite: true, log: () => {} }); + summary = await importLoincV2FromClassic({ source: path.join(dir, 'classic.db'), dest: path.join(dir, 'rev.db'), overwrite: true, log: () => {} }); + report = diffFiles(path.join(dir, 'csv.db'), path.join(dir, 'rev.db'), { examples: 20 }); +}, 120000); + +afterAll(() => { if (dir) fs.rmSync(dir, { recursive: true, force: true }); }); + +test('the same concepts, numbered the same, with the version from the classic Config', () => { + expect(summary.concepts).toBe(report.codeSystem_a.concept_count); + expect(summary.concepts).toBe(483); // 322 terms + 147 parts + 3 answer lists + 8 answers + 3 hierarchy-only nodes + expect(report.codeSystem_b).toEqual(report.codeSystem_a); + expect(report.codeSystem_b.version).toBe(VERSION); + expect(report.facts.concept.onlyA + report.facts.concept.onlyB).toBe(0); + expect(report.sets.identicalNumbering).toBe(true); +}); + +test.each(['link', 'literal', 'item', 'item_use', 'property', 'property_member', 'value_label'])('%s: every row agrees', (name) => { + const f = report.facts[name]; + expect([f.onlyA, f.onlyB, report.tables[name].a]).toEqual([0, 0, report.tables[name].b]); +}); + +test('external maps agree (main stores them in ExternalCodes / ExternalMappings)', () => { + const f = report.facts.mapping; + expect(report.tables.mapping.a).toBe(report.tables.mapping.b); + expect([f.onlyA, f.onlyB]).toEqual([0, 0]); +}); + +test('every stored set agrees: descendants (path closure), properties, has-property', () => { + for (const [kind, s] of Object.entries(report.sets.byKind)) { + expect({ kind, differ: s.differ, onlyA: s.onlyA, onlyB: s.onlyB }).toEqual({ kind, differ: 0, onlyA: 0, onlyB: 0 }); + } +}); + +test('the hierarchy order ($lookup parent and child) agrees: the classic Relationships rows against the release file', () => { + // each concept's entries as the reader gives them (stored arrays, or the parent links merged by seq) + const entries = (f) => { + const S = openStore(f, { unregistered: true }); + try { + const code = (id) => S.conceptRows([id]).get(id).code; + const out = []; + for (let id = 1; id <= S.conceptCount; id++) { + const e = S.hierarchyOrderOf(id); + if (e && e.length) out.push([code(id), [...e].map((x) => (x & 0x80000000 ? 'c' : 'p') + code(x & 0x7fffffff))]); + } + return out; + } finally { S.close(); } + }; + const a = entries(path.join(dir, 'csv.db')); + expect(a.length).toBeGreaterThan(20); + expect(entries(path.join(dir, 'rev.db'))).toEqual(a); +}); + +test('answer lists keep their order (the classic file has no SequenceNumber)', () => { + const order = (file) => { + const db = new Database(file, { readonly: true }); + try { + return db.prepare(`SELECT r.code list, group_concat(c.code) members FROM (SELECT l.* FROM link l JOIN property p ON p.id = l.property_id + WHERE p.code = 'Answer' ORDER BY l.subject_id, l.seq, l.target_id) m + JOIN concept r ON r.id = m.subject_id JOIN concept c ON c.id = m.target_id GROUP BY r.code ORDER BY r.code`).all(); + } finally { db.close(); } + }; + const a = order(path.join(dir, 'csv.db')); + expect(a.length).toBeGreaterThan(0); + expect(order(path.join(dir, 'rev.db'))).toEqual(a); +}); + +test('the system order (main\'s key order and whole-system walk, ix_order) agrees', () => { + const arrays = (file) => { + const db = new Database(file, { readonly: true }); + try { + return db.prepare("SELECT name, hex(group_concat(data, x'')) FROM (SELECT name, data FROM ix_order WHERE name IN ('rank', 'ids', 'walk', 'active') ORDER BY name, block) GROUP BY name ORDER BY name").raw().all(); + } finally { db.close(); } + }; + const a = arrays(path.join(dir, 'csv.db')); + expect(a.map((r) => r[0])).toEqual(['active', 'ids', 'rank', 'walk']); + expect(arrays(path.join(dir, 'rev.db'))).toEqual(a); +}); + +test('an older classic file: the blank Answer code is dropped with its links, CLASSTYPE comes back as its code', async () => { + const old = path.join(dir, 'old.db'); + fs.copyFileSync(path.join(dir, 'classic.db'), old); + const db = new Database(old); + const k = db.prepare('SELECT max(CodeKey) + 1 FROM Codes').pluck().get(); + db.prepare("INSERT INTO Codes (CodeKey, Code, Type, RelationshipKey, StatusKey, Description) VALUES (?, '', 4, NULL, 0, '')").run(k); + const list = db.prepare("SELECT CodeKey FROM Codes WHERE Type = 3 ORDER BY CodeKey LIMIT 1").pluck().get(); + const rk = db.prepare('SELECT max(RelationshipKey) + 1 FROM Relationships').pluck().get(); + const rel = (t) => db.prepare('SELECT RelationshipTypeKey FROM RelationshipTypes WHERE Description = ?').pluck().get(t); + db.prepare('INSERT INTO Relationships VALUES (?, ?, ?, ?, 0)').run(rk, rel('Answer'), list, k); + db.prepare('INSERT INTO Relationships VALUES (?, ?, ?, ?, 0)').run(rk + 1, rel('AnswerList'), k, list); + // CLASSTYPE as the older importer stored it + const ct = db.prepare("SELECT PropertyTypeKey FROM PropertyTypes WHERE Description = 'CLASSTYPE'").pluck().get(); + const names = { 1: 'Laboratory class', 2: 'Clinical class', 3: 'Claims attachment', 4: 'Surveys' }; + for (const [code, name] of Object.entries(names)) { + db.prepare(`UPDATE PropertyValues SET Value = ? WHERE Value = ? AND PropertyValueKey IN (SELECT PropertyValueKey FROM Properties WHERE PropertyTypeKey = ?)`).run(name, code, ct); + } + db.close(); + const s = await importLoincV2FromClassic({ source: old, dest: path.join(dir, 'old-rev.db'), overwrite: true, log: () => {} }); + expect([s.concepts, s.importer.blankCodesDropped, s.importer.linksToDropped]).toEqual([483, 1, 1]); + const r = diffFiles(path.join(dir, 'csv.db'), path.join(dir, 'old-rev.db')); + for (const name of ['concept', 'link', 'literal', 'item']) expect([name, r.facts[name].onlyA, r.facts[name].onlyB]).toEqual([name, 0, 0]); + for (const s2 of Object.values(r.sets.byKind)) expect([s2.differ, s2.onlyA, s2.onlyB]).toEqual([0, 0, 0]); +}); + +test('a version that does not match the classic Config is refused', async () => { + await expect(importLoincV2FromClassic({ source: path.join(dir, 'classic.db'), dest: path.join(dir, 'x.db'), version: '9.99', overwrite: true, log: () => {} })) + .rejects.toThrow(/classic db says 2.80-test/); +}); diff --git a/tests/tx/sqlite-v2-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js new file mode 100644 index 00000000..4e8b989a --- /dev/null +++ b/tests/tx/sqlite-v2-loinc.test.js @@ -0,0 +1,797 @@ +'use strict'; + +// LOINC on sqlite-v2: the importer (tx/importers/import-loinc-v2.module.js) and the LOINC +// dialect (tx/sqlite-v2/dialects.js) over the LOINC test fixture in tx/data/loinc, the one the +// classic tests use (tests/cs/cs-loinc.test.js). Each request runs twice through the real +// router: once on the sqlite-v2 file, once on main's provider (tx/cs/cs-loinc.js) over the same +// fixture; where main's answer is defined, the two must agree (as sets where order is not). +// +// The fixture gets small additions in a temporary copy, so the cases have something to find: +// an externally defined answer list (a row with no AnswerStringId, as AnswerList.csv in 2.83 has +// 65 of) linked to a term, a third-party copyright notice on one term, and a row in LL744-4 for +// an answer whose external code is on that list's row only (as LA11840-8's SNOMED CT code is in 2.83). + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const request = require('supertest'); +const Database = require('better-sqlite3'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { importLoincV2 } = require('../../tx/importers/import-loinc-v2.module'); +const { LoincDataMigrator } = require('../../tx/importers/import-loinc.module'); +const { splitCsv } = require('../../tx/importers/sqlite-v2/text'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); +const { LoincServicesFactory } = require('../../tx/cs/cs-loinc'); +const { countingTracer } = require('./sqlite-v2-counting-tracer'); +const { SqliteV2Provider } = require('../../tx/sqlite-v2/provider'); + +const L = 'http://loinc.org'; +const SRC = path.resolve(__dirname, '../../tx/data/loinc'); +const VERSION = '2.80-test'; +const EXT_LIST = 'LL1892-0'; // externally defined: no answers +const COPYRIGHT_TERM = '595-9'; +const LATE_MAPPED = 'LA32972-4'; // in LL6136-7 with no external code, then in LL744-4 with one + +let app, tx, dir, v2, classic; + +const q = (v) => '"' + String(v).replace(/"/g, '""') + '"'; +const csvLine = (fields) => fields.map(q).join(','); + +/** the fixture, with the two additions */ +function buildFixture(dest) { + fs.cpSync(SRC, dest, { recursive: true }); + const loinc = path.join(dest, 'LoincTable', 'Loinc.csv'); + const lines = fs.readFileSync(loinc, 'utf8').split(/\r?\n/); + const header = splitCsv(lines[0]); + const col = header.indexOf('EXTERNAL_COPYRIGHT_NOTICE'); + const k = lines.findIndex((l) => l.startsWith(q(COPYRIGHT_TERM) + ',')); + const row = splitCsv(lines[k]); + row[col] = 'Copyright (c) A Third Party. Used by permission.'; + lines[k] = csvLine(row); + fs.writeFileSync(loinc, lines.join('\n')); + // AnswerListId, AnswerListName, AnswerListOID, ExtDefinedYN, ExtDefinedAnswerListCodeSystem, + // ExtDefinedAnswerListLink, AnswerStringId, LocalAnswerCode, LocalAnswerCodeSystem, SequenceNumber, + // DisplayText, ExtCodeId, ExtCodeDisplayName, ExtCodeSystem, ExtCodeSystemVersion, + // ExtCodeSystemCopyrightNotice, SubsequentTextPrompt, Description, Score + const answers = path.join(dest, 'AccessoryFiles', 'AnswerFile', 'AnswerList.csv'); + fs.writeFileSync(answers, fs.readFileSync(answers, 'utf8').replace(/\s*$/, '') + '\n' + + csvLine(['LL744-4', 'Detected|Not det', '1.3.6.1.4.1.12009.10.1.3226', 'N', '', '', LATE_MAPPED, '', '', '3', 'Not met', + '9990001000', 'Not met (synthetic)', 'http://snomed.info/sct', 'http://snomed.info/sct/900000000000207008/version/20240701', '', '', '', '']) + '\n' + + csvLine([EXT_LIST, 'ICD-9_ICD-10', '1.3.6.1.4.1.12009.10.1.1892', 'Y', 'ICD-10', 'http://www.who.int/classifications/icd10', + '', '', '', '', '', '', '', '', '', '', '', '', '']) + '\n'); + const links = path.join(dest, 'AccessoryFiles', 'AnswerFile', 'LoincAnswerListLink.csv'); + const body = fs.readFileSync(links, 'utf8').replace(/\s*$/, ''); + fs.writeFileSync(links, body + '\n' + csvLine(['10332-5', 'Cortisol', EXT_LIST, 'ICD-9_ICD-10', 'EXAMPLE', '']) + '\n'); +} + +/** serve http://loinc.org from this factory only */ +function use(f) { + const p = tx.endpoints[0].provider; + for (const key of [...p.codeSystemFactories.keys()]) if (key === L || key.startsWith(L + '|')) p.codeSystemFactories.delete(key); + p.codeSystemFactories.set(L, f); + p.codeSystemFactories.set(L + '|' + f.version(), f); + for (const e of tx.endpoints) e.expansionCache.clearAll(); +} + +/** the same request on both engines: { v2, classic } */ +async function both(fn) { + use(v2); + const a = await fn('v2'); + use(classic); + const b = await fn('classic'); + use(v2); + return { v2: a, classic: b }; +} + +const vs = (include, exclude) => ({ resourceType: 'ValueSet', status: 'active', compose: Object.assign({ include }, exclude ? { exclude } : {}) }); +const filterVs = (...filters) => vs([{ system: L, filter: filters.map(([property, op, value]) => ({ property, op, value })) }]); + +function params(o) { + const parameter = []; + for (const [name, v] of Object.entries(o)) { + if (name === 'valueSet') parameter.push({ name, resource: v }); + else if (Array.isArray(v)) for (const x of v) parameter.push({ name, valueString: x }); + else if (typeof v === 'number') parameter.push({ name, valueInteger: v }); + else if (typeof v === 'boolean') parameter.push({ name, valueBoolean: v }); + else if (name === 'url') parameter.push({ name, valueUri: v }); + else parameter.push({ name, valueString: v }); + } + return { resourceType: 'Parameters', parameter }; +} + +async function expand(o) { + const res = await request(app).post('/tx/r5/ValueSet/$expand').send(params(o)); + if (res.status !== 200) return { status: res.status, text: (res.body.issue || []).map((i) => i.details?.text || i.diagnostics).join('; ') }; + return res.body.expansion; +} +const codes = (e) => (e.contains || []).map((c) => c.code); +const sorted = (a) => [...a].sort(); + +/** a concept as listed: code, display, inactive, designations and properties, order-free */ +function listed(c) { + const val = (p) => p.valueCode ?? p.valueString ?? p.valueBoolean ?? p.valueInteger ?? (p.valueCoding && sortedJson(p.valueCoding)); + return [c.code, c.display || '', !!c.inactive, + sorted((c.designation || []).map((d) => [d.language, d.use && d.use.code, d.value].join('|'))).join(';'), + sorted((c.property || []).map((p) => p.code + '=' + val(p))).join(';')].join(' # '); +} +const sortedJson = (o) => JSON.stringify(Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)))); + +/** a Parameters body as an order-free list of name=value (parts flattened) */ +function flatParams(body) { + const val = (p) => p.valueCode ?? p.valueString ?? p.valueBoolean ?? p.valueInteger ?? p.valueUri ?? p.valueDecimal ?? + (p.valueCoding && sortedJson(p.valueCoding)) ?? (p.valueCodeableConcept && JSON.stringify(p.valueCodeableConcept)); + const one = (p) => p.part ? p.name + '(' + sorted(p.part.map(one)).join(',') + ')' : p.name + '=' + val(p); + return sorted((body.parameter || []).map((p) => (p.resource ? p.name + ':' + JSON.stringify(p.resource.issue || p.resource) : one(p)))); +} + +beforeAll(async () => { + app = await getTestApp(); + tx = getTxModule(); + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-loinc-')); + buildFixture(path.join(dir, 'src')); + await importLoincV2({ source: path.join(dir, 'src'), dest: path.join(dir, 'v2.db'), version: VERSION, overwrite: true, log: () => {} }); + await new LoincDataMigrator().migrate(path.join(dir, 'src'), path.join(dir, 'classic.db'), VERSION, { verbose: false, mainOnly: false }); + v2 = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'v2.db')); + classic = new LoincServicesFactory(tx.i18n, path.join(dir, 'classic.db')); + await classic.load(); + use(v2); +}, 180000); + +afterAll(async () => { + await shutdownTestApp(); + if (v2) v2.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +// ---- the importer ------------------------------------------------------------------------- + +describe('LOINC v2 importer over the test fixture', () => { + let db, cdb; + beforeAll(() => { + db = new Database(path.join(dir, 'v2.db'), { readonly: true }); + cdb = new Database(path.join(dir, 'classic.db'), { readonly: true }); + }); + afterAll(() => { db.close(); cdb.close(); }); + const id = (code) => db.prepare('SELECT id FROM concept WHERE code = ?').pluck().get(code); + const links = (code, prop) => db.prepare(`SELECT t.code FROM link l JOIN concept s ON s.id = l.subject_id + JOIN concept t ON t.id = l.target_id JOIN property p ON p.id = l.property_id WHERE s.code = ? AND p.code = ? ORDER BY t.code`).pluck().all(code, prop); + + test('every term, part, answer list, answer and hierarchy node once: the same codes as main', () => { + const cs = db.prepare('SELECT * FROM code_system WHERE served = 1').get(); + // 322 terms + 147 parts + 4 answer lists (one externally defined) + 8 answers + 3 hierarchy-only nodes + expect([cs.uri, cs.version, cs.concept_count, cs.active_count]).toEqual([L, VERSION, 484, 482]); + const v2Codes = db.prepare('SELECT code FROM concept').pluck().all(); + const mainCodes = cdb.prepare('SELECT Code FROM Codes').pluck().all(); + expect(sorted(v2Codes)).toEqual(sorted(mainCodes)); + expect(new Set(v2Codes).size).toBe(v2Codes.length); + }); + + test('an externally defined answer list is a code with no answers, and no blank code (as main)', () => { + expect(id('')).toBeUndefined(); + expect(cdb.prepare("SELECT count(*) FROM Codes WHERE Code = ''").pluck().get()).toBe(0); + expect(db.prepare('SELECT display FROM concept WHERE code = ?').pluck().get(EXT_LIST)).toBe('ICD-9_ICD-10'); + expect(links(EXT_LIST, 'Answer')).toEqual([]); + expect(links(EXT_LIST, 'answers-for')).toEqual(['10332-5']); + // a list's members are its Answer links + expect(db.prepare("SELECT count(*) FROM link WHERE subject_id = ? AND property_id = (SELECT id FROM property WHERE code = 'Answer')") + .pluck().get(id(EXT_LIST))).toBe(0); + }); + + test('an answer\'s external code on a later list\'s row is kept, once, as main keeps it', () => { + const v = db.prepare('SELECT m.system, m.version, m.code, m.display, m.relationship FROM mapping m JOIN concept c ON c.id = m.concept_id WHERE c.code = ?') + .all(LATE_MAPPED); + expect(v).toEqual([{ system: 'http://snomed.info/sct', version: 'http://snomed.info/sct/900000000000207008/version/20240701', + code: '9990001000', display: 'Not met (synthetic)', relationship: 'equivalent' }]); + const m = cdb.prepare(`SELECT e.System system, e.Version version, e.Code code, e.Display display, m.Equivalence relationship + FROM ExternalMappings m JOIN Codes c ON c.CodeKey = m.CodeKey JOIN ExternalCodes e ON e.ExternalCodeKey = m.ExternalCodeKey WHERE c.Code = ?`).all(LATE_MAPPED); + expect(v).toEqual(m); + // an answer mapped on its first row only, in one list + expect(db.prepare('SELECT count(*) FROM mapping m JOIN concept c ON c.id = m.concept_id WHERE c.code = ?').pluck().get('LA6576-8')).toBe(1); + }); + + test('inactive iff DISCOURAGED; STATUS literal on terms and parts', () => { + expect(db.prepare('SELECT code FROM concept WHERE active = 0 ORDER BY code').pluck().all()).toEqual(['22760-3', '42569-4']); + const status = db.prepare(`SELECT l.value FROM literal l JOIN property p ON p.id = l.property_id + WHERE l.subject_id = ? AND p.code = 'STATUS'`).pluck(); + expect(status.all(id('22760-3'))).toEqual(['DISCOURAGED']); + expect(status.all(id('10550-2'))).toEqual(['DEPRECATED']); + expect(status.all(id('LP7786-9'))).toEqual(['ACTIVE']); + }); + + test('properties: part links, literals, hierarchy and answer properties; the inverse and closure rows', () => { + const defs = Object.fromEntries(db.prepare('SELECT code, shape, subsumption FROM property').all().map((r) => [r.code, [r.shape, r.subsumption]])); + for (const p of ['COMPONENT', 'PROPERTY', 'TIME_ASPCT', 'SYSTEM', 'SCALE_TYP', 'METHOD_TYP', 'CLASS', 'Answer', 'answers-for']) expect(defs[p]).toEqual(['link', 0]); + for (const p of ['CLASSTYPE', 'ORDER_OBS', 'EXAMPLE_UNITS', 'UNITSREQUIRED', 'Copyright', 'STATUS']) expect(defs[p]).toEqual(['literal', 0]); + expect(defs.parent).toEqual(['link', 1]); + const row = (code) => db.prepare('SELECT p.code, i.code AS inverse_of, p.filterable, p.ordered, p.n_rows FROM property p LEFT JOIN property i ON i.id = p.inverse_of WHERE p.code = ?').get(code); + expect(row('child')).toEqual({ code: 'child', inverse_of: 'parent', filterable: 1, ordered: 0, n_rows: 0 }); + expect(row('AnswerList')).toEqual({ code: 'AnswerList', inverse_of: 'Answer|answers-for', filterable: 1, ordered: 0, n_rows: 0 }); + expect(db.prepare("SELECT c.code FROM property_member m JOIN property p ON p.id = m.parent_id JOIN property c ON c.id = m.child_id WHERE p.code = 'Answer|answers-for' ORDER BY c.code").pluck().all()).toEqual(['Answer', 'answers-for']); + expect(row('Answer').ordered).toBe(1); + expect(db.prepare("SELECT a.code FROM property h JOIN property a ON a.id = h.closure_from WHERE h.code = 'parent'").pluck().get()).toBe('ancestor'); + expect(db.prepare("SELECT value, display FROM value_label WHERE property_id = (SELECT id FROM property WHERE code = 'CLASSTYPE') ORDER BY value").raw().all()) + .toEqual([['1', 'Laboratory class'], ['2', 'Clinical class'], ['3', 'Claims attachment'], ['4', 'Surveys']]); + // 10332-5: the six axes from LoincPartLink_Primary, CLASS from Loinc.csv + const axes = Object.fromEntries(['COMPONENT', 'PROPERTY', 'TIME_ASPCT', 'SYSTEM', 'SCALE_TYP', 'CLASS'].map((p) => [p, links('10332-5', p)])); + // (its CLASS, CHAL, has no CLASS part in the fixture: no link, as main) + expect(axes).toEqual({ COMPONENT: ['LP305473-3'], PROPERTY: ['LP6827-2'], TIME_ASPCT: ['LP6960-1'], SYSTEM: ['LP7576-4'], SCALE_TYP: ['LP7753-9'], CLASS: [] }); + expect(links('6298-4', 'CLASS')).toEqual(['LP7786-9']); + // the third-party notice, on that term only + expect(db.prepare(`SELECT c.code FROM literal l JOIN concept c ON c.id = l.subject_id + JOIN property p ON p.id = l.property_id WHERE p.code = 'Copyright' AND l.value != ''`).pluck().all()).toEqual([COPYRIGHT_TERM]); + }); + + test('answer lists: Answer links, members in SequenceNumber order, answers-for links', () => { + expect(links('LL6136-7', 'Answer')).toEqual(['LA10105-7', 'LA32971-6', 'LA32972-4', 'LA9040-2']); + // the SequenceNumber is the Answer link's seq + const members = db.prepare(`SELECT c.code, l.seq FROM link l JOIN concept c ON c.id = l.target_id + WHERE l.subject_id = ? AND l.property_id = (SELECT id FROM property WHERE code = 'Answer') ORDER BY l.seq`).raw().all(id('LL6136-7')); + expect(members).toEqual([['LA32971-6', 1], ['LA32972-4', 2], ['LA9040-2', 3], ['LA10105-7', 4]]); + expect(links('LL360-9', 'answers-for')).toEqual(['100041-3', '100865-5', '101448-9', '106016-9', '107188-5', '95675-5']); + }); + + test('hierarchy: parent links from IMMEDIATE_PARENT, ancestors from PATH_TO_ROOT', () => { + expect(links('LP31398-8', 'parent')).toEqual(['LP7786-9']); + // LP14355-9 is listed under two paths; one parent link (as main, cs-loinc.test.js) + expect(links('LP14355-9', 'parent')).toEqual(['LP31398-8']); + }); + + test('designations: English names, consumer names, every linguistic variant language', () => { + const langs = db.prepare('SELECT DISTINCT language FROM item ORDER BY language').pluck().all(); + const files = fs.readdirSync(path.join(SRC, 'AccessoryFiles', 'LinguisticVariants')).map((f) => /^([a-z]{2})([A-Z]{2})\d+LinguisticVariant/.exec(f)).filter(Boolean).map((m) => `${m[1]}-${m[2]}`); + expect(files.length).toBeGreaterThan(10); + expect(langs).toEqual(sorted(['en-US', ...files])); + const uses = db.prepare(`SELECT DISTINCT u.code FROM item d JOIN item_use u ON u.use_id = d.use_id WHERE d.concept_id = ? ORDER BY u.code`).pluck().all(id('10332-5')); + expect(uses).toEqual(expect.arrayContaining(['ConsumerName', 'LONG_COMMON_NAME', 'RELATEDNAMES2', 'SHORTNAME'])); + }); + + test('numbering: concept ids, not main\'s CodeKey; active ids first, ancestors before descendants', () => { + // the id is the builder's own numbering; main's CodeKey order is kept apart, in ix_order + expect(db.prepare("SELECT count(*) FROM pragma_table_info('concept') WHERE name IN ('code_key', 'main_seq', 'seq')").pluck().get()).toBe(0); + expect(db.prepare('SELECT max(id) FROM concept WHERE active = 1').pluck().get()).toBe(482); + expect(db.prepare('SELECT min(id) FROM concept WHERE active = 0').pluck().get()).toBe(483); + const bad = db.prepare(`SELECT count(*) FROM link l JOIN property p ON p.id = l.property_id + JOIN concept s ON s.id = l.subject_id JOIN concept t ON t.id = l.target_id + WHERE p.subsumption = 1 AND s.active = 1 AND t.active = 1 AND t.id >= s.id`).pluck().get(); + expect(bad).toBe(0); + }); + + // main's CodeKey order is kept as the ix_order arrays (derived-by-importer) + test('ix_order ids: main\'s CodeKey order', () => { + const { fromBlobs } = { fromBlobs: (name) => { const b = Buffer.concat(db.prepare('SELECT data FROM main.ix_order WHERE name = ? ORDER BY block').pluck().all(name)); return new Uint32Array(b.buffer, b.byteOffset, b.length / 4); } }; + const ids = fromBlobs('ids'), walk = fromBlobs('walk'); + const code = new Map(db.prepare('SELECT id, code FROM main.concept').raw().all()); + const main = cdb.prepare('SELECT Code FROM Codes ORDER BY CodeKey').pluck().all(); + expect([...ids].slice(0, main.length).map((i) => code.get(i))).toEqual(main); + expect(new Set(walk).size).toBe(484); + }); + + test('ix_order: the answer orders are stored at import, and the provider reads them from the file', () => { + const rows = new Map(db.prepare('SELECT name, CAST(group_concat(data, \'\' ORDER BY block) AS BLOB) FROM main.ix_order GROUP BY name').raw().all()); + // active: the walk's active concepts, stored as the DISCOURAGED terms are not at its end + expect([...rows.keys()].filter((k) => !k.startsWith('hier')).sort()).toEqual(['active', 'ids', 'rank', 'walk']); + const arr = (k) => { const b = rows.get(k); return [...new Uint32Array(b.buffer, b.byteOffset, b.length / 4)]; }; + expect(arr('active')).toEqual(arr('walk').filter((id) => id <= 482)); + const o = v2.engine._order; + expect([o.stored, o.kind, o.selfFirst, o.hasWalk]).toEqual([true, 'stored', false, true]); + expect([...o.rank]).toEqual(arr('rank')); + expect([...o.ids]).toEqual(arr('ids')); + expect([...o.walk]).toEqual(arr('walk')); + expect(new Set(o.walk).size).toBe(484); + }); + +}); + +// ---- the dialect, through the router, against main ---------------------------------------- + +describe('LOINC v2 dialect against main\'s provider (same fixture)', () => { + test('the v2 run is served by the engine (one selection), the classic one is not', async () => { + const sel = jest.spyOn(SqliteV2Provider.prototype, 'processSelection'); + try { + const calls = []; + const r = await both(async (arm) => { const before = sel.mock.calls.length; const e = await expand({ valueSet: filterVs(['CLASS', '=', 'CHEM']) }); calls.push([arm, sel.mock.calls.length - before]); return e; }); + expect(calls).toEqual([['v2', 1], ['classic', 0]]); + expect(codes(r.v2)).toEqual(codes(r.classic)); + } finally { sel.mockRestore(); } + }); + + test('CodeSystem/x-loinc: read and search give the same placeholder as main', async () => { + const r = await both(async () => { + const read = await request(app).get(`/tx/r5/CodeSystem/x-loinc${VERSION}`); + const search = await request(app).get(`/tx/r5/CodeSystem?url=${encodeURIComponent(L)}`); + const hits = (search.body.entry || []).map((e) => e.resource).filter((c) => c.url === L); + return { status: read.status, read: read.body, search: hits.map((c) => ({ id: c.id, version: c.version, name: c.name })) }; + }); + expect(r.classic.status).toBe(200); + expect(r.v2).toEqual(r.classic); + expect(r.v2.read.id).toBe(`x-loinc${VERSION}`); + expect(r.v2.search).toEqual([{ id: `x-loinc${VERSION}`, version: VERSION, name: 'LOINC' }]); + }); + + // [filter, expected count]: the same codes in the same order on both engines (main's key order) + const FILTERS = [ + [['COMPONENT', '=', 'LP14082-9'], 209], + [['COMPONENT', '=', 'Bacteria'], 209], // by the part's name + [['COMPONENT', 'in', 'LP14082-9,LP15098-4'], 263], + [['COMPONENT', 'regex', '.*Potassium.*'], 55], + [['CLASS', '=', 'LP7786-9'], 64], + [['CLASS', '=', 'CHEM'], 64], + [['SCALE_TYP', '=', 'LP7753-9'], 25], + [['METHOD_TYP', 'exists', 'true'], 24], + [['SYSTEM', 'exists', 'false'], 431], + [['STATUS', '=', 'DEPRECATED'], 7], + [['STATUS', '=', 'TRIAL'], 2], + [['STATUS', '=', 'DISCOURAGED'], 2], + [['parent', '=', 'LP31398-8'], 3], + [['ancestor', '=', 'LP7786-9'], 9], + [['ancestor', 'in', 'LP7786-9,LP14082-9'], 13], + [['concept', 'is-a', 'LP7786-9'], 10], + [['concept', 'descendent-of', 'LP7786-9'], 9], + [['code', 'is-a', 'LP31398-8'], 4], + [['answers-for', '=', '100041-3'], 2], // a term: its lists' answers + [['answers-for', '=', 'LL360-9'], 2], // a list: its answers + [['answers-for', '=', '10332-5'], 0], // an externally defined list only + [['LIST', '=', 'LL6136-7'], 4], + [['LIST', '=', EXT_LIST], 0], + [['copyright', '=', 'LOINC'], 483], + [['copyright', '=', '3rdParty'], 1], + [['ORDER_OBS', '=', 'Observation'], 48], + [['CLASSTYPE', '=', '2'], 9], + [['CLASSTYPE', '=', 'Clinical class'], 9], + // in is the union of = each value (main since #386): a part name, a literal value, a CLASSTYPE number + [['COMPONENT', 'in', 'Bacteria,LP15098-4'], 263], + [['CLASSTYPE', 'in', '2,Clinical class'], 9], + [['ORDER_OBS', 'in', 'Observation,Both'], 318], + [['answers-for', 'in', '100041-3,LL360-9'], 2], + [['CLASSTYPE', 'regex', 'Clin.*'], 9], + [['child', '=', 'LP31398-8'], 1], // the parents of the part + [['child', 'exists', 'true'], 14], + [['STATUS', '=', 'NotStated'], 15], // main's status 0: lists, answers and parts with no status + [['parent', 'regex', 'Bact.*'], 5], + ]; + test.each(FILTERS)('$expand %j: %d codes, as main', async (f, n) => { + const r = await both(() => expand({ valueSet: filterVs(f), count: 1000 })); + expect(r.v2.status).toBeUndefined(); + expect(codes(r.v2)).toEqual(codes(r.classic)); + expect(r.v2.total ?? codes(r.v2).length).toBe(n); + expect(codes(r.v2).length).toBe(n); + }); + + // a compose with a second system is not handed to the engine whole: expand.js iterates each + // filter through the filter API, and the engine lists its members in the same order + const GENDER = { system: 'http://hl7.org/fhir/administrative-gender', concept: [{ code: 'male' }] }; + test.each(FILTERS.filter(([, n]) => n > 1))('$expand %j beside another system: the same codes in the same order as main', async (f) => { + const r = await both(() => expand({ valueSet: vs([{ system: L, filter: [{ property: f[0], op: f[1], value: f[2] }] }, GENDER]), count: 1000 })); + expect(r.v2.status).toBeUndefined(); + expect(codes(r.v2)).toEqual(codes(r.classic)); + expect(codes(r.v2).slice(-1)).toEqual(['male']); + }); + + test('$expand: two filters intersect, an exclude subtracts (as main)', async () => { + const two = await both(() => expand({ valueSet: filterVs(['CLASS', '=', 'CHEM'], ['SCALE_TYP', '=', 'LP7753-9']) })); + expect(codes(two.v2)).toEqual(codes(two.classic)); + expect(codes(two.v2)).toHaveLength(10); + const ex = await both(() => expand({ valueSet: vs([{ system: L, filter: [{ property: 'CLASS', op: '=', value: 'CHEM' }] }], + [{ system: L, filter: [{ property: 'SCALE_TYP', op: '=', value: 'LP7753-9' }] }]) })); + expect(sorted(codes(ex.v2))).toEqual(sorted(codes(ex.classic))); + expect(codes(ex.v2)).toHaveLength(54); + }); + + test.each([ + [['COMPONENT', 'is-a', 'LP14082-9']], [['concept', 'not-in', '6298-4']], [['concept', 'generalizes', '6298-4']], + [['concept', 'child-of', 'LP7786-9']], [['concept', 'regex', '62.*']], [['code', 'in', '6298-4']], [['STATUS', 'in', 'ACTIVE']], + [['STATUS', '=', 'active']], [['display', '=', 'Potassium']], [['RELATEDNAMES2', '=', 'K']], [['COMPONENT', 'exists', 'maybe']], + ])('$expand %j: a filter main does not support is refused, as main', async (f) => { + const r = await both(() => expand({ valueSet: filterVs(f) })); + expect(r.v2.status).toBeGreaterThanOrEqual(400); + expect([r.v2.status, r.v2.text]).toEqual([r.classic.status, r.classic.text]); + }); + + test('$expand answer-list = [answer]: the lists the answer is in (UP-645, cs-loinc.test.js expectations)', async () => { + for (const [value, want] of [['LA9040-2', ['LL6136-7']], ['LA6576-8', ['LL360-9']], ['LL6136-7', []], ['LA0000-0', []]]) { + const r = await expand({ valueSet: filterVs(['answer-list', '=', value]) }); + expect(r.status).toBeUndefined(); + expect(sorted(codes(r))).toEqual(want); + } + const check = async (f, code) => { + const res = await request(app).post('/tx/r5/ValueSet/$validate-code').send({ resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: filterVs(f) }, { name: 'system', valueUri: L }, { name: 'code', valueCode: code }] }); + expect(res.status).toBe(200); + return flatParams(res.body).includes('result=true'); + }; + expect(await check(['answer-list', '=', 'LA9040-2'], 'LL6136-7')).toBe(true); + expect(await check(['answer-list', '=', 'LA9040-2'], 'LL360-9')).toBe(false); + }); + + test.each([ + [['LIST', '=', 'LL6136-7']], [['LIST', '=', 'LL360-9']], [['answers-for', '=', 'LL6136-7']], [['answers-for', '=', '100041-3']], + [['AnswerList', '=', 'LL360-9']], [['AnswerList', '=', 'LL6136-7']], + ])('$expand %j: the same codes in the same order as main', async (f) => { + const r = await both(() => expand({ valueSet: filterVs(f), count: 1000 })); + expect(r.v2.status).toBeUndefined(); + expect(codes(r.v2).length).toBeGreaterThan(0); + expect(codes(r.v2)).toEqual(codes(r.classic)); + }); + + test('$expand LIST = a code LOINC does not have: refused, as main', async () => { + const r = await both(() => expand({ valueSet: filterVs(['LIST', '=', 'LL0000-0']) })); + expect(r.v2.status).toBeGreaterThanOrEqual(400); + expect(r.classic.status).toBe(r.v2.status); + }); + + test('$expand of an answer list\'s implicit value set: the list\'s order, as main', async () => { + const r = await both(() => expand({ url: 'http://loinc.org/vs/LL6136-7' })); + expect(codes(r.v2)).toEqual(['LA32971-6', 'LA32972-4', 'LA9040-2', 'LA10105-7']); + expect(codes(r.v2)).toEqual(codes(r.classic)); + }); + + test('$expand of a part\'s implicit value set: its descendants, as main', async () => { + const r = await both(() => expand({ url: 'http://loinc.org/vs/LP7786-9' })); + expect(codes(r.v2)).toEqual(codes(r.classic)); + expect(codes(r.v2)).toHaveLength(9); + expect(codes(r.v2)).not.toContain('LP7786-9'); + }); + + test('$expand displays, designations and properties, as main', async () => { + for (const o of [ + { valueSet: filterVs(['CLASS', '=', 'CHEM']), displayLanguage: 'de-DE' }, + { valueSet: filterVs(['COMPONENT', '=', 'LP15098-4']), displayLanguage: 'nl-NL' }, + { valueSet: vs([{ system: L, concept: [{ code: '10332-5' }, { code: 'LP14355-9' }, { code: 'LA6576-8' }] }]), includeDesignations: true }, + { valueSet: vs([{ system: L, concept: [{ code: '10332-5' }, { code: '100041-3' }, { code: 'LP31398-8' }] }]), + property: ['COMPONENT', 'CLASS', 'STATUS', 'answers-for', 'AnswerList', 'parent', 'child'] }, + ]) { + const r = await both(() => expand(o)); + expect(sorted(r.v2.contains.map(listed))).toEqual(sorted(r.classic.contains.map(listed))); + } + const nl = await expand({ valueSet: filterVs(['COMPONENT', '=', 'LP15098-4']), displayLanguage: 'nl-NL' }); + expect(nl.contains.find((c) => c.code === '6298-4').display).toBe('Kalium [mol/volume] in bloed'); + }); + + test('$expand text filter: the same matches in the same order as main', async () => { + for (const filter of ['glucose', 'Bact', 'Kalium']) { + const r = await both(() => expand({ url: 'http://loinc.org/vs', filter, count: 1000 })); + expect(codes(r.v2)).toEqual(codes(r.classic)); + } + expect(codes(await expand({ url: 'http://loinc.org/vs', filter: 'glucose' }))).toEqual(['LP14635-4', '104597-0']); + }); + + test('$expand text filter (#398): words in any order in one name, codes, stop words, one letter; ties in main\'s CodeKey order', async () => { + let n = 0; + for (const filter of ['k', 'a', 'mass', 'serum', 'blood', 'urine', 'ser', 'glucose serum', 'serum glucose', 'mass or moles', 'in', 'the', + '2345', '2345-7', 'lp', 'la', 'b', 'hepatitis b', 'glucose [mass/volume]', 'qn', '-']) { + const r = await both(() => expand({ url: 'http://loinc.org/vs', filter, count: 1000 })); + expect([filter, codes(r.v2)]).toEqual([filter, codes(r.classic)]); + n += codes(r.v2).length; + } + expect(n).toBeGreaterThan(0); + }); + + test('$expand text filter (#399): ranked as main ranks (TextQuery.nameRank of the best name, codeRank), ties by display (localeCompare)', async () => { + for (const filter of ['glucose', 'serum glucose', 'glucose serum', 'urine calcium', 'calcium urine', 'mass serum', 'serum mass', 'la', 'lp', + 'gluc ser', 'bld', 'moles volume']) { + const r = await both(() => expand({ url: 'http://loinc.org/vs', filter, count: 1000 })); + expect([filter, codes(r.v2)]).toEqual([filter, codes(r.classic)]); + } + }); + + test('$expand of an include filter on an unknown concept (#396): no codes, and the same expansion-issue warning as main', async () => { + for (const [prop, op, value] of [['concept', 'is-a', 'LP0000-0'], ['concept', 'descendent-of', 'NOPE-1'], ['code', '=', 'NOPE-2'], ['concept', 'is-a', '2345-7'], + ['concept', 'in', '6298-4,NOPE-3'], ['code', 'in', '10332-5, NOPE-4'], ['concept', 'in', '6298-4, 10332-5']]) { + const body = async () => { + const res = await request(app).post('/tx/r5/ValueSet/$expand').send(params({ valueSet: filterVs([prop, op, value]), count: 20 })); + const oo = (res.body.contained || []).filter((c) => c.resourceType === 'OperationOutcome').flatMap((c) => c.issue.map((i) => [i.severity, i.details && i.details.text])); + return { status: res.status, codes: codes(res.body.expansion || {}), oo }; + }; + const r = await both(body); + expect([prop, op, value, r.v2]).toEqual([prop, op, value, r.classic]); + } + }); + + test('processSelection takes a `concept in` list whose codes are all known, and leaves one with an unknown code to the usual path', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const p2 = await v2.build(new OperationContext('en', tx.i18n), []); + const inc = (value) => [{ system: L, filter: [{ property: 'concept', op: 'in', value }] }]; + const known = await p2.processSelection(null, inc('6298-4, 10332-5'), [], false, -1, -1); + expect(known).not.toBeNull(); + expect(known.total).toBe(2); + expect(await p2.processSelection(null, inc('6298-4,NOPE-3'), [], false, -1, -1)).toBeNull(); + }); + + test('$expand whole system: the same codes as main; activeOnly drops the DISCOURAGED terms', async () => { + const all = await both(() => expand({ valueSet: vs([{ system: L }]), count: 1000 })); + expect(all.v2.total).toBe(484); + // main's order: expand.js's walk (by type, then CodeKey, each part followed by what is below + // it: ix_order walk) + expect(codes(all.v2)).toEqual(codes(all.classic)); + const act = await both(() => expand({ valueSet: vs([{ system: L }]), count: 1000, activeOnly: true })); + expect(sorted(codes(act.v2))).toEqual(sorted(codes(act.classic))); + expect(act.v2.total).toBe(482); + expect(codes(act.v2)).not.toContain('22760-3'); + // count=0: the total only, the code system's size as main reports it (activeOnly does not change it) + const n = await both(() => expand({ valueSet: vs([{ system: L }]), count: 0, activeOnly: true })); + expect([n.v2.total, n.v2.contains]).toEqual([484, undefined]); + expect(n.v2.total).toBe(n.classic.total); + }); + + test('$expand paging: every page is a slice of the full expansion, with the same total', async () => { + const full = codes(await expand({ valueSet: vs([{ system: L }]), count: 1000 })); + for (const [offset, count] of [[0, 10], [100, 20], [315, 15], [470, 50], [484, 5]]) { + const page = await expand({ valueSet: vs([{ system: L }]), offset, count }); + expect([page.total, page.offset]).toEqual([484, offset]); + expect(codes(page)).toEqual(full.slice(offset, offset + count)); + } + const f = filterVs(['COMPONENT', '=', 'LP14082-9']); + const fullF = codes(await expand({ valueSet: f, count: 1000 })); + const pages = []; + for (let offset = 0; offset < fullF.length; offset += 50) pages.push(...codes(await expand({ valueSet: f, offset, count: 50 }))); + expect(pages).toEqual(fullF); + }); + + const LOOKUP_CODES = ['10332-5', '100041-3', '22760-3', '62580-6', '10550-2', 'LP14355-9', 'LP7786-9', 'LP432695-7', 'LL360-9', EXT_LIST, 'LA6576-8']; + test.each(LOOKUP_CODES)('$lookup %s: the same properties and designations as main', async (code) => { + for (const extra of ['', '&property=*', '&displayLanguage=nl-NL']) { + const r = await both(async () => { + const res = await request(app).get(`/tx/r5/CodeSystem/$lookup?system=${L}&code=${code}${extra}`); + expect(res.status).toBe(200); + return flatParams(res.body); + }); + expect(r.v2).toEqual(r.classic); + } + }); + + test('$lookup 10332-5: part properties, literals and designations', async () => { + const res = await request(app).get(`/tx/r5/CodeSystem/$lookup?system=${L}&code=10332-5&property=*`); + const f = flatParams(res.body); + expect(f).toEqual(expect.arrayContaining(['property(code=COMPONENT,description=Cortisol^pre 250 ug corticotropin IM,value=LP305473-3)', 'property(code=SCALE_TYP,description=Qn,value=LP7753-9)', + 'property(code=CLASSTYPE,description=Laboratory class,value=1)', 'property(code=UNITSREQUIRED,value=Y)', 'property(code=ORDER_OBS,value=Observation)', + 'property(code=STATUS,value=ACTIVE)', 'property(code=AnswerList,description=ICD-9_ICD-10,value=LL1892-0)', 'property(code=RELATEDNAMES2,language=nl-NL,value=adrenocorticotroop hormoon; adrenocorticotrofine; corticotrofine)'])); + expect(f.some((p) => p.startsWith('designation(') && p.includes('value=Cortis pre 250 ug ACTH IM SerPl-mCnc'))).toBe(true); + }); + + // a code-valued property carries the display of the code it names as its description (as main, + // cs-loinc.test.js); CLASS stays a string property with the part code as partCode + test('$lookup: code-valued properties have the named code\'s display as their description, as main', async () => { + for (const [code, prop, value, description] of [['10332-5', 'COMPONENT', 'LP305473-3', 'Cortisol^pre 250 ug corticotropin IM'], + ['LP14355-9', 'parent', 'LP31398-8', 'Renal function'], ['10332-5', 'AnswerList', 'LL1892-0', 'ICD-9_ICD-10']]) { + const r = await both(async () => { + const res = await request(app).get(`/tx/r5/CodeSystem/$lookup?system=${L}&code=${code}&property=${prop}`); + return flatParams(res.body).filter((p) => p.startsWith('property(')); + }); + expect(r.v2).toEqual(r.classic); + expect(r.v2).toContain(`property(code=${prop},description=${description},value=${value})`); + } + }); + + const VALIDATE = [ + ['CodeSystem', `url=${L}&code=10332-5`], + ['CodeSystem', `url=${L}&code=10332-5&display=Wrong`], + ['CodeSystem', `url=${L}&code=10332-5&display=${encodeURIComponent('Cortis pre 250 ug ACTH IM SerPl-mCnc')}`], + ['CodeSystem', `url=${L}&code=6298-4&display=${encodeURIComponent('Kalium [mol/volume] in bloed')}&displayLanguage=nl-NL`], + ['CodeSystem', `url=${L}&code=nope-1`], + ['CodeSystem', `url=${L}&code=22760-3`], + ['CodeSystem', `url=${L}&code=LA6576-8&display=Positive`], + ['CodeSystem', `url=${L}&code=${EXT_LIST}`], + ['ValueSet', `url=${encodeURIComponent('http://loinc.org/vs/LL360-9')}&system=${L}&code=LA6576-8`], + ['ValueSet', `url=${encodeURIComponent('http://loinc.org/vs/LL360-9')}&system=${L}&code=LA11882-0`], + ['ValueSet', `url=${encodeURIComponent('http://loinc.org/vs/LP7786-9')}&system=${L}&code=6298-4`], + ['ValueSet', `url=${encodeURIComponent('http://loinc.org/vs/LP7786-9')}&system=${L}&code=595-9`], + ['ValueSet', `url=${encodeURIComponent('http://loinc.org/vs')}&system=${L}&code=22760-3&activeOnly=true`], + ]; + test.each(VALIDATE)('%s/$validate-code?%s: as main', async (kind, query) => { + const r = await both(async () => { + const res = await request(app).get(`/tx/r5/${kind}/$validate-code?${query}`); + expect(res.status).toBe(200); + return flatParams(res.body); + }); + expect(r.v2).toEqual(r.classic); + }); + + test('ValueSet/$validate-code against filters: in and out, as main', async () => { + const check = async (f, code) => { + const r = await both(async () => { + const res = await request(app).post('/tx/r5/ValueSet/$validate-code').send({ resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: filterVs(f) }, { name: 'system', valueUri: L }, { name: 'code', valueCode: code }] }); + expect(res.status).toBe(200); + return flatParams(res.body); + }); + expect(r.v2).toEqual(r.classic); + return r.v2.includes('result=true'); + }; + expect(await check(['COMPONENT', '=', 'LP14082-9'], '595-9')).toBe(true); + expect(await check(['COMPONENT', '=', 'LP14082-9'], '6298-4')).toBe(false); + expect(await check(['answers-for', '=', '100041-3'], 'LA6576-8')).toBe(true); + expect(await check(['ancestor', '=', 'LP7786-9'], 'LP7786-9')).toBe(false); + expect(await check(['copyright', '=', '3rdParty'], COPYRIGHT_TERM)).toBe(true); + expect(await check(['COMPONENT', 'regex', '.*Potassium.*'], '6298-4')).toBe(true); + }); + + test('$subsumes from the component hierarchy, as main', async () => { + for (const [a, b, outcome] of [['LP7786-9', '6298-4', 'subsumes'], ['6298-4', 'LP7786-9', 'subsumed-by'], ['LP7786-9', 'LP7786-9', 'equivalent'], + ['LP14082-9', '6298-4', 'not-subsumed'], ['LP15098-4', 'LP386601-1', 'subsumes']]) { + const r = await both(async () => { + const res = await request(app).get(`/tx/r5/CodeSystem/$subsumes?system=${L}&codeA=${a}&codeB=${b}`); + return res.body.parameter; + }); + expect(r.v2).toEqual([{ name: 'outcome', valueCode: outcome }]); + expect(r.v2).toEqual(r.classic); + } + }); + + test('$lookup properties in main\'s order (#385: relationships, properties, STATUS, RELATEDNAMES2, mappings), every term and answer', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const op = new OperationContext('en', tx.i18n); + const p2 = await v2.build(op, []); + const pc = await classic.build(op, []); + // not the parts: a part's children are in id order here, in hierarchy-file order on main + const codes = v2.store.db.prepare("SELECT code FROM concept WHERE code NOT LIKE 'LP%' ORDER BY id").pluck().all(); + let n = 0; + for (const code of codes) { + const c2 = (await p2.locate(code)).context; + const cc = (await pc.locate(code)).context; + if (!c2 || !cc) continue; + for (const props of [[], ['*'], ['STATUS', 'COMPONENT', 'CLASSTYPE']]) { + const a = [], b = []; + await p2.extendLookup(c2, props, a); + await pc.extendLookup(cc, props, b); + expect([code, props, JSON.stringify(a)]).toEqual([code, props, JSON.stringify(b)]); + n++; + } + } + expect(n).toBeGreaterThan(100); + }); + + test('$lookup of every part in main\'s order: parent and child in its Relationships rows\' order (hierarchy-file order)', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const op = new OperationContext('en', tx.i18n); + const p2 = await v2.build(op, []); + const pc = await classic.build(op, []); + const codes = v2.store.db.prepare("SELECT code FROM concept WHERE code LIKE 'LP%' ORDER BY id").pluck().all(); + let n = 0, withChildren = 0; + for (const code of codes) { + const c2 = (await p2.locate(code)).context; + const cc = (await pc.locate(code)).context; + if (!c2 || !cc) continue; + for (const props of [[], ['*'], ['parent', 'child']]) { + const a = [], b = []; + await p2.extendLookup(c2, props, a); + await pc.extendLookup(cc, props, b); + expect([code, props, JSON.stringify(a)]).toEqual([code, props, JSON.stringify(b)]); + if (props.length === 0 && a.filter((x) => x.part && x.part[0].valueCode === 'child').length > 1) withChildren++; + n++; + } + } + expect(n).toBeGreaterThan(100); + expect(withChildren).toBeGreaterThan(3); + }); + + test('ancestorsOf: the same sets as main\'s (#388, the Closure table) for every code of the fixture', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const op = new OperationContext('en', tx.i18n); + const p2 = await v2.build(op, []); + const pc = await classic.build(op, []); + const codes = v2.store.db.prepare('SELECT code FROM concept ORDER BY id').pluck().all(); + let withAncestors = 0; + for (const code of codes) { + const a2 = await p2.ancestorsOf(code); + const ac = await pc.ancestorsOf(code); + expect([code, a2 && [...a2].sort()]).toEqual([code, ac && [...ac].sort()]); + if (a2 && a2.size) withAncestors++; + } + expect(withAncestors).toBeGreaterThan(10); + expect(await p2.ancestorsOf('6298-4')).toEqual(expect.any(Set)); + expect((await p2.ancestorsOf('6298-4')).has('LP7786-9')).toBe(true); + expect(await p2.ancestorsOf('nope')).toBeNull(); + expect(await p2.ancestorsOf('lp7786-9')).toBe(await pc.ancestorsOf('lp7786-9')); + }); + + test('ancestorsOf agrees with subsumesTest (CodeSystemProvider.ancestorsOf)', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const p2 = await v2.build(new OperationContext('en', tx.i18n), []); + // the parts with children, and terms under them + const parts = v2.store.db.prepare('SELECT c.code FROM concept c JOIN ix_set s ON s.value = c.id AND s.kind = 4 ORDER BY c.id LIMIT 40').pluck().all(); + const terms = ['6298-4', '595-9', 'LP386601-1', 'LP14082-9', 'LP15098-4', 'LA6576-8']; + for (const b of [...parts, ...terms]) { + const anc = await p2.ancestorsOf(b); + for (const a of [...parts, ...terms]) { + if (a !== b) expect([a, b, anc.has(a)]).toEqual([a, b, (await p2.subsumesTest(a, b)) === 'subsumes']); + } + } + }); +}); + +// ---- the provider filter API (the path an include takes in a multi-system compose) --------- + +describe('LOINC v2 provider filter API against main\'s', () => { + const { OperationContext } = require('../../tx/operation-context'); + let p2, pc; + beforeAll(async () => { + const op = new OperationContext('en', tx.i18n); + p2 = await v2.build(op, []); + pc = await classic.build(op, []); + }); + + test('designations of every code in main\'s order (a part\'s DisplayName before its PartName variants)', async () => { + const { Designations } = require('../../tx/library/designations'); + const { OperationContext } = require('../../tx/operation-context'); + const op = new OperationContext('en', tx.i18n); + const p = await v2.build(op, []); + const pcl = await classic.build(new OperationContext('en', tx.i18n), []); + const codes = v2.store.db.prepare('SELECT code FROM concept ORDER BY id').pluck().all(); + let n = 0, partsWithBoth = 0; + for (const code of codes) { + const a = (await p.locate(code)).context; + const b = (await pcl.locate(code)).context; + if (!a || !b) continue; + const da = new Designations(op.i18n.languageDefinitions); + const db = new Designations(op.i18n.languageDefinitions); + await p.designations(a, da, true); + await pcl.designations(b, db, true); + const flat = (ds) => ds.designations.map((d) => [d.language && d.language.code, d.use && d.use.code, d.value]); + expect([code, flat(da)]).toEqual([code, flat(db)]); + const uses = flat(db).map((d) => d[1]); + if (uses.includes('DisplayName') && uses.includes('PartName')) partsWithBoth++; + n++; + } + expect(n).toBeGreaterThan(400); + expect(partsWithBoth).toBeGreaterThan(5); + }); + + test('a prefetched list: status and designations as main, from three statements whatever the length', async () => { + const { Designations } = require('../../tx/library/designations'); + const codes = ['10332-5', '100041-3', '22760-3', '62580-6', '10550-2', 'LP14355-9', 'LA6576-8', 'nope']; + const op = new OperationContext('en', tx.i18n); + const t = countingTracer(); + op.tracer = t; + const p = await v2.build(op, []); + const pcl = await classic.build(new OperationContext('en', tx.i18n), []); + const h = await p.prefetchCodes(codes, true); + const after = t.stats.statements; + expect(after).toBe(3); // codes with rows, STATUS, designations (RELATEDNAMES2 left out) + for (const code of codes) { + const a = await p.locate(code, h); + const b = await pcl.locate(code); + expect(!!a.context).toBe(!!b.context); + if (!a.context) continue; + expect(await p.getStatus(a.context)).toBe(await pcl.getStatus(b.context)); + const da = new Designations(op.i18n.languageDefinitions); + const db = new Designations(op.i18n.languageDefinitions); + await p.designations(a.context, da, true); + await pcl.designations(b.context, db, true); + const flat = (ds) => ds.designations.map((d) => [d.language && d.language.code, d.use && d.use.code, d.value]).sort(); + expect(flat(da)).toEqual(flat(db)); + } + expect(t.stats.statements).toBe(after); + // $lookup still reports RELATEDNAMES2 for a prefetched concept + const params = []; + await p.extendLookup((await p.locate('10332-5', h)).context, ['RELATEDNAMES2'], params); + expect(params.some((x) => x.part.some((q) => q.name === 'code' && q.valueCode === 'RELATEDNAMES2'))).toBe(true); + }); + + async function run(p, prop, opr, value) { + const prep = await p.getPrepContext(true); + await p.filter(prep, true, prop, opr, value); + const [set] = await p.executeFilters(prep); + const out = []; + while (await p.filterMore(prep, set)) out.push(await p.code(await p.filterConcept(prep, set))); + return { out, size: await p.filterSize(prep, set), prep, set }; + } + + test.each([ + ['COMPONENT', '=', 'LP14082-9'], ['CLASS', '=', 'CHEM'], ['SCALE_TYP', '=', 'LP7753-9'], ['STATUS', '=', 'DEPRECATED'], + ['parent', '=', 'LP31398-8'], ['ancestor', 'in', 'LP7786-9,LP14082-9'], ['concept', 'is-a', 'LP7786-9'], + ['answers-for', '=', '100041-3'], ['LIST', '=', 'LL6136-7'], ['copyright', '=', '3rdParty'], ['ORDER_OBS', '=', 'Observation'], + ['COMPONENT', 'regex', '.*Potassium.*'], + ])('%s %s %s: the same codes; locate and check agree', async (prop, opr, value) => { + expect(await p2.doesFilter(prop, opr, value)).toBe(true); + const a = await run(p2, prop, opr, value); + const b = await run(pc, prop, opr, value); + expect(sorted(a.out)).toEqual(sorted(b.out)); + expect(a.size).toBe(a.out.length); + if (a.out.length) { + const located = await p2.filterLocate(a.prep, a.set, a.out[0]); + expect(await p2.code(located)).toBe(a.out[0]); + } + const outside = (await p2.locate('LP432695-7')).context; + expect(!!(await p2.filterCheck(a.prep, a.set, outside))).toBe(a.out.includes('LP432695-7')); + }); +}); diff --git a/tests/tx/sqlite-v2-mixed-providers.test.js b/tests/tx/sqlite-v2-mixed-providers.test.js new file mode 100644 index 00000000..37062c13 --- /dev/null +++ b/tests/tx/sqlite-v2-mixed-providers.test.js @@ -0,0 +1,283 @@ +'use strict'; + +// Mixed value sets: a sqlite-v2 (engine-backed) code system next to providers that run their own +// code (UCUM, BCP-47) and a FHIR CodeSystem resource, through the real router. A compose of more +// than one system takes expand.js's usual path: the v2 include goes through the provider's filter +// API, on the engine; the other includes stay on their own providers. These are the cases where +// the engine and main gave the same answers on a library with SNOMED CT and LOINC on sqlite-v2 +// (a small v2 fixture here). + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { TerminologyBuilder } = require('../../tx/importers/sqlite-v2/builder'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); +const { UcumService } = require('../../tx/library/ucum-service'); +const { UcumCodeSystemFactory } = require('../../tx/cs/cs-ucum'); +const { IETFLanguageCodeFactory } = require('../../tx/cs/cs-lang'); +const ValueSet = require('../../tx/library/valueset'); + +const V2 = 'http://example.org/fhir/CodeSystem/v2-mixed'; +const UCUM = 'http://unitsofmeasure.org'; +const BCP47 = 'urn:ietf:bcp:47'; +const FHIRCS = 'http://example.org/fhir/CodeSystem/mixed-resource'; +const EXPAND = '/tx/r5/ValueSet/$expand'; +const VALIDATE = '/tx/r5/ValueSet/$validate-code'; + +// root ─┬─ A ─┬─ A1 +// │ ├─ A2 (inactive) +// │ └─ A3 +// └─ B ─── B1 +function buildV2(dest) { + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: V2, version: '1' }); + const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); + const c = {}; + for (const code of ['root', 'A', 'A1', 'A2', 'A3', 'B', 'B1']) { + c[code] = b.concept(code, { active: code !== 'A2', display: `display ${code}` }); + } + for (const [ch, pa] of [['A', 'root'], ['B', 'root'], ['A1', 'A'], ['A2', 'A'], ['A3', 'A'], ['B1', 'B']]) b.link(c[ch], isa, c[pa]); + b.item(c.A1, { language: 'de', text: 'Anzeige A1' }); + b.finish(); +} + +// a v2 system that is not closed (compositional, as SNOMED CT is: post-coordination), and a +// supplement that defines a property on it +const V2OPEN = 'http://example.org/fhir/CodeSystem/v2-open'; +function buildV2Open(dest) { + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: V2OPEN, version: '1', compositional: true }); + const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); + const c = {}; + for (const code of ['X', 'X1', 'X2', 'X3']) c[code] = b.concept(code, { active: true, display: `display ${code}` }); + for (const ch of ['X1', 'X2', 'X3']) b.link(c[ch], isa, c.X); + b.finish(); +} +const SUPP_TIER = { + resourceType: 'CodeSystem', url: 'http://example.org/fhir/CodeSystem/v2-open-tier', version: '1', status: 'active', + content: 'supplement', supplements: V2OPEN, property: [{ code: 'tier', type: 'string' }], + concept: [{ code: 'X3', property: [{ code: 'tier', valueString: 'gold' }] }, { code: 'X1', property: [{ code: 'tier', valueString: 'gold' }] }, + { code: 'X2', property: [{ code: 'tier', valueString: 'silver' }] }] +}; + +// a FHIR CodeSystem resource with a hierarchy, a retired concept and a property to filter on +const FHIR_CS = { + resourceType: 'CodeSystem', url: FHIRCS, version: '1', status: 'active', content: 'complete', hierarchyMeaning: 'is-a', + property: [{ code: 'status', uri: 'http://hl7.org/fhir/concept-properties#status', type: 'code' }, + { code: 'colour', type: 'string' }], + concept: [{ code: 'P', display: 'Parent', concept: [ + { code: 'P1', display: 'Child one', property: [{ code: 'colour', valueString: 'red' }] }, + { code: 'P2', display: 'Child two', property: [{ code: 'status', valueCode: 'retired' }] }, + { code: 'P3', display: 'Child three', property: [{ code: 'colour', valueString: 'red' }] }] }] +}; +// the common units list the UCUM `canonical` filter enumerates (the library binds ucum-common) +const COMMON_UNITS = { + resourceType: 'ValueSet', url: 'http://example.org/fhir/ValueSet/test-ucum-common', status: 'active', + compose: { include: [{ system: UCUM, concept: ['mg', 'g', 'kg', 'ug', 'mL', 'L', 'mmol/L', 'mg/dL'].map(code => ({ code })) }] } +}; +const SUPP_V2 = { + resourceType: 'CodeSystem', url: 'http://example.org/fhir/CodeSystem/v2-mixed-de', version: '1', status: 'active', + content: 'supplement', supplements: V2, concept: [{ code: 'A3', designation: [{ language: 'de', value: 'Anzeige A3' }] }] +}; +const SUPP_FHIR = { + resourceType: 'CodeSystem', url: 'http://example.org/fhir/CodeSystem/mixed-resource-de', version: '1', status: 'active', + content: 'supplement', supplements: FHIRCS, concept: [{ code: 'P1', designation: [{ language: 'de', value: 'Kind eins' }] }] +}; + +const inc = (system, { codes, filters } = {}) => Object.assign({ system }, + codes ? { concept: codes.map(code => ({ code })) } : {}, + filters ? { filter: filters.map(([property, op, value]) => ({ property, op, value })) } : {}); + +// v2 is-a + UCUM list + BCP-47 list + FHIR resource is-a, with excludes on each kind of provider +const MIXED = { + resourceType: 'ValueSet', url: 'http://example.org/fhir/ValueSet/v2-mixed', version: '1', status: 'active', + compose: { + include: [inc(V2, { filters: [['concept', 'is-a', 'A']] }), inc(UCUM, { codes: ['mg', 'mg/dL', 'kg'] }), + inc(BCP47, { codes: ['en', 'en-US', 'de'] }), inc(FHIRCS, { filters: [['concept', 'is-a', 'P']] })], + exclude: [inc(V2, { codes: ['A3'] }), inc(UCUM, { codes: ['kg'] }), inc(BCP47, { codes: ['de'] }), inc(FHIRCS, { codes: ['P3'] })] + } +}; +const MIXED_CODES = [[V2, 'A'], [V2, 'A1'], [V2, 'A2'], [UCUM, 'mg'], [UCUM, 'mg/dL'], [BCP47, 'en'], [BCP47, 'en-US'], + [FHIRCS, 'P'], [FHIRCS, 'P1'], [FHIRCS, 'P2']]; + +function flat(contains, out = []) { + for (const c of contains || []) { + out.push([c.system, c.code]); + flat(c.contains, out); + } + return out; +} +const named = (body, name) => (body.parameter || []).find(p => p.name === name); + +describe('sqlite-v2 in mixed value sets (custom-code providers alongside the engine)', () => { + let app, dir; + + async function post(url, parameter) { + const res = await request(app).post(url).set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [{ name: 'tx-resource', resource: FHIR_CS }, ...parameter] }); + return res; + } + async function expand(vs, extra = []) { + const res = await post(EXPAND, [{ name: 'valueSet', resource: vs }, ...extra]); + expect(res.status).toBe(200); + return res.body; + } + async function validate(vs, system, code, extra = []) { + const res = await post(VALIDATE, [{ name: 'valueSet', resource: vs }, { name: 'system', valueUri: system }, { name: 'code', valueCode: code }, ...extra]); + expect(res.status).toBe(200); + return res.body; + } + + beforeAll(async () => { + app = await getTestApp(); + const tx = getTxModule(); + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-mixed-')); + buildV2(path.join(dir, 'v2.db')); + const v2 = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'v2.db')); + buildV2Open(path.join(dir, 'v2-open.db')); + const v2open = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'v2-open.db')); + const ucumService = new UcumService(); + await ucumService.init(fs.readFileSync(path.join(__dirname, '../../tx/data/ucum-essence.xml'), 'utf8')); + const ucum = new UcumCodeSystemFactory(tx.i18n, ucumService); + await ucum.load(); + ucum.processCommonUnits(new ValueSet(COMMON_UNITS)); + const lang = new IETFLanguageCodeFactory(tx.i18n); + await lang.load(); + const provider = tx.endpoints[0].provider; + for (const f of [v2, v2open, ucum, lang]) { + provider.codeSystemFactories.set(f.system(), f); + provider.codeSystemFactories.set(f.system() + '|' + f.version(), f); + } + }, 120000); + + afterAll(async () => { + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + test('includes and excludes across both kinds of provider: segments in include order, v2 members in id order', async () => { + const body = await expand(MIXED); + expect(flat(body.expansion.contains)).toEqual(MIXED_CODES); + expect(body.expansion.total).toBe(MIXED_CODES.length); + // listed UCUM and BCP-47 codes do not make the expansion unclosed (main and v2 agree) + expect((body.expansion.extension || []).some(e => e.url.endsWith('valueset-unclosed'))).toBe(false); + }); + + test('count=0 gives the total of the whole mixed compose', async () => { + const body = await expand(MIXED, [{ name: 'count', valueInteger: 0 }]); + expect(body.expansion.total).toBe(MIXED_CODES.length); + expect(body.expansion.contains).toBeUndefined(); + }); + + test('pages across the provider boundaries are slices of the full expansion, with the same total', async () => { + for (const [offset, count] of [[0, 3], [2, 4], [3, 3], [6, 10], [9, 5], [12, 5]]) { + const body = await expand(MIXED, [{ name: 'offset', valueInteger: offset }, { name: 'count', valueInteger: count }]); + expect(flat(body.expansion.contains)).toEqual(MIXED_CODES.slice(offset, offset + count)); + expect(body.expansion.total).toBe(MIXED_CODES.length); + expect(body.expansion.offset).toBe(offset); + } + }); + + test('activeOnly drops the inactive v2 concept and the retired resource concept', async () => { + const body = await expand(MIXED, [{ name: 'activeOnly', valueBoolean: true }]); + const expected = MIXED_CODES.filter(([s, c]) => !(s === V2 && c === 'A2') && !(s === FHIRCS && c === 'P2')); + expect(flat(body.expansion.contains)).toEqual(expected); + expect(body.expansion.total).toBe(expected.length); + }); + + test.each([ + [V2, 'A1', true], [V2, 'A2', true], [V2, 'A3', false], [V2, 'B1', false], + [UCUM, 'mg/dL', true], [UCUM, 'kg', false], [UCUM, 'mL', false], [UCUM, 'mg/dLx', false], + [BCP47, 'en-US', true], [BCP47, 'de', false], [BCP47, 'fr', false], + [FHIRCS, 'P1', true], [FHIRCS, 'P3', false], [FHIRCS, 'P2', true], + ['http://example.org/nosuch', 'x', false] + ])('$validate-code on the mixed set: %s#%s -> %s', async (system, code, result) => { + const body = await validate(MIXED, system, code); + expect(named(body, 'result').valueBoolean).toBe(result); + }); + + test('$validate-code with activeOnly: inactive members on either kind of provider are not valid', async () => { + const active = [{ name: 'activeOnly', valueBoolean: true }]; + expect(named(await validate(MIXED, V2, 'A2', active), 'result').valueBoolean).toBe(false); + expect(named(await validate(MIXED, FHIRCS, 'P2', active), 'result').valueBoolean).toBe(false); + expect(named(await validate(MIXED, V2, 'A1', active), 'result').valueBoolean).toBe(true); + }); + + test('a UCUM canonical filter next to a v2 include, with a UCUM exclude', async () => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { + include: [inc(UCUM, { filters: [['canonical', '=', 'g']] }), inc(V2, { codes: ['B1'] })], + exclude: [inc(UCUM, { codes: ['kg'] })] } }; + const body = await expand(vs); + expect(flat(body.expansion.contains)).toEqual([[UCUM, 'mg'], [UCUM, 'g'], [UCUM, 'ug'], [V2, 'B1']]); + expect(named(await validate(vs, UCUM, 'ng'), 'result').valueBoolean).toBe(true); // valid code with the canonical: not only the common list + expect(named(await validate(vs, UCUM, 'kg'), 'result').valueBoolean).toBe(false); + expect(named(await validate(vs, UCUM, 'mL'), 'result').valueBoolean).toBe(false); + expect(named(await validate(vs, V2, 'B1'), 'result').valueBoolean).toBe(true); + }); + + test('supplements on the v2 system and on the resource, displayLanguage and designations', async () => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { + include: [inc(V2, { codes: ['A1', 'A3'] }), inc(FHIRCS, { codes: ['P1'] }), inc(BCP47, { codes: ['fr'] }), inc(UCUM, { codes: ['mg'] })] } }; + const supps = [{ name: 'tx-resource', resource: SUPP_V2 }, { name: 'tx-resource', resource: SUPP_FHIR }, + { name: 'useSupplement', valueCanonical: SUPP_V2.url }, { name: 'useSupplement', valueCanonical: SUPP_FHIR.url }]; + const de = await expand(vs, [...supps, { name: 'displayLanguage', valueCode: 'de' }]); + expect(de.expansion.contains.map(c => c.display)).toEqual(['Anzeige A1', 'Anzeige A3', 'Kind eins', 'Französisch', 'mg']); + const used = (de.expansion.parameter || []).filter(p => p.name === 'used-supplement').map(p => p.valueUri).sort(); + expect(used).toEqual([SUPP_FHIR.url + '|1', SUPP_V2.url + '|1']); + + const des = await expand(vs, [...supps, { name: 'includeDesignations', valueBoolean: true }]); + const a3 = des.expansion.contains.find(c => c.code === 'A3'); + expect((a3.designation || []).some(d => d.language === 'de' && d.value === 'Anzeige A3')).toBe(true); + + const ok = await validate(vs, V2, 'A3', [...supps, { name: 'display', valueString: 'Anzeige A3' }, { name: 'displayLanguage', valueCode: 'de' }]); + expect(named(ok, 'result').valueBoolean).toBe(true); + }); + + test('a filter on a supplement-defined property of a not-closed system does not make the expansion unclosed', async () => { + const supp = [{ name: 'tx-resource', resource: SUPP_TIER }, { name: 'useSupplement', valueCanonical: SUPP_TIER.url }]; + const unclosed = (body) => (body.expansion.extension || []).some(e => e.url.endsWith('valueset-unclosed')); + const vs = (...include) => ({ resourceType: 'ValueSet', status: 'active', compose: { include } }); + // next to a UCUM include (expand.js's include-by-include path) and alone (the engine's whole-compose path). + // Members compared as sets: main lists supplement-filter matches in the supplement's order, v2 in id order. + const mixed = await expand(vs(inc(V2OPEN, { filters: [['tier', '=', 'gold']] }), inc(UCUM, { codes: ['mg'] })), supp); + expect(flat(mixed.expansion.contains).map(String).sort()).toEqual([[UCUM, 'mg'], [V2OPEN, 'X1'], [V2OPEN, 'X3']].map(String).sort()); + expect(unclosed(mixed)).toBe(false); + const alone = await expand(vs(inc(V2OPEN, { filters: [['tier', '=', 'gold']] })), supp); + expect(flat(alone.expansion.contains).map(String).sort()).toEqual([[V2OPEN, 'X1'], [V2OPEN, 'X3']].map(String).sort()); + expect(unclosed(alone)).toBe(false); + // the system's own filters still leave it open, with or without a supplement filter beside them + expect(unclosed(await expand(vs(inc(V2OPEN, { filters: [['concept', 'is-a', 'X']] }), inc(UCUM, { codes: ['mg'] })), supp))).toBe(true); + expect(unclosed(await expand(vs(inc(V2OPEN, { filters: [['concept', 'is-a', 'X'], ['tier', '=', 'gold']] }), inc(UCUM, { codes: ['mg'] })), supp))).toBe(true); + expect(unclosed(await expand(vs(inc(V2OPEN, { filters: [['concept', 'is-a', 'X'], ['tier', '=', 'gold']] })), supp))).toBe(true); + }); + + test('$translate with a ConceptMap from the v2 system to UCUM and from BCP-47', async () => { + const cm = { resourceType: 'ConceptMap', url: 'http://example.org/fhir/ConceptMap/v2-mixed', version: '1', status: 'active', + group: [{ source: V2, target: UCUM, element: [{ code: 'A1', target: [{ code: 'mg', relationship: 'equivalent' }] }] }, + { source: BCP47, target: V2, element: [{ code: 'en-US', target: [{ code: 'B1', relationship: 'related-to' }] }] }] }; + for (const [system, code, target] of [[V2, 'A1', [UCUM, 'mg']], [BCP47, 'en-US', [V2, 'B1']]]) { + const res = await request(app).post('/tx/r5/ConceptMap/$translate').set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [{ name: 'tx-resource', resource: cm }, { name: 'url', valueUri: cm.url }, + { name: 'system', valueUri: system }, { name: 'sourceCode', valueCode: code }] }); + expect(res.status).toBe(200); + expect(named(res.body, 'result').valueBoolean).toBe(true); + const concept = named(res.body, 'match').part.find(p => p.name === 'concept').valueCoding; + expect([concept.system, concept.code]).toEqual(target); + } + }); + + test('$subsumes on UCUM (same unit written two ways) and on the v2 system', async () => { + const subsumes = async (system, codeA, codeB) => { + const res = await request(app).post('/tx/r5/CodeSystem/$subsumes').set('Content-Type', 'application/json') + .send({ resourceType: 'Parameters', parameter: [{ name: 'system', valueUri: system }, { name: 'codeA', valueCode: codeA }, { name: 'codeB', valueCode: codeB }] }); + expect(res.status).toBe(200); + return named(res.body, 'outcome').valueCode; + }; + expect(await subsumes(UCUM, '1/min', 'min-1')).toBe('equivalent'); + expect(await subsumes(UCUM, 'm', 'cm')).toBe('not-subsumed'); + expect(await subsumes(V2, 'A', 'A1')).toBe('subsumes'); + expect(await subsumes(V2, 'B1', 'A')).toBe('not-subsumed'); + }); +}); diff --git a/tests/tx/sqlite-v2-regex.test.js b/tests/tx/sqlite-v2-regex.test.js new file mode 100644 index 00000000..30cae957 --- /dev/null +++ b/tests/tx/sqlite-v2-regex.test.js @@ -0,0 +1,187 @@ +'use strict'; + +// display regex: required-literal extraction (trigram prefilter) and ".*" affix stripping must not +// change which strings match. + +const regexUtilities = require('../../library/regex-utilities'); +const { requiredLiterals, ftsQuery, stripAnyAffixes } = require('../../tx/sqlite-v2/engine/regex-literals'); + +const PATTERNS = ['tumour|neoplasm', '(tumour|tumor) of liver', '\\d+ mg tablet', 'heart.attack', 'colou?r', 'abc+de', '[Tt]umour', '.*[Tt]umou?r.*', '.*e.*', '^Fracture of.*femur.*', '^Diabetes.*', '(?i)heart attack', 'foo\\.bar+x', + 'ab{0,2}cde', 'x(abc)?yzw', '[abc]defg', 'a|bcd', '.*\\(disorder\\)$', '^Malignant neoplasm of .*', 'q.*', '.*', 'x\\.*', 'colou?r .*red']; +const STRINGS = ['Tumour of liver', 'tumor', 'Benign tumour', 'Fracture of neck of femur', 'Fracture of femur', 'fracture of femur', + 'Diabetes mellitus', 'Type 2 diabetes', 'Heart attack', 'HEART ATTACK', 'foo.barrx', 'foo.barx', 'foobarx', 'acde', 'abbcde', 'xyzw', + 'xabcyzw', 'adefg', 'bcd', 'a', 'Asthma (disorder)', 'Malignant neoplasm of lung', 'q', '', 'x...', 'colour red', 'color red', 'e', 'tumor of liver', 'neoplasm', '25 mg tablet', 'mg tablet', 'heart-attack', 'abccde', 'abde', 'Tumour']; + +describe('sqlite-v2 display regex: prefilter literals', () => { + test('every match contains every required literal (case-insensitively)', () => { + for (const p of PATTERNS) { + const re = regexUtilities.compile(p); + const lits = requiredLiterals(p); + for (const s of STRINGS) { + if (re.test(s)) for (const l of lits) expect([p, s, s.toLowerCase().includes(l.toLowerCase())]).toEqual([p, s, true]); + } + } + }); + + test('extraction: alternation, classes, escapes, anchors, groups, quantifiers', () => { + const cases = [ + // alternation at the top level: nothing is required by every branch + ['tumour|neoplasm', []], ['^a.*|b', []], ['(?:abc|abd)ef', []], + // alternation inside a group: the group is skipped, the rest still counts + ['(tumour|tumor) of liver', [' of liver']], + // classes break a literal and are never part of one + ['[Tt]umour', ['umour']], ['fe[mM]ur', []], ['[^a]bcde', ['bcde']], ['x[]a]yzw', ['yzw']], ['[a\\]]bcd', ['bcd']], + // escapes: escaped punctuation is a literal; class escapes break + ['\\(disorder\\)', ['(disorder)']], ['a\\.b\\.c', ['a.b.c']], ['\\d+ mg tablet', [' mg tablet']], ['foo\\sbar', ['foo', 'bar']], + // anchors and the dot break, and are dropped + ['^Diabetes$', ['Diabetes']], ['^Frac.ure', ['Frac', 'ure']], ['heart.attack', ['heart', 'attack']], + // optional atoms are dropped; + keeps one occurrence + ['colou?r', ['colo']], ['ab*cde', ['cde']], ['abc+de', ['abc']], ['x{0,3}abcd', ['abcd']], ['ab{2}cd', []], ['abc{1,}xyz', ['abc', 'xyz']], + // (?i) and other groups are skipped + ['(?i)heart attack', ['heart attack']], ['(abc)?def', ['def']], + // no literal of 3 characters: no prefilter + ['.*e.*', []], ['ab', []], ['a.b.c', []], ['[0-9]+', []], ['', []], ['.*', []], + ]; + for (const [p, want] of cases) expect([p, requiredLiterals(p)]).toEqual([p, want]); + }); + + test('examples', () => { + expect(requiredLiterals('.*[Tt]umou?r.*')).toEqual(['umo']); + expect(requiredLiterals('^Fracture of.*femur.*')).toEqual(['Fracture of', 'femur']); + expect(requiredLiterals('.*e.*')).toEqual([]); + expect(requiredLiterals('a|bcd')).toEqual([]); + expect(ftsQuery(['say "hi"', 'abc'])).toBe('"say ""hi""" AND "abc"'); + }); + + test('stripping ".*" affixes does not change the find-anywhere result', () => { + for (const p of PATTERNS) { + const a = regexUtilities.compile(p); + const b = regexUtilities.compile(stripAnyAffixes(p)); + for (const s of STRINGS) expect([p, s, b.test(s)]).toEqual([p, s, a.test(s)]); + } + expect(stripAnyAffixes('.*e.*')).toBe('e'); + expect(stripAnyAffixes('x\\.*')).toBe('x\\.*'); + expect(stripAnyAffixes('a|.*b')).toBe('a|.*b'); + }); +}); + +describe('sqlite-v2 display regex (generic code system): prefilter on and off give the same expansion, whole term', () => { + const fs = require('fs'); + const os = require('os'); + const path = require('path'); + const { TerminologyBuilder } = require('../../tx/importers/sqlite-v2/builder'); + const { openStore } = require('../../tx/sqlite-v2/store'); + const { Engine } = require('../../tx/sqlite-v2/engine/engine'); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + const { dialectFor } = require('../../tx/sqlite-v2/dialects'); + const SCT = 'http://example.org/cs'; // not SNOMED CT: the display regex tests concept.display + let dir; + let S; + beforeAll(() => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-regex-')); + const b = new TerminologyBuilder(path.join(dir, 'sct.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: SCT, version: '1' }); + const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); + const root = b.concept('138875005', { active: true, display: 'SNOMED CT Concept' }); + const extra = ['Tumour of skin', 'Benign tumor of skin', 'TUMOUR', 'Fracture of shaft of femur', 'Closed fracture of femur', + 'Fracture of femur (disorder)', 'Diabetes mellitus type 2', 'Pre-diabetes', 'Heart attack', 'heart attack', 'Herzinfarkt', + 'Ödem der Leber', 'oedema', 'Paracetamol 500 mg tablet', 'mg tablet', '10 mg/ml', 'a.b.c', 'abc', 'colour', 'color', 'tumour|x']; + const displays = [...new Set([...STRINGS, ...extra])].filter((d) => d !== ''); + displays.forEach((d, i) => b.link(b.concept(String(1000000 + i * 10 + 1), { active: true, display: d }), isa, root)); + b.finish(); + S = openStore(path.join(dir, 'sct.db')); + }); + afterAll(() => { S.close(); fs.rmSync(dir, { recursive: true, force: true }); }); + + const run = (re, strip) => { + const c = new Compiler({ store: S, dialect: dialectFor(SCT) }); + const sel = c.selection([{ system: SCT, filter: [{ property: 'display', op: 'regex', value: re }] }], [], false); + const walk = (n) => { if (n && typeof n === 'object') { if (n.t === 'text' && strip) delete n.lits; Object.values(n).forEach(walk); } }; + walk(sel); + const r = new Engine(S).run(sel, { offset: 0, count: -1 }); + return r.page(0, -1); + }; + + test('identical results (and the same as RE2 on every display)', () => { + expect(S.hasFts).toBe(true); + const all = S.db.prepare('SELECT id AS concept_id, display FROM concept').all(); + for (const p of [...PATTERNS, '[Tt]umou?r', 'Fracture of.*femur', '(?i)HEART ATTACK', '\\d+ mg', 'Ödem', '(?i)ödem', 'tumour\\|x']) { + const on = run(p, false); + const off = run(p, true); + const re = regexUtilities.compile('^(?:' + p + ')$'); // whole term + const truth = all.filter((r) => re.test(r.display)).map((r) => r.concept_id).sort((a, b) => a - b); + expect([p, on]).toEqual([p, off]); + expect([p, [...on].sort((a, b) => a - b)]).toEqual([p, truth]); + } + }); +}); + + +describe('sqlite-v2 display regex on the SNOMED CT test edition (tx/data/snomed RF2)', () => { + const fs = require('fs'); + const os = require('os'); + const path = require('path'); + const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); + const { openStore } = require('../../tx/sqlite-v2/store'); + const { Engine } = require('../../tx/sqlite-v2/engine/engine'); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + const { dialectFor } = require('../../tx/sqlite-v2/dialects'); + const SCT = 'http://snomed.info/sct'; + const SRC = path.resolve(__dirname, '../../tx/data/snomed'); + let dir; + let S; + + const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); + // the fixture is split by module; the RF2 importer reads one file per kind + function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt')) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } + } + + beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-regex-test-edition-')); + mergeSnapshot(SRC, path.join(dir, 'Snapshot')); + await importSnomedV2({ source: path.join(dir, 'Snapshot'), dest: path.join(dir, 'test.db'), edition: '31000003106', version: '20250909', overwrite: true, log: () => {} }); + S = openStore(path.join(dir, 'test.db')); + }, 120000); + afterAll(() => { if (S) S.close(); if (dir) fs.rmSync(dir, { recursive: true, force: true }); }); + + test('prefilter on = off = RE2 over every active FSN/synonym in the language, whole term', () => { + const FSN = '900000000000003001'; + const SYN = '900000000000013009'; + const uses = new Set([...S.uses].filter(([, u]) => u && (u.code === FSN || u.code === SYN)).map(([id]) => id)); + const all = S.db.prepare('SELECT concept_id, text AS display, language, use_id, active FROM item').all() + .filter((r) => r.active && uses.has(r.use_id) && String(r.language).toLowerCase().split('-')[0] === 'en'); + expect(all.length).toBeGreaterThan(1000); + const pats = ['.*[Tt]umou?r.*', '^Fracture of.*femur.*', '^Diabetes.*', '.*e.*', '(?i)LIVER', 'syndrome$', '.*\\(disorder\\)$', + '.*of (left|right) .*', '.*hepat.*|.*renal.*', '[A-Z][a-z]+ [a-z]+ of', '\\d+', 'ure.*ure', '(?i)hepatorenal syndrome', 'Liver structure']; + let prefiltered = 0; + for (const p of pats) { + const c = new Compiler({ store: S, dialect: dialectFor(SCT) }); + const mk = () => c.selection([{ system: SCT, filter: [{ property: 'display', op: 'regex', value: p }] }], [], false); + const selOn = mk(); + const selOff = mk(); + const strip = (n) => { if (n && typeof n === 'object') { if (n.t === 'text' || n.t === 'desigRegex') delete n.lits; Object.values(n).forEach(strip); } }; + strip(selOff); + if (JSON.stringify(selOn).includes('"lits"')) prefiltered++; + const on = new Engine(S).run(selOn, { offset: 0, count: -1 }).page(0, -1); + const off = new Engine(S).run(selOff, { offset: 0, count: -1 }).page(0, -1); + const re = regexUtilities.compile('^(?:' + p + ')$'); + const truth = [...new Set(all.filter((r) => re.test(r.display)).map((r) => r.concept_id))].sort((a, b) => a - b); + expect([p, on]).toEqual([p, off]); + expect([p, [...on].sort((a, b) => a - b)]).toEqual([p, truth]); + } + expect(prefiltered).toBeGreaterThanOrEqual(8); + }); +}); diff --git a/tests/tx/sqlite-v2-rxnorm-filters.test.js b/tests/tx/sqlite-v2-rxnorm-filters.test.js new file mode 100644 index 00000000..e1915e16 --- /dev/null +++ b/tests/tx/sqlite-v2-rxnorm-filters.test.js @@ -0,0 +1,224 @@ +'use strict'; + +// RxNorm include filters on sqlite-v2 against main's provider (tx/cs/cs-rxnorm.js), both built +// from one small RRF fixture and run through the real router. Main takes `=` and `in` on TTY, STY +// and SAB (any case), on concept and code, and on a relationship (a REL or RELA that RXNREL has, +// from any source) whose values are all CUI: or AUI:. Anything else is a 422 +// FILTER_NOT_UNDERSTOOD. A CUI: value follows RxNorm's own concept-level rows. An AUI: value +// main follows over the atom-level rows of every source; sqlite-v2 stores no atom-level rows and +// refuses it with the same 422 (a known difference). + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { importRxNormV2 } = require('../../tx/importers/import-rxnorm-v2.module'); +const { RxNormImporter } = require('../../tx/importers/import-rxnorm.module'); +const { RxNormServicesFactory } = require('../../tx/cs/cs-rxnorm'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); + +const RX = 'http://www.nlm.nih.gov/research/umls/rxnorm'; +const VERSION = '01012026'; +let app, tx, dir, v2, classic; + +// RXNCONSO: RXCUI|LAT|TS|LUI|STT|SUI|ISPREF|RXAUI|SAUI|SCUI|SDUI|SAB|TTY|CODE|STR|SRL|SUPPRESS|CVF +const conso = (cui, aui, sab, tty, str, sup = 'N') => [cui, 'ENG', '', '', '', '', '', aui, '', '', '', sab, tty, cui, str, '', sup, ''].join('|') + '|'; +// RXNATOMARCHIVE: RXAUI|AUI|STR|ARCHIVE_TIMESTAMP|CREATED_TIMESTAMP|UPDATED_TIMESTAMP|CODE|IS_BRAND|LAT| +// LAST_RELEASED|SAUI|VSAB|RXCUI|SAB|TTY|MERGED_TO_RXCUI +const archive = (cui, aui, tty, str) => [aui, '', str, '', '', '', cui, '', 'ENG', '', '', '', cui, 'RXNORM', tty, ''].join('|') + '|'; +// RXNREL: RXCUI1|RXAUI1|STYPE1|REL|RXCUI2|RXAUI2|STYPE2|RELA|RUI|SRUI|SAB|SL|RG|DIR|SUPPRESS|CVF +const cuiRel = (cui1, rel, cui2, rela, sab = 'RXNORM') => [cui1, '', 'CUI', rel, cui2, '', 'CUI', rela, '', '', sab, '', '', '', 'N', ''].join('|') + '|'; +const auiRel = (aui1, rel, aui2, rela, sab) => ['', aui1, 'AUI', rel, '', aui2, 'AUI', rela, '', '', sab, '', '', '', '', ''].join('|') + '|'; + +function buildRrf(rrf) { + fs.mkdirSync(rrf, { recursive: true }); + fs.writeFileSync(path.join(rrf, 'RXNCONSO.RRF'), [ + conso('100', '1001', 'RXNORM', 'SCD', 'drug a 10 MG Oral Tablet'), + conso('100', '1003', 'MMSL', 'BD', 'drug a tablet (MMSL)'), + conso('200', '2001', 'RXNORM', 'IN', 'ingredient b'), + conso('200', '2002', 'MMSL', 'IN', 'ingredient b (MMSL)'), + conso('300', '3001', 'RXNORM', 'SBD', 'brand c 10 MG Oral Tablet'), + conso('300', '3002', 'MTHSPL', 'SU', 'brand c (SPL)'), + conso('400', '4001', 'RXNORM', 'IN', 'ingredient d'), + conso('500', '5001', 'MMSL', 'BD', 'not an RxNorm concept'), + conso('90', '9001', 'RXNORM', 'SCD', 'drug e 5 MG Oral Tablet'), // before 100 by number, after it as text + conso('600', '6001', 'RXNORM', 'SCD', 'obsolete drug f', 'O'), + ].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNREL.RRF'), [ + cuiRel('200', 'RO', '100', 'has_ingredient'), // 100 has_ingredient 200 + cuiRel('400', 'RO', '100', 'has_ingredient'), // 100 has_ingredient 400 + cuiRel('100', 'RB', '300', 'tradename_of'), // 300 tradename_of 100 + cuiRel('200', 'RO', '700', 'has_ingredient'), // the archived concept: never selected + auiRel('2002', 'RO', '1003', 'has_ingredient', 'MMSL'), // atom 1003 (concept 100) has_ingredient atom 2002 + auiRel('3001', 'SY', '3002', '', 'RXNORM'), // atom-level SY row, no RELA + auiRel('2002', 'RO', '3002', 'has_active_ingredient', 'MTHSPL'), // a RELA only atom-level rows have + auiRel('2002', 'RO', '5001', 'has_active_ingredient', 'MTHSPL'), // to an atom of a concept RxNorm doesn't have + ].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNSTY.RRF'), ['100|T200|||A|', '200|T121|||A|', '300|T200|||A|', '400|T121|||A|', '90|T200|||A|', '600|T200|||A|', '700|T200|||A|'].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNATOMARCHIVE.RRF'), archive('700', '7001', 'SCD', 'archived drug g') + '\n'); +} + +/** serve RxNorm from this factory only */ +function use(f) { + const p = tx.endpoints[0].provider; + for (const key of [...p.codeSystemFactories.keys()]) if (key === RX || key.startsWith(RX + '|')) p.codeSystemFactories.delete(key); + p.codeSystemFactories.set(RX, f); + p.codeSystemFactories.set(RX + '|' + f.version(), f); + for (const e of tx.endpoints) e.expansionCache.clearAll(); +} + +async function expand(filters, { count = 100, inactive, activeOnly } = {}) { + const include = filters ? { system: RX, filter: filters.map(([property, op, value]) => ({ property, op, value })) } : { system: RX }; + const valueSet = { resourceType: 'ValueSet', status: 'active', compose: Object.assign({ include: [include] }, inactive != null ? { inactive } : {}) }; + const parameter = [{ name: 'valueSet', resource: valueSet }, { name: 'count', valueInteger: count }]; + if (activeOnly != null) parameter.push({ name: 'activeOnly', valueBoolean: activeOnly }); + const res = await request(app).post('/tx/r5/ValueSet/$expand').send({ resourceType: 'Parameters', parameter }); + if (res.status !== 200) { + const issues = (res.body.issue || []).map((i) => [i.severity, i.code, i.details && i.details.text, + ((i.details && i.details.coding) || []).map((c) => c.code).join(','), + ((i.extension || []).find((e) => /operationoutcome-message-id/.test(e.url)) || {}).valueString]); + return { status: res.status, issues }; + } + return { status: 200, codes: (res.body.expansion.contains || []).map((c) => c.code), total: res.body.expansion.total }; +} + +async function both(filters, opts) { + use(v2); + const a = await expand(filters, opts); + use(classic); + const b = await expand(filters, opts); + use(v2); + return { v2: a, main: b }; +} + +beforeAll(async () => { + app = await getTestApp(); + tx = getTxModule(); + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-rxfilters-')); + const rrf = path.join(dir, 'rrf'); + buildRrf(rrf); + await importRxNormV2({ source: rrf, dest: path.join(dir, 'rx.db'), version: VERSION, overwrite: true, log: () => {} }); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new RxNormImporter(rrf, path.join(dir, 'rxnorm_' + VERSION + '.db'), VERSION, { verbose: false, createStems: true }).import(); + } finally { quiet.mockRestore(); } + v2 = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'rx.db')); + classic = new RxNormServicesFactory(tx.i18n, path.join(dir, 'rxnorm_' + VERSION + '.db')); + await classic.load(); + use(v2); +}, 120000); + +afterAll(async () => { + await shutdownTestApp(); + if (v2) v2.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +const ACCEPTED = [ + [['TTY', '=', 'SCD']], [['TTY', 'in', 'SCD,IN']], [['tty', '=', 'IN']], [['STY', '=', 'T200']], [['SAB', '=', 'MMSL']], + [['SAB', 'in', 'MMSL, MTHSPL']], [['concept', '=', '100']], [['concept', 'in', '100,200']], [['code', '=', '300']], + [['has_ingredient', '=', 'CUI:200']], [['has_ingredient', 'in', 'CUI:200,CUI:400']], [['RO', '=', 'CUI:200']], + [['RB', '=', 'CUI:100']], [['tradename_of', '=', 'CUI:100']], + // a REL or RELA only atom-level rows have, with a CUI value: RxNorm's own rows have none of it + [['has_active_ingredient', '=', 'CUI:200']], [['SY', '=', 'CUI:300']], + [['TTY', '=', 'SCD'], ['has_ingredient', '=', 'CUI:200']], +]; + +const REFUSED = [ + [['TTY', 'regex', 'SC.*']], [['TTY', 'not-in', 'SCD']], [['TTY', 'exists', 'true']], [['STY', 'is-a', 'T200']], + [['concept', 'is-a', '100']], [['concept', 'descendent-of', '100']], [['concept', 'regex', '1.*']], [['concept', 'not-in', '100']], + [['display', 'regex', 'drug.*']], [['display', '=', 'ingredient b']], + [['has_ingredient', '=', '200']], [['has_ingredient', 'in', 'CUI:200,400']], [['has_ingredient', 'exists', 'true']], + [['has_ingredient', 'not-in', 'CUI:200']], [['has_ingredient', 'regex', 'CUI:.*']], [['RO', '=', '200']], + [['XX', '=', 'CUI:1']], [['SUPPRESS', '=', 'N']], [['TTY', 'in', ' , ']], + [['TTY', '=', 'SCD'], ['TTY', 'regex', 'S.*']], +]; + +// main follows these over the atom-level rows (200); sqlite-v2 refuses them +const AUI = [ + [['has_ingredient', '=', 'AUI:2002']], [['has_ingredient', 'in', 'CUI:400,AUI:2002']], [['has_ingredient', 'in', 'AUI:2002,CUI:400']], + [['RO', '=', 'AUI:2002']], [['SY', '=', 'AUI:3001']], [['has_active_ingredient', '=', 'AUI:2002']], [['has_ingredient', '=', 'AUI:9999']], +]; + +const refusal = (filters) => { + const [property, op, value] = filters[filters.length - 1]; + return { status: 422, issues: [['error', 'not-supported', `The filter "${property} ${op} ${value}" is not understood or supported`, 'vs-invalid', 'FILTER_NOT_UNDERSTOOD']] }; +}; + +describe('sqlite-v2 RxNorm filters, as main', () => { + test.each(ACCEPTED)('accepted: %j', async (...filters) => { + const r = await both(filters); + expect(r.main.status).toBe(200); + expect(r.v2).toEqual(r.main); + }); + + test.each(REFUSED)('refused: %j', async (...filters) => { + const r = await both(filters); + expect(r.main.status).toBe(422); + expect(r.main.issues.map((i) => i[4])).toContain('FILTER_NOT_UNDERSTOOD'); + expect(r.v2).toEqual(r.main); + }); + + test.each(AUI)('AUI: value, main follows atom-level rows, sqlite-v2 refuses: %j', async (...filters) => { + const r = await both(filters); + expect(r.main.status).toBe(200); + expect(r.v2).toEqual(refusal(filters)); + }); + + test.each([ + [{}], [{ count: 2 }], [{ count: 0 }], [{ count: 0, inactive: false }], [{ count: 0, activeOnly: true }], [{ activeOnly: true }], [{ inactive: false }], + ])('the whole system %j: the same codes, order and total', async (opts) => { + const r = await both(null, opts); + expect(r.main.status).toBe(200); + expect(r.v2).toEqual(r.main); + }); + + test('the whole system: obsolete concepts are counted and listed, archived ones never; RXCUI in text order', async () => { + const r = await both(null, {}); + expect(r.main.codes).toEqual(['100', '200', '300', '400', '600', '90']); + expect(r.main.total).toBe(6); + expect((await both(null, { count: 0, inactive: false })).main.total).toBe(6); + }); + + test.each([[[['STY', '=', 'T200']]], [[['has_ingredient', '=', 'CUI:200']]], [[['TTY', 'in', 'SCD,SBD']]]])('the filter API (expand.js\'s usual path) %j: the codes of main, in its order', async (filters) => { + const { OperationContext } = require('../../tx/operation-context'); + const op = new OperationContext('en', tx.i18n); + const codesOf = async (f) => { + const p = await f.build(op, []); + const prep = await p.getPrepContext(true); + for (const [prop, o, value] of filters) await p.filter(prep, true, prop, o, value); + const [set] = await p.executeFilters(prep); + const out = []; + while (await p.filterMore(prep, set)) out.push(await p.code(await p.filterConcept(prep, set))); + return out; + }; + const want = await codesOf(classic); + expect(want.length).toBeGreaterThan(0); + expect(want).not.toContain('700'); + expect(await codesOf(v2)).toEqual(want); + }); + + test('the fixture finds something: CUI values, and (main only) AUI values over other sources\' rows', async () => { + const r = async (f) => (await both([f])).main.codes; + expect(await r(['has_ingredient', '=', 'CUI:200'])).toEqual(['100']); + expect(await r(['has_ingredient', '=', 'AUI:2002'])).toEqual(['100']); + expect(await r(['SY', '=', 'AUI:3001'])).toEqual(['300']); + expect(await r(['has_active_ingredient', '=', 'AUI:2002'])).toEqual(['300']); + expect(await r(['has_active_ingredient', '=', 'CUI:200'])).toEqual([]); + }); + + test('the default file holds no atom-level rows; the REL and RELA names of every source are catalog rows', () => { + const Database = require('better-sqlite3'); + const db = new Database(path.join(dir, 'rx.db'), { readonly: true }); + try { + expect(db.prepare("SELECT count(*) FROM property WHERE code LIKE 'AUI:%'").pluck().get()).toBe(0); + expect(db.prepare('SELECT count(*) FROM identifier').pluck().get()).toBe(0); + const rows = Object.fromEntries(db.prepare('SELECT code, shape, wildcard, n_rows FROM property').raw().all().map(([c, ...r]) => [c, r])); + for (const rela of ['has_ingredient', 'has_active_ingredient', 'tradename_of']) expect(rows[rela]).toBeDefined(); + for (const rel of ['RO', 'RB', 'SY']) expect(rows[rel]).toBeDefined(); + // has_active_ingredient: only other sources' atom-level rows have it, so it selects nothing + expect(rows.has_active_ingredient).toEqual(['link', 1, 0]); + } finally { db.close(); } + }); +}); diff --git a/tests/tx/sqlite-v2-rxnorm-status.test.js b/tests/tx/sqlite-v2-rxnorm-status.test.js new file mode 100644 index 00000000..aedbd00a --- /dev/null +++ b/tests/tx/sqlite-v2-rxnorm-status.test.js @@ -0,0 +1,88 @@ +'use strict'; + +// sqlite-v2 RxNorm concept status, as cs-rxnorm.js: a concept whose display atom is +// SUPPRESS = O is inactive with status 'obsolete' (still selected by filters and whole-system +// includes, not deprecated); one found only in RXNATOMARCHIVE is inactive, 'archived' and +// deprecated, and never selected. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { importRxNormV2 } = require('../../tx/importers/import-rxnorm-v2.module'); +const { openStore } = require('../../tx/sqlite-v2/store'); +const { Engine } = require('../../tx/sqlite-v2/engine/engine'); +const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); +const { dialectFor } = require('../../tx/sqlite-v2/dialects'); + +const RX = 'http://www.nlm.nih.gov/research/umls/rxnorm'; +let dir, db; + +// RXNCONSO: RXCUI|LAT|TS|LUI|STT|SUI|ISPREF|RXAUI|SAUI|SCUI|SDUI|SAB|TTY|CODE|STR|SRL|SUPPRESS|CVF +const conso = (cui, aui, sab, tty, str, sup) => [cui, 'ENG', '', '', '', '', '', aui, '', '', '', sab, tty, cui, str, '', sup, ''].join('|'); +// RXNATOMARCHIVE: RXAUI|AUI|STR|ARCHIVE_TIMESTAMP|CREATED_TIMESTAMP|UPDATED_TIMESTAMP|CODE|IS_BRAND|LAT| +// LAST_RELEASED|SAUI|VSAB|RXCUI|SAB|TTY|MERGED_TO_RXCUI +const archive = (cui, aui, tty, str) => [aui, '', str, '', '', '', cui, '', 'ENG', '', '', '', cui, 'RXNORM', tty, ''].join('|'); + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-rxstatus-')); + const rrf = path.join(dir, 'rrf'); + fs.mkdirSync(rrf); + fs.writeFileSync(path.join(rrf, 'RXNCONSO.RRF'), [ + conso('100', 'A1', 'RXNORM', 'SCD', 'current drug', 'N'), + conso('200', 'A2', 'RXNORM', 'SCD', 'obsolete drug', 'O'), + conso('200', 'A3', 'RXNORM', 'SY', 'obsolete synonym', 'N'), // SY: never the display atom + conso('300', 'A4', 'RXNORM', 'PSN', 'prescribable name', 'O'), // ranked after the SCD atom + conso('300', 'A5', 'RXNORM', 'SCD', 'current by display atom', 'N'), + conso('100', 'A6', 'MMSL', 'BD', 'other source, obsolete', 'O'), // other sources do not count + ].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNATOMARCHIVE.RRF'), archive('400', 'A7', 'SCD', 'archived drug') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNREL.RRF'), ''); + fs.writeFileSync(path.join(rrf, 'RXNSTY.RRF'), ['100', '200', '300'].map((c) => `${c}|T200|||A|`).join('\n') + '\n'); + db = path.join(dir, 'rx.db'); + await importRxNormV2({ source: rrf, dest: db, version: '01012026', overwrite: true, log: () => {} }); +}); +afterAll(() => fs.rmSync(dir, { recursive: true, force: true })); + +describe('sqlite-v2 RxNorm obsolete and archived concepts', () => { + test('selection: filters and the whole system take obsolete concepts, never archived ones', () => { + const S = openStore(db); + try { + const run = (includes, activeOnly = false) => { + const c = new Compiler({ store: S, dialect: dialectFor(S.system) }); + const r = new Engine(S).run(c.selection(includes, [], activeOnly), { offset: 0, count: -1 }); + const rows = S.conceptRows(r.page(0, -1)); + return [...rows.values()].map((x) => x.code).sort(); + }; + expect(run([{ system: RX }])).toEqual(['100', '200', '300']); + expect(run([{ system: RX }], true)).toEqual(['100', '300']); + expect(run([{ system: RX, filter: [{ property: 'TTY', op: '=', value: 'SCD' }] }])).toEqual(['100', '200', '300']); + expect(run([{ system: RX, filter: [{ property: 'STY', op: '=', value: 'T200' }] }], true)).toEqual(['100', '300']); + } finally { + S.close(); + } + }); + + test('provider: inactive, status and deprecation as cs-rxnorm.js', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const factory = new SqliteV2Factory(op.i18n, db); + await factory.load(); + try { + const p = await factory.build(op, []); + const facts = async (code) => { + const ctx = (await p.locate(code)).context; + return [await p.isInactive(ctx), await p.getStatus(ctx), await p.isDeprecated(ctx)]; + }; + expect(await facts('100')).toEqual([false, null, false]); + expect(await facts('200')).toEqual([true, 'obsolete', false]); + expect(await facts('300')).toEqual([false, null, false]); + expect(await facts('400')).toEqual([true, 'archived', true]); + const all = await p.iteratorAll(); + expect(all.total).toBe(3); + } finally { + factory.store.close(); + } + }); +}); diff --git a/tests/tx/sqlite-v2-sct-concrete-type-relationship.test.js b/tests/tx/sqlite-v2-sct-concrete-type-relationship.test.js new file mode 100644 index 00000000..3062b4cf --- /dev/null +++ b/tests/tx/sqlite-v2-sct-concrete-type-relationship.test.js @@ -0,0 +1,94 @@ +'use strict'; + +// An inactive sct2_Relationship row whose typeId is also a concrete-value attribute, with a concept +// target (the UK Edition has two: retired pre-concrete-domain drug rows of 149501000000101 typed +// 1142139005 and 1142140007). Both importers keep the row, as a link of that attribute, whose +// catalog row then has shape 'both' (links and literals). Main's provider never reads inactive +// relationships, nor links of a concrete attribute: the reader leaves them out where no property +// is named (READER_RULES unnamedLinksSkipBoth), so $lookup is main's. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { openStore } = require('../../tx/sqlite-v2/store'); +const { SnomedImporter } = require('../../tx/importers/import-sct.module'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); +const { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +const SCT_LICENSE = path.join(SRC, 'license.txt'); +const COUNT_OF_BASE = '1142139005'; // a concrete attribute of the fixture (#1 on 329238006 and 776168003) +const SOURCE = '329238006', TARGET = '776168003'; +let dir, snap; + +function walk(d) { + return fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +} + +// one file per kind, as the RF2 v2 importer reads (as sqlite-v2-sct-from-cache.test.js) +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt')) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + const lines = files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)); + fs.writeFileSync(out, lines.join('\n') + '\n'); + } +} + +/** the attribute's catalog shape, its rows, and the links the reader gives a $lookup of the source */ +function rows(db, code) { + const d = new Database(db, { readonly: true }); + let p, links, literals; + try { + p = d.prepare('SELECT id, shape FROM property WHERE code = ?').get(code); + links = d.prepare('SELECT count(*) FROM link WHERE property_id = ?').pluck().get(p.id); + literals = d.prepare('SELECT count(*) FROM literal WHERE property_id = ?').pluck().get(p.id); + } finally { d.close(); } + const S = openStore(db, { unregistered: true }); + try { + const unnamed = S.linksFrom([S.idOf(SOURCE)], null, false).filter((l) => l.p === p.id).length; + const named = S.linksFrom([S.idOf(SOURCE)], new Set([p.id]), false).length; + return { shape: p.shape, links, literals, unnamed, named }; + } finally { S.close(); } +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sct-concrete-type-')); + snap = path.join(dir, 'Snapshot'); + mergeSnapshot(SRC, snap); + const rel = walk(snap).find((f) => /sct2_Relationship_Snapshot_/.test(path.basename(f))); + fs.appendFileSync(rel, ['9990011000003121', '20200101', '0', '31000003106', SOURCE, TARGET, '0', COUNT_OF_BASE, + '900000000000011006', '900000000000451002'].join('\t') + '\n'); +}, 30000); + +afterAll(() => { if (dir) fs.rmSync(dir, { recursive: true, force: true }); }); + +test('RF2: the inactive row is a link of the attribute (shape both), not read by an unnamed lookup', async () => { + const db = path.join(dir, 'rf2.db'); + const summary = await importSnomedV2({ source: snap, dest: db, edition: '31000003106', version: '20250909', overwrite: true, + normalForms: false, log: () => {} }); + expect(summary.importer.concreteTypeLinks).toBe(1); + expect(rows(db, COUNT_OF_BASE)).toEqual({ shape: 'both', links: 1, literals: 4, unnamed: 0, named: 1 }); +}, 120000); + +test('cache: the same row from main\'s cache, the same way', async () => { + const cache = path.join(dir, 't.cache'); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new SnomedImporter({ source: snap, dest: cache, edition: '31000003106', version: '20250909', + uri: 'http://snomed.info/sct/31000003106/version/20250909', language: 'en-US', license: SCT_LICENSE, verbose: false, overwrite: true }).run(); + } finally { quiet.mockRestore(); } + const db = path.join(dir, 'rev.db'); + const summary = await importSnomedV2FromCache({ source: cache, dest: db, overwrite: true, normalForms: false, log: () => {} }); + expect(summary.importer.concreteTypeLinks).toBe(1); + expect(rows(db, COUNT_OF_BASE)).toEqual({ shape: 'both', links: 1, literals: 4, unnamed: 0, named: 1 }); +}, 120000); diff --git a/tests/tx/sqlite-v2-sct-default-language.test.js b/tests/tx/sqlite-v2-sct-default-language.test.js new file mode 100644 index 00000000..c1d1f6d9 --- /dev/null +++ b/tests/tx/sqlite-v2-sct-default-language.test.js @@ -0,0 +1,187 @@ +'use strict'; + +// The SNOMED CT edition's default language (#397, 1.0.4): the language a text or display regex +// filter searches when the request names none. Main's importer records the edition's language in +// the cache's default-language slot (format 20), and its server reads the slot (a language byte, +// or, in the original server's caches, a language reference set's offset). The engine's importers +// record the same language in cs_config, and the engine chooses the search language as +// cs-snomed.js #filterLanguage does. Here: the test edition imported as a Dutch edition +// (--language nl-NL), by main's importer and the engine's two. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { SnomedServicesFactory } = require('../../tx/cs/cs-snomed'); +const { SnomedImporter } = require('../../tx/importers/import-sct.module'); +// main's importer requires the license the edition is distributed under (cache format 21) +const SCT_LICENSE = path.join(__dirname, '../../tx/data/snomed/license.txt'); +const { cacheDefaultLanguage } = require('../../tx/importers/import-sct-v2-cache.module'); +const { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { rf2DefaultLanguage } = require('../../tx/importers/import-sct-v2.module'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); +const { SnomedFileReader } = require('../../tx/sct/structures'); +const { languageByte } = require('../../tx/sct/languages'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); +const { OperationContext } = require('../../tx/operation-context'); +const { SearchFilterText } = require('../../tx/library/designations'); +const { Languages } = require('../../library/languages'); +const { TestUtilities } = require('../test-utilities'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +let dir, op, langDefs, main, fromCache, fromRf2, mainEn, engineEn; + +const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +async function mainCache(snap, dest, language) { + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new SnomedImporter({ source: snap, dest, edition: '31000003106', version: '20250909', + uri: 'http://snomed.info/sct/31000003106/version/20250909', language, license: SCT_LICENSE, verbose: false, overwrite: true }).run(); + } finally { quiet.mockRestore(); } +} + +const config = (file) => { + const db = new Database(file, { readonly: true }); + try { return db.prepare('SELECT default_language FROM code_system WHERE served = 1').pluck().get(); } finally { db.close(); } +}; + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-sct-deflang-')); + langDefs = await TestUtilities.loadLanguageDefinitions(); + op = new OperationContext('en', await TestUtilities.loadTranslations(langDefs)); + const snap = path.join(dir, 'Snapshot'); + mergeSnapshot(SRC, snap); + await mainCache(snap, path.join(dir, 'nl.cache'), 'nl-NL'); + await mainCache(snap, path.join(dir, 'en.cache'), 'en-US'); + main = new SnomedServicesFactory(op.i18n, path.join(dir, 'nl.cache')); + await main.load(); + mainEn = new SnomedServicesFactory(op.i18n, path.join(dir, 'en.cache')); + await mainEn.load(); + await importSnomedV2FromCache({ source: path.join(dir, 'nl.cache'), dest: path.join(dir, 'nl-cache.db'), overwrite: true, normalForms: false, log: () => {} }); + await importSnomedV2FromCache({ source: path.join(dir, 'en.cache'), dest: path.join(dir, 'en-cache.db'), overwrite: true, normalForms: false, log: () => {} }); + await importSnomedV2({ source: snap, dest: path.join(dir, 'nl-rf2.db'), edition: '31000003106', version: '20250909', language: 'nl-NL', overwrite: true, normalForms: false, log: () => {} }); + fromCache = await loadSqliteV2Factory(op.i18n, path.join(dir, 'nl-cache.db')); + fromRf2 = await loadSqliteV2Factory(op.i18n, path.join(dir, 'nl-rf2.db')); + engineEn = await loadSqliteV2Factory(op.i18n, path.join(dir, 'en-cache.db')); +}, 180000); + +afterAll(async () => { + for (const f of [fromCache, fromRf2, engineEn]) if (f) f.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +const langs = (header) => (header ? Languages.fromAcceptLanguage(header, langDefs, false) : null); + +/** the codes a provider's text filter (or display regex) selects, in its order */ +async function select(factory, how, header = null) { + const p = await factory.build(op, []); + const prep = await p.getPrepContext(true, langs(header)); + if (how.text != null) await p.searchFilter(prep, new SearchFilterText(how.text), true); + else await p.filter(prep, true, 'display', 'regex', how.regex); + const sets = await p.executeFilters(prep); + const out = []; + while (await p.filterMore(prep, sets[0])) out.push(await p.code(await p.filterConcept(prep, sets[0]))); + return out; +} + +async function same(how, header = null, m = main, engines = [fromCache, fromRf2]) { + const want = await select(m, how, header); + for (const e of engines) expect([how, header, await select(e, how, header)]).toEqual([how, header, want]); + return want; +} + +describe('SNOMED CT default language', () => { + test('main\'s importer writes the edition\'s language; the engine\'s files record the same', async () => { + const d = await new SnomedFileReader(path.join(dir, 'nl.cache')).loadSnomedData(); + expect(d.cacheVersion).toBe('21'); + expect(d.defaultLanguage).toBe(languageByte('nl')); + expect(main.snomedServices.defaultLanguage).toBe(languageByte('nl')); + expect(cacheDefaultLanguage(d)).toBe(languageByte('nl')); + expect(config(path.join(dir, 'nl-cache.db'))).toBe('nl'); + expect(config(path.join(dir, 'nl-rf2.db'))).toBe('nl'); + // English: as before + expect(config(path.join(dir, 'en-cache.db'))).toBe('en-US'); + }); + + test('an older cache: a language reference set\'s offset in the slot (the original server\'s caches) is read as main read it up to 1.0.4', async () => { + const d = await new SnomedFileReader(path.join(dir, 'nl.cache')).loadSnomedData(); + const svc = main.snomedServices; + // main up to 1.0.4: the language most of that reference set's descriptions are in; any + // other value English. Main's server now reads only format 21 (a language byte). + let seen = 0; + for (let i = 0; i < svc.refSetIndex.count(); i++) { + const offset = svc.refSetIndex.getReferenceSet(i).membersByRef; + const counts = [...svc.refSetMembers.descriptionLanguages(offset, svc.descriptions)].sort((a, b) => b[1] - a[1]); + const want = counts.length ? counts[0][0] : 1; + if (counts.length) seen++; + expect(cacheDefaultLanguage({ ...d, cacheVersion: '16', defaultLanguage: offset })).toBe(want); + } + expect(seen).toBeGreaterThan(0); // the test edition has language reference sets + expect(cacheDefaultLanguage({ ...d, cacheVersion: '19', defaultLanguage: languageByte('nl') })).toBe(languageByte('nl')); + expect(cacheDefaultLanguage({ ...d, cacheVersion: '20', defaultLanguage: 999999 })).toBe(1); + }); + + test('the RF2 importer: --language, else the edition\'s language, if the edition has descriptions in it', () => { + expect(rf2DefaultLanguage({ edition: '11000146104' }, new Set(['en', 'nl']))).toBe('nl'); + expect(rf2DefaultLanguage({ edition: '11000146104' }, new Set(['en']))).toBe(null); + expect(rf2DefaultLanguage({ edition: '449081005' }, new Set(['en', 'es']))).toBe('es'); + expect(rf2DefaultLanguage({ edition: '900000000000207008' }, new Set(['en']))).toBe(null); + expect(rf2DefaultLanguage({ edition: '31000003106', language: 'nl-NL' }, new Set(['en', 'nl']))).toBe('nl'); + expect(rf2DefaultLanguage({ edition: '51000202101' }, new Set(['en', 'no']))).toBe('no'); + expect(rf2DefaultLanguage({ edition: '31000003106' }, new Set(['en', 'nl']))).toBe(null); + }); + + test('a text filter with no request language searches the edition\'s language, as main', async () => { + for (const [f, h] of [['hematoom', null], ['hematoma', null], ['lever', null], ['hematoom', 'en'], ['hematoma', 'en'], + ['hematoom', 'nl'], ['hematoom', 'de'], ['hematoma', 'de'], ['hemat', null]]) await same({ text: f }, h); + expect(await same({ text: 'hematoom' })).toContain('35566002'); + expect(await same({ text: 'hematoma' })).toEqual([]); + // the English edition, as before + expect(await same({ text: 'hematoom' }, null, mainEn, [engineEn])).toEqual([]); + }); + + test('a display regex with no request language matches the edition\'s language, as main', async () => { + for (const [r, h] of [['.*hematoom.*', null], ['.*[Hh]ematoma.*', null], ['.*hematoom.*', 'en'], ['.*[Hh]ematoma.*', 'en']]) { + await same({ regex: r }, h); + } + expect((await same({ regex: '.*hematoom.*' })).length).toBeGreaterThan(0); + }); + + test('a request in Norwegian finds descriptions under either "no" or "nb"/"nn" (languageBytesFor)', async () => { + const p = await fromCache.build(op, []); + const store = p.store; + const saved = store._textLangs; + try { + store._textLangs = new Set(['en', 'no']); + expect(p._sctFilterLanguage(['nb'])).toBe('no'); + expect(p._sctFilterLanguage(['nn-NO'])).toBe('no'); + store._textLangs = new Set(['en', 'nb']); + expect(p._sctFilterLanguage(['no'])).toBe('nb'); + expect(p._sctFilterLanguage(['de', 'nb'])).toBe('nb'); + // none named: the default (nl), if the edition has it, else its language with the lowest byte + expect(p._sctFilterLanguage([])).toBe('en'); + store._textLangs = new Set(['nb', 'fr']); + expect(p._sctFilterLanguage([])).toBe('fr'); + store._textLangs = new Set(['nl', 'en']); + expect(p._sctFilterLanguage([])).toBe('nl'); + } finally { + store._textLangs = saved; + } + }); +}); diff --git a/tests/tx/sqlite-v2-sct-dialects.test.js b/tests/tx/sqlite-v2-sct-dialects.test.js new file mode 100644 index 00000000..f16e9d1a --- /dev/null +++ b/tests/tx/sqlite-v2-sct-dialects.test.js @@ -0,0 +1,261 @@ +'use strict'; + +// SNOMED CT English dialects on the engine: the designations (and so the displays) it reports +// are those of cs-snomed.js, for the test edition read as three kinds of edition: +// - the International edition (display reference set: US English) - en and en-US get the US +// preferred term, en-GB the GB one +// - a UK edition (display reference set: GB English) - en and en-GB get the GB term, en-US the US one +// - a national edition with no entry of its own (display reference sets: US then GB English) +// - an Australian edition (main: Australian, GB, then US English; the test data has no Australian +// reference set, so GB then US English) +// Each edition is built twice, from main's cache and from the RF2 files, and both files are +// compared with cs-snomed.js. +// 262797004 has the GB synonym "Subcapsular liver haematoma" stored before the US "Subcapsular +// liver hematoma"; 35566002 has "Hematoma" (US) before "Haematoma" (GB); 64572001 "Disease" is +// preferred in both. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { SnomedServicesFactory } = require('../../tx/cs/cs-snomed'); +const { SnomedImporter } = require('../../tx/importers/import-sct.module'); +const SCT_LICENSE = path.join(__dirname, '../../tx/data/snomed/license.txt'); +const { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); +const { OperationContext } = require('../../tx/operation-context'); +const { Designations } = require('../../tx/library/designations'); +const { Languages } = require('../../library/languages'); +const { TestUtilities } = require('../test-utilities'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +const EDITIONS = { intl: '31000003106', uk: '83821000000107', national: '11000146104', au: '32506021000036107' }; +let dir, op, langDefs; +const main = {}, engine = {}; + +const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-sct-dialects-')); + langDefs = await TestUtilities.loadLanguageDefinitions(); + op = new OperationContext('en', await TestUtilities.loadTranslations(langDefs)); + const snap = path.join(dir, 'Snapshot'); + mergeSnapshot(SRC, snap); + for (const [name, edition] of Object.entries(EDITIONS)) { + const cache = path.join(dir, name + '.cache'); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new SnomedImporter({ source: snap, dest: cache, edition, version: '20250909', + uri: `http://snomed.info/sct/${edition}/version/20250909`, language: 'en-US', license: SCT_LICENSE, verbose: false, overwrite: true }).run(); + } finally { quiet.mockRestore(); } + main[name] = new SnomedServicesFactory(op.i18n, cache); + await main[name].load(); + await importSnomedV2FromCache({ source: cache, dest: path.join(dir, name + '.db'), overwrite: true, normalForms: false, log: () => {} }); + engine[name] = await loadSqliteV2Factory(op.i18n, path.join(dir, name + '.db')); + await importSnomedV2({ source: snap, dest: path.join(dir, name + '-rf2.db'), edition, version: '20250909', overwrite: true, normalForms: false, log: () => {} }); + engine[name + '-rf2'] = await loadSqliteV2Factory(op.i18n, path.join(dir, name + '-rf2.db')); + } +}, 240000); + +afterAll(async () => { + for (const f of Object.values(engine)) if (f) f.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +async function designations(factory, code, significantOnly) { + const p = await factory.build(op, []); + const { context } = await p.locate(code); + const list = new Designations(langDefs); + await p.designations(context, list, significantOnly); + list.source = p; + return list; +} +const rows = (list) => list.designations.map((d) => `${d.language.code}|${d.use ? d.use.code : ''}|${d.status || ''}|${d.value}`); +async function display(factory, code, lang, significantOnly) { + const list = await designations(factory, code, significantOnly); + const pd = list.preferredDesignation(lang ? Languages.fromAcceptLanguage(lang, langDefs, false) : null); + return pd ? pd.value : null; +} + +describe('SNOMED CT English dialects (engine)', () => { + test('the three files are the editions meant: their display reference sets', () => { + const codes = (f) => f.displayRefsetIds().map((id) => f.store.conceptRows([id]).get(id).code); + expect(codes(engine.intl)).toEqual(['900000000000509007']); + expect(codes(engine.uk)).toEqual(['900000000000508004']); + expect(codes(engine.national)).toEqual(['900000000000509007', '900000000000508004']); + expect(codes(engine.au)).toEqual(['900000000000508004', '900000000000509007']); + for (const name of Object.keys(EDITIONS)) expect(codes(engine[name + '-rf2'])).toEqual(codes(engine[name])); + expect(engine.intl.store.hasRank).toBe(true); // item.rank: acceptability is read only where needed + }); + + for (const significantOnly of [true, false]) { + const op2 = significantOnly ? '$expand' : '$lookup'; + + test(op2 + ' designations: International edition - US term for en and en-US, GB term for en-GB', async () => { + for (const lang of [null, 'en', 'en-US']) { + expect(await display(engine.intl, '262797004', lang, significantOnly)).toBe('Subcapsular liver hematoma'); + expect(await display(engine.intl, '35566002', lang, significantOnly)).toBe('Hematoma'); + expect(await display(engine.intl, '64572001', lang, significantOnly)).toBe('Disease'); + } + expect(await display(engine.intl, '262797004', 'en-GB', significantOnly)).toBe('Subcapsular liver haematoma'); + expect(await display(engine.intl, '35566002', 'en-GB', significantOnly)).toBe('Haematoma'); + expect(await display(engine.intl, '64572001', 'en-GB', significantOnly)).toBe('Disease'); + expect(await display(engine.intl, '262797004', 'nl', significantOnly)).toBe('subcapsulair leverhematoom'); + }); + + test(op2 + ' designations: UK edition - GB term for en and en-GB, US term for en-US', async () => { + for (const lang of [null, 'en', 'en-GB']) { + expect(await display(engine.uk, '262797004', lang, significantOnly)).toBe('Subcapsular liver haematoma'); + expect(await display(engine.uk, '35566002', lang, significantOnly)).toBe('Haematoma'); + } + expect(await display(engine.uk, '262797004', 'en-US', significantOnly)).toBe('Subcapsular liver hematoma'); + expect(await display(engine.uk, '35566002', 'en-US', significantOnly)).toBe('Hematoma'); + }); + + // the RF2-built files on $expand only: on $lookup, the designations that no display rule orders + // (FSNs, definitions, acceptable synonyms) come in the order the importer read them, which for + // this merged test snapshot is not the order main's cache stores them in + const names = [...Object.keys(EDITIONS), ...(significantOnly ? Object.keys(EDITIONS).map((n) => n + '-rf2') : [])]; + test.each(names)(op2 + ' designations: every concept, %s, as cs-snomed.js reports them', async (name) => { + { + const codes = engine[name].store.db.prepare('SELECT code FROM concept ORDER BY id').pluck().all(); + expect(codes.length).toBeGreaterThan(2000); + let dialectTagged = 0; + for (const code of codes) { + const want = rows(await designations(main[name.replace(/-rf2$/, '')], code, significantOnly)); + const got = rows(await designations(engine[name], code, significantOnly)); + expect([name, code, got]).toEqual([name, code, want]); + if (want.some((r) => /^en-GB\|900000000000013009/.test(r) || /^en-US\|900000000000013009/.test(r))) dialectTagged++; + } + // the comparison covers concepts whose dialects differ + expect(dialectTagged).toBeGreaterThan(50); + } + }, 120000); + } + + test('$expand designations: the display, one FSN and one synonym per language, and the other dialect where it differs', async () => { + expect(rows(await designations(engine.intl, '262797004', true))).toEqual([ + 'en-US|preferredForLanguage|active|Subcapsular liver hematoma', + 'en|900000000000003001|active|Subcapsular liver hematoma (disorder)', + 'en|900000000000013009|active|Subcapsular liver hematoma', + 'nl|900000000000013009|active|subcapsulair leverhematoom', + 'en-GB|900000000000013009|active|Subcapsular liver haematoma' + ]); + }); + + test('a page read for its displays only: a UK edition reads the designations when en-US is asked for', async () => { + const ask = async (factory, header) => { + const ctx = new OperationContext(Languages.fromAcceptLanguage(header, langDefs, false), op.i18n); + const p = await factory.build(ctx, []); + const handle = await p.prefetchCodes(['262797004'], true, { displayOnly: true }); + const { context } = await p.locate('262797004', handle); + const list = new Designations(langDefs); + await p.designations(context, list, true); + list.source = p; + return list.preferredDesignation(ctx.langs).value; + }; + expect(await ask(engine.uk, 'en-US')).toBe('Subcapsular liver hematoma'); + expect(await ask(engine.uk, 'en')).toBe('Subcapsular liver haematoma'); + expect(await ask(engine.intl, 'en-US')).toBe('Subcapsular liver hematoma'); + expect(await ask(engine.intl, 'en')).toBe('Subcapsular liver hematoma'); + }); + + test('an Australian edition with no Australian reference set displays GB English, as cs-snomed.js does', async () => { + for (const f of [engine.au, engine['au-rf2'], main.au]) { + expect(await display(f, '262797004', null, true)).toBe('Subcapsular liver haematoma'); + expect(await display(f, '262797004', 'en-US', true)).toBe('Subcapsular liver hematoma'); + } + }); +}); + +// An Australian release as shipped: its own English reference set has the members, the GB and US +// reference set concepts are in the release with no members. That imports from the cache without +// --force (the empty refsets are fallbacks); an Australian refset with no members does not. +describe('display reference sets without members (Australian edition)', () => { + const AU = '32570271000036106', GB = '900000000000508004', US = '900000000000509007'; + let au, sum = {}; + const lines = (f) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean); + const file = (snap, re) => walk(snap).find((f) => re.test(path.basename(f))); + // the merged snapshot with an Australian English refset concept (is-a English language refset); + // `langRows(refset)` -> the refset id a GB / US row is moved to (null: the row is dropped) + function auSnapshot(name, langRows) { + const snap = path.join(dir, name); + mergeSnapshot(SRC, snap); + fs.appendFileSync(file(snap, /^sct2_Concept_Snapshot_/), `${AU}\t20230731\t1\t31000003106\t900000000000074008\n`); + fs.appendFileSync(file(snap, /^sct2_Description_Snapshot-en_/), + `9000001000036110\t20230731\t1\t31000003106\t${AU}\ten\t900000000000003001\tAustralian English language reference set (foundation metadata concept)\t900000000000017005\n`); + fs.appendFileSync(file(snap, /^sct2_Relationship_Snapshot_/), + `9000001000036121\t20230731\t1\t31000003106\t${AU}\t900000000000507009\t0\t116680003\t900000000000011006\t900000000000451002\n`); + const lang = file(snap, /^der2_cRefset_LanguageSnapshot-en_/); + const [head, ...rows] = lines(lang); + const out = [head]; + for (const r of rows) { + const c = r.split('\t'); + if (c[4] !== GB && c[4] !== US) { out.push(r); continue; } + const to = langRows(c[4]); + if (to) { c[4] = to; out.push(c.join('\t')); } + } + fs.writeFileSync(lang, out.join('\n') + '\n'); + return snap; + } + async function cache(snap, name) { + const dest = path.join(dir, name + '.cache'); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new SnomedImporter({ source: snap, dest, edition: EDITIONS.au, version: '20230731', + uri: `http://snomed.info/sct/${EDITIONS.au}/version/20230731`, language: 'en-US', license: SCT_LICENSE, verbose: false, overwrite: true }).run(); + } finally { quiet.mockRestore(); } + return dest; + } + const db = (name) => path.join(dir, name + '.db'); + + beforeAll(async () => { + // the GB rows become the Australian refset's; the US ones are dropped + const shipped = auSnapshot('au-shipped', (r) => (r === GB ? AU : null)); + const c = await cache(shipped, 'au-shipped'); + sum.cache = await importSnomedV2FromCache({ source: c, dest: db('au-shipped'), overwrite: true, normalForms: false, log: () => {} }); + sum.rf2 = await importSnomedV2({ source: shipped, dest: db('au-shipped-rf2'), edition: EDITIONS.au, version: '20230731', overwrite: true, normalForms: false, log: () => {} }); + au = await loadSqliteV2Factory(op.i18n, db('au-shipped')); + // the Australian refset without members, the GB and US ones as the test edition has them + sum.lostCache = await cache(auSnapshot('au-lost', (r) => r), 'au-lost'); + }, 120000); + afterAll(() => { if (au) au.store.close(); }); + + test('the shipped layout imports from the cache without --force; the empty fallbacks are warnings', async () => { + const codes = au.displayRefsetIds().map((id) => au.store.conceptRows([id]).get(id).code); + expect(codes).toEqual([AU, GB, US]); + const w = sum.cache.importer.cacheWarnings; + expect(w.filter((x) => /display language refset/.test(x)).map((x) => x.split(' ')[3]).sort()).toEqual([GB, US].sort()); + expect(await display(au, '262797004', null, true)).toBe('Subcapsular liver haematoma'); + expect(await display(au, '35566002', null, true)).toBe('Haematoma'); + }); + + test('the RF2 import of the same release reports the same fallbacks, and the same displays', () => { + expect(sum.rf2.importer.displayRefsetWarnings.map((x) => x.split(' ')[3]).sort()).toEqual([GB, US].sort()); + const read = (f) => { const d = new (require('better-sqlite3'))(f, { readonly: true }); + try { return d.prepare('SELECT code, display FROM concept ORDER BY code').all(); } finally { d.close(); } }; + expect(read(db('au-shipped-rf2'))).toEqual(read(db('au-shipped'))); + }); + + test("the edition's own refset without members stops the import unless forced", async () => { + await expect(importSnomedV2FromCache({ source: sum.lostCache, dest: db('au-lost'), overwrite: true, normalForms: false, log: () => {} })) + .rejects.toThrow(`display language refset ${AU} has no members`); + const forced = await importSnomedV2FromCache({ source: sum.lostCache, dest: db('au-lost'), overwrite: true, force: true, normalForms: false, log: () => {} }); + expect(forced.importer.cacheWarnings).toContain(`display language refset ${AU} has no members`); + }); +}); diff --git a/tests/tx/sqlite-v2-sct-ecl.test.js b/tests/tx/sqlite-v2-sct-ecl.test.js new file mode 100644 index 00000000..410a26d7 --- /dev/null +++ b/tests/tx/sqlite-v2-sct-ecl.test.js @@ -0,0 +1,120 @@ +'use strict'; + +// SNOMED CT ECL with description filters ({{ term = ... }}, dialect, language, type, active; 1.0.4 +// #401 narrows the term filters by the text index) and compound ECL: the same concepts as +// cs-snomed.js, in its order (_eclIntersect: the right side's; _eclUnion: the left's, then the +// right's; _eclMinus: the left's; refinements and {{ }} filters: their base's; << X: X first; < fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +async function mainCache(snap, dest, language) { + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new SnomedImporter({ source: snap, dest, edition: '31000003106', version: '20250909', + uri: 'http://snomed.info/sct/31000003106/version/20250909', language, license: SCT_LICENSE, verbose: false, overwrite: true }).run(); + } finally { quiet.mockRestore(); } +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-sct-ecl-')); + const langDefs = await TestUtilities.loadLanguageDefinitions(); + op = new OperationContext('en', await TestUtilities.loadTranslations(langDefs)); + const snap = path.join(dir, 'Snapshot'); + mergeSnapshot(SRC, snap); + await mainCache(snap, path.join(dir, 't.cache'), 'en-US'); + main = new SnomedServicesFactory(op.i18n, path.join(dir, 't.cache')); + await main.load(); + await importSnomedV2FromCache({ source: path.join(dir, 't.cache'), dest: path.join(dir, 't.db'), overwrite: true, normalForms: false, log: () => {} }); + engine = await loadSqliteV2Factory(op.i18n, path.join(dir, 't.db')); +}, 180000); + +afterAll(async () => { + if (engine) engine.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +/** the codes an ECL filter selects, in the provider's order (as expand.js walks the filter set) */ +async function ecl(factory, text) { + const p = await factory.build(op, []); + const prep = await p.getPrepContext(true, null); + await p.filter(prep, true, 'constraint', '=', text); + const sets = await p.executeFilters(prep); + const out = []; + while (await p.filterMore(prep, sets[0])) out.push(await p.code(await p.filterConcept(prep, sets[0]))); + return out; +} + +async function same(text) { + const want = await ecl(main, text); + expect([text, await ecl(engine, text)]).toEqual([text, want]); + return want; +} + +describe('SNOMED CT ECL description filters and compound ECL, as cs-snomed.js', () => { + test('description filters: term, dialect, language, type, active', async () => { + for (const e of ['<< 159033005 {{ term = "dietitian" }}', '<< 159033005 {{ term = "renal diet" }}', '<< 159033005 {{ term = "DIET" }}', + '<< 159033005 {{ term = ("renal" "liver") }}', '<< 159033005 {{ term = wild:"*dietitian" }}', '<< 159033005 {{ term != "renal" }}', + '<< 159033005 {{ term = "a" }}', '<< 159033005 {{ term = "dietitian", dialect = en-us }}', '<< 159033005 {{ dialect = en-us (prefer) }}', + '<< 159033005 {{ dialect = en-gb }}', '<< 159033005 {{ term = "dietitian", language = en }}', '<< 159033005 {{ term = "dietitian", type = fsn }}', + '<< 159033005 {{ term = "dietitian", active = true }}', '<< 159033005 {{ term = "dietitian", active = false }}', + '<< 159033005 {{ D term = "dietitian" }} {{ D term = "renal" }}', '<< 138875005 {{ term = "dietitian" }}']) await same(e); + expect((await same('<< 159033005 {{ term = "dietitian", dialect = en-us }}')).length).toBeGreaterThan(1); + expect((await same('<< 159033005 {{ term = "dietitian" }}'))[0]).toBe('159033005'); + }); + + test('compound ECL in cs-snomed.js\'s order', async () => { + for (const e of ['<< 309413008 OR << 159033005', '<< 159033005 OR << 309413008', '<< 159033005 AND << 309413008', '<< 309413008 AND << 159033005', + '<< 159033005 AND *', '* AND << 159033005', '<< 159033005 MINUS << 309413008', '< { + test('evaluated by main\'s (async) ECL first, then compiled: the same codes as cs-snomed.js', async () => { + const texts = ['< 404684003 : { [1..1] 363698007 = << 123037004 }', '< 404684003 : { [0..1] 363698007 = * }']; + for (const text of texts) { + const want = await same(text); + expect([text, want.length > 0]).toEqual([text, true]); + // the engine did not evaluate it: main's result is kept for the file + expect(engine.store._mainEcl && engine.store._mainEcl.has(text)).toBe(true); + } + }); + + test('an unknown concept in such ECL is reported as before (a filter error, at compile)', async () => { + const p = await engine.build(op, []); + const prep = await p.getPrepContext(true, null); + await expect(p.filter(prep, true, 'constraint', '=', '< 404684003 : { [1..1] 363698007 = << 999999999999 }')).rejects.toThrow(); + }); +}); diff --git a/tests/tx/sqlite-v2-sct-from-cache.test.js b/tests/tx/sqlite-v2-sct-from-cache.test.js new file mode 100644 index 00000000..5b5cf328 --- /dev/null +++ b/tests/tx/sqlite-v2-sct-from-cache.test.js @@ -0,0 +1,198 @@ +'use strict'; + +// Reverse loader (FHIRsmith SNOMED cache -> sqlite-v2): build a cache from the test edition RF2 in +// tx/data/snomed with main's cache importer, reverse-load it, and compare with the RF2 v2 import of +// the same files. Every fact and every stored set must agree, except what the cache cannot carry: +// here, refset fields naming concepts that are not in the edition. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { SnomedImporter } = require('../../tx/importers/import-sct.module'); +// main's importer requires the license the edition is distributed under (cache format 21) +const SCT_LICENSE = path.join(__dirname, '../../tx/data/snomed/license.txt'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); +const { readCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { SnomedFileReader } = require('../../tx/sct/structures'); +const { diffFiles } = require('../../tx/importers/sqlite-v2/diff'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +let dir, report, cacheSummary, olderSummary, olderReport; + +function walk(d) { + return fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +} + +// The fixture is split by module (INT, TEST1000003, LO1010000); the RF2 v2 importer reads one +// concept / relationship file, so merge each kind into one Snapshot file first. +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt')) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + const lines = files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)); + fs.writeFileSync(out, lines.join('\n') + '\n'); + } +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sct-from-cache-')); + const snap = path.join(dir, 'Snapshot'); + mergeSnapshot(SRC, snap); + const quiet = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + await new SnomedImporter({ source: snap, dest: path.join(dir, 't.cache'), edition: '31000003106', version: '20250909', + uri: 'http://snomed.info/sct/31000003106/version/20250909', language: 'en-US', license: SCT_LICENSE, verbose: false, overwrite: true }).run(); + } finally { quiet.mockRestore(); } + await importSnomedV2({ source: snap, dest: path.join(dir, 'rf2.db'), edition: '31000003106', version: '20250909', overwrite: true, log: () => {} }); + cacheSummary = await importSnomedV2FromCache({ source: path.join(dir, 't.cache'), dest: path.join(dir, 'rev.db'), overwrite: true, log: () => {} }); + report = diffFiles(path.join(dir, 'rf2.db'), path.join(dir, 'rev.db'), { examples: 50 }); + // the same edition in cache format 20 (main's server reads only 21; this importer reads both) + writeFormat20(await new SnomedFileReader(path.join(dir, 't.cache')).loadSnomedData(), path.join(dir, 't20.cache')); + olderSummary = await importSnomedV2FromCache({ source: path.join(dir, 't20.cache'), dest: path.join(dir, 'rev20.db'), overwrite: true, log: () => {} }); + olderReport = diffFiles(path.join(dir, 'rev.db'), path.join(dir, 'rev20.db'), { examples: 50 }); +}, 120000); + +/** + * A cache in format 20's layout (tx/sct/structures.js before 1.0.5), from a format-21 cache's + * sections: no license or text indexes; empty words and stems sections (nothing read them) + */ +function writeFormat20(d, file) { + const out = []; + const str = (t) => { const b = Buffer.from(t, 'utf8'); out.push(Buffer.from([6, b.length]), b); }; + const int = (n) => { const b = Buffer.alloc(5); b.writeUInt8(4, 0); b.writeInt32LE(n, 1); out.push(b); }; + const bytes = (b) => { int(b.length); out.push(Buffer.from(b)); }; + const u64 = (n) => { const b = Buffer.alloc(8); b.writeBigUInt64LE(BigInt(n)); out.push(b); }; + str('20'); str(d.versionUri); str(d.versionDate); + bytes(d.strings); bytes(d.refs); bytes(d.desc); bytes(Buffer.alloc(0)); bytes(Buffer.alloc(0)); + bytes(d.concept); bytes(d.rel); bytes(d.refSetIndex); bytes(d.refSetMembers); bytes(d.descRef); + int(d.isAIndex); + int(d.inactiveRoots.length); d.inactiveRoots.forEach(u64); + int(d.activeRoots.length); d.activeRoots.forEach(u64); + int(d.defaultLanguage); + bytes(Buffer.from(JSON.stringify(d.identifiers))); + bytes(Buffer.from(JSON.stringify(d.concreteValues))); + fs.writeFileSync(file, Buffer.concat(out)); +} + +afterAll(() => { if (dir) fs.rmSync(dir, { recursive: true, force: true }); }); + +test('the current cache format carries everything else', () => { + expect(cacheSummary.importer.cacheVersion).toBe('21'); + expect(cacheSummary.importer.cacheWarnings).toEqual([]); +}); + +test('an older cache format (20, which main\'s server no longer reads) gives the same file', async () => { + expect(SnomedFileReader.isCurrent(path.join(dir, 't20.cache'))).toBe(false); + await expect(new SnomedFileReader(path.join(dir, 't20.cache')).loadSnomedData()).rejects.toThrow(/only reads format 21/); + const d = await readCache(path.join(dir, 't20.cache')); + expect([d.cacheVersion, d.hasLangs, d.concreteValues !== null]).toEqual(['20', true, true]); + expect(olderSummary.importer.cacheVersion).toBe('20'); + expect(olderSummary.importer.cacheWarnings).toEqual([]); + for (const [f, x] of Object.entries(olderReport.facts)) expect([f, x.onlyA, x.onlyB]).toEqual([f, 0, 0]); + expect(olderReport.sets.identicalNumbering).toBe(true); + for (const [kind, x] of Object.entries(olderReport.sets.byKind)) expect([kind, x.differ, x.onlyA, x.onlyB]).toEqual([kind, 0, 0, 0]); +}); + +test('a cache format this importer does not know is refused', async () => { + const bad = path.join(dir, 'bad.cache'); + fs.writeFileSync(bad, Buffer.concat([Buffer.from([6, 2]), Buffer.from('15'), Buffer.alloc(16)])); + await expect(readCache(bad)).rejects.toThrow(/format 15 is not one this importer reads/); +}); + +test('concepts, items, the catalog, links, literals and identifiers are identical', () => { + for (const f of ['concept', 'item', 'item_use', 'property', 'property_member', 'link', 'literal', 'identifier']) { + expect([f, report.facts[f].onlyA, report.facts[f].onlyB]).toEqual([f, 0, 0]); + } +}); + +test('numbering and every stored set are identical', () => { + expect(report.sets.identicalNumbering).toBe(true); + for (const [kind, s] of Object.entries(report.sets.byKind)) { + expect([kind, s.differ, s.onlyA, s.onlyB]).toEqual([kind, 0, 0, 0]); + } +}); + +test('records (refset rows, language refsets included) differ only where a field names a concept missing from the edition', () => { + const r = report.facts.record; + expect(r.onlyA).toBe(r.onlyB); + // [relation, subject, target, active, fields] + const a = new Map(r.examplesA.map((x) => [`${x[0]}|${x[1]}`, x])); + for (const x of r.examplesB) { + const ya = a.get(`${x[0]}|${x[1]}`); + expect(ya).toBeDefined(); + expect([x[2], x[3]]).toEqual([ya[2], ya[3]]); + x[4].forEach((v, i) => { if (v !== ya[4][i]) expect(v === '' || v === null).toBe(true); }); + } + expect(cacheSummary.importer.unknownFieldValues).toBe(r.onlyB); +}); + +test('link order: the cache\'s record order gives the same parents and children order as the RF2 rows', () => { + const Database = require('better-sqlite3'); + const order = (file) => { + const db = new Database(file, { readonly: true }); + try { + const h = db.prepare('SELECT id FROM property WHERE subsumption = 1').pluck().get(); + const children = db.prepare(`SELECT a.code k, group_concat(b.code) v FROM (SELECT * FROM ix_in WHERE active = 1 AND group_id = 0 + AND property_id = ? ORDER BY target_id, seq) l JOIN concept a ON a.id = l.target_id JOIN concept b ON b.id = l.subject_id + GROUP BY a.code ORDER BY a.code`).all(h); + const parents = db.prepare(`SELECT a.code k, group_concat(b.code) v FROM (SELECT * FROM link WHERE active = 1 AND group_id = 0 + AND property_id = ? ORDER BY subject_id, seq) l JOIN concept a ON a.id = l.subject_id JOIN concept b ON b.id = l.target_id + GROUP BY a.code ORDER BY a.code`).all(h); + return { children, parents }; + } finally { db.close(); } + }; + const a = order(path.join(dir, 'rf2.db')); + expect(a.children.length).toBeGreaterThan(100); + expect(order(path.join(dir, 'rev.db'))).toEqual(a); +}); + +describe('the system order (ix_order, tx/sqlite-v2/orders.js)', () => { + const Database = require('better-sqlite3'); + const { computeOrder, storedOrder } = require('../../tx/sqlite-v2/orders'); + const { openStore } = require('../../tx/sqlite-v2/store'); + const arrays = (file) => { + const db = new Database(file, { readonly: true }); + try { + return db.prepare("SELECT name, hex(group_concat(data, x'') ) FROM (SELECT name, data FROM ix_order ORDER BY name, block) GROUP BY name ORDER BY name").raw().all() + .concat(db.prepare("SELECT key, value FROM meta WHERE key LIKE 'ix.ix_order.%' ORDER BY key").raw().all()); + } finally { db.close(); } + }; + + test('both importers store the same orders, equal to those computed from the facts', () => { + const a = arrays(path.join(dir, 'rf2.db')); + expect(a.map((r) => r[0])).toEqual(['ids', 'rank', 'walk', 'ix.ix_order.walk.reached']); + expect(arrays(path.join(dir, 'rev.db'))).toEqual(a); + const db = new Database(path.join(dir, 'rf2.db'), { readonly: true }); + try { + const n = db.prepare('SELECT concept_count FROM code_system WHERE served = 1').pluck().get(); + const want = computeOrder(db, 'snomed', n); + expect([want.rank.length, want.ids.length, want.walk.length]).toEqual([n + 1, n + 1, n]); + expect(Number(a.find((r) => r[0] === 'ix.ix_order.walk.reached')[1])).toBe(want.walk.reached); + expect(want.walk.reached).toBeGreaterThan(n / 2); + expect(want.walk.reached).toBeLessThan(n); + for (const r of a.slice(0, 3)) expect(r[1]).toBe(Buffer.from(want[r[0]].buffer).toString('hex').toUpperCase()); + } finally { db.close(); } + }); + + test('read lazily: no array until used', () => { + const s1 = openStore(path.join(dir, 'rf2.db'), { unregistered: true }); + try { + const stored = storedOrder(s1, s1.behaviour.expansionOrder); + expect(stored.loadedBytes()).toBe(0); + expect([stored.selfFirst, stored.hasWalk]).toEqual([true, true]); + const n = stored.rank.length; + expect(stored.loadedBytes()).toBe(stored.rank.byteLength); + expect(stored.ids.length).toBe(n); + expect(stored.walk.reached).toBeGreaterThan(0); + } finally { s1.close(); } + }); +}); diff --git a/tests/tx/sqlite-v2-sct-lookup.test.js b/tests/tx/sqlite-v2-sct-lookup.test.js new file mode 100644 index 00000000..5788fe00 --- /dev/null +++ b/tests/tx/sqlite-v2-sct-lookup.test.js @@ -0,0 +1,147 @@ +'use strict'; + +// SNOMED CT on sqlite-v2: $lookup properties and implicit value set urls as main reports them +// (cs-snomed.js after #331), and main's ECL over the file seeing active relationships only. +// Test edition: the RF2 in tx/data/snomed. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); +const { SnomedV2Factory } = require('../../tx/sqlite-v2/snomed'); +const { OperationContext } = require('../../tx/operation-context'); +const { TestUtilities } = require('../test-utilities'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +let dir, factory, op; + +const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-sct-lookup-')); + mergeSnapshot(SRC, path.join(dir, 'Snapshot')); + await importSnomedV2({ source: path.join(dir, 'Snapshot'), dest: path.join(dir, 'test.db'), edition: '31000003106', version: '20250909', + versionUri: 'http://snomed.info/xsct/31000003106/version/20250909', overwrite: true, log: () => {} }); + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + factory = new SnomedV2Factory(op.i18n, path.join(dir, 'test.db')); + await factory.load(); +}, 120000); + +afterAll(() => { + if (factory) factory.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + + +async function lookup(code, props) { + const p = await factory.build(op, []); + const r = await p.locate(code); + const params = []; + await p.extendLookup(r.context, props, params); + const out = {}; + for (const x of params) { + const c = x.part.find((pp) => pp.name === 'code').valueCode; + const v = x.part.find((pp) => pp.name === 'value'); + (out[c] = out[c] || []).push(v.valueCode ?? v.valueString ?? v.valueBoolean ?? v.valueInteger ?? v.valueDecimal ?? v.valueDateTime); + } + return out; +} + +describe('sqlite-v2 SNOMED CT $lookup and implicit value sets, as main', () => { + test('moduleId by default; module asked for by name is answered as moduleId', async () => { + const all = await lookup('40468003', []); + expect(all.moduleId).toEqual(['900000000000207008']); + expect(all.module).toBeUndefined(); + expect(all.semanticTag).toBeUndefined(); + expect(all.normalForm).toBeUndefined(); + expect(await lookup('40468003', ['module'])).toEqual({ moduleId: ['900000000000207008'] }); + }); + + test('property=* adds sufficientlyDefined and semanticTag, not the normal forms', async () => { + const all = await lookup('40468003', ['*']); + expect(all.sufficientlyDefined).toEqual([true]); + expect(all.semanticTag).toEqual(['disorder']); + expect(all.normalForm).toBeUndefined(); + }); + + test('the normal forms, by name', async () => { + const nf = await lookup('40468003', ['normalForm', 'normalFormTerse']); + expect(nf.normalFormTerse).toEqual(['64572001:{116676008=409774005,246075003=32452004,363698007=10200004,370135005=441862004}']); + expect(nf.normalForm[0]).toMatch(/^64572001\|Disease\|:\{116676008\|Associated morphology\|=409774005\|/); + }); + + test('implicit value set urls: generic, edition (sct or the version\'s own base) and version forms', async () => { + expect(factory.implicitValueSetForm('http://snomed.info/sct?fhir_vs=isa/16763008').form).toBe('generic'); + expect(factory.implicitValueSetForm('http://snomed.info/sct/31000003106?fhir_vs=isa/16763008').form).toBe('edition'); + expect(factory.implicitValueSetForm('http://snomed.info/xsct/31000003106?fhir_vs=isa/16763008').form).toBe('edition'); + expect(factory.implicitValueSetForm('http://snomed.info/sct/31000003106/version/20250909?fhir_vs').form).toBe('version'); + expect(factory.implicitValueSetForm('http://snomed.info/sct/900000000000207008?fhir_vs')).toBeNull(); + const vs = await factory.buildKnownValueSet('http://snomed.info/sct/31000003106?fhir_vs=isa/16763008', null); + expect(vs.compose.include[0].version).toBe('http://snomed.info/xsct/31000003106/version/20250909'); + const generic = await factory.buildKnownValueSet('http://snomed.info/sct?fhir_vs=isa/16763008', null); + expect(generic.compose.include[0].version).toBeUndefined(); + }); + + test('$expand properties: no property definitions (no uris), and each code\'s properties in main\'s order', async () => { + // main's SNOMED CT provider declares no property definitions, so expansion.property has codes + // and no uris. The HL7 tester sorts expansion.property by uri (absent first), then code: a + // uri here would order the definitions differently from the expected response + // (snomed-expand-property) + const p = await factory.build(op, []); + expect(p.propertyDefinitions()).toBeNull(); + const r = await p.locate('51292008'); + const props = await p.properties(r.context, ['moduleId', 'sufficientlyDefined', '363698007']); + expect(props.map((x) => x.code)).toEqual(['moduleId', 'sufficientlyDefined', '363698007', '363698007']); + expect(props.filter((x) => x.code === '363698007').map((x) => x.valueCode)).toEqual(['10200004', '64033007']); + }); + + test('main\'s ECL over the file: refinements see the relationships', async () => { + const { evaluateEcl } = require('../../tx/sqlite-v2/sct-main-ecl'); + const bm = await evaluateEcl(factory.store, '< 64572001 : 363698007 = << 10200004', null); + expect(bm.size).toBeGreaterThan(0); + }); +}); + +describe('sqlite-v2 SNOMED CT designation rank', () => { + test('the stored rank orders designations as acceptability does (files without it)', async () => { + const { Designations } = require('../../tx/library/designations'); + const S = factory.store; + expect(S.hasRank).toBe(true); + const ids = S.db.prepare('SELECT DISTINCT concept_id FROM item ORDER BY concept_id').pluck().all(); + const run = async (significant) => { + const out = []; + for (const id of ids) { + const p = await factory.build(op, []); + const r = await p.locate(S.db.prepare('SELECT code FROM concept WHERE id = ?').pluck().get(id)); + const d = new Designations(op.i18n.languageDefinitions); + await p.designations(r.context, d, significant); + out.push(d.designations.map((x) => [x.language && x.language.code, x.use && x.use.code, x.value])); + } + return out; + }; + for (const significant of [false, true]) { + const ranked = await run(significant); + S.hasRank = false; // as a v4 file: acceptability per designation + try { + expect(await run(significant)).toEqual(ranked); + } finally { + S.hasRank = true; + } + } + }); +}); diff --git a/tests/tx/sqlite-v2-sct-parity-http.test.js b/tests/tx/sqlite-v2-sct-parity-http.test.js new file mode 100644 index 00000000..319dd83e --- /dev/null +++ b/tests/tx/sqlite-v2-sct-parity-http.test.js @@ -0,0 +1,213 @@ +'use strict'; + +// SNOMED CT on sqlite-v2 against main's provider (tx/cs/cs-snomed.js) through the real router, +// both over the repo's SNOMED CT test cache (tx/data/snomed-testing.cache): code spellings main +// reads as a concept id (cs-snomed.js stringToIdOrZero: BigInt), a text filter of digits only, +// and an unknown concept in a `concept in` / `not-in` filter. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const request = require('supertest'); +const { getTestApp, getTxModule, shutdownTestApp } = require('./setup'); +const { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { SnomedServicesFactory } = require('../../tx/cs/cs-snomed'); +const { SnomedV2Factory } = require('../../tx/sqlite-v2/snomed'); + +const SCT = 'http://snomed.info/sct'; +const CACHE = path.resolve(__dirname, '../../tx/data/snomed-testing.cache'); +let app, tx, dir, v2, classic; + +function use(f) { + const p = tx.endpoints[0].provider; + for (const key of [...p.codeSystemFactories.keys()]) if (key === SCT || key.startsWith(SCT + '|')) p.codeSystemFactories.delete(key); + p.codeSystemFactories.set(SCT, f); + p.codeSystemFactories.set(SCT + '|' + f.version(), f); + for (const e of tx.endpoints) e.expansionCache.clearAll(); +} + +const issuesOf = (body) => (body.issue || []).map((i) => [i.severity, i.code, i.details && i.details.text]); + +async function call(method, url, body) { + const res = method === 'get' ? await request(app).get(url) : await request(app).post(url).send(body); + return res; +} + +async function both(fn) { + use(v2); + const a = await fn(); + use(classic); + const b = await fn(); + use(v2); + return { v2: a, main: b }; +} + +const param = (body, name) => { + const p = (body.parameter || []).find((x) => x.name === name); + return p ? (p.valueString ?? p.valueBoolean ?? p.valueCode ?? p.valueUri) : undefined; +}; + +beforeAll(async () => { + app = await getTestApp(); + tx = getTxModule(); + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-sct-http-')); + await importSnomedV2FromCache({ source: CACHE, dest: path.join(dir, 'sct.db'), overwrite: true, force: true, normalForms: false, log: () => {} }); + v2 = new SnomedV2Factory(tx.i18n, path.join(dir, 'sct.db')); + await v2.load(); + classic = new SnomedServicesFactory(tx.i18n, CACHE); + await classic.load(); + use(v2); +}, 180000); + +afterAll(async () => { + await shutdownTestApp(); + if (v2 && v2.store) v2.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +describe('SNOMED CT code spellings, as main reads them (BigInt)', () => { + // 22298006 |Myocardial infarction|; 0x1543d96 is 22298006 in hexadecimal + test.each(['22298006', '022298006', ' 22298006 ', '+22298006', '0x1543d96', '-22298006', '0', '22298007', 'abc'])('$lookup %j', async (code) => { + const r = await both(async () => { + const res = await call('get', `/tx/r5/CodeSystem/$lookup?system=${encodeURIComponent(SCT)}&code=${encodeURIComponent(code)}`); + return { status: res.status, display: param(res.body, 'display'), issues: issuesOf(res.body) }; + }); + expect(r.v2).toEqual(r.main); + }); + + test.each(['+22298006', '0x1543d96', '-22298006'])('$validate-code %j', async (code) => { + const r = await both(async () => { + const res = await call('get', `/tx/r5/CodeSystem/$validate-code?url=${encodeURIComponent(SCT)}&code=${encodeURIComponent(code)}`); + return { status: res.status, result: param(res.body, 'result'), display: param(res.body, 'display'), message: param(res.body, 'message') }; + }); + expect(r.v2).toEqual(r.main); + }); +}); + +describe('SNOMED CT text filter of digits only', () => { + // filter=0 / 00 with count=0: main counts a concept again for each identifier length its range + // covers (#addCodeMatches: the ranges for a prefix of zeros nest), so its total is inflated; v2 + // counts each concept once. A known difference: the codes listed are the same + test.each([['0', 0], ['00', 0]])('filter=%s count=%i: main\'s total counts repeats, v2\'s does not', async (filter, count) => { + const r = await both(async () => { + const res = await call('get', `/tx/r5/ValueSet/$expand?url=${encodeURIComponent(SCT + '?fhir_vs')}&filter=${filter}&count=${count}`); + return (res.body.expansion || {}).total; + }); + use(v2); + const all = await call('get', `/tx/r5/ValueSet/$expand?url=${encodeURIComponent(SCT + '?fhir_vs')}&filter=${filter}&count=100000`); + expect(r.v2).toBe((all.body.expansion.contains || []).length); + expect(r.main).toBeGreaterThan(r.v2); + }); + + test.each([['0', 20], ['0', 100000], ['2', 0], ['2229', 20], ['22298006', 0]])('filter=%s count=%i', async (filter, count) => { + const r = await both(async () => { + const res = await call('get', `/tx/r5/ValueSet/$expand?url=${encodeURIComponent(SCT + '?fhir_vs')}&filter=${filter}&count=${count}`); + const e = res.body.expansion || {}; + return { status: res.status, total: e.total, codes: (e.contains || []).map((c) => c.code), issues: issuesOf(res.body) }; + }); + expect(r.v2).toEqual(r.main); + }); +}); + +describe('SNOMED CT description id as a code: an unknown code, as main', () => { + // 183388015 is a description of 118696008 |Procedure on mediastinum| in the test cache + const DESCRIPTION = '183388015'; + const vsBody = { resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: SCT }] } } }, + { name: 'coding', valueCoding: { system: SCT, code: DESCRIPTION } }] }; + test.each([ + ['$lookup', 'get', `/tx/r5/CodeSystem/$lookup?system=${encodeURIComponent(SCT)}&code=${DESCRIPTION}`, null], + ['CodeSystem/$validate-code', 'get', `/tx/r5/CodeSystem/$validate-code?url=${encodeURIComponent(SCT)}&code=${DESCRIPTION}`, null], + ['ValueSet/$validate-code', 'post', '/tx/r5/ValueSet/$validate-code', vsBody], + ])('%s', async (name, method, url, body) => { // every row has a body (null for a GET): jest passes done as a 4th argument otherwise + const r = await both(async () => { + const res = await call(method, url, body); + return { status: res.status, result: param(res.body, 'result'), message: param(res.body, 'message'), issues: issuesOf(res.body), + oo: (res.body.parameter || []).filter((p) => p.resource && p.resource.resourceType === 'OperationOutcome').flatMap((p) => issuesOf(p.resource)) }; + }); + expect(r.v2).toEqual(r.main); + expect(JSON.stringify(r.v2)).not.toContain('description id'); + }); +}); + +describe('SNOMED CT concept in / not-in with an unknown concept', () => { + // in: expand.js reports an unknown concept and skips the include (filterConceptCodes, since + // main 4e99d163); not-in: cs-snomed.js doesn't have it (SNOMED_CONCEPT_FILTER_OPS), a 422 + test.each([['in', '22298006,99999999999'], ['in', '22298006, 22298007'], ['not-in', '22298006,99999999999'], ['not-in', '22298006']])('concept %s %s', async (op, value) => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: SCT, filter: [{ property: 'concept', op, value }] }] } }; + const r = await both(async () => { + const res = await call('post', '/tx/r5/ValueSet/$expand', { resourceType: 'Parameters', parameter: [{ name: 'valueSet', resource: vs }, { name: 'count', valueInteger: 5 }] }); + const e = res.body.expansion || {}; + const oo = (res.body.contained || []).filter((c) => c.resourceType === 'OperationOutcome').flatMap((c) => issuesOf(c)); + return { status: res.status, total: e.total, codes: (e.contains || []).map((c) => c.code), issues: issuesOf(res.body), oo }; + }); + expect(r.v2).toEqual(r.main); + }); +}); + +describe('SNOMED CT filter properties and operators: accepted and refused as main', () => { + // 235856003 |Disease of liver| (41 children in the test cache), 64572001 |Disease|, 10200004 |Liver structure| + const props = ['concept', 'code', 'inactive', 'moduleId', 'constraint', 'expressions', 'display', 'parent', 'child', '116680003', '363698007', 'mapped:30051010000102', 'nonsense']; + const ops = ['=', 'in', 'not-in', 'is-a', 'descendent-of', 'child-of', 'generalizes', 'descendent-leaf', 'is-not-a', 'regex', 'exists']; + const valueFor = (prop, op) => { + if (op === 'exists') return 'true'; + if (prop === 'inactive' || prop === 'expressions') return 'false'; + if (prop === 'constraint') return '<< 235856003'; + if (prop === 'display') return op === 'regex' ? 'Disease of.*' : 'Disease of liver'; + if (prop === 'moduleId') return '900000000000207008'; + if (prop === '363698007') return op === 'in' || op === 'not-in' ? '10200004,1340143004' : '10200004'; + if (op === 'regex') return '2358.*'; + if (op === 'in' || op === 'not-in') return '235856003,64572001'; + return '235856003'; + }; + // known differences, listed in the PR (not compared here): the order of `concept in` (main: the + // list's order; v2: by id) and `generalizes` (main: its ancestor walk; v2: by id); `expressions` + // as the only filter (main: no codes; v2: every concept); `116680003 = X` (main: one concept; v2: + // none); an unknown concept in is-not-a (main: 500; v2: 400) + const KNOWN = new Set(['concept in', 'code in', 'concept generalizes', 'code generalizes', 'expressions =', '116680003 =']); + const cases = [...props.flatMap((p) => ops.map((o) => [p, o, valueFor(p, o)])), ['expressions', '=', 'true'], ['inactive', '=', 'true'], + ['concept', '=', '22298006']].filter(([p, o]) => !KNOWN.has(p + ' ' + o)); + test.each(cases)('%s %s %s', async (property, op, value) => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: SCT, filter: [{ property, op, value }] }] } }; + const r = await both(async () => { + const res = await call('post', '/tx/r5/ValueSet/$expand', { resourceType: 'Parameters', parameter: [{ name: 'valueSet', resource: vs }, { name: 'count', valueInteger: 10 }] }); + const e = res.body.expansion || {}; + return { status: res.status, total: e.total, codes: (e.contains || []).map((c) => c.code), issues: issuesOf(res.body) }; + }); + expect(r.v2).toEqual(r.main); + }); +}); + +describe('SNOMED CT closedness of unions and excludes, as main', () => { + // main decides one include and exclude at a time (expand.js includeCodes / excludeCodes): an + // include of the whole system, or an include or exclude whose filters are not closed + // (cs-snomed.js filtersNotClosed: none of them `expressions = false`), makes the expansion + // unclosed; one include with `expressions = false` does not close a union + // 235856003 |Disease of liver|, 10200004 |Liver structure|, 192008 |Congenital syphilitic hepatomegaly| (a disease of liver) + const E = { property: 'expressions', op: '=', value: 'false' }; + const isa = (code, closed) => ({ system: SCT, filter: [{ property: 'concept', op: 'is-a', value: code }, ...(closed ? [E] : [])] }); + const cases = [ + ['is-a+E', [isa('235856003', true)], [], false], + ['is-a', [isa('235856003', false)], [], true], + ['is-a+E, is-a+E', [isa('235856003', true), isa('10200004', true)], [], false], + ['is-a+E, is-a', [isa('235856003', true), isa('10200004', false)], [], true], + ['is-a, is-a+E', [isa('235856003', false), isa('10200004', true)], [], true], + ['is-a+E, whole system', [isa('235856003', true), { system: SCT }], [], true], + ['is-a+E exclude is-a', [isa('235856003', true)], [isa('192008', false)], true], + ['is-a+E exclude is-a+E', [isa('235856003', true)], [isa('192008', true)], false], + ['is-a+E, is-a+E exclude is-a', [isa('235856003', true), isa('10200004', true)], [isa('192008', false)], true], + ]; + test.each(cases)('%s', async (name, include, exclude, unclosed) => { + const compose = exclude.length ? { include, exclude } : { include }; + const vs = { resourceType: 'ValueSet', status: 'active', compose }; + const r = await both(async () => { + const res = await call('post', '/tx/r5/ValueSet/$expand', { resourceType: 'Parameters', parameter: [{ name: 'valueSet', resource: vs }, { name: 'count', valueInteger: 10 }] }); + const ext = (res.body.expansion || {}).extension || []; + return { status: res.status, unclosed: ext.some((e) => e.url.endsWith('valueset-unclosed') && e.valueBoolean), + reasons: ext.filter((e) => e.url.endsWith('valueset-unclosed-reason')).map((e) => e.valueString) }; + }); + expect(r.v2).toEqual(r.main); + expect(r.v2.status).toBe(200); + expect(r.v2.unclosed).toBe(unclosed); + }); +}); diff --git a/tests/tx/sqlite-v2-sct-postcoord.test.js b/tests/tx/sqlite-v2-sct-postcoord.test.js new file mode 100644 index 00000000..87ff5d36 --- /dev/null +++ b/tests/tx/sqlite-v2-sct-postcoord.test.js @@ -0,0 +1,176 @@ +'use strict'; + +// SNOMED CT on sqlite-v2: post-coordination (tx/sqlite-v2/sct-native.js) - an expression is located, +// rendered, checked against the MRCM and subsumed as main does, from the file - and ECL the engine +// refuses, run by main's ECL over the file (tx/sqlite-v2/sct-main-ecl.js). Test edition: the RF2 in tx/data/snomed. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); +const { SnomedV2Factory } = require('../../tx/sqlite-v2/snomed'); +const { OperationContext } = require('../../tx/operation-context'); +const { TestUtilities } = require('../test-utilities'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +let dir, factory, op; + +const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); +function mergeSnapshot(src, dst) { + const groups = new Map(); + for (const f of walk(src)) { + if (!f.endsWith('.txt') || /Readme/i.test(f)) continue; + const rel = path.relative(src, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(dst, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-sct-postcoord-')); + mergeSnapshot(SRC, path.join(dir, 'Snapshot')); + await importSnomedV2({ source: path.join(dir, 'Snapshot'), dest: path.join(dir, 'test.db'), edition: '31000003106', version: '20250909', + versionUri: 'http://snomed.info/xsct/31000003106/version/20250909', overwrite: true, log: () => {} }); + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + factory = new SnomedV2Factory(op.i18n, path.join(dir, 'test.db')); + await factory.load(); +}, 120000); + +afterAll(() => { + if (factory) factory.store.close(); + if (dir) fs.rmSync(dir, { recursive: true, force: true }); +}); + +describe('sqlite-v2 SNOMED CT post-coordination (native) and ECL fallback', () => { + test('an expression is located and displayed as main renders it', async () => { + const p = await factory.build(op, []); + const r = await p.locate('128241005:{363698007=181268008}'); + expect(r.context).toBeTruthy(); + expect(await p.display(r.context)).toBe('128241005|Inflammatory disease of liver|:{363698007|Finding site|=181268008|Entire liver|}'); + }); + + test('a refinement never breaks a stated is-a; plain concepts still use the engine', async () => { + const p = await factory.build(op, []); + expect(await p.subsumesTest('40468003:{363698007=181268008}', '3738000')).toBe('subsumed-by'); + expect(await p.subsumesTest('3738000', '40468003')).toBe('subsumes'); + }); + + test('the MRCM is applied: an attribute outside its domain is reported', async () => { + const p = await factory.build(op, []); + const r = await p.locate('367430006:{42752001=789750003}'); + expect(r.context).toBeNull(); + expect(r.message).toMatch(/does not allow the attribute 42752001 \|Due to\| on 367430006/); + }); + + test('ECL the engine does not evaluate itself is evaluated by main over the file', async () => { + const p = await factory.build(op, []); + const ids = async (ecl) => { + const prep = await p.getPrepContext(true); + await p.filter(prep, true, 'constraint', '=', ecl); + const [set] = await p.executeFilters(prep); + return set.bm.size; + }; + // group cardinality [0..0]: clinical findings with no finding site at all + const none = await ids('< 404684003 : [0..0] { 363698007 = * }'); + const some = await ids('< 404684003 : [1..*] { 363698007 = * }'); + const all = await ids('< 404684003'); + expect(none + some).toBe(all); + }); + + test('a concept filter naming a concept the edition lacks is a 400 invalid, not a 500', async () => { + const p = await factory.build(op, []); + for (const [prop, o, v] of [['concept', 'in', '41000147108'], ['code', 'in', '3738000,61231000210108'], ['concept', 'is-a', '584021000052104'], ['concept', 'descendent-of', '99999999']]) { + const prep = await p.getPrepContext(true); + const err = await p.filter(prep, true, prop, o, v).then(() => null, (e) => e); + expect(err).toBeTruthy(); + expect(err.statusCode).toBe(400); + expect(err.isSetForhandleAsOO).toBe(true); + expect(err.asIssue()).toMatchObject({ severity: 'error', code: 'invalid' }); + expect(err.message).toBe(`The SNOMED CT Concept ${v.split(',').pop()} is not known`); + } + }); + + test('mapped: exists: concepts with (or without) an alternate identifier', async () => { + const p = await factory.build(op, []); + const count = async (v) => { + const prep = await p.getPrepContext(true); + await p.filter(prep, true, 'mapped:30051010000102', 'exists', v); + const [set] = await p.executeFilters(prep); + return set.bm.size; + }; + const yes = await count('true'); + expect(yes).toBeGreaterThan(0); + expect(yes + (await count('false'))).toBe(factory.store.conceptCount); + }); + + test('refset members keep effectiveTime, module and RF2 order; ECL member filters use them natively', async () => { + const S = factory.store; + // the decoded record rows, as the reader reads them + const rows = [...S.relations.keys()].flatMap((rid) => S.refsetMemberRows(rid)); + const meta = { n: rows.length, t: rows.filter((r) => r.effective_time != null).length, m: rows.filter((r) => r.module_id != null).length }; + expect(meta.n).toBeGreaterThan(0); + expect(meta.t).toBe(meta.n); + expect(meta.m).toBe(meta.n); + const p = await factory.build(op, []); + const size = async (ecl) => { + const prep = await p.getPrepContext(true); + await p.filter(prep, true, 'constraint', '=', ecl); + const [set] = await p.executeFilters(prep); + return set.bm.size; + }; + const all = await size('^ 900000000000526001'); + const after = await size('^ 900000000000526001 {{ M effectiveTime >= "20240101" }}'); + const before = await size('^ 900000000000526001 {{ M effectiveTime < "20240101" }}'); + expect(all).toBeGreaterThan(0); + expect(after + before).toBeGreaterThanOrEqual(all); + expect(after).toBeLessThanOrEqual(all); + // the target column (record.target_id): a small value set reads only its rows (SQL), a wide one + // every row; both as the decoded rows say + const decoded = S.refsetMemberRows(S.idOf('900000000000526001')); + const target = S.refsetDef(S.idOf('900000000000526001')).names.indexOf('targetComponentId'); + const t = JSON.parse(decoded[0].fields)[target]; + const want = new Set(decoded.filter((r) => JSON.parse(r.fields)[target] === t).map((r) => r.concept_id)).size; + expect(await size(`^ 900000000000526001 {{ M targetComponentId = ${t} }}`)).toBe(want); + expect(await size('^ 900000000000526001 {{ M targetComponentId = * }}')).toBe(new Set(decoded.filter((r) => S.idOf(JSON.parse(r.fields)[target]) != null).map((r) => r.concept_id)).size); + }); + + test('expressions: locate, display, MRCM, subsumption, stored normal forms', async () => { + const p = await factory.build(op, []); + const r = await p.locate('128241005:{363698007=181268008}'); + expect(await p.display(r.context)).toBe('128241005|Inflammatory disease of liver|:{363698007|Finding site|=181268008|Entire liver|}'); + expect(await p.subsumesTest('40468003:{363698007=181268008}', '3738000')).toBe('subsumed-by'); + const bad = await p.locate('367430006:{42752001=789750003}'); + expect(bad.message).toMatch(/does not allow the attribute 42752001 \|Due to\| on 367430006/); + const nf = factory.store.db.prepare("SELECT count(*) AS n FROM ix_key WHERE name = 'normalForm'").get().n; + expect(nf).toBeGreaterThan(100); + }); + + test('ancestorsOf agrees with subsumesTest for plain concept ids; expressions and other spellings get null', async () => { + const p = await factory.build(op, []); + const all = factory.store.db.prepare('SELECT code FROM concept ORDER BY id').pluck().all(); + const codes = [...new Set([...all.filter((c, i) => i % 40 === 0), '3738000', '40468003', '128241005', '138875005'])]; + let related = 0; + for (const b of codes) { + const anc = await p.ancestorsOf(b); + expect(anc).toBeInstanceOf(Set); + for (const a of codes) { + if (a === b) continue; + const s = (await p.subsumesTest(a, b)) === 'subsumes'; + if (s) related++; + expect([a, b, anc.has(a)]).toEqual([a, b, s]); + } + } + expect(related).toBeGreaterThan(20); + expect((await p.ancestorsOf('40468003')).has('3738000')).toBe(true); + expect(await p.ancestorsOf('40468003:{363698007=181268008}')).toBeNull(); + expect(await p.ancestorsOf('40468003|Viral hepatitis, type A|')).toBeNull(); + expect(await p.ancestorsOf(' 40468003')).toBeNull(); + expect(await p.ancestorsOf('999999999')).toBeNull(); + }); +}); diff --git a/tx/cs/cs-snomed.js b/tx/cs/cs-snomed.js index 62740c66..1d635e95 100644 --- a/tx/cs/cs-snomed.js +++ b/tx/cs/cs-snomed.js @@ -5290,5 +5290,6 @@ module.exports = { SnomedExpressionContext, SnomedServices, SnomedFilterContext, - SnomedProviderContextKind + SnomedProviderContextKind, + LANGUAGE_REFSET_DIALECTS }; \ No newline at end of file diff --git a/tx/importers/import-loinc-v2-classic.module.js b/tx/importers/import-loinc-v2-classic.module.js new file mode 100644 index 00000000..b1dab591 --- /dev/null +++ b/tx/importers/import-loinc-v2-classic.module.js @@ -0,0 +1,254 @@ +'use strict'; + +// FHIRsmith classic LOINC db (import-loinc.module.js, served by tx/cs/cs-loinc.js) -> a terminology +// file ("reverse loader"). For releases we only have as a classic file (LOINC 2.77: loinc-2.77-a.db). +// +// Source-specific decoding only, onto the CSV importer's catalog (import-loinc-v2.module.js +// loincCatalog) and its derived-by-importer orders (writeOrders), so a reverse-loaded file serves +// like one built from the release. What is read, and how it maps: +// Codes concepts. Type 1 term, 2 part, 3 answer list, 4 answer; a Type 2 code with +// RelationshipKey 0 and no status is a ComponentHierarchyBySystem-only node. +// display = Description; inactive iff StatusKey is DISCOURAGED (cs-loinc.js +// isInactive); STATUS literal iff StatusKey != 0 (what cs-loinc.js reports). +// The blank code '' (older classic files made one Answer '' shared by the +// externally defined answer lists) is dropped with its links, as the CSV +// importer does. +// Properties literal properties by PropertyTypes name; CLASSTYPE back from its description +// ('Laboratory class') to its code ('1'), as the CSV importer stores it. +// Relationships links by RelationshipTypes name: the part axes, CLASS, parent, Answer +// (list -> answer, in RelationshipKey order = AnswerList.csv order, which also +// gives each answer's sequence in its list: link.seq), answers-for (list -> term). +// The inverses child and AnswerList are catalog rows (inverse_of), not links. +// The parent and child rows, in RelationshipKey order, are cs-loinc.js's $lookup +// order (ix_order hier_start / hier, unless the parent links' seq gives it). +// Closure the explicit ancestor pairs (`ancestor` links: the PATH_TO_ROOT closure, as the +// CSV importer). +// Descriptions designations, language from Languages, use from DescriptionTypes; preferred +// for the en-US LONG_COMMON_NAME (as the CSV importer). +// ExternalCodes/ExternalMappings (when present) mapping rows. +// Not in a classic file: answer SequenceNumber (the list order stands in for it), parts whose +// Part.csv status is NOTSTATED are indistinguishable from parts with no status (no STATUS +// literal either way, as cs-loinc.js reports them). + +const fs = require('fs'); +const Database = require('better-sqlite3'); +const { BaseTerminologyModule } = require('./tx-import-base'); +const { TerminologyBuilder, vacuumFile } = require('./sqlite-v2/builder'); +const { loincCatalog, loincCodeSystem, loincWalk, writeOrders, hierarchyCheck, KIND, LOINC } = require('./import-loinc-v2.module'); + +// classic stores CLASSTYPE as its description; the terminology file the code (with a value_label) +const CLASSTYPE_CODE = { 'Laboratory class': '1', 'Clinical class': '2', 'Claims attachment': '3', 'Surveys': '4' }; +const SKIP_REL = new Set(['child', 'AnswerList', 'N/A']); +const TYPE_KIND = { 1: KIND.term, 2: KIND.part, 3: KIND.list, 4: KIND.answer }; +const DISCOURAGED = 'DISCOURAGED'; + +/** @param {object} cfg { source (classic .db), dest, version (default: Config key 2), overwrite, log } */ +async function importLoincV2FromClassic(cfg) { + const log = cfg.log || console.log; + if (!fs.existsSync(cfg.source)) throw new Error(`classic LOINC db not found: ${cfg.source}`); + const src = new Database(cfg.source, { readonly: true, fileMustExist: true }); + try { + const tables = new Set(src.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(r => r.name)); + for (const t of ['Codes', 'Relationships', 'RelationshipTypes', 'Properties', 'PropertyTypes', 'PropertyValues', + 'Descriptions', 'DescriptionTypes', 'Languages', 'StatusCodes', 'Closure', 'Config']) { + if (!tables.has(t)) throw new Error(`not a classic LOINC db (no ${t} table): ${cfg.source}`); + } + const conf = new Map(src.prepare('SELECT ConfigKey k, Value v FROM Config').all().map(r => [r.k, r.v])); + const version = cfg.version || conf.get(2); + if (!version) throw new Error('no version: pass one (the classic Config has no key 2)'); + if (cfg.version && conf.get(2) && cfg.version !== conf.get(2)) { + throw new Error(`version ${cfg.version} given, but the classic db says ${conf.get(2)}`); + } + const lookup = (sql) => new Map(src.prepare(sql).all().map(r => [r.k, r.v])); + const statusName = lookup('SELECT StatusKey k, Description v FROM StatusCodes'); + const relName = lookup('SELECT RelationshipTypeKey k, Description v FROM RelationshipTypes'); + const propName = lookup('SELECT PropertyTypeKey k, Description v FROM PropertyTypes'); + const descName = lookup('SELECT DescriptionTypeKey k, Description v FROM DescriptionTypes'); + const langCode = lookup('SELECT LanguageKey k, Code v FROM Languages'); + + const b = new TerminologyBuilder(cfg.dest, { overwrite: cfg.overwrite, log, importer: 'loinc-v2-classic' }); + b.addSource(cfg.source); + loincCodeSystem(b, version, `LOINC ${version} (FHIRsmith classic db)`); + const { link, parent, partProp, lit, answer, answersFor, ancestor } = loincCatalog(b); + const prop = (code, kind) => (kind === 'literal' + ? b.property({ code, uri: `${LOINC}/property/${code}`, shape: 'literal', fhirType: 'string', display: code }) : link(code)); + // the classic file's own keys (cs-loinc.js's orders): handle -> [Type, CodeKey] + const sourceOrder = new Map(); + const stats = { blankCodesDropped: 0, linksToDropped: 0, unknownRelationshipTypes: {}, hierarchyNodes: 0, ancestorPairs: 0 }; + + // classic CodeKey -> staging index (undefined: dropped) + const idx = new Map(); + await b.stage('read Codes', async () => { + let n = 0; + for (const r of src.prepare('SELECT CodeKey, Code, Type, RelationshipKey, StatusKey, Description FROM Codes ORDER BY Type, CodeKey').iterate()) { + const code = (r.Code || '').trim(); + if (!code) { stats.blankCodesDropped++; continue; } + const node = r.Type === 2 && r.RelationshipKey === 0 && r.StatusKey === 0; + if (node) stats.hierarchyNodes++; + const st = r.StatusKey ? statusName.get(r.StatusKey) : null; + const i = b.concept(code, { active: st !== DISCOURAGED, display: (r.Description || '').trim() || code, + sortKey: node ? KIND.node : (TYPE_KIND[r.Type] ?? KIND.node) }); + idx.set(r.CodeKey, i); + sourceOrder.set(i, [r.Type, r.CodeKey]); + if (st) b.literal(i, lit.STATUS, st); + n++; + } + return n; + }); + + await b.stage('read Properties', async () => { + let n = 0; + const litProp = new Map(); + const litFor = (k) => { + if (!litProp.has(k)) litProp.set(k, lit[propName.get(k)] ?? prop(propName.get(k) || `property-${k}`, 'literal')); + return litProp.get(k); + }; + for (const r of src.prepare(`SELECT p.CodeKey c, p.PropertyTypeKey t, v.Value v FROM Properties p + JOIN PropertyValues v ON v.PropertyValueKey = p.PropertyValueKey ORDER BY p.PropertyKey`).iterate()) { + const i = idx.get(r.c); + if (i === undefined) { stats.linksToDropped++; continue; } + const name = propName.get(r.t); + const v = String(r.v).trim(); + b.literal(i, litFor(r.t), name === 'CLASSTYPE' ? (CLASSTYPE_CODE[v] ?? v) : v); + n++; + } + return n; + }); + + const childLinks = new Map(); + const hier = { xs: [], others: [], child: [] }; // cs-loinc.js's parent / child entries, in order + const parentLinks = []; // [child, parent, row] of each parent link + await b.stage('read Relationships', async () => { + let n = 0; + // property per relationship type, defined on first use (the CSV importer defines no + // property for axes LOINC does not link, e.g. adjustment, count) + const relProp = new Map(); + const propFor = (k) => { + if (!relProp.has(k)) { + const name = relName.get(k); + relProp.set(k, name === undefined || SKIP_REL.has(name) ? undefined + : name === 'parent' ? parent : name === 'Answer' ? answer : name === 'answers-for' ? answersFor + : (partProp[name] ?? prop(name, 'concept'))); + } + return relProp.get(k); + }; + const seq = new Map(); // list index -> answers so far + const hierSeen = new Set(); + const linkSeen = new Set(); + let row = 0; + for (const r of src.prepare('SELECT RelationshipTypeKey t, SourceKey s, TargetKey g FROM Relationships ORDER BY RelationshipKey').iterate()) { + row++; + if (relName.get(r.t) === 'child' && idx.has(r.s) && idx.has(r.g)) { + // (the child links, in their rows' order: the whole-system walk below) + let kids = childLinks.get(idx.get(r.s)); + if (!kids) childLinks.set(idx.get(r.s), kids = []); + if (!kids.includes(idx.get(r.g))) kids.push(idx.get(r.g)); + } + const rel = relName.get(r.t); + if ((rel === 'parent' || rel === 'child') && idx.has(r.s) && idx.has(r.g)) { + // a code's parent and child rows in RelationshipKey order: cs-loinc.js's $lookup order + const key = rel + ':' + r.s + ':' + r.g; + if (!hierSeen.has(key)) { hierSeen.add(key); hier.xs.push(idx.get(r.s)); hier.others.push(idx.get(r.g)); hier.child.push(rel === 'child' ? 1 : 0); } + } + const p = propFor(r.t); + if (p === undefined) { + if (!relName.has(r.t)) stats.unknownRelationshipTypes[r.t] = (stats.unknownRelationshipTypes[r.t] || 0) + 1; + continue; + } + const s = idx.get(r.s), t = idx.get(r.g); + if (s === undefined || t === undefined) { stats.linksToDropped++; continue; } + if (p === answer) { + // the answer's place in its list: the list's rows in RelationshipKey order + const k = (seq.get(s) || 0) + 1; + seq.set(s, k); + b.link(s, p, t, { seq: k }); + } else { + b.link(s, p, t, { seq: row }); + const lk = s + ':' + t; + if (p === parent && !linkSeen.has(lk)) { linkSeen.add(lk); parentLinks.push(s, t, row); } + } + n++; + } + return n; + }); + + await b.stage('read Closure', async () => { + let n = 0; + for (const r of src.prepare('SELECT AncestorKey a, DescendentKey d FROM Closure ORDER BY DescendentKey, AncestorKey').iterate()) { + const a = idx.get(r.a), d = idx.get(r.d); + if (a === undefined || d === undefined || a === d) continue; + b.link(d, ancestor, a); + n++; + } + stats.ancestorPairs = n; + return n; + }); + + await b.stage('read Descriptions', async () => { + let n = 0; + for (const r of src.prepare('SELECT CodeKey c, LanguageKey l, DescriptionTypeKey t, Value v FROM Descriptions ORDER BY DescriptionKey').iterate()) { + const i = idx.get(r.c); + const term = (r.v || '').trim(); + if (i === undefined || !term) continue; + const language = langCode.get(r.l) || null; + const use = descName.get(r.t); + b.item(i, { language, use: use ? { system: LOINC, code: use, display: use } : null, text: term, active: true, + preferred: use === 'LONG_COMMON_NAME' && language === 'en-US' }); + n++; + } + return n; + }); + + if (tables.has('ExternalMappings') && tables.has('ExternalCodes')) { + await b.stage('read external maps', async () => { + let n = 0; + for (const r of src.prepare(`SELECT m.CodeKey c, e.System s, e.Version v, e.Code code, e.Display d, m.Equivalence q + FROM ExternalMappings m JOIN ExternalCodes e ON e.ExternalCodeKey = m.ExternalCodeKey ORDER BY m.ExternalMappingKey`).iterate()) { + const i = idx.get(r.c); + if (i === undefined || !r.code || !r.s) continue; + b.mapping(i, { system: r.s, version: r.v || null, code: r.code, display: r.d || null, relationship: r.q || 'equivalent' }); + n++; + } + return n; + }); + } + + const walkPlace = await b.stage('whole-system walk', async () => loincWalk(sourceOrder, childLinks)); + const order = hierarchyCheck(b.codes.length, hier, parentLinks); + stats.hierarchyOrder = order.stats; + const storeHier = order.stats.conceptsDiffering > 0; + const derived = [{ table: 'ix_order', name: 'rank' }, { table: 'ix_order', name: 'ids' }, { table: 'ix_order', name: 'walk' }]; + if (storeHier) derived.push({ table: 'ix_order', name: 'hier_start' }, { table: 'ix_order', name: 'hier' }); + b.setMeta('derived-by-importer', derived); + stats.hierarchyArraysStored = storeHier; + const summary = b.finish(stats, { vacuum: false }); + writeOrders(cfg.dest, b, sourceOrder, walkPlace, storeHier ? hier : null); + vacuumFile(cfg.dest); + summary.fileBytes = fs.statSync(cfg.dest).size; + return summary; + } finally { + src.close(); + } +} + +class LoincV2ClassicModule extends BaseTerminologyModule { + getName() { return 'loinc-v2-classic'; } + getDescription() { return 'FHIRsmith classic LOINC db -> SQLite terminology file (sqlite-v2 provider)'; } + getSupportedFormats() { return ['sqlite']; } + + registerCommands(cmd) { + cmd.command('import') + .description('Convert a classic FHIRsmith LOINC .db into a terminology file') + .requiredOption('-s, --source ', 'classic LOINC .db (e.g. loinc-2.77-a.db)') + .requiredOption('-d, --dest ', 'destination .db') + .option('-v, --loinc-version ', 'checked against the classic Config (default: its version)') + .option('--overwrite', 'replace the destination') + .action(async (o) => { + const s = await importLoincV2FromClassic({ source: o.source, dest: o.dest, version: o.loincVersion, + overwrite: !!o.overwrite, log: (m) => this.logInfo(m) }); + this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); + }); + } +} + +module.exports = { LoincV2ClassicModule, importLoincV2FromClassic }; diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js new file mode 100644 index 00000000..b7306641 --- /dev/null +++ b/tx/importers/import-loinc-v2.module.js @@ -0,0 +1,536 @@ +'use strict'; + +// LOINC CSV release -> a terminology file (tx/importers/sqlite-v2/schema.sql). The files read +// (paths relative to the release root): LoincTable/Loinc.csv, AccessoryFiles/PartFile/{Part, +// LoincPartLink_Primary,PartRelatedCodeMapping}.csv, ComponentHierarchyBySystem/ +// ComponentHierarchyBySystem.csv, AnswerFile/{AnswerList,LoincAnswerListLink}.csv, +// ConsumerName/ConsumerName.csv, LinguisticVariants/*LinguisticVariant.csv and the IEEE device +// code table. Where each fact goes: +// concept terms, parts, answer lists, answers, hierarchy-only nodes; display; inactive iff +// STATUS is DISCOURAGED; sort keys by kind (the builder's numbering) +// item every designation (LONG_COMMON_NAME preferred, SHORTNAME, RELATEDNAMES2, the part's +// DisplayName, ConsumerName, the linguistic variants and their PartName translations) +// link part links (LoincPartLink_Primary, seq = its row), CLASS (Loinc.csv, seq = the term's +// row), parent (ComponentHierarchyBySystem, seq = the first row of the pair: the +// hierarchy order upstream lists parents and children in, see below), Answer (list -> +// answer, seq = the answer's SequenceNumber in the list: answer lists are ordered), +// answers-for (list -> term, seq = its LoincAnswerListLink row), ancestor (PATH_TO_ROOT +// pairs, descendant -> ancestor; the closure of `parent`, catalog closure_from) +// literal the Loinc.csv properties and the part's STATUS +// value_label CLASSTYPE 1-4 names +// mapping PartRelatedCodeMapping, the IEEE device code table, answers' external codes +// catalog loincCatalog: the link and literal properties, then `child` (inverse_of parent), +// `Answer|answers-for` (a union, filterable 0), `AnswerList` (inverse_of that union) and +// `ancestor` (the closure source, filterable through the hierarchy's sets only) +// ix_order derived-by-importer: rank / ids (upstream's code key order: Part.csv's parts, +// Loinc.csv's terms, AnswerList.csv's lists and answers as they first appear, then +// hierarchy-only codes) and walk (the whole system in upstream's walk of that order). +// They are the upstream importer's numbering, not a release fact, and need its file +// sequence to compute: the importer writes them. hier_start / hier (upstream's +// parent / child entry order) only when the parent links' seq does not reproduce it. + +const fs = require('fs'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { TerminologyBuilder, vacuumFile, analyze } = require('./sqlite-v2/builder'); +const { writeOrderArray, writeActiveOrder } = require('./sqlite-v2/indexes'); +const { csvObjects } = require('./sqlite-v2/text'); +const { hierarchyArrays } = require('../sqlite-v2/orders'); +const { BaseTerminologyModule } = require('./tx-import-base'); + +const LOINC = 'http://loinc.org'; +const PROP = `${LOINC}/property`; + +// LoincPartLink_Primary PartTypeName -> property code (tx.fhir.org's LOINC vocabulary). +const PART_LINK = { + 'COMPONENT': 'COMPONENT', 'PROPERTY': 'PROPERTY', 'TIME': 'TIME_ASPCT', 'SYSTEM': 'SYSTEM', + 'SCALE': 'SCALE_TYP', 'METHOD': 'METHOD_TYP', + 'Document.Kind': 'document-kind', 'Document.Role': 'document-role', 'Document.Setting': 'document-setting', + 'Document.SubjectMatterDomain': 'document-subject-matter-domain', 'Document.TypeOfService': 'document-type-of-service', + 'Rad.Anatomic Location.Imaging Focus': 'rad-anatomic-location-imaging-focus', + 'Rad.Anatomic Location.Laterality': 'rad-anatomic-location-laterality', + 'Rad.Anatomic Location.Laterality.Presence': 'rad-anatomic-location-laterality-presence', + 'Rad.Anatomic Location.Region Imaged': 'rad-anatomic-location-region-imaged', + 'Rad.Guidance for.Action': 'rad-guidance-for-action', 'Rad.Guidance for.Approach': 'rad-guidance-for-approach', + 'Rad.Guidance for.Object': 'rad-guidance-for-object', 'Rad.Guidance for.Presence': 'rad-guidance-for-presence', + 'Rad.Maneuver.Maneuver Type': 'rad-maneuver-maneuver-type', + 'Rad.Modality.Modality Subtype': 'rad-modality-modality-subtype', 'Rad.Modality.Modality Type': 'rad-modality-modality-type', + 'Rad.Pharmaceutical.Route': 'rad-pharmaceutical-route', + 'Rad.Pharmaceutical.Substance Given': 'rad-pharmaceutical-substance-given', + 'Rad.Reason for Exam': 'rad-reason-for-exam', 'Rad.Subject': 'rad-subject', 'Rad.Timing': 'rad-timing', + 'Rad.View.Aggregation': 'rad-view-aggregation', 'Rad.View.View Type': 'rad-view-view-type', +}; + +// The axis columns of a LinguisticVariant file, named as the term's links to its Parts are +const VARIANT_AXES = ['COMPONENT', 'PROPERTY', 'TIME_ASPCT', 'SYSTEM', 'SCALE_TYP', 'METHOD_TYP', 'CLASS']; + +// Loinc.csv column -> literal property (all strings, as tx.fhir.org emits them). +const LITERALS = [ + ['CLASSTYPE', 'CLASSTYPE'], ['ORDER_OBS', 'ORDER_OBS'], ['EXAMPLE_UNITS', 'EXAMPLE_UNITS'], + ['EXAMPLE_UCUM_UNITS', 'EXAMPLE_UCUM_UNITS'], ['PanelType', 'PanelType'], ['AskAtOrderEntry', 'AskAtOrderEntry'], + ['UNITSREQUIRED', 'UNITSREQUIRED'], ['Copyright', 'EXTERNAL_COPYRIGHT_NOTICE'], + ['ValidHL7AttachmentRequest', 'ValidHL7AttachmentRequest'], ['STATUS', 'STATUS'], +]; + +const STATUS = new Map([['NOTSTATED', 'NotStated'], ['ACTIVE', 'ACTIVE'], ['DEPRECATED', 'DEPRECATED'], + ['TRIAL', 'TRIAL'], ['DISCOURAGED', 'DISCOURAGED'], ['EXAMPLE', 'EXAMPLE'], ['PREFERRED', 'PREFERRED'], + ['PRIMARY', 'Primary'], ['DOCUMENTONTOLOGY', 'DocumentOntology'], ['RADIOLOGY', 'Radiology'], ['NORMATIVE', 'NORMATIVE']]); +const status = (s, dflt) => STATUS.get(String(s || '').trim().toUpperCase()) || dflt; + +// Sort keys: siblings and roots are ordered by kind first, then code. +const KIND = { term: 0, part: 1, list: 2, answer: 3, node: 4 }; + +// The built-in importer's key order (import-loinc.module.js gives each code a CodeKey as it +// inserts it): Part.csv's parts, then Loinc.csv's terms, then AnswerList.csv's lists and answers +// as they first appear, then the ComponentHierarchyBySystem codes not seen yet. cs-loinc.js lists +// filter results by that key, and the whole system by type (its Codes.Type), then key. Kept in +// as (type, stage * ORDER_STAGE + row): the ix_order rank / ids the importer writes (writeOrders) +const ORDER_TYPE = { term: 1, part: 2, list: 3, answer: 4 }; +const ORDER_STAGE = 1e7; +const ORDER = { parts: 0, terms: 1, answers: 2, hierarchy: 3, unkeyed: 4 }; + +/** + * cs-loinc.js's whole-system order, which expand.js walks: every code by type, then key, each + * followed (depth first) by the parts and terms below it, children in the order the importer + * linked them (its Relationships rows), each code once. Only parts are walked into. + * @param {Map} order index -> [type, key] + * @param {Map} children part index -> child indexes, in link order + * @returns {Map} index -> place in the walk + */ +function loincWalk(order, children) { + const roots = [...order.keys()].sort((a, b) => (order.get(a)[0] - order.get(b)[0]) || (order.get(a)[1] - order.get(b)[1])); + const place = new Map(); + for (const r of roots) { + const stack = [r]; + while (stack.length) { + const i = stack.pop(); + if (place.has(i)) continue; + place.set(i, place.size); + const kids = order.get(i) && order.get(i)[0] === ORDER_TYPE.part ? children.get(i) : null; + if (kids) for (let k = kids.length - 1; k >= 0; k--) if (!place.has(kids[k])) stack.push(kids[k]); + } + } + return place; +} + +// LOINC names some systems other than by their FHIR URI (as import-loinc.module.js). +const EXTERNAL_SYSTEMS = { + 'CMS/HCPCS': 'http://www.cms.gov/Medicare/Coding/HCPCSReleaseCodeSets', + 'https://www.cdc.gov/phin': 'urn:oid:2.16.840.1.113883.6.238', +}; +// IEEE equivalence is stated from the LOINC side; ConceptMap's from the target side. +const IEEE_EQUIVALENCE = { broader: 'narrower', narrower: 'wider', '': 'equivalent' }; + +function files(root) { + const p = (...x) => path.join(root, ...x); + const f = { + loinc: p('LoincTable', 'Loinc.csv'), + part: p('AccessoryFiles', 'PartFile', 'Part.csv'), + partLink: p('AccessoryFiles', 'PartFile', 'LoincPartLink_Primary.csv'), + hierarchy: p('AccessoryFiles', 'ComponentHierarchyBySystem', 'ComponentHierarchyBySystem.csv'), + answerList: p('AccessoryFiles', 'AnswerFile', 'AnswerList.csv'), + answerLink: p('AccessoryFiles', 'AnswerFile', 'LoincAnswerListLink.csv'), + consumer: p('AccessoryFiles', 'ConsumerName', 'ConsumerName.csv'), + partMap: p('AccessoryFiles', 'PartFile', 'PartRelatedCodeMapping.csv'), + ieee: p('AccessoryFiles', 'LoincIeeeMedicalDeviceCodeMappingTable', 'LoincIeeeMedicalDeviceCodeMappingTable.csv'), + }; + for (const k of ['loinc', 'part', 'partLink', 'hierarchy', 'answerList', 'answerLink', 'consumer']) { + if (!fs.existsSync(f[k])) throw new Error(`required LOINC file missing: ${f[k]}`); + } + const lv = p('AccessoryFiles', 'LinguisticVariants'); + f.variants = fs.existsSync(lv) ? fs.readdirSync(lv).filter(n => /^[a-z]{2}[A-Z]{2}\d+LinguisticVariant\.csv$/.test(n)).sort().map(n => path.join(lv, n)) : []; + return f; +} + + +const CLASSTYPE = { 1: 'Laboratory class', 2: 'Clinical class', 3: 'Claims attachment', 4: 'Surveys' }; + +/** + * The LOINC catalog (shared with the classic-db importer): the hierarchy, the part axes and CLASS, + * the Loinc.csv literals, Answer (ordered: link.seq is the answer's place in its list) and + * answers-for; the inverse rows cs-loinc.js names (`child` of parent; `AnswerList` of the union of + * Answer and answers-for, which no filter names); `ancestor`, the PATH_TO_ROOT pairs the + * hierarchy's descendants come from (closure_from); the CLASSTYPE value labels. + */ +function loincCatalog(b) { + const link = (code, extra = {}) => b.property({ code, uri: `${PROP}/${code}`, shape: 'link', display: code, ...extra }); + const parent = link('parent', { subsumption: true }); + const partProp = Object.fromEntries([...new Set(Object.values(PART_LINK)), 'CLASS'].map((c) => [c, link(c)])); + const lit = Object.fromEntries(LITERALS.map(([c]) => [c, b.property({ code: c, uri: `${PROP}/${c}`, shape: 'literal', fhirType: 'string', display: c })])); + const answer = link('Answer', { ordered: true }); + const answersFor = link('answers-for'); + b.property({ code: 'child', uri: `${PROP}/child`, shape: 'link', display: 'child', inverseOf: parent }); + const listLinks = b.property({ code: 'Answer|answers-for', shape: 'union', display: 'Answer and answers-for', filterable: false }); + b.propertyMember(listLinks, answer); + b.propertyMember(listLinks, answersFor); + b.property({ code: 'AnswerList', uri: `${PROP}/AnswerList`, shape: 'link', display: 'AnswerList', inverseOf: listLinks }); + const ancestor = b.property({ code: 'ancestor', uri: `${PROP}/ancestor`, shape: 'link', display: 'ancestor (PATH_TO_ROOT)' }); + b.setClosureFrom(parent, ancestor); + for (const [v, d] of Object.entries(CLASSTYPE)) b.valueLabel(lit.CLASSTYPE, String(v), d); + return { link, parent, partProp, lit, answer, answersFor, ancestor }; +} + +/** the code system row of a LOINC file */ +function loincCodeSystem(b, version, description) { + b.codeSystem({ uri: LOINC, version, name: 'LOINC', title: 'Logical Observation Identifier Names and Codes (LOINC)', + description, caseSensitive: true, hierarchyMeaning: 'is-a', defaultLanguage: 'en-US' }); + // as cs-loinc.js presents it: the stored order (main's key order and walk), $lookup's name the + // title, the description the name, versions compared naturally + b.setBehaviour('expansionOrder', 'stored'); + b.setBehaviour('lookupName', 'title'); + b.setBehaviour('description', 'name'); + b.setBehaviour('versionAlgorithm', 'natural'); +} + +/** @param {object} cfg { source, dest, version, overwrite, log, hierarchyArrays: 'auto' | 'always' | 'never' } */ +async function importLoincV2(cfg) { + const log = cfg.log || console.log; + const f = files(cfg.source); + const b = new TerminologyBuilder(cfg.dest, { overwrite: cfg.overwrite, log, importer: 'loinc-v2' }); + for (const p of [f.loinc, f.part, f.partLink, f.hierarchy, f.answerList, f.answerLink, f.consumer, f.partMap, f.ieee, ...f.variants]) { + if (fs.existsSync(p)) b.addSource(p); + } + loincCodeSystem(b, cfg.version, `LOINC ${cfg.version} (CSV release)`); + const { parent, partProp, lit, answer, answersFor, ancestor } = loincCatalog(b); + + const use = (code) => ({ system: LOINC, code, display: code }); + // Designations stay active when the term is DISCOURAGED (as tx.fhir.org reports them). + const desig = (i, language, code, term, preferred = false) => + term && b.item(i, { language, use: use(code), text: term.trim(), active: true, preferred }); + const stats = { classLinksMissing: 0, partLinksSkipped: 0, hierarchyNodes: 0, ancestorPairs: 0 }; + + // upstream's code key order and walk, by concept handle + const sourceOrder = new Map(); + const setOrder = (i, type, seq) => sourceOrder.set(i, [type, seq]); + + const axisParts = new Map(); + const noteAxisPart = (term, axis, part) => { + let a = axisParts.get(term); + if (!a) axisParts.set(term, a = {}); + a[axis] = part; + }; + + const terms = []; + let termRow = 0; + await b.stage('parse Loinc.csv', async () => { + for await (const r of csvObjects(f.loinc)) { + const code = r.LOINC_NUM.trim(); + if (!code) continue; + const st = status(r.STATUS, 'ACTIVE'); + const i = b.concept(code, { active: st !== 'DISCOURAGED', display: r.LONG_COMMON_NAME.trim() || code, sortKey: KIND.term }); + setOrder(i, ORDER_TYPE.term, ORDER.terms * ORDER_STAGE + (++termRow)); + for (const [p, col] of LITERALS) b.literal(i, lit[p], p === 'STATUS' ? st : r[col].trim()); + desig(i, 'en-US', 'LONG_COMMON_NAME', r.LONG_COMMON_NAME, true); + desig(i, 'en-US', 'SHORTNAME', r.SHORTNAME); + desig(i, 'en-US', 'RELATEDNAMES2', r.RELATEDNAMES2); + if (r.CLASS.trim()) terms.push(i, r.CLASS.trim().toUpperCase(), termRow); + } + return termRow; + }); + + const classPart = new Map(); + await b.stage('parse Part.csv', async () => { + let n = 0; + for await (const r of csvObjects(f.part)) { + const code = r.PartNumber.trim(); + if (!code) continue; + const st = status(r.Status, null); + const i = b.concept(code, { active: st !== 'DISCOURAGED', display: r.PartName.trim() || code, sortKey: KIND.part }); + setOrder(i, ORDER_TYPE.part, ORDER.parts * ORDER_STAGE + n + 1); + if (r.PartTypeName.trim() === 'CLASS' && r.PartName.trim()) classPart.set(r.PartName.trim().toUpperCase(), i); + desig(i, 'en-US', 'DisplayName', r.PartDisplayName); + if (st) b.literal(i, lit.STATUS, st); + n++; + } + for (let k = 0; k < terms.length; k += 3) { + const c = classPart.get(terms[k + 1]); + if (c === undefined) stats.classLinksMissing++; + else { b.link(terms[k], partProp.CLASS, c, { seq: terms[k + 2] }); noteAxisPart(terms[k], 'CLASS', c); } + } + terms.length = 0; + return n; + }); + + await b.stage('parse AnswerList.csv', async () => { + let n = 0, row = 0, currentList = ''; + // an answer's external code is on the row of the list that names it, not always its first: + // each (answer, system, code) once + const mapped = new Set(); + for await (const r of csvObjects(f.answerList)) { + const listCode = r.AnswerListId.trim(), answerCode = r.AnswerStringId.trim(); + const newRun = listCode !== currentList; + currentList = listCode; + if (!listCode) continue; + const list = b.concept(listCode, { display: r.AnswerListName.trim() || listCode, sortKey: KIND.list }); + if (newRun) setOrder(list, ORDER_TYPE.list, ORDER.answers * ORDER_STAGE + (++row)); + if (!answerCode) continue; + const a = b.concept(answerCode, { display: r.DisplayText.trim() || answerCode, sortKey: KIND.answer }); + if (!sourceOrder.has(a)) setOrder(a, ORDER_TYPE.answer, ORDER.answers * ORDER_STAGE + (++row)); + // the answer's position in the list (lists are ordered: ordinal scales, questionnaires) + const seq = Number.parseInt(r.SequenceNumber, 10); + b.link(list, answer, a, { seq: Number.isFinite(seq) ? seq : null }); + const extSystem = EXTERNAL_SYSTEMS[r.ExtCodeSystem.trim()] || r.ExtCodeSystem.trim(), extCode = r.ExtCodeId.trim(); + if (extCode && extSystem && !mapped.has(`${a}|${extSystem}|${extCode}`)) { + mapped.add(`${a}|${extSystem}|${extCode}`); + b.mapping(a, { system: extSystem, version: r.ExtCodeSystemVersion.trim() || null, + code: extCode, display: r.ExtCodeDisplayName.trim() || null, relationship: 'equivalent' }); + } + n++; + } + return n; + }); + + await b.stage('parse LoincAnswerListLink.csv', async () => { + let n = 0, row = 0; + for await (const r of csvObjects(f.answerLink)) { + row++; + const t = b.idx(r.LoincNumber.trim()), l = b.idx(r.AnswerListId.trim()); + if (t === undefined || l === undefined) continue; + b.link(l, answersFor, t, { seq: row }); + n++; + } + return n; + }); + + await b.stage('parse LoincPartLink_Primary.csv', async () => { + let n = 0, row = 0; + for await (const r of csvObjects(f.partLink)) { + row++; + const p = PART_LINK[r.PartTypeName.trim()]; + const s = b.idx(r.LoincNumber.trim()), t = b.idx(r.PartNumber.trim()); + if (!p || s === undefined || t === undefined) { stats.partLinksSkipped++; continue; } + b.link(s, partProp[p], t, { seq: row }); + if (VARIANT_AXES.includes(p)) noteAxisPart(s, p, t); + n++; + } + return n; + }); + + const placeholder = new Set(); + const childLinks = new Map(); // upstream's child links (for the walk) + const hierPairs = new Set(); + const hier = { xs: [], others: [], child: [] }; // upstream's entries, in order (v2 hierarchyEntry) + const node = (code) => { + const before = b.codes.length; + const i = b.concept(code, { display: code, sortKey: KIND.node }); + if (b.codes.length > before) { placeholder.add(i); stats.hierarchyNodes++; } + return i; + }; + const parentLinks = []; // [child, parent, first row] of each parent link, for the order check + const parentSeen = new Set(); + await b.stage('parse ComponentHierarchyBySystem.csv', async () => { + let n = 0; + for await (const r of csvObjects(f.hierarchy)) { + const code = r.CODE.trim(); + if (!code) continue; + const before = b.codes.length; + const c = b.concept(code, { display: r.CODE_TEXT.trim() || code, sortKey: KIND.node }); + if (!sourceOrder.has(c)) setOrder(c, ORDER_TYPE.part, ORDER.hierarchy * ORDER_STAGE + n + 1); + if (b.codes.length > before) stats.hierarchyNodes++; + else if (placeholder.delete(c)) b.setDisplay(c, r.CODE_TEXT.trim() || code); + const parentCode = r.IMMEDIATE_PARENT.trim(); + if (parentCode && b.idx(parentCode) !== undefined && sourceOrder.has(b.idx(parentCode))) { + const p = b.idx(parentCode); + let kids = childLinks.get(p); + if (!kids) childLinks.set(p, kids = []); + if (!kids.includes(c)) kids.push(c); + const pair = c + ':' + p; + if (!hierPairs.has(pair)) { + hierPairs.add(pair); + hier.xs.push(c, p); hier.others.push(p, c); hier.child.push(0, 1); + } + } + if (parentCode && parentCode !== code) { + const p = node(parentCode); + // seq: the hierarchy row (the builder keeps a pair's first) + b.link(c, parent, p, { seq: n + 1 }); + const k = c + ':' + p; + if (!parentSeen.has(k)) { parentSeen.add(k); parentLinks.push(c, p, n + 1); } + } + for (const a of r.PATH_TO_ROOT.split('.')) { + const ac = a.trim(); + if (!ac || ac === code) continue; + b.link(c, ancestor, node(ac)); + stats.ancestorPairs++; + } + n++; + } + return n; + }); + + await b.stage('parse designations', async () => { + let n = 0; + const partNamesSeen = new Set(); + for await (const r of csvObjects(f.consumer)) { + const i = b.idx(r.LoincNumber.trim()); + if (i !== undefined && r.ConsumerName.trim()) { desig(i, 'en-US', 'ConsumerName', r.ConsumerName); n++; } + } + for (const file of f.variants) { + const m = /^([a-z]{2})([A-Z]{2})/.exec(path.basename(file)); + const lang = `${m[1]}-${m[2]}`; + for await (const r of csvObjects(file)) { + const i = b.idx(r.LOINC_NUM.trim()); + if (i === undefined) continue; + desig(i, lang, 'LONG_COMMON_NAME', r.LONG_COMMON_NAME); + desig(i, lang, 'SHORTNAME', r.SHORTNAME); + desig(i, lang, 'LinguisticVariantDisplayName', r.LinguisticVariantDisplayName); + desig(i, lang, 'RELATEDNAMES2', r.RELATEDNAMES2); + const axes = axisParts.get(i); + if (axes) { + for (const axis of VARIANT_AXES) { + const value = r[axis] ? r[axis].trim() : ''; + const part = axes[axis]; + if (!value || part === undefined) continue; + const key = part + '|' + lang + '|' + value; + if (partNamesSeen.has(key)) continue; + partNamesSeen.add(key); + desig(part, lang, 'PartName', value); + } + } + n++; + } + } + return n; + }); + + await b.stage('parse external maps', async () => { + let n = 0; + if (fs.existsSync(f.partMap)) { + for await (const r of csvObjects(f.partMap)) { + const i = b.idx(r.PartNumber.trim()); + const system = r.ExtCodeSystem.trim(); + if (i === undefined || !r.ExtCodeId.trim() || !system || system === 'http://www.radlex.org') continue; + b.mapping(i, { system: EXTERNAL_SYSTEMS[system] || system, version: r.ExtCodeSystemVersion.trim() || null, + code: r.ExtCodeId.trim(), display: r.ExtCodeDisplayName.trim() || null, relationship: r.Equivalence.trim() || 'equivalent' }); + n++; + } + } + if (fs.existsSync(f.ieee)) { + for await (const r of csvObjects(f.ieee)) { + const i = b.idx(r.LOINC_NUM.trim()); + if (i === undefined || !r.IEEE_CF_CODE10.trim()) continue; + const eq = r.EQUIVALENCE.trim(); + b.mapping(i, { system: 'urn:iso:std:iso:11073:10101', code: r.IEEE_CF_CODE10.trim(), + display: r.IEEE_REFID.trim() || null, relationship: IEEE_EQUIVALENCE[eq] || eq }); + n++; + } + } + return n; + }); + + stats.unkeyed = 0; + for (let i = 0; i < b.codes.length; i++) if (!sourceOrder.has(i)) setOrder(i, ORDER_TYPE.part, ORDER.unkeyed * ORDER_STAGE + (++stats.unkeyed)); + const walkPlace = await b.stage('whole-system walk', async () => loincWalk(sourceOrder, childLinks)); + + // does the parent links' seq give upstream's entry order? (then the reader merges a concept's + // parent links and its children's links by seq, and no array is stored) + const order = await b.stage('hierarchy order check', async () => hierarchyCheck(b.codes.length, hier, parentLinks)); + stats.hierarchyOrder = order.stats; + const storeHier = cfg.hierarchyArrays === 'always' || (cfg.hierarchyArrays !== 'never' && order.stats.conceptsDiffering > 0); + const derived = [{ table: 'ix_order', name: 'rank' }, { table: 'ix_order', name: 'ids' }, { table: 'ix_order', name: 'walk' }]; + if (storeHier) derived.push({ table: 'ix_order', name: 'hier_start' }, { table: 'ix_order', name: 'hier' }); + b.setMeta('derived-by-importer', derived); + stats.hierarchyArraysStored = storeHier; + + const summary = b.finish(stats, { vacuum: false }); + const t0 = Date.now(); + writeOrders(cfg.dest, b, sourceOrder, walkPlace, storeHier ? hier : null); + summary.timings.derived = { s: (Date.now() - t0) / 1000, peakRssMiB: Math.round(process.resourceUsage().maxRSS / 1024) }; + const t1 = Date.now(); + vacuumFile(cfg.dest); + summary.timings.vacuum = { s: (Date.now() - t1) / 1000 }; + summary.fileBytes = fs.statSync(cfg.dest).size; + return summary; +} + +/** + * Upstream's entries (per concept: its parent and child relations in hierarchy-file row order, + * only pairs whose parent had a key at that row, each once) against the parent links ordered by + * the first row of each pair. Counts concepts whose lists differ (by handle). + */ +function hierarchyCheck(n, hier, parentLinks) { + const key = (other, isChild) => `${isChild ? 'c' : 'p'}${other}`; + const up = new Map(); + for (let k = 0; k < hier.xs.length; k++) { + let l = up.get(hier.xs[k]); + if (!l) up.set(hier.xs[k], l = []); + l.push(key(hier.others[k], hier.child[k])); + } + const fromLinks = new Map(); + const add = (x, e, seq) => { let l = fromLinks.get(x); if (!l) fromLinks.set(x, l = []); l.push([seq, e]); }; + for (let k = 0; k < parentLinks.length; k += 3) { + const [c, p, seq] = [parentLinks[k], parentLinks[k + 1], parentLinks[k + 2]]; + add(c, key(p, 0), seq); + add(p, key(c, 1), seq); + } + let differ = 0, extra = 0, missing = 0; + const examples = []; + for (let x = 0; x < n; x++) { + const a = up.get(x) || []; + const l = (fromLinks.get(x) || []).sort((u, v) => u[0] - v[0]).map((e) => e[1]); + if (a.length !== l.length || a.some((e, i) => e !== l[i])) { + differ++; + if (l.length > a.length) extra++; else if (l.length < a.length) missing++; + if (examples.length < 5) examples.push({ handle: x, upstream: a.slice(0, 6), links: l.slice(0, 6) }); + } + } + return { stats: { concepts: n, upstreamEntries: hier.xs.length, conceptsDiffering: differ, withExtraLinks: extra, withMissingLinks: missing, examples } }; +} + +/** the derived-by-importer ix_order rows: rank, ids, walk (and hier_start / hier when asked) */ +function writeOrders(file, b, sourceOrder, walkPlace, hier) { + const db = new Database(file); + db.pragma('journal_mode = OFF'); + db.pragma('synchronous = OFF'); + try { + const n = db.prepare('SELECT concept_count FROM main.code_system WHERE served = 1').pluck().get(); + const idOf = new Uint32Array(b.codes.length); + for (const [id, code] of db.prepare('SELECT id, code FROM main.concept').raw().iterate()) idOf[b.idx(code)] = id; + const rows = [...sourceOrder].map(([i, [type, seq]]) => [idOf[i], type, seq, walkPlace.get(i)]); + // rank by key, the walk by its place (or, without a walk, by type then key) + rows.sort((x, y) => x[2] - y[2]); + const rank = new Uint32Array(n + 1), ids = new Uint32Array(n + 1); + rows.forEach((r, k) => { rank[r[0]] = k; ids[k] = r[0]; }); + const byWalk = rows.every((r) => r[3] != null); + const walk = Uint32Array.from(rows.slice().sort(byWalk ? (x, y) => x[3] - y[3] : (x, y) => x[1] - y[1]).map((r) => r[0])); + db.exec('BEGIN'); + db.prepare("DELETE FROM main.ix_order WHERE name IN ('rank', 'ids', 'walk', 'hier_start', 'hier')").run(); + const ins = db.prepare('INSERT INTO main.ix_order VALUES (?, ?, ?)'); + writeOrderArray(db, 'rank', rank, ins); + writeOrderArray(db, 'ids', ids, ins); + writeOrderArray(db, 'walk', walk, ins); + writeActiveOrder(db); + if (hier) { + const arrays = hierarchyArrays(n, hier.xs.map((i) => idOf[i]), hier.others.map((i) => idOf[i]), hier.child); + writeOrderArray(db, 'hier_start', arrays.start, ins); + writeOrderArray(db, 'hier', arrays.entries, ins); + } + db.exec('COMMIT'); + analyze(db, 'main.ix_order'); + db.pragma('journal_mode = DELETE'); + } finally { + db.close(); + } +} + +class LoincV2Module extends BaseTerminologyModule { + getName() { return 'loinc-v2'; } + getDescription() { return 'LOINC CSV release -> SQLite terminology file (sqlite-v2 provider)'; } + getSupportedFormats() { return ['directory']; } + + registerCommands(cmd) { + cmd.command('import') + .description('Import an unzipped LOINC release into a terminology file') + .requiredOption('-s, --source ', 'release root (contains LoincTable/ and AccessoryFiles/)') + .requiredOption('-d, --dest ', 'destination .db') + .requiredOption('-v, --loinc-version ', 'e.g. 2.83') + .option('--overwrite', 'replace the destination') + .action(async (o) => { + const s = await importLoincV2({ source: o.source, dest: o.dest, version: o.loincVersion, overwrite: !!o.overwrite, log: (m) => this.logInfo(m) }); + this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); + }); + } +} + +module.exports = { LoincV2Module, importLoincV2, loincCatalog, loincCodeSystem, loincWalk, writeOrders, hierarchyCheck, files, status, + KIND, LOINC, ORDER_TYPE, ORDER_STAGE, ORDER, LITERALS, PART_LINK }; diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js new file mode 100644 index 00000000..e56567cc --- /dev/null +++ b/tx/importers/import-rxnorm-v2.module.js @@ -0,0 +1,307 @@ +'use strict'; + +// RxNorm RRF release -> a terminology file (tx/importers/sqlite-v2/schema.sql). The selection and +// display rules follow cs-rxnorm.js; where each fact goes: +// concepts every RXCUI with an SAB=RXNORM atom in RXNCONSO, inactive when its display atom is +// SUPPRESS = O; RXCUIs only in RXNATOMARCHIVE (SAB=RXNORM) inactive, no SUPPRESS. +// concept.display (derived): the first non-SY atom by PSN, ET, TMSY rank, else the code. +// items every SAB=RXNORM atom of RXNCONSO (all of them, duplicates of a text included): +// external_id = RXAUI, use = its TTY (item_use system = RxNorm), en-US, active. +// Archived concepts: their RXNATOMARCHIVE atoms, active = 0. +// literals on the concept, as served: TTY (each TTY of its RXNORM atoms), SAB (each source +// with an atom for it), SUPPRESS (each flag of its RXNORM atoms), STY (RXNSTY TUI). +// links RXNREL SAB=RXNORM rows between concepts: one link under the RELA property, +// subject = RXCUI2, target = RXCUI1 (a row with no RELA: under `@REL`, a member of the REL). +// catalog TTY, SAB, SUPPRESS, STY literal properties; one link property per RELA +// (wildcard = 1) and per REL (wildcard = 0) that RXNREL names, from any source and +// at any level - those without concept-level RXNORM rows have n_rows = 0 (a name a +// filter may use that selects nothing). A REL is the union (property_member) of the +// RELAs its rows carry. A RELA whose rows carry more than one REL is also +// stored under `RELA@REL` properties (wildcard = 0), one per REL, which are the +// REL's members instead, so a REL's union is exact. +// atom rows with atomRelationships (optional, off by default): every RXNREL atom-level row +// (STYPE AUI, any source), as cs-rxnorm.js reads them for a REL / RELA = AUI: +// filter: one identifier statement value RXAUI1 -> the concept owning RXAUI2 (its +// RXCUI in RXNCONSO, any source; rows whose concept is not served are left out), +// under one catalog row per (REL, RELA) pair `AUI::` (shape identifier, +// filterable 0); `AUI:` and `AUI:` are unions of the pairs. No item is +// needed for another source's atom: the value is the RXAUI. +// not imported other sources' atoms, RXNSAT, archive atoms of live concepts (as the built-in +// provider). +// order concepts by (primary TTY rank, ingredient group): the numbering's sort key. + +const fs = require('fs'); +const path = require('path'); +const { BaseTerminologyModule } = require('./tx-import-base'); +const { TerminologyBuilder } = require('./sqlite-v2/builder'); +const { lines } = require('./sqlite-v2/text'); + +const RXNORM = 'http://www.nlm.nih.gov/research/umls/rxnorm'; +const TTY_RANK = ['IN', 'PIN', 'MIN', 'BN', 'DF', 'DFG', 'SCDC', 'SCDF', 'SCDFP', 'SCDG', 'SCDGP', 'SCD', + 'SBDC', 'SBDF', 'SBDFP', 'SBDG', 'SBD', 'GPCK', 'BPCK', 'PSN', 'SY', 'TMSY', 'ET']; +const DISPLAY_RANK = { PSN: 1, ET: 2, TMSY: 3, SY: 4 }; +const TOWARDS_INGREDIENT = new Set(['has_ingredient', 'has_precise_ingredient', 'has_ingredients', 'tradename_of', + 'consists_of', 'isa', 'has_part', 'contains', 'form_of', 'quantified_form_of']); + +async function* rrf(file) { + for await (const l of lines(file)) if (l) yield l.split('|'); +} + +/** @param {object} cfg { source (rrf dir), dest, version (MMDDYYYY), overwrite, log, atomRelationships } */ +async function importRxNormV2(cfg) { + const log = cfg.log || console.log; + const f = (n) => path.join(cfg.source, n); + for (const n of ['RXNCONSO.RRF', 'RXNREL.RRF', 'RXNSTY.RRF']) if (!fs.existsSync(f(n))) throw new Error(`missing ${f(n)}`); + const b = new TerminologyBuilder(cfg.dest, { overwrite: cfg.overwrite, log, importer: 'rxnorm-v2' }); + for (const n of ['RXNCONSO.RRF', 'RXNREL.RRF', 'RXNSTY.RRF', 'RXNATOMARCHIVE.RRF']) if (fs.existsSync(f(n))) b.addSource(f(n)); + const v = cfg.version; + b.codeSystem({ uri: RXNORM, version: v, name: 'RxNorm', title: 'RxNorm', + releaseDate: /^\d{8}$/.test(v) ? `${v.slice(4)}-${v.slice(0, 2)}-${v.slice(2, 4)}` : null, + description: 'RxNorm normalized drug nomenclature (U.S. National Library of Medicine)', + caseSensitive: true, defaultLanguage: 'en-US' }); + // as cs-rxnorm.js presents it: by RXCUI as text (the stored order), each atom text once, no + // designation uses, versions by date + b.setBehaviour('expansionOrder', 'stored'); + b.setBehaviour('distinctDesignationTexts', true); + b.setBehaviour('designationUses', 'drop'); + b.setBehaviour('versionAlgorithm', 'date'); + // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships + const EQ_IN = ['=', 'in']; + + const lit = (code, display, extra = {}) => b.property({ code, uri: `${RXNORM}/${code}`, shape: 'literal', fhirType: 'code', display, filterOps: EQ_IN, ...extra }); + // SUPPRESS is no filter name (cs-rxnorm.js filters TTY, STY, SAB): its has-property set is the + // RXNCONSO concepts (the live domain), and it has no property = value sets + const TTY = lit('TTY', 'Term Type'), SAB = lit('SAB', 'Source'), SUPPRESS = lit('SUPPRESS', 'Suppress flag', { filterable: false, filterOps: null }), + STY = lit('STY', 'Semantic Type (TUI)'); + const useOf = new Map(); + const use = (tty) => { let u = useOf.get(tty); if (u === undefined) useOf.set(tty, u = b.use({ system: RXNORM, code: tty || 'unknown', display: tty || null })); return u; }; + const rank = new Map(); + const stats = { archivedConcepts: 0, relSkipped: 0, atomStatements: 0, atomRowsSkipped: 0 }; + const atomCui = cfg.atomRelationships ? new Map() : null; // RXAUI -> RXCUI, every source's atom + + // RXNCONSO: RXCUI|LAT|TS|LUI|STT|SUI|ISPREF|RXAUI|SAUI|SCUI|SDUI|SAB|TTY|CODE|STR|SRL|SUPPRESS|CVF + const sabs = []; + await b.stage('parse RXNCONSO', async () => { + let n = 0; + const shown = new Map(); // concept -> [rank, SUPPRESS] of its display atom so far + for await (const c of rrf(f('RXNCONSO.RRF'))) { + const cui = c[0], aui = c[7], sab = c[11], tty = c[12], str = c[14].trim(), sup = c[16]; + if (atomCui) atomCui.set(aui, cui); + if (sab !== 'RXNORM') { + sabs.push(cui, sab); + continue; + } + const i = b.concept(cui); + if (tty !== 'SY') { + const cur = shown.get(i), dr = DISPLAY_RANK[tty] || 0; + if (!cur || dr < cur[0]) { b.setDisplay(i, str); shown.set(i, [dr, sup]); } + } + b.item(i, { externalId: aui, language: 'en-US', use: use(tty), text: str, active: true }); + b.literal(i, TTY, tty); + b.literal(i, SUPPRESS, sup); + const r = TTY_RANK.indexOf(tty); + const rr = r < 0 ? TTY_RANK.length : r; + if (!rank.has(i) || rr < rank.get(i)) rank.set(i, rr); + n++; + } + stats.obsoleteConcepts = 0; + for (const [i, [, sup]] of shown) if (sup === 'O') { b.setActive(i, false); stats.obsoleteConcepts++; } + shown.clear(); + const sabSeen = new Set(); + for (let i = 0; i < b.codes.length; i++) { b.literal(i, SAB, 'RXNORM'); if (b.display[i] === null) b.setDisplay(i, b.codes[i]); } + for (let k = 0; k < sabs.length; k += 2) { + const i = b.idx(sabs[k]); + if (i === undefined || sabs[k + 1] === 'RXNORM') continue; + const key = `${i}|${sabs[k + 1]}`; + if (!sabSeen.has(key)) { sabSeen.add(key); b.literal(i, SAB, sabs[k + 1]); } + } + sabs.length = 0; + return n; + }); + + // RXNATOMARCHIVE: RXAUI|AUI|STR|ARCHIVE_TIMESTAMP|CREATED_TIMESTAMP|UPDATED_TIMESTAMP|CODE|IS_BRAND|LAT| + // LAST_RELEASED|SAUI|VSAB|RXCUI|SAB|TTY|MERGED_TO_RXCUI + if (fs.existsSync(f('RXNATOMARCHIVE.RRF'))) { + await b.stage('parse RXNATOMARCHIVE', async () => { + const live = b.codes.length; + const archShown = new Map(); + let n = 0; + for await (const c of rrf(f('RXNATOMARCHIVE.RRF'))) { + const cui = c[12], sab = c[13], tty = c[14], str = c[2].trim(); + if (sab !== 'RXNORM' || !cui) continue; + const known = b.idx(cui); + if (known !== undefined && known < live) continue; // still live: archive atoms are history (not imported) + const i = b.concept(cui, { active: false }); + if (tty !== 'SY') { + const dr = DISPLAY_RANK[tty] || 0, cur = archShown.get(i); + if (cur === undefined || dr < cur) { archShown.set(i, dr); b.setDisplay(i, str); } + } + b.item(i, { externalId: c[0], language: 'en-US', use: use(tty), text: str, active: false }); + n++; + } + for (let i = live; i < b.codes.length; i++) if (b.display[i] === null) b.setDisplay(i, b.codes[i]); + stats.archivedConcepts = b.codes.length - live; + return n; + }); + } + + // RXNSTY: RXCUI|TUI|STN|STY|ATUI|CVF + await b.stage('parse RXNSTY', async () => { + let n = 0; + for await (const c of rrf(f('RXNSTY.RRF'))) { + const i = b.idx(c[0]); + if (i !== undefined && c[1]) { b.literal(i, STY, c[1]); n++; } + } + return n; + }); + + // RXNREL: RXCUI1|RXAUI1|STYPE1|REL|RXCUI2|RXAUI2|STYPE2|RELA|RUI|SRUI|SAB|SL|DIR|RG|SUPPRESS|CVF + const relProp = (rel) => b.property({ code: rel, uri: `${RXNORM}/${rel}`, shape: 'link', display: rel, wildcard: false, filterOps: EQ_IN }); + const relaProp = (rela) => b.property({ code: rela, uri: `${RXNORM}/${rela}`, shape: 'link', display: rela, wildcard: true, filterOps: EQ_IN }); + // a REL's rows with no RELA (atom-level SY rows): their own property `@REL`, one of the REL's + // members, so that a REL is a union whether or not its other rows carry RELAs + const noRelaOf = new Map(); + const noRela = (rel) => { + let p = noRelaOf.get(rel); + if (p === undefined) { + p = b.property({ code: `@${rel}`, uri: `${RXNORM}/${rel}`, shape: 'link', display: `${rel} (no RELA)`, wildcard: false, filterable: false }); + b.propertyMember(relProp(rel), p); + noRelaOf.set(rel, p); + } + return p; + }; + // atom-level rows: value RXAUI1 -> the concept of RXAUI2, one statement per row under its + // (REL, RELA) pair; AUI: and AUI: are the unions a filter reads + const atomUnion = new Map(); + const atomUnionOf = (name) => { + let u = atomUnion.get(name); + if (u === undefined) { + u = b.property({ code: `AUI:${name}`, uri: `${RXNORM}/${name}`, shape: 'union', display: `${name}, atom-level rows`, filterable: false }); + atomUnion.set(name, u); + } + return u; + }; + const atomPair = new Map(); + const atomProp = (rel, rela) => { + const code = `AUI:${rel}:${rela}`; + let p = atomPair.get(code); + if (p === undefined) { + // read by value only (a filter's RXAUI): no by-subject index + p = b.property({ code, uri: `${RXNORM}/${rela || rel}`, shape: 'identifier', bySubject: false, + display: `${rel} ${rela}, atom-level rows (RXAUI1 -> the concept of RXAUI2)`, filterable: false }); + if (rel) b.propertyMember(atomUnionOf(rel), p); + if (rela) b.propertyMember(atomUnionOf(rela), p); + atomPair.set(code, p); + } + return p; + }; + const towards = []; + const names = { rel: new Set(), rela: new Set() }; + const relsOf = new Map(); // RELA -> the RELs its concept-level RXNORM rows carry + const relRows = []; // (subject, target, RELA property, REL) per link, for the RELA@REL split + await b.stage('parse RXNREL', async () => { + let n = 0; + for await (const c of rrf(f('RXNREL.RRF'))) { + const rel = c[3], rela = c[7]; + if (rel) names.rel.add(rel); + if (rela) names.rela.add(rela); + if (c[2] === 'AUI' || c[6] === 'AUI') { + // an atom-level row (any source): with atomRelationships, value RXAUI1 -> RXAUI2's concept + if (!atomCui || !c[1] || !c[5]) continue; + const subject = b.idx(atomCui.get(c[5])); + if (subject === undefined) { stats.atomRowsSkipped++; continue; } + b.identifier(atomProp(rel, rela), c[1], subject); + stats.atomStatements++; + continue; + } + if (c[10] !== 'RXNORM' || !c[0] || !c[4]) continue; + const t = b.idx(c[0]), s = b.idx(c[4]); + if (s === undefined || t === undefined) { stats.relSkipped++; continue; } + if (rela) { + const p = relaProp(rela); + b.link(s, p, t); + if (rel) { + let r = relsOf.get(rela); + if (!r) relsOf.set(rela, r = new Set()); + r.add(rel); + relRows.push(s, t, p, rel); + } + } else if (rel) b.link(s, noRela(rel), t); // a row with no RELA: under `@REL`, a member of the REL + if (TOWARDS_INGREDIENT.has(rela) && s >= 0 && t >= 0) towards.push(s, t); + n++; + } + // a RELA under several RELs: its rows again under RELA@REL, the REL's member instead of the RELA + const split = new Map(); + for (const [rela, rels] of relsOf) if (rels.size > 1) split.set(relaProp(rela), rela); + const qualified = new Map(); + for (let k = 0; k < relRows.length; k += 4) { + const rela = split.get(relRows[k + 2]); + if (rela === undefined) continue; + const rel = relRows[k + 3], code = `${rela}@${rel}`; + let q = qualified.get(code); + if (q === undefined) { + // (a member of one REL's union only: no filter names it, cs-rxnorm.js knows no such name) + q = b.property({ code, uri: `${RXNORM}/${rela}`, shape: 'link', display: `${rela} (REL ${rel})`, wildcard: false, filterable: false }); + qualified.set(code, q); + } + b.link(relRows[k], q, relRows[k + 1]); + stats.relQualifiedLinks = (stats.relQualifiedLinks || 0) + 1; + } + relRows.length = 0; + for (const [rela, rels] of relsOf) { + for (const rel of rels) b.propertyMember(relProp(rel), rels.size > 1 ? b.propertyId(`${rela}@${rel}`) : relaProp(rela)); + } + stats.relQualifiedProperties = [...qualified.keys()].sort(); + // the names RXNREL has without concept-level RXNORM rows: catalog rows with no rows + for (const rela of names.rela) relaProp(rela); + for (const rel of names.rel) relProp(rel); + return n; + }); + + await b.stage('ordering keys', async () => { + const n = b.codes.length; + const NONE = 1e6; + const group = new Float64Array(n).fill(NONE); + const ings = []; + for (const [i, r] of rank) if (r <= 2) ings.push(i); + ings.sort((x, y) => (b.codes[x].length - b.codes[y].length) || (b.codes[x] < b.codes[y] ? -1 : 1)); + ings.forEach((i, k) => { group[i] = k; }); + for (let round = 0; round < 20; round++) { + let changed = 0; + for (let k = 0; k < towards.length; k += 2) { + const s = towards[k], t = towards[k + 1]; + if ((rank.get(s) ?? 99) <= 2) continue; + if (group[t] < group[s]) { group[s] = group[t]; changed++; } + } + if (!changed) break; + } + for (let i = 0; i < n; i++) b.setSortKey(i, (rank.get(i) ?? TTY_RANK.length) * 2e6 + group[i]); + towards.length = 0; + return n; + }); + + return b.finish(stats); +} + +class RxNormV2Module extends BaseTerminologyModule { + getName() { return 'rxnorm-v2'; } + getDescription() { return 'RxNorm RRF -> SQLite terminology file (sqlite-v2 provider)'; } + getSupportedFormats() { return ['directory']; } + + registerCommands(cmd) { + cmd.command('import') + .description('Import an unzipped RxNorm full release (rrf folder) into a terminology file') + .requiredOption('-s, --source ', 'the rrf/ folder of the release') + .requiredOption('-d, --dest ', 'destination .db') + .requiredOption('-v, --rxnorm-version ', 'e.g. 03022026') + .option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI: filters (otherwise refused)') + .option('--overwrite', 'replace the destination') + .action(async (o) => { + const s = await importRxNormV2({ source: o.source, dest: o.dest, version: o.rxnormVersion, + overwrite: !!o.overwrite, atomRelationships: !!o.atomRelationships, log: (m) => this.logInfo(m) }); + this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); + }); + } +} + +module.exports = { RxNormV2Module, importRxNormV2 }; diff --git a/tx/importers/import-sct-v2-cache.module.js b/tx/importers/import-sct-v2-cache.module.js new file mode 100644 index 00000000..cf0cef6b --- /dev/null +++ b/tx/importers/import-sct-v2-cache.module.js @@ -0,0 +1,395 @@ +'use strict'; + +// FHIRsmith SNOMED CT cache (*.cache, tx/sct/structures.js) -> a terminology file ("reverse loader"), +// for the editions we can only get as tx.fhir.org's binary caches. Cache decoding only; where each +// fact goes is the shared stage (sct-v2-common.js SnomedSink), as for RF2: +// concepts active (status nibble), module, definition status (primitive flag), effectiveTime +// descriptions every description record (incl. text definitions), active and inactive, language +// from the cache's language byte +// relationships every relationship record, active and inactive, in record order +// concrete values cache v19 and later (active inferred rows) +// identifiers cache v18 and later (active rows) +// refsets language refsets (members referencing descriptions, refset under 900000000000506000); +// every other refset's members, on concepts or on descriptions +// What the cache does not carry (inactive refset members, map refsets, concrete values before v19, +// ...) is not in the file either. Dates: 'auto' adds a day to caches built east of UTC (upstream +// b082f98); known defects of older cache vintages stop the import unless forced. + +const path = require('path'); +const { BaseTerminologyModule } = require('./tx-import-base'); +const { + SnomedStrings, SnomedReferences, SnomedDescriptions, SnomedConceptList, SnomedRelationshipList, + SnomedReferenceSetMembers, SnomedReferenceSetIndex, +} = require('../sct/structures'); +const { SnomedFileReader, SNOMED_CACHE_VERSION } = require('../sct/structures'); +const { isoDate, displayRefsetsFor, checkDisplayRefsets, concrete, SnomedSink, SCT } = require('./sct-v2-common'); +const { editionName } = require('../sct/editions'); + +const LANGUAGE_TYPE_REFSET = '900000000000506000'; +const PRIMITIVE = '900000000000074008'; +const DEFINED = '900000000000073002'; +// the cache's language byte -> ISO 639-1 code: main's one table (tx/sct/languages.js; before cache +// format 20 only 1-9 were written, anything else as 1) +const { LANGUAGE_CODES: LANGUAGE } = require('../sct/languages'); +const DAY = 86400000; +const PASCAL_EPOCH = Date.UTC(1899, 11, 30); + +function view(Cls, buf, ...args) { + const o = new Cls(null, ...args); + o.master = buf; // a view on the file buffer: no copy + return o; +} + +/** + * The cache's default description language (a language byte). The current format (21): as main's + * server resolves its slot. An older format (main's server no longer reads them, but this importer + * does): as main's server read it, up to 1.0.4 - a language byte (only 1-9 before format 20), else + * the membersByRef offset of the edition's default language reference set (the original server's + * caches), read as the language most of that reference set's descriptions are in; else English. + */ +function cacheDefaultLanguage(d) { + if (d.cacheVersion === SNOMED_CACHE_VERSION) { + const { SnomedServices } = require('../cs/cs-snomed'); + return new SnomedServices(d).defaultLanguage; + } + const slot = d.defaultLanguage; + const maxByte = parseInt(d.cacheVersion, 10) >= 20 ? 255 : 9; + if (slot <= maxByte && LANGUAGE[slot]) return slot; + const rsIndex = view(SnomedReferenceSetIndex, d.refSetIndex, d.hasLangs); + const rsMembers = view(SnomedReferenceSetMembers, d.refSetMembers); + const descs = view(SnomedDescriptions, d.desc); + for (let i = 0; i < rsIndex.count(); i++) { + if (rsIndex.getReferenceSet(i).membersByRef !== slot) continue; + let best = 1, most = 0; + for (const [lang, n] of rsMembers.descriptionLanguages(slot, descs)) { + if (LANGUAGE[lang] && n > most) { best = lang; most = n; } + } + return best; + } + return 1; +} + +// The cache formats before 21 this importer still reads. Main's server reads only the current +// format (1.0.5); an edition whose release is not at hand may only exist as an older cache. +const OLDER_FORMATS = ['16', '17', '18', '19', '20']; + +/** + * A cache's sections, as SnomedFileReader.loadSnomedData returns them: from main's reader for the + * current format; for an older one, read here in its layout (the words and stems sections, which + * nothing read, are skipped; no license, no text indexes). + * @param {string} file + */ +async function readCache(file) { + if (SnomedFileReader.isCurrent(file)) return new SnomedFileReader(file).loadSnomedData(); + const r = new SnomedFileReader(file); + await r.load(); + const cacheVersion = r.readString(); + if (!OLDER_FORMATS.includes(cacheVersion)) { + throw new Error(`${path.basename(file)}: SNOMED CT cache format ${cacheVersion} is not one this importer reads (${[...OLDER_FORMATS, SNOMED_CACHE_VERSION].join(', ')})`); + } + const v = parseInt(cacheVersion, 10); + const d = { cacheVersion, versionUri: r.readString(), versionDate: r.readString(), hasLangs: v >= 17, license: null, textIndexes: null }; + d.isTesting = d.versionUri.includes('/xsct/'); + const parts = d.versionUri.split('/'); + if (parts.length >= 7) { d.edition = parts[4]; d.version = parts[6]; } + d.strings = r.readBytes(); + d.refs = r.readBytes(); + d.desc = r.readBytes(); + r.readBytes(); // words + r.readBytes(); // stems + d.concept = r.readBytes(); + d.rel = r.readBytes(); + d.refSetIndex = r.readBytes(); + d.refSetMembers = r.readBytes(); + d.descRef = r.readBytes(); + d.isAIndex = r.readInteger(); + d.inactiveRoots = []; + for (let i = r.readInteger(); i > 0; i--) d.inactiveRoots.push(r.readUInt64()); + d.activeRoots = []; + for (let i = r.readInteger(); i > 0; i--) d.activeRoots.push(r.readUInt64()); + d.defaultLanguage = r.readInteger(); + d.identifiers = v >= 18 ? JSON.parse(r.readBytes().toString('utf8')) : []; + d.concreteValues = v >= 19 ? JSON.parse(r.readBytes().toString('utf8')) : null; + return d; +} + +/** days since 1899-12-30 -> YYYYMMDD */ +function sctDate(days) { + if (!days) return null; + return new Date(PASCAL_EPOCH + days * DAY).toISOString().slice(0, 10).replace(/-/g, ''); +} + +/** @param {object} cfg { source (.cache), dest, overwrite, dateShift ('auto' | days), force, log, normalForms } */ +async function importSnomedV2FromCache(cfg) { + const log = cfg.log || console.log; + const t0 = Date.now(); + const d = await readCache(cfg.source); + log(`cache v${d.cacheVersion} ${d.versionUri} loaded in ${((Date.now() - t0) / 1000).toFixed(1)} s`); + + const strings = view(SnomedStrings, d.strings); + const refs = view(SnomedReferences, d.refs); + const descs = view(SnomedDescriptions, d.desc); + const concepts = view(SnomedConceptList, d.concept); + const rels = view(SnomedRelationshipList, d.rel); + const rsIndex = view(SnomedReferenceSetIndex, d.refSetIndex, d.hasLangs); + const rsMembers = view(SnomedReferenceSetMembers, d.refSetMembers); + const C = SnomedConceptList.CONCEPT_SIZE, D = SnomedDescriptions.DESC_SIZE, R = SnomedRelationshipList.RELATIONSHIP_SIZE; + const nC = concepts.count(), nD = descs.count(), nR = rels.count(); + const cbuf = concepts.master, dbuf = descs.master, rbuf = rels.master; + const getRefs = (i) => (i ? refs.getReferences(i) : null) || []; + + const m = /^http:\/\/snomed\.info\/x?sct\/(\d+)\/version\/(\d{8})$/.exec(d.versionUri); + if (!m) throw new Error(`unexpected version URI ${d.versionUri}`); + const [, edition, version] = m; + + const code = new Array(nC); + for (let k = 0; k < nC; k++) code[k] = cbuf.readBigUInt64LE(k * C).toString(); + const ord = (offset) => { + if (offset % C !== 0 || offset >= cbuf.length) throw new Error(`bad concept offset ${offset}`); + return offset / C; + }; + const ordOf = new Map(); + for (let k = 0; k < nC; k++) ordOf.set(code[k], k); + const known = (c) => ordOf.get(c); + const descId = (k) => dbuf.readBigUInt64LE(k * D + 5).toString(); + + // dates ('auto': +1 day for caches built east of UTC before upstream b082f98) + let shift = 0; + { + const rel = Math.round((Date.UTC(+version.slice(0, 4), +version.slice(4, 6) - 1, +version.slice(6, 8)) - PASCAL_EPOCH) / DAY); + let onRelease = 0, dayBefore = 0; + for (let k = 0; k < nC; k++) { + const t = cbuf.readUInt16LE(k * C + 34); + if (t === rel) onRelease++; else if (t === rel - 1) dayBefore++; + } + if (cfg.dateShift === undefined || cfg.dateShift === 'auto') shift = onRelease === 0 && dayBefore > 0 ? 1 : 0; + else shift = Number(cfg.dateShift) || 0; + log(`dates: ${onRelease} concepts on the release date, ${dayBefore} the day before -> shift ${shift} day(s)`); + } + const date = (days) => (days ? sctDate(days + shift) : null); + + const refsets = []; + for (let k = 0; k < rsIndex.count(); k++) refsets.push(rsIndex.getReferenceSet(k)); + // the known defects of older cache vintages (fatal unless cfg.force), and warnings + const warnings = []; + { + const fatal = []; + let noModule = 0, primitive = 0; + for (let k = 0; k < nC; k++) { + if (!cbuf.readUInt32LE(k * C + 36)) noModule++; + if (cbuf.readUInt8(k * C + 8) & SnomedConceptList.MASK_CONCEPT_PRIMITIVE) primitive++; + } + if (noModule > nC / 100) fatal.push(`${noModule} of ${nC} concepts have no module`); + if (primitive === 0) fatal.push('no concept is primitive (definition status lost)'); + const defs = new Map(), members = new Map(); + for (const e of refsets) { + defs.set(e.definition, (defs.get(e.definition) || 0) + 1); + members.set(e.definition, (members.get(e.definition) || 0) + rsMembers.getMemberCount(e.membersByRef)); + } + const dup = [...defs].filter(([, n]) => n > 1); + if (dup.length) fatal.push(`refset index names ${dup.map(([o, n]) => `${code[o / C]} x${n}`).join(', ')} (refsets collapsed onto one concept)`); + const shown = checkDisplayRefsets(edition, displayRefsetsFor(edition).filter((r) => known(r) !== undefined), + (r) => members.get(known(r) * C), nC); + fatal.push(...shown.fatal); + warnings.push(...shown.warnings); + if (shift) warnings.push(`dates shifted by ${shift} day(s) (cache built east of UTC before upstream b082f98)`); + if (!(d.concreteValues || []).length) warnings.push(`no concrete values (cache v${d.cacheVersion}; carried from v19)`); + warnings.push(...fatal); + for (const w of warnings) log(`WARNING: ${w}`); + if (cfg.inspectOnly) return { inspectOnly: true, cacheVersion: d.cacheVersion, versionUri: d.versionUri, shift, fatal, warnings, + counts: { concepts: nC, descriptions: nD, relationships: nR, refsets: refsets.length } }; + if (fatal.length && !cfg.force) throw new Error(`${path.basename(cfg.source)}: defective cache (${fatal.join('; ')}); use --force to import anyway`); + } + + const displayRefsets = displayRefsetsFor(edition).filter((c) => known(c) !== undefined); + const defByte = cacheDefaultLanguage(d); + const name = (editionName(edition) ? `SNOMED CT ${editionName(edition)}` : `SNOMED CT edition ${edition}`); + const sink = new SnomedSink({ + dest: cfg.dest, overwrite: cfg.overwrite, log, importer: 'sct-v2-from-cache', edition, + codeSystem: { uri: SCT, version: d.versionUri, name, title: name, releaseDate: isoDate(version), + description: `SNOMED CT edition ${edition} version ${version}, from FHIRsmith cache v${d.cacheVersion} (${path.basename(cfg.source)})`, + // the cache's default-language slot (cacheDefaultLanguage; en-US for English) + defaultLanguage: defByte !== 1 && LANGUAGE[defByte] ? LANGUAGE[defByte] : 'en-US' }, + // the description flag `preferred` = Preferred in the first display refset + displayRefsets, preferredRefset: displayRefsets[0], normalForms: cfg.normalForms, + }); + sink.b.addSource(cfg.source); + sink.b.setMeta('provenance.sourceFormat', `fhirsmith-cache-v${d.cacheVersion}`); + const stats = { cacheVersion: d.cacheVersion, dateShiftDays: shift, cacheWarnings: warnings, conceptsWithoutModule: 0, unknownFieldValues: 0, refsetsWithoutConcept: 0, otherRefsetRowsSkipped: 0, languageRefsets: [] }; + + await sink.stage('decode concepts', async () => { + for (let k = 0; k < nC; k++) { + const flags = cbuf.readUInt8(k * C + 8); + const i = sink.concept(code[k], (flags & SnomedConceptList.MASK_CONCEPT_STATUS) === 0); + if (i !== k) throw new Error(`duplicate concept ${code[k]} in cache`); + } + const prim = known(PRIMITIVE), defd = known(DEFINED); + for (let k = 0; k < nC; k++) { + const o = k * C; + const mod = cbuf.readUInt32LE(o + 36); + if (!mod) stats.conceptsWithoutModule++; + const ds = (cbuf.readUInt8(o + 8) & SnomedConceptList.MASK_CONCEPT_PRIMITIVE) ? prim : defd; + const t = date(cbuf.readUInt16LE(o + 34)); + sink.conceptMeta(k, mod ? ord(mod) : undefined, ds, t ? isoDate(t) : null); + } + return nC; + }); + + const langRoot = known(LANGUAGE_TYPE_REFSET); + const isLanguageRefset = (k) => { + const seen = new Set(); + const stack = [k]; + while (stack.length) { + const x = stack.pop(); + if (x === langRoot) return true; + if (seen.has(x)) continue; + seen.add(x); + for (const p of getRefs(cbuf.readUInt32LE(x * C + 9))) stack.push(ord(p)); + } + return false; + }; + + // a member's extra field values as RF2 text (component ids as SCTIDs) + const fieldValues = (valuesRef) => { + const v = getRefs(valuesRef); + const out = []; + for (let j = 0; j + 1 < v.length; j += 2) { + const val = v[j], type = v[j + 1]; + switch (type) { + case 1: out.push(val > 0 && val % C === 0 && val < cbuf.length ? code[val / C] : (stats.unknownFieldValues++, '')); break; + case 2: out.push(dbuf.readBigUInt64LE(val + 5).toString()); break; + case 4: out.push(String(val | 0)); break; + case 5: out.push(strings.getEntry(val)); break; + default: stats.unknownFieldValues++; out.push(''); + } + } + return out; + }; + + const langs = new Set(); + await sink.stage('decode language refsets', async () => { + let n = 0; + for (const e of refsets) { + const r = e.definition / C; + const members = rsMembers.getMembers(e.membersByRef) || []; + if (!members.some((x) => x.kind === 1) || !isLanguageRefset(r)) continue; + stats.languageRefsets.push(code[r]); + langs.add(code[r]); + for (const x of members) { + if (x.kind !== 1) continue; + const acc = getRefs(x.values); + if (acc.length < 2 || acc[1] !== 1) continue; + sink.languageMember(descId(x.ref / D), code[r], code[acc[0] / C]); + n++; + } + } + return n; + }); + + await sink.stage('decode descriptions', async () => { + for (let k = 0; k < nD; k++) { + const o = k * D; + const id = descId(k); + sink.description({ key: id, id, concept: ord(dbuf.readUInt32LE(o + 13)), language: LANGUAGE[dbuf.readUInt8(o + 31)] || 'en', + type: code[ord(dbuf.readUInt32LE(o + 21))], term: strings.getEntry(dbuf.readUInt32LE(o)), active: dbuf.readUInt8(o + 4) !== 0 }); + } + sink.descriptionsDone(); + return nD; + }); + + // concrete-value attribute types (of known concepts), with the literal type of each type's first value + const concreteTypes = new Map(); + for (const [src, type, , raw] of d.concreteValues || []) { + if (known(String(src)) !== undefined && !concreteTypes.has(String(type))) concreteTypes.set(String(type), concrete(String(raw)).fhirType); + } + sink.setConcreteTypes(concreteTypes); + await sink.stage('decode relationships', async () => { + for (let k = 0; k < nR; k++) { + const o = k * R; + sink.relationship(ord(rbuf.readUInt32LE(o)), ord(rbuf.readUInt32LE(o + 4)), code[ord(rbuf.readUInt32LE(o + 8))], + rbuf.readInt32LE(o + 28) || 0, rbuf.readUInt8(o + 26) !== 0); + } + return nR; + }); + await sink.stage('decode concrete values', async () => { + let n = 0; + for (const [src, type, group, raw] of d.concreteValues || []) { + sink.concreteValue(known(String(src)), String(type), Number(group) || 0, String(raw)); + n++; + } + sink.concreteDone(); + return n; + }); + + await sink.stage('decode identifiers', async () => { + for (const [scheme, , id, concept] of d.identifiers || []) sink.identifier(String(scheme), String(id), String(concept)); + return (d.identifiers || []).length; + }); + + await sink.stage('decode refsets', async () => { + let n = 0; + for (const e of refsets) { + const r = e.definition / C; + let rname = ''; + try { rname = strings.getEntry(e.name) || ''; } catch (err) { rname = ''; } + if (code[r] === '900000000000534007' || rname.startsWith('ModuleDependency')) { + for (const x of rsMembers.getMembers(e.membersByRef) || []) { + if (x.kind !== 0 || x.module == null) continue; + const f = fieldValues(x.values); + sink.moduleDependency([code[ord(x.module)], code[ord(x.ref)], f[0] || null, f[1] || null]); + n++; + } + continue; + } + if (langs.has(code[r])) continue; + if (r === 0) { stats.refsetsWithoutConcept++; continue; } + const types = getRefs(e.fieldTypes).map((t) => String.fromCharCode(t)); + const names = getRefs(e.fieldNames).map((s) => strings.getEntry(s)); + const def = { names: names.length === types.length ? names : types.map((t, j) => `field${j + 1}`), types }; + for (const x of rsMembers.getMembers(e.membersByRef) || []) { + if (x.kind !== 0 && x.kind !== 1) { stats.otherRefsetRowsSkipped++; continue; } + const ref = x.kind === 0 ? code[ord(x.ref)] : descId(x.ref / D); + const meta = { time: x.date != null ? date(x.date) : null, module: x.module != null ? code[ord(x.module)] : null }; + sink.refsetMember(code[r], ref, def, types.length ? fieldValues(x.values) : null, meta, x.kind === 1); + n++; + } + } + return n; + }); + + log(`default language: slot ${d.defaultLanguage} -> ${LANGUAGE[defByte] || 'en'}`); + return sink.finish(stats); +} + +class SnomedV2FromCacheModule extends BaseTerminologyModule { + getName() { return 'snomed-v2-from-cache'; } + getDescription() { return 'FHIRsmith SNOMED CT .cache -> SQLite terminology file (sqlite-v2 provider), for editions without RF2'; } + getSupportedFormats() { return ['file']; } + + registerCommands(cmd) { + cmd.command('import') + .description('Reverse-load a FHIRsmith SNOMED CT cache (*.cache) into a terminology file') + .requiredOption('-s, --source ', 'the .cache file') + .requiredOption('-d, --dest ', 'destination .db') + .option('--date-shift ', 'days to add to every cache date (auto: fix caches built east of UTC)', 'auto') + .option('--overwrite', 'replace the destination') + .option('--force', 'import a cache with known defects (see the warnings)') + .action(async (o) => { + const s = await importSnomedV2FromCache({ source: o.source, dest: o.dest, overwrite: !!o.overwrite, + dateShift: o.dateShift, force: !!o.force, log: (msg) => this.logInfo(msg) }); + this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); + }); + cmd.command('inspect') + .description('Check FHIRsmith SNOMED CT caches for the known defects of older cache vintages (no import)') + .argument('', '.cache files') + .action(async (files) => { + for (const f of files) { + const s = await importSnomedV2FromCache({ source: f, inspectOnly: true, log: () => {} }); + console.log(JSON.stringify({ file: path.basename(f), version: s.cacheVersion, uri: s.versionUri, + shift: s.shift, fatal: s.fatal, warnings: s.warnings.filter((w) => !s.fatal.includes(w)), counts: s.counts })); + } + }); + } +} + +module.exports = { SnomedV2FromCacheModule, importSnomedV2FromCache, cacheDefaultLanguage, readCache, view, sctDate }; diff --git a/tx/importers/import-sct-v2.module.js b/tx/importers/import-sct-v2.module.js new file mode 100644 index 00000000..b1e65d48 --- /dev/null +++ b/tx/importers/import-sct-v2.module.js @@ -0,0 +1,173 @@ +'use strict'; + +// SNOMED CT RF2 Snapshot -> a terminology file. RF2 parsing only; where each fact goes is the shared +// stage (sct-v2-common.js SnomedSink). What is read, from the Snapshot folder: sct2_Concept, +// sct2_Description and sct2_TextDefinition (every language), sct2_Relationship (inferred; stated is +// not read), sct2_RelationshipConcreteValues (active inferred rows), sct2_Identifier, the language +// refsets and every der2_*Refset_* file under Refset/ (rows on concepts and on descriptions; the +// module dependency refset as meta moduleDependencies). + +const path = require('path'); +const { BaseTerminologyModule } = require('./tx-import-base'); +const { tsvRows, firstLine } = require('./sqlite-v2/text'); +const { + SnomedSink, discover, MODULE_DEPENDENCY, displayRefsetsFor, checkDisplayRefsets, isoDate, concrete, EDITION_NAMES, rf2DefaultLanguage, + SCT, US_ENGLISH, INFERRED, +} = require('./sct-v2-common'); + +/** @param {object} cfg { source, dest, edition, version (YYYYMMDD), versionUri, language, overwrite, log, normalForms } */ +async function importSnomedV2(cfg) { + const log = cfg.log || console.log; + const files = discover(cfg.source); + const versionUri = cfg.versionUri || `${SCT}/${cfg.edition}/version/${cfg.version}`; + const name = EDITION_NAMES[cfg.edition] || `SNOMED CT edition ${cfg.edition}`; + // the display refsets are known once the concepts are read: the sink gets them by reference + const displayRefsets = []; + const sink = new SnomedSink({ + dest: cfg.dest, overwrite: cfg.overwrite, log, importer: 'sct-v2', edition: cfg.edition, + codeSystem: { uri: SCT, version: versionUri, name, title: name, releaseDate: isoDate(cfg.version), + description: `SNOMED CT RF2 Snapshot, module ${cfg.edition}, version ${cfg.version}`, defaultLanguage: 'en-US' }, + displayRefsets, preferredRefset: US_ENGLISH, normalForms: cfg.normalForms, + }); + const b = sink.b; + for (const p of [files.concept, ...files.description, files.relationship, files.concrete, ...files.identifier, + ...files.language, ...files.refset].filter(Boolean)) b.addSource(p); + const stats = {}; + + const meta = []; + await sink.stage('parse concepts', async () => { + for await (const c of tsvRows(files.concept)) meta.push(sink.concept(c[0], c[2] === '1'), c[3], c[4], c[1]); + for (let k = 0; k < meta.length; k += 4) sink.conceptMeta(meta[k], sink.idx(meta[k + 1]), sink.idx(meta[k + 2]), isoDate(meta[k + 3])); + return meta.length / 4; + }); + const nConcepts = meta.length / 4; + meta.length = 0; + for (const c of displayRefsetsFor(cfg.edition)) if (sink.idx(c) !== undefined) displayRefsets.push(c); + // an edition without any of its display refsets lists US English + if (!displayRefsets.length) sink.displayContextsFallback = [US_ENGLISH]; + + await sink.stage('parse language refsets', async () => { + let n = 0; + for (const f of files.language) { + for await (const r of tsvRows(f)) { + if (r[2] !== '1') continue; + sink.languageMember(r[5], r[4], r[6]); + n++; + } + } + return n; + }); + // the cache importer's display refset check; a release has no defects to force past, so warnings only + { + const shown = checkDisplayRefsets(cfg.edition, displayRefsets, (r) => sink.langMembers.get(r), nConcepts); + stats.displayRefsetWarnings = [...shown.fatal, ...shown.warnings]; + for (const w of stats.displayRefsetWarnings) log(`WARNING: ${w}`); + } + + const activeLanguages = new Set(); + await sink.stage('parse descriptions', async () => { + let n = 0; + for (const f of files.description) { + for await (const r of tsvRows(f)) { + const i = sink.idx(r[4]); + if (i === undefined) continue; + const active = r[2] === '1'; + sink.description({ key: r[0], id: r[0], concept: i, language: r[5], type: r[6], term: r[7], active }); + if (active) activeLanguages.add(String(r[5] || '').toLowerCase().split('-')[0]); + n++; + } + } + sink.descriptionsDone(); + return n; + }); + + // the concrete-value attribute types (active inferred rows of known concepts), with the literal + // type of each type's first row + const concreteTypes = new Map(); + if (files.concrete) { + for await (const r of tsvRows(files.concrete)) { + if (r[2] === '1' && r[8] === INFERRED && sink.idx(r[4]) !== undefined && !concreteTypes.has(r[7])) concreteTypes.set(r[7], concrete(r[5]).fhirType); + } + } + sink.setConcreteTypes(concreteTypes); + await sink.stage('parse relationships', async () => { + let n = 0; + for await (const r of tsvRows(files.relationship)) { + sink.relationship(sink.idx(r[4]), sink.idx(r[5]), r[7], Number(r[6]) || 0, r[2] === '1'); + n++; + } + return n; + }); + await sink.stage('parse concrete values', async () => { + let n = 0; + if (files.concrete) { + for await (const r of tsvRows(files.concrete)) { + if (r[2] !== '1' || r[8] !== INFERRED) continue; + sink.concreteValue(sink.idx(r[4]), r[7], Number(r[6]) || 0, r[5]); + n++; + } + } + sink.concreteDone(); + return n; + }); + + await sink.stage('parse identifiers', async () => { + let n = 0; + for (const f of files.identifier) { + for await (const r of tsvRows(f)) { + if (r[2] !== '1') continue; + sink.identifier(r[4], r[0], r[5]); + n++; + } + } + return n; + }); + + await sink.stage('parse refsets', async () => { + let n = 0; + for (const f of files.refset) { + // der2_Refset_Snapshot...: = one letter per extra column (c, i, s) + const m = /^der2_([cis]*)Refset_/.exec(path.basename(f)); + const types = m ? m[1].split('') : []; + const names = firstLine(f).split('\t').slice(6); + const def = { names, types: types.length === names.length ? types : names.map(() => 's') }; + for await (const r of tsvRows(f)) { + if (r[2] !== '1') continue; + n++; + if (r[4] === MODULE_DEPENDENCY) { sink.moduleDependency([r[3], r[5], r[6] || null, r[7] || null]); continue; } + sink.refsetMember(r[4], r[5], def, names.length ? r.slice(6) : null, { time: r[1], module: r[3] }); + } + } + return n; + }); + + if (sink.displayContextsFallback) sink.displayRefsets.push(...sink.displayContextsFallback); + const defLang = rf2DefaultLanguage(cfg, activeLanguages); + if (defLang) b.systems[0].defaultLanguage = defLang; + return sink.finish(stats); +} + +class SnomedV2Module extends BaseTerminologyModule { + getName() { return 'snomed-v2'; } + getDescription() { return 'SNOMED CT RF2 Snapshot -> SQLite terminology file (sqlite-v2 provider)'; } + getSupportedFormats() { return ['directory']; } + + registerCommands(cmd) { + cmd.command('import') + .description('Import an RF2 Snapshot into a terminology file') + .requiredOption('-s, --source ', 'unzipped RF2 release (the Snapshot folder is used)') + .requiredOption('-d, --dest ', 'destination .db') + .requiredOption('-e, --edition ', 'edition module id') + .requiredOption('--snomed-version ', 'release date') + .option('--version-uri ', 'version URI to record') + .option('--overwrite', 'replace the destination') + .option('-l, --language ', 'default language code') + .action(async (o) => { + const s = await importSnomedV2({ source: o.source, dest: o.dest, edition: o.edition, version: o.snomedVersion, + versionUri: o.versionUri, language: o.language, overwrite: !!o.overwrite, log: (m) => this.logInfo(m) }); + this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); + }); + } +} + +module.exports = { SnomedV2Module, importSnomedV2, rf2DefaultLanguage }; diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js new file mode 100644 index 00000000..64ce70ca --- /dev/null +++ b/tx/importers/sct-v2-common.js @@ -0,0 +1,466 @@ +'use strict'; + +// SNOMED CT -> a terminology file (tx/importers/sqlite-v2/schema.sql): the RF2 reading helpers and +// everything after parsing, shared by the RF2 importer (import-sct-v2.module.js) and the cache +// importer (import-sct-v2-cache.module.js). +// +// A parser feeds a SnomedSink in this order: concepts, conceptMeta, languageMember (held until the +// descriptions), description, concreteTypes, relationship, concreteValue, identifier, +// refsetMember / moduleDependency; then finish(). Where each fact goes: +// concept code, active; display (derived: preferred synonym in the display refsets in +// order, else preferred in any language refset, else FSN, else the first active +// description; ties by description id: cs-snomed.js's rule) +// item every description and text definition (kind 1), active and inactive: +// external_id = the description SCTID, use = its type (item_use display = the type +// concept's display), language, preferred (a description Preferred in +// `preferredRefset`; a definition: the one the concept shows, its last active +// one); rank is derived by the builder from the language relations and meta +// displayContexts (synonyms: 0 Preferred in a display refset, 1 in another, 2 any other) +// link relationships (inferred, active and inactive; group_id = role group, seq = row +// order), moduleId and definitionStatusId (non-refinable); a relationship typed by +// a concrete-value attribute (UK: retired drug rows) is a link of that literal +// property, which is then shape 'both' +// literal concrete values (active inferred), effectiveTime (non-refinable) +// record every reference set: language refsets (role 'language': rows on items, +// target = acceptability), all others (rows on concepts or on descriptions, +// columns effectiveTime, moduleId, then the refset's own; the first component +// column is the target). Active rows only. +// identifier alternate identifiers (scheme = an identifier catalog row) +// catalog is-a (subsumption), attributes (refinable, wildcard), moduleId / +// definitionStatusId / effectiveTime (filterable, not refinable: named as ECL's +// concept filters name them), `child` (inverse_of is-a), one record row per +// refset, one identifier row per scheme +// code_system compositional = 1 (post-coordinated expressions are codes too, so an +// expansion is never closed) +// behaviour grammar 'snomed', expansionOrder 'stored-self-first', lookupSkipsMixedLinks +// meta edition, displayContexts ({relations: the display refsets, ordered, preferred: +// the acceptability that ranks, use: synonym}), moduleDependencies, +// derived-by-importer: normal forms (ix_key 'normalForm') and the walk (ix_order +// 'walk', reached in meta 'ix.ix_order.walk.reached'), written after the build; +// then the file is vacuumed. + +const path = require('path'); +const Database = require('better-sqlite3'); +const { TerminologyBuilder, vacuumFile, analyze } = require('./sqlite-v2/builder'); + +const MODULE_DEPENDENCY = '900000000000534007'; +const { firstLine, walk } = require('./sqlite-v2/text'); + +const SCT = 'http://snomed.info/sct'; +const IS_A = '116680003'; +const FSN = '900000000000003001'; +const SYNONYM = '900000000000013009'; +const DEFINITION = '900000000000550004'; +const PREFERRED = '900000000000548007'; +const US_ENGLISH = '900000000000509007'; +const GB_ENGLISH = '900000000000508004'; +// The edition's display language reference sets, in the order they are tried: main's table +// (tx/cs/cs-snomed.js SnomedServices._displayRefsetOrder), and its default for any other edition. +// Those the edition doesn't have are left out +const DISPLAY_REFSETS = { + '900000000000207008': [US_ENGLISH], // International + '31000003106': [US_ENGLISH], // tx-ecosystem test edition + '731000124108': [US_ENGLISH], // US + '5991000124107': [US_ENGLISH], // US (with ICD-10-CM maps) + '83821000000107': [GB_ENGLISH], // UK + '999000021000000109': [GB_ENGLISH], // UK Clinical + '32506021000036107': ['32570271000036106', GB_ENGLISH, US_ENGLISH], // Australian + '20621000087109': ['19491000087109', US_ENGLISH, GB_ENGLISH], // Canadian (English) + '21000210109': ['271000210107', GB_ENGLISH, US_ENGLISH], // New Zealand + '11000220105': ['21000220103', GB_ENGLISH, US_ENGLISH] // Irish +}; +const displayRefsetsFor = (edition) => DISPLAY_REFSETS[edition] || [US_ENGLISH, GB_ENGLISH]; + +/** + * The display language refsets an import found: `present`, the edition's display refsets that are + * concepts in it, in order; count(code), its members. The first is the one the displays and + * item.preferred come from, so for an edition with an entry of its own, that one without members + * means its language refset was lost (fatal). A fallback refset without members is a warning only: + * a national release may ship its own refset and leave the International dialects empty. + * @returns {{fatal: string[], warnings: string[]}} + */ +function checkDisplayRefsets(edition, present, count, nConcepts) { + const fatal = [], warnings = []; + present.forEach((r, k) => { + const n = count(r) || 0; + if (n === 0 && k === 0 && DISPLAY_REFSETS[edition]) fatal.push(`display language refset ${r} has no members`); + else if (n === 0) warnings.push(`display language refset ${r} has no members${k ? ' (a fallback; displays come from the refsets before it)' : ''}`); + else if (n < nConcepts / 10) warnings.push(`display language refset ${r} has only ${n} members (displays fall back to the FSN)`); + }); + return { fatal, warnings }; +} +const INFERRED = '900000000000011006'; +const EDITION_NAMES = { + '900000000000207008': 'SNOMED CT International Edition', + '731000124108': 'SNOMED CT US Edition', +}; + +// The edition's language, as main's importer has it (tx/importers/import-sct.module.js, its +// editions table): the language a text or display filter with no request language searches +const EDITION_LANGUAGES = { + '900000000000207008': 'en-US', '731000124108': 'en-US', '32506021000036107': 'en-AU', '449081005': 'es', + '11000279109': 'cs-CZ', '554471000005108': 'da-DK', '11000146104': 'nl-NL', '45991000052106': 'sv-SE', + '83821000000107': 'en-GB', '11000172109': 'fr-BE', '11000221109': 'es-AR', '11000234105': 'de-AT', + '20621000087109': 'en-CA', '20611000087101': 'fr-CA', '11000181102': 'et-EE', '11000229106': 'fi-FI', + '11000274103': 'de-DE', '1121000189102': 'en-IN', '11000220105': 'en-IE', '21000210109': 'en-NZ', + '51000202101': 'no-NO', '11000267109': 'ko-KR', '900000001000122104': 'es-ES', '2011000195101': 'de-CH', + '999000021000000109': 'en-GB', '5631000179106': 'es-UY', '21000325107': 'es-CL', '5991000124107': 'en-US', +}; + +/** + * The edition's default description language, as main's importer records it (defaultLanguageByte): + * cfg.language (--language), else the edition's language, if the edition has active descriptions + * in it; else English. A primary subtag, or null for English (the file keeps en-US then). + */ +function rf2DefaultLanguage(cfg, activeLanguages) { + const { languageByte, languageCode } = require('../sct/languages'); + const b = languageByte(cfg.language || EDITION_LANGUAGES[cfg.edition] || 'en-US'); + const code = b ? languageCode(b) : null; + return code && code !== 'en' && activeLanguages.has(code) ? code : null; +} + +const H = { + concept: 'id\teffectiveTime\tactive\tmoduleId\tdefinitionStatusId', + description: 'id\teffectiveTime\tactive\tmoduleId\tconceptId\tlanguageCode\ttypeId\tterm\tcaseSignificanceId', + relationship: 'id\teffectiveTime\tactive\tmoduleId\tsourceId\tdestinationId\trelationshipGroup\ttypeId\tcharacteristicTypeId\tmodifierId', + concrete: 'id\teffectiveTime\tactive\tmoduleId\tsourceId\tvalue\trelationshipGroup\ttypeId\tcharacteristicTypeId\tmodifierId', + identifier: 'alternateIdentifier\teffectiveTime\tactive\tmoduleId\tidentifierSchemeId\treferencedComponentId', + language: 'id\teffectiveTime\tactive\tmoduleId\trefsetId\treferencedComponentId\tacceptabilityId', + refset: 'id\teffectiveTime\tactive\tmoduleId\trefsetId\treferencedComponentId', +}; + +function discover(root) { + const f = { concept: null, description: [], relationship: null, concrete: null, identifier: [], language: [], refset: [] }; + for (const p of walk(root)) { + if (!p.endsWith('.txt') || !/snapshot/i.test(p)) continue; + const name = path.basename(p); + const h = firstLine(p); + if (h.startsWith(H.concept)) f.concept = p; + else if (h.startsWith(H.description)) f.description.push(p); + else if (h.startsWith(H.relationship)) { if (!/StatedRelationship/i.test(name)) f.relationship = p; } + else if (h.startsWith(H.concrete)) f.concrete = p; + else if (h.startsWith(H.identifier)) f.identifier.push(p); + else if (h.startsWith(H.language) && /Language/i.test(name)) f.language.push(p); + else if (h.startsWith(H.refset) && /^der2_/.test(name) && p.includes('/Refset/')) f.refset.push(p); + } + if (!f.concept || !f.description.length || !f.relationship) throw new Error(`${root}: not an RF2 Snapshot (concept/description/relationship missing)`); + return f; +} + +const isoDate = (t) => (/^\d{8}$/.test(t) ? `${t.slice(0, 4)}-${t.slice(4, 6)}-${t.slice(6, 8)}` : t); +// SCTIDs compare numerically: shorter is smaller, then lexically. +const idLess = (a, b) => (a.length !== b.length ? a.length < b.length : a < b); + +function concrete(raw) { + if (raw.startsWith('#')) return { fhirType: 'decimal', value: raw.slice(1) }; + if (raw === 'true' || raw === 'false') return { fhirType: 'boolean', value: raw }; + if (raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"')) return { fhirType: 'string', value: raw.slice(1, -1) }; + return { fhirType: 'string', value: raw }; +} + + +const DERIVED = [{ table: 'ix_key', name: 'normalForm' }, { table: 'ix_order', name: 'walk' }]; + +class SnomedSink { + /** + * @param {object} cfg { dest, overwrite, log, importer, codeSystem: {uri, version, name, title, + * description, releaseDate, defaultLanguage}, edition, displayRefsets: [codes, in order], + * preferredRefset: code (item.preferred), normalForms (default true) } + */ + constructor(cfg) { + this.cfg = cfg; + this.log = cfg.log || (() => {}); + const b = this.b = new TerminologyBuilder(cfg.dest, { overwrite: cfg.overwrite, log: this.log, importer: cfg.importer }); + b.codeSystem({ caseSensitive: true, hierarchyMeaning: 'is-a', compositional: true, ...cfg.codeSystem }); + b.setMeta('edition', cfg.edition); + // how cs-snomed.js presents it: SNOMED CT expressions and ECL; results by concept id, an is-a + // filter's concept first; $lookup reads no link of a concrete-value attribute + b.setBehaviour('grammar', 'snomed'); + b.setBehaviour('expansionOrder', 'stored-self-first'); + b.setBehaviour('lookupSkipsMixedLinks', true); + b.setMeta('derived-by-importer', DERIVED); + this.stats = { languageRows: 0, languageRowsSkipped: 0, descriptions: 0, relationships: 0, relationshipsSkipped: 0, + concreteTypeLinks: 0, concreteValues: 0, identifiers: 0, refsetRows: 0, refsetRowsOnDescriptions: 0, + refsetRowsUnknown: 0, refsetTargetsNotNodes: 0, moduleDependencies: 0 }; + // the catalog rows every SNOMED file has (is-a may be named in a refinement; `* = x` is over + // the attributes, not the hierarchy). moduleId, definitionStatusId and effectiveTime are named + // as ECL's concept filters ({{ C moduleId = ... }}) and the FHIR filter moduleId name them + this.isA = b.property({ code: IS_A, uri: `${SCT}/${IS_A}`, shape: 'link', subsumption: true, refinable: true, wildcard: false }); + this.module = b.property({ code: 'moduleId', shape: 'link', display: 'Module', refinable: false, wildcard: false }); + this.defStatus = b.property({ code: 'definitionStatusId', shape: 'link', display: 'Definition status', refinable: false, wildcard: false }); + this.effTime = b.property({ code: 'effectiveTime', shape: 'literal', fhirType: 'dateTime', display: 'Effective time', refinable: false, wildcard: false }); + this.displayRefsets = cfg.displayRefsets; + // language members, held until the descriptions: [key, refset handle, acceptability handle] + this.lang = { key: [], refset: [], acc: [] }; + this.langMembers = new Map(); // language refset code -> active rows read + this.prefRank = new Map(); // description key -> best display-refset rank where Preferred + this.anyPreferred = new Set(); // description keys Preferred in any language refset + this.preferredKeys = new Set(); // description keys Preferred in cfg.preferredRefset + this.descItem = new Map(); // description key -> item handle + this.lastDefinition = new Map(); // concept handle -> its last active definition item (preferred) + this.best = new Map(); // concept handle -> [tier, description id, term] + this.relSeq = 0; + this.concreteTypes = new Map(); + this.deferred = []; // relationships typed by a concrete attribute, until its property exists + this.relations = new Map(); // refset code -> {id, cols} + this.schemes = new Map(); + this.moduleDependencies = []; + } + + idx(code) { return this.b.idx(code); } + + concept(code, active) { return this.b.concept(code, { active }); } + + /** module / definition status handles (undefined: none), effectiveTime as YYYY-MM-DD */ + conceptMeta(i, module, defStatus, effectiveTime) { + if (module !== undefined) this.b.link(i, this.module, module); + if (defStatus !== undefined) this.b.link(i, this.defStatus, defStatus); + if (effectiveTime) this.b.literal(i, this.effTime, effectiveTime); + } + + /** an active language refset row; key: the parser's description key */ + languageMember(key, refsetCode, accCode) { + const refset = this.b.idx(refsetCode), acc = this.b.idx(accCode); + if (refset === undefined || acc === undefined) { this.stats.languageRowsSkipped++; return; } + this.lang.key.push(key); this.lang.refset.push(refset); this.lang.acc.push(acc); + this.langMembers.set(refsetCode, (this.langMembers.get(refsetCode) || 0) + 1); + if (accCode === PREFERRED) { + this.anyPreferred.add(key); + if (refsetCode === this.cfg.preferredRefset) this.preferredKeys.add(key); + const k = this.displayRefsets.indexOf(refsetCode); + if (k >= 0 && !(this.prefRank.get(key) <= k)) this.prefRank.set(key, k); + } + } + + /** { key, id (SCTID), concept (handle), language, type (code), term, active } */ + description(d) { + const syn = d.type === SYNONYM; + const def = d.type === DEFINITION; + const h = this.b.item(d.concept, { kind: def ? 1 : 0, externalId: d.id, language: d.language, + use: { system: SCT, code: d.type }, text: d.term, active: d.active, preferred: !def && this.preferredKeys.has(d.key) }); + if (h !== null) this.descItem.set(d.key, h); + if (h !== null && def && d.active) this.lastDefinition.set(d.concept, h); + this.stats.descriptions++; + if (!d.active) return; + const k = this.displayRefsets.length; + if (syn && this.prefRank.has(d.key)) this._consider(d.concept, this.prefRank.get(d.key), d.id, d.term); + else if (syn && this.anyPreferred.has(d.key)) this._consider(d.concept, k, d.id, d.term); + else if (d.type === FSN) this._consider(d.concept, k + 1, d.id, d.term); + else this._consider(d.concept, k + 2, d.id, d.term); + } + + _consider(i, tier, id, term) { + const cur = this.best.get(i); + if (!cur || tier < cur[0] || (tier === cur[0] && idLess(id, cur[1]))) this.best.set(i, [tier, id, term]); + } + + /** after the descriptions: displays (concepts and use codings) */ + descriptionsDone() { + for (const [i, c] of this.best) this.b.setDisplay(i, c[2].trim()); + this.best.clear(); + for (const u of this.b.uses.values()) { const i = this.b.idx(u.code); if (i !== undefined) u.display = this.b.display[i]; } + this.prefRank.clear(); this.anyPreferred.clear(); this.preferredKeys.clear(); + } + + /** the concrete-value attribute types and the literal type of each (type code -> fhirType) */ + setConcreteTypes(map) { this.concreteTypes = map; } + + _attr(type) { + return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: 'link', refinable: true, wildcard: true }); + } + + /** a relationship row (inferred); s, t: concept handles */ + relationship(s, t, type, group, active) { + if (s === undefined || t === undefined) { this.stats.relationshipsSkipped++; return; } + const seq = this.relSeq++; + if (this.concreteTypes.has(type)) { this.deferred.push([s, t, type, group, active ? 1 : 0, seq]); return; } + this.b.link(s, type === IS_A ? this.isA : this._attr(type), t, { group, active, seq }); + this.stats.relationships++; + } + + _concreteProp(type, fhirType) { + const known = this.b.propertyId(type); + if (known !== undefined) return known; + if (!this.deferredTypes) this.deferredTypes = new Set(this.deferred.map((r) => r[2])); + const both = this.deferredTypes.has(type); + return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: both ? 'both' : 'literal', fhirType, refinable: true, wildcard: true }); + } + + /** an active inferred concrete value row; s: concept handle; raw: the RF2 value (#n, "s", true) */ + concreteValue(s, type, group, raw) { + if (s === undefined) return; + const v = concrete(raw); + this.b.literal(s, this._concreteProp(type, v.fhirType), v.value, { group }); + this.stats.concreteValues++; + } + + /** after the concrete values: the deferred links of concrete-typed relationships */ + concreteDone() { + for (const [s, t, type, group, active, seq] of this.deferred) { + const p = this._concreteProp(type, this.concreteTypes.get(type)); + this.b.link(s, p, t, { group, active: !!active, seq }); + this.stats.concreteTypeLinks++; + } + this.deferred.length = 0; + // the inverse catalog row: child, the reverse of is-a + // (not a filter name: cs-snomed.js takes no `child` filter; $lookup reports children itself) + this.b.property({ code: 'child', shape: 'link', display: 'Child', inverseOf: this.isA, filterable: false, refinable: false, wildcard: false }); + // language refset rows, now that the descriptions are items + const L = this.lang; + for (let k = 0; k < L.key.length; k++) { + const item = this.descItem.get(L.key[k]); + if (item === undefined) { this.stats.languageRowsSkipped++; continue; } + this.b.record(this._languageRelation(L.refset[k]), item, { target: L.acc[k] }); + this.stats.languageRows++; + } + this.lang = null; + } + + _languageRelation(refset) { + const code = this.b.codes[refset]; + let r = this.relations.get(code); + if (!r) { + r = { id: this.b.property({ code, uri: `${SCT}/${code}`, shape: 'record', role: 'language', concept: refset, refinable: false, wildcard: false, + fields: [{ name: 'acceptabilityId', type: 'c', target: true }] }), cols: null }; + this.relations.set(code, r); + } + return r.id; + } + + /** an active alternate identifier row */ + identifier(schemeCode, value, conceptCode) { + const scheme = this.b.idx(schemeCode), c = this.b.idx(conceptCode); + if (scheme === undefined || c === undefined) return; + let p = this.schemes.get(schemeCode); + if (p === undefined) { + p = this.b.property({ code: schemeCode, uri: `${SCT}/${schemeCode}`, shape: 'identifier', concept: scheme, refinable: false, wildcard: false }); + this.schemes.set(schemeCode, p); + } + this.b.identifier(p, value, c); + this.stats.identifiers++; + } + + /** + * An active refset row (not a language refset, not module dependency). + * @param {string} refsetCode + * @param {string} ref referencedComponentId: a concept code or a description key (see `onDescription`) + * @param {{names: string[], types: string[]}} def the refset's own columns (c component, i int, s string) + * @param {string[]|null} values their values, as RF2 text + * @param {{time?: string, module?: string}} meta the row's effectiveTime (YYYYMMDD) and moduleId + * @param {boolean} [onDescription] ref is a description key + */ + refsetMember(refsetCode, ref, def, values, meta = {}, onDescription = false) { + const refset = this.b.idx(refsetCode); + if (refset === undefined) { this.stats.refsetRowsUnknown++; return; } + let subject = onDescription ? undefined : this.b.idx(ref); + if (subject === undefined) { + subject = this.descItem.get(ref); + if (subject === undefined) { this.stats.refsetRowsUnknown++; return; } + this.stats.refsetRowsOnDescriptions++; + } + let r = this.relations.get(refsetCode); + if (!r) { + const own = (def.names || []).map((name, j) => ({ name, type: def.types[j] || 's' })); + const first = own.findIndex((c) => c.type === 'c'); + if (first >= 0) own[first].target = true; + const cols = [{ name: 'effectiveTime', type: 't' }, { name: 'moduleId', type: 'c' }, ...own]; + r = { id: this.b.property({ code: refsetCode, uri: `${SCT}/${refsetCode}`, shape: 'record', concept: refset, refinable: false, wildcard: false, fields: cols }), cols }; + this.relations.set(refsetCode, r); + } + const fields = []; + let target = null, tail; + const time = meta.time ? Number(meta.time) : null; + const mod = meta.module != null && meta.module !== '' ? this.b.idx(meta.module) : undefined; + fields.push(time, mod !== undefined ? mod : (meta.module || null)); + for (let j = 2; j < r.cols.length; j++) { + const c = r.cols[j]; + const v = values ? values[j - 2] : undefined; + let x; + if (v == null) x = null; + else if (c.type === 'c') { + const h = v === '' ? undefined : (this.b.idx(v) ?? this.descItem.get(v)); + x = h !== undefined ? h : v; + } else if (c.type === 'i') x = v === '' ? null : Number(v); + else x = v; + if (c.target) { + if (typeof x === 'number') target = x; + else { tail = x; this.stats.refsetTargetsNotNodes++; } + } else fields.push(x); + } + if (target === null && r.cols.some((c) => c.target)) fields.push(tail ?? null); + this.b.record(r.id, subject, { target, fields }); + this.stats.refsetRows++; + } + + /** a module dependency row: [moduleId, referencedComponentId, sourceEffectiveTime, targetEffectiveTime] */ + moduleDependency(row) { this.moduleDependencies.push(row); this.stats.moduleDependencies++; } + + stage(name, fn) { return this.b.stage(name, fn); } + + /** build the file, then the derived-by-importer indexes (normal forms, the walk) */ + async finish(extra = {}) { + const b = this.b; + this.descItem.clear(); + for (const h of this.lastDefinition.values()) b.setItemPreferred(h, true); + this.lastDefinition.clear(); + // the display refsets in order, the acceptability that ranks, the item use ranked (synonyms) + b.setMeta('displayContexts', { relations: this.displayRefsets, preferred: PREFERRED, use: { system: SCT, code: SYNONYM } }); + if (this.moduleDependencies.length) b.setMeta('moduleDependencies', this.moduleDependencies); + const summary = b.finish({ ...extra, ...this.stats }, { vacuum: false }); + const t0 = Date.now(); + const derived = derivedIndexes(this.cfg.dest, this.log, this.cfg.normalForms !== false); + summary.derived = derived; + summary.normalForms = derived.normalForms; + summary.timings.derived = { s: (Date.now() - t0) / 1000, peakRssMiB: Math.round(process.resourceUsage().maxRSS / 1024) }; + const t1 = Date.now(); + vacuumFile(this.cfg.dest); + summary.timings.vacuum = { s: (Date.now() - t1) / 1000 }; + summary.fileBytes = require('fs').statSync(this.cfg.dest).size; + return summary; + } +} + +/** + * The derived-by-importer indexes of a built SNOMED file: the walk (tx/sqlite-v2/orders.js + * snomedWalk, over the is-a links) and the normal forms (sct-native.js buildNormalForms over the + * file's store), into ix_order / ix_key. Rerunnable: replaces the rows of those names. + */ +function derivedIndexes(file, log = () => {}, normalForms = true) { + const db = new Database(file); + db.pragma('journal_mode = OFF'); + db.pragma('synchronous = OFF'); + const { writeOrderArray, writeActiveOrder } = require('./sqlite-v2/indexes'); + const out = {}; + try { + const { computeOrder } = require('../sqlite-v2/orders'); + const n = db.prepare('SELECT concept_count FROM main.code_system WHERE served = 1').pluck().get(); + let t = Date.now(); + const walk = computeOrder(db, 'snomed', n).walk; + db.exec('BEGIN'); + db.prepare("DELETE FROM main.ix_order WHERE name = 'walk'").run(); + out.walk = { rows: writeOrderArray(db, 'walk', walk), reached: walk.reached, seconds: (Date.now() - t) / 1000 }; + out.activeOrderRows = writeActiveOrder(db); + db.exec('COMMIT'); + log(` walk: ${walk.reached.toLocaleString()} reached, ${out.walk.seconds.toFixed(1)} s`); + if (normalForms) { + t = Date.now(); + const { Store } = require('../sqlite-v2/store'); + const { buildNormalForms } = require('../sqlite-v2/sct-native'); + const store = new Store(file, { db, unregistered: true }); + db.prepare("DELETE FROM main.ix_key WHERE name = 'normalForm'").run(); + const ins = db.prepare("INSERT OR REPLACE INTO main.ix_key VALUES ('normalForm', ?, ?)"); + const r = buildNormalForms(store, db, log, { write: (id, nf) => ins.run(nf, id) }); + out.normalForms = { ...r, seconds: (Date.now() - t) / 1000 }; + db.prepare("INSERT OR REPLACE INTO main.meta VALUES ('ix.ix_key.normalForm.stats', ?)").run(JSON.stringify(out.normalForms)); + log(`normal forms: ${r.written.toLocaleString()} stored (${r.failed} could not be built), ${out.normalForms.seconds.toFixed(1)} s`); + } + analyze(db, 'main.ix_key'); analyze(db, 'main.ix_order'); + db.pragma('journal_mode = DELETE'); + } finally { + db.close(); + } + return out; +} + +module.exports = { SnomedSink, derivedIndexes, discover, isoDate, idLess, concrete, displayRefsetsFor, checkDisplayRefsets, rf2DefaultLanguage, + DISPLAY_REFSETS, EDITION_NAMES, EDITION_LANGUAGES, MODULE_DEPENDENCY, SCT, IS_A, PREFERRED, US_ENGLISH, INFERRED }; diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js new file mode 100644 index 00000000..514f7e22 --- /dev/null +++ b/tx/importers/sqlite-v2/builder.js @@ -0,0 +1,603 @@ +'use strict'; + +// Generic builder for the terminology file (schema.sql). No terminology knowledge here. +// +// An importer names concepts by code and gets back a handle; items (terms, definitions, atoms) +// hang off a concept and also get a handle. Statements (link, literal, identifier, record) take +// node handles, so any of them can be about a concept or an item. Facts are staged with +// provisional handles in a scratch SQLite file; finish(): +// 1. numbers concepts (sqlite-v2/numbering.js: active first, depth-first over the subsumption +// links, siblings by sort key) -> ids 1..N, then items N+1.. in (concept, arrival) order; +// 2. rewrites every staged fact to final ids, in key order, into the destination; +// item.rank (derived) from the role 'language' relations and meta displayContexts; +// 3. fills the catalog's computed fields (subject_kind, target_kind, n_rows; shape 'union' for a +// link row with members and no rows of its own) from the rows, by_target (hierarchy or +// refinable) and by_subject (every identifier row) unless the importer set them; +// 4. builds the ix_* tables (indexes.js, which reads fact tables only); +// 5. writes meta (format, provenance), ANALYZE (sqlite_stat1 only: analyze()) and VACUUM (unless +// the importer still writes derived-by-importer rows: then it calls vacuumFile() after them). +// +// Handles: a concept is its 0-based arrival index (>= 0); an item is -(its staging row id) (< 0). + +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const Database = require('better-sqlite3'); +const { numberConcepts } = require('../sqlite-v2/numbering'); +const { buildIndexes } = require('./indexes'); + +const SCHEMA_PATH = path.join(__dirname, 'schema.sql'); +const FORMAT = 'tx-terminology/1'; +// PRAGMA user_version of a file in this format (the earlier sqlite-v2 schema wrote 5), so a reader can +// tell an old file before reading any table +const USER_VERSION = 1; +const COMMIT_EVERY = 100000; +const SHAPES = new Set(['link', 'literal', 'both', 'identifier', 'record', 'union']); +const ROLES = new Set(['language']); +/** + * a source id that is a canonical decimal integer is stored as INTEGER. Bound as a BigInt: + * better-sqlite3 binds every JS number as REAL, which an untyped column keeps (and CAST AS TEXT + * then gives '220306011.0') + */ +function externalIdValue(v) { + if (v == null || v === '') return null; + if (typeof v === 'bigint') return v; + if (typeof v === 'number') { + if (!Number.isSafeInteger(v) || v < 0) throw new Error(`external id ${v}: a number must be a safe non-negative integer (pass the source text)`); + return BigInt(v); + } + const t = String(v); + if (!/^(0|[1-9][0-9]{0,18})$/.test(t)) return t; + const b = BigInt(t); + return b > 9223372036854775807n ? t : b; +} +const LITERAL_TYPES = new Set(['code', 'Coding', 'string', 'integer', 'decimal', 'boolean', 'dateTime']); + +/** the sections of schema.sql: { facts, factIndexes, ix } */ +function schemaSections() { + const ddl = fs.readFileSync(SCHEMA_PATH, 'utf8'); + const part = (name) => { + const m = ddl.split(/^-- @(facts|fact-indexes|ix)\s*$/m); + const i = m.indexOf(name); + if (i < 0) throw new Error(`schema.sql: no @${name} section`); + return m[i + 1]; + }; + return { facts: part('facts'), factIndexes: part('fact-indexes'), ix: part('ix') }; +} + +class TerminologyBuilder { + /** @param {string} dest @param {object} [options] { overwrite, log, importer } */ + constructor(dest, options = {}) { + this.dest = path.resolve(dest); + this.log = options.log || (() => {}); + this.importer = options.importer || 'unknown'; + this.t0 = Date.now(); + this.timings = {}; + if (fs.existsSync(this.dest)) { + if (!options.overwrite) throw new Error(`Destination exists: ${this.dest} (use overwrite)`); + fs.rmSync(this.dest, { force: true }); + } + fs.mkdirSync(path.dirname(this.dest), { recursive: true }); + this.stagePath = `${this.dest}.stage`; + fs.rmSync(this.stagePath, { force: true }); + this.st = new Database(this.stagePath); + this.st.pragma('journal_mode = OFF'); + this.st.pragma('synchronous = OFF'); + this.st.pragma('cache_size = -200000'); + this.st.exec(` + CREATE TABLE s_item (id INTEGER PRIMARY KEY, concept INTEGER, kind INTEGER, external_id, cs_id INTEGER, + language TEXT, use_id INTEGER, text TEXT, active INTEGER, preferred INTEGER, rank INTEGER); + CREATE TABLE s_link (subject INTEGER, prop INTEGER, grp INTEGER, target INTEGER, active INTEGER, seq INTEGER); + CREATE TABLE s_literal (subject INTEGER, prop INTEGER, grp INTEGER, value, active INTEGER); + CREATE TABLE s_identifier (prop INTEGER, value, subject INTEGER, resolves INTEGER); + CREATE TABLE s_record (id INTEGER PRIMARY KEY, relation INTEGER, subject INTEGER, target INTEGER, active INTEGER, fields TEXT); + CREATE TABLE s_mapping (concept INTEGER, prop INTEGER, system TEXT, version TEXT, code TEXT, display TEXT, relationship TEXT); + CREATE TABLE s_value_label (prop INTEGER, value, display TEXT); + `); + const p = (sql) => this.st.prepare(sql); + this.ins = { + item: p('INSERT INTO s_item (concept, kind, external_id, cs_id, language, use_id, text, active, preferred, rank) VALUES (?,?,?,?,?,?,?,?,?,?)'), + link: p('INSERT INTO s_link VALUES (?,?,?,?,?,?)'), + literal: p('INSERT INTO s_literal VALUES (?,?,?,?,?)'), + identifier: p('INSERT INTO s_identifier VALUES (?,?,?,?)'), + record: p('INSERT INTO s_record (relation, subject, target, active, fields) VALUES (?,?,?,?,?)'), + mapping: p('INSERT INTO s_mapping VALUES (?,?,?,?,?,?,?)'), + valueLabel: p('INSERT INTO s_value_label VALUES (?,?,?)'), + }; + this.pending = 0; + this.st.exec('BEGIN'); + + this.systems = []; // cs_id - 1 -> spec; cs_id 1 is the served system + this.codes = []; + this.index = new Map(); + this.conceptCs = []; + this.active = []; + this.display = []; + this.sortKey = []; + this.properties = []; // id - 1 -> def + this.propertyByKey = new Map(); // cs_id|code -> def + this.members = []; + this.uses = new Map(); + this.meta = new Map(); + this.sources = []; + this.counts = {}; + } + + _tick() { if (++this.pending >= COMMIT_EVERY) { this.st.exec('COMMIT; BEGIN'); this.pending = 0; } } + _count(name) { this.counts[name] = (this.counts[name] || 0) + 1; } + + // ---- release --------------------------------------------------------------------------- + + /** + * A code system row. The first one is the served system (cs_id 1); later ones are sources that + * only contribute items (served = 0). Returns the cs_id. + * { uri, version, name, title, description, releaseDate, content, caseSensitive, hierarchyMeaning, defaultLanguage, + * compositional, resource } + */ + codeSystem(spec) { + if (!spec.uri || spec.version == null) throw new Error('codeSystem: uri and version are required'); + this.systems.push({ content: 'complete', ...spec, served: this.systems.length === 0 ? 1 : 0 }); + return this.systems.length; + } + + /** a behaviour setting (meta behaviour., a JSON value; tx/sqlite-v2/store.js BEHAVIOUR) */ + setBehaviour(key, value) { + this.meta.set(`behaviour.${key}`, JSON.stringify(value)); + } + + /** a release fact without a column (displayContexts, moduleDependencies, ...): JSON for objects */ + setMeta(key, value) { + this.meta.set(key, value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value)); + } + + addSource(filePath) { + const st = fs.statSync(filePath); + if (st.isDirectory()) { for (const e of fs.readdirSync(filePath).sort()) this.addSource(path.join(filePath, e)); return; } + this.sources.push({ path: filePath, size: st.size }); + } + + // ---- catalog --------------------------------------------------------------------------- + + /** + * A catalog row; returns its id (an existing (cs, code) returns the existing id, which must have + * the same shape). { code, cs = 1, uri, display, shape, fhirType, concept (handle), subsumption, + * closureFrom, filterable = true, refinable, wildcard, inverseOf (may name a union row), byTarget + * (default: subsumption or refinable; being named by inverseOf does not imply it), bySubject + * (shape identifier: its rows are read by subject, ix_by_subject; default true), ordered + * (link.seq orders a subject's targets and the order is part of the answer), fields + * ([{name, type, target}]: record shape), role (NULL or 'language': a record relation on items that + * ranks displays, by meta displayContexts), filterOps (the FHIR operators a filter on it accepts), + * report ('named' | 'always': when $lookup reports it) } + */ + property(spec) { + const cs = spec.cs || 1; + const key = `${cs}|${spec.code}`; + const known = this.propertyByKey.get(key); + if (known) { + if (known.shape !== spec.shape) throw new Error(`property ${spec.code}: shape ${known.shape}, not ${spec.shape}`); + return known.id; + } + if (!SHAPES.has(spec.shape)) throw new Error(`property ${spec.code}: bad shape ${spec.shape}`); + if (spec.role != null && !ROLES.has(spec.role)) throw new Error(`property ${spec.code}: bad role ${spec.role}`); + if (spec.role === 'language' && (spec.shape !== 'record' || !(spec.fields || []).some((f) => f.target))) { + throw new Error(`property ${spec.code}: a language relation is a record with a target column (the acceptability)`); + } + if (spec.bySubject != null && spec.shape !== 'identifier') throw new Error(`property ${spec.code}: bySubject is for shape identifier`); + if ((spec.shape === 'literal' || spec.shape === 'both') && !LITERAL_TYPES.has(spec.fhirType)) { + throw new Error(`property ${spec.code}: bad fhirType ${spec.fhirType}`); + } + const def = { + id: this.properties.length + 1, cs, code: spec.code, uri: spec.uri ?? null, display: spec.display ?? null, + concept: spec.concept ?? null, shape: spec.shape, role: spec.role ?? null, fhirType: spec.fhirType ?? null, + subsumption: spec.subsumption ? 1 : 0, closureFrom: spec.closureFrom ?? null, + filterable: spec.filterable === false ? 0 : 1, refinable: spec.refinable ? 1 : 0, wildcard: spec.wildcard ? 1 : 0, + inverseOf: spec.inverseOf ?? null, byTarget: spec.byTarget == null ? null : (spec.byTarget ? 1 : 0), + bySubject: spec.shape === 'identifier' && spec.bySubject !== false ? 1 : 0, + ordered: spec.ordered ? 1 : 0, + filterOps: spec.filterOps ? JSON.stringify(spec.filterOps) : null, report: spec.report ?? null, + fields: spec.fields ? JSON.stringify(spec.fields) : null, + // record shape: positions in record.fields (the non-target columns) that hold node handles + nodeCols: spec.fields ? spec.fields.filter((f) => !f.target).map((f, i) => ((f.type === 'c' || f.type === 'n') ? i : -1)).filter((i) => i >= 0) : [], + }; + this.properties.push(def); + this.propertyByKey.set(key, def); + return def.id; + } + + propertyId(code, cs = 1) { const d = this.propertyByKey.get(`${cs}|${code}`); return d ? d.id : undefined; } + + /** the property whose explicit pairs are this (subsumption) property's closure, set after both exist */ + setClosureFrom(property, from) { this.properties[property - 1].closureFrom = from; } + + /** the parent property is the union of the child (property_member) */ + propertyMember(parent, child) { this.members.push([parent, child]); } + + // ---- nodes ----------------------------------------------------------------------------- + + /** a concept; returns its handle. Re-adding a code returns the existing handle. */ + concept(code, { cs = 1, active = true, display = null, sortKey = 0 } = {}) { + const known = this.index.get(code); + if (known !== undefined) return known; + if (cs !== 1) throw new Error('concepts belong to the served system (cs 1)'); + const i = this.codes.length; + this.codes.push(code); + this.index.set(code, i); + this.conceptCs.push(cs); + this.active.push(active ? 1 : 0); + this.display.push(display); + this.sortKey.push(sortKey); + return i; + } + + idx(code) { return this.index.get(code); } + setActive(i, active) { this.active[i] = active ? 1 : 0; } + setDisplay(i, display) { this.display[i] = display; } + setSortKey(i, key) { this.sortKey[i] = key; } + + /** an item_use coding; returns its use_id */ + use({ system = null, code, display = null }) { + const k = `${system || ''}|${code}`; + let u = this.uses.get(k); + if (!u) this.uses.set(k, u = { id: this.uses.size + 1, system, code, display }); + return u.id; + } + + /** + * An item below a concept; returns its handle (< 0), or null for an empty text. + * { kind = 0, externalId, cs = 1, language, use ({system, code, display} or a use_id), text, active, preferred, rank } + */ + item(concept, { kind = 0, externalId = null, cs = 1, language = null, use = null, text, active = true, preferred = false, rank = null }) { + if (text === null || text === undefined || text === '') return null; + if (!(concept >= 0)) throw new Error('item: the concept handle is required'); + const useId = use == null ? null : typeof use === 'number' ? use : this.use(use); + const id = this.ins.item.run(concept, kind, externalIdValue(externalId), cs, language, useId, text, active ? 1 : 0, preferred ? 1 : 0, rank).lastInsertRowid; + this._count('items'); + this._tick(); + return -Number(id); + } + + /** change an item's preferred flag (the importer decides after reading, e.g. the definition shown) */ + setItemPreferred(handle, preferred) { + if (!(handle < 0)) throw new Error('setItemPreferred: an item handle is required'); + if (!this._setPref) this._setPref = this.st.prepare('UPDATE s_item SET preferred = ? WHERE id = ?'); + this._setPref.run(preferred ? 1 : 0, -handle); + this._tick(); + } + + // ---- statements ------------------------------------------------------------------------ + + link(subject, property, target, { group = 0, active = true, seq = null } = {}) { + this.ins.link.run(subject, property, group, target, active ? 1 : 0, seq); + this._count('links'); + this._tick(); + } + + literal(subject, property, value, { group = 0, active = true } = {}) { + if (value === null || value === undefined || value === '') return; + this.ins.literal.run(subject, property, group, this._typed(property, value), active ? 1 : 0); + this._count('literals'); + this._tick(); + } + + /** + * a value -> subject statement. resolves: 0 not a code; 1 an alias, accepted as a code and answered + * with the subject's own code; 2 a code in its own right, answered as written + */ + identifier(property, value, subject, { resolves = 0 } = {}) { + const r = resolves === true ? 1 : resolves === false ? 0 : resolves; + if (r !== 0 && r !== 1 && r !== 2) throw new Error(`identifier ${value}: resolves is 0, 1 or 2`); + this.ins.identifier.run(property, externalIdValue(value), subject, r); + this._count('identifiers'); + this._tick(); + } + + /** + * a record row; seq is its arrival order within the relation. target: a node handle. + * fields: the values of the relation's non-target columns (property.fields order). In a node + * column (type c / n) a number is a node handle (rewritten to the node id at finish); a string + * is kept as it is (a source code that is not a node of this file). + */ + record(relation, subject, { target = null, active = true, fields = null } = {}) { + this.ins.record.run(relation, subject, target, active ? 1 : 0, fields ? JSON.stringify(fields) : null); + this._count('records'); + this._tick(); + } + + /** the display of a literal value of a property (value_label) */ + valueLabel(property, value, display) { + this.ins.valueLabel.run(property, this._typed(property, value), display); + } + + mapping(concept, { property = null, system, version = null, code, display = null, relationship }) { + this.ins.mapping.run(concept, property, system, version, code, display, relationship); + this._count('mappings'); + this._tick(); + } + + _typed(property, value) { + const def = this.properties[property - 1]; + switch (def.fhirType) { + case 'integer': case 'decimal': { + const n = Number(value); + if (Number.isNaN(n)) throw new Error(`property ${def.code}: '${value}' is not a number`); + return n; + } + case 'boolean': + return (value === true || value === 'true' || value === '1' || value === 1 || value === 'Y') ? 1 : 0; + default: + return String(value); + } + } + + // ---- final stage ----------------------------------------------------------------------- + + _record(name, t, r) { + const rec = { s: (Date.now() - t) / 1000, peakRssMiB: Math.round(process.resourceUsage().maxRSS / 1024) }; + if (typeof r === 'number') rec.rows = r; + this.timings[name] = rec; + this.log(` ${name}: ${rec.s.toFixed(1)} s${rec.rows !== undefined ? `, ${rec.rows.toLocaleString()} rows` : ''}, peak RSS ${rec.peakRssMiB} MiB`); + } + + _time(name, fn) { const t = Date.now(); const r = fn(); this._record(name, t, r); return r; } + + async stage(name, fn) { const t = Date.now(); const r = await fn(); this._record(name, t, typeof r === 'number' ? r : undefined); return r; } + + /** + * record rows to final ids, in SQL: subject and target through the node map, the node columns of + * fields (property nodeCols: a JSON number there is a node handle) with json_set; seq = arrival + * order within the relation. One statement per relation, in relation order, so rows go in + * key order. + */ + _rewriteRecords(db) { + db.exec('CREATE INDEX st.s_record_relation ON s_record(relation, id)'); + const rels = db.prepare('SELECT DISTINCT relation FROM st.s_record ORDER BY 1').pluck().all(); + let n = 0; + for (const rel of rels) { + const def = this.properties[rel - 1]; + const cols = (def && def.nodeCols) || []; + // each node column from the staged row: its node id where it is a handle, else as it is + const f = cols.length ? `json_set(r.fields, ${cols.map((i) => `'$[${i}]', CASE WHEN json_type(r.fields, '$[${i}]') = 'integer' + THEN (SELECT new FROM st.s_node WHERE old = json_extract(r.fields, '$[${i}]')) ELSE json_extract(r.fields, '$[${i}]') END`).join(', ')})` : 'r.fields'; + n += db.prepare(`INSERT INTO record SELECT r.relation, m.new, + row_number() OVER (ORDER BY r.id) - 1, mt.new, r.active, ${f} + FROM st.s_record r JOIN st.s_node m ON m.old = r.subject LEFT JOIN st.s_node mt ON mt.old = r.target + WHERE r.relation = ? ORDER BY 2, 3`).run(rel).changes; + } + return n; + } + + /** + * item.rank (derived), from the relations with role 'language' and meta displayContexts + * ({relations, preferred, use}): 0 an item whose target is `preferred` in one of + * `relations`, 1 Preferred in another language relation, 2 any other. Only items of `use` + * ({system, code}) rank 0 or 1, when it is set (SNOMED CT: synonyms; an FSN is Preferred too, but + * is not a display). Without language relations: the rank the importer gave. + * Returns the SQL expression for item.rank over staged s_item i and the join it needs. + */ + _stageRank(db) { + const lang = this.properties.filter((p) => p.role === 'language'); + if (!lang.length) return { expr: 'i.rank', join: '' }; + // meta displayContexts = {relations: [codes, in order], preferred: , use: {system, code}} + const dc = JSON.parse(this.meta.get('displayContexts') || '{}'); + const contexts = (dc.relations || []).map(String); + if (dc.preferred == null) throw new Error('meta displayContexts: no preferred target for the language relations'); + const t = this.index.get(String(dc.preferred)); + db.exec('CREATE TABLE st.s_pref (relation INTEGER PRIMARY KEY, target INTEGER, display INTEGER)'); + const ins = db.prepare('INSERT INTO st.s_pref VALUES (?, ?, ?)'); + if (t !== undefined) for (const p of lang) ins.run(p.id, t, contexts.includes(p.code) ? 1 : 0); + db.exec(`CREATE TABLE st.s_rank (item INTEGER PRIMARY KEY, flag INTEGER NOT NULL); + INSERT INTO st.s_rank SELECT -r.subject, max(CASE WHEN p.display = 1 THEN 2 ELSE 1 END) FROM st.s_record r + JOIN st.s_pref p ON p.relation = r.relation AND p.target = r.target WHERE r.active = 1 AND r.subject < 0 GROUP BY r.subject`); + const du = dc.use || null; + const u = du ? this.uses.get(`${du.system || ''}|${du.code}`) : null; + const useCond = du ? `i.use_id IS NOT ${u ? u.id : 'NULL'}` : '0'; + return { expr: `CASE WHEN ${useCond} THEN 2 WHEN rk.flag = 2 THEN 0 WHEN rk.flag = 1 THEN 1 ELSE 2 END`, join: 'LEFT JOIN st.s_rank rk ON rk.item = i.id' }; + } + + /** + * @param {object} [extra] importer stats, kept in meta 'provenance.importer' + * @param {object} [opts] { vacuum: false when the importer writes derived-by-importer rows after + * this (it then calls vacuumFile) } + */ + finish(extra = {}, opts = {}) { + if (!this.systems.length) throw new Error('codeSystem() was not called'); + this.st.exec('COMMIT'); + this.timings.parse = { s: (Date.now() - this.t0) / 1000, peakRssMiB: Math.round(process.resourceUsage().maxRSS / 1024) }; + const n = this.codes.length; + this.log(`Final stage: ${n.toLocaleString()} concepts`); + + // 1. numbering: concepts over the active subsumption links between concepts + const hier = this.properties.filter((p) => p.subsumption).map((p) => p.id); + const [childOf, parentOf] = hier.length + ? intPairs(this.st.prepare(`SELECT subject, target FROM s_link WHERE active = 1 AND subject >= 0 AND target >= 0 AND prop IN (${hier.join(',')})`)) + : [new Int32Array(0), new Int32Array(0)]; + const num = this._time('number', () => numberConcepts({ + codes: this.codes, active: Uint8Array.from(this.active), childOf, parentOf, sortKey: Float64Array.from(this.sortKey), + })); + const { idOf, order, activeCount } = num; + + const db = new Database(this.dest); + this.db = db; + db.pragma('page_size = 4096'); + db.pragma('journal_mode = OFF'); + db.pragma('synchronous = OFF'); + db.pragma('cache_size = -400000'); + const ddl = schemaSections(); + db.exec(ddl.facts); + db.pragma(`user_version = ${USER_VERSION}`); + this.st.close(); + db.prepare('ATTACH DATABASE ? AS st').run(this.stagePath); + const run = (name, sql) => this._time(`rewrite ${name}`, () => db.prepare(sql).run().changes); + + db.exec('BEGIN'); + // node map: concept handles -> 1..N, item handles -> N+1.. in (concept id, arrival) order + db.exec('CREATE TABLE st.s_node (old INTEGER PRIMARY KEY, new INTEGER NOT NULL)'); + const insNode = db.prepare('INSERT INTO st.s_node VALUES (?, ?)'); + for (let i = 0; i < n; i++) insNode.run(i, idOf[i]); + run('item map', `INSERT INTO st.s_node SELECT -i.id, ${n} + row_number() OVER (ORDER BY m.new, i.id) + FROM st.s_item i JOIN st.s_node m ON m.old = i.concept`); + + const insCs = db.prepare(`INSERT INTO code_system (cs_id, uri, version, name, title, description, release_date, content, + case_sensitive, hierarchy_meaning, default_language, compositional, served, concept_count, active_count, resource) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + const flag = (v) => (v == null ? null : (v ? 1 : 0)); + this.systems.forEach((cs, k) => insCs.run(k + 1, cs.uri, String(cs.version), cs.name ?? null, cs.title ?? null, + cs.description ?? null, cs.releaseDate ?? null, cs.content, flag(cs.caseSensitive), + cs.hierarchyMeaning ?? null, cs.defaultLanguage ?? null, flag(cs.compositional), cs.served, cs.served ? n : 0, cs.served ? activeCount : 0, + cs.resource == null ? null : (typeof cs.resource === 'string' ? cs.resource : JSON.stringify(cs.resource)))); + const insUse = db.prepare('INSERT INTO item_use VALUES (?,?,?,?)'); + for (const u of this.uses.values()) insUse.run(u.id, u.system, u.code, u.display); + + const insConcept = db.prepare('INSERT INTO concept VALUES (?,?,?,?,?)'); + this._time('rewrite concept', () => { + for (let k = 0; k < n; k++) { const i = order[k]; insConcept.run(k + 1, this.conceptCs[i], this.codes[i], this.active[i], this.display[i]); } + return n; + }); + const rank = this._time('item rank', () => this._stageRank(db)); + run('item', `INSERT INTO item SELECT m.new, mc.new, i.kind, i.external_id, i.cs_id, i.language, i.use_id, i.text, i.active, i.preferred, ${rank.expr} + FROM st.s_item i JOIN st.s_node m ON m.old = -i.id JOIN st.s_node mc ON mc.old = i.concept ${rank.join} ORDER BY 1`); + // duplicates by key collapse; a link in several rows keeps its first seq + run('link', `INSERT INTO link SELECT ms.new, l.prop, l.grp, mt.new, l.active, min(l.seq) FROM st.s_link l + JOIN st.s_node ms ON ms.old = l.subject JOIN st.s_node mt ON mt.old = l.target + GROUP BY 1, 2, 3, 4, 5 ORDER BY 1, 2, 3, 4, 5`); + run('literal', `INSERT OR IGNORE INTO literal SELECT m.new, l.prop, l.grp, l.value, l.active FROM st.s_literal l + JOIN st.s_node m ON m.old = l.subject ORDER BY 1, 2, 3, 4, 5`); + run('identifier', `INSERT OR IGNORE INTO identifier SELECT i.prop, i.value, m.new, i.resolves FROM st.s_identifier i + JOIN st.s_node m ON m.old = i.subject ORDER BY 1, 2, 3`); + this._time('rewrite record', () => this._rewriteRecords(db)); + run('value_label', `INSERT OR IGNORE INTO value_label SELECT prop, value, display FROM st.s_value_label ORDER BY 1, 2`); + run('mapping', `INSERT OR IGNORE INTO mapping SELECT m.new, x.prop, x.system, x.version, x.code, x.display, x.relationship + FROM st.s_mapping x JOIN st.s_node m ON m.old = x.concept ORDER BY 1, 3, 5`); + + // catalog, with its computed fields from the rows just written + const nodeId = (h) => (h == null ? null : h >= 0 ? idOf[h] : db.prepare('SELECT new FROM st.s_node WHERE old = ?').pluck().get(h)); + const computed = this._time('catalog computed fields', () => catalogStats(db, n)); + const insProp = db.prepare(`INSERT INTO property (id, cs_id, code, uri, display, concept_id, shape, role, fhir_type, subject_kind, + target_kind, n_rows, subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, filter_ops, report, fields) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + const parents = new Set(this.members.map(([a]) => a)); + for (const p of this.properties) { + // subject_kind NULL for a catalog row with no rows + const c = computed.get(p.id) || { subjectKind: null, targetKind: null, n: 0 }; + // shape 'union': a link row whose only rows are its members' + let shape = p.shape; + if (parents.has(p.id)) { + if (c.n > 0) throw new Error(`property ${p.code}: a union (property_member) with rows of its own`); + if (shape !== 'link' && shape !== 'union') throw new Error(`property ${p.code}: shape ${shape} with property_member rows`); + shape = 'union'; + } else if (shape === 'union') throw new Error(`property ${p.code}: shape union without members`); + const byTarget = p.byTarget != null ? p.byTarget + : ((shape === 'link' || shape === 'both') && (p.subsumption || p.refinable) ? 1 : 0); + insProp.run(p.id, p.cs, p.code, p.uri, p.display, nodeId(p.concept), shape, p.role, p.fhirType, c.subjectKind, + (shape === 'link' || shape === 'both' || shape === 'record') ? c.targetKind : null, c.n, + p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.filterOps, p.report, p.fields); + } + const insMember = db.prepare('INSERT OR IGNORE INTO property_member VALUES (?, ?)'); + for (const [a, b] of this.members) insMember.run(a, b); + db.exec('COMMIT'); + db.exec('DETACH DATABASE st'); + this._time('fact indexes', () => db.exec(ddl.factIndexes)); + this._time('checks', () => checkFacts(db, n, activeCount)); + + // meta: format and provenance (release facts were set by the importer); behaviour settings + // as a reader checks them + require('../../sqlite-v2/store').readBehaviour(this.meta, this.dest); + const insMeta = db.prepare('INSERT OR REPLACE INTO meta VALUES (?, ?)'); + for (const [k, v] of [...this.meta].sort()) insMeta.run(k, v); + insMeta.run('format', FORMAT); + // the languages of the served system's items, in order of first appearance (a release fact) + insMeta.run('languages', JSON.stringify(db.prepare(`SELECT language FROM item WHERE cs_id = 1 AND language IS NOT NULL + GROUP BY language ORDER BY min(id)`).pluck().all())); + this._time('hash', () => { for (const s of this.sources) s.sha256 = sha256File(s.path); }); + insMeta.run('provenance.importer', this.importer); + insMeta.run('provenance.builtAt', new Date().toISOString()); + insMeta.run('provenance.node', process.version); + insMeta.run('provenance.sources', JSON.stringify(this.sources.map((s) => ({ name: path.basename(s.path), size: s.size, sha256: s.sha256 })))); + insMeta.run('provenance.importerStats', JSON.stringify(extra)); + + // indexes: from the fact tables only + const ixStats = buildIndexes(db, { log: this.log, time: (name, fn) => this._time(name, fn) }); + this._time('analyze', () => analyze(db)); + this.timings.total = (Date.now() - this.t0) / 1000; + insMeta.run('provenance.timings', JSON.stringify(this.timings)); + db.pragma('journal_mode = DELETE'); + if (opts.vacuum !== false) this._time('vacuum', () => { db.exec('VACUUM'); }); + + const tables = {}; + for (const t of ['concept', 'item', 'property', 'link', 'literal', 'identifier', 'record', 'mapping', 'ix_set', 'ix_in', 'ix_order', 'ix_word']) { + tables[t] = db.prepare(`SELECT count(*) AS c FROM ${t}`).get().c; + } + db.close(); + fs.rmSync(this.stagePath, { force: true }); + const summary = { concepts: n, activeConcepts: activeCount, items: this.counts.items || 0, tables, indexes: ixStats, + staged: this.counts, importer: extra, fileBytes: fs.statSync(this.dest).size, timings: this.timings }; + this.log(`Done: ${this.dest} (${(summary.fileBytes / 1048576).toFixed(1)} MiB, ${this.timings.total.toFixed(0)} s)`); + return summary; + } +} + +/** per property: n_rows, subject_kind, target_kind from the fact rows (ids <= n are concepts) */ +function catalogStats(db, n) { + const out = new Map(); + const kind = (lo, hi) => (lo == null ? null : hi <= n ? 'concept' : lo > n ? 'item' : 'both'); + const merge = (pid, rows, sLo, sHi, tLo, tHi) => { + const c = out.get(pid) || { n: 0, s: [], t: [] }; + c.n += rows; c.s.push(sLo, sHi); + if (tLo != null) c.t.push(tLo, tHi); + out.set(pid, c); + }; + for (const r of db.prepare('SELECT property_id p, count(*) c, min(subject_id) a, max(subject_id) b, min(target_id) x, max(target_id) y FROM link GROUP BY 1').all()) merge(r.p, r.c, r.a, r.b, r.x, r.y); + for (const r of db.prepare('SELECT property_id p, count(*) c, min(subject_id) a, max(subject_id) b FROM literal GROUP BY 1').all()) merge(r.p, r.c, r.a, r.b); + for (const r of db.prepare('SELECT property_id p, count(*) c, min(subject_id) a, max(subject_id) b FROM identifier GROUP BY 1').all()) merge(r.p, r.c, r.a, r.b); + for (const r of db.prepare('SELECT relation_id p, count(*) c, min(subject_id) a, max(subject_id) b, min(target_id) x, max(target_id) y FROM record GROUP BY 1').all()) merge(r.p, r.c, r.a, r.b, r.x, r.y); + const res = new Map(); + for (const [pid, c] of out) { + res.set(pid, { n: c.n, subjectKind: kind(Math.min(...c.s), Math.max(...c.s)), + targetKind: c.t.length ? kind(Math.min(...c.t), Math.max(...c.t)) : null }); + } + return res; +} + +function checkFacts(db, n, activeCount) { + const one = (sql) => db.prepare(sql).pluck().get(); + const fail = (m) => { throw new Error(`integrity: ${m}`); }; + if (one('SELECT count(*) FROM concept') !== n) fail('concept count'); + if (one(`SELECT count(*) FROM concept WHERE active <> (id <= ${activeCount})`)) fail('active concepts are not a prefix'); + if (one(`SELECT count(*) FROM item WHERE id <= ${n}`)) fail('an item id is not above every concept id'); + if (one('SELECT count(*) FROM item i LEFT JOIN code_system c ON c.cs_id = i.cs_id WHERE c.cs_id IS NULL')) fail('an item has an unknown cs_id'); + return true; +} + +function intPairs(stmt) { + let a = new Int32Array(1 << 16), b = new Int32Array(1 << 16), k = 0; + for (const [x, y] of stmt.raw().iterate()) { + if (k === a.length) { const a2 = new Int32Array(k * 2); a2.set(a); a = a2; const b2 = new Int32Array(k * 2); b2.set(b); b = b2; } + a[k] = x; b[k] = y; k++; + } + return [a.slice(0, k), b.slice(0, k)]; +} + +function sha256File(p) { + const h = crypto.createHash('sha256'); + const fd = fs.openSync(p, 'r'); + const buf = Buffer.allocUnsafe(1 << 22); + try { let r; while ((r = fs.readSync(fd, buf, 0, buf.length, null)) > 0) h.update(buf.subarray(0, r)); } finally { fs.closeSync(fd); } + return h.digest('hex'); +} + +/** + * ANALYZE (the whole file, or `what`: a table or index) and keep sqlite_stat1 only: the format ships no + * sqlite_stat4 (with it SQLite re-plans a `col = ?` statement on every bind) + */ +function analyze(db, what = null) { + db.exec(what ? `ANALYZE ${what}` : 'ANALYZE'); + db.exec('DROP TABLE IF EXISTS sqlite_stat4'); +} + +/** VACUUM a built file (after the importer's derived-by-importer rows), without sqlite_stat4 */ +function vacuumFile(file) { + const db = new Database(file); + try { db.exec('DROP TABLE IF EXISTS sqlite_stat4'); db.exec('VACUUM'); } finally { db.close(); } +} + +module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, analyze, externalIdValue }; diff --git a/tx/importers/sqlite-v2/diff.js b/tx/importers/sqlite-v2/diff.js new file mode 100644 index 00000000..398d89a1 --- /dev/null +++ b/tx/importers/sqlite-v2/diff.js @@ -0,0 +1,146 @@ +#!/usr/bin/env node +'use strict'; + +// Compare two terminology files of the same code system by codes (node and property ids are local +// to a file). Used to check the reverse loaders (a SNOMED CT .cache, a classic LOINC .db) against +// builds from the release. +// +// node tx/importers/sqlite-v2/diff.js A.db B.db [--json out.json] [--examples N] +// +// Reports, per fact table, rows only in A / only in B as code-keyed tuples (a node is 'c:' +// for a concept, 'i::' for an item; record node fields are +// translated the same way), whether the concept numbering is identical, and ix_set equality per +// (kind, property code, value kind, value): by bytes when the numbering is identical, else by +// members translated to codes. Holds each file's keyed rows in memory: a tool for fixtures and +// single editions. + +const fs = require('fs'); +const Database = require('better-sqlite3'); +const sets = require('./sets'); // RoaringBitmap32 through sets: roaring loads on first use + +const FACTS = ['concept', 'item', 'item_use', 'property', 'property_member', 'link', 'literal', 'identifier', 'record', 'mapping', 'value_label']; + +/** node id -> key, property id -> code, and the keyed rows of every fact table, for one file */ +function keyed(db) { + const conceptCode = new Map(db.prepare('SELECT id, code FROM concept').raw().all()); + const node = new Map(); + for (const [id, code] of conceptCode) node.set(id, 'c:' + code); + for (const [id, c, x, t] of db.prepare('SELECT id, concept_id, CAST(external_id AS TEXT), text FROM item').raw().iterate()) { + node.set(id, 'i:' + conceptCode.get(c) + ':' + (x != null ? x : t)); + } + const pcode = new Map(db.prepare('SELECT id, code FROM property').raw().all()); + const key = (id) => (id == null ? null : node.get(id) ?? '?' + id); + const uses = new Map(db.prepare('SELECT use_id, code FROM item_use').raw().all()); + const out = {}; + const view = (name, sql, fn) => { + const m = new Map(); + for (const r of db.prepare(sql).raw().iterate()) { + const k = JSON.stringify(fn(r)); + m.set(k, (m.get(k) || 0) + 1); + } + out[name] = m; + }; + view('concept', 'SELECT code, active, display FROM concept', (r) => r); + view('item', 'SELECT concept_id, kind, CAST(external_id AS TEXT), language, use_id, text, active, preferred, rank FROM item', + ([c, ...r]) => [conceptCode.get(c), r[0], r[1], r[2], uses.get(r[3]) ?? null, ...r.slice(4)]); + view('item_use', 'SELECT system, code, display FROM item_use', (r) => r); + view('property', `SELECT code, uri, display, concept_id, shape, role, fhir_type, subject_kind, target_kind, n_rows, subsumption, + closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, fields FROM property`, + (r) => { r[3] = key(r[3]); r[11] = r[11] == null ? null : pcode.get(r[11]); r[15] = r[15] == null ? null : pcode.get(r[15]); return r; }); + view('property_member', 'SELECT parent_id, child_id FROM property_member', ([a, b]) => [pcode.get(a), pcode.get(b)]); + view('link', 'SELECT subject_id, property_id, group_id, target_id, active FROM link', ([s, p, g, t, a]) => [key(s), pcode.get(p), g, key(t), a]); + view('literal', 'SELECT subject_id, property_id, group_id, CAST(value AS TEXT), active FROM literal', ([s, p, g, v, a]) => [key(s), pcode.get(p), g, v, a]); + view('identifier', 'SELECT property_id, value, subject_id, resolves FROM identifier', ([p, v, s, r]) => [pcode.get(p), String(v), key(s), r]); + // record node fields (property.fields types c / n, not the target column): numbers are node ids + const nodeCols = new Map(); + for (const [id, f] of db.prepare("SELECT id, fields FROM property WHERE shape = 'record'").raw().all()) { + const cols = (f ? JSON.parse(f) : []).filter((c) => !c.target); + nodeCols.set(id, new Set(cols.map((c, i) => (c.type === 'c' || c.type === 'n' ? i : -1)).filter((i) => i >= 0))); + } + view('record', 'SELECT relation_id, subject_id, target_id, active, fields FROM record', ([rel, s, t, a, f]) => { + const cols = nodeCols.get(rel) || new Set(); + const fields = f ? JSON.parse(f).map((v, i) => (cols.has(i) && typeof v === 'number' ? key(v) : v)) : null; + return [pcode.get(rel), key(s), key(t), a, fields]; + }); + view('mapping', 'SELECT concept_id, property_id, system, version, code, display, relationship FROM mapping', + ([c, p, ...r]) => [key(c), p == null ? null : pcode.get(p), ...r]); + view('value_label', 'SELECT property_id, CAST(value AS TEXT), display FROM value_label', ([p, ...r]) => [pcode.get(p), ...r]); + return { out, conceptCode, node, pcode, key }; +} + +/** + * @param {string} A first .db + * @param {string} B second .db + * @param {object} [o] { log (default: silent), examples (default 5) } + * @returns report: tables (row counts), codeSystem_a / _b, facts (per view: onlyA, onlyB, examplesA, + * examplesB: decoded tuples), sets (identicalNumbering, byKind: {same, differ, onlyA, onlyB}) + */ +function diffFiles(A, B, o = {}) { + const nEx = o.examples ?? 5; + const log = o.log || (() => {}); + const da = new Database(A, { readonly: true }); + const dbb = new Database(B, { readonly: true }); + try { + const report = { a: A, b: B, tables: {}, facts: {}, sets: {} }; + for (const t of [...FACTS, 'ix_set']) { + report.tables[t] = { a: da.prepare(`SELECT count(*) FROM ${t}`).pluck().get(), b: dbb.prepare(`SELECT count(*) FROM ${t}`).pluck().get() }; + } + const cs = (d) => d.prepare('SELECT uri, version, concept_count, active_count FROM code_system WHERE served = 1').get(); + report.codeSystem_a = cs(da); + report.codeSystem_b = cs(dbb); + const ka = keyed(da), kb = keyed(dbb); + for (const v of FACTS) { + const a = ka.out[v], b = kb.out[v]; + const onlyA = [], onlyB = []; + for (const [k, n] of a) { const m = b.get(k) || 0; for (let i = m; i < n; i++) onlyA.push(k); } + for (const [k, n] of b) { const m = a.get(k) || 0; for (let i = m; i < n; i++) onlyB.push(k); } + report.facts[v] = { onlyA: onlyA.length, onlyB: onlyB.length, + examplesA: onlyA.slice(0, nEx).map((k) => JSON.parse(k)), examplesB: onlyB.slice(0, nEx).map((k) => JSON.parse(k)) }; + log(` ${v.padEnd(16)} onlyA ${onlyA.length} onlyB ${onlyB.length}`); + } + // sets + const order = (d) => d.prepare('SELECT code FROM concept ORDER BY id').pluck().all(); + const oa = order(da), ob = order(dbb); + const identical = oa.length === ob.length && oa.every((c, i) => c === ob[i]); + report.sets.identicalNumbering = identical; + const setRows = (d, k) => { + const m = new Map(); + for (const [kind, p, vk, value, data] of d.prepare('SELECT kind, property_id, value_kind, value, data FROM ix_set').raw().iterate()) { + const v = vk === 1 ? k.key(value) : typeof value === 'number' ? value : String(value); + const id = JSON.stringify([kind, p ? k.pcode.get(p) : 0, vk, v]); + let members; + if (identical) members = data.toString('hex'); + else members = Array.from(sets.RoaringBitmap32.deserialize(data, 'portable')).map((x) => k.conceptCode.get(x)).sort().join(','); + m.set(id, { kind, members }); + } + return m; + }; + const sa = setRows(da, ka), sb = setRows(dbb, kb); + const byKind = {}; + const of = (k) => byKind[k] || (byKind[k] = { same: 0, differ: 0, onlyA: 0, onlyB: 0, examples: [] }); + for (const [id, x] of sa) { + const y = sb.get(id); + const s = of(x.kind); + if (!y) { s.onlyA++; if (s.examples.length < nEx) s.examples.push(['onlyA', JSON.parse(id)]); } else if (y.members === x.members) s.same++; + else { s.differ++; if (s.examples.length < nEx) s.examples.push(['differ', JSON.parse(id)]); } + } + for (const [id, y] of sb) if (!sa.has(id)) { const s = of(y.kind); s.onlyB++; if (s.examples.length < nEx) s.examples.push(['onlyB', JSON.parse(id)]); } + report.sets.byKind = byKind; + return report; + } finally { + da.close(); + dbb.close(); + } +} + +module.exports = { diffFiles }; + +if (require.main === module) { + const args = process.argv.slice(2); + const [A, B] = args.filter((x) => !x.startsWith('--')); + const jsonAt = args.indexOf('--json'); + const exAt = args.indexOf('--examples'); + const r = diffFiles(A, B, { log: console.log, examples: exAt >= 0 ? Number(args[exAt + 1]) : 5 }); + if (jsonAt >= 0) fs.writeFileSync(args[jsonAt + 1], JSON.stringify(r, null, 2)); + else console.log(JSON.stringify({ tables: r.tables, sets: r.sets }, null, 2)); +} diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js new file mode 100644 index 00000000..a5119598 --- /dev/null +++ b/tx/importers/sqlite-v2/indexes.js @@ -0,0 +1,329 @@ +'use strict'; + +// Index builder for the terminology file: drops and recreates every ix_* table from the fact tables. +// Runnable on a built file whose ix_* tables were dropped (node indexes.js ); the result is +// the same as the builder's. Rows listed in meta 'derived-by-importer' (terminology logic: SNOMED +// normal forms in ix_key, the SNOMED walk in ix_order, LOINC's orders) are kept as they are, with +// their meta keys. Facts about an index are meta keys 'ix..', owned here. +// +// ix_set all, active, leaf, descendants (closure of the active subsumption links between +// concepts, or the explicit pairs of the catalog's closure_from property), +// property = value (for the properties a filter can name: filterable, or a member of +// a filterable union) and has-property (every property), from the active link / +// literal rows about concepts (not for a closure_from source: its sets are the +// descendants), +// record members (active rows about concepts) +// ix_in links by target, for the catalog rows with by_target = 1 +// ix_by_subject identifier rows by subject, for the catalog rows with by_subject = 1 +// ix_text_display concept.display, rowid = concept id +// ix_text_item item.text, rowid = item id +// ix_order the reader's system order (tx/sqlite-v2/orders.js computeOrder: rank and ids) +// ix_word the reader's word index (tx/sqlite-v2/text-index.js rules over the names +// tx/sqlite-v2/text-index.js eachName lists) +// ix_key nothing generic (SNOMED normal forms are derived-by-importer) + +const Database = require('better-sqlite3'); +const { serialize, rangeSet, descendantsFromEdges, descendantsFromPairs } = require('../sqlite-v2/sets'); +const sets = require('../sqlite-v2/sets'); +const dialectOf = (uri) => require('../../sqlite-v2/dialects').dialectFor(uri).name; + +const KIND = { all: 1, active: 2, leaf: 3, descendants: 4, prop: 5, hasProp: 6, record: 7 }; +const VK = { none: 0, node: 1, literal: 2 }; +const ORDER_BLOCK = 1024; + +function ixDdl() { + const { schemaSections } = require('./builder'); + // IF NOT EXISTS: a table that holds derived-by-importer rows is kept (rows of other names deleted) + return schemaSections().ix.replace(/CREATE (TABLE|INDEX|VIRTUAL TABLE) (?!IF NOT EXISTS)/g, 'CREATE $1 IF NOT EXISTS '); +} + +function ixTables(db) { + return db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'ix\\_%' ESCAPE '\\' AND sql IS NOT NULL AND name NOT LIKE 'ix\\_text\\_%\\_%' ESCAPE '\\'").pluck().all(); +} + +/** meta 'derived-by-importer': [{table, name}] (ix_key / ix_order rows the importer writes) */ +function derivedByImporter(db) { + const v = db.prepare("SELECT value FROM main.meta WHERE key = 'derived-by-importer'").pluck().get(); + const list = v ? JSON.parse(v) : []; + for (const d of list) if (d.table !== 'ix_key' && d.table !== 'ix_order') throw new Error(`derived-by-importer: ${d.table} rows cannot be kept`); + return list; +} + +/** + * drop every ix_* table (FTS shadow tables go with their virtual table) and the ix meta keys, + * except the derived-by-importer rows: their tables keep those rows (and only those) + */ +function dropIndexes(db) { + const derived = derivedByImporter(db); + const keep = new Map(); + for (const d of derived) { if (!keep.has(d.table)) keep.set(d.table, []); keep.get(d.table).push(d.name); } + for (const t of ixTables(db)) { + const names = keep.get(t); + if (names) db.prepare(`DELETE FROM "${t}" WHERE name NOT IN (SELECT value FROM json_each(?))`).run(JSON.stringify(names)); + else db.exec(`DROP TABLE IF EXISTS "${t}"`); + } + const keepKeys = derived.map((d) => `ix.${d.table}.${d.name}.`); + for (const k of db.prepare("SELECT key FROM meta WHERE key LIKE 'ix.%'").pluck().all()) { + if (!keepKeys.some((p) => k.startsWith(p))) db.prepare('DELETE FROM meta WHERE key = ?').run(k); + } +} + +/** + * @param {Database} db a writable connection to a built file + * @param {object} [opts] { log, time(name, fn) } + */ +function buildIndexes(db, opts = {}) { + const time = opts.time || ((name, fn) => fn()); + dropIndexes(db); + db.exec(ixDdl()); + const cs = db.prepare('SELECT cs_id, uri, concept_count AS n, active_count AS a, default_language FROM main.code_system WHERE served = 1').get(); + const n = cs.n; + const stats = {}; + db.exec('BEGIN'); + stats.sets = time('ix_set', () => buildSets(db, n, cs.a)); + stats.in = time('ix_in', () => db.prepare(`INSERT INTO ix_in SELECT target_id, property_id, active, group_id, coalesce(seq, 0), subject_id + FROM main.link WHERE property_id IN (SELECT id FROM main.property WHERE by_target = 1) ORDER BY 1, 2, 3, 4, 5, 6`).run().changes); + stats.bySubject = time('ix_by_subject', () => db.prepare(`INSERT INTO ix_by_subject SELECT subject_id, property_id, value + FROM main.identifier WHERE property_id IN (SELECT id FROM main.property WHERE by_subject = 1) ORDER BY 1, 2, 3`).run().changes); + stats.textDisplay = time('ix_text_display', () => db.prepare(`INSERT INTO ix_text_display(rowid, text) SELECT id, display FROM main.concept + WHERE display IS NOT NULL AND display <> '' ORDER BY id`).run().changes); + stats.textItem = time('ix_text_item', () => db.prepare('INSERT INTO ix_text_item(rowid, text) SELECT id, text FROM main.item ORDER BY id').run().changes); + db.exec('COMMIT'); + + // the reader's orders and word index, from the fact tables (tx/sqlite-v2/orders.js, text-index.js) + const dialect = dialectOf(cs.uri); + const { Store } = require('../../sqlite-v2/store'); + const { orderKind, computeOrder } = require('../../sqlite-v2/orders'); + const { computeTextIndexFrom, indexed, FORMAT } = require('../../sqlite-v2/text-index'); + const { stem } = require('../../library/text-match'); + db.exec('BEGIN'); + const kind = orderKind(dialect); + const derived = new Set(derivedByImporter(db).filter((d) => d.table === 'ix_order').map((d) => d.name)); + if (kind && !['rank', 'ids'].every((x) => derived.has(x))) { + stats.order = time('ix_order', () => writeOrder(db, computeOrder(db, kind, n, { walk: false }), derived)); + } + if (indexed(dialect)) { + const store = new Store(db.name, { db, unregistered: true }); + stats.words = time('ix_word', () => writeWords(db, computeTextIndexFrom((fn) => store.eachSearchName(dialect, fn), dialect, n), stem)); + db.prepare("INSERT OR REPLACE INTO main.meta VALUES ('ix.ix_word.format', ?)").run(FORMAT); + } + // the 'active' order from a walk an importer kept (derived-by-importer); importers that write + // the walk after this call it again + stats.activeOrder = writeActiveOrder(db); + db.exec('COMMIT'); + return stats; +} + +function buildSets(db, n, activeCount) { + const ins = db.prepare('INSERT INTO ix_set VALUES (?, ?, ?, ?, ?, ?)'); + const stats = {}; + // the sets by key, written after the reads (one connection); a key met twice (rows about + // concepts, then rows about items projected to their concepts) is the union + const out = new Map(); + const put = (kind, pid, vk, value, bm) => { + if (bm.size === 0) return; + const k = kind + '|' + pid + '|' + vk + '|' + (typeof value === 'string' ? 's' : 'n') + value; + const cur = out.get(k); + if (cur) cur[4].orInPlace(bm); else out.set(k, [kind, pid, vk, value, bm]); + }; + // rows about items count for their concept (the item -> concept projection: an atom's + // relationship, a description's refset row); language relations rank displays, no sets + const hasItemRows = (table) => !!db.prepare(`SELECT 1 FROM main.${table} WHERE subject_id > ${n} LIMIT 1`).get(); + const projected = (table, cols, where) => `SELECT ${cols}, i.concept_id FROM main.${table} x JOIN main.item i ON i.id = x.subject_id + WHERE x.active = 1 AND x.subject_id > ${n} ${where} ORDER BY 1, 2, 3`; + put(KIND.all, 0, VK.none, 0, rangeSet(1, n)); + put(KIND.active, 0, VK.none, 0, rangeSet(1, activeCount)); + + // descendants: the explicit pairs of a closure_from property, else the closure of the active + // subsumption links between concepts + const sub = db.prepare('SELECT id, closure_from FROM main.property WHERE subsumption = 1').all(); + const from = sub.map((p) => p.closure_from).filter((x) => x != null); + let res; + if (from.length) { + // explicit (descendant -> ancestor) pairs as links of the closure_from property + const [d, a] = intPairs(db.prepare(`SELECT subject_id, target_id FROM main.link WHERE active = 1 AND property_id IN (${from.join(',')}) + AND subject_id <= ${n} AND target_id <= ${n}`)); + res = descendantsFromPairs(n, d, a); + } else { + const [c, p] = sub.length + ? intPairs(db.prepare(`SELECT subject_id, target_id FROM main.link WHERE active = 1 AND property_id IN (${sub.map((x) => x.id).join(',')}) + AND subject_id <= ${n} AND target_id <= ${n}`)) + : [new Int32Array(0), new Int32Array(0)]; + res = descendantsFromEdges(n, c, p); + } + if (res.cyclic) throw new Error(`hierarchy has a cycle: ${res.cyclic} concepts could not be closed`); + const leaf = new sets.RoaringBitmap32(); + for (let id = 1; id <= n; id++) { + const d = res.desc[id]; + if (d) put(KIND.descendants, 0, VK.node, id, d); + else if (id <= activeCount) leaf.add(id); + } + put(KIND.leaf, 0, VK.none, 0, leaf); + + // property = value and has-property, from the active rows about concepts (not the closure + // sources: their rows are the descendants sets above) + const closureSources = from.length ? `AND property_id NOT IN (${from.join(',')})` : ''; + const has = new Map(); + const hasOf = (p) => { let b = has.get(p); if (!b) has.set(p, b = new sets.RoaringBitmap32()); return b; }; + // kind 5 sets only for what a filter can name: filterable rows, and the members of a filterable + // union (a REL's RELAs); has-property sets for every property + const named = new Set(db.prepare('SELECT id FROM main.property WHERE filterable = 1').pluck().all()); + const memberRows = db.prepare('SELECT parent_id, child_id FROM main.property_member').raw().all(); + for (let grew = true; grew;) { + grew = false; + for (const [a, c] of memberRows) if (named.has(a) && !named.has(c)) { named.add(c); grew = true; } + } + const passes = []; + for (const [table, val, vk] of [['link', 'target_id', VK.node], ['literal', 'value', VK.literal]]) { + passes.push([vk, `SELECT property_id, ${val}, subject_id FROM main.${table} WHERE active = 1 AND subject_id <= ${n} + ${table === 'link' ? closureSources : ''} ORDER BY property_id, ${val}, subject_id`]); + if (hasItemRows(table)) passes.push([vk, projected(table, `x.property_id, x.${val}`, table === 'link' ? closureSources.replace('property_id', 'x.property_id') : '')]); + } + for (const [vk, sql] of passes) { + const it = db.prepare(sql).raw().iterate(); + let curP = null, curV, members = []; + const flush = () => { + if (curP === null) return; + const bm = new sets.RoaringBitmap32(members); + if (named.has(curP)) put(KIND.prop, curP, vk, curV, bm); + hasOf(curP).orInPlace(bm); + members = []; + }; + // rows arrive grouped by (property, value); !== keeps 1 and '1' apart + for (const [p, v, s] of it) { + if (p !== curP || v !== curV) { flush(); curP = p; curV = v; } + members.push(s); + } + flush(); + } + // an inverse_of row's has-property set is the targets of the property it reverses (of + // each member, for a union): `child exists`, `AnswerList exists` read one bitmap + const union = new Map(); + for (const [a, c] of db.prepare('SELECT parent_id, child_id FROM main.property_member').raw().all()) { + if (!union.has(a)) union.set(a, []); + union.get(a).push(c); + } + const reversed = (pid) => (union.has(pid) ? union.get(pid).flatMap(reversed) : [pid]); + for (const [inv, of] of db.prepare('SELECT id, inverse_of FROM main.property WHERE inverse_of IS NOT NULL').raw().all()) { + const pids = reversed(of); + const ids = db.prepare(`SELECT DISTINCT target_id FROM main.link WHERE active = 1 AND subject_id <= ${n} AND target_id <= ${n} + AND property_id IN (${pids.join(',')}) ORDER BY 1`).pluck().all(); + if (ids.length) has.set(inv, new sets.RoaringBitmap32(ids)); + } + // a property with both shapes has one has-property set (the union) + for (const [p, bm] of [...has].sort((a, b) => a[0] - b[0])) put(KIND.hasProp, p, VK.none, 0, bm); + + // record members (active rows about concepts, and about items projected), per relation + const lang = db.prepare("SELECT id FROM main.property WHERE role = 'language'").pluck().all(); + const recordPasses = [`SELECT DISTINCT relation_id, subject_id FROM main.record WHERE active = 1 AND subject_id <= ${n} ORDER BY 1, 2`]; + if (hasItemRows('record')) recordPasses.push(projected('record', 'x.relation_id, 0', lang.length ? `AND x.relation_id NOT IN (${lang.join(',')})` : '').replace('ORDER BY 1, 2, 3', 'ORDER BY 1, 3')); + for (const sql of recordPasses) { + let cur = null, members = []; + const flushR = () => { if (cur !== null) put(KIND.record, cur, VK.none, 0, new sets.RoaringBitmap32(members)); members = []; }; + for (const row of db.prepare(sql).raw().iterate()) { + const r = row[0], s = row[row.length - 1]; + if (r !== cur) { flushR(); cur = r; } + members.push(s); + } + flushR(); + } + for (const [kind, pid, vk, value, bm] of out.values()) { + const buf = serialize(bm); + ins.run(kind, pid, vk, value, bm.size, buf); + const st = stats[kind] || (stats[kind] = { sets: 0, members: 0, bytes: 0 }); + st.sets++; st.members += bm.size; st.bytes += buf.length; + } + const names = Object.fromEntries(Object.entries(KIND).map(([k, v]) => [v, k])); + return Object.fromEntries(Object.entries(stats).map(([k, s]) => [names[k], s])); +} + +/** + * {rank, ids, walk} Uint32Arrays -> ix_order rows of ORDER_BLOCK entries (names in `skip`: kept + * as the importer wrote them). An array's `reached` (the SNOMED walk: how many concepts the walk + * reaches) goes to meta 'ix.ix_order..reached'. + */ +function writeOrder(db, order, skip = new Set()) { + const ins = db.prepare('INSERT INTO ix_order VALUES (?, ?, ?)'); + let rows = 0; + for (const name of ['rank', 'ids', 'walk']) { + const a = order[name]; + if (!a || skip.has(name)) continue; + rows += writeOrderArray(db, name, a, ins); + } + return rows; +} + +function writeOrderArray(db, name, a, ins = db.prepare('INSERT INTO ix_order VALUES (?, ?, ?)')) { + let rows = 0; + for (let b = 0; b * ORDER_BLOCK < a.length; b++) { + const part = a.subarray(b * ORDER_BLOCK, Math.min(a.length, (b + 1) * ORDER_BLOCK)); + ins.run(name, b, toLE(part)); + rows++; + } + if (a.reached != null) db.prepare('INSERT OR REPLACE INTO main.meta VALUES (?, ?)').run(`ix.ix_order.${name}.reached`, String(a.reached)); + return rows; +} + +/** + * The standard order 'active': the walk restricted to the active concepts (ids 1..active_count), + * stored only where they are not a prefix of the walk (else a reader takes the walk's first + * active_count entries). Called after the walk is written; replaces an earlier 'active'. + * @returns {number} rows written (0: not needed) + */ +function writeActiveOrder(db) { + db.prepare("DELETE FROM main.ix_order WHERE name = 'active'").run(); + const blocks = db.prepare("SELECT data FROM main.ix_order WHERE name = 'walk' ORDER BY block").pluck().all(); + if (!blocks.length) return 0; + const buf = Buffer.concat(blocks); + const walk = new Uint32Array(buf.length / 4); + for (let i = 0; i < walk.length; i++) walk[i] = buf.readUInt32LE(i * 4); + const a = db.prepare('SELECT active_count FROM main.code_system WHERE served = 1').pluck().get(); + let prefix = walk.length >= a; + for (let i = 0; prefix && i < a; i++) if (walk[i] > a) prefix = false; + if (prefix) return 0; + return writeOrderArray(db, 'active', walk.filter((id) => id <= a)); +} + +function toLE(a) { + const buf = Buffer.alloc(a.length * 4); + for (let i = 0; i < a.length; i++) buf.writeUInt32LE(a[i], i * 4); + return buf; +} + +/** computeTextIndex's Map(lang -> {words, counts}) -> ix_word rows; the counts in the row with word '' */ +function writeWords(db, byLang, stem) { + const ins = db.prepare('INSERT INTO ix_word VALUES (?, ?, ?, ?)'); + let words = 0; + for (const [lang, x] of byLang) { + for (const [w, ids] of x.words) { + if (w === '') throw new Error("ix_word: an empty word (the row with word '' holds the counts)"); + ins.run(lang, w, stem(w, lang), new sets.RoaringBitmap32(ids).serialize('portable')); + words++; + } + if (x.counts) ins.run(lang, '', '', Buffer.from(x.counts.buffer, x.counts.byteOffset, x.counts.byteLength)); + } + return words; +} + +function intPairs(stmt) { + const a = [], b = []; + for (const [x, y] of stmt.raw().iterate()) { a.push(x); b.push(y); } + return [Int32Array.from(a), Int32Array.from(b)]; +} + +module.exports = { buildIndexes, dropIndexes, ixTables, derivedByImporter, writeOrderArray, writeActiveOrder, KIND, VK }; + +// node indexes.js [--drop-only]: rebuild (or only drop) the ix_* tables of a built file +if (require.main === module) { + const [file, flag] = process.argv.slice(2); + const db = new Database(file); + db.pragma('journal_mode = OFF'); + db.pragma('synchronous = OFF'); + const t0 = Date.now(); + if (flag === '--drop-only') { dropIndexes(db); db.exec('VACUUM'); console.log('dropped'); } else { + const s = buildIndexes(db, { time: (name, fn) => { const t = Date.now(); const r = fn(); console.error(`${name}: ${((Date.now() - t) / 1000).toFixed(1)} s`); return r; } }); + require('./builder').analyze(db); + console.log(JSON.stringify({ seconds: (Date.now() - t0) / 1000, ...s })); + } + db.close(); +} diff --git a/tx/importers/sqlite-v2/numbering.js b/tx/importers/sqlite-v2/numbering.js new file mode 100644 index 00000000..9472c135 --- /dev/null +++ b/tx/importers/sqlite-v2/numbering.js @@ -0,0 +1,115 @@ +'use strict'; + +// Dense concept numbering for the sqlite-v2 schema. +// +// concept_id is assigned here, once, at import. It is a 1-based position in this order: +// +// 1. active concepts, depth-first over the active hierarchy edges between active concepts. +// The walk is topological: a concept is numbered when the LAST of its parents has been +// numbered, so every ancestor gets a smaller id than its descendants. Roots and +// siblings are visited in (sort key, code) order. +// 2. active concepts the walk could not reach (only possible with a cycle), in (key, code) +// order. +// 3. inactive concepts, in (key, code) order. +// +// So `active` is exactly the range [1, activeCount] and, for every active concept A, every +// descendant of A has an id greater than A's. With polyhierarchy a concept lives under its +// last-visited parent; subtrees are still mostly contiguous id ranges, which is what makes +// the Roaring descendant sets small. + +const DIGITS = /^\d+$/; + +// Deterministic code order: all-digit codes (SNOMED, RxNorm) compare numerically (length +// first, then lexically; no BigInt needed for 18-digit SCTIDs); anything else lexically. +function compareCodes(a, b) { + if (a.length !== b.length && DIGITS.test(a) && DIGITS.test(b)) return a.length - b.length; + return a < b ? -1 : a > b ? 1 : 0; +} + +/** + * @param {object} input + * @param {string[]} input.codes provisional index -> code (index 0..n-1) + * @param {Uint8Array} input.active provisional index -> 1/0 + * @param {Int32Array} input.childOf hierarchy edge i: child index + * @param {Int32Array} input.parentOf hierarchy edge i: parent index + * @param {Float64Array|Int32Array} [input.sortKey] optional per-index sort key (smaller first) + * @returns {{ order: Int32Array, idOf: Int32Array, activeCount: number, reached: number, + * unreached: number, roots: number }} + * order[k] = provisional index of the concept that gets concept_id k+1; + * idOf[i] = concept_id (1-based) of provisional index i. + */ +function numberConcepts(input) { + const { codes, active, childOf, parentOf } = input; + const n = codes.length; + const key = input.sortKey || null; + const cmp = (a, b) => (key ? key[a] - key[b] : 0) || compareCodes(codes[a], codes[b]); + + // Edges used for ordering: active child, active parent, no self loops, de-duplicated. + // (child * n + parent stays below 2^53 for any realistic n.) + let pairs = new Float64Array(childOf.length); + let m = 0; + for (let e = 0; e < childOf.length; e++) { + const c = childOf[e], p = parentOf[e]; + if (c === p || !active[c] || !active[p]) continue; + pairs[m++] = c * n + p; + } + pairs = pairs.subarray(0, m).sort(); + let u = 0; + for (let i = 0; i < m; i++) if (i === 0 || pairs[i] !== pairs[u - 1]) pairs[u++] = pairs[i]; + pairs = pairs.subarray(0, u); + m = u; + + // CSR child lists (sorted by key, code) and remaining-parent counts. + const childStart = new Int32Array(n + 1); + const remaining = new Int32Array(n); + for (const x of pairs) { const p = x % n; childStart[p + 1]++; remaining[Math.floor(x / n)]++; } + for (let i = 0; i < n; i++) childStart[i + 1] += childStart[i]; + const children = new Int32Array(m); + const fill = childStart.slice(0, n); + for (const x of pairs) { const p = x % n; children[fill[p]++] = Math.floor(x / n); } + for (let p = 0; p < n; p++) { + const s = childStart[p], e = childStart[p + 1]; + if (e - s > 1) children.set(Array.from(children.subarray(s, e)).sort(cmp), s); + } + + const roots = []; + for (let i = 0; i < n; i++) if (active[i] && remaining[i] === 0) roots.push(i); + roots.sort(cmp); + + const order = new Int32Array(n); + const placed = new Uint8Array(n); + let k = 0; + const nodeStack = new Int32Array(n); + const curStack = new Int32Array(n); + for (const r of roots) { + order[k++] = r; placed[r] = 1; + let sp = 0; + nodeStack[0] = r; curStack[0] = childStart[r]; + while (sp >= 0) { + const node = nodeStack[sp]; + if (curStack[sp] >= childStart[node + 1]) { sp--; continue; } + const c = children[curStack[sp]++]; + if (--remaining[c] !== 0) continue; // another parent is still to come + order[k++] = c; placed[c] = 1; + sp++; nodeStack[sp] = c; curStack[sp] = childStart[c]; + } + } + const reached = k; + + const rest = []; + for (let i = 0; i < n; i++) if (active[i] && !placed[i]) rest.push(i); + rest.sort(cmp); + for (const i of rest) { order[k++] = i; placed[i] = 1; } + const activeCount = k; + + const inactive = []; + for (let i = 0; i < n; i++) if (!active[i]) inactive.push(i); + inactive.sort(cmp); + for (const i of inactive) order[k++] = i; + + const idOf = new Int32Array(n); + for (let j = 0; j < n; j++) idOf[order[j]] = j + 1; + return { order, idOf, activeCount, reached, unreached: rest.length, roots: roots.length }; +} + +module.exports = { numberConcepts, compareCodes }; diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql new file mode 100644 index 00000000..1941df72 --- /dev/null +++ b/tx/importers/sqlite-v2/schema.sql @@ -0,0 +1,195 @@ +-- Terminology file (meta format 'tx-terminology/1'): one code system version per file, in a +-- terminology-neutral model (tx/sqlite-v2/README.md). Nodes are concepts (ids 1..N, active first) +-- and items below them (terms, descriptions, atoms, definitions; ids above N), in one id space. +-- Statements have four shapes: link (subject -> node), literal (subject -> value), identifier +-- (value -> subject) and record (an n-ary row about a subject). The catalog (`property`) says for +-- every property, relation and scheme where its rows are and what may search it. Fact tables first, +-- then the index tables (ix_*), which are rebuildable from the facts (indexes.js). +-- +-- Sections: `-- @facts` (created before the load), `-- @fact-indexes` (secondary indexes on the +-- fact tables, created after the bulk load), `-- @ix` (index tables: indexes.js drops and +-- recreates them from the fact tables). +-- +-- Statistics: a file carries sqlite_stat1 and no sqlite_stat4 (the builder runs ANALYZE, then drops +-- sqlite_stat4). With stat4 SQLite re-plans a `col = ?` statement on every bind. Readers never ANALYZE. + +-- @facts +CREATE TABLE code_system ( + cs_id INTEGER PRIMARY KEY, uri TEXT NOT NULL, version TEXT NOT NULL, + name TEXT, title TEXT, description TEXT, release_date TEXT, + content TEXT NOT NULL, case_sensitive INTEGER, hierarchy_meaning TEXT, default_language TEXT, + compositional INTEGER, -- FHIR CodeSystem.compositional: codes may be expressions, so no + -- expansion of the system is closed (SNOMED CT) + served INTEGER NOT NULL, -- 1 for the file's system; 0 for sources that only contribute items + concept_count INTEGER NOT NULL, active_count INTEGER NOT NULL, + resource TEXT -- FHIR CodeSystem JSON without concepts, when there is one +); +-- release facts with no column (displayContexts, moduleDependencies, languages, edition, titles), the format +-- and provenance, facts about indexes (ix.*), and behaviour settings: behaviour. = a JSON value, +-- how the system is presented (grammar, lookupName, description, versionAlgorithm, expansionOrder, +-- designationUses, distinctDesignationTexts, lookupSkipsMixedLinks, aliasProperty, aliasExtension, +-- preferredForLanguage, aliasLiterals, filters; +-- values and defaults in tx/sqlite-v2/README.md). A reader refuses a file with a key or value it +-- does not know. +CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID; + +CREATE TABLE concept ( + id INTEGER PRIMARY KEY, cs_id INTEGER NOT NULL, code TEXT NOT NULL, active INTEGER NOT NULL, + display TEXT -- derived: the default display +); + +CREATE TABLE item ( + id INTEGER PRIMARY KEY, -- > every concept id + concept_id INTEGER NOT NULL, + kind INTEGER NOT NULL, -- 0 term, 1 definition (a designation too only when it has a use_id) + external_id, -- its id in the source (description SCTID, RXAUI); NULL if none; INTEGER + -- when the source id is a canonical decimal integer, else TEXT + cs_id INTEGER NOT NULL, -- the asserting system (a served = 0 row for foreign atoms) + language TEXT, use_id INTEGER, text TEXT NOT NULL, + active INTEGER NOT NULL, -- an inactive item is still a designation of its concept (RxNorm: an archived + -- concept's RXNATOMARCHIVE atoms, active = 0) + preferred INTEGER NOT NULL DEFAULT 0, -- the source's own preferred flag for its language, if it has one + rank INTEGER -- derived: display order within the concept under meta.displayContexts +); +CREATE TABLE item_use (use_id INTEGER PRIMARY KEY, system TEXT, code TEXT NOT NULL, display TEXT); + +CREATE TABLE property ( -- the catalog: properties, refsets, relations + id INTEGER PRIMARY KEY, cs_id INTEGER NOT NULL, code TEXT NOT NULL, uri TEXT, display TEXT, + concept_id INTEGER, -- the concept that defines it, when it is one (SNOMED attribute, refset) + shape TEXT NOT NULL, -- 'link' | 'literal' | 'both' | 'identifier' | 'record' | 'union' + -- ('union': only property_member rows, computed at build) + role TEXT, -- NULL or 'language': a record relation on items that ranks displays + fhir_type TEXT, -- literal type + subject_kind TEXT, -- 'concept' | 'item' | 'both' (computed at build; NULL when n_rows = 0) + target_kind TEXT, -- 'concept' | 'item' | 'both' (computed; link / record target) + n_rows INTEGER NOT NULL, -- computed; 0 is legal (a name that exists but selects nothing) + subsumption INTEGER NOT NULL DEFAULT 0, -- child -> parent edge of the hierarchy + closure_from INTEGER, -- property whose explicit pairs are the closure (LOINC, OMOP); NULL = derive + filterable INTEGER NOT NULL DEFAULT 1, -- a FHIR filter may name it + refinable INTEGER NOT NULL DEFAULT 0, -- an ECL attribute refinement may name it + wildcard INTEGER NOT NULL DEFAULT 0, -- included in `* : * = x` + inverse_of INTEGER, -- a virtual property: the reverse of another (which may be a union) + by_target INTEGER NOT NULL DEFAULT 0, -- its links are read by target (ix_in); set per property by the importer + by_subject INTEGER NOT NULL DEFAULT 0, -- shape 'identifier': its rows are read by subject (ix_by_subject); the + -- builder's default for an identifier row is 1, an importer sets 0 for + -- rows only ever read by value (RxNorm atom relationships AUI:*) + ordered INTEGER NOT NULL DEFAULT 0, -- link.seq orders a subject's targets, and the order is part of the answer + filter_ops TEXT, -- JSON list of the FHIR filter operators a filter on it accepts (NULL: the + -- server's rule for the system) + report TEXT, -- when $lookup reports it: 'named' (only when asked for by name), 'always' + -- (also listed on expansions); NULL: the server's rule + fields TEXT, -- record shape: JSON [{name, type[, target: true]}] in source + -- column order; type c component (node id, or the source's code when it is + -- not a node here), n node, i int, s string, t time (YYYYMMDD int); `target` + -- marks the column held in record.target_id (the others are record.fields, + -- in order) + UNIQUE (cs_id, code) +); +CREATE TABLE property_member (parent_id INTEGER NOT NULL, child_id INTEGER NOT NULL, + PRIMARY KEY (parent_id, child_id)) WITHOUT ROWID; -- a property that is the union of others + +CREATE TABLE link ( + subject_id INTEGER NOT NULL, property_id INTEGER NOT NULL, group_id INTEGER NOT NULL, + target_id INTEGER NOT NULL, active INTEGER NOT NULL, + seq INTEGER, -- source order + PRIMARY KEY (subject_id, property_id, group_id, target_id, active) +) WITHOUT ROWID; + +CREATE TABLE literal ( + subject_id INTEGER NOT NULL, property_id INTEGER NOT NULL, group_id INTEGER NOT NULL, + value NOT NULL, active INTEGER NOT NULL, + PRIMARY KEY (subject_id, property_id, group_id, value, active) +) WITHOUT ROWID; + +CREATE TABLE identifier ( + property_id INTEGER NOT NULL, + value NOT NULL, -- INTEGER when a canonical decimal integer, else TEXT; read as text + subject_id INTEGER NOT NULL, + resolves INTEGER NOT NULL DEFAULT 0, -- 0 not a code; 1 an alias: accepted as a code and answered with + -- the subject's own code (ICD-11 short codes); 2 a code in its own + -- right: accepted and answered as written (NDC 11-digit forms). + -- A concept code always wins over an identifier with the same value. + PRIMARY KEY (property_id, value, subject_id) +) WITHOUT ROWID; + +CREATE TABLE record ( + relation_id INTEGER NOT NULL, -- property.id, shape 'record' + subject_id INTEGER NOT NULL, -- concept or item + seq INTEGER NOT NULL, -- 0.. the row's order within the relation (whole-relation source order) + target_id INTEGER, -- the field the schema marks `target: true`, when its value is a node here + active INTEGER NOT NULL, + fields TEXT, -- JSON array of the other fields, per property.fields. In a field typed + -- c or n, a JSON number is a node id of this file and a JSON string a + -- code that is not in the file + PRIMARY KEY (relation_id, subject_id, seq) +) WITHOUT ROWID; + +-- displays of literal values (LOINC CLASSTYPE 1 = 'Laboratory class') +CREATE TABLE value_label (property_id INTEGER NOT NULL, value NOT NULL, display TEXT NOT NULL, + PRIMARY KEY (property_id, value)) WITHOUT ROWID; + +CREATE TABLE mapping ( + concept_id INTEGER NOT NULL, property_id INTEGER, system TEXT NOT NULL, version TEXT, code TEXT NOT NULL, + display TEXT, + relationship TEXT NOT NULL, -- FHIR R4 ConceptMap equivalence codes (equivalent, wider, narrower, + -- relatedto, ...), as main's providers report them + PRIMARY KEY (concept_id, system, code) +) WITHOUT ROWID; + +-- optional, usually empty +CREATE TABLE resource (type TEXT NOT NULL, id TEXT NOT NULL, url TEXT, version TEXT, json TEXT NOT NULL, + PRIMARY KEY (type, id)) WITHOUT ROWID; -- resources the release defines that cannot be derived from its + -- facts (value sets that follow from stored records are not stored) +CREATE TABLE node_extra (id INTEGER PRIMARY KEY, json TEXT NOT NULL); -- FHIR extensions etc. for round-trip + +-- @fact-indexes +CREATE UNIQUE INDEX concept_code ON concept(cs_id, code); +CREATE INDEX item_concept ON item(concept_id); +CREATE INDEX item_external ON item(external_id) WHERE external_id IS NOT NULL; +-- the definition a concept shows: its kind 1 item with preferred = 1 (a partial index, so a concept +-- with none costs one probe of an index that is empty for LOINC and RxNorm) +CREATE INDEX item_definition ON item(concept_id) WHERE kind = 1 AND preferred = 1; +-- identifiers accepted as codes, by value: a probe must say `resolves > 0` (as well as value = ?) for +-- SQLite to use this partial index; without it the probe scans every identifier row +CREATE INDEX identifier_code ON identifier(value) WHERE resolves > 0; +CREATE INDEX resource_url ON resource(type, url, version); + +-- @ix +-- Rows that need terminology logic to build are written by the importer and listed in +-- meta 'derived-by-importer' (JSON [{table, name}]: ix_key / ix_order rows of that name, with +-- their meta keys 'ix.
..*'); indexes.js keeps them and rebuilds everything else. +-- Facts about an index are meta keys 'ix.
.'; the index builder owns them. +-- Roaring bitmaps (portable serialisation) of concept ids. kind: 1 all, 2 active, 3 leaf, +-- 4 descendants (value = the anchor concept), 5 property = value, 6 has property (for an inverse_of row: the +-- targets of the property it reverses), 7 record members +-- (property_id = the relation). value_kind: 0 none, 1 node (value = node id), 2 literal. Kind 5 sets exist +-- only for properties a filter can name: filterable = 1, and the members of a filterable union; any +-- other property is answered from link / literal. +CREATE TABLE ix_set (kind INTEGER, property_id INTEGER, value_kind INTEGER, value, card INTEGER, data BLOB, + PRIMARY KEY (kind, property_id, value, value_kind)) WITHOUT ROWID; +-- links by target, for the catalog rows with by_target = 1 only. +-- seq: link.seq, or 0 where the link has none. active and group_id are in the key so a reader +-- can take active group-0 rows (SNOMED children in release order) without visiting link. +CREATE TABLE ix_in (target_id INTEGER NOT NULL, property_id INTEGER NOT NULL, active INTEGER NOT NULL, + group_id INTEGER NOT NULL, seq INTEGER NOT NULL, subject_id INTEGER NOT NULL, + PRIMARY KEY (target_id, property_id, active, group_id, seq, subject_id)) WITHOUT ROWID; +-- identifier rows by subject, for the catalog rows with by_subject = 1 only (SNOMED CT alternate +-- identifiers, aliases); the value-keyed primary key of identifier serves every other read. +CREATE TABLE ix_by_subject (subject_id INTEGER NOT NULL, property_id INTEGER NOT NULL, value NOT NULL, + PRIMARY KEY (subject_id, property_id, value)) WITHOUT ROWID; +-- per-id arrays (little-endian Uint32), 1,024 entries per block. Standard names: rank (concept id -> place +-- in the system order), ids (place -> concept id), walk (the whole system in the built-in walk order), +-- active (walk restricted to the active concepts; stored only where they are not a prefix of walk), +-- hier_start / hier (LOINC: a concept's parent and child entries in the built-in order) +CREATE TABLE ix_order (name TEXT, block INTEGER, data BLOB, PRIMARY KEY (name, block)) WITHOUT ROWID; +CREATE TABLE ix_key (name TEXT, key TEXT, id INTEGER, PRIMARY KEY (name, key, id)) WITHOUT ROWID; +CREATE INDEX ix_key_id ON ix_key(name, id); -- the key of a node (SNOMED: a concept's normal form) +-- word index (tx/sqlite-v2/text-index.js rules; format in meta 'ix.ix_word.format'): per language +-- (primary subtag) every word with its stem and the concepts that have it (Roaring); the row with +-- word '' and stem '' holds the per-concept distinct-word counts (Uint16 by concept id), where the +-- rules keep them. +CREATE TABLE ix_word (lang TEXT NOT NULL, word TEXT NOT NULL, stem TEXT NOT NULL, ids BLOB NOT NULL, + PRIMARY KEY (lang, word)) WITHOUT ROWID; +CREATE INDEX ix_word_stem ON ix_word(lang, stem); +CREATE VIRTUAL TABLE ix_text_display USING fts5(text, tokenize = 'trigram', content = ''); +CREATE VIRTUAL TABLE ix_text_item USING fts5(text, tokenize = 'trigram', content = ''); diff --git a/tx/importers/sqlite-v2/sets.js b/tx/importers/sqlite-v2/sets.js new file mode 100644 index 00000000..0407c664 --- /dev/null +++ b/tx/importers/sqlite-v2/sets.js @@ -0,0 +1,121 @@ +'use strict'; + +// Set construction for the sqlite-v2 schema: every membership question is answered by one of +// these Roaring bitmaps over concept_id. Pure functions over typed arrays, so the shared +// final import stage and the tests use the same code. + +// roaring is loaded when a set is first made, not with this module: the importer CLI loads every +// importer module, and one without the engine's dependency installed should not warn about it +let roaring = null; +function R() { + return roaring || (roaring = require('roaring').RoaringBitmap32); +} + +const SET_KIND = Object.freeze({ + all: 1, active: 2, leaf: 3, descendants: 4, prop: 5, hasProp: 6, refset: 7, +}); + +/** Run-optimise and serialise ('portable' = the CRoaring cross-language format). */ +function serialize(bm) { + bm.runOptimize(); + bm.shrinkToFit(); + return bm.serialize('portable'); +} + +function rangeSet(lo, hiInclusive) { + const bm = new (R())(); + if (hiInclusive >= lo) bm.addRange(lo, hiInclusive + 1); + return bm; +} + +/** + * Descendant sets (self excluded) from child -> parent edges by the transitive closure. + * Children are folded into parents in reverse topological order (Kahn over the edge graph), + * so this does not depend on the numbering. + * + * @param {number} n concept count (ids 1..n) + * @param {Int32Array} childOf edge i child id + * @param {Int32Array} parentOf edge i parent id + * @returns {{ desc: Array, cyclic: number }} desc[id] (undefined = empty) + */ +function descendantsFromEdges(n, childOf, parentOf) { + // CSR children per parent, de-duplicated. + const start = new Int32Array(n + 2); + for (let e = 0; e < parentOf.length; e++) start[parentOf[e] + 1]++; + for (let i = 0; i <= n; i++) start[i + 1] += start[i]; + const kids = new Int32Array(parentOf.length); + const fill = start.slice(0, n + 1); + for (let e = 0; e < parentOf.length; e++) kids[fill[parentOf[e]]++] = childOf[e]; + const parentsStart = new Int32Array(n + 2); + for (let e = 0; e < childOf.length; e++) parentsStart[childOf[e] + 1]++; + for (let i = 0; i <= n; i++) parentsStart[i + 1] += parentsStart[i]; + const parents = new Int32Array(childOf.length); + const pfill = parentsStart.slice(0, n + 1); + for (let e = 0; e < childOf.length; e++) parents[pfill[childOf[e]]++] = parentOf[e]; + + const pending = new Int32Array(n + 1); // children not yet folded in + for (let p = 1; p <= n; p++) pending[p] = start[p + 1] - start[p]; + const desc = new Array(n + 1); + const queue = new Int32Array(n + 1); + let qh = 0, qt = 0; + for (let i = 1; i <= n; i++) if (pending[i] === 0) queue[qt++] = i; + let done = 0; + while (qh < qt) { + const node = queue[qh++]; + done++; + if (start[node + 1] > start[node]) { + const parts = [new (R())(kids.subarray(start[node], start[node + 1]))]; + for (let k = start[node]; k < start[node + 1]; k++) { + const d = desc[kids[k]]; + if (d) parts.push(d); + } + desc[node] = parts.length === 1 ? parts[0] : R().orMany(parts); + } + for (let k = parentsStart[node]; k < parentsStart[node + 1]; k++) { + const p = parents[k]; + if (--pending[p] === 0) queue[qt++] = p; + } + } + return { desc, cyclic: n - done }; +} + +/** + * Descendant sets from explicit (descendant, ancestor) pairs (e.g. LOINC PATH_TO_ROOT). + * Self pairs are ignored. + */ +function descendantsFromPairs(n, descOf, ancOf) { + const lists = new Map(); + for (let i = 0; i < descOf.length; i++) { + const a = ancOf[i], d = descOf[i]; + if (a === d) continue; + let l = lists.get(a); + if (!l) lists.set(a, l = []); + l.push(d); + } + const desc = new Array(n + 1); + for (const [a, l] of lists) desc[a] = new (R())(l); + return { desc, cyclic: 0 }; +} + +/** + * Group (key, member) rows that arrive sorted by key into sets. + * `rows` is an iterable of [key, member]; calls emit(key, RoaringBitmap32) once per key. + */ +function groupSorted(rows, emit) { + let cur, have = false; + let buf = new Uint32Array(1024), len = 0; + const flush = () => { + if (have) emit(cur, new (R())(buf.subarray(0, len))); + len = 0; + }; + for (const [key, member] of rows) { + if (!have || key !== cur) { flush(); cur = key; have = true; } + if (len === buf.length) { const b = new Uint32Array(buf.length * 2); b.set(buf); buf = b; } + buf[len++] = member; + } + flush(); +} + +module.exports = { SET_KIND, serialize, rangeSet, descendantsFromEdges, descendantsFromPairs, groupSorted }; +// (a getter, so that only a module that uses RoaringBitmap32 loads roaring) +Object.defineProperty(module.exports, 'RoaringBitmap32', { enumerable: true, get: R }); diff --git a/tx/importers/sqlite-v2/text.js b/tx/importers/sqlite-v2/text.js new file mode 100644 index 00000000..a3171f2a --- /dev/null +++ b/tx/importers/sqlite-v2/text.js @@ -0,0 +1,98 @@ +'use strict'; + +// Streaming text helpers for the sqlite-v2 importers. + +const fs = require('fs'); + +/** Lines of a UTF-8 file (no terminators, CR stripped), streamed in 4 MiB chunks. */ +async function* lines(filePath) { + let rest = ''; + for await (const chunk of fs.createReadStream(filePath, { encoding: 'utf8', highWaterMark: 1 << 22 })) { + const parts = (rest + chunk).split('\n'); + rest = parts.pop(); + for (const l of parts) yield l.endsWith('\r') ? l.slice(0, -1) : l; + } + if (rest) yield rest.endsWith('\r') ? rest.slice(0, -1) : rest; +} + +/** Tab-separated rows (RF2), header skipped. Yields arrays of fields. */ +async function* tsvRows(filePath) { + let first = true; + for await (const l of lines(filePath)) { + if (first) { first = false; continue; } + if (l) yield l.split('\t'); + } +} + +/** Split one CSV record (RFC 4180: quotes, doubled quotes, embedded commas/newlines). */ +function splitCsv(rec) { + const out = []; + let i = 0; + const n = rec.length; + while (i <= n) { + if (rec.charCodeAt(i) === 34) { // quoted + let v = ''; + i++; + for (;;) { + const q = rec.indexOf('"', i); + if (q < 0) { v += rec.slice(i); i = n; break; } + v += rec.slice(i, q); + if (rec.charCodeAt(q + 1) === 34) { v += '"'; i = q + 2; } else { i = q + 1; break; } + } + out.push(v); + const c = rec.indexOf(',', i); + i = c < 0 ? n + 1 : c + 1; + } else { + const c = rec.indexOf(',', i); + if (c < 0) { out.push(rec.slice(i)); break; } + out.push(rec.slice(i, c)); + i = c + 1; + if (i === n) { out.push(''); break; } + } + } + return out; +} + +/** + * CSV records as objects keyed by header name. A record whose quotes are unbalanced at the + * end of a line continues on the next line (LOINC has newlines inside quoted fields). + */ +async function* csvObjects(filePath) { + let header = null, pending = null, quotes = 0; + for await (const l of lines(filePath)) { + pending = pending === null ? l : `${pending}\n${l}`; + for (let i = 0; i < l.length; i++) if (l.charCodeAt(i) === 34) quotes++; + if (quotes % 2) continue; + const rec = pending; + pending = null; quotes = 0; + if (!rec) continue; + const f = splitCsv(rec); + if (!header) { header = f.map((h, k) => (k === 0 ? h.replace(/^\uFEFF/, '') : h)); continue; } + const o = {}; + for (let k = 0; k < header.length; k++) o[header[k]] = f[k] === undefined ? '' : f[k]; + yield o; + } +} + +/** First line of a file (for header sniffing). */ +function firstLine(filePath) { + const fd = fs.openSync(filePath, 'r'); + try { + const buf = Buffer.alloc(4096); + const n = fs.readSync(fd, buf, 0, buf.length, 0); + const t = buf.toString('utf8', 0, n); + const e = t.indexOf('\n'); + return (e < 0 ? t : t.slice(0, e)).replace(/\r$/, '').replace(/^\uFEFF/, ''); + } finally { fs.closeSync(fd); } +} + +/** Every regular file under dir, sorted. */ +function walk(dir, out = []) { + for (const e of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) { + const p = `${dir}/${e.name}`; + if (e.isDirectory()) { if (!e.name.startsWith('.')) walk(p, out); } else if (e.isFile()) out.push(p); + } + return out; +} + +module.exports = { lines, tsvRows, splitCsv, csvObjects, firstLine, walk }; diff --git a/tx/importers/sqlite-v2/verify-indexes.js b/tx/importers/sqlite-v2/verify-indexes.js new file mode 100644 index 00000000..9faf0423 --- /dev/null +++ b/tx/importers/sqlite-v2/verify-indexes.js @@ -0,0 +1,51 @@ +'use strict'; +// Check that the ix_* tables of a built terminology file are rebuildable from its fact tables: +// digest every ix_* table (FTS5 shadow tables included), drop them all, rebuild with indexes.js, +// digest again, compare. Modifies the file: run it on a copy. +// +// node tx/importers/sqlite-v2/verify-indexes.js + +const crypto = require('crypto'); +const Database = require('better-sqlite3'); +const { buildIndexes, dropIndexes } = require('./indexes'); + +function digests(db) { + const out = {}; + const tables = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'ix\\_%' ESCAPE '\\' AND sql NOT LIKE 'CREATE VIRTUAL%' ORDER BY name").pluck().all(); + for (const t of tables) { + const h = crypto.createHash('sha256'); + let rows = 0; + // every column, ordered by all of them + const cols = db.prepare(`PRAGMA table_info("${t}")`).all().length; + const by = Array.from({ length: cols }, (_, i) => i + 1).join(', '); + for (const r of db.prepare(`SELECT * FROM "${t}" ORDER BY ${by}`).raw().iterate()) { + for (const v of r) h.update(v === null ? '\u0000N' : Buffer.isBuffer(v) ? Buffer.concat([Buffer.from('\u0000B'), v]) : '\u0000' + typeof v + String(v)); + h.update('\u0001'); + rows++; + } + out[t] = { rows, sha256: h.digest('hex').slice(0, 16) }; + } + out['meta ix.*'] = db.prepare("SELECT group_concat(key || '=' || value, ';') FROM (SELECT * FROM meta WHERE key LIKE 'ix.%' ORDER BY key)").pluck().get(); + return out; +} + +if (require.main === module) { + const file = process.argv[2]; + const db = new Database(file); + db.pragma('journal_mode = OFF'); + db.pragma('synchronous = OFF'); + const before = digests(db); + dropIndexes(db); + const left = db.prepare("SELECT name FROM sqlite_master WHERE name LIKE 'ix\\_%' ESCAPE '\\'").pluck().all(); + const t0 = Date.now(); + buildIndexes(db); + const seconds = (Date.now() - t0) / 1000; + const after = digests(db); + db.close(); + const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(); + const diff = names.filter((n) => JSON.stringify(before[n]) !== JSON.stringify(after[n])); + console.log(JSON.stringify({ file, leftAfterDrop: left, rebuildSeconds: seconds, tables: names.length, differ: diff, before, after }, null, 2)); + process.exit(diff.length ? 1 : 0); +} + +module.exports = { digests }; diff --git a/tx/library.js b/tx/library.js index 0b493f82..cdc80fa0 100644 --- a/tx/library.js +++ b/tx/library.js @@ -79,6 +79,13 @@ async function folderSize(dir) { * based on the stated FHIR version, and the other (optional) context information * */ +// the code system each sqlite-v2 source type's file must hold (loadSqliteV2) +const SQLITE_V2_SYSTEMS = { + 'snomed-v2': 'http://snomed.info/sct', + 'loinc-v2': 'http://loinc.org', + 'rxnorm-v2': 'http://www.nlm.nih.gov/research/umls/rxnorm' +}; + class Library { /** * {Map} A list of code system factories that contains all the preloaded native code systems @@ -493,6 +500,12 @@ class Library { await this.loadIcd11(details, isDefault, mode); break; + case 'snomed-v2': + case 'loinc-v2': + case 'rxnorm-v2': + await this.loadSqliteV2(type, details, isDefault, mode); + break; + case 'npm': await this.loadNpm(packageManager, details, isDefault, mode, false); break; @@ -1035,6 +1048,26 @@ class Library { await this.#loadLocalSource(new FileContentLoader(filePath, cacheSubdir)); } + /** + * A SNOMED CT, LOINC or RxNorm file in the sqlite-v2 format (tx/sqlite-v2; source syntax + * `snomed-v2:`, `loinc-v2:`, `rxnorm-v2:`, with `!` as for the other types). + * Opt-in: the engine (and its roaring dependency) is required only when a library names such a + * file. The file is opened read-only, so tx-workers in a cluster load the same line as the master. + */ + async loadSqliteV2(type, details, isDefault, mode) { + const fn = await this.getOrDownloadFile(details); + if (mode !== "cs") { + return; + } + const { loadSqliteV2Factory } = require('./sqlite-v2'); + const factory = await loadSqliteV2Factory(this.i18n, fn); + const expected = SQLITE_V2_SYSTEMS[type]; + if (factory.system() !== expected) { + throw new Error(`${type}:${details}: the file holds ${factory.system()}, not ${expected}`); + } + this.registerProvider(fn, factory, isDefault); + } + /** * Relative paths in folder:/file: sources are resolved against the project root. * @private diff --git a/tx/sqlite-v2/.gitignore b/tx/sqlite-v2/.gitignore new file mode 100644 index 00000000..cc1b31de --- /dev/null +++ b/tx/sqlite-v2/.gitignore @@ -0,0 +1,2 @@ +# tools/test-cases-engine.sh runs (the default --out) +test-cases-runs/ diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md new file mode 100644 index 00000000..dd78b13d --- /dev/null +++ b/tx/sqlite-v2/README.md @@ -0,0 +1,197 @@ +# sqlite-v2: terminology files + +The `sqlite-v2` providers (`tx/sqlite-v2/`) serve SNOMED CT, LOINC and RxNorm from one SQLite file per +code system version. The importers in `tx/importers/` write those files; the format is +`tx/importers/sqlite-v2/schema.sql`. A file says what it is in `meta` `format` = `tx-terminology/1` +and `PRAGMA user_version = 1`. + +## The model + +A file holds one code system version as **nodes**, a **catalog** and **statements**. + +- **Nodes.** Concepts have ids 1..N, active ones first. Items (terms, descriptions, atoms, + definitions) hang under a concept and have ids above N. Both share one id space, so a statement + can be about either, and a set of concepts is a dense bitmap. +- **Statements** come in four shapes. The shape follows from the structure of the fact, not from the + terminology: + + | shape | table | read | examples | + |---|---|---|---| + | subject -> node | `link` | by subject; by target through `ix_in` | SNOMED CT relationships, LOINC parts and answer lists (ordered), RxNorm RELA, ancestor pairs | + | subject -> value | `literal` | by subject; sets in `ix_set` | concrete values, TTY, STATUS, effectiveTime | + | value -> subject | `identifier` | by value; by subject through `ix_by_subject` (rows with `by_subject = 1`) | SNOMED CT alternate identifiers, ICD-11 short codes, NDC 11-digit forms, RxNorm atom relationships (optional) | + | n-ary row about a subject | `record` | by relation, then subject | every SNOMED CT reference set, language reference sets included | + + Two-column facts are `link` or `literal`; anything with more columns, or several rows per pair, is + a `record`. A property can have both links and literals (shape `both`: SNOMED CT attributes that + have relationship rows and concrete values). +- **The catalog** (`property`) has one row per property, reference set, identifier scheme and + relation. It says where the rows are and what may search them (shape, subject and target kinds, + `filterable`, `refinable`, `wildcard`, `subsumption`, `closure_from`, `inverse_of`, unions through + `property_member`, `ordered`, `by_target`, `by_subject`, a record's field schema). Readers never probe tables to + find out. +- **Facts and indexes.** Fact tables hold what the release says. The `ix_*` tables are derived and + can be dropped and rebuilt from the facts (`indexes.js`; `verify-indexes.js` checks a file). A few + index rows need terminology logic (SNOMED CT normal forms, the SNOMED CT walk, LOINC's key order): + the importer writes those and lists them in `meta` `derived-by-importer`. Two derived columns sit + in fact tables, named as such: `concept.display` and `item.rank`. +- **Statistics.** A file carries `sqlite_stat1` and no `sqlite_stat4`: the builder runs `ANALYZE` and + then drops `sqlite_stat4` (`analyze()` in `builder.js`; `vacuumFile()` drops it too). With stat4 + SQLite re-plans a `col = ?` statement on every bind (better-sqlite3 on RxNorm: `item WHERE + concept_id = ?` 12.1 -> 8.0 us, an `ix_set` point read 16.1 -> 7.5 us without stat4); the benchmark + requests of the four editions give the same answers at the same speed with stat1 alone. Readers + never run `ANALYZE` or `PRAGMA optimize`. +- **Behaviour settings.** Where every server reading the file would present the system the same + way, the file says how (`meta` `behaviour.*`, `property.filter_ops`, `property.report`, below). + Facts about one server stay in that server. + +## Tables + +Fact tables: + +| table | holds | +|---|---| +| `code_system` | the served system (`served = 1`; other rows only for sources that contribute items): uri, version, name, title, description, release date, content, case sensitivity, hierarchy meaning, default language, `compositional` (codes may be expressions: no expansion is closed), counts, `resource` (a CodeSystem resource without concepts, where there is one) | +| `meta` | release facts with no column (`displayContexts`, `moduleDependencies`, `languages`, `edition`, `titles`), the format, provenance (`provenance.*`: importer, sources with sha256, timings), facts about indexes (`ix.
.`), behaviour settings (`behaviour.*`) | +| `concept` | id, code, active, display (derived) | +| `item` | id (> N), concept, kind (0 term, 1 definition), external id (description SCTID, RXAUI: INTEGER when a canonical decimal integer, else TEXT), language, use, text, active, preferred (the source's own flag), rank (derived display order). A definition is a designation too only when it has a use. An inactive item is still a designation of its concept: RxNorm stores an archived concept's RXNATOMARCHIVE atoms with `active = 0`, and they are that concept's designations | +| `item_use` | the uses (SNOMED CT description types, LOINC name kinds, RxNorm TTYs) | +| `property`, `property_member` | the catalog; a union property's members | +| `link` | subject, property, role group, target, active, seq (source order) | +| `literal` | subject, property, role group, value, active | +| `identifier` | property (the scheme), value (INTEGER when a canonical decimal integer, else TEXT; compared as text), subject, `resolves`: 0 not a code; 1 an alias, accepted as a code and answered with the subject's own code (ICD-11 short codes); 2 a code in its own right, answered as written (NDC 11-digit forms). A concept code always wins over an identifier with the same value. A probe for codes that are identifiers says `resolves > 0` as well as `value = ?`: only then does SQLite use the partial index `identifier_code` (the readers' probes do); without it the probe scans every identifier row. The catalog's `by_subject` says which properties' rows are also read by subject (`ix_by_subject`) | +| `record` | relation, subject, seq (order within the relation), target (the field the schema marks `target`, when it is a node), active, fields (JSON array of the other fields in schema order; in a field typed `c` or `n` a JSON number is a node id of this file and a JSON string a code that is not in it) | +| `value_label` | displays of literal values (LOINC CLASSTYPE 1 = Laboratory class) | +| `mapping` | maps to other systems (LOINC part and answer maps, IEEE device codes); `relationship` holds FHIR R4 ConceptMap equivalence codes (`equivalent`, `wider`, `narrower`, `relatedto`, ...), as main's providers report them | +| `resource` | resources the release defines that cannot be derived from its facts (none of the three systems has one; value sets that follow from stored records are not stored) | +| `node_extra` | FHIR extensions of a node, for round trip (none of the three systems has one) | + +Index tables (rebuildable): + +| table | holds | +|---|---| +| `ix_set` | Roaring bitmaps of concept ids by (kind, property, value, value kind): 1 all, 2 active, 3 leaf, 4 descendants of a concept, 5 property = value (only for properties a filter can name: `filterable = 1`, or a member of a filterable union), 6 has property (every property; for an inverse row, the targets of what it reverses), 7 record members (rows about items count for their concept) | +| `ix_in` | links by target, for the properties with `by_target = 1` (SNOMED CT children in release order, ECL reverse attributes) | +| `ix_by_subject` | identifier rows by subject (subject, property, value), for the properties with `by_subject = 1`: SNOMED CT alternate identifiers, aliases. The builder sets `by_subject = 1` on every identifier property unless the importer says otherwise; RxNorm's atom relationships (`AUI:*`, read only by value) are `by_subject = 0`. Every other identifier read goes by the primary key (property, value, subject) or `identifier_code` | +| `ix_order` | per-concept arrays in 1,024-entry blocks: `rank`, `ids` (the system order), `walk` (the whole system in the built-in walk order; `ix.ix_order.walk.reached` in meta), `active` (walk restricted to active concepts, stored only where they are not a prefix of walk: LOINC), `hier_start` / `hier` (LOINC parent and child entries in main's order, where the parent links' seq does not give it) | +| `ix_key` | text keys of nodes (SNOMED CT normal forms) | +| `ix_word` | the text-filter word index per language: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (Uint16 by concept id) | +| `ix_text_display`, `ix_text_item` | FTS5 trigram indexes over displays and item texts (regex prefilter) | + +## Behaviour settings + +`meta` keys `behaviour.`, JSON values. A key that is absent has its default. A reader refuses a +file with a key or value it does not know (the importers check the same at build). + +| key | values | default | written by | +|---|---|---|---| +| `grammar` | `"snomed"`, `"icd11"`, `null` | `null` (plain codes) | SNOMED CT: `"snomed"` (expressions, ECL; the SNOMED CT provider). ICD-11 MMS and ICF files: `"icd11"` (postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records) | +| `expansionOrder` | `"ids"`, `"stored"`, `"stored-self-first"` | `"ids"` | SNOMED CT `"stored-self-first"`; LOINC, RxNorm `"stored"`; NDC files `"stored"` (every selection, filtered or not, in `ix_order` `rank`) | +| `lookupName` | `"name"`, `"title"` | `"name"` | LOINC `"title"` | +| `description` | `"name"`, `"title"` | `"title"` | LOINC `"name"` | +| `versionAlgorithm` | a string, `null` | `null` | LOINC `"natural"`, RxNorm `"date"` | +| `designationUses` | `"keep"`, `"drop"` | `"keep"` | RxNorm `"drop"` | +| `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | +| `lookupSkipsMixedLinks` | `true`, `false` | `false` | SNOMED CT `true`: a `both` attribute's links are not read where no property is named (main keeps one value kind per attribute) | +| `aliasProperty` | a property code, `null` | `null` | ICD-11 MMS and ICF files `"classificationCode"`: $validate-code of a code written in its canonical form also returns its alias (an identifier with `resolves = 1`) as an output parameter of this name | +| `aliasExtension` | a URL, `null` | `null` | ICD-11 files: a Coding extension that restates the alias form of its code; $validate-code checks it against the code's alias (an error where the file has no `aliasProperty`, or the code is not in canonical form, has no alias, or the value is not its alias) | +| `preferredForLanguage` | `true`, `false` | `false` | ICD-11 and NDC files `true`: a designation whose item has `preferred = 1` and no use is reported with the use `preferredForLanguage` (`http://terminology.hl7.org/CodeSystem/hl7TermMaintInfra`) in its own language; other designations keep their stored use | +| `aliasLiterals` | an object, property code -> value | `{}` | NDC files `{"code-type": "11-digit", "synonym": "{code}"}`: a concept read through an identifier code (`resolves` 1 or 2) reports these literal values instead of its stored values of those properties; `{code}` is the concept's own code | +| `filters` | a list, `null` | `null` (every property with `filterable = 1`, with its `filter_ops`, and the server's built-in filters) | NDC files: the only filters the system understands, as FHIR CodeSystem.filter: `{"code", "operator": [...], "values": [...]}`; `values` (optional) lists the only values a filter accepts (each item of an `in` list). Any other filter, operator or value is FILTER_NOT_UNDERSTOOD. `code` names a catalog property, or `inactive` (FHIR's concept status: `= true` the inactive concepts, `= false` the active ones) | + +Release facts in `meta` that a reader also presents: `titles` (JSON object, language -> the system's +title in that language; ICD-11 files). With `lookupName` = `"title"`, $lookup reports the title in the +first requested language that has one (by primary subtag), else `code_system.title`. + +Per property: `filter_ops` (JSON list of the operators a filter on it accepts; RxNorm TTY, STY, SAB +and the relationships: `=`, `in`) and `report` (`named`: $lookup returns it only when asked for; +`always`: also on expansions; NULL: the server's rule; none of the three systems sets it; ICD-11 files +set `named` on `child`, `browserUrl` and `residual`, and `always` on `classificationCode` in MMS and ICF; +NDC files `named` on `kind`). + +## How each terminology maps + +| source | becomes | +|---|---| +| SNOMED CT concept | `concept`; module and definition status as links `moduleId` / `definitionStatusId`, effectiveTime as a literal (filterable, not refinable: ECL concept filters and the FHIR `moduleId` filter name them) | +| SNOMED CT description, text definition | `item` (external id = SCTID, use = type); the display from the edition's display refsets, then any preferred synonym, the FSN, the first description | +| SNOMED CT relationship (inferred, active and inactive), concrete value | `link` (group, seq = row order) / `literal`; one property may have both (`both`) | +| SNOMED CT language refset | `record` (role `language`, target = acceptability); `item.rank` derived with `meta` `displayContexts` | +| SNOMED CT other refsets (on concepts or on descriptions) | `record` with the field schema (effectiveTime, moduleId, the refset's own columns); members in `ix_set` kind 7 | +| SNOMED CT alternate identifier | `identifier` (`resolves = 0`) | +| SNOMED CT `child` | catalog row `inverse_of` is-a | +| LOINC terms, parts, answer lists, answers, hierarchy-only nodes | `concept`; designations as items | +| LOINC part links, CLASS, parent, Answer (ordered, seq = SequenceNumber), answers-for | `link` | +| LOINC PATH_TO_ROOT | `link` under `ancestor`, the hierarchy's `closure_from` | +| LOINC `child`, `AnswerList` | catalog rows `inverse_of` parent and of the union of Answer and answers-for | +| LOINC properties, STATUS, CLASSTYPE labels | `literal`, `value_label` | +| LOINC key order and walk | `ix_order` (derived-by-importer) | +| RxNorm RXCUI with an RxNorm atom (and archived ones) | `concept`; its RxNorm atoms as items (external id = RXAUI, use = TTY); an archived concept (only in RXNATOMARCHIVE) is inactive and its archive atoms are items with `active = 0`, still its designations | +| RxNorm TTY, SAB, SUPPRESS, STY | `literal` on the concept | +| RxNorm RXNREL concept rows | `link` under the RELA; a REL is the union of its RELAs (`RELA@REL` where a RELA occurs under two RELs; `@REL` for rows with none) | +| RxNorm RXNREL atom rows (option `atomRelationships`) | `identifier` value RXAUI1 -> the concept of RXAUI2, one per row under its pair `AUI::`; `AUI:` and `AUI:` are unions of the pairs; `by_subject = 0` (read by value only) | +| ICD-11, NDC (files built by other readers of this format) | short codes `identifier resolves = 1`, 11-digit NDC forms `resolves = 2` (a form shared by two packages: `resolves = 0` on the package that loses); post-coordination axes as relation `postcoordinationAxis` (seq = axis order; fields axis, axisCode, required, allowMultiple, valueSet) and their roots as relation `postcoordinationRoot` (target = root; field axisSeq); scale value sets derived from those records, not stored; definitions as kind 1 items without a use; the Foundation entity of an MMS or ICF concept as a `mapping` row | + +## How filters and ECL find their rows + +A filter name resolves to one catalog row (base file, then supplements in order). The row picks the path: + +| catalog field | what the compiler does | read | +|---|---|---| +| `shape = 'link'` | `=` / `in`: the property = value set of each value's concept; `exists`: has property; `regex`: the targets' displays | `ix_set` 5 / 6 | +| `shape = 'literal'` (+ `fhir_type`, `value_label`) | the stored values that match (no case; labels to values; search prefixes on numbers and dates) | `ix_set` 5 keys | +| `shape = 'both'` | a code of the file: the link set; else (and `#n`, quoted) the literal sets | `ix_set` 5 by value kind | +| `shape = 'union'` | the union of the members' sets | `ix_set` per member | +| `inverse_of` | the reversed properties from the value's concepts; `exists` one set | `link` by subject; `ix_set` 6 | +| `closure_from`, `subsumption` | hierarchy filters and ECL `<`, `<<`, `>`, `>>`, `!` | `ix_set` 3-6; `link`; `ix_in` | +| `ordered` | a list's members in seq (LOINC answer lists) | `link` by subject | +| `role = 'language'` | display ranking, `{{ D dialect }}`, acceptability | `record` | +| `shape = 'record'` | `^ R`, `concept in R`; `{{ M field op v }}` over the stored rows (node fields compared as node ids) | `ix_set` 7; `record` | +| `shape = 'identifier'` | `mapped: exists`, alternate identifiers, codes that are identifiers (`resolves > 0`) | `identifier` by property and value; `identifier_code`; `ix_by_subject` (`by_subject`) | +| `refinable`, `wildcard` | ECL attribute names; `*` | the attribute's sets and links | + +What stays in each system's adapter (`dialects.js`, `snomed.js`, `provider.js`) is value grammar and +upstream naming: LOINC's filter names (`answers-for`, `LIST`, `copyright`, `ancestor`, +`STATUS = NotStated`) and its answer-list order; RxNorm's `CUI:` / `AUI:` prefixes and the live +domain (concepts with a SUPPRESS literal); SNOMED CT SCTID grammar, concept filter operators, ECL +description type and dialect aliases, history profiles, the English dialect display rules; each +system's text-search names and ranking; the $lookup property lists and order. + +## Importers + +``` +node tx/importers/tx-import.js snomed-v2 import -s -d sct-intl-20260701.db -e 900000000000207008 --snomed-version 20260701 +node tx/importers/tx-import.js snomed-v2-from-cache import -s sct_uk_20261021.cache -d sct-uk-20261021.db +node tx/importers/tx-import.js snomed-v2-from-cache inspect +node tx/importers/tx-import.js loinc-v2 import -s -d loinc-2.83.db -v 2.83 +node tx/importers/tx-import.js loinc-v2-classic import -s loinc-2.77-a.db -d loinc-2.77.db +node tx/importers/tx-import.js rxnorm-v2 import -s -d rxnorm-03022026.db -v 03022026 [--atom-relationships] +``` + +`snomed-v2-from-cache` and `loinc-v2-classic` reverse-load the files main's providers use, for +releases that are not at hand. Every importer stages into `.stage` beside the destination, +then numbers the concepts, writes the fact tables in key order, builds the indexes, and VACUUMs. +`tx/importers/sqlite-v2/diff.js A.db B.db` compares two files by codes (the reverse loaders are +checked against release builds with it); `verify-indexes.js ` drops and rebuilds every index +table and compares. + +A file of the earlier sqlite-v2 schema (user_version 5) is refused at start-up with a message to +re-import it; there is no in-place upgrade. + +## Known differences from main + +| case | main | sqlite-v2 | +|---|---|---| +| an unknown SNOMED CT concept in a `concept is-not-a` filter | 500 `exception` | 400 `invalid` | +| RxNorm `REL` / `RELA = AUI:` | follows RXNREL's atom-level rows of every source | default build: 422 FILTER_NOT_UNDERSTOOD; a file built with `--atom-relationships` answers as main | +| SNOMED CT ` = ` on a concrete attribute (`1142139005 = 1`) | 500 "Invalid concept ID: 1" | the concepts with that concrete value (`#1` too) | +| SNOMED CT ECL `{{ D id = }}` | the concepts of those descriptions | the same | +| SNOMED CT reference set whose members are descriptions (`^ R`, `concept in R`) | not compared on these editions | the concepts of the member descriptions | +| the opioid imported-value-set `$expand` (mix line 1685) | 422 too-costly, at its 20 s limit | 200 in 0.1 s | +| an AU refset in ECL; code `0` in the US edition; a code with its term attached; RxNorm PSN display in a VSAC value set sent as a tx-resource | `invalid`; a second issue; no `normalized-code`; rejected | `not-supported`; one issue; `normalized-code`; accepted | +| LOINC extension edition, concept 760691010000106: two synonyms both preferred, no display-refset entry | one synonym | the other | +| SNOMED CT `filter=0` with `count=0` | 20,184 on the test cache (each concept once per identifier length its range covers) | 2,227 (each concept once) | +| SNOMED CT `concept in A,B` | in list order | by concept id | +| SNOMED CT `concept generalizes X` | in its ancestor walk's order | by concept id | +| SNOMED CT `expressions = true/false` as the only filter | no codes | every concept | +| SNOMED CT `116680003 = X` (is-a as an attribute filter) | 1 code on the test cache | none | diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js new file mode 100644 index 00000000..6694ad30 --- /dev/null +++ b/tx/sqlite-v2/dialects.js @@ -0,0 +1,367 @@ +'use strict'; +// Per-system filter rules on top of the generic compiler (compile.js), matching what the +// upstream providers (cs-loinc.js, cs-rxnorm.js, cs-snomed.js) accept and report. + +const { FilterError, Unsupported, splitList } = require('./engine/compile'); +const { KIND } = require('./store'); +const { requiredLiterals } = require('./engine/regex-literals'); +const regexUtilities = require('../../library/regex-utilities'); + +const FSN_ID = '900000000000003001'; +const SYNONYM_ID = '900000000000013009'; + +/** + * A filter the code system has no rule for: reported as main's providers report it since #383, + * FILTER_NOT_UNDERSTOOD, 422 (the provider translates it, provider.js filterError) + */ +function notUnderstood(prop, op, value) { + return new FilterError(`The filter "${prop} ${op} ${value}" is not understood or supported`, { notUnderstood: [prop, op, value] }); +} + +const LOINC = 'http://loinc.org'; +const RXNORM = 'http://www.nlm.nih.gov/research/umls/rxnorm'; +const SCT = 'http://snomed.info/sct'; + +// ---- LOINC --------------------------------------------------------------------------------- + +// The filters cs-loinc.js knows (#executeFilterQuery); any other is "not supported", as there. +// Its relationship and property types are those the built-in importer creates; the relationship +// types it creates but never uses (no rows) match nothing +const LOINC_RELATIONSHIPS = new Set(['N/A', 'adjustment', 'challenge', 'CLASS', 'COMPONENT', 'count', 'analyte-divisor', 'document-kind', + 'document-role', 'document-setting', 'document-subject-matter-domain', 'document-type-of-service', 'analyte-gene', 'METHOD_TYP', 'PROPERTY', + 'rad-anatomic-location-imaging-focus', 'rad-guidance-for-action', 'rad-guidance-for-approach', 'rad-guidance-for-object', + 'rad-guidance-for-presence', 'rad-maneuver-maneuver-type', 'rad-modality-modality-subtype', 'rad-modality-modality-type', + 'rad-pharmaceutical-route', 'rad-pharmaceutical-substance-given', 'rad-reason-for-exam', 'rad-subject', 'rad-timing', + 'rad-view-aggregation', 'rad-view-view-type', 'SCALE_TYP', 'analyte-suffix', 'super-system', 'SYSTEM', 'TIME_ASPCT', 'time-modifier', + 'rad-anatomic-location-laterality', 'rad-anatomic-location-laterality-presence', 'rad-anatomic-location-region-imaged', + 'AnswerList', 'Answer', 'answers-for', 'parent', 'child']); +const LOINC_UNUSED_RELATIONSHIPS = new Set(['N/A', 'adjustment', 'challenge', 'count', 'analyte-divisor', 'analyte-gene', 'analyte-suffix', + 'super-system', 'time-modifier']); +const LOINC_PROPERTIES = new Set(['CLASSTYPE', 'ORDER_OBS', 'EXAMPLE_UNITS', 'EXAMPLE_UCUM_UNITS', 'PanelType', 'AskAtOrderEntry', + 'UNITSREQUIRED', 'Copyright', 'ValidHL7AttachmentRequest']); +const LOINC_STATUS = new Set(['NotStated', 'ACTIVE', 'DEPRECATED', 'TRIAL', 'DISCOURAGED', 'EXAMPLE', 'PREFERRED', 'Primary', + 'DocumentOntology', 'Radiology', 'NORMATIVE']); +const LOINC_GENERIC_OPS = new Set(['=', 'in', 'exists', 'regex']); +function loincKnows(c, prop, op, value) { + if (prop === 'LIST' && op === '=' && c.id(value) != null) return true; + if (prop === 'answer-list' && op === '=') return true; + if (prop === 'answers-for' && (op === '=' || op === 'in')) return true; + if ((LOINC_RELATIONSHIPS.has(prop) || LOINC_PROPERTIES.has(prop)) && LOINC_GENERIC_OPS.has(op)) { + return op !== 'exists' || value === 'true' || value === 'false'; + } + if (prop === 'STATUS') return op === '=' && LOINC_STATUS.has(value); + if (prop === 'concept') return ['is-a', 'descendent-of', '=', 'in'].includes(op); + if (prop === 'code') return ['is-a', 'descendent-of', '='].includes(op); + if (prop === 'ancestor') return op === '=' || op === 'in'; + if (prop === 'copyright') return op === '=' && (value === 'LOINC' || value === '3rdParty'); + if (prop === '$text') return op === '>' || op === '<'; + return false; +} + +const loinc = { + name: 'loinc', + notSupported(prop, op, value) { + return notUnderstood(prop, op, value); + }, + /** a relationship filter value may be the target's code or its name (Codes.Description, no case): every match */ + valuesByName(c, v) { + return c.store.displayIdsNoCase(v); + }, + searchMode: 'display', + filter(c, prop, op, value) { + const S = c.store; + if (!loincKnows(c, prop, op, value)) throw loinc.notSupported(prop, op, value); + if (op === 'in' && (LOINC_RELATIONSHIPS.has(prop) || LOINC_PROPERTIES.has(prop) || prop === 'answers-for')) { + // in is the union of = each value (cs-loinc.js since #386): a relationship's value is a + // part code or a part name, a property's its own value (CLASSTYPE: 1-4 or the name), + // answers-for's an answer list or a term + const items = [...new Set(splitList(value))].map((v) => c.filter(prop, '=', v)).filter((n) => n.t !== 'empty'); + if (!items.length) return { t: 'empty' }; + return items.length === 1 ? items[0] : { t: 'or', items }; + } + if (LOINC_UNUSED_RELATIONSHIPS.has(prop) && !S.props.has(prop)) { + return op === 'exists' && value === 'false' ? { t: 'minus', a: { t: 'all' }, b: { t: 'empty' } } : { t: 'empty' }; + } + if (prop === 'STATUS' && value === 'NotStated' && S.props.has(prop)) { + // upstream's status key 0: the codes the release gives no status (answer lists, answers, + // hierarchy-only parts, parts without one), and any it calls NotStated + const p = S.props.get(prop); + return { t: 'or', items: [{ t: 'minus', a: { t: 'all' }, b: { t: 'set', kind: KIND.hasProp, pid: p.id, value: 0 } }, c.propertyFilter(p, '=', value)] }; + } + if (prop === 'parent' && op === 'regex' && S.hierarchy) { + // the codes whose parent's name matches (a relationship regex, as for the other links) + return { t: 'propIn', pids: [S.hierarchy.id], values: { t: 'text', field: 'display', re: value } }; + } + if (prop === 'LIST' && op === '=') { + // answers-for = [answer list], kept for backwards compatibility (cs-loinc.js, UP-645). + // Upstream supports it only for a code LOINC has + const id = c.id(value); + if (id == null) throw loinc.notSupported(prop, op, value); + // in upstream's order (ORDER BY its key), which is not the list's sequence: answers by + // where they first appear in the release (engine.js _firstSeen) + const ans = S.props.get('Answer'); + return { t: 'set', kind: KIND.refset, pid: 0, value: id, ...(ans ? { order: 'firstSeen', via: ans.id } : {}) }; + } + if (prop === 'AnswerList' && S.filterProp(prop)) { + // upstream's AnswerList relationship (a term or an answer -> its answer lists): the catalog's + // inverse of Answer and answers-for (generic). Upstream's key order: terms, then answers + // where they first appear (engine.js _firstSeen, by the ordered Answer lists) + const n = c.propertyFilter(S.filterProp(prop), op, value); + const ans = S.props.get('Answer'); + return ans && n.t !== 'minus' ? { ...n, order: 'firstSeen', via: ans.id } : n; + } + if (prop === 'ancestor' && op === '=') { + // implicit part value sets (http://loinc.org/vs/LP...): the codes below the part + const id = c.id(value); + return id == null ? { t: 'empty' } : { t: 'set', kind: KIND.descendants, pid: 0, value: id }; + } + if (prop === 'ancestor' && op === 'in') { + // the union over the parts (cs-loinc.js, #331) + const m = c.ids(splitList(value)); + const ids = [...new Set([...m.values()].filter((x) => x != null))]; + if (!ids.length) return { t: 'empty' }; + const n = ids.map((id) => ({ t: 'set', kind: KIND.descendants, pid: 0, value: id })); + return n.length === 1 ? n[0] : { t: 'or', items: n }; + } + if (prop === 'answers-for' && op === '=') { + const id = c.id(value); + if (id == null) return { t: 'empty' }; + if (String(value).startsWith('LL')) return { t: 'set', kind: KIND.refset, pid: 0, value: id }; + const p = S.props.get('answers-for'); + // a term's answers: its lists in order, each in its sequence (as upstream lists them) + return { t: 'refsetOf', of: { t: 'set', kind: KIND.prop, pid: p.id, value: id }, order: 'lists' }; + } + if (prop === 'answer-list' && op === '=') { + // the answer lists (LL) an answer (LA) is in: the sources of Answer = value, by code only + // (cs-loinc.js, #371, UP-645). Any other code, an answer list included, is in none + const id = c.id(value); + const p = S.props.get('Answer'); + return id == null || !p ? { t: 'empty' } : { t: 'set', kind: KIND.prop, pid: p.id, value: id }; + } + if (prop === 'copyright' && op === '=') { + const p = S.props.get('Copyright'); + const has = { t: 'set', kind: KIND.hasProp, pid: p ? p.id : -1, value: 0 }; + if (value === 'LOINC') return { t: 'minus', a: { t: 'all' }, b: has }; + if (value === '3rdParty') return has; + throw loinc.notSupported(prop, op, value); + } + // CLASSTYPE = takes the code (1-4) or its name ("Laboratory class", ...), as upstream does; + // the generic literal rule maps names through the value labels. Upstream stores the name, and + // maps a code to it for = only: in and regex match the names + const names = S.props.has('CLASSTYPE') ? S.valueLabels(S.props.get('CLASSTYPE')) : null; + if (prop === 'CLASSTYPE' && names && S.props.has(prop) && op === 'regex') { + const re = regexUtilities.compile('^(?:' + value + ')$'); + const codes = Object.keys(names).filter((k) => re.test(String(names[k]))); + return codes.length ? c.propertyFilter(S.props.get(prop), 'in', codes.join(',')) : { t: 'empty' }; + } + // in, on a property the file has beyond cs-loinc.js's lists: only the values that are LOINC + // codes (the rule cs-loinc.js had before #386; its own properties and relationships are the + // union of = above) + if (op === 'in' && S.props.has(prop)) { + const p = S.props.get(prop); + const m = c.ids(splitList(value)); + const known = [...m].filter(([, id]) => id != null).map(([v]) => v); + if (!known.length || p.kind !== 'concept') return { t: 'empty' }; + return c.propertyFilter(p, 'in', known.join(',')); + } + return null; + } +}; + +// ---- RxNorm -------------------------------------------------------------------------------- + +const rxnorm = { + name: 'rxnorm', + // text filter: cs-rxnorm.js's stem search (text-index.js rxTextSearch) + searchMode: 'rxnorm', + // every upstream query is over RXNCONSO: archived concepts (RXNATOMARCHIVE only) are never + // selected; obsolete ones (inactive, but in RXNCONSO) are. RXNCONSO concepts are the ones with + // a SUPPRESS literal; a file without SUPPRESS has no obsolete concepts, so its active set. + domain: 'live', + live(S) { + const p = S.props.get('SUPPRESS'); + return p ? { t: 'set', kind: KIND.hasProp, pid: p.id, value: 0 } : { t: 'active' }; + }, + notSupported(prop, op, value) { + return notUnderstood(prop, op, value); + }, + /** + * cs-rxnorm.js doesFilter / filter: `=` and `in` only, with at least one value; on TTY, STY and + * SAB (any case), on concept and code, and on a relationship - a REL or RELA that RXNREL has, + * from any source - whose values are all CUI:, or AUI: in a file built with the + * atom-level relationships (importer option atomRelationships: identifier rows RXAUI1 -> the + * concept of RXAUI2 under AUI:, every source's, as cs-rxnorm.js reads RXNREL). Without + * them an AUI: value is refused. Anything else is FILTER_NOT_UNDERSTOOD, 422. A + * filter on a property a supplement in use defines is left to the supplement layer, as before. + */ + filter(c, prop, op, value) { + const S = c.store; + const up = String(prop).toUpperCase(); + const refuse = () => { + const n = c.term && c.term.layers && !S.props.has(prop) ? c.term.layers.filterNode(c, prop, op, value) : null; + if (n) return n; + throw rxnorm.notSupported(prop, op, value); + }; + // the operators the catalog row takes (filter_ops; TTY, STY, SAB by any case); concept / code + // and the rest: = and in + const row = S.catalog.get(up === 'TTY' || up === 'STY' || up === 'SAB' ? up : prop); + if (!((row && row.filterOps) || ['=', 'in']).includes(op)) return refuse(); + // cs-rxnorm.js #filterValues + const vals = op === 'in' ? splitList(value) : (value != null && String(value).trim() ? [String(value).trim()] : []); + if (!vals.length) return refuse(); + if (up === 'TTY' || up === 'STY' || up === 'SAB') { + // property names are case-insensitive upstream; the generic rule matches the literal + const v = op === '=' ? vals[0] : value; + if (prop !== up || !S.props.has(up) || v !== value) return c.filter(up, op, v); + return null; + } + if (prop === 'concept' || prop === 'code') return null; // the generic rule: the codes listed + // a relationship: a REL (the catalog's union of its RELAs) or a RELA, whatever source RXNREL + // has it from (a name only other sources' rows have selects nothing) + const p = S.filterProp(prop); + if (!p || p.kind !== 'concept') return refuse(); + // CUI: names a concept; AUI: an atom of any source (the file's atom-level rows) + if (!vals.every((v) => v.startsWith('CUI:') || (v.startsWith('AUI:') && S.hasAtomRelationships))) return refuse(); + const cuis = vals.filter((v) => v.startsWith('CUI:')).map((v) => v.substring(4)); + const auis = vals.filter((v) => v.startsWith('AUI:')).map((v) => v.substring(4)); + const items = []; + if (cuis.length) items.push(c.propertyFilter(p, 'in', cuis.join(','))); + if (auis.length) { + const atoms = S.catalog.get('AUI:' + p.code); + items.push(atoms ? { t: 'ids', ids: S.subjectsOfIdentifiers(atoms, auis, c.stats) } : { t: 'empty' }); + } + return items.length === 1 ? items[0] : { t: 'or', items }; + } +}; + +// ---- SNOMED CT ----------------------------------------------------------------------------- + +function sctId(v) { + return /^\s*\d{6,18}\s*$/.test(String(v)); +} + +const snomed = { + name: 'snomed', + searchMode: 'designation', + generalizesExcludesSelf: true, // as cs-snomed.js filterGeneralizes(id, false) + strictIn: true, // concept in X,Y: an unknown concept is an error (cs-snomed.js filterIn) + notSupported(prop, op, value) { + return notUnderstood(prop, op, value); + }, + /** ECL the engine refuses: evaluated by main's ECL (cs-snomed.js) over this file, as ids */ + eclFallback(c, text, e) { + const M = require('./sct-main-ecl'); + const kept = M.mainEclResult(c.store, text); + if (kept === undefined) throw new M.NeedsMainEcl(c.store, text); + const bm = kept.bm; + if (kept.err) { + const err = kept.err; + const msg = err && err.message ? err.message : String(err); + if ((err && err.eclInvalid) || /is not known/.test(msg)) throw new FilterError(msg, { eclUnknown: true }); + throw new Unsupported('ecl-feature', msg); + } + void e; + return { t: 'ids', ids: bm.toArray(), label: 'ECL (main) ' + text.slice(0, 60) }; + }, + rootNode(c) { + const id = c.id('138875005'); + return id == null ? { t: 'empty' } : { t: 'ids', ids: [id] }; + }, + unknownConcept(c, op, value) { + throw new FilterError(`The SNOMED CT Concept ${value} is not known`, { unknownConcept: value }); + }, + /** + * concept in X,Y,…: a refset contributes its active members, any other concept itself (owner and + * THO, 2026-11-02; tx-ecosystem sct/*-concept-in). An unknown concept is an error (strictIn). + */ + conceptIn(c, ids) { + const S = c.store; + const sets = S.loadSets(KIND.refset, 0, ids, c.stats); + const items = []; + const plain = []; + for (const id of ids) { + if (sets.get(id) && sets.get(id).size) items.push({ t: 'set', kind: KIND.refset, pid: 0, value: id }); + else plain.push(id); + } + if (plain.length) items.push({ t: 'ids', ids: plain }); + return items.length === 1 ? items[0] : { t: 'or', items }; + }, + filter(c, prop, op, value) { + const S = c.store; + // code is the same filter property as concept (cs-snomed.js #filterProperty; tx-ecosystem + // sct/*-code-in), and is reported as concept + if (prop === 'concept' || prop === 'code') { + // cs-snomed.js SNOMED_CONCEPT_FILTER_OPS (no not-in, regex or exists) + if (!['=', 'is-a', 'descendent-of', 'child-of', 'generalizes', 'in', 'is-not-a', 'descendent-leaf'].includes(op)) { + throw notUnderstood('concept', op, value); + } + if (op !== 'in' && !sctId(value)) throw new FilterError(`Invalid concept ID: ${value}`); + return null; // generic concept rules + } + if (prop === 'inactive') { + if (op !== '=') throw notUnderstood(prop, op, value); + if (value !== 'true' && value !== 'false') throw new FilterError(`Invalid filter value: ${value}`); + return value === 'true' ? { t: 'inactive' } : { t: 'active' }; + } + if (prop === 'constraint') { + if (op !== '=') throw notUnderstood(prop, op, value); + return c.ecl(value); + } + if (prop === 'moduleId') { + if (op !== '=') throw notUnderstood(prop, op, value); + if (!sctId(value)) throw new FilterError(`Invalid concept ID: ${value}`); + const id = c.id(value); + return id == null ? { t: 'empty' } : { t: 'set', kind: KIND.prop, pid: S.props.get('moduleId').id, value: id }; + } + if (prop === 'expressions' && op === '=') { + // true: expressions are allowed as well (an expansion still lists only concepts; an + // expression's membership is decided by main's services over this file, see snomed.js) + if (value === 'true') return { t: 'all', expressionsTrue: true }; + return { t: 'all', expressionsFalse: true }; + } + if (String(prop).startsWith('mapped:')) { + // mapped: exists true|false: concepts with (or without) an alternate + // identifier in that scheme (e.g. 30051010000102: a LOINC code) + const scheme = String(prop).substring('mapped:'.length); + if (!sctId(scheme)) throw notUnderstood(prop, op, value); + if (op !== 'exists') throw notUnderstood(prop, op, value); + if (value !== 'true' && value !== 'false') throw new FilterError(`Invalid filter value: ${value}`); + const sid = c.id(scheme); + const ids = sid == null ? [] : S.conceptsWithScheme(sid); + const has = { t: 'ids', ids, label: `${prop} exists` }; + return value === 'true' ? has : { t: 'minus', a: { t: 'all' }, b: has }; + } + if (prop === 'display' && op === 'regex') { + // tx-ecosystem requirements (display regex): any active FSN or synonym in the one language the + // request chooses (c.term.lang) matches the whole term, case-sensitively + const lits = S.hasFts ? requiredLiterals(value) : []; + const lang = c.term.lang || 'en'; + return { t: 'desigRegex', re: String(value), lang, uses: [FSN_ID, SYNONYM_ID], ...(lits.length ? { lits } : {}), label: `display (${lang}) ~ /${value}/` }; + } + // display: regex only, as cs-snomed.js + if (prop === 'display') throw notUnderstood(prop, op, value); + if (sctId(prop)) { + if (op !== '=') throw notUnderstood(prop, op, value); + const p = S.filterProp(String(prop).trim()); + // a concrete attribute (literal values, or literals and links): its value is a number or a + // string (#n as ECL writes it), tried as a concept id first where it has links + if (p && p.kind !== 'concept') return c.propertyFilter(p, '=', String(value).trim().replace(/^#/, '')); + if (!sctId(value)) throw new FilterError(`Invalid concept ID: ${value}`); + const id = c.id(value); + if (!p || id == null) return { t: 'empty' }; + return { t: 'set', kind: KIND.prop, pid: p.id, value: id }; + } + return null; // generic rules (supplement properties, ...); unknown properties fail there + } +}; + +const generic = { name: 'generic' }; + +function dialectFor(system) { + if (system === LOINC) return loinc; + if (system === RXNORM) return rxnorm; + if (system === SCT) return snomed; + return generic; +} + +module.exports = { dialectFor, LOINC, RXNORM, SCT }; diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js new file mode 100644 index 00000000..c81fe669 --- /dev/null +++ b/tx/sqlite-v2/engine/compile.js @@ -0,0 +1,864 @@ +'use strict'; +// ValueSet.compose includes / filters and ECL -> IR (see evaluate.js for the node list). +// +// Generic rules cover the concept filters (is-a, descendent-of, child-of, generalizes, =, in, +// not-in, is-not-a, descendent-leaf, regex) and every catalog property a filter may name (=, in, not-in, +// exists, regex). A per-system dialect (dialects.js) adds or overrides filters. Two error kinds: +// FilterError - the request is wrong for this system (the message is what upstream reports) +// Unsupported - the engine cannot do it; the caller hands the request back to expand.js + +const { ECLLexer, ECLParser } = require('../../sct/ecl'); +const { requiredLiterals } = require('./regex-literals'); +const { Unsupported, Evaluator } = require('./evaluate'); +const { KIND } = require('../store'); + +// an ECL wild: term: main's matcher (cs-snomed.js wildTermMatcher), linear with no regex +const { wildTermMatcher } = require('../../sct/ecl'); + +class FilterError extends Error { + constructor(message, extra = {}) { + super(message); + Object.assign(this, extra); + this.filterError = true; + } +} + +function splitList(v) { + return String(v).split(',').map((s) => s.trim()).filter(Boolean); +} + +function uniqSorted(ids) { + return Array.from(new Set(ids)).sort((a, b) => a - b); +} + +class Compiler { + /** + * @param {object} term { store, dialect, layers: [{store, ...}] } + * @param {object} [opts] { stats } + */ + constructor(term, opts = {}) { + this.term = term; + this.store = term.store; + this.dialect = term.dialect || {}; + this.stats = opts.stats || null; + this.codeMap = new Map(); // codes resolved while compiling this request (one statement for all) + } + + // ---- codes ------------------------------------------------------------------------------- + + ids(codes) { + const miss = codes.filter((c) => c != null && !this.codeMap.has(String(c))); + if (miss.length) for (const [c, id] of this.store.resolveCodes(miss, this.stats)) this.codeMap.set(c, id); + const out = new Map(); + for (const c of codes) if (c != null) out.set(c, this.codeMap.get(String(c)) ?? null); + return out; + } + + id(code) { + // through the request's code map: a member filter tests one code per row + const c = String(code).trim(); + return this.ids([c]).get(c); + } + + /** concept ids for a filter value: the code, or a dialect-specific alternative (LOINC part names) */ + valueIds(v) { + const id = this.id(v); + if (id != null) return [id]; + return this.dialect.valuesByName ? this.dialect.valuesByName(this, v) : []; + } + + // ---- compose ------------------------------------------------------------------------------- + + /** prefetch every code a set of includes mentions, in one statement */ + prefetch(incs) { + const want = new Set(); + for (const inc of incs) { + for (const c of inc.concept || []) want.add(c.code); + for (const f of inc.filter || []) { + if (f.value == null || f.op === 'regex' || f.property === 'constraint' || f.property === 'expression') continue; + for (const v of splitList(f.value)) want.add(v); + } + } + if (want.size) this.ids([...want]); + } + + selection(includes, excludes, activeOnly) { + this.prefetch([...includes, ...excludes]); + return { + includes: includes.map((inc) => this.include(inc)), + excludes: excludes.map((inc) => this.include(inc)), + activeOnly: !!activeOnly + }; + } + + include(inc) { + if (inc.valueSet && inc.valueSet.length) throw new Unsupported('valueset-import'); + if (inc.otherVersion) { + // another version of this system (an exclude): compiled on that file, evaluated there and + // translated into this file's ids by code (tx/sqlite-v2/store.js translateFrom) + const other = inc.provider && inc.provider.store; + if (!other || other.system !== this.store.system) throw new Unsupported('other-version', inc.version); + const oc = new Compiler({ store: other, dialect: inc.provider.dialect }, { stats: this.stats }); + oc.prefetch([inc]); + const parts = oc.include({ ...inc, otherVersion: false }); + return { parts: parts.parts.map((p) => ({ node: { t: 'xlate', from: other, node: p.node, label: 'from ' + other.version }, order: null })) }; + } + if (inc.imports && inc.imports.length) { + // value set imports resolved by expand.js: each is a set; an include is their + // intersection with its own concepts/filters (FHIR include semantics) + const items = inc.imports.map((c) => this.importNode(c)); + if (inc.system && ((inc.filter && inc.filter.length) || (inc.concept && inc.concept.length))) { + const own = this.include({ ...inc, imports: undefined }); + items.push(own.parts.length === 1 ? own.parts[0].node : { t: 'or', items: own.parts.map((p) => p.node) }); + } + return { parts: [{ node: items.length === 1 ? items[0] : { t: 'and', items }, order: null }] }; + } + const parts = []; + if (!(inc.concept && inc.concept.length) && !(inc.filter && inc.filter.length)) { + // (whole: the include names the whole code system, which the built-in provider walks) + parts.push({ node: this.domain({ t: 'all', whole: true }), order: null }); + return { parts }; + } + if (inc.concept && inc.concept.length) { + const codes = inc.concept.map((c) => c.code); + const m = this.ids(codes); + const order = []; + for (const c of codes) if (m.get(c) != null) order.push(m.get(c)); + parts.push({ node: { t: 'ids', ids: uniqSorted(order) }, order }); + } + if (inc.filter && inc.filter.length) { + const items = inc.filter.map((f) => this.filter(f.property, f.op, f.value)); + const node = items.length === 1 ? items[0] : { t: 'and', items }; + // upstream adds an include's concepts and its filters separately (expand.js includeCodes) + parts.push({ node: this.domain(node), order: null }); + } + return { parts }; + } + + /** the concepts a filter can select at all (RxNorm: never archived concepts) */ + domain(node) { + if (this.dialect.domain !== 'live') return node; + const live = this.dialect.live(this.store); + return node.t === 'all' ? live : { t: 'and', items: [node, live] }; + } + + /** an imported value set's compose as one node: its includes minus its excludes */ + importNode(c) { + this.prefetch([...(c.include || []), ...(c.exclude || [])]); + const flat = (list) => list.flatMap((inc) => this.include(inc).parts.map((p) => p.node)); + const inc = flat(c.include || []); + const exc = flat(c.exclude || []); + let node = inc.length === 1 ? inc[0] : { t: 'or', items: inc }; + if (exc.length) node = { t: 'minus', a: node, b: exc.length === 1 ? exc[0] : { t: 'or', items: exc } }; + if (c.inactive === false) node = { t: 'and', items: [node, { t: 'active' }] }; + return node; + } + + // ---- filters ------------------------------------------------------------------------------- + + filter(prop, op, value) { + if (this.dialect.filter) { + const n = this.dialect.filter(this, prop, op, value); + if (n) return n; + } + if (prop === 'display' && !this.store.filterProp('display')) return this.displayFilter(op, value); + if (prop === 'designation' && !this.store.filterProp('designation')) { + // R5 CodeSystem 4.8.15 generic filters: designation = / regex; the display counts as one + if (op === '=') return { t: 'desigMatch', eq: String(value), label: `designation = "${value}"` }; + if (op === 'regex') return { t: 'desigMatch', re: String(value), label: `designation regex /${value}/` }; + throw this.notSupported(prop, op, value); + } + if (prop === 'concept' || prop === 'code' || (this.store.hierarchy && prop === this.store.hierarchy.code && op !== '=' && op !== 'in' && op !== 'exists')) { + return this.conceptFilter(op, value, prop); + } + // the property's catalog entry is its access path (store filterProp) + const p = this.store.filterProp(prop); + if (!p) { + const n = this.term.layers ? this.term.layers.filterNode(this, prop, op, value) : null; + if (n) return n; + throw this.notSupported(prop, op, value); + } + return this.propertyFilter(p, op, value); + } + + /** display = / in / regex (the concept's display; FHIR's "display" filter property) */ + displayFilter(op, value) { + if (op === 'regex') { + // literals every match contains: candidates from the trigram index before RE2 runs (evaluate.js) + const lits = this.store.hasFts ? requiredLiterals(value) : []; + return lits.length ? { t: 'text', field: 'display', re: value, lits } : { t: 'text', field: 'display', re: value }; + } + if (op === '=' || op === 'in') { + const vals = op === '=' ? [String(value)] : splitList(value); + const esc = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + return { t: 'text', field: 'display', re: '^(?:' + vals.map(esc).join('|') + ')$' }; + } + throw this.notSupported('display', op, value); + } + + notSupported(prop, op, value) { + if (this.dialect.notSupported) return this.dialect.notSupported(prop, op, value); + return new FilterError(`The filter "${prop} ${op} ${value}" is not supported for ${this.store.system}`); + } + + conceptFilter(op, value, prop = 'concept') { + const S = this.store; + if (op === 'in' || op === 'not-in') { + const vals = splitList(value); + const m = this.ids(vals); + const unknown = vals.filter((v) => m.get(v) == null); + // SNOMED: a concept (or refset) the edition does not have is an error, as upstream reports it + if (unknown.length && this.dialect.strictIn && this.dialect.unknownConcept) this.dialect.unknownConcept(this, op, unknown[0]); + const ids = uniqSorted(vals.map((v) => m.get(v)).filter((x) => x != null)); + const n = this.dialect.conceptIn ? this.dialect.conceptIn(this, ids) : { t: 'ids', ids }; + return op === 'in' ? n : { t: 'minus', a: { t: 'all' }, b: n }; + } + if (op === 'regex') return { t: 'text', field: 'code', re: value }; + if (op === 'exists') throw this.notSupported(prop, op, value); + const id = this.id(value); + if (id == null) { + if (this.dialect.unknownConcept) return this.dialect.unknownConcept(this, op, value); + return { t: 'empty', why: 'unknown code ' + value }; + } + const desc = { t: 'set', kind: KIND.descendants, pid: 0, value: id }; + switch (op) { + case '=': return { t: 'ids', ids: [id] }; + case 'is-a': return { t: 'self', id, of: desc }; + case 'descendent-of': return desc; + case 'is-not-a': return { t: 'minus', a: { t: 'all' }, b: { t: 'self', id, of: desc } }; + case 'generalizes': return { t: 'anc', id, self: !this.dialect.generalizesExcludesSelf }; + case 'child-of': return S.hierarchy ? { t: 'set', kind: KIND.prop, pid: S.hierarchy.id, value: id } : { t: 'empty' }; + case 'descendent-leaf': return { t: 'and', items: [desc, { t: 'leaf' }] }; + default: throw this.notSupported(prop, op, value); + } + } + + /** + * A filter on a catalog entry, by its access path: + * inverse (reverses): the targets of the reversed properties from the values' concepts (of a + * hierarchy property: their parents); exists, the inverse row's has-property set where the + * file has one; + * union (members): the union of its members' sets; + * node-valued (link): the prop set of each value's concept; + * 'both' (links and literals): a value that is a code is a node, otherwise a literal; + * literal: the prop sets of the stored values that match (labels, search prefixes). + */ + propertyFilter(p, op, value) { + if (p.reverses) return this.inverseFilter(p, op, value); + const pids = pidsOf(p); + switch (op) { + case '=': + case 'in': + case 'not-in': { + const vals = op === '=' ? [String(value)] : splitList(value); + let node; + if (p.kind === 'concept') { + node = this.nodeSets(pids, uniqSorted(vals.flatMap((v) => this.valueIds(v)))); + } else if (p.shape === 'both') { + node = this.bothValues(p, vals); + } else if (op === '=' && ['integer', 'decimal', 'dateTime'].includes(p.type) && /^(eq|ne|gt|lt|ge|le|sa|eb|ap)./.test(String(value))) { + // R5 CodeSystem 4.8.15.1: FHIR search prefixes on integer, decimal and dateTime properties + node = litSets(p.id, this.store.propValues(p.id, this.stats).filter((r) => searchPrefixMatch(p.type, String(value), r.value)).map((r) => r.value)); + } else { + node = litSets(p.id, this.literalKeys(p, vals)); + } + return op === 'not-in' ? { t: 'minus', a: { t: 'all' }, b: node } : node; + } + case 'exists': { + const v = String(value).toLowerCase(); + if (v !== 'true' && v !== 'false') throw this.notSupported(p.code, op, value); + const items = pids.map((pid) => ({ t: 'set', kind: KIND.hasProp, pid, value: 0 })); + const n = items.length === 1 ? items[0] : items.length ? { t: 'or', items } : { t: 'empty' }; + return v === 'false' ? { t: 'minus', a: { t: 'all' }, b: n } : n; + } + case 'regex': + if (p.kind === 'concept') { + // regex over the target's code or display: match the target keys, then their sources + return { t: 'propIn', pids, values: { t: 'text', field: this.dialect.conceptRegexField || 'display', re: value } }; + } + return { t: 'litMatch', pid: p.id, re: value }; + default: + throw this.notSupported(p.code, op, value); + } + } + + /** the concepts with a node value in ids of one of the properties pids (prop sets) */ + nodeSets(pids, ids, vk = 0) { + if (!pids.length || !ids.length) return { t: 'empty' }; + if (ids.length === 1) { + const items = pids.map((pid) => ({ t: 'set', kind: KIND.prop, pid, value: ids[0], ...(vk ? { vk } : {}) })); + return items.length === 1 ? items[0] : { t: 'or', items }; + } + return { t: 'propIn', pids, values: { t: 'ids', ids }, ...(vk ? { vk } : {}) }; + } + + /** + * Values of a property with links and literals (SCHEMA-REDESIGN, scoping): a value that is a + * code of this file is a node (the link sets); otherwise, and for a #n or quoted value, a + * literal (the stored values it matches, numbers as numbers) + */ + bothValues(p, vals) { + const items = []; + const lits = []; + for (const v of vals) { + const lit = /^#|^"/.test(v); + const id = lit ? null : this.id(v); + if (id != null) items.push({ t: 'set', kind: KIND.prop, pid: p.id, value: id, vk: 1 }); + else lits.push(lit ? v.replace(/^#/, '').replace(/^"(.*)"$/, '$1') : v); + } + if (lits.length) { + const keys = this.store.propValues(p.id, this.stats, 2); + for (const v of lits) { + for (const r of keys) if (String(r.value) === v || (typeof r.value === 'number' && Number(v) === r.value)) items.push({ t: 'set', kind: KIND.prop, pid: p.id, value: r.value, vk: 2 }); + } + } + return items.length === 0 ? { t: 'empty' } : items.length === 1 ? items[0] : { t: 'or', items }; + } + + /** P' op X where P' reverses P: the targets of P from X's concepts (of a hierarchy: X's parents) */ + inverseFilter(p, op, value) { + const rev = p.reverses; + const hier = rev.filter((q) => q.isHierarchy); + const other = rev.filter((q) => !q.isHierarchy).map((q) => q.id); + const of = (sources) => { + const items = hier.map(() => ({ t: 'hier', dir: 'parents', self: false, of: sources })); + if (other.length) items.push({ t: 'propOf', pids: other, sources }); + return items.length === 1 ? items[0] : items.length ? { t: 'or', items } : { t: 'empty' }; + }; + switch (op) { + case '=': + case 'in': + case 'not-in': { + const vals = op === '=' ? [String(value)] : splitList(value); + const node = of({ t: 'ids', ids: uniqSorted(vals.flatMap((v) => this.valueIds(v))) }); + return op === 'not-in' ? { t: 'minus', a: { t: 'all' }, b: node } : node; + } + case 'exists': { + const v = String(value).toLowerCase(); + if (v !== 'true' && v !== 'false') throw this.notSupported(p.code, op, value); + // the inverse row's has-property set (the reversed properties' targets), where the file has one + const n = p.id != null ? { t: 'set', kind: KIND.hasProp, pid: p.id, value: 0 } : of({ t: 'all' }); + return v === 'false' ? { t: 'minus', a: { t: 'all' }, b: n } : n; + } + case 'regex': return of({ t: 'text', field: 'display', re: value }); + default: throw this.notSupported(p.code, op, value); + } + } + + /** map literal filter values onto stored keys (case-insensitive for strings) */ + literalKeys(p, vals) { + const keys = this.store.propValues(p.id, this.stats); + const out = new Set(); + const map = this.store.valueLabels(p); + for (let v of vals) { + if (map) for (const [k, d] of Object.entries(map)) if (String(d).toLowerCase() === v.toLowerCase()) v = k; + const lv = v.toLowerCase(); + for (const r of keys) if (String(r.value).toLowerCase() === lv) out.add(r.value); + } + return [...out]; + } + + // ---- ECL ----------------------------------------------------------------------------------- + + ecl(text) { + let ast; + try { + ast = new ECLParser(new ECLLexer(text).tokenize()).parse(); + } catch (e) { + throw new FilterError(e.message, { eclSyntax: true }); + } + const pre = new Set(); + collectIds(ast, pre); + if (pre.size) this.ids([...pre]); + try { + return this.eclNode(ast); + } catch (e) { + // a feature the engine does not evaluate: the dialect may hand the expression on (SNOMED CT: + // main's ECL over this file); otherwise the error stands + if (e.unsupported && this.dialect.eclFallback) return this.dialect.eclFallback(this, text, e); + throw e; + } + } + + eclNode(n) { + switch (n.type) { + case 'SubExpressionConstraint': return this.eclSub(n); + case 'CompoundExpressionConstraint': { + const l = this.eclNode(n.left); + const r = this.eclNode(n.right); + // eclOrder: the order cs-snomed.js lists the result in (engine.js _eclOrdered) + if (n.operator === 'Conjunction') return { t: 'and', items: [l, r], eclOrder: 'conj' }; + if (n.operator === 'Disjunction') return { t: 'or', items: [l, r], eclOrder: 'disj' }; + return { t: 'minus', a: l, b: r, eclOrder: 'minus' }; + } + case 'RefinedExpressionConstraint': + return { t: 'and', items: [this.eclNode(n.base), this.eclRefinement(n.refinement)], eclOrder: 'base' }; + case 'DottedExpressionConstraint': { + let cur = this.eclNode(n.base); + for (const a of n.attributes) cur = { t: 'propOf', pids: this.eclAttrIds(a), sources: cur }; + return cur; + } + case 'ConceptReference': case 'Wildcard': case 'MemberOf': + return this.eclSub({ type: 'SubExpressionConstraint', operator: null, focus: n }); + default: + throw new Unsupported('ecl-feature', n.type); + } + } + + eclConcept(code) { + const id = this.id(code); + if (id == null) throw new FilterError(`The SNOMED CT Concept ${code} is not known`, { eclUnknown: true }); + return id; + } + + eclSub(n) { + if (n.filters && n.filters.length) { + // {{ C }} concept filters and {{ D }} description filters narrow; {{ + HISTORY }} adds + let node = this.eclSub({ ...n, filters: undefined }); + const narrow = []; + for (const fc of n.filters) if (fc.kind === 'C') narrow.push(...fc.filters.map((f) => this.eclConceptFilter(f))); + for (const fc of n.filters) if (fc.kind === 'D') narrow.push(this.eclDescriptionFilter(fc.filters)); + if (narrow.length) node = { t: 'and', items: [node, ...narrow], eclOrder: 'base' }; + for (const fc of n.filters) if (fc.kind === '+') node = this.eclHistory(node, fc); + for (const fc of n.filters) if (!['C', 'D', '+'].includes(fc.kind)) throw new Unsupported('ecl-feature', 'filter ' + fc.kind); + return node; + } + const f = n.focus; + let base; + let id = null; + if (f.type === 'ConceptReference') { + id = this.eclConcept(f.conceptId); + base = { t: 'ids', ids: [id] }; + } else if (f.type === 'Wildcard') { + base = { t: 'all' }; + } else if (f.type === 'MemberOf') { + if (f.fields) throw new Unsupported('ecl-feature', 'member fields'); + if (f.memberFilters && f.memberFilters.length) { + if (f.refSet.type !== 'ConceptReference') throw new Unsupported('ecl-feature', 'member filter on a refset expression'); + return this.eclMemberFilter(this.eclConcept(f.refSet.conceptId), f.refSet.conceptId, f.memberFilters); + } + if (f.refSet.type === 'ConceptReference') { + const rid = this.eclConcept(f.refSet.conceptId); + if (!this.store.getSet(KIND.refset, 0, rid, this.stats).size && this.store.isLanguageRefset(rid)) { + // a language reference set: its members are descriptions (as main reports it) + throw new FilterError(`The members of reference set ${f.refSet.conceptId} are descriptions, not concepts, so ^ cannot be evaluated for it`); + } + base = { t: 'set', kind: KIND.refset, pid: 0, value: rid }; + } else if (f.refSet.type === 'Wildcard') { + throw new Unsupported('ecl-feature', '^ *'); + } else { + base = { t: 'refsetOf', of: this.eclNode(f.refSet) }; + } + } else if (f.type === 'AltIdentifier') { + throw new Unsupported('ecl-feature', 'alternate identifier'); + } else { + base = this.eclNode(f); + } + const op = n.operator; + if (!op) return base; + if (f.type === 'Wildcard') { + // over every concept (tx-ecosystem sct/ecl/*-of-any): "has a parent" is having an active is-a + // link (stored as hasProp); "has a child" is an active concept that is not a leaf + const hier = this.store.hierarchy; + const hasParent = hier ? { t: 'set', kind: KIND.hasProp, pid: hier.id, value: 0 } : { t: 'empty' }; + const hasChild = { t: 'minus', a: { t: 'active' }, b: { t: 'leaf' } }; + switch (op) { + case 'DESCENDANT_OR_SELF_OF': case 'CHILD_OR_SELF_OF': case 'ANCESTOR_OR_SELF_OF': case 'PARENT_OR_SELF_OF': return { t: 'all' }; + case 'DESCENDANT_OF': case 'CHILD_OF': return hasParent; + case 'ANCESTOR_OF': case 'PARENT_OF': return hasChild; + case 'TOP_OF_SET': return { t: 'minus', a: { t: 'all' }, b: hasParent }; + case 'BOTTOM_OF_SET': return { t: 'minus', a: { t: 'all' }, b: hasChild }; + default: throw new Unsupported('ecl-feature', op + ' *'); + } + } + if (id != null) { + const desc = { t: 'set', kind: KIND.descendants, pid: 0, value: id }; + const hid = this.store.hierarchy.id; + switch (op) { + case 'DESCENDANT_OF': return desc; + case 'DESCENDANT_OR_SELF_OF': return { t: 'self', id, of: desc }; + case 'CHILD_OF': return { t: 'set', kind: KIND.prop, pid: hid, value: id }; + case 'CHILD_OR_SELF_OF': return { t: 'self', id, of: { t: 'set', kind: KIND.prop, pid: hid, value: id } }; + case 'ANCESTOR_OF': return { t: 'anc', id, self: false }; + case 'ANCESTOR_OR_SELF_OF': return { t: 'anc', id, self: true }; + case 'PARENT_OF': return { t: 'parents', id, self: false }; + case 'PARENT_OR_SELF_OF': return { t: 'parents', id, self: true }; + default: break; + } + } + const map = { + DESCENDANT_OF: ['desc', false], DESCENDANT_OR_SELF_OF: ['desc', true], + CHILD_OF: ['children', false], CHILD_OR_SELF_OF: ['children', true], + ANCESTOR_OF: ['anc', false], ANCESTOR_OR_SELF_OF: ['anc', true], + PARENT_OF: ['parents', false], PARENT_OR_SELF_OF: ['parents', true], + TOP_OF_SET: ['top', false], BOTTOM_OF_SET: ['bottom', false] + }; + const m = map[op]; + if (!m) throw new Unsupported('ecl-feature', op); + return { t: 'hier', dir: m[0], self: m[1], of: base }; + } + + /** {{ C field op value }} as a set */ + eclConceptFilter(f) { + const S = this.store; + const field = f.field.toLowerCase(); + const neg = f.operator === '!='; + const not = (n) => (neg ? { t: 'minus', a: { t: 'all' }, b: n } : n); + if (field === 'active') return (f.value === true) !== neg ? { t: 'active' } : { t: 'inactive' }; + // a concept filter field is the catalog row of that name (moduleId, definitionStatusId, + // effectiveTime: filterable, not refinable) + const row = [...S.props.values()].find((d) => d.code.toLowerCase() === field && d.filterable && !d.refinable); + if (field === 'moduleid' || field === 'definitionstatusid') { + if (!row) return { t: 'empty' }; + return not({ t: 'propIn', pids: [row.id], values: this.eclNode(f.value) }); + } + if (field === 'definitionstatus') { + const p = S.props.get('definitionStatusId'); + const ids = (f.values || []).map((v) => this.id(v === 'primitive' ? '900000000000074008' : '900000000000073002')).filter((x) => x != null); + return not({ t: 'propIn', pids: [p.id], values: { t: 'ids', ids } }); + } + if (field === 'effectivetime') { + const p = row; + const vals = (f.values || []).map(String); + const cmp = { '=': (x) => vals.includes(x), '!=': (x) => !vals.includes(x), '<': (x) => x < vals[0], '<=': (x) => x <= vals[0], '>': (x) => x > vals[0], '>=': (x) => x >= vals[0] }[f.operator]; + if (!p || !cmp) throw new Unsupported('ecl-feature', 'effectiveTime ' + f.operator); + return litSets(p.id, S.propValues(p.id, this.stats).filter((r) => cmp(String(r.value).replace(/-/g, ''))).map((r) => r.value)); + } + throw new Unsupported('ecl-feature', 'concept filter ' + f.field); + } + + /** {{ D ... }}: one description of the concept must satisfy every filter of the block */ + eclDescriptionFilter(filters) { + const S = this.store; + const prepared = filters.map((f) => { + const field = f.field.toLowerCase(); + const out = { field, neg: f.operator === '!=' }; + if (f.valueType === 'term') out.matchers = f.values.map((v) => termMatcher(v)); + else if (field === 'language') out.values = f.values.map((v) => String(v).toLowerCase()); + else if (field === 'type') out.uses = f.values.map((t) => ({ syn: '900000000000013009', fsn: '900000000000003001', def: '900000000000550004' })[t]); + else if (field === 'typeid') out.uses = this.eclCodes(f.value); + else if (field === 'dialect' || field === 'dialectid') { + out.dialects = f.dialects.map((d) => ({ + refsets: d.alias ? [this.id(DIALECT_ALIASES[d.alias] || '')].filter((x) => x != null) : this.eclIds(d.expression), + acceptability: d.acceptability ? d.acceptability.map((a) => this.id(a === 'preferred' ? '900000000000548007' : a === 'acceptable' ? '900000000000549004' : a)) : null + })); + } else if (field === 'active') out.value = f.value; + else if (field === 'id') out.ids = f.values.map(String); // a description's own id (item external_id) + else throw new Unsupported('ecl-feature', 'description filter ' + f.field); + return out; + }); + // words for a full-text pre-selection (match terms with words of >= 3 characters) + const words = []; + for (const f of prepared) { + if (f.field === 'term' && !f.neg && f.matchers.length === 1 && f.matchers[0].words) words.push(...f.matchers[0].words.filter((w) => w.length >= 3)); + } + void S; + // descriptions named by id: their concepts are the candidates (item external_id) + const byId = prepared.find((f) => f.field === 'id' && !f.neg); + return { t: 'descFilter', filters: prepared, words, ...(byId ? { ids: byId.ids } : {}), label: 'description filter' }; + } + + eclIds(expr) { + if (!expr) return null; + return new (require('./engine').Engine)(this.store).evaluate(this.eclNode(expr)).toArray(); + } + + eclCodes(expr) { + const ids = this.eclIds(expr); + if (!ids) return null; + return [...this.store.conceptRows(ids, this.stats).values()].map((r) => r.code); + } + + /** {{ + HISTORY-x }}: add the inactive concepts associated with members of the result */ + eclHistory(node, hs) { + const PROFILES = { MIN: ['900000000000527005'], MOD: ['900000000000527005', '900000000000528000', '900000000000526001', '1186924009'] }; + let refsets; + if (hs.profile === 'EXPLICIT') refsets = this.eclIds(hs.refsets) || []; + else if (hs.profile === 'MAX' || !hs.profile) { + const root = this.id('900000000000522004'); + refsets = root == null ? [] : this.store.getSet(KIND.descendants, 0, root, this.stats).toArray(); + } else refsets = (PROFILES[hs.profile] || []).map((c) => this.id(c)).filter((x) => x != null); + return { t: 'history', of: node, refsets }; + } + + eclRefinement(r) { + switch (r.type) { + case 'Attribute': return this.eclAttribute(r); + case 'AttributeSet': { + const items = r.attributes.map((a) => this.eclRefinement(a)); + return items.length === 1 ? items[0] : { t: r.operator === 'OR' ? 'or' : 'and', items }; + } + case 'AttributeGroup': return this.eclGroup(r); + default: throw new Unsupported('ecl-feature', r.type); + } + } + + eclGroup(g) { + const card = g.cardinality; + const attrs = g.attributes; + const simple = attrs.every((a) => a.type === 'Attribute' && !a.reverse && !a.cardinality && a.comparison && a.comparison.type === 'ExpressionComparison' && a.comparison.operator === 'EQUALS'); + if (!simple) throw new Unsupported('ecl-feature', 'group content'); + const parts = attrs.map((a) => ({ pids: this.eclAttrIds(a.name), values: this.eclNode(a.comparison.value) })); + const node = parts.length === 1 ? { t: 'propIn', pids: parts[0].pids, values: parts[0].values } : { t: 'group', attrs: parts }; + if (!card || (card.min === 1 && card.max === '*')) return node; + if (card.min === 0 && card.max === 0) return { t: 'minus', a: { t: 'all' }, b: node }; + // [m..n] { ... }: count the role groups that satisfy every attribute + const g2 = { t: 'group', attrs: parts, min: card.min, max: card.max === '*' ? Infinity : card.max }; + return card.min === 0 ? { t: 'or', items: [g2, { t: 'minus', a: { t: 'all' }, b: node }] } : g2; + } + + eclAttribute(a) { + const c = a.comparison; + const card = a.cardinality; + const pids = this.eclAttrIds(a.name); + let node; + if (c.type === 'ExpressionComparison') { + const value = this.eclNode(c.value); + if (c.operator === 'EQUALS') { + if (!a.reverse && value.t === 'all') { + // attr = * : any value; the hasProp sets + const items = pids.map((pid) => ({ t: 'set', kind: KIND.hasProp, pid, value: 0 })); + node = items.length === 1 ? items[0] : { t: 'or', items }; + node.values = value; + } else { + node = a.reverse ? { t: 'propOf', pids, sources: value } : { t: 'propIn', pids, values: value }; + // a concept value of an attribute with links and literals: its link sets (value kind 1) + if (!a.reverse && pids.some((pid) => (this.store.propsById.get(pid) || {}).shape === 'both')) node.vk = 1; + } + } else if (c.operator === 'NOT_EQUALS' && !a.reverse) { + // has a value outside the set + node = { t: 'propIn', pids, values: { t: 'minus', a: { t: 'all' }, b: value } }; + } else { + throw new Unsupported('ecl-feature', 'attribute ' + c.operator); + } + } else if (c.type === 'NumericComparison' || c.type === 'StringComparison' || c.type === 'BooleanComparison') { + node = this.eclConcrete(pids, c); + } else { + throw new Unsupported('ecl-feature', c.type); + } + if (!card || (card.min === 1 && card.max === '*')) return node; + if (card.min === 0 && card.max === 0) return { t: 'minus', a: { t: 'all' }, b: node }; + if (card.min === 0 && card.max === '*') return { t: 'all' }; + if (c.type !== 'ExpressionComparison' || a.reverse) throw new Unsupported('ecl-feature', 'attribute cardinality on this comparison'); + // [m..n]: count the matching (group, value) occurrences on each candidate + return { t: 'attrCard', pids, values: node.values, min: card.min, max: card.max === '*' ? Infinity : card.max, base: node }; + } + + eclConcrete(pids, c) { + // concrete values: keys of the attribute's literal prop sets that satisfy the comparison + const S = this.store; + const items = []; + for (const pid of pids) { + const def = S.propsById.get(pid); + if (!def) continue; + const opName = c.operator; + let test; + // a value only compares with a value of its own type: a number with a number (#4000), a + // string with a string ("4000" matches no numeric value) + const isNum = (x) => typeof x === 'number' || (typeof x === 'string' && /^-?\d+(\.\d+)?$/.test(x) && def.type !== 'string'); + if (c.type === 'NumericComparison') { + const v = Number(c.value); + const cmp = { EQUALS: (x) => x === v, NOT_EQUALS: (x) => x !== v, GT: (x) => x > v, GTE: (x) => x >= v, LT: (x) => x < v, LTE: (x) => x <= v }[opName]; + test = cmp && ((x) => isNum(x) && cmp(Number(x))); + } else if (c.type === 'BooleanComparison') { + test = opName === 'EQUALS' ? (x) => String(x) === String(c.value ? 1 : 0) || String(x) === String(c.value) : (x) => !(String(x) === String(c.value ? 1 : 0) || String(x) === String(c.value)); + } else { + // string values: exact, or match:/wild: as description terms are matched + const tests = (c.values || []).map((v) => { + if (typeof v === 'object' && v.kind) return termMatcher({ kind: v.kind === 'wild' ? 'wild' : 'match', value: v.value }); + const s = typeof v === 'object' ? v.value : v; + return (x) => x === s; + }); + const any = (x) => !isNum(x) && tests.some((t) => t(String(x))); + test = opName === 'EQUALS' ? any : (x) => !isNum(x) && !tests.some((t) => t(String(x))); + } + if (!test) throw new Unsupported('ecl-feature', 'concrete ' + opName); + const keys = S.propValues(pid, this.stats).filter((r) => test(r.value)).map((r) => r.value); + items.push(litSets(pid, keys)); + } + if (!items.length) return { t: 'empty' }; + return items.length === 1 ? items[0] : { t: 'or', items }; + } + + /** + * ^ X {{ M ... }}: the members whose row passes every member filter (refset_member rows: active + * only, with effectiveTime and moduleId when the file has them, and the refset's own fields) + */ + eclMemberFilter(rid, code, filters) { + const S = this.store; + // the filters' value sets, each evaluated once + const sets = new Map(); + const setFor = (fl) => { + if (fl.valueType !== 'expression') return null; + if (!sets.has(fl)) sets.set(fl, new Evaluator(S).mat(this.eclNode(fl.value))); + return sets.get(fl); + }; + // `target = ` on the column held in record.target_id: only those rows are read (SQL) + const target = (S.refsetTargetField(rid) || '').toLowerCase(); + const onTarget = target && filters.find((fl) => String(fl.field).toLowerCase() === target && fl.operator === '=' && fl.valueType === 'expression'); + const targetIn = onTarget && setFor(onTarget).size <= 10000 ? setFor(onTarget).toArray() : null; + // the rows as stored: a node column's value is its node id, compared with the filter's set + // without looking codes up (a code only where a string comparison names a node column) + const rows = S.refsetMemberRows(rid, null, targetIn ? { raw: true, targetIn } : { raw: true }); + const codeCache = new Map(); + const codeOf = (v) => { + if (typeof v !== 'number') return v; + if (!codeCache.has(v)) codeCache.set(v, S.codesOfNodes([v]).get(v) ?? ''); + return codeCache.get(v); + }; + const def = S.refsetDef(rid); + const names = def ? def.names.map((n) => String(n).toLowerCase()) : []; + const types = def ? def.types : []; + const cmp = (actual, op, values, c) => { + switch (op) { + case '=': return values.some((v) => c(actual, v) === 0); + case '!=': return !values.some((v) => c(actual, v) === 0); + case '<': return c(actual, values[0]) < 0; + case '<=': return c(actual, values[0]) <= 0; + case '>': return c(actual, values[0]) > 0; + case '>=': return c(actual, values[0]) >= 0; + default: throw new Unsupported('ecl-feature', 'member filter operator ' + op); + } + }; + const str = (a, b) => String(a).localeCompare(String(b)); + const tests = filters.map((fl) => { + const field = String(fl.field).toLowerCase(); + const setOf = () => setFor(fl); + if (field === 'active') return () => (fl.operator === '=') === fl.value; + if (field === 'effectivetime') return (r) => r.effective_time != null && cmp(String(r.effective_time), fl.operator, fl.values, str); + if (field === 'moduleid') { + const bm = setOf(); + return (r) => r.module_id != null && (fl.operator === '=' ? bm.has(r.module_id) : !bm.has(r.module_id)); + } + const i = names.indexOf(field); + if (i < 0) throw new FilterError(`Reference set ${code} has no field named ${fl.field}`); + const t = types[i]; + if (fl.valueType === 'expression') { + if (t !== 'c') throw new FilterError(`Reference set field ${fl.field} is not a concept field`); + const bm = setOf(); + return (r) => { + const v = r.f[i]; + if (v == null || v === '') return false; + // a node id; a string is a code that is no node of the file + const id = typeof v === 'number' ? v : this.id(String(v)); + const inSet = id != null && bm.has(id); + return fl.operator === '=' ? inSet : !inSet; + }; + } + if (fl.valueType === 'numeric') { + if (t !== 'i') throw new FilterError(`Reference set field ${fl.field} is not a numeric field`); + return (r) => r.f[i] != null && r.f[i] !== '' && cmp(Number(r.f[i]), fl.operator, [Number(fl.value)], (a, b) => a - b); + } + if (fl.valueType === 'boolean') return (r) => (fl.operator === '=') === ((String(codeOf(r.f[i])) === '1' || String(codeOf(r.f[i])).toLowerCase() === 'true') === fl.value); + // string / time + return (r) => r.f[i] != null && r.f[i] !== '' && cmp(String(codeOf(r.f[i])), fl.operator, fl.values, str); + }); + const ids = new Set(); + for (const r of rows) if (tests.every((t) => t(r))) ids.add(r.concept_id); + return { t: 'ids', ids: [...ids].sort((a, b) => a - b), label: `^ ${code} {{ M ... }}` }; + } + + /** + * attribute name expression -> property ids (attributes are concepts too): the catalog's + * refinable rows by code; `*` the wildcard rows + */ + eclAttrIds(name) { + const S = this.store; + if (name.type === 'ConceptReference') { + const p = S.props.get(name.conceptId); + return p && p.refinable ? [p.id] : []; + } + if (name.type === 'Wildcard') { + return [...S.props.values()].filter((p) => p.wildcard).map((p) => p.id); + } + if (name.type === 'SubExpressionConstraint' && name.focus.type === 'ConceptReference' && !name.filters) { + const id = this.eclConcept(name.focus.conceptId); + const op = name.operator; + if (!op) return this.eclAttrIds(name.focus); + if (op === 'DESCENDANT_OR_SELF_OF' || op === 'DESCENDANT_OF') { + const d = S.getSet(KIND.descendants, 0, id, this.stats); + const ids = d.toArray(); + if (op === 'DESCENDANT_OR_SELF_OF') ids.push(id); + const rows = S.conceptRows(ids, this.stats); + const out = []; + for (const r of rows.values()) { + const p = S.props.get(r.code); + if (p && p.refinable && !p.isHierarchy) out.push(p.id); + } + if (op === 'DESCENDANT_OR_SELF_OF' && S.hierarchy && S.hierarchy.code === name.focus.conceptId) out.push(S.hierarchy.id); + return out; + } + } + throw new Unsupported('ecl-feature', 'attribute name expression'); + } +} + +/** FHIR search prefix comparison of a stored literal against `eq5`, `ge2020-01-01`, ... */ +function searchPrefixMatch(type, spec, stored) { + const pre = spec.substring(0, 2); + const raw = spec.substring(2); + let a, b; + if (type === 'dateTime') { + // compare at the precision of the value given: digits only (YYYY[MM[DD[hh[mm[ss]]]]]) + b = raw.replace(/\D/g, ''); + a = String(stored).replace(/\D/g, '').substring(0, b.length); + } else { + a = Number(stored); + b = Number(raw); + if (!Number.isFinite(a) || !Number.isFinite(b)) return false; + } + switch (pre) { + case 'eq': case 'ap': return a === b || (typeof a === 'string' && a === b); + case 'ne': return a !== b; + case 'gt': case 'sa': return a > b; + case 'lt': case 'eb': return a < b; + case 'ge': return a >= b; + case 'le': return a <= b; + default: return false; + } +} + +/** the stored properties a catalog entry stands for: a union's members, else itself */ +function pidsOf(p) { + return p.members ? p.members.flatMap(pidsOf) : p.id != null ? [p.id] : []; +} + +/** literal property = any of the stored keys: their prop sets (prefetched in one statement) */ +function litSets(pid, keys) { + if (!keys.length) return { t: 'empty' }; + const items = keys.map((v) => ({ t: 'set', kind: KIND.prop, pid, value: v })); + return items.length === 1 ? items[0] : { t: 'or', items }; +} + +const DIALECT_ALIASES = { + 'en-us': '900000000000509007', 'en-gb': '900000000000508004', 'en-au': '32570271000036106', 'en-ca': '19491000087109', + 'en-nz': '271000210107', 'en-ie': '21000220103', 'fr-ca': '20581000087109', 'fr-be': '21000172104', 'nl-be': '31000172101', + 'nl-nl': '31000146106', 'es-es': '448879004', 'sv-se': '46011000052107' +}; + +/** ECL term matching: "match" = every word is a prefix of a word of the term; "wild" = whole-term pattern */ +function termMatcher(v) { + if (typeof v === 'string') v = { kind: 'match', value: v }; + if (v.kind === 'wild') { + // as main's ECL wild: (cs-snomed.js): no regex, so no backtracking; a run of '*'s means one + return wildTermMatcher(String(v.value)); + } + const words = v.value.toLowerCase().split(/\s+/).filter(Boolean); + const m = (t) => { + const tw = t.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean); + return words.every((w) => tw.some((x) => x.startsWith(w))); + }; + m.words = words; + return m; +} + +function collectIds(n, out) { + if (!n || typeof n !== 'object') return; + if (n.type === 'ConceptReference' && n.conceptId) out.add(n.conceptId); + for (const v of Object.values(n)) { + if (Array.isArray(v)) v.forEach((x) => collectIds(x, out)); + else if (v && typeof v === 'object') collectIds(v, out); + } +} + +module.exports = { Compiler, FilterError, Unsupported, splitList, uniqSorted, litSets, pidsOf }; diff --git a/tx/sqlite-v2/engine/engine.js b/tx/sqlite-v2/engine/engine.js new file mode 100644 index 00000000..d73a7dfb --- /dev/null +++ b/tx/sqlite-v2/engine/engine.js @@ -0,0 +1,358 @@ +'use strict'; +// Expansion engine for one store: compiled selection -> ordered result -> pages. +// +// A selection is { includes: [Include], excludes: [Include], activeOnly }, where an Include is +// { parts: [{ node, order }] } in the order upstream expand.js would add codes (enumerated +// concepts first, then filters); order = explicit id order (enumerated concepts) or null +// (id order = depth-first hierarchy order). +// +// The result is a list of segments, one per part, each with the members not already in an +// earlier segment and not excluded. Paging is by position across segments. Nothing is cached: +// every request plans and evaluates. Ids are eager unless the plan has a costly unselective input +// (text/regex scan) and the request is paged: then only the members up to offset+count are +// produced (lazy first page, no total). + +const { RoaringBitmap32 } = require('roaring'); +const { Evaluator, runSync, runAsync } = require('./evaluate'); +const { KIND, registry } = require('../store'); + +const LAZY_MIN_DRIVER = 50000; // a costly filter over at least this many candidates goes lazy when paged + +class Result { + constructor() { + this.segments = []; // { bm } (id order) or { list } (explicit order) + this.total = 0; + this.complete = true; // false: lazy, total unknown + this.bytes = 0; + } + + add(seg) { + const n = seg.bm ? seg.bm.size : seg.list.length; + if (!n) return; + seg.n = n; + this.segments.push(seg); + this.total += n; + this.bytes += seg.bm ? seg.bm.getSerializationSizeInBytes('portable') + 352 : seg.list.length * 16 + 64; + } + + /** ids at positions [offset, offset+count) */ + page(offset, count) { + const out = []; + let pos = 0; + const end = count < 0 ? Infinity : offset + count; + for (const s of this.segments) { + if (pos + s.n <= offset) { pos += s.n; continue; } + if (pos >= end) break; + const from = Math.max(0, offset - pos); + const take = Math.min(s.n - from, end - pos - from); + if (s.bm) { + for (const id of s.bm.rangeUint32Array(from, take)) out.push(id); + } else { + for (let i = from; i < from + take; i++) out.push(s.list[i]); + } + pos += s.n; + } + return out; + } + + has(id) { + for (const s of this.segments) if (s.bm ? s.bm.has(id) : s.list.includes(id)) return true; + return false; + } +} + +class Engine { + constructor(store, opts = {}) { + this.store = store; + registry.engines.add(this); + this.lazyMinDriver = opts.lazyMinDriver || LAZY_MIN_DRIVER; + // optional system order (LOINC, SNOMED CT; orders.js): { rank[id], ids[rank], walk, selfFirst }, + // data the importer stored in the file, read on first use + this._order = opts.order || null; + } + + /** + * @param {object} sel compiled selection + * @param {object} opts { offset, count, trace } + * @returns {Result} + */ + run(sel, opts = {}) { + return runSync(this._runG(sel, opts)); + } + + /** + * run(), pausing between the steps and chunks of a long evaluation: opts.pause (the request's + * opContext.checkAndYield) is awaited at each pause point (evaluate.js runAsync) + * @returns {Promise} + */ + runAsync(sel, opts = {}) { + return opts.pause ? runAsync(this._runG(sel, opts), opts.pause) : Promise.resolve(this.run(sel, opts)); + } + + * _runG(sel, opts) { + // every request plans and evaluates: the design keeps no caches + const trace = opts.trace || null; + const want = opts.count >= 0 ? Math.max(opts.offset, 0) + opts.count : -1; + const ev = new Evaluator(this.store, { trace }); + if (!trace) return yield* this._evaluate(ev, sel, want); + const s = trace.open('evaluate selection', 'set', this.store.system); + try { + const r = yield* this._evaluate(ev, sel, want); + trace.close(s, r); + return r; + } catch (e) { + s.error = e.message; + trace.close(s, null); + throw e; + } + } + + * _evaluate(ev, sel, want) { + const allNodes = []; + for (const inc of [...sel.includes, ...sel.excludes]) for (const p of inc.parts) allNodes.push(p.node); + ev.prefetch(allNodes); + + let excl = null; + for (const inc of sel.excludes) { + for (const p of inc.parts) { + const b = yield* ev.matG(p.node); + excl = excl ? RoaringBitmap32.or(excl, b) : b; + } + } + const active = sel.activeOnly ? yield* ev.matG({ t: 'active' }) : null; + + const parts = []; + for (const inc of sel.includes) for (const p of inc.parts) parts.push(p); + + // lazy only for a single filter part whose plan is driver ∧ costly filters over a large driver + // lazy needs a page to stop at: count = 0 asks for the total, which only a full evaluation gives + if (want > 0 && parts.length === 1 && !parts[0].order && !this._order) { + const plan = yield* this._lazyPlan(ev, parts[0].node, active, excl); + if (plan) { + const r = new Result(); + const got = yield* ev.lazyG(plan.driver, plan.filters, want, 0); + let ids = got.ids; + if (excl) ids = RoaringBitmap32.andNot(ids, excl); + { + r.add({ bm: ids }); + if (!r.segments.length) r.segments.push({ bm: ids, n: 0 }); + } + r.complete = got.done; + return r; + } + } + + const r = new Result(); + let seen = null; + for (const p of parts) { + let b = yield* ev.matG(p.node); + if (active) b = RoaringBitmap32.and(b, active); + if (excl) b = RoaringBitmap32.andNot(b, excl); + if (seen) b = RoaringBitmap32.andNot(b, seen); + if (p.order) { + const list = []; + const dup = new Set(); + for (const id of p.order) if (b.has(id) && !dup.has(id)) { dup.add(id); list.push(id); } + r.add({ list }); + } else if (p.node.order === 'firstSeen') { + r.add({ list: this._firstSeen(ev, b, p.node.via) }); + } else if (p.node.order === 'lists') { + r.add({ list: yield* this._listsInSequence(ev, p.node.of, b) }); + } else if (p.node.t === 'set' && p.node.kind === KIND.refset && this.store.sequenceOf(p.node.value)) { + // an ordered list (LOINC answer list): its own order + const seqd = this.store.sequenceOf(p.node.value).filter((id) => b.has(id)); + const rest = RoaringBitmap32.andNot(b, new RoaringBitmap32(seqd)); + r.add({ list: [...seqd, ...(this._order ? this._ordered(rest) : rest.toArray())] }); + } else if (this._order && this._order.selfFirst && this.store.hasLinkOrder && p.node.t === 'set' && p.node.kind === KIND.prop + && this.store.hierarchy && p.node.pid === this.store.hierarchy.id) { + // (SNOMED CT child-of, ECL b.has(id)))]; + const rest = RoaringBitmap32.andNot(b, new RoaringBitmap32(ordered)); + r.add({ list: [...ordered, ...this._ordered(rest)] }); + } else if (p.node.t === 'all' && p.node.whole && this._order && this._order.hasWalk) { + // (an include of the whole code system: the built-in walk, see orders.js snomedWalk, + // loincOrder; SNOMED CT's leaves out the concepts it does not reach. wholeSystem: its + // count=0 total is the code system's size, SqliteV2Provider.processSelection. Every code + // otherwise, as ECL *: the system order, by id for SNOMED CT, as cs-snomed.js lists it) + const walk = this._order.walk; + const end = walk.reached != null ? walk.reached : walk.length; + const list = []; + for (let k = 0; k < end; k++) { + if (b.has(walk[k])) list.push(walk[k]); + if (k && k % 100000 === 0) yield; + } + r.add({ list }); + if (!excl && parts.length === 1) r.wholeSystem = true; + } else if (this._order && this._order.selfFirst && p.node.eclOrder) { + // (SNOMED CT ECL: the order cs-snomed.js lists a compound, refined or filtered result in) + r.add({ list: yield* this._eclOrdered(ev, p.node, b) }); + } else if (this._order && this._order.selfFirst && p.node.t === 'self' && b.has(p.node.id)) { + // (SNOMED CT is-a, ECL <<: the concept, then its descendants in the system order; < [l, m])); + const loose = ids.filter((id) => !firstList.has(id)); + const answers = ids.filter((id) => firstList.has(id)); + answers.sort((x, y) => (this._rank(firstList.get(x)) - this._rank(firstList.get(y))) || ((seq.get(x) ?? 0) - (seq.get(y) ?? 0)) || (x - y)); + return [...(this._order ? this._ordered(new RoaringBitmap32(loose)) : loose), ...answers]; + } + + /** + * the members of the ordered lists `of` (LOINC answers-for = a term: its answer lists), list + * by list in the system order, each in its sequence, an answer in several once (upstream's + * order: cs-loinc.js answers-for). One statement for the lists' members + */ + * _listsInSequence(ev, of, b) { + const lists = (yield* ev.matG(of)).toArray().sort((x, y) => this._rank(x) - this._rank(y)); + const seqs = this.store.sequencesOf(lists); + const out = []; + const seen = new Set(); + for (const l of lists) for (const m of seqs.get(l)) if (b.has(m) && !seen.has(m)) { seen.add(m); out.push(m); } + if (seen.size < b.size) { + const rest = RoaringBitmap32.andNot(b, new RoaringBitmap32([...seen])); + out.push(...(this._order ? this._ordered(rest) : rest.toArray())); + } + return out; + } + + /** members of b in the system's order: sort their ranks (typed arrays) */ + /** + * The members b of an ECL node, in the order cs-snomed.js lists them: a refinement or a {{ }} + * filter keeps its base's order (_evalRefined, _eclDescriptionFilter walk the base); AND, the + * right side's (_eclIntersect: the right filtered by the left, unless one side is *); OR, the + * left side's, then the rest in the right side's (_eclUnion); MINUS, the left side's + * (_eclMinus). << X: X first, then the rest in the system order (by id); < b.has(id)))]; + return [...ordered, ...this._ordered(RoaringBitmap32.andNot(b, new RoaringBitmap32(ordered)))]; + } + return this._ordered(b); + } + + _ordered(b) { + const { rank, ids } = this._order; + const arr = b.toUint32Array(); + const ranks = new Uint32Array(arr.length); + for (let i = 0; i < arr.length; i++) ranks[i] = rank[arr[i]]; + ranks.sort(); + const out = new Array(ranks.length); + for (let k = 0; k < ranks.length; k++) out[k] = ids[ranks[k]]; + return out; + } + + /** driver (free) and costly filters, if this node is worth evaluating lazily */ + * _lazyPlan(ev, node, active, excl) { + const items = node.t === 'and' ? node.items : [node]; + const free = items.filter((i) => ev.isFree(i)); + const costly = items.filter((i) => !ev.isFree(i) && ((i.t === 'text' && !i.lits) || (i.t === 'desigRegex' && !i.lits) || i.t === 'litMatch' || i.t === 'descFilter' || (i.t === 'desigMatch' && i.re != null))); + if (!costly.length || free.length + costly.length !== items.length) return null; // (a prefiltered text node is neither: evaluated whole) + let driver = free.length ? (free.length === 1 ? free[0] : { t: 'and', items: free }) : { t: 'all' }; + if (active) driver = { t: 'and', items: [driver, { t: 'active' }] }; + const size = (yield* ev.matG(driver)).size; + if (size < this.lazyMinDriver) return null; + void excl; + return { driver, filters: costly }; + } + + /** membership of one id in a node (validate-code): probes, never materialises costly inputs */ + contains(node, id, trace) { + const ev = new Evaluator(this.store, { trace }); + ev.prefetch([node]); + return ev.filter(node, new RoaringBitmap32([id])).has(id); + } + + /** contains(), pausing (see runAsync) */ + async containsAsync(node, id, trace, pause = null) { + const ev = new Evaluator(this.store, { trace }); + ev.prefetch([node]); + return (await ev.filterAsync(node, new RoaringBitmap32([id]), pause)).has(id); + } + + /** materialise one node (filter API) */ + evaluate(node, trace) { + const ev = new Evaluator(this.store, { trace }); + ev.prefetch([node]); + return ev.mat(node); + } + + /** evaluate(), pausing (see runAsync) */ + evaluateAsync(node, trace, pause = null) { + const ev = new Evaluator(this.store, { trace }); + ev.prefetch([node]); + return ev.matAsync(node, pause); + } +} + +module.exports = { Engine, Result }; diff --git a/tx/sqlite-v2/engine/evaluate.js b/tx/sqlite-v2/engine/evaluate.js new file mode 100644 index 00000000..01314671 --- /dev/null +++ b/tx/sqlite-v2/engine/evaluate.js @@ -0,0 +1,778 @@ +'use strict'; +// Set evaluation of IR nodes over one store (one release of one code system). +// +// IR (all ids are concept_ids = bit positions): +// {t:'all'} {t:'active'} {t:'inactive'} {t:'leaf'} {t:'empty'} +// {t:'ids', ids} explicit concepts +// {t:'set', kind, pid, value} one stored set (descendants, prop, hasProp, refset) +// {t:'self', id, of:node} node ∪ {id} +// {t:'anc', id, self} {t:'parents', id, self} upward walks over hierarchy facts +// {t:'hier', dir, self, of} hierarchy operator applied to a set +// {t:'propIn', pids, values:node} concepts with P -> a member of values +// {t:'propOf', pids, sources:node} targets of P from sources (reverse / dotted) +// {t:'litIn', pid, values} {t:'litMatch', pid, re} literal-valued property +// {t:'text', field:'code'|'display', re} regex on code / display +// {t:'search', text, mode, lang} full-text (FTS), in one language (lang) or all +// {t:'group', attrs:[{pids, values}]} attributes satisfied inside one role group +// {t:'and', items} {t:'or', items} {t:'minus', a, b} +// {t:'layer', layer, node} node evaluated on a supplement layer (same ids) +// +// Cost classes: stored sets and explicit ids are "free" (one batched read, exact size); the +// others ("costly") read facts. An intersection evaluates its free inputs first, smallest first, +// then narrows the candidates with each costly input by probing the candidates' facts when there +// are few of them, or by materialising the input when that is cheaper. + +const { RoaringBitmap32 } = require('roaring'); +const { KIND } = require('../store'); +const regexUtilities = require('../../../library/regex-utilities'); +const { ftsQuery, stripAnyAffixes } = require('./regex-literals'); +const { settings, TooCostly } = require('../settings'); + +const PROBE_MAX = 20000; // probe a costly input when the candidates are at most this many +const SCAN_CHUNK = 4096; // lazy evaluation: candidates examined per chunk +const ROW_CHUNK = 5000; // rows read and tested per statement between pauses (scans, probes) + +// Cooperative evaluation. The evaluation steps are generators: a bare `yield` marks a pause +// point between chunks of a long read, `yield*` runs a sub-step. runSync drives one straight +// through (the sync API: compile.js, stored code systems); runAsync awaits `pause` (the request's +// opContext.checkAndYield, which gives the event loop a turn every 10 ms of compute) at each +// pause point, so a long evaluation does not hold the worker's event loop. better-sqlite3 is +// synchronous and a connection cannot run another statement while an iterator is open, so no +// statement iterator is held across a pause: long scans read bounded chunks with .all(). +function runSync(g) { + let r = g.next(); + while (!r.done) r = g.next(); + return r.value; +} + +async function runAsync(g, pause) { + let r = g.next(); + while (!r.done) { + try { + await pause(); + } catch (e) { + g.return(); + throw e; + } + r = g.next(); + } + return r.value; +} + +/** run a generator step inside a trace span (as Tracer.span does for a function) */ +function* spanG(trace, label, kind, system, g) { + const s = trace.open(label, kind, system); + let r = null; + let ok = false; + try { + r = yield* g; + ok = true; + return r; + } catch (e) { + s.error = e.message; + throw e; + } finally { + trace.close(s, ok ? r : null); + } +} + +const FREE = new Set(['all', 'active', 'inactive', 'leaf', 'empty', 'ids', 'set']); + +class Unsupported extends Error { + constructor(reason, detail) { + super(reason + (detail ? ': ' + detail : '')); + this.reason = reason; + this.detail = detail; + this.unsupported = true; + } +} + +function key(node) { + let k = node._key; + if (!k) { + k = JSON.stringify(node, (n, v) => { + if (n === '_key' || n === 'why' || n === 'label' || n === 'eclOrder') return undefined; // eclOrder: order only (engine.js) + if (n === 'layer') return 'L' + v.id; // a supplement layer: its identity, not its content + if (n === 'from') return 'S' + v.uid; // another file of the same system + return v; + }); + Object.defineProperty(node, '_key', { value: k, enumerable: false }); + } + return k; +} + +/** a short human label for a node (trace spans) */ +function label(node) { + if (node.label) return node.label; + switch (node.t) { + case 'set': return ['', 'all', 'active', 'leaf', 'descendants', 'prop', 'hasProp', 'refset'][node.kind] + (node.pid ? ' p' + node.pid : '') + (node.kind > 3 ? ' ' + node.value : ''); + case 'ids': return node.ids.length + ' codes'; + case 'and': case 'or': return node.t + '(' + node.items.length + ')'; + case 'text': return node.field + ' ~ /' + node.re + '/'; + case 'litMatch': return 'p' + node.pid + ' ~ /' + node.re + '/'; + case 'search': return 'search "' + node.text + '"'; + default: return node.t; + } +} + +class Evaluator { + /** + * @param {Store} store + * @param {object} [opts] { trace: Tracer|null } + */ + constructor(store, opts = {}) { + this.store = store; + this.trace = opts.trace || null; + this.stats = this.trace ? this.trace.stats : null; + this.memo = new Map(); + this.local = new Map(); // stored sets read in this evaluation (read once, used by every step) + this.history = new Map(); // association indexes built in this evaluation + this.spent = 0; // planner estimate of fact rows this evaluation reads + } + + /** account for an estimated read before doing it; refuse when over the budget */ + spend(rows, what) { + this.spent += rows; + if (this.spent > settings.maxScanRows) { + throw new TooCostly(`estimated cost ${Math.round(this.spent).toLocaleString('en-US')} rows (${what}) > ${settings.maxScanRows.toLocaleString('en-US')}`); + } + } + + isFree(node) { + if (FREE.has(node.t)) return true; + if (node.t === 'self') return this.isFree(node.of); + if (node.t === 'and' || node.t === 'or') return node.items.every((i) => this.isFree(i)); + if (node.t === 'minus') return this.isFree(node.a) && this.isFree(node.b); + if (node.t === 'propIn') return this.isFree(node.values); + return this.memo.has(key(node)); + } + + /** load every stored-set leaf of a plan with one statement per (kind, property) */ + prefetch(nodes) { + const want = new Map(); + const walk = (n) => { + if (!n || typeof n !== 'object') return; + if (n.t === 'layer' || n.t === 'xlate') return; + if (n.t === 'set') { + const k = n.kind + ':' + n.pid + ':' + (n.vk || 0); + if (!want.has(k)) want.set(k, { kind: n.kind, pid: n.pid, vk: n.vk || 0, values: new Set() }); + want.get(k).values.add(n.value); + return; + } + for (const v of Object.values(n)) { + if (Array.isArray(v)) v.forEach(walk); + else if (v && typeof v === 'object' && v.t) walk(v); + } + }; + nodes.forEach(walk); + if (!want.size) return; + const run = () => { + for (const w of want.values()) this.store.loadSets(w.kind, w.pid, [...w.values], this.stats, this.local, w.vk); + }; + if (this.trace) this.trace.span('load stored sets (' + [...want.values()].reduce((n, w) => n + w.values.size, 0) + ' keys, ' + want.size + ' statements)', 'set', this.store.system, run); + else run(); + } + + // ---- materialise ------------------------------------------------------------------------- + + /** the members of a node (sync: no pauses) */ + mat(node) { return runSync(this.matG(node)); } + + /** the members of a node, pausing between chunks (pause: the request's checkAndYield) */ + matAsync(node, pause) { return pause ? runAsync(this.matG(node), pause) : Promise.resolve(this.mat(node)); } + + * matG(node) { + const k = key(node); + let b = this.memo.get(k); + if (b) return b; + if (this.trace && !FREE.has(node.t)) b = yield* spanG(this.trace, label(node), 'set', this.store.system, this._mat(node)); + else b = yield* this._mat(node); + this.memo.set(k, b); + return b; + } + + * _mat(node) { + const S = this.store; + const st = this.stats; + switch (node.t) { + case 'empty': return new RoaringBitmap32(); + case 'all': return S.all(st, this.local); + case 'active': return S.active(st, this.local); + case 'inactive': return RoaringBitmap32.andNot(S.all(st, this.local), S.active(st, this.local)); + case 'leaf': return S.leaf(st, this.local); + case 'ids': return new RoaringBitmap32(node.ids); + case 'set': return S.getSet(node.kind, node.pid, node.value, st, this.local, node.vk || 0); + case 'self': { + const r = (yield* this.matG(node.of)).clone(); + r.add(node.id); + return r; + } + case 'anc': { + const r = new RoaringBitmap32(S.ancestorsOf(node.id, st)); + if (node.self) r.add(node.id); + return r; + } + case 'parents': { + const r = new RoaringBitmap32(S.parentsOf(node.id, st)); + if (node.self) r.add(node.id); + return r; + } + case 'hier': return yield* this._hier(node); + case 'propIn': return yield* this._propIn(node); + case 'propOf': { + const src = yield* this.matG(node.sources); + this.spend(src.size * 8, 'relation image'); + const pids = new Set(node.pids); + const out = new RoaringBitmap32(); + const ids = src.toArray(); + for (let i = 0; i < ids.length; i += 50000) { + if (i) yield; + for (const r of S.linksFrom(ids.slice(i, i + 50000), pids, true, st)) out.add(r.t); + } + return out; + } + case 'litIn': { + const sets = S.loadSets(KIND.prop, node.pid, node.values, st, this.local); + return RoaringBitmap32.orMany([...sets.values()]); + } + case 'litMatch': { + const re = wholeTerm(node.re); + this.spend(S.propValues(node.pid, st).length, 'regex over property values'); + const keys = S.propValues(node.pid, st).filter((r) => re.test(String(r.value))).map((r) => r.value); + if (!keys.length) return new RoaringBitmap32(); + return RoaringBitmap32.orMany([...S.loadSets(KIND.prop, node.pid, keys, st, this.local).values()]); + } + case 'refsetOf': { + const ids = (yield* this.matG(node.of)).toArray(); + const sets = [...S.loadSets(KIND.refset, 0, ids, st, this.local).values()]; + return sets.length ? RoaringBitmap32.orMany(sets) : new RoaringBitmap32(); + } + case 'descFilter': { + if (node.ids) { + // {{ D id = ... }}: the concepts of those descriptions, then the block's filters on them + const cand = new RoaringBitmap32(); + for (const v of node.ids) for (const r of S.itemsByExternalId(v)) cand.add(r.concept); + return yield* this._descFilter(node, cand); + } + if (node.words.length) { + // full-text pre-selection, then the exact test on the candidates + const q = node.words.map((w) => '"' + w.replace(/"/g, '""') + '"').join(' AND '); + return yield* this._descFilter(node, new RoaringBitmap32(S.ftsDesignationConcepts(q, st))); + } + this.spend(S.conceptCount * 3, 'description scan'); + return yield* this._descFilter(node, S.all(st, this.local)); + } + case 'history': { + const base = yield* this.matG(node.of); + const add = new RoaringBitmap32(); + for (const rs of node.refsets) { + for (const [target, sources] of this._historyIndex(rs)) if (base.has(target)) for (const x of sources) add.add(x); + } + return RoaringBitmap32.or(base, add); + } + case 'desigMatch': return yield* this._desigMatch(node, null); + case 'desigRegex': return yield* this._desigRegex(node, null); + case 'text': return yield* this._textScan(node, null); + case 'search': return (yield* S.searchTextG(node.text, st, node.mode, node.lang || null, node.defLang)) || new RoaringBitmap32(); + case 'group': return yield* this.filterG(node, yield* this.matG({ t: 'and', items: node.attrs.map(attrNode) })); + case 'attrCard': { + const has = yield* this.matG(node.base); // at least one occurrence + const counted = yield* this._attrCard(node, has); + return node.min === 0 ? RoaringBitmap32.or(counted, RoaringBitmap32.andNot(S.all(st, this.local), has)) : counted; + } + case 'layer': return yield* new Evaluator(node.layer.store, { trace: this.trace }).matG(node.node); + case 'xlate': { + // evaluate on the other file, then map its ids to this file's by code + const b = yield* new Evaluator(node.from, { trace: this.trace }).matG(node.node); + return S.translateFrom(node.from, b, st); + } + case 'and': return yield* this._and(node.items); + case 'or': { + const parts = []; + for (const i of node.items) parts.push(yield* this.matG(i)); + return parts.length === 1 ? parts[0] : RoaringBitmap32.orMany(parts); + } + case 'minus': { + const A = yield* this.matG(node.a); + return RoaringBitmap32.andNot(A, yield* this.filterG(node.b, A)); + } + default: throw new Error('mat: unknown node ' + node.t); + } + } + + * _hier(node) { + const of = yield* this.matG(node.of); + const ids = of.toArray(); + const S = this.store; + let out; + if (node.dir === 'desc') { + const sets = S.loadSets(KIND.descendants, 0, ids, this.stats, this.local); + out = RoaringBitmap32.orMany([...sets.values()]); + } else if (node.dir === 'children') { + const sets = S.loadSets(KIND.prop, S.hierarchy.id, ids, this.stats, this.local); + out = RoaringBitmap32.orMany([...sets.values()]); + } else if (node.dir === 'top' || node.dir === 'bottom') { + const sets = S.loadSets(KIND.descendants, 0, ids, this.stats, this.local); + if (node.dir === 'top') { + out = RoaringBitmap32.andNot(of, RoaringBitmap32.orMany([...sets.values()])); + } else { + out = new RoaringBitmap32(); + for (const id of ids) if (!sets.get(id).intersects(of)) out.add(id); + } + return out; + } else if (node.dir === 'parents') { + out = new RoaringBitmap32(); + for (const r of S.linksFrom(ids, new Set([S.hierarchy.id]), true, this.stats)) out.add(r.t); + } else { + out = new RoaringBitmap32(); + for (let i = 0; i < ids.length; i++) { + if (i && i % 200 === 0) yield; + out.orInPlace(new RoaringBitmap32(S.ancestorsOf(ids[i], this.stats))); + } + } + if (node.self) out = RoaringBitmap32.or(out, of); + return out; + } + + * _propIn(node) { + const V = yield* this._propValues(node); + if (V.size === 0) return new RoaringBitmap32(); + this.spend(V.size * node.pids.length, 'value sets'); + const vals = V.toArray(); + const parts = []; + for (const pid of node.pids) { + // one statement for all the values: stored prop sets keyed by target concept_id + const sets = this.store.loadSets(KIND.prop, pid, vals, this.stats, this.local, node.vk || 0); + for (const b of sets.values()) if (b.size) parts.push(b); + } + return parts.length ? RoaringBitmap32.orMany(parts) : new RoaringBitmap32(); + } + + /** + * The values of a propIn node that can matter: only a target of one of its properties has a + * stored prop set, so a costly values node (a regex over the targets' displays) is evaluated on + * the properties' targets (the keys of their prop sets) instead of the whole system. The union + * _propIn takes is the same; a LOINC CLASS regex tests ~1,000 part displays, not 250,000. + */ + * _propValues(node) { + if (this.isFree(node.values)) return yield* this.matG(node.values); + let targets = null; + for (const pid of node.pids) { + const keys = new RoaringBitmap32(this.store.propValues(pid, this.stats, node.vk || 0).map((r) => r.value).filter((v) => Number.isInteger(v))); + targets = targets ? RoaringBitmap32.or(targets, keys) : keys; + } + return yield* this.filterG(node.values, targets); + } + + * _and(items) { + const free = items.filter((i) => this.isFree(i)); + const costly = items.filter((i) => !this.isFree(i)); + let cand = null; + if (free.length) { + const sets = []; + for (const i of free) sets.push(yield* this.matG(i)); + sets.sort((a, b) => a.size - b.size); + cand = sets[0]; + for (let j = 1; j < sets.length && cand.size; j++) cand = RoaringBitmap32.and(cand, sets[j]); + } + for (const c of costly) { + if (cand && cand.size === 0) break; + cand = cand ? yield* this.filterG(c, cand) : yield* this.matG(c); + } + return cand || new RoaringBitmap32(); + } + + // ---- filter: members of `cand` that are in node's set ---------------------------------- + + /** the members of cand in node (sync: no pauses) */ + filter(node, cand) { return runSync(this.filterG(node, cand)); } + + filterAsync(node, cand, pause) { return pause ? runAsync(this.filterG(node, cand), pause) : Promise.resolve(this.filter(node, cand)); } + + * filterG(node, cand) { + if (cand.size === 0) return cand; + if (this.isFree(node) || cand.size > PROBE_MAX) return RoaringBitmap32.and(cand, yield* this.matG(node)); + if (this.trace) return yield* spanG(this.trace, 'probe ' + label(node) + ' on ' + cand.size, 'rows', this.store.system, this._probe(node, cand)); + return yield* this._probe(node, cand); + } + + * _probe(node, cand) { + const S = this.store; + const st = this.stats; + switch (node.t) { + case 'and': { + let cur = cand; + const order = [...node.items].sort((a, b) => (this.isFree(b) ? 1 : 0) - (this.isFree(a) ? 1 : 0)); + for (const i of order) { if (!cur.size) break; cur = yield* this.filterG(i, cur); } + return cur; + } + case 'or': { + let res = new RoaringBitmap32(); + let rem = cand; + for (const i of node.items) { + if (!rem.size) break; + const f = yield* this.filterG(i, rem); + res = RoaringBitmap32.or(res, f); + rem = RoaringBitmap32.andNot(rem, f); + } + return res; + } + case 'minus': { + const x = yield* this.filterG(node.a, cand); + return RoaringBitmap32.andNot(x, yield* this.filterG(node.b, x)); + } + case 'propIn': { + const pids = new Set(node.pids); + this.spend(cand.size * 8, 'attribute probe'); + const rows = S.linksFrom(cand.toArray(), pids, true, st); + if (!rows.length) return new RoaringBitmap32(); + const targets = new RoaringBitmap32(rows.map((r) => r.t)); + const ok = yield* this.filterG(node.values, targets); + const out = new RoaringBitmap32(); + for (const r of rows) if (ok.has(r.t)) out.add(r.s); + return out; + } + case 'group': return yield* this._group(node, cand); + case 'attrCard': return RoaringBitmap32.and(cand, yield* this.matG(node)); + case 'descFilter': return yield* this._descFilter(node, cand); + case 'desigMatch': return yield* this._desigMatch(node, cand); + case 'desigRegex': return yield* this._desigRegex(node, cand); + case 'text': return yield* this._textScan(node, cand); + case 'litMatch': { + const re = wholeTerm(node.re); + const out = new RoaringBitmap32(); + for (const r of S.literalsOf(cand.toArray(), true, st)) if (r.p === node.pid && re.test(String(r.v))) out.add(r.c); + return out; + } + default: + return RoaringBitmap32.and(cand, yield* this.matG(node)); + } + } + + /** concepts in cand with one description that passes every filter of the block */ + * _descFilter(node, cand) { + const S = this.store; + const out = new RoaringBitmap32(); + const ids = cand.toArray(); + const activeFilter = node.filters.find((f) => f.field === 'active'); + // a dialect filter reads the acceptability rows (a file with designation.rank does not read them + // otherwise) + const opts = { withAcc: node.filters.some((f) => f.field === 'dialect' || f.field === 'dialectid'), withExternalId: node.filters.some((f) => f.field === 'id') }; + for (let i = 0; i < ids.length; i += ROW_CHUNK) { + if (i) yield; + const rows = S.designationRows(ids.slice(i, i + ROW_CHUNK), this.stats, opts); + for (const [id, list] of rows) { + if (list.some((d) => (activeFilter || d.active) && node.filters.every((f) => descMatches(d, f)))) out.add(id); + } + } + return out; + } + + /** designation = / regex (R5 generic filter): the display or an active designation */ + * _desigMatch(node, cand) { + const S = this.store; + const test = node.re != null ? ((re) => (t) => t != null && re.test(t))(wholeTerm(node.re)) : (t) => t === node.eq; + if (!cand && node.eq != null && node.eq.length >= 3 && S.hasFts) { + // full-text candidates, then the exact test + const q = '"' + node.eq.replace(/"/g, '""') + '"'; + cand = S.ftsDisplayIds(q, this.stats); + cand.addMany(S.ftsDesignationConcepts(q, this.stats)); + } + const out = new RoaringBitmap32(); + if (!cand) { + this.spend(S.conceptCount * 4, 'designation scan'); + for (const [a, b] of idRanges(S)) { + for (const [id, display] of S.conceptColumn('display', a, b)) if (test(display)) out.add(id); + yield; + } + for (const [a, b] of idRanges(S)) { + for (const [id, term] of S.designationRange(a, b)) if (test(term)) out.add(id); + yield; + } + return out; + } + this.spend(cand.size * 4, 'designation probe'); + const ids = cand.toArray(); + for (let i = 0; i < ids.length; i += ROW_CHUNK) { + if (i) yield; + const chunk = ids.slice(i, i + ROW_CHUNK); + for (const r of S.conceptRows(chunk, this.stats).values()) if (test(r.display)) out.add(r.concept_id); + for (const [id, list] of S.designationRows(chunk, this.stats)) if (!out.has(id) && list.some((d) => d.active && test(d.term))) out.add(id); + } + return out; + } + + /** + * SNOMED CT display regex: concepts with an active description of one of node.uses (FSN, + * synonym) in node.lang whose whole term matches (RE2, case-sensitive). With required literals the + * candidates come from the trigram index on designations; otherwise that language's active + * descriptions are scanned. + */ + * _desigRegex(node, cand) { + const S = this.store; + const whole = (t) => wholeTermRe.test(t); + const wholeTermRe = wholeTerm(node.re); + const useIds = new Set(); + for (const [id, u] of S.uses) if (u && node.uses.includes(u.code)) useIds.add(id); + const lang = String(node.lang).toLowerCase(); + const inLang = (l) => { if (!l) return false; const x = String(l).toLowerCase(); return x === lang || x.startsWith(lang + '-'); }; + const out = new RoaringBitmap32(); + const take = (cid, term, language, use, active) => { if (active && useIds.has(use) && inLang(language) && whole(term)) out.add(cid); }; + // candidates given (a lazy chunk, a membership probe, an is-a): read their descriptions, unless + // the trigram candidates are the smaller set + if (cand && (cand.size <= 2000 || (!node.lits && cand.size <= 200000))) { + this.spend(cand.size * 4, 'description regex probe'); + const ids = cand.toArray(); + for (let i = 0; i < ids.length; i += ROW_CHUNK) { + if (i) yield; + const rows = S.designationsRaw(ids.slice(i, i + ROW_CHUNK), this.stats); + for (const [cid, term, language, use, active] of rows) take(cid, term, language, use, active); + } + return out; + } + if (node.lits && S.hasFts) { + // one statement (each chunk would run the trigram query again); the rows tested in chunks + const rows = S.ftsDesignationRows(ftsQuery(node.lits), this.stats); + this.spend(rows.length, 'description regex (trigram candidates)'); + for (let i = 0; i < rows.length; i++) { + if (i && i % ROW_CHUNK === 0) yield; + const [cid, term, language, use, active] = rows[i]; + if (!cand || cand.has(cid)) take(cid, term, language, use, active); + } + return out; + } + this.spend(S.conceptCount * 4, 'description regex scan'); + let n = 0; + for (const [a, b] of idRanges(S)) { + const rows = S.designationRange(a, b, lang); + n += rows.length; + for (const [cid, term, language, use, active] of rows) if (!cand || cand.has(cid)) take(cid, term, language, use, active); + yield; + } + if (this.stats) { this.stats.statements++; this.stats.rows += n; } + return out; + } + + /** association refset: target concept -> [source concepts], built once per evaluation */ + _historyIndex(refsetId) { + const S = this.store; + let m = this.history.get(refsetId); + if (!m) { + m = new Map(); + const rows = S.refsetMemberRows(refsetId); + const targets = S.resolveCodes([...new Set(rows.map((r) => JSON.parse(r.fields)[0]).filter(Boolean).map(String))]); + for (const r of rows) { + const t = targets.get(String(JSON.parse(r.fields)[0])); + if (t == null) continue; + if (!m.has(t)) m.set(t, []); + m.get(t).push(r.concept_id); + } + this.history.set(refsetId, m); + } + return m; + } + + /** candidates whose count of matching (group, value) occurrences is within [min, max] */ + * _attrCard(node, cand) { + const out = new RoaringBitmap32(); + if (!cand.size) return out; + const V = yield* this.matG(node.values); + const pids = new Set(node.pids); + this.spend(cand.size * 8, 'cardinality count'); + const ids = cand.toArray(); + for (let i = 0; i < ids.length; i += 50000) { + if (i) yield; + const counts = new Map(); + for (const r of this.store.linksFrom(ids.slice(i, i + 50000), pids, true, this.stats)) { + if (!V.has(r.t)) continue; + let m = counts.get(r.s); + if (!m) counts.set(r.s, m = new Set()); + m.add(r.g + ':' + r.t); + } + for (const [s, m] of counts) if (m.size >= node.min && m.size <= node.max) out.add(s); + } + return out; + } + + /** + * attributes that must hold together in one role group (group 0, ungrouped, is not a role + * group); with min/max, the number of such groups must be in range + */ + * _group(node, cand) { + let pre = cand; + for (const a of node.attrs) pre = yield* this.filterG(attrNode(a), pre); + if (!pre.size) return pre; + const allPids = new Set(node.attrs.flatMap((a) => a.pids)); + const rows = this.store.linksFrom(pre.toArray(), allPids, true, this.stats); + const valueSets = []; + for (const a of node.attrs) valueSets.push(yield* this.matG(a.values)); + const bySource = new Map(); + for (const r of rows) { + if (r.g === 0) continue; + let m = bySource.get(r.s); + if (!m) bySource.set(r.s, m = new Map()); + let g = m.get(r.g); + if (!g) m.set(r.g, g = []); + g.push(r); + } + const min = node.min ?? 1; + const max = node.max ?? Infinity; + const out = new RoaringBitmap32(); + for (const [s, groups] of bySource) { + let n = 0; + for (const g of groups.values()) { + if (node.attrs.every((a, i) => g.some((r) => a.pids.includes(r.p) && valueSets[i].has(r.t)))) n++; + } + if (n >= min && n <= max) out.add(s); + } + return out; + } + + * _textScan(node, cand) { + const re = wholeTerm(node.re); + const col = node.field === 'code' ? 'code' : 'display'; + const out = new RoaringBitmap32(); + // (a few candidates, e.g. one code's membership, are cheaper to test directly) + if (node.lits && col === 'display' && this.store.hasFts && !(cand && cand.size <= 2000)) { + // trigram prefilter: the concepts whose display contains every required literal, then RE2 + let c = this.store.ftsDisplayIds(ftsQuery(node.lits), this.stats); + if (cand) c = RoaringBitmap32.and(c, cand); + this.spend(c.size, 'text scan (trigram candidates)'); + const ids = c.toArray(); + for (let i = 0; i < ids.length; i += ROW_CHUNK) { + if (i) yield; + for (const r of this.store.conceptRows(ids.slice(i, i + ROW_CHUNK), this.stats).values()) if (r[col] != null && re.test(r[col])) out.add(r.concept_id); + } + return out; + } + this.spend(cand ? cand.size : this.store.conceptCount, 'text scan'); + if (cand) { + const ids = cand.toArray(); + for (let i = 0; i < ids.length; i += ROW_CHUNK) { + if (i) yield; + for (const r of this.store.conceptRows(ids.slice(i, i + ROW_CHUNK), this.stats).values()) if (r[col] != null && re.test(r[col])) out.add(r.concept_id); + } + return out; + } + let n = 0; + // raw rows: no object per row; id ranges, one statement each, a pause between them + for (const [a, b] of idRanges(this.store)) { + for (const [id, v] of this.store.conceptColumn(col, a, b)) { + n++; + if (v != null && re.test(v)) out.add(id); + } + yield; + } + if (this.stats) { this.stats.statements++; this.stats.rows += n; } + return out; + } + + // ---- lazy: first members of driver ∩ filters in id order, stopping at `want` ---------------- + + /** + * Evaluate `driver` (free) narrowed by `filters` (costly) chunk by chunk in id order until + * `want` members are found. Returns { ids: RoaringBitmap32, done, cursor } where cursor is the + * last driver id examined (resume after it). + */ + lazy(driver, filters, want, after = 0) { return runSync(this.lazyG(driver, filters, want, after)); } + + * lazyG(driver, filters, want, after = 0) { + const D = yield* this.matG(driver); + const out = new RoaringBitmap32(); + const it = D.iterator(); + let chunk = []; + let cursor = after; + let done = false; + const self = this; + function* flush() { + if (!chunk.length) return; + let c = new RoaringBitmap32(chunk); + for (const f of filters) { if (!c.size) break; c = yield* self._probe(f, c); } + out.orInPlace(c); + cursor = chunk[chunk.length - 1]; + chunk = []; + yield; + } + if (after > 0) { + // skip to the cursor + for (;;) { + const n = it.next(); + if (n.done) { done = true; break; } + if (n.value > after) { chunk.push(n.value); break; } + } + } + while (!done) { + const n = it.next(); + if (n.done) { done = true; break; } + chunk.push(n.value); + if (chunk.length >= SCAN_CHUNK) { + yield* flush(); + if (out.size >= want) break; + } + } + yield* flush(); + return { ids: out, done, cursor }; + } +} + +/** [lo, hi] id ranges covering the store's concepts, ROW_CHUNK ids each (a long scan in bounded statements) */ +function* idRanges(S) { + for (let a = S.lo; a <= S.hi; a += ROW_CHUNK) yield [a, Math.min(a + ROW_CHUNK - 1, S.hi)]; +} + +/** concepts with attribute a (any of its properties) = a value in a.values; `= *` is hasProp */ +function attrNode(a) { + if (a.values.t !== 'all') return { t: 'propIn', pids: a.pids, values: a.values }; + const items = a.pids.map((pid) => ({ t: 'set', kind: KIND.hasProp, pid, value: 0 })); + return items.length === 1 ? items[0] : { t: 'or', items }; +} + +function descMatches(d, f) { + let r; + switch (f.field) { + case 'term': r = f.matchers.some((m) => m(d.term)); break; + case 'language': r = f.values.includes(String(d.language || 'en').toLowerCase().split('-')[0]); break; + case 'type': case 'typeid': r = !f.uses || (!!d.use && f.uses.includes(d.use.code)); break; + case 'active': r = d.active === f.value; break; + case 'id': r = d.sctid != null && f.ids.includes(String(d.sctid)); break; + case 'dialect': case 'dialectid': { + const acc = (d.acc || '').split(',').filter(Boolean).map((a) => a.split(':').map(Number)); + r = f.dialects.some((dl) => acc.some(([rs, av]) => (!dl.refsets || dl.refsets.includes(rs)) && (!dl.acceptability || dl.acceptability.includes(av)))); + break; + } + default: r = false; + } + return f.neg ? !r : r; +} + +/** + * Regex filters as upstream evaluates them (library/regex-utilities): RE2 (linear time, so a + * request cannot make it backtrack) and found anywhere in the value, not anchored. + */ +/** + * Every regex filter matches the whole value (tx-ecosystem: simple-expand-regex, regex2, + * validation-simple-code-bad-regex, expand-regex-bad(-2), snomed display regex): RE2 find of + * "^(?:P)$". ".*X.*" is tested as find("X") when X has no top-level alternation and the value has + * no line break (where "." would stop), which skips scanning every prefix. + * @returns {{test: function(string): boolean}} + */ +function wholeTerm(src) { + const p = String(src); + const full = compileRe('^(?:' + p + ')$'); + const inner = p.startsWith('.*') && p.endsWith('.*') && p.length >= 4 ? p.slice(2, -2) : null; + if (inner != null && stripAnyAffixes(p) !== p && !/^[?*+{]/.test(inner) && !inner.endsWith('\\')) { + const re = compileRe(stripAnyAffixes(p)); + return { test: (t) => t != null && (String(t).indexOf('\n') < 0 ? re.test(t) : full.test(t)) }; + } + return { test: (t) => t != null && full.test(t) }; +} + +function compileRe(src) { + try { + return regexUtilities.compile(src); + } catch (e) { + throw new Unsupported('bad-regex', src); + } +} + +module.exports = { Evaluator, Unsupported, key, label, compileRe, PROBE_MAX, FREE, runSync, runAsync }; diff --git a/tx/sqlite-v2/engine/regex-literals.js b/tx/sqlite-v2/engine/regex-literals.js new file mode 100644 index 00000000..c61d699b --- /dev/null +++ b/tx/sqlite-v2/engine/regex-literals.js @@ -0,0 +1,151 @@ +'use strict'; + +// Literal substrings that every match of an RE2 pattern must contain (codesearch-style, kept +// deliberately simple and conservative). A substring of 3 or more characters can narrow the +// candidates through the FTS5 trigram index on displays (ix_text_display) before RE2 runs on them. +// +// The extractor is sound when it returns literals: any string the pattern matches contains each of +// them. When it is unsure (alternation at the top level, unusual syntax) it returns []. Case: the +// trigram index is case-insensitive, so the candidate set is a superset either way. + +const BREAK_ESCAPES = new Set('dDwWsSbBpPQEAzZ'.split('')); + +/** @returns {string[]} required literals of at least `min` characters (possibly none) */ +function requiredLiterals(pattern, min = 3) { + const s = String(pattern); + const runs = []; + let cur = ''; + const brk = () => { if (cur.length) runs.push(cur); cur = ''; }; + let i = 0; + let depth = 0; + // a top-level alternation: no literal is required by every branch (as far as we know) + for (let k = 0, d = 0, inClass = false; k < s.length; k++) { + const c = s[k]; + if (c === '\\') { k++; continue; } + if (inClass) { if (c === ']') inClass = false; continue; } + if (c === '[') { inClass = true; if (s[k + 1] === '^') k++; if (s[k + 1] === ']') k++; continue; } + if (c === '(') d++; + else if (c === ')') d--; + else if (c === '|' && d === 0) return []; + } + const quant = (k) => { + // a quantifier at k: returns { optional, end } or null + const c = s[k]; + if (c === '?' || c === '*') return { optional: true, end: k + 1 + (s[k + 1] === '?' ? 1 : 0) }; + if (c === '+') return { optional: false, end: k + 1 + (s[k + 1] === '?' ? 1 : 0) }; + if (c === '{') { + const m = /^\{(\d*)(,\d*)?\}\??/.exec(s.slice(k)); + if (m) return { optional: !m[1] || Number(m[1]) === 0, end: k + m[0].length }; + } + return null; + }; + while (i < s.length) { + const c = s[i]; + if (c === '\\') { + const n = s[i + 1]; + if (n == null || BREAK_ESCAPES.has(n) || /[0-9xu]/.test(n)) { + // a class escape (\d, \w, \p{…}, …): not a literal, nor is its quantifier + brk(); + i += 2; + if ((n === 'p' || n === 'P' || n === 'x') && s[i] === '{') { const e = s.indexOf('}', i); i = e < 0 ? s.length : e + 1; } + const q = quant(i); + if (q) i = q.end; + continue; + } + // an escaped literal (\. \( \\ ...) + const q = quant(i + 2); + if (q) { if (!q.optional) cur += n; brk(); i = q.end; continue; } + cur += n; + i += 2; + continue; + } + if (c === '[') { + // a character class: not a literal + brk(); + let k = i + 1; + if (s[k] === '^') k++; + if (s[k] === ']') k++; + while (k < s.length && s[k] !== ']') { if (s[k] === '\\') k++; k++; } + i = k + 1; + const q = quant(i); + if (q) i = q.end; + continue; + } + if (c === '(') { + // a group (or flags): skip it whole + brk(); + depth = 0; + let k = i; + for (; k < s.length; k++) { + if (s[k] === '\\') { k++; continue; } + if (s[k] === '[') { k++; if (s[k] === '^') k++; if (s[k] === ']') k++; while (k < s.length && s[k] !== ']') { if (s[k] === '\\') k++; k++; } continue; } + if (s[k] === '(') depth++; + else if (s[k] === ')') { depth--; if (depth === 0) break; } + } + i = k + 1; + const q = quant(i); + if (q) i = q.end; + continue; + } + if (c === '.' || c === '^' || c === '$') { + brk(); + i++; + const q = quant(i); + if (q) i = q.end; + continue; + } + if (c === '|' || c === ')') return []; // not expected at the top level (checked above) + const q = quant(i + 1); + if (q) { + if (!q.optional) cur += c; + brk(); + i = q.end; + continue; + } + cur += c; + i++; + } + brk(); + return [...new Set(runs.filter((r) => [...r].length >= min))]; +} + +/** + * The same test with a leading and trailing unanchored ".*" removed. Matching is "find anywhere" + * and ".*" can match the empty string, so find(".*X.*") = find("X"); RE2JS then skips scanning + * every prefix. Kept unchanged when there is a top-level alternation or the affix is escaped or + * quantified. + */ +function stripAnyAffixes(pattern) { + let s = String(pattern); + if (hasTopLevelAlternation(s)) return s; + while (s.startsWith('.*') && !/^\.\*[?*+{]/.test(s)) s = s.slice(2); + while (s.endsWith('.*') && !s.endsWith('\\.*') && !endsEscaped(s, s.length - 2) && s.length > 2) s = s.slice(0, -2); + return s.length ? s : String(pattern); +} + +function endsEscaped(s, pos) { + let n = 0; + for (let k = pos - 1; k >= 0 && s[k] === '\\'; k--) n++; + return n % 2 === 1; +} + +function hasTopLevelAlternation(s) { + for (let k = 0, d = 0, inClass = false; k < s.length; k++) { + const c = s[k]; + if (c === '\\') { k++; continue; } + if (inClass) { if (c === ']') inClass = false; continue; } + if (c === '[') { inClass = true; if (s[k + 1] === '^') k++; if (s[k + 1] === ']') k++; continue; } + if (c === '(') d++; + else if (c === ')') d--; + else if (c === '|' && d === 0) return true; + } + return false; +} + +/** an FTS5 query requiring every literal (each a quoted phrase), or null */ +function ftsQuery(literals) { + if (!literals || !literals.length) return null; + return literals.map((l) => '"' + l.replace(/"/g, '""') + '"').join(' AND '); +} + +module.exports = { requiredLiterals, ftsQuery, stripAnyAffixes }; diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js new file mode 100644 index 00000000..3502f22a --- /dev/null +++ b/tx/sqlite-v2/index.js @@ -0,0 +1,28 @@ +'use strict'; +// sqlite-v2 terminology files: provider registration entry point. +// +// A library source line `snomed-v2:`, `loinc-v2:` or `rxnorm-v2:` loads one file +// (Library.loadSqliteV2). Without such a line nothing here, nor roaring, is loaded. + +const Database = require('better-sqlite3'); +const { SqliteV2Factory } = require('./provider'); +const { SnomedV2Factory } = require('./snomed'); +const { checkFormat } = require('./store'); + +/** a factory for the file, chosen by the grammar it says its codes have */ +async function loadSqliteV2Factory(i18n, file, opts = {}) { + const db = new Database(file, { readonly: true, fileMustExist: true }); + let grammar; + try { + checkFormat(db, file); + grammar = JSON.parse(db.prepare("SELECT value FROM main.meta WHERE key = 'behaviour.grammar'").pluck().get() || 'null'); + } finally { + db.close(); + } + // behaviour.grammar 'snomed': SNOMED CT expressions and ECL (snomed.js) + const factory = grammar === 'snomed' ? new SnomedV2Factory(i18n, file, opts) : new SqliteV2Factory(i18n, file, opts); + await factory.load(); + return factory; +} + +module.exports = { loadSqliteV2Factory }; diff --git a/tx/sqlite-v2/layers.js b/tx/sqlite-v2/layers.js new file mode 100644 index 00000000..07083f8b --- /dev/null +++ b/tx/sqlite-v2/layers.js @@ -0,0 +1,339 @@ +'use strict'; +// CodeSystem supplements as layers. +// +// A supplement (loaded with the server, or supplied per request through tx-resource / +// useSupplement) becomes an in-memory terminology file (the base file's schema, read by the same +// Store). Its concepts carry the BASE concept ids, so its bitmaps (prop, hasProp) combine with the +// base sets by ordinary set algebra: a filter on a supplement-defined property is just another +// IR leaf ({t:'layer'}), evaluated against the layer's store. Supplement codes the base does not +// contain are not imported (upstream treats them as unknown codes) and are counted. +// +// Displays and designations keep upstream's semantics: the base provider class reads them from +// the CodeSystem resource (_displayFromSupplements / _listSupplementDesignations), which is +// already a hash lookup per code. The layer adds what upstream cannot do: supplement property +// filters and text search over supplement designations. +// +// Built layers are kept in one small LRU per process (LayerCache below), bounded by +// settings.supplementLayerCacheMB: a repeat request with the same supplement (server-known, or +// the same tx-resource sent again) reuses the layer instead of rebuilding it. The key is base +// store + url|version + a hash of the supplement's content, so a changed supplement never hits +// an entry built from another. A cached layer is read-only (query_only) and shared by +// concurrent requests; each request holds a reference, so an evicted layer is closed only when +// the last request using it ends. + +const crypto = require('crypto'); +const Database = require('better-sqlite3'); +const { Store, KIND, VK, FORMAT } = require('./store'); +const { serialize, rangeSet, RoaringBitmap32 } = require('../importers/sqlite-v2/sets'); +const { schemaSections } = require('../importers/sqlite-v2/builder'); +const { settings } = require('./settings'); + +let schema = null; +const SCHEMA = () => { + if (!schema) { const d = schemaSections(); schema = d.facts + d.factIndexes + d.ix; } + return schema; +}; +// a supplement property's FHIR type -> the literal type the file records +const LITERAL_TYPE = { code: 'code', string: 'string', integer: 'integer', decimal: 'decimal', boolean: 'boolean', datetime: 'dateTime', dateTime: 'dateTime', Coding: 'Coding' }; + +let layerSeq = 0; + +class Layer { + constructor(store, info) { + this.id = ++layerSeq; + this.store = store; + this.info = info; // { url, version, concepts, unknownCodes, buildMs, properties } + } +} + +/** literal value of a supplement property, as stored (same typing rule as the importers) */ +function propValue(p) { + for (const k of ['valueCode', 'valueString', 'valueInteger', 'valueDecimal', 'valueDateTime']) if (p[k] !== undefined) return [k.substring(5).toLowerCase(), p[k]]; + if (p.valueBoolean !== undefined) return ['boolean', p.valueBoolean ? 1 : 0]; + if (p.valueCoding) return ['code', p.valueCoding.code]; + return [null, null]; +} + +/** + * Write a supplement's layer into an open, empty database: the terminology file schema, its + * concepts under the BASE concept ids, its designations as items (ids above the base's concepts), + * its property values as literals, and their sets (buildLayer: an in-memory database, kept in the + * process's LayerCache). + * @returns {{concepts: object[], unknown: number, props: Map}} + */ +function fillLayer(db, base, json) { + db.exec(SCHEMA()); + const concepts = []; + const walk = (list) => { for (const c of list || []) { concepts.push(c); walk(c.concept); } }; + walk(json.concept); + const ids = base.resolveCodes(concepts.map((c) => c.code)); + let unknown = 0; + const props = new Map(); + const types = new Map(); + const insConcept = db.prepare('INSERT OR IGNORE INTO concept (id, cs_id, code, active, display) VALUES (?, 1, ?, 1, ?)'); + const insUse = db.prepare('INSERT INTO item_use (use_id, system, code, display) VALUES (?, ?, ?, ?)'); + const insItem = db.prepare('INSERT INTO item (id, concept_id, kind, cs_id, language, use_id, text, active, preferred) VALUES (?, ?, 0, 1, ?, ?, ?, 1, 0)'); + const insLit = db.prepare('INSERT OR IGNORE INTO literal (subject_id, property_id, group_id, value, active) VALUES (?, ?, 0, ?, 1)'); + const pending = []; + const tx = db.transaction(() => { + const prop = (code, uri, type) => { + let pid = props.get(code); + if (pid === undefined) { + pid = props.size + 1; + props.set(code, pid); + types.set(pid, { code, uri: uri || null, type: LITERAL_TYPE[type] || 'string' }); + } + return pid; + }; + for (const pd of json.property || []) prop(pd.code, pd.uri, pd.type || 'string'); + const uses = new Map(); + let item = base.conceptCount; + for (const c of concepts) { + const id = ids.get(c.code); + if (id == null) { unknown++; continue; } + insConcept.run(id, c.code, c.display || null); + for (const d of c.designation || []) { + if (d.value == null || d.value === '') continue; + let uid = null; + if (d.use) { + const k = (d.use.system || '') + '|' + d.use.code; + uid = uses.get(k); + if (uid === undefined) { + uid = uses.size + 1; + insUse.run(uid, d.use.system || null, d.use.code, d.use.display || null); + uses.set(k, uid); + } + } + insItem.run(++item, id, d.language || json.language || null, uid, d.value); + } + for (const p of c.property || []) { + const [type, v] = propValue(p); + if (v == null) continue; + const pid = prop(p.code, null, type); + insLit.run(id, pid, v); + pending.push([pid, v, id]); + } + } + // the catalog: literal properties of concepts + const counts = new Map(); + for (const [pid] of pending) counts.set(pid, (counts.get(pid) || 0) + 1); + const insProp = db.prepare(`INSERT INTO property (id, cs_id, code, uri, shape, fhir_type, subject_kind, n_rows) + VALUES (?, 1, ?, ?, 'literal', ?, ?, ?)`); + for (const [pid, t] of types) insProp.run(pid, t.code, t.uri, t.type, counts.get(pid) ? 'concept' : null, counts.get(pid) || 0); + // sets: all / active are the BASE ranges, so layer-side complements mean the same thing + const insSet = db.prepare('INSERT INTO ix_set (kind, property_id, value_kind, value, card, data) VALUES (?, ?, ?, ?, ?, ?)'); + const put = (kind, pid, vk, value, bm) => { if (bm.size) insSet.run(kind, pid, vk, value, bm.size, serialize(bm)); }; + put(KIND.all, 0, VK.none, 0, rangeSet(1, base.conceptCount)); + put(KIND.active, 0, VK.none, 0, rangeSet(1, base.activeCount)); + const groups = new Map(); // pid -> Map(value -> ids) + for (const [pid, v, id] of pending) { + let g = groups.get(pid); + if (!g) groups.set(pid, g = new Map()); + let l = g.get(v); + if (!l) g.set(v, l = []); + l.push(id); + } + for (const [pid, g] of groups) { + const all = []; + for (const [v, l] of g) { + const bm = new RoaringBitmap32(l); + put(KIND.prop, pid, VK.literal, v, bm); + all.push(bm); + } + put(KIND.hasProp, pid, VK.none, 0, RoaringBitmap32.orMany(all)); + } + db.prepare(`INSERT INTO code_system (cs_id, uri, version, name, content, served, concept_count, active_count) VALUES (1, ?, ?, ?, 'supplement', 1, ?, ?)`) + .run(json.url || 'urn:supplement', json.version || '', json.name || null, base.conceptCount, base.activeCount); + db.prepare("INSERT INTO meta (key, value) VALUES ('format', ?)").run(FORMAT); + }); + tx(); + db.pragma('user_version = 1'); + return { concepts, unknown, props }; +} + +/** + * Build a layer for one supplement over a base store. + * @param {Store} base + * @param {object} json CodeSystem (content = supplement) + */ +function buildLayer(base, json) { + const t0 = process.hrtime.bigint(); + const db = new Database(':memory:'); + db.pragma('journal_mode = OFF'); + const { concepts, unknown, props } = fillLayer(db, base, json); + const store = new Store(':memory:', { db, unregistered: true }); + // read-only from here on: a layer may be shared by concurrent requests (LayerCache) + db.pragma('query_only = ON'); + const ms = Number(process.hrtime.bigint() - t0) / 1e6; + const bytes = db.pragma('page_count', { simple: true }) * db.pragma('page_size', { simple: true }); + return new Layer(store, Object.freeze({ url: json.url, version: json.version, concepts: concepts.length - unknown, unknownCodes: unknown, + buildMs: Math.round(ms * 10) / 10, bytes, properties: Object.freeze([...props.keys()]) })); +} + +/** sha-256 of a supplement's content; computed once per resource object (resources are not mutated) */ +const hashes = new WeakMap(); +function contentHash(json) { + let h = hashes.get(json); + if (!h) { + h = crypto.createHash('sha256').update(JSON.stringify(json)).digest('hex'); + hashes.set(json, h); + } + return h; +} + +/** + * The built layers of this process, least recently used first, bounded by + * settings.supplementLayerCacheMB (the layers' SQLite pages: about 120 bytes per concept with + * one designation). Each process of a cluster has its own. + */ +class LayerCache { + constructor() { + this.entries = new Map(); // key -> { key, layer, bytes, users, evicted }; Map order = LRU order + this.bytes = 0; + this.stats = { hits: 0, misses: 0, uncached: 0, evictions: 0 }; + } + + get maxBytes() { return settings.supplementLayerCacheMB * 1048576; } + + /** + * A layer for `key`, built by `build` on a miss. Returns a handle; pass it to release() when + * the request ends. A layer bigger than the whole bound is not kept (handle.entry is null). + */ + acquire(key, build) { + let e = this.entries.get(key); + if (e) { + this.stats.hits++; + this.entries.delete(key); + this.entries.set(key, e); // most recently used + e.users++; + return { layer: e.layer, entry: e }; + } + this.stats.misses++; + const layer = build(); + const bytes = layer.info.bytes; + if (bytes > this.maxBytes) { + this.stats.uncached++; + return { layer, entry: null }; + } + e = { key, layer, bytes, users: 1, evicted: false }; + this.entries.set(key, e); + this.bytes += bytes; + for (const [k, old] of this.entries) { + if (this.bytes <= this.maxBytes) break; + this._evict(k, old); + } + return { layer, entry: e }; + } + + release(handle) { + const e = handle.entry; + if (!e) { handle.layer.store.close(); return; } + e.users--; + if (e.evicted && e.users === 0) e.layer.store.close(); + } + + _evict(key, e) { + this.entries.delete(key); + this.bytes -= e.bytes; + this.stats.evictions++; + e.evicted = true; + if (e.users === 0) e.layer.store.close(); + } + + /** drop every unused entry (tests; and a lowered bound) */ + clear() { + for (const [k, e] of this.entries) this._evict(k, e); + } +} + +const layerCache = new LayerCache(); + +/** the layers that apply to one request: built on first use (a filter or search that needs one) */ +class LayerSet { + /** + * @param {Array<{json, build}>} entries the request's supplements; a layer is built only when + * a filter names a property that supplement defines, and closed when the request ends + */ + constructor(entries) { + this.entries = entries; + this.built = []; + this.closed = false; + } + + get size() { return this.entries.length; } + + /** IR for a filter on a property only a supplement defines, or null */ + filterNode(compiler, prop, op, value) { + for (const e of this.entries) { + // a disk-backed supplement's layer is open already: its file says which properties it has + if (e.layer ? !e.layer.store.props.has(prop) : !definesProperty(e.json, prop)) continue; + if (!e.layer) { + if (this.closed) { + // the request has ended (closeProviders ran: the client went, or the batch entry is + // done): a layer built now would never be closed + const error = new Error('supplement layer requested after the request ended'); + error.abandoned = true; + throw error; + } + const h = e.build(); + e.layer = h.layer; + this.built.push(h); + } + const l = e.layer; + const def = l.store.props.get(prop); + if (!def) continue; + const { Compiler } = require('./engine/compile'); + const node = new Compiler({ store: l.store, dialect: {} }, { stats: compiler.stats }).propertyFilter(def, op, value); + return { t: 'layer', layer: l, node, label: `supplement ${l.info.url} ${prop} ${op} ${value}` }; + } + return null; + } + + /** release the layers this request used (an uncached one is closed; a cached one is kept) */ + close() { + this.closed = true; + for (const h of this.built) layerCache.release(h); + this.built = []; + } +} + +/** does the supplement define (or use) this property? (no layer needed to answer) */ +function definesProperty(json, prop) { + if ((json.property || []).some((p) => p.code === prop)) return true; + const walk = (list) => (list || []).some((c) => (c.property || []).some((p) => p.code === prop) || walk(c.concept)); + return walk(json.concept); +} + +class SupplementLayers { + constructor(base) { + this.base = base; + } + + /** + * The layers for one request. A layer is built only when a filter needs it, and is then + * kept in the process's LayerCache for later requests with the same supplement content. + */ + forSupplements(supplements) { + const layers = []; + for (const s of supplements || []) { + const json = s.jsonObj || s; + if (!(json.concept && json.concept.length)) continue; + layers.push({ json, build: () => layerCache.acquire(this.keyOf(json, s), () => buildLayer(this.base, json)) }); + } + return new LayerSet(layers); + } + + /** + * cache key: the base store, the supplement's url|version, and a hash of its content. A + * wrapper's hash is the one it remembers for the expansion cache key + * (CanonicalResource.expansionKeyHash: the first 16 hex characters of the sha256 of the same + * JSON), which the expansion cache key has usually just computed, so a tx-resource supplement + * is serialised and hashed once per request; a plain resource's is the full sha256. + */ + keyOf(json, s) { + const h = s && s.jsonObj === json && typeof s.expansionKeyHash === 'function' ? 'k' + s.expansionKeyHash() : contentHash(json); + return this.base.uid + '|' + (json.url || '') + '|' + (json.version || '') + '|' + h; + } +} + +module.exports = { SupplementLayers, LayerSet, LayerCache, layerCache, buildLayer, fillLayer, Layer, contentHash }; diff --git a/tx/sqlite-v2/orders.js b/tx/sqlite-v2/orders.js new file mode 100644 index 00000000..ed3e8b53 --- /dev/null +++ b/tx/sqlite-v2/orders.js @@ -0,0 +1,235 @@ +'use strict'; +// The built-in providers' answer orders for LOINC, SNOMED CT and RxNorm, as typed arrays over concept ids: +// rank[id] the concept's place in the system order (rank.length = concept count + 1) +// ids[r] the concept at place r +// walk the whole system in the built-in walk order (SNOMED CT: walk.reached is how many +// the walk reaches; RxNorm: none) +// +// Stored in the file's ix_order table as little-endian Uint32 arrays in 1,024-entry blocks, the +// array's `reached` in meta 'ix.ix_order..reached'. The index builder computes them from the +// fact tables (computeOrder: SNOMED CT and RxNorm by code); an importer may write them itself (meta +// derived-by-importer: LOINC's orders are the built-in importer's numbering, SNOMED CT's walk). A +// provider reads each array the first time an answer needs it (storedOrder): no row objects, 4 +// bytes per concept per array, and nothing for an array no request uses. + +const os = require('os'); + +const LITTLE = os.endianness() === 'LE'; + +/** the order kind of a code system (by its dialect name), or null for a system without one */ +function orderKind(dialectName) { + return dialectName === 'loinc' || dialectName === 'snomed' || dialectName === 'rxnorm' ? dialectName : null; +} + +/** text order of codes (SQLite BINARY for BMP text) */ +function byText(a, b) { return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0; } + +/** numeric order of digit strings without leading zeros: by length, then as text */ +function byNumber(a, b) { return (a[1].length - b[1].length) || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0); } + +/** rank / ids arrays from [id, code] rows sorted by cmp */ +function rankBy(n, rows, cmp) { + rows.sort(cmp); + const rank = new Uint32Array(n + 1); + const ids = new Uint32Array(n + 1); + rows.forEach((r, i) => { rank[r[0]] = i; ids[i] = r[0]; }); + return { rank, ids }; +} + +/** + * The walk (snomedWalk) from its facts, whatever the file format: pairs [parent, child] of the + * active group-0 is-a links by parent, in release order; the concepts with any is-a link (a + * root has none, active or not: cs-snomed's import, activeRoots); the active concepts + */ +function walkFrom(n, byCode, pairs, withParent, activeIds) { + const start = new Uint32Array(n + 2); + for (const [t] of pairs) start[t + 1]++; + for (let i = 1; i <= n + 1; i++) start[i] += start[i - 1]; + const kids = new Uint32Array(pairs.length); + const fill = start.slice(); + for (const [t, c] of pairs) kids[fill[t]++] = c; + const hasParent = new Uint8Array(n + 1); + for (const c of withParent) hasParent[c] = 1; + const isActive = new Uint8Array(n + 1); + for (const id of activeIds) isActive[id] = 1; + const out = new Uint32Array(n); + const seen = new Uint8Array(n + 1); + let k = 0; + const stack = []; + for (let r = 0; r < n; r++) { + const id = byCode[r]; + if (!isActive[id] || hasParent[id]) continue; // an active root, in id order + stack.push(id); + while (stack.length) { + const c = stack.pop(); + if (seen[c]) continue; + seen[c] = 1; out[k++] = c; + for (let j = start[c + 1] - 1; j >= start[c]; j--) if (!seen[kids[j]]) stack.push(kids[j]); + } + } + const reached = k; + for (let r = 0; r < n; r++) if (!seen[byCode[r]]) out[k++] = byCode[r]; + out.reached = reached; + return out; +} + +function fromBlob(b) { + const len = b.length >>> 2; + if (LITTLE && b.byteOffset % 4 === 0) return new Uint32Array(b.buffer, b.byteOffset, len); + const a = new Uint32Array(len); + for (let i = 0; i < len; i++) a[i] = b.readUInt32LE(i * 4); + return a; +} + +/** + * The lazy order object over stored arrays: meta name -> [name, length, reached], read(name) -> + * the array's bytes (whatever the file format keeps them in) + */ +function orderOf(store, kind, meta, readBytes) { + for (const k of ['rank', 'ids']) { + if (!meta.has(k) || meta.get(k)[1] !== store.conceptCount + 1) throw new Error(`${store.file}: ix_order ${k} does not match concept_count`); + } + const read = (name) => { + const t0 = Date.now(); + const buf = store.withoutMmap(() => readBytes(name)); + const a = fromBlob(buf); + const r = meta.get(name)[2]; + if (r != null) a.reached = r; + order.readMs += Date.now() - t0; + return a; + }; + let rank = null, ids = null, walk; + const order = { + kind, + // behaviour.expansionOrder 'stored-self-first': an is-a / << filter lists its concept first + selfFirst: kind === 'stored-self-first', + hasWalk: meta.has('walk'), + stored: true, + readMs: 0, + get rank() { return rank || (rank = read('rank')); }, + get ids() { return ids || (ids = read('ids')); }, + get walk() { if (walk === undefined) walk = meta.has('walk') ? read('walk') : null; return walk; }, + /** bytes of the arrays read so far */ + loadedBytes() { return (rank ? rank.byteLength : 0) + (ids ? ids.byteLength : 0) + (walk ? walk.byteLength : 0); }, + }; + return order; +} + +const readArray = (store, name) => Buffer.concat(store.stmt('SELECT data FROM main.ix_order WHERE name = ? ORDER BY block').pluck().all(name)); + +/** the stored rank / ids / walk arrays, read on first use */ +function storedOrder(store, kind) { + // each array's length from its block count and its last block (no other block's data is read at open) + const meta = new Map(store.db.prepare(`SELECT g.name, g.last * 1024 + (SELECT length(l.data) / 4 FROM main.ix_order l WHERE l.name = g.name AND l.block = g.last), + (SELECT CAST(value AS INTEGER) FROM main.meta WHERE key = 'ix.ix_order.' || g.name || '.reached') + FROM (SELECT name, max(block) AS last FROM main.ix_order GROUP BY name) g`).raw().all().map((r) => [r[0], r])); + return orderOf(store, kind, meta, (name) => readArray(store, name)); +} + +/** + * A concept's parent and child entries in the built-in provider's order (LOINC): the stored + * hier_start / hier arrays where the importer kept them; else from the facts, the concept's parent + * links (by subject) and its children's (ix_in, by target) merged by seq (the hierarchy-file row of + * the pair). Null for a file whose hierarchy is not read by target. + */ +function hierarchyOrder(store) { + const names = new Set(store.db.prepare("SELECT DISTINCT name FROM main.ix_order WHERE name IN ('hier_start', 'hier')").pluck().all()); + if (names.size === 2) { + let start = null, entries = null; + const read = (name) => fromBlob(store.withoutMmap(() => readArray(store, name))); + return { + of(id) { + if (!start) { + start = read('hier_start'); entries = read('hier'); + if (start.length !== store.conceptCount + 2) throw new Error(`${store.file}: ix_order hier_start does not match concept_count`); + } + return entries.subarray(start[id], start[id + 1]); + }, + loadedBytes() { return start ? start.byteLength + entries.byteLength : 0; }, + }; + } + const h = store.hierarchy; + if (!h || !h.byTarget) return null; + const up = store.stmt('SELECT target_id, seq FROM main.link WHERE subject_id = +? AND property_id = +? AND active = 1').raw(); + const down = store.stmt('SELECT subject_id, seq FROM main.ix_in WHERE target_id = +? AND property_id = +? AND active = 1 AND group_id = 0').raw(); + return { + of(id) { + const e = []; + for (const [t, seq] of up.all(id, h.id)) e.push([seq ?? 0, t >>> 0]); + for (const [c, seq] of down.all(id, h.id)) e.push([seq, (c | HIER_CHILD) >>> 0]); + e.sort((a, b) => a[0] - b[0]); + return Uint32Array.from(e.map((x) => x[1])); + }, + loadedBytes() { return 0; }, + }; +} + +/** + * The order arrays from the fact tables, for the index builder: kind 'snomed' (by concept id as + * a number, as cs-snomed.js lists results; the walk from the is-a links in source order: for is-a + * and ECL << the concept itself first, selfFirst), 'rxnorm' (by RXCUI as text, '10' before '9': + * cs-rxnorm.js groups by a text column). LOINC's order is the upstream importer's numbering, + * which only its importer can compute (derived-by-importer). + * @param {object} db a connection to the file + * @param {object} [opts] { walk: false to leave the SNOMED walk out } + */ +function computeOrder(db, kind, n, opts = {}) { + const rows = db.prepare('SELECT id, code FROM main.concept WHERE cs_id = (SELECT cs_id FROM main.code_system WHERE served = 1)').raw().all(); + if (kind === 'rxnorm') return { ...rankBy(n, rows, byText), walk: null, selfFirst: false }; + if (kind !== 'snomed') throw new Error(`no system order computable from the facts for ${kind}`); + const { rank, ids } = rankBy(n, rows, byNumber); + return { rank, ids, walk: opts.walk === false ? null : snomedWalk(db, n, ids), selfFirst: true }; +} + +/** + * The whole code system in cs-snomed.js's walk order (iterator + includeCodeAndDescendants): from + * each active root (no active parent; by id), depth first, the children in release order (inbound + * active is-a links by seq), each concept once, where first reached. Concepts the walk does not + * reach (the inactive ones: they have no active is-a row) follow, by id: walk.reached is how many + * it reaches. cs-snomed.js's expansion of the whole system has only those; other selections of + * every concept (ECL *) have them all. + */ +function snomedWalk(db, n, byCode) { + const hid = db.prepare('SELECT id FROM main.property WHERE subsumption = 1 ORDER BY id LIMIT 1').pluck().get(); + return walkFrom(n, byCode, + db.prepare('SELECT target_id, subject_id FROM main.ix_in WHERE target_id <= ? AND property_id = ? AND active = 1 AND group_id = 0 AND subject_id <= ? ORDER BY target_id, seq').raw().all(n, hid, n), + db.prepare('SELECT DISTINCT subject_id FROM main.link WHERE property_id = ? AND subject_id <= ? AND target_id <= ?').pluck().iterate(hid, n, n), + db.prepare('SELECT id FROM main.concept WHERE active = 1 AND id <= ?').pluck().iterate(n)); +} + +// ---- LOINC hierarchy order ----------------------------------------------------------------- +// +// cs-loinc.js lists a code's parent and child relationships in its Relationships rows' order +// (the $lookup query has no ORDER BY; SQLite reads the SourceKey index, so by RelationshipKey). +// The built-in importer inserts them from ComponentHierarchyBySystem.csv, one row at a time: for +// a row (code under parent) the code's parent row, then the parent's child row, each pair once, +// and only when the parent already has a CodeKey. So a part's children come in hierarchy-file +// order, and a part on two paths has its second parent among its children. +// +// Where the parent links' seq (the hierarchy-file row of each pair) does not give that order, the +// importer stores two ix_order arrays: hier_start (concept count + 2 offsets, by concept id) and +// hier, each concept's entries in that order: the other concept's id, with HIER_CHILD set for a +// child. Read on the first $lookup that needs it (store.hierarchyOrderOf). + +const HIER_CHILD = 0x80000000; + +/** + * The two arrays from a concept's entries in order (stable: entries of one concept keep the + * order they were given in). + * @param {number} n concept count + * @param {ArrayLike} xs concept id of each entry + * @param {ArrayLike} others the related concept id of each entry + * @param {ArrayLike} isChild 1 where the related concept is a child, else 0 (a parent) + */ +function hierarchyArrays(n, xs, others, isChild) { + const start = new Uint32Array(n + 2); + for (let k = 0; k < xs.length; k++) start[xs[k] + 1]++; + for (let i = 1; i < start.length; i++) start[i] += start[i - 1]; + const entries = new Uint32Array(xs.length); + const fill = start.slice(); + for (let k = 0; k < xs.length; k++) entries[fill[xs[k]]++] = (others[k] | (isChild[k] ? HIER_CHILD : 0)) >>> 0; + return { start, entries }; +} + +module.exports = { orderKind, rankBy, byText, byNumber, walkFrom, fromBlob, orderOf, storedOrder, hierarchyOrder, computeOrder, snomedWalk, + HIER_CHILD, hierarchyArrays }; diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js new file mode 100644 index 00000000..36d2e83f --- /dev/null +++ b/tx/sqlite-v2/provider.js @@ -0,0 +1,1488 @@ +'use strict'; +const { TxParameters } = require('../params'); +// Generic CodeSystemProvider over one sqlite-v2 file (LOINC, RxNorm, and the base of SNOMED CT; +// see snomed.js for the SNOMED layer). +// +// Membership questions (filters, validate-code, subsumes) are answered by the engine over the +// stored bitmaps; SQL is used for facts only (rows of a page, designations, properties). Rows are +// fetched in batches: a page of an expansion is one statement per table. +// +// handlesSelecting()/processSelection() hand whole single-system composes to the engine. +// Anything the engine does not support returns null, and expand.js then takes its usual path, +// which reaches this provider through the filter API (itself engine-backed). + +const { Issue } = require('../library/operation-outcome'); +const { CodeSystemFactoryProvider, CodeSystemProvider } = require('../cs/cs-api'); +const { BaseCSServices } = require('../cs/cs-base'); +const { CodeSystem } = require('../library/codesystem'); +const { Language } = require('../../library/languages'); +const { openStore, KIND } = require('./store'); +const { Engine } = require('./engine/engine'); +const { Compiler, FilterError } = require('./engine/compile'); +const { dialectFor, LOINC, RXNORM } = require('./dialects'); +const { SupplementLayers } = require('./layers'); +const { HIER_CHILD } = require('./orders'); +const { RoaringBitmap32 } = require('roaring'); +const { sctTextSearchG, sctTextLanguages, rxTextSearchG, loincTextSearchG, genericTextSearchG, rxSearchable } = require('./text-index'); +const { runAsync: runPausing } = require('./engine/evaluate'); +const { SupplementTextIndex } = require('../library/supplement-text-index'); +const { languageByte, languageCode, languageBytesFor } = require('../sct/languages'); + +const CHUNK = 500; // rows fetched per statement while iterating a filter set +const PAGE_ROWS = 2000; // a processSelection page's rows read per statement, with a pause between + +/** a concept handle: id (concept_id), code; row/designations filled lazily or by a page batch */ +class V2Concept { + constructor(id, code, row = null) { + this.id = id; + this.code = code; + this.row = row; + this.desigs = null; + this.peers = null; // the chunk whose designations are read together (_loadChunk) + this.status = undefined; // LOINC STATUS, when read with the row (undefined = not read) + } +} + +/** a filter set: a bitmap (or a page of ids) iterated with batched row fetches */ +class V2FilterSet { + constructor(bm, opts = {}) { + this.bm = bm; // RoaringBitmap32 or null (membership by probing `node`) + this.node = opts.node || null; + this.ids = opts.ids || null; // explicit page (processSelection) + this.total = opts.total; + this.pos = -1; + this.buf = []; + this.bufStart = 0; + this.current = null; + this.expressionsFalse = !!opts.expressionsFalse; + } + get size() { return this.ids ? this.ids.length : (this.bm ? this.bm.size : 0); } +} + +class V2Prep { + constructor(iterate, languages = null) { + this.forIterate = iterate; + this.languages = languages; // what the request asked for (a text filter searches one language) + this.filters = []; + this.nodes = []; + this.specs = []; // the filters as given (prop, op, value), for providers that hand some requests on + this.expressionsFalse = false; + } +} + +class SqliteV2Provider extends BaseCSServices { + /** + * @param {OperationContext} opContext + * @param {CodeSystem[]} supplements + * @param {SqliteV2Factory} factory + */ + constructor(opContext, supplements, factory) { + super(opContext, supplements); + this.f = factory; + this.store = factory.store; + this.engine = factory.engine; + this.dialect = factory.dialect; + this.concepts = new Map(); // id -> V2Concept handle, for this request (the provider is per request) + this.byCode = new Map(); // normalised code -> V2Concept (or null: not in this file) located by this request + this.layers = factory.layers.forSupplements(supplements || []); + // the request's trace (OperationContext.tracer: a tracer a request may carry), or null: store + // reads count into it + this._trace = opContext.tracer || null; + } + + // ---- metadata --------------------------------------------------------------------------- + + system() { return this.store.system; } + version() { return this.store.version; } + name() { return this.f.name(); } + description() { return this.f.description(); } + lookupName() { return this.f.lookupName(); } + defLang() { return this.f.defLang(); } + totalCount() { return this.f.totalCount(); } + /** + * expand.js asks this for count=0 of a whole code system. cs-snomed.js counts the active concepts + * for a compose without inactive codes; cs-loinc.js and cs-rxnorm.js don't override cs-api's + * default, which ignores the flag (totalCount) + */ + async countAllCodes(excludeInactive) { + if (this.dialect.name === 'loinc' || this.dialect.name === 'rxnorm') return this.totalCount(); + return excludeInactive ? this.store.active().size : this.totalCount(); + } + hasParents() { return !!this.store.hierarchy || this.dialect.name === 'rxnorm'; } + isNotClosed() { return !!this.store.notClosed; } + contentMode() { return this.store.cs.content || 'complete'; } + versionAlgorithm() { return this.f.versionAlgorithm(); } + isCaseSensitive() { return this.store.caseSensitive; } + sourcePackage() { return null; } + + /** + * cs-api _supplementSearchCodes (main since #398): the codes a supplement in use gives a name in + * the search language that has every word of the filter, but those whose matching names only + * repeat the code's own display (_rootDisplay); `sources` gets the supplement each came from (for + * used-supplement), each searched with main's SupplementTextIndex + */ + async _supplementSearchCodes(filter, searchLang, sources = null) { + const codes = new Set(); + for (const s of this.supplements || []) { + const matches = await SupplementTextIndex.of(s, this.defLang()).searchTexts(filter, searchLang); + // the codes' own displays, read together (a language pack's copies of the English names + // can match thousands of codes) + const roots = this._rootDisplays([...matches.keys()].filter((c) => !codes.has(c))); + for (const [code, texts] of matches) { + if (codes.has(code)) continue; + const root = roots.get(code); + if (root && texts.every((t) => CodeSystemProvider.sameText(t, root))) continue; + codes.add(code); + if (sources) sources.set(code, s.vurl); + } + } + return codes; + } + + /** _rootDisplay of many codes: Map code -> display (those with one) */ + _rootDisplays(codes) { + const out = new Map(); + if (!codes.length || (this.dialect.name !== 'snomed' && this.dialect.name !== 'loinc')) return out; + const norm = codes.map((c) => this.normaliseCode(c)); + const ids = this.store.resolveCodes(norm, this._stats()); + const rows = this.store.conceptRows([...new Set(ids.values())], this._stats()); + codes.forEach((c, i) => { + const id = ids.get(norm[i]); + const row = id != null ? rows.get(id) : null; + if (row && row.display) out.set(c, row.display); + }); + return out; + } + + /** the code's own display in the file (cs-api _rootDisplay): SNOMED CT's preferred term, LOINC's display */ + async _rootDisplay(code) { + if (this.dialect.name !== 'snomed' && this.dialect.name !== 'loinc') return null; + const id = this.store.idOf(this.normaliseCode(code), this._stats()); + if (id == null) return null; + const row = this.store.conceptRows([id], this._stats()).get(id); + return (row && row.display) || null; + } + + hasAnyDisplays(languages) { + const langs = this._ensureLanguages(languages); + if (this._hasAnySupplementDisplays(langs)) return true; + for (const requested of langs.languages) { + for (const l of this.f.languages()) { + if (new Language(l).matchesForDisplay(requested)) return true; + } + } + return super.hasAnyDisplays(langs); + } + + // ---- concepts --------------------------------------------------------------------------- + + _concept(id, row) { + let c = this.concepts.get(id); + if (!c) { + c = new V2Concept(id, row ? row.code : null, row || null); + this.concepts.set(id, c); + } else if (row && !c.row) { + c.row = row; + c.code = row.code; + } + return c; + } + + /** make sure the page's rows (and designations) are loaded, in one statement per table */ + _loadRows(concepts, withDesignations = true) { + const need = concepts.filter((c) => !c.row).map((c) => c.id); + const st = this._stats(); + if (need.length) { + const rows = this.store.conceptRows(need, st); + for (const c of concepts) if (!c.row) { c.row = rows.get(c.id); c.code = c.row ? c.row.code : c.code; } + } + // LOINC STATUS with the rows: getStatus() is asked for every code of an expansion + const sp = this.dialect.name === 'loinc' ? this.store.props.get('STATUS') : null; + if (sp) { + const ns = concepts.filter((c) => c.status === undefined && c.row).map((c) => c.id); + if (ns.length) { + const vals = this.store.literalValues(ns, sp.id, st); + for (const c of concepts) if (c.status === undefined && c.row) c.status = vals.has(c.id) ? vals.get(c.id) : null; + } + } + if (withDesignations) { + const nd = concepts.filter((c) => !c.desigs).map((c) => c.id); + if (nd.length) { + // LOINC: RELATEDNAMES2 is never a designation or a display (only a $lookup property): not read here + const skip = this._relatedUse(); + const d = this.store.designationRows(nd, st, skip != null ? { skipUse: skip } : {}); + for (const c of concepts) if (!c.desigs) { c.desigs = d.get(c.id) || []; if (skip != null) c.desigsNoRelated = true; } + } + } + } + + /** + * An iterated chunk's rows now, its designations when one of them first needs them (_needDesigs), + * in one statement for the chunk's others still without them. An import expanded for its codes + * only (expand.js deferDetails) never reads most of its designations: an imported SNOMED CT + * value set of 100,000s of codes held them all in this request's working set until it ended. + */ + _loadChunk(concepts) { + this._loadRows(concepts, false); + const peers = concepts.filter((c) => !c.desigs && !c.displayOnly); + for (const c of peers) c.peers = peers; + } + + /** a concept's designations, read with its chunk's (see _loadChunk) */ + _needDesigs(c) { + if (c.desigs) return; + const peers = c.peers; + if (!peers) { + this._loadRows([c], true); + return; + } + this._loadRows(peers.filter((p) => !p.desigs), true); + for (const p of peers) p.peers = null; + } + + _stats() { return this._trace ? this._trace.stats : null; } + + /** + * The request's cooperative yield for engine evaluations (opContext.checkAndYield: it gives the + * event loop a turn after each 10 ms of compute, and stops at the request's deadline or when the + * client has gone, as the built-in providers' loops do), or null outside a request + */ + _pause() { + const oc = this.opContext; + if (!oc || typeof oc.checkAndYield !== 'function') return null; + return () => oc.checkAndYield('sqlite-v2'); + } + + /** LOINC's RELATEDNAMES2 use_id when designation reads leave it out (else null) */ + _relatedUse() { + if (this.dialect.name !== 'loinc') return null; + if (this.f._relatedUseId === undefined) { + this.f._relatedUseId = null; + for (const [id, u] of this.store.uses) if (u.code === 'RELATEDNAMES2') this.f._relatedUseId = id; + } + return this.f._relatedUseId; + } + + async _ensure(context) { + if (context == null) return null; + if (context instanceof V2Concept) { + if (!context.row) this._loadRows([context], false); + return context; + } + if (typeof context === 'string') { + const r = await this.locate(context); + if (!r.context) throw new Error(r.message || `Unknown code ${context}`); + return r.context; + } + throw new Error('Invalid context for ' + this.name()); + } + + async locate(code, prefetched = null) { + if (!this._trace) return this._locate(code, prefetched); + return this._trace.spanAsync('locate code', 'sql', this.system(), () => this._locate(code, prefetched)); + } + + async _locate(code, prefetched = null) { + if (code == null || code === '') return { context: null, message: 'Empty code' }; + const n = this.normaliseCode(code); + // a prefetchCodes handle read from this file answers for the codes it holds, without a + // statement: this provider's, or, in a $batch-validate-code, the batch's (cs-api.md, Batches) + const ids = prefetched && prefetched.store === this.store && prefetched.ids ? prefetched.ids : null; + let c; + if (ids && ids.has(n)) { + const id = ids.get(n); + c = id == null ? null : this._fromHandle(prefetched, id); + } else { + // a code this request already located is not looked up again; otherwise the code and its + // row in one statement + c = this.byCode.get(n); + if (c === undefined) { + const row = this.store.rowForCode(n, this._stats()); + c = row ? this._concept(row.concept_id, row) : (this.store.hasCodeIdentifiers ? this._locateIdentifier(n) : null); + this.byCode.set(n, c); + } + } + if (!c) return { context: null, message: undefined }; + if (!c.row) this._loadRows([c], false); + return { context: c, message: null }; + } + + normaliseCode(code) { return String(code); } + + /** + * A code that is no concept code but an identifier the file accepts as a code (identifier + * resolves > 0; a concept code always wins): 1, an alias, is answered with the concept's own + * code; 2, a code in its own right, as written (the concept's row and designations otherwise). + */ + _locateIdentifier(n) { + const hit = this.store.identifierAsCode(n, this._stats()); + if (!hit) return null; + const c = this._concept(hit.concept_id, hit); + if (hit.resolves !== 2) return c; + const own = new V2Concept(c.id, n, { ...hit, code: n }); + return own; + } + + /** a listed code that locate() finds as written, so processSelection can resolve it by code */ + _plainListedCode(code) { return typeof code === 'string' && code !== '' && this.normaliseCode(code) === code; } + + /** + * This provider's concept for an id a prefetchCodes handle holds. The handle may be another + * provider's of this file (a $batch-validate-code's, read before its entries ran): what it read + * is taken into this provider's working set. + */ + _fromHandle(handle, id) { + const got = handle.concepts && handle.concepts.get(id); + const c = this._concept(id, got ? got.row : null); + if (got && got !== c) { + if (!c.desigs && got.desigs) { c.desigs = got.desigs; c.desigsNoRelated = got.desigsNoRelated; } + if (!c.desigs && got.displayOnly) c.displayOnly = true; + if (c.status === undefined) c.status = got.status; + } + return c; + } + + /** + * cs-api: the worker is about to locate these listed codes one by one. Resolve them and read + * their rows in one statement (and designations, and LOINC STATUS, in one more each), and return the handle the worker passes + * back to locate(): { store, ids, concepts }, ids a map of normalised code -> id (or null), + * concepts what was read, by id. Nothing about the list is kept on the provider; two lists in + * progress have two handles. The handle holds what it read, and is told by its file (store), so + * another provider of the file can use it: a $batch-validate-code reads its codes once, before + * its entries run, and each entry has its own provider (cs-api.md, Batches). (The concepts read + * are in this request's working set, this.concepts, as any concept the request reads.) + * hints.displayOnly: the response shows each code's display only (expand.js, the rule + * processSelection applies itself), so the designation rows aren't read; designations() + * reports the display. + */ + async prefetchCodes(codes, withDesignations = true, hints = {}) { + const norm = []; + for (const c of codes || []) { + if (c == null || c === '') continue; + norm.push(this.normaliseCode(c)); + } + if (!norm.length) return null; + const ids = new Map(); + const read = new Map(); + const run = () => { + const concepts = []; + // codes and their rows in one statement + const uniq = [...new Set(norm)]; + const rows = this.store.rowsForCodes(uniq, this._stats()); + for (const n of uniq) { + const r = rows.get(n); + ids.set(n, r ? r.concept_id : null); + if (r) concepts.push(this._concept(r.concept_id, r)); + } + for (const c of concepts) read.set(c.id, c); + const displayOnly = !!(hints && hints.displayOnly); + if (displayOnly) for (const c of concepts) if (!c.desigs) c.displayOnly = true; + this._loadRows(concepts, withDesignations && !displayOnly); + }; + if (this._trace) this._trace.span('prefetch enumerated codes (' + norm.length + ')', 'rows', this.system(), run); + else run(); + return { store: this.store, ids, concepts: read }; + } + + async code(context) { + const c = await this._ensure(context); + return c ? c.code : null; + } + + async display(context) { + const c = await this._ensure(context); + if (!c) return null; + const s = this._displayFromSupplements(c.code); + if (s) return s; + if (this.dialect.name === 'loinc' && this.opContext.langs && !this.opContext.langs.isEnglishOrNothing()) { + this._needDesigs(c); + const types = ['LONG_COMMON_NAME', 'SHORTNAME', 'DisplayName']; + const cands = [{ language: 'en-US', term: c.row.display }] + .concat(c.desigs.filter((d) => d.use && types.includes(d.use.code)).sort((a, b) => types.indexOf(a.use.code) - types.indexOf(b.use.code))); + const langs = this.opContext.langs.languages || []; + for (const exact of [true, false]) { + for (const l of langs) for (const d of cands) if (l.matches(d.language, exact)) return d.term; + } + } + return (c.row && c.row.display) || ''; + } + + async definition(context) { + const c = await this._ensure(context); + return c && c.row ? c.row.definition || null : null; + } + + async isAbstract() { return false; } + + async isInactive(context) { + const c = await this._ensure(context); + return c ? !c.row.active : false; + } + + async isDeprecated(context) { + const c = await this._ensure(context); + if (this.dialect.name === 'rxnorm') return this._rxArchived(c); + return false; + } + + /** RxNorm: the concepts in RXNCONSO (active or obsolete), not the archived ones */ + _rxLive() { + const p = this.store.props.get('SUPPRESS'); + return p ? this.store.getSet(KIND.hasProp, p.id, 0, this._stats()) : this.store.active(); + } + + /** RxNorm: inactive because archived (RXNATOMARCHIVE only), not obsolete (SUPPRESS = O) */ + _rxArchived(c) { return !c.row.active && !this._rxLive().has(c.id); } + + async getStatus(context) { + const c = await this._ensure(context); + if (!c) return null; + if (this.dialect.name === 'loinc') { + if (c.status !== undefined) return c.status; + const p = this.store.props.get('STATUS'); + if (!p) return null; + const v = this.store.literalValues([c.id], p.id, this._stats()).get(c.id); + return v === undefined ? null : v; + } + if (this.dialect.name === 'rxnorm') return c.row.active ? null : (this._rxArchived(c) ? 'archived' : 'obsolete'); + return c.row.active ? 'active' : 'inactive'; + } + + async parent() { return null; } + + isDisplay(d) { + if (this.dialect.name === 'loinc') return !!(d.use && ['SHORTNAME', 'LONG_COMMON_NAME', 'LinguisticVariantDisplayName'].includes(d.use.code)); + return false; + } + + async designations(context, displays, significantOnly) { + // one step only when it reads rows (an expansion page has them already) + const c = context instanceof V2Concept ? context : null; + if (!this._trace || (c && (c.desigs || c.displayOnly))) return this._designations(context, displays, significantOnly); + return this._trace.spanAsync('designations', 'rows', this.system(), () => this._designations(context, displays, significantOnly)); + } + + async _designations(context, displays) { + const c = await this._ensure(context); + if (!c) return; + if (!c.desigs && c.displayOnly) { + // a page whose response shows displays only (see processSelection) + this._displayOnly(c, displays); + return; + } + this._needDesigs(c); + if (this.dialect.name === 'loinc') { + displays.addDesignation(true, 'active', 'en-US', CodeSystem.makeUseForDisplay(), (c.row.display || '').trim()); + for (const d of sortLoinc(c.desigs)) { + if (d.use && d.use.code === 'RELATEDNAMES2') continue; + displays.addDesignation(false, 'active', d.language, d.use ? { system: d.use.system, code: d.use.code, display: d.use.display } : null, d.term.trim()); + } + } else if (this.dialect.name === 'rxnorm') { + // upstream: the display is the first non-SY atom; every other atom is a designation (with no + // use where the file says so: behaviour.designationUses) + const use = (d) => (this.store.behaviour.designationUses === 'drop' || !d.use ? null : { system: d.use.system, code: d.use.code, display: d.use.display }); + displays.addDesignation(true, 'active', 'en-US', null, c.row.display || ''); + let skipped = false; + for (const d of c.desigs) { + if (!skipped && d.term === c.row.display && !(d.use && d.use.code === 'SY')) { skipped = true; continue; } + displays.addDesignation(false, 'active', 'en-US', use(d), d.term); + } + } else { + if (c.row.display) displays.addDesignation(true, 'active', this.defLang(), null, c.row.display); + for (const d of c.desigs) { + displays.addDesignation(false, d.active ? 'active' : 'inactive', d.language, d.use, d.term); + } + } + this._listSupplementDesignations(c.code, displays); + } + + /** the display as the one designation, as each dialect adds it, plus supplement designations */ + _displayOnly(c, displays) { + const d = (c.row && c.row.display) || ''; + if (this.dialect.name === 'loinc') displays.addDesignation(true, 'active', 'en-US', CodeSystem.makeUseForDisplay(), d.trim()); + else if (this.dialect.name === 'rxnorm' || this.dialect.name === 'snomed') displays.addDesignation(true, 'active', 'en-US', null, d); + else if (d) displays.addDesignation(true, 'active', this.defLang(), null, d); + this._listSupplementDesignations(c.code, displays); + } + + + + // ---- iteration -------------------------------------------------------------------------- + + async iterator(context) { + let ids; + if (context == null) { + // the usual path's whole-system walk (expand.js includeCodeAndDescendants): rows are then + // read in batches by nextContext and counted in the include's span + if (this._trace) this._trace.annotate({ walk: 'whole system from roots (expand.js usual path)' }); + ids = this._roots(); + } else { + const c = await this._ensure(context); + if (!this.store.hierarchy) return { ids: [], pos: 0, total: 0 }; + ids = this.store.getSet(KIND.prop, this.store.hierarchy.id, c.id, this._stats()).toArray(); + } + return { ids, pos: 0, total: context == null ? this.totalCount() : ids.length }; + } + + _roots() { + if (this.dialect.name === 'loinc' || this.dialect.name === 'rxnorm') { + if (this.dialect.name === 'loinc') return this.store.all().toArray(); + // cs-rxnorm.js iterator(null): ORDER BY RXCUI + return this.engine._order ? this.engine._ordered(this._rxLive()) : this._rxLive().toArray(); + } + // concepts without an active parent + const hid = this.store.hierarchy ? this.store.hierarchy.id : -1; + const hasParent = this.store.getSet(KIND.hasProp, hid, 0); + return RoaringBitmap32.andNot(this.store.active(), hasParent).toArray(); + } + + async iteratorAll() { + const ids = (this.dialect.name === 'rxnorm' ? this._rxLive() : this.store.all()).toArray(); + return { ids, pos: 0, total: ids.length }; + } + + async nextContext(iter) { + if (!iter || iter.pos >= iter.ids.length) return null; + if (!iter.loaded || iter.pos >= iter.loaded) { + const batch = iter.ids.slice(iter.pos, iter.pos + CHUNK).map((id) => this._concept(id)); + this._loadChunk(batch); + iter.loaded = iter.pos + batch.length; + } + return this._concept(iter.ids[iter.pos++]); + } + + // ---- subsumption -------------------------------------------------------------------------- + + async subsumesTest(codeA, codeB) { + if (!this._trace) return this._subsumesTest(codeA, codeB); + return this._trace.spanAsync('subsumes', 'set', this.system(), () => this._subsumesTest(codeA, codeB)); + } + + async _subsumesTest(codeA, codeB) { + const a = await this._ensure(codeA); + const b = await this._ensure(codeB); + if (this.dialect.name === 'rxnorm') return 'not-subsumed'; + if (a.id === b.id) return 'equivalent'; + const st = this._stats(); + if (this.store.getSet(KIND.descendants, 0, a.id, st).has(b.id)) return 'subsumes'; + if (this.store.getSet(KIND.descendants, 0, b.id, st).has(a.id)) return 'subsumed-by'; + return 'not-subsumed'; + } + + /** + * The codes a code sits under, for $closure (CodeSystemProvider.ancestorsOf), answered from + * what subsumesTest reads: a is in ancestorsOf(b) exactly when a's descendant set holds b. + * + * The candidates are the upward walk over the hierarchy links (store.ancestorsOf), and each is + * kept only if its descendant set holds the code, so nothing is listed that subsumesTest would + * not say subsumes. The walk reaches every such ancestor when the descendant sets are the + * closure of those links (SNOMED CT: the importer's hierarchy-closure). For LOINC the sets are + * the explicit PATH_TO_ROOT pairs, and the link graph is a superset of each path (a part's own + * rows give its parents), so the walk reaches them too; this is checked over every concept of + * the LOINC files in use (engine-1114b/tools/anc-check.js). A file with more than one + * hierarchy property gets null: the walk follows one. + * + * Only a code in the form code() gives is answered: another spelling (a SNOMED CT id with + * spaces or a term, an expression) gets null, and $closure asks subsumesTest. RxNorm's + * subsumesTest is flat (not-subsumed), so a known RxNorm code sits under nothing. + * + * @param {string|V2Concept} code + * @returns {Promise|null>} + */ + async ancestorsOf(code) { + const c = typeof code === 'string' ? (await this.locate(code)).context : code; + if (!(c instanceof V2Concept) || (typeof code === 'string' && c.code !== code)) return null; + if (this.dialect.name === 'rxnorm') return new Set(); + const S = this.store; + if (!S.hierarchy) return new Set(); + if ([...S.props.values()].filter((p) => p.isHierarchy).length > 1) return null; + const st = this._stats(); + const candidates = S.ancestorsOf(c.id, st).filter((a) => a !== c.id); + if (!candidates.length) return new Set(); + const sets = S.loadSets(KIND.descendants, 0, candidates, st); + const kept = candidates.filter((a) => { const d = sets.get(a); return !!d && d.has(c.id); }); + const rows = S.conceptRows(kept, st); + return new Set(kept.map((a) => rows.get(a)).filter(Boolean).map((r) => r.code)); + } + + async locateIsA(code, parent, disallowParent = false) { + const r = await this.locate(code); + if (!r.context) return r; + const p = await this.locate(parent); + if (!p.context) return { context: null, message: 'Concept not found' }; + if (r.context.id === p.context.id) return disallowParent ? { context: null, message: 'Concept is not subsumed by parent' } : r; + return this.store.getSet(KIND.descendants, 0, p.context.id).has(r.context.id) ? r : { context: null, message: 'Concept is not subsumed by parent' }; + } + + // ---- $lookup -------------------------------------------------------------------------------- + + async extendLookup(context, props, params) { + if (!this._trace) return this._extendLookup(context, props, params); + return this._trace.spanAsync('lookup properties', 'rows', this.system(), () => this._extendLookup(context, props, params)); + } + + async _extendLookup(context, props, params) { + const c = await this._ensure(context); + if (!c) return; + if (this.dialect.name === 'loinc') return this._loincLookup(c, props, params); + if (this.dialect.name === 'rxnorm') return this._rxnormLookup(c, props, params); + return this._genericLookup(c, props, params); + } + + _targetDisplays(ids) { + return this.store.conceptRows(ids, this._stats()); + } + + _loincLookup(c, props, params) { + // order as main emits it since #385 (cs-loinc.js extendLookup's fixed groups): relationships + // (CLASS, the axes, the rest), the other properties, STATUS, RELATEDNAMES2, then the mappings + const S = this.store; + const st = this._stats(); + const AXES = ['CLASS', 'COMPONENT', 'PROPERTY', 'TIME_ASPCT', 'SYSTEM', 'SCALE_TYP', 'METHOD_TYP']; + // (an answer list's answers-for links come after its answers: upstream's rows are in import order, + // AnswerList.csv before LoincAnswerListLink.csv) + const pos = (code) => { const i = AXES.indexOf(code); return i >= 0 ? i : code === 'parent' || code === 'child' ? 100 : code === 'answers-for' ? 60 : 50; }; + const links = S.linksFrom([c.id], null, true, st); + // the catalog's inverse names (child, AnswerList): the concepts whose reversed property points here + for (const inv of S.inverses()) { + for (const p of inv.reverses) { + for (const id of S.getSet(KIND.prop, p.id, c.id, st).toArray()) links.push({ t: id, name: inv.code }); + } + } + const rows = this._targetDisplays(links.map((l) => l.t)); + const named = links.map((l) => ({ ...l, code: l.name || (S.propsById.get(l.p) || {}).code })).filter((l) => l.code && rows.get(l.t)); + const seq = new Map((S.sequenceOf(c.id) || []).map((id, i) => [id, i])); + // answers-for: LoincAnswerListLink.csv's order, by term code as text + // the other relationships (document and radiology axes, ...): the part links file's order, by part code as text + const textOrder = (a, b) => (rows.get(a.t).code < rows.get(b.t).code ? -1 : rows.get(a.t).code > rows.get(b.t).code ? 1 : 0); + const byCode = (a, b) => ((a.code === 'answers-for' && b.code === 'answers-for') || (pos(a.code) === 50 && pos(b.code) === 50 && !seq.has(a.t) && !seq.has(b.t)) ? textOrder(a, b) : 0); + // parent and child: the built-in importer's Relationships rows' order (hierarchy-file order, a + // part's second parent among its children), when the file has it (orders.js) + const hier = S.hierarchyOrderOf(c.id); + let hierRank = null; + if (hier && hier.length) { + hierRank = new Map(); + for (let i = 0; i < hier.length; i++) hierRank.set(hier[i], i); + } + const hierOf = (l) => { + if (!hierRank || pos(l.code) !== 100) return 0; + const r = hierRank.get(((l.code === 'child' ? HIER_CHILD : 0) | l.t) >>> 0); + return r === undefined ? hier.length : r; + }; + named.sort((a, b) => (pos(a.code) - pos(b.code)) || (hierOf(a) - hierOf(b)) || ((seq.get(a.t) ?? 0) - (seq.get(b.t) ?? 0)) || byCode(a, b)); + for (const l of named) { + if (!this._hasProp(props, l.code, true)) continue; + const t = rows.get(l.t); + if (l.code === 'CLASS') { + const pr = this._addStringProperty(params, 'property', 'CLASS', t.display || t.code); + pr.part.push({ name: 'partCode', valueCode: t.code }); + } else { + // the target's display as the description, as main gives it (cs-loinc.js: Codes.Description) + this._addCodeProperty(params, 'property', l.code, t.code, null, t.display || null); + } + } + const lits = S.literalsOf([c.id], true, st).map((r) => ({ ...r, code: (S.propsById.get(r.p) || {}).code })).filter((r) => r.code); + for (const r of lits) { + if (r.code === 'STATUS' || !this._hasProp(props, r.code, true)) continue; + if (r.code === 'CLASSTYPE') { + const map = S.valueLabels(S.props.get('CLASSTYPE')) || {}; + const pr = this._addStringProperty(params, 'property', 'CLASSTYPE', String(r.v)); + if (map[r.v]) pr.part.push({ name: 'description', valueString: map[r.v] }); + } else { + this._addStringProperty(params, 'property', r.code, String(r.v)); + } + } + for (const r of lits) if (r.code === 'STATUS' && this._hasProp(props, 'STATUS', true)) this._addStringProperty(params, 'property', 'STATUS', String(r.v)); + this._needDesigs(c); + if (this._hasProp(props, 'RELATEDNAMES2', true)) { + const rel = c.desigsNoRelated ? (S.designationRows([c.id], st, { onlyUse: this._relatedUse() }).get(c.id) || []) : c.desigs; + for (const d of rel) if (d.use && d.use.code === 'RELATEDNAMES2') this._addStringProperty(params, 'property', 'RELATEDNAMES2', d.term, d.language); + } + const maps = S.externalMaps(c.id); + for (const m of maps) { + const key = loincMapKey(m.system); + if (!key || !this._hasProp(props, key, true)) continue; + // main's key order: system, version, code, display + const coding = { system: m.system }; + if (m.version) coding.version = m.version; + coding.code = m.code; + if (m.display) coding.display = m.display; + params.push({ name: 'property', part: [{ name: 'code', valueCode: key }, { name: 'value', valueCoding: coding }, + { name: 'subproperty', part: [{ name: 'code', valueCode: 'equivalence' }, { name: 'value', valueCode: m.equivalence }] }] }); + } + } + + /** + * RxNorm properties as cs-rxnorm.js gives them: TTY, STY and SAB (by default), each sorted by + * value; then, only when properties are named (property=* or by name, never by default), the + * RxNorm relationships by RELA (REL where there is none), then the related RXCUI as text, + * each name and RXCUI once, with no description. SUPPRESS is not reported (the built-in + * provider has no such property). + */ + _rxnormLookup(c, props, params) { + const S = this.store; + const st = this._stats(); + const lits = new Map(); + for (const r of S.literalsOf([c.id], true, st)) { + const p = S.propsById.get(r.p); + if (p) (lits.get(p.code) || lits.set(p.code, new Set()).get(p.code)).add(String(r.v)); + } + const asText = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + for (const name of ['TTY', 'STY', 'SAB']) { + if (!this._hasProp(props, name, true)) continue; + for (const v of [...(lits.get(name) || [])].sort(asText)) this._addCodeProperty(params, 'property', name, v); + } + if (!(props && props.length > 0)) return; + const links = S.linksFrom([c.id], null, true, st).filter((l) => { const p = S.propsById.get(l.p); return p && !p.code.includes('@'); }); + const rows = this._targetDisplays(links.map((l) => l.t)); + // cs-rxnorm.js: ORDER BY RELA, REL, RXCUI1 - a REL-only name (upper case: RB, RN, ...) has a null RELA, which sorts first + const relOnly = (n) => /^[A-Z]+$/.test(n); + const named = []; + const seen = new Set(); + for (const l of links) { + const name = S.propsById.get(l.p).code; + const t = rows.get(l.t); + if (!t || seen.has(name + '|' + t.code) || !this._hasProp(props, name, false)) continue; + seen.add(name + '|' + t.code); + named.push({ name, code: t.code }); + } + named.sort((a, b) => (relOnly(b.name) - relOnly(a.name)) || asText(relOnly(a.name) ? '' : a.name, relOnly(b.name) ? '' : b.name) + || asText(a.name, b.name) || asText(a.code, b.code)); + for (const n of named) this._addCodeProperty(params, 'property', n.name, n.code); + } + + /** + * The properties this system reports ({code, uri, type}), for expansion.property: the file's + * property definitions plus the ones the lookup builds (parent, child, ...). FHIR's standard + * concept-property URIs where they exist. + * + * None for SNOMED CT, LOINC and RxNorm, as main (cs-snomed.js, cs-loinc.js and cs-rxnorm.js + * declare none), so expansion.property carries their codes without a uri. The HL7 tester sorts + * expansion.property by uri (absent first), then code, so a uri here would put the definitions + * in a different order from the expected responses, which have none. + */ + propertyDefinitions() { return this.f.propDefs; } + + /** + * Properties of a concept for an expansion (ValueSet contains.property): the same values + * $lookup reports, read only when the request asks for properties: expand.js passes the names + * (none = nothing is read). + */ + async properties(context, names) { + // the names expand.js asks for (#335: the requested ones and the mandatory ones; none means + // none), else those processSelection noted + const wanted = names !== undefined + ? ((names || []).filter((p) => p !== 'definition').length ? names.filter((p) => p !== 'definition') : null) + : this._propertiesWanted; + if (!wanted) return []; + const c = await this._ensure(context); + if (!c) return []; + const params = []; + await this._extendLookup(c, wanted, params); + const out = []; + for (const p of params) { + const code = p.part.find((x) => x.name === 'code'); + const value = p.part.find((x) => x.name === 'value'); + if (!code || !value) continue; + const vk = Object.keys(value).find((k) => k.startsWith('value')); + out.push({ code: code.valueCode, [vk]: value[vk] }); + } + return out; + } + + async getTranslations(map, coding, target) { + const lm = map && map.jsonObj && map.jsonObj.loincMap; + if (!lm) return []; + const targetSystem = target ? target.split('|')[0] : null; + const S = this.store; + const out = []; + if (coding.system === this.system() && (!targetSystem || targetSystem === lm.system)) { + const id = S.idOf(coding.code); + if (id == null) return []; + for (const r of S.externalMaps(id, lm.system)) { + const t = { map: map.vurl, system: lm.system, code: r.code, relationship: mapRelationship(r.equivalence, true) }; + if (r.version) t.version = r.version; + if (r.display) t.display = r.display; + out.push(t); + } + } else if (coding.system === lm.system && (!targetSystem || targetSystem === this.system())) { + for (const r of S.mapsTo(lm.system, coding.code)) { + out.push({ map: map.vurl, system: this.system(), version: this.version(), code: r.code, display: r.display, relationship: mapRelationship(r.equivalence, false) }); + } + } + return out; + } + + _genericLookup(c, props, params) { + const S = this.store; + const links = S.linksFrom([c.id], null, true, this._stats()); + const rows = this._targetDisplays(links.map((l) => l.t)); + for (const l of links) { + const p = S.propsById.get(l.p); + const t = rows.get(l.t); + if (!p || !t || !this._hasProp(props, p.code, true)) continue; + this._addCodeProperty(params, 'property', p.isHierarchy ? 'parent' : p.code, t.code, null, t.display); + } + for (const r of S.literalsOf([c.id], true, this._stats())) { + const p = S.propsById.get(r.p); + if (p && this._hasProp(props, p.code, true)) this._addStringProperty(params, 'property', p.code, String(r.v)); + } + } + + // ---- filters -------------------------------------------------------------------------------- + + /** + * fn() (a compile), again after evaluating what it needs evaluated first: ECL that only main's + * (async) evaluator answers (sct-main-ecl.js NeedsMainEcl) + */ + async _compiled(fn) { + for (let tries = 0; ; tries++) { + try { + return fn(); + } catch (e) { + if (!e || !e.needsMainEcl || tries >= 16) throw e; + await e.resolve(); + } + } + } + + _compiler(stats) { + const provider = this; + let lang; + // lang: the language of a display regex (dialects.js), chosen when one asks for it, so that + // another filter or ECL does not list the file's languages (sctTextLanguages) + const term = { store: this.store, dialect: this.dialect, layers: this.layers, + get lang() { return lang === undefined ? (lang = provider._regexLanguage()) : lang; } }; + return new Compiler(term, { stats: stats || this._stats() }); + } + + /** + * The one language a SNOMED CT display regex searches: the first language the request names + * (displayLanguage, else Accept-Language: getPrepContext, processSelection) that the file has + * descriptions in; else the file's default language. + */ + _regexLanguage() { + const primary = (c) => String(c || '').toLowerCase().split('-')[0]; + if (this.dialect.searchMode === 'designation') { + const requested = (this._requestedLangs && this._requestedLangs.languages) || []; + return this._sctFilterLanguage(requested.map((l) => l && l.language)); + } + const named = (this._requestLangs && this._requestLangs.languages) || (this.opContext.langs && this.opContext.langs.languages) || []; + const have = new Set((this.f.languages() || []).map(primary)); + for (const l of named) { + const p = primary(l && (l.code || l.language)); + if (p && p !== '*' && have.has(p)) return p; + } + return primary(this.store.defaultLanguage) || 'en'; + } + + /** + * The one language a SNOMED CT text or display regex filter searches, as cs-snomed.js + * #filterLanguage chooses it: the first language named (each as tx/sct/languages.js + * languageBytesFor has it: Norwegian under either "no" or "nb"/"nn") that the edition has active + * descriptions in; else the edition's default language (code_system default_language, which the + * importers set as main's importer and server read the cache's default-language slot), if it + * has active descriptions in it, or has none at all; else the edition's language with the lowest + * language byte. + * @param {string[]} named language codes or tags, in the request's order + * @returns {string} a primary language subtag + */ + _sctFilterLanguage(named) { + const present = sctTextLanguages(this.store); + for (const l of named || []) { + for (const b of languageBytesFor(l)) { + const code = languageCode(b); + if (present.has(code)) return code; + } + } + const def = String(this.store.defaultLanguage || 'en').toLowerCase().split('-')[0]; + if (present.has(def) || present.size === 0) return def; + const bytes = [...present].map(languageByte).filter((b) => b); + return bytes.length ? languageCode(Math.min(...bytes)) : def; + } + + async doesFilter(prop, op, value) { + try { + await this._compiled(() => this._compiler().filter(prop, op, value)); + return true; + } catch (e) { + return false; + } + } + + /** is this ValueSet filter on a property only a supplement in use defines (a supplement layer)? */ + _isSupplementFilter(f) { + try { + return this._compiler().filter(f.property, f.op, f.value).t === 'layer'; + } catch (e) { + return false; + } + } + + /** + * cs-api getPrepContext(iterate, languages) (#331): languages is what the request asked for + * (displayLanguage, else Accept-Language). Kept for the request's later filters too: a SNOMED + * CT display regex searches one of them (_regexLanguage). + */ + async getPrepContext(iterate, languages = null) { + if (languages) this._requestLangs = languages; + // what the request named, or null: a SNOMED CT filter's language (cs-snomed.js reads the filter + // context's languages only) + this._requestedLangs = languages || null; + return new V2Prep(iterate, languages); + } + + async filter(prep, forIteration, prop, op, value) { + let node; + try { + node = await this._compiled(() => this._compiler().filter(prop, op, value)); + } catch (e) { + throw this.filterError(e, prop, op, value); + } + if (node.t === 'all' && node.expressionsFalse) prep.expressionsFalse = true; + prep.nodes.push(node); + prep.specs.push({ prop, op, value }); + return null; + } + + /** errors as the upstream provider reports them; dialects may wrap them (SNOMED ECL) */ + filterError(e) { + if (e.unsupported) return new Error(`The filter is not supported: ${e.message}`); + if (e.notUnderstood) { + // a filter the code system has no rule for: a 4xx, as main's providers since #383 + return new Issue('error', 'not-supported', null, 'FILTER_NOT_UNDERSTOOD', + this.opContext.i18n.translate('FILTER_NOT_UNDERSTOOD', this.opContext.langs, e.notUnderstood), 'vs-invalid', 422); + } + return e; + } + + /** + * A text filter searches one language, as main does since #335 (CodeSystemProvider.searchLanguage): + * the first language the request names (displayLanguage, else Accept-Language) that the file or + * a supplement in use has text in, else the file's own language. The file's names in that + * language take part (Store.searchText, text-index.js), and, as each built-in provider adds + * them, the codes a supplement in use gives a matching name in that language that the file's + * own search does not find (_supplementSearchCodes; SNOMED CT: active ones; RxNorm: none). A + * supplement that adds codes is noted on the filter context (prep.usedSupplements), for + * used-supplement. + */ + async searchFilter(prep, filter) { + const text = typeof filter === 'string' ? filter : (filter && filter.filter) || ''; + const node = { t: 'search', text, mode: this.dialect.searchMode }; + const requested = (prep && prep.languages) || this._requestLangs || this.opContext.langs || null; + // SNOMED CT: the filter context's languages only, as cs-snomed.js (none: the edition's default) + const searchLang = this.dialect.searchMode === 'designation' ? this._sctSearchLanguage(prep ? prep.languages : this._requestedLangs) : this.searchLanguage(requested); + node.lang = (searchLang.language || this.defLang() || 'en').toLowerCase(); + node.defLang = this.defLang(); + let n = node; + if (this.dialect.searchMode !== 'rxnorm' && this.supplements && this.supplements.length && filter && typeof filter.passes === 'function') { + const sources = new Map(); + const codes = await this._supplementSearchCodes(filter, searchLang, sources); + const base = codes.size ? ((await this._pausing(this.store.searchTextG(text, this._stats(), node.mode, node.lang, node.defLang))) || new RoaringBitmap32()) : null; + const ids = []; + const active = this.dialect.searchMode === 'designation' ? this.store.active(this._stats()) : null; + const idsOf = this.store.resolveCodes([...codes].map((c) => this.normaliseCode(c)), this._stats()); + for (const code of codes) { + const id = idsOf.get(this.normaliseCode(code)); + if (id == null || base.has(id) || (active && !active.has(id)) || ids.includes(id)) continue; + ids.push(id); + CodeSystemProvider.noteSupplementUsed(prep, sources.get(code)); + } + if (ids.length) { + // codes only a supplement's text matches: after the file's matches, in the supplement's + // order (SNOMED CT, LOINC), or rated 10 among them (other code systems: cs-cs.js) + prep.searchExtras = ids; + n = { t: 'or', items: [{ t: 'ids', ids: base.toArray() }, { t: 'ids', ids }] }; + } + } + prep.nodes.push(n); + prep.searchText = text; + prep.searchLang = node.lang; + return null; + } + + /** + * The language a SNOMED CT text filter searches, as cs-snomed.js chooses it (#filterLanguage): + * _sctFilterLanguage, for the languages the request names. + */ + _sctSearchLanguage(languages) { + const named = ((languages && languages.languages) || []).filter((l) => l && l.language); + const code = this._sctFilterLanguage(named.map((l) => l.language)); + // the request's own Language when it is the one chosen (its region and the rest kept) + return named.find((l) => l.language.toLowerCase() === code) || new Language(code); + } + + /** a text-index.js search step, pausing at its pause points (the request's checkAndYield) */ + _pausing(g) { + const pause = this._pause(); + if (pause) return runPausing(g, pause); + let r = g.next(); + while (!r.done) r = g.next(); + return Promise.resolve(r.value); + } + + /** the order the built-in provider lists text-search results in (text-index.js) */ + async _searchOrder(bm, text, extras = null, lang = null) { + const keep = (ids) => { const out = []; for (const id of ids) if (bm.has(id)) out.push(id); return out; }; + const mode = this.dialect.searchMode; + if (mode === 'rxnorm') return keep((await this._pausing(rxTextSearchG(this.store, text, rxSearchable(this.store, this._stats()), this._stats()))).ids); + if (mode !== 'designation' && mode !== 'display') { + // cs-cs.js: a supplement's codes are rated 10, among the others + const extra = extras && extras.length ? new Set(this.store.conceptRows(extras, this._stats()).values().map((r) => r.code)) : null; + return keep((await this._pausing(genericTextSearchG(this.store, text, lang || 'en', this.defLang(), this._stats(), extra))).ids); + } + const ordinal = this.store.ordinal || ((id) => id); + const found = (await this._pausing(mode === 'designation' + ? sctTextSearchG(this.store, text, lang || 'en', ordinal, this._stats()) + : loincTextSearchG(this.store, text, lang || 'en', ordinal, this._stats()))).ids; + const out = keep(found); + if (extras && extras.length) { + // the supplements' codes, after the file's own matches (cs-snomed.js, cs-loinc.js) + for (const id of extras) if (bm.has(id)) out.push(id); + } + return out; + } + + async executeFilters(prep) { + if (!this._trace) return this._executeFilters(prep); + return this._trace.spanAsync('evaluate filters', 'set', this.system(), () => this._executeFilters(prep)); + } + + async _executeFilters(prep) { + if (!prep.nodes.length) return []; + // within the code system's domain, as processSelection's includes are (compile.js domain: + // RxNorm never selects a concept found only in RXNATOMARCHIVE) + const node = this._compiler().domain(prep.nodes.length === 1 ? prep.nodes[0] : { t: 'and', items: prep.nodes }); + if (prep.forIterate) { + if (prep.searchText != null) { + const bm = await this.engine.evaluateAsync(node, this._trace, this._pause()); + prep.filters = [new V2FilterSet(null, { node, ids: await this._searchOrder(bm, prep.searchText, prep.searchExtras, prep.searchLang), expressionsFalse: prep.expressionsFalse })]; + return prep.filters; + } + if (this.engine._order) { + // a system with a built-in answer order (LOINC, SNOMED CT): the members in that order, as + // processSelection lists them (is-a: the concept first; child-of: release order; answer + // lists: their sequence). expand.js iterates a filter this way when it does not hand the + // compose over whole (an include that also names a value set; several systems) + const ids = await this.engine.orderedAsync(node, this._trace, this._pause()); + prep.filters = [new V2FilterSet(new RoaringBitmap32(ids), { node, ids, expressionsFalse: prep.expressionsFalse })]; + } else { + prep.filters = [new V2FilterSet(await this.engine.evaluateAsync(node, this._trace, this._pause()), { node, expressionsFalse: prep.expressionsFalse })]; + } + } else { + prep.filters = [new V2FilterSet(null, { node, expressionsFalse: prep.expressionsFalse })]; + } + for (const f of prep.filters) f.specs = prep.specs; + return prep.filters; + } + + async filtersNotClosed(prep) { + if (!this.isNotClosed()) return false; + // filters only on properties a supplement in use defines select from the supplement's + // listed codes, a closed set (main evaluates them outside the code system: supplement-filters.js) + if (prep.supplementOnly || (prep.nodes && prep.nodes.length && prep.nodes.every((n) => n.t === 'layer'))) return false; + return !prep.expressionsFalse; + } + + async filterSize(prep, set) { + if (!set.bm && !set.ids) set.bm = await this.engine.evaluateAsync(set.node, this._trace, this._pause()); + return set.total != null ? set.total : set.size; + } + + async filterMore(prep, set) { + if (!set.bm && !set.ids) set.bm = await this.engine.evaluateAsync(set.node, this._trace, this._pause()); + set.pos++; + if (set.pos >= set.size) return false; + const off = set.pos - set.bufStart; + if (off >= set.buf.length || set.pos < set.bufStart) { + const ids = set.ids ? set.ids.slice(set.pos, set.pos + CHUNK) : Array.from(set.bm.rangeUint32Array(set.pos, CHUNK)); + set.buf = ids.map((id) => this._concept(id)); + set.bufStart = set.pos; + this._loadChunk(set.buf); + } + set.current = set.buf[set.pos - set.bufStart]; + return true; + } + + async filterConcept(prep, set) { return set.current; } + + async filterLocate(prep, set, code) { + if (!this._trace) return this._filterLocate(prep, set, code); + return this._trace.spanAsync('membership', 'set', this.system(), () => this._filterLocate(prep, set, code)); + } + + async _filterLocate(prep, set, code) { + const r = await this.locate(code); + if (!r.context) return this.dialect.name === 'loinc' ? `Not a valid code: ${code}` : r.message; + return this._member(set, r.context.id) ? r.context : null; + } + + async filterCheck(prep, set, concept) { + const c = await this._ensure(concept); + return this._member(set, c.id); + } + + _member(set, id) { + if (set.bm) return set.bm.has(id); + if (set.ids) return set.ids.includes(id); + return this.engine.contains(set.node, id, this._trace); + } + + async filterFinish() { } + + // ---- processSelection (whole single-system composes) ---------------------------------------- + + handlesSelecting() { return true; } + + /** + * cs-api processSelection (expand.js processCodes): the page of the whole compose, with the + * selection's total. offset -1 = from the start; count -1 = to the end, 0 = the total only. + * context.valueSet ({ url, version }) is the value set the compose belongs to; it names a refusal. + * @returns {{sets: V2FilterSet[], total: number, notClosed: boolean}|null} null = not handled + * (expand.js takes its usual path) + */ + /** + * whether an include filter selects by concept on a code the code system doesn't have + * (expand.js #filterNamesUnknownCode: the value, or for `in`, any code of its list) + */ + async _namesUnknownConcept(includes) { + const { filterConceptCodes } = require('../workers/expand'); + for (const cset of includes) { + for (const fc of cset.filter || []) { + for (const code of filterConceptCodes(fc)) { + let loc = null; + try { loc = await this.locate(code); } catch (e) { loc = null; } + if (!loc || !loc.context) return true; + } + } + } + return false; + } + + async processSelection(params, includes, excludes, excludeInactive, offset, count, context = {}) { + // the request's working languages, for a display regex in the compose (_regexLanguage) + if (params && typeof params.workingLanguages === 'function' && params.workingLanguages()) this._requestLangs = params.workingLanguages(); + if (params && typeof params.requestedLanguages === 'function') this._requestedLangs = params.requestedLanguages() || null; + const trace = this._trace; + // an include filter that selects by concept (is-a, =, ...) on a code the file doesn't have: the + // usual path reports it (#396: an expansion-issue warning, or 422 with errorsForInvalidCodes) + // and the include adds nothing + if (await this._namesUnknownConcept(includes)) return null; + // listed codes (an exclude's concept list) are resolved by the code as written. One that + // locate() would read otherwise (normalised, or an expression) is left to the usual path + for (const cset of [...includes, ...excludes]) { + for (const cc of cset.concept || []) { + if (!this._plainListedCode(cc.code)) return null; + } + } + // properties requested (property=..., compose.property): properties() reads them per code + this._propertiesWanted = params && params.properties && params.properties.length ? params.properties.filter((p) => p !== 'definition') : null; + let sel; + try { + const compile = () => this._compiler(trace ? trace.stats : null).selection(includes, excludes, excludeInactive || (params && params.activeOnly)); + sel = await this._compiled(() => (trace ? trace.span('compile compose', 'sql', this.system(), compile) : compile())); + } catch (e) { + if (trace) trace.span('fallback: ' + e.message, 'set', this.system(), () => null); + if (e.unsupported) return null; + if (e.filterError) return null; // expand.js reports it through filter() + throw e; + } + const start = Math.max(offset, 0); + let result; + try { + result = await this.engine.runAsync(sel, { offset: start, count, trace, pause: this._pause() }); + } catch (e) { + if (e && e.tooCostly) throw this._tooCostly(params, context, e.message); + throw e; + } + const page = result.page(start, count); + const set = new V2FilterSet(null, { ids: page, total: result.complete ? result.total : null }); + if (count >= 0) { + // the page's rows, and its designations only when the response can use them: one + // statement each. An English-or-default request without includeDesignations/designation + // shows the display only, so the designation rows are not read. + const needDesignations = !TxParameters.prototype.showsDisplayOnly.call(params || {}, this.opContext.langs); + const concepts = page.map((id) => this._concept(id)); + if (!needDesignations) for (const c of concepts) c.displayOnly = true; + // in slices of PAGE_ROWS with a pause between: a whole-system page (count=-1) is 100,000s of rows + const pause = this._pause(); + const fetch = async () => { + for (let i = 0; i < concepts.length; i += PAGE_ROWS) { + if (i && pause) await pause(); + this._loadRows(i === 0 && concepts.length <= PAGE_ROWS ? concepts : concepts.slice(i, i + PAGE_ROWS), needDesignations); + } + }; + if (trace) await trace.spanAsync('fetch page rows (' + concepts.length + ')', 'rows', this.system(), fetch); + else await fetch(); + set.buf = concepts; + set.bufStart = 0; + } + set.complete = result.complete; + set.result = result; + if (trace) trace.annotate({ codesReturned: page.length, total: result.complete ? result.total : null }); + // count=0 on the whole system: what expand.js asks the built-in provider for (countAllCodes: + // cs-snomed.js the concepts, or the active ones for a compose without inactive codes; cs-loinc.js + // every code), not the walk's count (activeOnly does not change it; SNOMED CT's walk does not + // reach the inactive concepts) + // (RxNorm: its whole system is the RXNCONSO concepts, a set, not the walk; the include is the + // whole system whatever activeOnly or compose.inactive say, as expand.js counts it) + const whole = result.wholeSystem || (this.dialect.name === 'rxnorm' && includes.length === 1 && !excludes.length + && ['filter', 'concept', 'valueSet'].every((k) => !(includes[0][k] || []).length)); + const total = count === 0 && whole ? await this.countAllCodes(excludeInactive) : result.total; + return { sets: [set], total: result.complete ? total : -1, notClosed: await this._selectionNotClosed(includes, excludes) }; + } + + /** + * Whether a compose processSelection took is open, as the usual path decides it one include and + * exclude at a time (expand.js includeCodes / excludeCodes): the code system is open + * (isNotClosed) and an include of the whole system, or an include or exclude whose filters are + * open (filtersNotClosed: not every one a supplement's, and none `expressions = false`), makes + * the expansion open. So one include with `expressions = false` does not close a union. + */ + async _selectionNotClosed(includes, excludes) { + const open = async (cset) => { + const filters = cset.filter || []; + const prep = { + expressionsFalse: filters.some((f) => f.property === 'expressions' && String(f.value) === 'false'), + supplementOnly: filters.length > 0 && filters.every((f) => this._isSupplementFilter(f)) + }; + return filters.length > 0 && await this.filtersNotClosed(prep); + }; + if (!this.isNotClosed()) return false; + for (const cset of includes) { + if (!(cset.filter || []).length || await open(cset)) return true; + } + for (const cset of excludes) { + if (await open(cset)) return true; + } + return false; + } + + /** + * The engine's planner refused (estimated cost over maxScanRows): the standard too-costly Issue + * (cs-api processSelection), naming the value set processSelection was told it serves. + */ + _tooCostly(params, context, what) { + const vs = (context && context.valueSet) || {}; + const vurl = vs.url ? (vs.version ? vs.url + '|' + vs.version : vs.url) : '??'; + return new Issue('error', 'too-costly', null, 'VALUESET_TOO_COSTLY', + this.opContext.i18n.translate('VALUESET_TOO_COSTLY', (params && params.httpLanguages) || this.opContext.langs, [vurl, what]), null, 422) + .withDiagnostics(this.opContext.diagnostics()); + } + + /** request end (opContext.closeProviders): release the supplement layers built for it */ + async close() { this.layers.close(); } + +} + +/** the property definitions a file reports (data built at load) */ +const NO_PROPERTY_DEFINITIONS = new Set(['snomed', 'loinc', 'rxnorm']); + +function propertyDefinitionsFor(store, dialect) { + // main's SNOMED CT, LOINC and RxNorm providers declare none (see propertyDefinitions) + if (NO_PROPERTY_DEFINITIONS.has(dialect.name)) return null; + const std = { parent: 'http://hl7.org/fhir/concept-properties#parent', child: 'http://hl7.org/fhir/concept-properties#child', + inactive: 'http://hl7.org/fhir/concept-properties#inactive', status: 'http://hl7.org/fhir/concept-properties#status' }; + const defs = []; + const seen = new Set(); + const add = (code, uri, type) => { if (!seen.has(code)) { seen.add(code); defs.push({ code, uri: uri || std[code] || undefined, type }); } }; + for (const p of store.props.values()) if (!p.code.includes('@')) add(p.isHierarchy ? 'parent' : p.code, p.uri, p.type); + for (const c of ['parent', 'child', 'inactive']) add(c, null, 'code'); + return defs; +} + +function sortLoinc(desigs) { + // a part's PartName rows (the linguistic variants' part files) come after its DisplayName (Part.csv), as main's + // Descriptions rows do (its query has no ORDER BY; rows in import order) + const order = ['LONG_COMMON_NAME', 'SHORTNAME', 'ConsumerName', 'RELATEDNAMES2', 'DisplayName', 'LinguisticVariantDisplayName', 'PartName']; + return [...desigs].sort((a, b) => { + const ua = a.use ? order.indexOf(a.use.code) : 99; + const ub = b.use ? order.indexOf(b.use.code) : 99; + if (ua !== ub) return ua - ub; + if (a.language === 'en-US' && b.language !== 'en-US') return -1; + if (b.language === 'en-US' && a.language !== 'en-US') return 1; + return a.id - b.id; + }); +} + +// LOINC's mappings to other systems: $lookup properties named , and the implicit +// ConceptMaps http://loinc.org/cm/ (as cs-loinc.js) +const LOINC_MAPS = [ + { system: 'http://loinc.org', key: 'loinc' }, + { system: 'http://pubchem.ncbi.nlm.nih.gov', key: 'ncbi' }, + { system: 'http://snomed.info/sct', key: 'sct' }, + { system: 'http://www.cms.gov/Medicare/Coding/HCPCSReleaseCodeSets', key: 'hcpcs' }, + { system: 'http://www.genenames.org', key: 'gene-names' }, + { system: 'http://www.nlm.nih.gov/research/umls/rxnorm', key: 'rxnorm' }, + { system: 'https://www.ebi.ac.uk/chebi', key: 'chebi' }, + { system: 'https://www.ncbi.nlm.nih.gov/clinvar', key: 'ncbi-clinvar' }, + { system: 'https://www.ncbi.nlm.nih.gov/gene', key: 'ncbi-gene' }, + { system: 'https://www.ncbi.nlm.nih.gov/taxonomy', key: 'ncbi-taxo' }, + { system: 'urn:iso:std:iso:11073:10101', key: 'mdc' }, + { system: 'urn:oid:2.16.840.1.113883.6.238', key: 'race' } +]; +const LOINC_MAP_BASE = 'http://loinc.org/cm/'; +function loincMapKey(system) { const m = LOINC_MAPS.find((x) => x.system === system); return m ? m.key : null; } + +/** R4 equivalence from the LOINC side -> R5 relationship from the translated code's side */ +function mapRelationship(equivalence, fromLoinc) { + switch (equivalence) { + case 'equivalent': case 'equal': return 'equivalent'; + case 'narrower': return fromLoinc ? 'source-is-broader-than-target' : 'source-is-narrower-than-target'; + case 'wider': return fromLoinc ? 'source-is-narrower-than-target' : 'source-is-broader-than-target'; + default: return 'related-to'; + } +} + +// ---- factory ------------------------------------------------------------------------------- + +class SqliteV2Factory extends CodeSystemFactoryProvider { + constructor(i18n, file, opts = {}) { + super(i18n); + this.file = file; + this.opts = opts; + } + + async load() { + this.store = openStore(this.file, this.opts); + this.dialect = dialectFor(this.store.system); + // behaviour.expansionOrder: concept ids, or the stored order (ix_order) + const kind = this.store.behaviour.expansionOrder; + const order = kind !== 'ids' ? this._systemOrder(kind) : null; + this.engine = new Engine(this.store, order ? { ...this.opts, order } : this.opts); + // SNOMED CT text search ranks ties by the built-in concept order (text-index.js) + if (order) this.store.ordinal = (id) => order.rank[id]; + this.layers = new SupplementLayers(this.store); + this.propDefs = propertyDefinitionsFor(this.store, this.dialect); + // data, not cache: read once when the file loads + this._langs = this.store.languages(); + } + + /** + * The built-in answer order of LOINC, SNOMED CT and RxNorm (orders.js): arrays stored in the + * file (ix_order), read lazily, array by array. + */ + _systemOrder(kind) { + const t0 = Date.now(); + const order = this.store.systemOrder(kind); + this.orderBuildMs = Date.now() - t0; + return order; + } + + system() { return this.store.system; } + version() { return this.store.version; } + defaultVersion() { return this.store.version; } + name() { return this.store.cs.name || this.store.system; } + // behaviour.description / lookupName: the code system's name or its title (LOINC: description + // 'LOINC', $lookup name the title, as cs-loinc.js) + description() { return this.store.behaviour.description === 'name' ? this.name() : (this.store.cs.title || this.name()); } + lookupName() { return this.store.behaviour.lookupName === 'title' ? (this.store.cs.title || this.name()) : this.name(); } + defLang() { return 'en'; } + /** + * RxNorm: the concepts in RXNCONSO, as cs-rxnorm.js counts them (its totalCodeCount), not those + * found only in RXNATOMARCHIVE, which the file also holds (archived) but no answer selects + */ + totalCount() { + if (this.dialect.name !== 'rxnorm') return this.store.conceptCount; + if (this._liveCount == null) { + const p = this.store.props.get('SUPPRESS'); + this._liveCount = p ? this.store.getSet(KIND.hasProp, p.id, 0).size : this.store.active().size; + } + return this._liveCount; + } + versionAlgorithm() { return this.store.behaviour.versionAlgorithm; } + /** + * The factory id, as main's provider for the same system forms it (read.js and search.js serve + * it as CodeSystem/x-; tx.fhir.org uses the same ids): LOINC 'loinc' + version + * (cs-loinc.js: x-loinc2.82), RxNorm name + '-' + version (cs-rxnorm.js: x-RxNorm-03022026). + * SNOMED CT is SnomedV2Factory.id(). Other systems have no classic provider to follow. + */ + id() { + if (this.store.system === LOINC) return 'loinc' + this.version(); + if (this.store.system === RXNORM) return this.name() + '-' + this.version(); + return (this.name().replace(/\W/g, '') + '-' + this.version()).toLowerCase(); + } + describeVersion(v) { + if (this.store.system === RXNORM) { + const { formatDateMMDDYYYY } = require('../../library/utilities'); + return formatDateMMDDYYYY(v); + } + return super.describeVersion(v); + } + + /** designation languages: data read at load */ + languages() { return this._langs; } + + async build(opContext, supplements) { + this.recordUse(); + return new SqliteV2Provider(opContext, supplements, this); + } + + async buildKnownValueSet(url, version) { + if (version && version !== this.version()) return null; + if (this.store.system === LOINC) return this._loincKnownValueSet(url); + return null; + } + + _loincKnownValueSet(url) { + if (url === 'http://loinc.org/vs') { + // (the members in cs-loinc.js's order, so the JSON matches) + return { resourceType: 'ValueSet', url, version: this.version(), status: 'active', + name: 'LOINC Value Set - all LOINC codes', description: 'All LOINC codes', date: new Date().toISOString(), experimental: false, + compose: { include: [{ system: LOINC }] } }; + } + const m = /^http:\/\/loinc\.org\/vs\/(.+)$/.exec(url); + if (!m) return null; + const code = m[1]; + const id = this.store.idOf(code); + if (id == null) return null; + const row = this.store.conceptRows([id]).get(id); + const base = { resourceType: 'ValueSet', url, version: this.version(), status: 'active' }; + const dated = () => ({ date: new Date().toISOString(), experimental: false }); + if (code.startsWith('LP')) { + return { ...base, name: 'LOINCValueSetFor' + code.replace(/-/g, '_'), description: `LOINC value set for code ${code}: ${row.display}`, + ...dated(), compose: { include: [{ system: LOINC, filter: [{ property: 'ancestor', op: '=', value: code }] }] } }; + } + if (code.startsWith('LL')) { + const members = this.store.sequenceOf(id) || this.store.getSet(KIND.refset, 0, id).toArray(); + const rows = this.store.conceptRows(members); + return { ...base, name: 'LOINCAnswerList' + code.replace(/-/g, '_'), description: `LOINC Answer list for code ${code}: ${row.display}`, + ...dated(), compose: { include: [{ system: LOINC, concept: members.map((i) => ({ code: rows.get(i).code })) }] } }; + } + return null; + } + + // LOINC's implicit concept maps (http://loinc.org/cm/) + async findImplicitConceptMaps(conceptMaps, source, sourceVersion, dest, code = null) { + if (this.store.system !== LOINC || !dest) return; + const destSystem = dest.split('|')[0]; + const other = source === LOINC ? destSystem : destSystem === LOINC ? source : null; + const lm = LOINC_MAPS.find((m) => m.system === other); + if (!lm || conceptMaps.some((m) => m.url === LOINC_MAP_BASE + lm.key)) return; + if (code) { + const id = this.store.idOf(code); + if (!this.store.hasMap(id, lm.system, code)) return; + } + conceptMaps.push(this._loincMap(lm)); + } + + async findImplicitConceptMap(url, version) { + if (this.store.system !== LOINC || !url || !url.startsWith(LOINC_MAP_BASE)) return null; + if (version && version !== this.version()) return null; + const lm = LOINC_MAPS.find((m) => LOINC_MAP_BASE + m.key === url); + return lm ? this._loincMap(lm) : null; + } + + _loincMap(lm) { + const { ConceptMap } = require('../library/conceptmap'); + const groups = [{ source: LOINC, target: lm.system }]; + if (lm.system !== LOINC) groups.push({ source: lm.system, target: LOINC }); + return new ConceptMap({ resourceType: 'ConceptMap', internalSource: this, loincMap: lm, url: LOINC_MAP_BASE + lm.key, + name: `LOINC ${lm.key} Concept Map`, description: `The mappings between LOINC ${this.version()} and ${lm.system}, as published by LOINC`, + status: 'active', group: groups }); + } + + async close() { this.store.close(); } +} + +module.exports = { SqliteV2Provider, SqliteV2Factory, V2Concept, V2FilterSet, FilterError }; diff --git a/tx/sqlite-v2/sct-main-ecl.js b/tx/sqlite-v2/sct-main-ecl.js new file mode 100644 index 00000000..568a1a05 --- /dev/null +++ b/tx/sqlite-v2/sct-main-ecl.js @@ -0,0 +1,555 @@ +'use strict'; + +// ECL that the sqlite-v2 engine does not evaluate itself (some group/attribute cardinality +// combinations, alternate identifiers, attribute-name sets, member filters on older files), evaluated +// by main's own ECL code (tx/cs/cs-snomed.js) over a sqlite-v2 file: the binary structures main's +// ECL reads (tx/sct/structures.js) are replaced by read-through views of the store that answer the +// same calls. Post-coordination does not come here: it is native (sct-native.js). +// +// Built per call: what it reads stays in this call's memo maps. Main's ECL evaluation is async +// (1.0.5), and the engine compiles synchronously, so the result is evaluated first and kept per +// file (resolveMainEcl: the file is read-only, so a result never goes stale); the compiler then +// reads it (mainEclResult). A compile that needs one not evaluated yet throws NeedsMainEcl, which +// the provider's async entry points answer by evaluating it and compiling again +// (provider.js _compiled). +// +// Addresses: a concept's "index" is (concept_id - 1) * 56, as main's fixed-size records; +// a description's is designation_id * 40; a relationship gets an index the first time it is read. +// Lists (main's refs) and strings are handles allocated on demand. + +const { SnomedServices } = require('../cs/cs-snomed'); +const { SnomedExpressionServices } = require('../sct/expressions'); +const { SnomedTextIndexes } = require('../sct/text-index'); +const { KIND } = require('./store'); +const { RoaringBitmap32 } = require('roaring'); +// a description's language, as main's language byte (the one table, shared with main's importer) +const { languageByte } = require('../sct/languages'); + +const CONCEPT_SIZE = 56; +const DESC_SIZE = 40; +const REL_SIZE = 40; +const NO = 0xFFFFFFFF; +const IS_A = '116680003'; +const PRIMITIVE = '900000000000074008'; +const INFERRED = '900000000000011006'; +const IDENTIFIER_SCHEME_TYPES = { c: 1, i: 4, s: 5 }; + +/** handles for main's list (refs) and string offsets: numbers, resolved lazily */ +class Handles { + constructor() { + this.next = 16; + this.thunks = new Map(); + this.values = new Map(); + } + + value(v) { + const h = this.next; + this.next += 4; + this.values.set(h, v); + return h; + } + + lazy(thunk) { + const h = this.next; + this.next += 4; + this.thunks.set(h, thunk); + return h; + } + + get(h) { + if (this.values.has(h)) return this.values.get(h); + const t = this.thunks.get(h); + if (!t) throw new Error(`sqlite-v2 adapter: unknown handle ${h}`); + const v = t(); + this.thunks.delete(h); + this.values.set(h, v); + return v; + } +} + +/** the store, read as main's structures */ +class V2View { + constructor(store) { + this.store = store; + this.h = new Handles(); + this.rows = new Map(); // concept_id -> row (+ facts) + this.idByCode = new Map(); + this.rels = []; // relationship records; index = (position + 1) * REL_SIZE + this.relKey = new Map(); + this.desc = new Map(); // designation_id -> record + const p = store.props; + this.isAProp = p.get(IS_A); + this.moduleProp = p.get('moduleId'); + this.defStatusProp = p.get('definitionStatusId'); + this.timeProp = p.get('effectiveTime'); + // attribute properties are the ones named by a concept id + this.attrProps = new Map(); + for (const [code, def] of p) if (def.attribute && def.kind === 'concept') this.attrProps.set(def.id, code); + this.literalAttrProps = new Map(); + for (const [code, def] of p) if (def.attribute && def.kind !== 'concept') this.literalAttrProps.set(def.id, code); + } + + /** the reference sets a concept belongs to (concept indexes), from the stored refset sets */ + refsetsOf(id) { + if (!this.refsetSets) { + const S = this.store; + const rids = S.refsetIds(); + this.refsetSets = [...S.loadSets(KIND.refset, 0, rids)]; + } + return this.refsetSets.filter(([, bm]) => bm.has(id)).map(([rid]) => this.idx(rid)); + } + + idx(id) { return (id - 1) * CONCEPT_SIZE; } + idOf(index) { return index / CONCEPT_SIZE + 1; } + + conceptId(code) { + const c = String(code); + if (!this.idByCode.has(c)) this.idByCode.set(c, this.store.idOf(c)); + return this.idByCode.get(c); + } + + /** concept row and its facts, read once per request */ + facts(id) { + let f = this.rows.get(id); + if (f) return f; + const S = this.store; + const row = S.conceptRows([id]).get(id); + if (!row) throw new Error(`sqlite-v2 adapter: no concept ${id}`); + const links = S.linksFrom([id], null, false); + const lits = S.literalsOf([id], false); + f = { row, links, lits }; + this.rows.set(id, f); + return f; + } + + code(id) { return this.facts(id).row.code; } + + relIndex(source, pid, group, target, active) { + const key = source + ':' + pid + ':' + group + ':' + target + ':' + active; + let i = this.relKey.get(key); + if (i === undefined) { + this.rels.push({ source, pid, group, target, active }); + i = this.rels.length * REL_SIZE; + this.relKey.set(key, i); + } + return i; + } + + relationship(index) { + const r = this.rels[index / REL_SIZE - 1]; + if (!r) throw new Error('Wrong length index getting snomed relationship Details'); + const type = this.conceptId(this.attrProps.get(r.pid)); + const inferred = this.conceptId(INFERRED); + return { + source: this.idx(r.source), target: this.idx(r.target), relType: type ? this.idx(type) : 0, + module: 0, kind: inferred ? this.idx(inferred) : 0, modifier: 0, date: 0, + active: !!r.active, defining: true, group: r.group, identity: 0n + }; + } + + /** designation record (main's description) */ + description(did) { + let d = this.desc.get(did); + if (d) return d; + const S = this.store; + const r = S.designationById(did); + if (!r) throw new Error('Wrong length index getting snomed Desc Details'); + const acc = r.accs; + const use = r.useId != null ? S.uses.get(r.useId) : null; + const useId = use ? this.conceptId(use.code) : null; + const lang = String(r.language || 'en').toLowerCase().split('-')[0]; + d = { + // the description's SCTID where the file keeps it (item external_id), else the row id + iDesc: this.h.value(r.term), active: r.active, id: BigInt(r.sctid != null ? r.sctid : r.id), concept: this.idx(r.conceptId), + module: 0, kind: useId ? this.idx(useId) : 0, caps: 0, date: 0, lang: languageByte(lang) || 1, + refsets: acc.length ? this.h.value(acc.map((a) => this.idx(a[0]))) : 0, + valueses: acc.length ? this.h.value(acc.map((a) => this.h.value([this.idx(a[1]), 1]))) : 0 + }; + this.desc.set(did, d); + return d; + } + + effectiveTime(lits) { + const t = this.timeProp && lits.find((l) => l.p === this.timeProp.id); + if (!t) return 0; + const s = String(t.v).replace(/-/g, ''); + if (!/^\d{8}$/.test(s)) return 0; + const d = Date.UTC(+s.substring(0, 4), +s.substring(4, 6) - 1, +s.substring(6, 8)); + return Math.round((d - Date.UTC(1899, 11, 30)) / 86400000); + } +} + +// ---- main's structure interfaces over the view --------------------------------------------- + +function strings(v) { + return { getEntry: (h) => String(v.h.get(h)) }; +} + +function refs(v) { + return { + getReferences: (h) => (h === 0 || h === NO || h == null ? null : v.h.get(h)), + getLength: (h) => (h === 0 || h === NO || h == null ? 0 : (v.h.get(h) || []).length) + }; +} + +function concepts(v) { + const S = v.store; + const self = { + findConcept(identity) { + const id = v.conceptId(String(identity)); + return id == null ? { found: false, index: 0 } : { found: true, index: v.idx(id) }; + }, + count() { return S.conceptCount; }, + getConceptByCount(ord) { return self.getConcept(ord * CONCEPT_SIZE); }, + conceptExists(index) { return index >= 0 && index % CONCEPT_SIZE === 0 && v.idOf(index) <= S.conceptCount; }, + getConcept(index) { + const id = v.idOf(index); + const f = v.facts(id); + const prim = v.defStatusProp && f.links.some((l) => l.p === v.defStatusProp.id && v.code(l.t) === PRIMITIVE); + return { + index, identity: BigInt(f.row.code), + flags: (f.row.active ? 0 : 1) | (prim ? 0x10 : 0), + parents: self.getParent(index), + descriptions: self.getDescriptions(index), + inbounds: self.getInbounds(index), + outbounds: self.getOutbounds(index), + effectiveTime: v.effectiveTime(f.lits), + refsets: self.getRefsets(index) + }; + }, + getConceptId(index) { return BigInt(v.code(v.idOf(index))); }, + getIdentity(index) { return BigInt(v.code(v.idOf(index))); }, + getParent(index) { + const id = v.idOf(index); + // as main: 0 when there are none (callers read 0 as "no parents") + const ps = v.facts(id).links.filter((l) => v.isAProp && l.p === v.isAProp.id && l.active).map((l) => v.idx(l.t)); + return ps.length ? v.h.value(ps) : 0; + }, + getDescriptions(index) { + const id = v.idOf(index); + return v.h.lazy(() => S.designationIdsOf(id).map((d) => d * DESC_SIZE)); + }, + getOutbounds(index) { + const id = v.idOf(index); + return v.h.lazy(() => v.facts(id).links.filter((l) => v.attrProps.has(l.p)).map((l) => v.relIndex(id, l.p, l.g || 0, l.t, l.active ? 1 : 0))); + }, + getInbounds(index) { + const id = v.idOf(index); + return v.h.lazy(() => S.linksTo(id, false) + .filter((r) => v.attrProps.has(r.p)).map((r) => v.relIndex(r.s, r.p, r.g, id, r.active))); + }, + getAllDesc(index) { + const id = v.idOf(index); + return v.h.lazy(() => { + const bm = S.loadSets(KIND.descendants, 0, [id]).get(id); + return bm ? bm.toArray().map((d) => v.idx(d)) : []; + }); + }, + getDepth(index) { + // ancestors along the longest is-a path (main stores the depth at import) + let depth = 0; + let frontier = [v.idOf(index)]; + const seen = new Set(); + while (frontier.length && depth < 64) { + const next = []; + for (const id of frontier) { + for (const l of v.facts(id).links) if (v.isAProp && l.p === v.isAProp.id && l.active && !seen.has(l.t)) { seen.add(l.t); next.push(l.t); } + } + if (!next.length) break; + depth++; + frontier = next; + } + return depth; + }, + getModuleId(index) { + const f = v.facts(v.idOf(index)); + const m = v.moduleProp && f.links.find((l) => l.p === v.moduleProp.id); + return m ? v.idx(m.t) : 0; + }, + getStatus(index) { return v.facts(v.idOf(index)).row.active ? 0 : 1; }, + getRefsets(index) { + const id = v.idOf(index); + return v.h.lazy(() => v.refsetsOf(id)); + }, + getNormalForm() { return 0; }, // ECL never reads normal forms (expressions do: sct-native.js) + getStems() { return 0; } + }; + return self; +} + +function relationships(v) { + return { + getRelationship: (index) => v.relationship(index), + // the fields relationship matching needs (main's getRelationshipCore, 1.0.5) + getRelationshipCore: (index) => { + const r = v.relationship(index); + return { source: r.source, target: r.target, relType: r.relType, active: r.active, group: r.group }; + }, + // main's getConceptRelationships keeps active rows only (cs-snomed.js, #331) + isActive: (index) => v.relationship(index).active, + count: () => v.rels.length + }; +} + +function descriptions(v) { + return { + count: () => 0, + getDescription: (index) => v.description(index / DESC_SIZE), + conceptByIndex: (index) => v.description(index / DESC_SIZE).concept + }; +} + +function descriptionIndex() { + // not built over the file: the engine answers {{ D id = ... }} itself (item external ids) + return { findDescription: () => ({ found: false, index: 0 }), count: () => 0 }; +} + +/** reference sets: one record per refset (record relation, or member set), members sorted by ref */ +function refSetIndexAndMembers(v) { + const S = v.store; + let list = null; + const load = () => { + if (list) return list; + const defs = S.refsetDefs(); + const ids = [...defs.keys()]; + // simple reference sets are kept only as stored sets (refset sets) + for (const id of S.refsetIds()) if (!ids.includes(id)) ids.push(id); + const md = S.moduleDependencies; + list = ids.sort((a, b) => a - b).map((rid) => { + const def = defs.get(rid); + const names = def ? def.names : []; + const types = def ? def.types : []; + const code = v.code(rid); + return { + definition: v.idx(rid), filename: v.h.value(''), name: v.h.value(nameFor(code, names)), + fieldTypes: v.h.value(types.map((t) => IDENTIFIER_SCHEME_TYPES[t] || 5)), + fieldNames: names.length ? v.h.value(names.map((n) => v.h.value(n))) : 0, + membersByRef: v.h.lazy(() => members(rid, names, types)), + membersByName: NO, langs: 0 + }; + }); + if (md && md.length) { + // module dependencies (meta moduleDependencies): main's ModuleDependency refset, members by the row's module + list.push({ + definition: NO, filename: v.h.value(''), name: v.h.value('ModuleDependency'), fieldTypes: v.h.value([5, 5]), + fieldNames: v.h.value([v.h.value('sourceEffectiveTime'), v.h.value('targetEffectiveTime')]), + membersByRef: v.h.lazy(() => md.map(([module, ref, se, te]) => { + const m = v.conceptId(module); + const r = v.conceptId(ref); + return r ? { id: null, module: m ? v.idx(m) : 0, date: null, kind: 0, ref: v.idx(r), values: v.h.value([v.h.value(se || ''), 5, v.h.value(te || ''), 5]) } : null; + }).filter(Boolean).sort((a, b) => a.ref - b.ref)), + membersByName: NO, langs: 0 + }); + } + return list; + }; + const members = (rid, names, types) => { + // v4 files keep each row's effectiveTime, module and RF2 order + let rows = S.refsetMemberRows(rid); + if (!rows.length) { + const bm = S.loadSets(KIND.refset, 0, [rid]).get(rid); + rows = bm ? bm.toArray().map((c) => ({ concept_id: c, fields: '[]' })) : []; + } + const out = []; + for (const r of rows) { + const fields = JSON.parse(r.fields || '[]'); + const vals = []; + fields.forEach((x, i) => { + const t = types[i]; + if (t === 'c') { const c = v.conceptId(x); vals.push(c ? v.idx(c) : 0, 1); } + else if (t === 'i') vals.push(Number(x), 4); + else vals.push(v.h.value(String(x)), 5); + }); + const mod = r.module_id != null ? v.idx(r.module_id) : null; + out.push({ id: null, module: mod, date: r.effective_time != null ? daysOf(String(r.effective_time)) : null, kind: 0, ref: v.idx(r.concept_id), values: vals.length ? v.h.value(vals) : 0 }); + } + out.sort((a, b) => a.ref - b.ref); // stable: rows for one concept stay in RF2 order + return out; + }; + const index = { + count: () => load().length, + getReferenceSet: (i) => { const r = load()[i]; if (!r) throw new Error('Wrong length index getting snomed relationship Details'); return r; }, + getRefSetByConcept: (conceptIndex) => load().findIndex((r) => r.definition === conceptIndex), + getMembersByConcept: (conceptIndex, byName = false) => { const r = load().find((x) => x.definition === conceptIndex); return r ? (byName ? r.membersByName : r.membersByRef) : 0; } + }; + const mem = { + getMembers: (h) => (h === NO || h === 0 || h == null ? null : v.h.get(h)), + getMemberCount: (h) => (h === NO || h === 0 || h == null ? 0 : (v.h.get(h) || []).length) + }; + return { index, mem }; +} + +/** YYYYMMDD -> main's stored date (days since 1899-12-30) */ +function daysOf(s) { + const t = String(s).replace(/-/g, ''); + if (!/^\d{8}$/.test(t)) return null; + return Math.round((Date.UTC(+t.substring(0, 4), +t.substring(4, 6) - 1, +t.substring(6, 8)) - Date.UTC(1899, 11, 30)) / 86400000); +} + +function nameFor(code, names) { + if (code === '900000000000534007') return 'ModuleDependency'; + return names.length ? 'cRefset' : 'Refset'; +} + +// ---- main's services and provider over the view -------------------------------------------- + +/** + * SnomedServices (main) answering from a sqlite-v2 file. Built for one request. + * @param {import('./snomed').SnomedV2Factory} factory + */ +function servicesFor(factory) { + const store = factory.store; + if (!factory.version) factory = { store, version: () => store.version, edition: () => store.cs.edition }; + const v = new V2View(store); + // a real (empty) instance, for its class-field methods; its structures are replaced below + const sv = new SnomedServices({ identifiers: [], concreteValues: null, textIndexes: noTextIndexes() }); + sv.strings = strings(v); + sv.words = { getEntry: () => null, getString: () => '', count: () => 0 }; + sv.stems = { getEntry: () => null, getString: () => '', count: () => 0 }; + sv._textIndex = null; + sv._textIndexPromise = null; + sv.refs = refs(v); + sv.descriptions = descriptions(v); + sv.descriptionIndex = descriptionIndex(); + sv.concepts = concepts(v); + sv.relationships = relationships(v); + const rs = refSetIndexAndMembers(v); + sv.refSetIndex = rs.index; + sv.refSetMembers = rs.mem; + sv.versionUri = factory.version(); + const vd = /\/version\/(\d{8})$/.exec(sv.versionUri); + sv.versionDate = vd ? vd[1] : null; + sv.edition = factory.edition(); + sv.version = vd ? vd[1] : null; + sv.totalCount = store.conceptCount; + const isa = v.conceptId(IS_A); + sv.isAIndex = isa ? v.idx(isa) : 0; + const root = v.conceptId('138875005'); + sv.activeRoots = root ? [v.idx(root)] : []; + sv.inactiveRoots = []; + sv.defaultLanguage = languageByte(store.defaultLanguage) || 1; + sv.isTesting = /\/xsct\//.test(sv.versionUri); + sv.expressionServices = new SnomedExpressionServices({ + strings: sv.strings, words: sv.words, stems: sv.stems, refs: sv.refs, descriptions: sv.descriptions, + descriptionIndex: sv.descriptionIndex, concepts: sv.concepts, relationships: sv.relationships, + refSetMembers: sv.refSetMembers, refSetIndex: sv.refSetIndex + }, sv.isAIndex); + // whole-edition enumerations come from the stored sets, without reading each concept + sv._eclEnumerateAllConcepts = () => store.all().toArray().map((id) => v.idx(id)); + sv.activeConceptCount = () => store.active().size; + // read when first used + lazyField(sv, ['identifiersByConcept', 'conceptsByIdentifier', 'identifierModules'], () => loadIdentifiers(sv, v)); + lazyField(sv, ['concreteValues'], () => loadConcreteValues(sv, v)); + return sv; +} + +function lazyField(obj, names, load) { + let done = false; + for (const n of names) { + Object.defineProperty(obj, n, { + configurable: true, enumerable: true, + get() { + if (!done) { done = true; for (const m of names) Object.defineProperty(obj, m, { value: undefined, writable: true, configurable: true, enumerable: true }); load(); } + return obj[n]; + }, + set(x) { Object.defineProperty(obj, n, { value: x, writable: true, configurable: true, enumerable: true }); } + }); + } +} + +/** main's #loadIdentifiers, from the identifier rows (the module is the concept's) */ +function loadIdentifiers(sv, v) { + sv.identifiersByConcept = new Map(); + sv.conceptsByIdentifier = new Map(); + sv.identifierModules = new Map(); + const S = v.store; + for (const r of S.allAlternateIds()) { + const conceptId = v.code(r.concept_id); + const scheme = v.code(r.scheme_id); + const modIdx = sv.concepts.getModuleId(v.idx(r.concept_id)); + const module = modIdx ? String(sv.concepts.getConceptId(modIdx)) : ''; + const entry = { scheme, module, code: r.identifier }; + if (!sv.identifiersByConcept.has(conceptId)) sv.identifiersByConcept.set(conceptId, []); + sv.identifiersByConcept.get(conceptId).push(entry); + const key = scheme + '|' + r.identifier; + if (!sv.conceptsByIdentifier.has(key)) sv.conceptsByIdentifier.set(key, []); + sv.conceptsByIdentifier.get(key).push(conceptId); + if (!sv.identifierModules.has(module)) sv.identifierModules.set(module, new Set()); + sv.identifierModules.get(module).add(scheme); + } +} + +/** main's #loadConcreteValues, from the concept literals of attribute properties */ +function loadConcreteValues(sv, v) { + sv.concreteValues = new Map(); + const S = v.store; + if (!v.literalAttrProps.size) return; + const pids = [...v.literalAttrProps.keys()]; + const rows = S.literalRows(pids); + for (const r of rows) { + const type = v.conceptId(v.literalAttrProps.get(r.property_id)); + if (!type) continue; + let value; + if (typeof r.value === 'number') value = { kind: 'number', value: r.value, decimal: !Number.isInteger(r.value) }; + else if (/^#-?\d+(\.\d+)?$/.test(String(r.value))) value = { kind: 'number', value: Number(String(r.value).substring(1)), decimal: String(r.value).includes('.') }; + else if (/^(true|false)$/i.test(String(r.value))) value = { kind: 'boolean', value: String(r.value).toLowerCase() === 'true' }; + else value = { kind: 'string', value: String(r.value).replace(/^"(.*)"$/, '$1') }; + const src = v.idx(r.concept_id); + const list = sv.concreteValues.get(src) || []; + list.push({ relType: v.idx(type), group: r.group_id || 0, concrete: value }); + sv.concreteValues.set(src, list); + } +} + +/** + * An ECL expression the engine does not evaluate itself, by main's ECL over this file: the concept + * ids (a bitmap). Errors are main's (INVALID_ECL / UNSUPPORTED_ECL). + */ +/** an empty text index section (main's ECL only uses it to narrow term filters: none, no narrowing) */ +let NO_TEXT_INDEXES = null; +function noTextIndexes() { + return NO_TEXT_INDEXES || (NO_TEXT_INDEXES = new SnomedTextIndexes([], new Map()).serialize()); +} + +async function evaluateEcl(store, text, opContext) { + const { ECLLexer, ECLParser } = require('../sct/ecl'); + const sv = servicesFor({ store }); + const ast = new ECLParser(new ECLLexer(text).tokenize()).parse(); + const ctx = await sv._evalECLNode(ast, opContext || null); + if (ctx.eclWildcard && !(ctx.descendants && ctx.descendants.length)) return store.all(); + return new RoaringBitmap32(sv._eclToIndexArray(ctx).map((i) => i / CONCEPT_SIZE + 1)); +} + +// ---- results kept per file, for the synchronous compiler ------------------------------------ + +const KEPT_RESULTS = 64; // per file; the oldest is let go first + +/** A compile needs main's ECL result for `text`, not evaluated yet: resolve() it and compile again */ +class NeedsMainEcl extends Error { + constructor(store, text) { + super(`main's ECL has not evaluated ${text.slice(0, 60)} yet`); + this.needsMainEcl = true; + this.resolve = () => resolveMainEcl(store, text); + } +} + +/** the kept result for `text`: {bm} or {err}; undefined if not evaluated */ +function mainEclResult(store, text) { + return store._mainEcl ? store._mainEcl.get(text) : undefined; +} + +/** evaluate `text` with main's ECL and keep the result (or the error it throws) */ +async function resolveMainEcl(store, text) { + const kept = store._mainEcl || (store._mainEcl = new Map()); + if (kept.has(text)) return; + let entry; + try { + entry = { bm: await evaluateEcl(store, text, null) }; + } catch (err) { + entry = { err }; + } + if (kept.size >= KEPT_RESULTS) kept.delete(kept.keys().next().value); + kept.set(text, entry); +} + +module.exports = { evaluateEcl, mainEclResult, resolveMainEcl, NeedsMainEcl }; diff --git a/tx/sqlite-v2/sct-native.js b/tx/sqlite-v2/sct-native.js new file mode 100644 index 00000000..aeced27d --- /dev/null +++ b/tx/sqlite-v2/sct-native.js @@ -0,0 +1,512 @@ +'use strict'; + +// Native SNOMED CT post-coordination on a sqlite-v2 file: expressions are parsed with the +// compositional-grammar parser (tx/sct/expressions.js), and checked, normalised, compared and +// rendered by NativeExpressionServices. That class keeps main's expression algorithms (it extends +// SnomedExpressionServices) but answers every data question from the engine and the file: +// - a concept "reference" is its concept id; +// - definitions are the concept's active links; is-a and descendants are the stored sets; +// - normal forms are read from ix_key 'normalForm', which the importer fills (buildNormalForms); +// - the MRCM rules come from the MRCM reference sets' records, parsed once per file (store._nativeMrcm: file-load +// data, like the LOINC order rank); +// - an MRCM range or an ECL value-set constraint is evaluated by the engine's own ECL. +// Membership of an expression in an ECL constraint (exprSatisfies) and the edition and +// identifier translations are implemented here over the same data. +// +// One instance per request (no state kept between requests). + +const E = require('../sct/expressions'); +const { ECLLexer, ECLParser, ECLNodeType, ECLTokenType } = require('../sct/ecl'); +const { KIND } = require('./store'); +const { wildTermMatcher } = require('../sct/ecl'); + +const IS_A = '116680003'; +const PRIMITIVE = '900000000000074008'; +const ROOT = '138875005'; +const US_ENGLISH = '900000000000509007'; +const PREFERRED = '900000000000548007'; +const SYNONYM = '900000000000013009'; +const FSN = '900000000000003001'; +const MRCM_ATTRIBUTE_DOMAIN = '723561005'; +const MRCM_ATTRIBUTE_RANGE = '723562003'; +const CONTENT_ALL = '723596005'; +const CONTENT_POST = '723595009'; +const STRENGTH_OPTIONAL = '723598006'; +const NO_REFERENCE = E.NO_REFERENCE; + +class NativeExpressionServices extends E.SnomedExpressionServices { + /** + * @param {import('./store').Store} store + * @param {{building?: boolean, compilerFor?: function}} opts + */ + constructor(store, opts = {}) { + super({}, null); + this.S = store; + this.building = !!opts.building; + this._log = { warn() { } }; // main's log is a getter that fetches the logger when _log is unset (#379) + this.defaultLanguage = 1; + this.assumeClassified = true; + this.relationships = { getRelationship: (r) => r }; // relationships are records here + this.ids = new Map(); // code -> concept_id | null + this.facts = new Map(); // concept_id -> { code, active, links, primitive, module, display } + this.nf = new Map(); // concept_id -> rendered normal form (building mode) + this.ecl = new Map(); // constraint text -> bitmap | null + this.compilerFor = opts.compilerFor || null; + this.isAIndex = this.id(IS_A); + this.eclConstraintMatcher = (constraint, value) => this.rangeSatisfied(constraint, value); + this.conceptList = { findConcept: (code) => { const id = this.id(String(code)); return id == null ? { found: false, index: 0 } : { found: true, index: id }; } }; + } + + // ---- data ----------------------------------------------------------------------------- + + id(code) { + const c = String(code); + if (!this.ids.has(c)) this.ids.set(c, this.S.idOf(c)); + return this.ids.get(c); + } + + fact(id) { + let f = this.facts.get(id); + if (f) return f; + const S = this.S; + const row = S.conceptRows([id]).get(id); + if (!row) throw new Error(`Concept ${id} not found`); + const links = S.linksFrom([id], null, true); + const props = S.propsById; + let primitive = false; + let module = null; + const defs = []; + for (const l of links) { + const p = props.get(l.p); + if (!p) continue; + if (p.code === 'definitionStatusId') primitive = S.conceptRows([l.t]).get(l.t).code === PRIMITIVE; + else if (p.code === 'moduleId') module = l.t; + else if (p.attribute && p.code !== IS_A && p.kind === 'concept') defs.push({ relType: this.id(p.code), target: l.t, group: l.g || 0, active: true, defining: true, source: id }); + } + f = { code: row.code, active: !!row.active, display: row.display, links, primitive, module, defs }; + this.facts.set(id, f); + return f; + } + + descendants(id) { return this.S.getSet(KIND.descendants, 0, id); } + + // ---- what main's algorithms ask of the data ------------------------------------------- + + getConceptId(ref) { return this.fact(ref).code; } + conceptIndexOf(conceptId) { const id = this.id(String(conceptId)); return id == null ? null : id; } + isPrimitive(ref) { return this.fact(ref).primitive; } + isActive(ref) { return this.fact(ref).active; } + moduleOf(ref) { return this.fact(ref).module; } + + getConceptParents(ref) { + const isa = this.S.hierarchy.id; + return this.fact(ref).links.filter((l) => l.p === isa).map((l) => l.t); + } + + getConceptChildren(ref) { return this.S.getSet(KIND.prop, this.S.hierarchy.id, ref).toArray(); } + + subsumes(a, b) { return a === b || this.descendants(a).has(b); } + + getDefiningRelationships(ref) { return this.fact(ref).defs; } + + /** the normal form: stored at import (ix_key 'normalForm'); computed when building it */ + createNormalForm(ref) { + if (this.building) { + let s = this.nf.get(ref); + if (s === undefined) { + this.nf.set(ref, null); // a definition cycle reads as the concept itself + const exp = new E.SnomedExpression(); + this.createDefinedExpression(ref, exp, false); + s = this.renderExpression(this.normaliseExpression(exp), E.SnomedServicesRenderOption.Minimal); + this.nf.set(ref, s); + } + const r = new E.SnomedExpressionParser(this.conceptList).parse(s || this.getConceptId(ref)); + return r; + } + const nf = this.S.normalFormOf(ref); + const r = new E.SnomedExpressionParser().parse(nf || this.getConceptId(ref)); + this.resolveExpressionReferences(r); + return r; + } + + checkConcept(concept, limits) { + if (concept.code) { + const id = this.id(concept.code); + if (id != null) concept.reference = id; + else if (concept.code !== '111115') throw new Error(`Concept ${concept.code} not found`); + } + if (limits && concept.reference && concept.reference !== NO_REFERENCE) { + let ok = false; + for (const limit of limits) { + const lid = this.id(String(limit)); + if (lid != null && this.descendants(lid).has(concept.reference)) { ok = true; break; } + } + if (!ok) { + const desc = this.describeConceptForMessage(concept.reference); + const limitDesc = limits.map((l) => { const ix = this.conceptIndexOf(String(l)); return ix === null ? String(l) : this.describeConceptForMessage(ix); }); + if (limits.length === 1) throw new Error(`Concept ${desc} is not valid in this context (must be a descendant of ${limitDesc[0]})`); + throw new Error(`Concept ${desc} is not valid in this context (must be a descendant of one of ${limitDesc.join(', ')})`); + } + } + if (concept.reference !== NO_REFERENCE && concept.reference && concept.description) { + const displayNames = this.listDisplayNames(concept.reference, 0); + const wanted = this.normalizeText(concept.description); + const ok = displayNames.some((d) => this.normalizeText(d.term) === wanted); + if (!ok) { + const validTerms = displayNames.map((d) => d.term).join('", "'); + throw new Error(`Term "${concept.description}" doesn't match a defined term at position ${concept.start} (valid terms would be from this list: "${validTerms}")`); + } + } + } + + /** active FSNs and synonyms, in description order, the US English preferred synonym marked */ + listDisplayNames(ref) { + const S = this.S; + const rows = S.designationRows([ref], null, { withAcc: true }).get(ref) || []; + const us = this.id(US_ENGLISH); + const pref = this.id(PREFERRED); + const out = []; + for (const d of rows) { + if (!d.active || !d.use || (d.use.code !== SYNONYM && d.use.code !== FSN)) continue; + const accs = d.acc ? String(d.acc).split(',').map((x) => x.split(':').map(Number)) : []; + const isPreferred = d.use.code === SYNONYM && accs.some(([r, a]) => r === us && a === pref); + out.push({ isPreferred, isActive: true, languageCode: String(d.language || 'en').split('-')[0], term: d.term.trim() }); + } + // (in description order, as main lists them: messages name a concept by the first) + if (!out.length) { + const f = this.fact(ref); + if (f.display) out.push({ isPreferred: true, isActive: true, languageCode: 'en', term: f.display }); + } + return out; + } + + getDisplayName(conceptIdOrReference) { + const ref = typeof conceptIdOrReference === 'string' ? this.id(conceptIdOrReference) : conceptIdOrReference; + if (ref == null) return ''; + const names = this.listDisplayNames(ref); + const p = names.find((d) => d.isPreferred); + return p ? p.term : (names[0] ? names[0].term : ''); + } + + describeConceptForMessage(ref) { + const id = this.getConceptId(ref); + const names = this.listDisplayNames(ref); + return names.length && names[0].term ? `${id} |${names[0].term}|` : id; + } + + conceptInRefSet(refSetConcept, ref) { return this.S.getSet(KIND.refset, 0, refSetConcept).has(ref); } + + findRefSetByConceptId(conceptId) { + const id = this.conceptIndexOf(String(conceptId)); + return id != null && this.S.getSet(KIND.refset, 0, id).size ? { definition: id } : null; + } + + /** the MRCM rules of the file, parsed once per file (file-load data) */ + mrcm() { + const S = this.S; + if (S._nativeMrcm) return S._nativeMrcm; + const domains = new Map(); + const ranges = new Map(); + const parseMax = (t) => { const m = /^\s*\d+\s*\.\.\s*(\d+|\*)\s*$/.exec(t || ''); return !m || m[1] === '*' ? Infinity : parseInt(m[1], 10); }; + const all = this.id(CONTENT_ALL); + const post = this.id(CONTENT_POST); + const optional = this.id(STRENGTH_OPTIONAL); + const rows = (rid) => (rid == null ? [] : S.refsetMemberRows(rid)); + const refsets = new Set(S.refsetIds()); + for (const r of rows(this.id(MRCM_ATTRIBUTE_DOMAIN))) { + // domainId, grouped, attributeCardinality, attributeInGroupCardinality, ruleStrengthId, contentTypeId + const [domainId, grouped, card, inGroup, strength, content] = JSON.parse(r.fields); + const ct = this.id(content); + if (ct !== all && ct !== post) continue; + const domain = this.id(domainId); + if (domain == null) continue; + if (!domains.has(r.concept_id)) domains.set(r.concept_id, []); + domains.get(r.concept_id).push({ domain, isRefset: refsets.has(domain), grouped: String(grouped) === '1', optional: this.id(strength) === optional, max: parseMax(card), maxInGroup: parseMax(inGroup) }); + } + const fromPost = new Set(); + for (const r of rows(this.id(MRCM_ATTRIBUTE_RANGE))) { + // rangeConstraint, attributeRule, ruleStrengthId, contentTypeId + const [constraint, , , content] = JSON.parse(r.fields); + const ct = this.id(content); + if (ct !== all && ct !== post) continue; + if (ranges.has(r.concept_id) && fromPost.has(r.concept_id) && ct !== post) continue; + if (!constraint) continue; + ranges.set(r.concept_id, constraint); + if (ct === post) fromPost.add(r.concept_id); + } + S._nativeMrcm = { domains, ranges }; + return S._nativeMrcm; + } + + mrcmAttributeDomains() { return this.mrcm().domains; } + mrcmAttributeRanges() { return this.mrcm().ranges; } + + // ---- ECL through the engine ----------------------------------------------------------- + + /** the concepts an ECL constraint selects (engine), or null when the engine cannot say */ + async eclSet(text) { + if (this.ecl.has(text)) return this.ecl.get(text); + let bm = null; + for (let tries = 0; ; tries++) { + try { + const c = this.compilerFor(); + bm = c.engineFor().evaluate(c.ecl(text)); + } catch (e) { + // ECL only main's (async) evaluator answers: evaluate it, then compile again + if (e && e.needsMainEcl && tries < 16) { + await e.resolve(); + continue; + } + bm = null; + } + break; + } + this.ecl.set(text, bm); + return bm; + } + + evalNode(node) { + const c = this.compilerFor(); + return c.engineFor().evaluate(c.eclNode(node)); + } + + /** does a refinement value satisfy an MRCM range constraint? null: cannot say (a concrete range) */ + async rangeSatisfied(constraint, value) { // awaited by main's checkRefinementRange (1.0.5) + const set = await this.eclSet(constraint); + if (!set) return null; + const concepts = (value.concepts || []).filter((c) => c.reference != null && c.reference !== NO_REFERENCE); + const refined = value.hasRefinements() || value.hasRefinementGroups(); + if (!refined) { + if (!concepts.length) return null; + return concepts.every((c) => set.has(c.reference)); + } + let ast; + try { ast = new ECLParser(new ECLLexer(constraint).tokenize()).parse(); } catch (e) { return null; } + return this.exprSatisfies(value, ast); + } + + // ---- an expression against an ECL constraint ------------------------------------------ + + /** relationship records of an expression: its focus concepts' (and their inbound) plus its own */ + exprRels(expression) { + const rels = []; + const S = this.S; + for (const c of expression.concepts || []) { + if (c.reference == null || c.reference === NO_REFERENCE) continue; + for (const d of this.fact(c.reference).defs) rels.push(d); + for (const l of S.literalsOf([c.reference], true)) { + const p = S.propsById.get(l.p); + if (!p || !p.attribute) continue; + rels.push({ active: true, relType: this.id(p.code), group: l.g || 0, target: -1, concrete: concreteOf(p, l.v) }); + } + } + // inbound relationships (for reversed attributes) are read only when one is asked about + // (ix_in, the links of the by-target properties) + const focus = (expression.concepts || []).map((c) => c.reference).filter((r) => r != null && r !== NO_REFERENCE); + Object.defineProperty(rels, 'inbound', { value: () => { + const out = []; + for (const ref of focus) { + for (const r of S.linksTo(ref, true)) { + const p = S.propsById.get(r.p); + if (!p || !p.attribute || p.code === IS_A) continue; + out.push({ active: true, relType: this.id(p.code), group: r.g, source: r.s, target: ref, inbound: true }); + } + } + return out; + } }); + let maxGroup = 0; + for (const r of rels) if (r.group > maxGroup) maxGroup = r.group; + const toRel = (ref, g) => { + const t = ref.name ? ref.name.reference : NO_REFERENCE; + const v = ref.value && ref.value.concepts && ref.value.concepts.length ? ref.value.concepts[0].reference : NO_REFERENCE; + return t === NO_REFERENCE || v === NO_REFERENCE ? null : { active: true, relType: t, target: v, group: g }; + }; + for (const ref of expression.refinements || []) { const r = toRel(ref, 0); if (r) rels.push(r); } + let g = maxGroup; + for (const grp of expression.refinementGroups || []) { + g += 1; + for (const ref of grp.refinements || []) { const r = toRel(ref, g); if (r) rels.push(r); } + } + return rels; + } + + exprSatisfies(expr, node) { + return this.exprNode(expr, this.exprRels(expr), node); + } + + exprNode(expr, rels, node) { + if (!node) return false; + switch (node.type) { + case ECLNodeType.SUB_EXPRESSION_CONSTRAINT: { + const f = node.focus; + if (f.type === ECLNodeType.WILDCARD) return true; + if (f.type === ECLNodeType.MEMBER_OF) return false; // an expression is not a refset member + if (f.type === ECLNodeType.CONCEPT_REFERENCE) return this.exprConcept(expr, f.conceptId, node.operator); + return this.exprNode(expr, rels, f); + } + case ECLNodeType.COMPOUND_EXPRESSION_CONSTRAINT: { + const l = this.exprNode(expr, rels, node.left); + const r = this.exprNode(expr, rels, node.right); + if (node.operator === ECLNodeType.CONJUNCTION) return l && r; + if (node.operator === ECLNodeType.DISJUNCTION) return l || r; + if (node.operator === ECLNodeType.EXCLUSION) return l && !r; + throw new Error(`Unsupported ECL compound operator: ${node.operator}`); + } + case ECLNodeType.REFINED_EXPRESSION_CONSTRAINT: + return this.exprNode(expr, rels, node.base) && this.refinementMatches(rels, node.refinement); + case ECLNodeType.CONCEPT_REFERENCE: + return this.exprConcept(expr, node.conceptId, null); + case ECLNodeType.WILDCARD: + return true; + case ECLNodeType.MEMBER_OF: + return false; + default: + throw new Error(`Unsupported ECL node type for expression membership: ${node.type}`); + } + } + + /** a refined expression is strictly below its focus: only < and << can hold */ + exprConcept(expr, conceptId, operator) { + const target = this.id(conceptId); + if (target == null) throw new Error(`The SNOMED CT Concept ${conceptId} is not known`); + const focus = (expr.concepts || []).map((c) => c.reference).filter((r) => r != null && r !== NO_REFERENCE); + if (!focus.length) return false; + const subsumed = focus.every((f) => this.subsumes(target, f)); + return (operator === ECLTokenType.DESCENDANT_OR_SELF_OF || operator === ECLTokenType.DESCENDANT_OF) ? subsumed : false; + } + + refinementMatches(rels, r) { + switch (r.type) { + case ECLNodeType.ATTRIBUTE: return this.attributeMatches(rels, r, null); + case ECLNodeType.ATTRIBUTE_SET: + return r.operator === 'OR' ? r.attributes.some((a) => this.refinementMatches(rels, a)) : r.attributes.every((a) => this.refinementMatches(rels, a)); + case ECLNodeType.ATTRIBUTE_GROUP: return this.groupMatches(rels, r); + default: throw new Error(`Unsupported refinement node type: ${r.type}`); + } + } + + inGroup(rels, node, g) { + if (node.type === ECLNodeType.ATTRIBUTE_SET) { + return node.operator === 'OR' ? node.attributes.some((a) => this.inGroup(rels, a, g)) : node.attributes.every((a) => this.inGroup(rels, a, g)); + } + if (node.type !== ECLNodeType.ATTRIBUTE) throw new Error(`Unsupported node type in attribute group: ${node.type}`); + return this.attributeMatches(rels, node, g); + } + + attributeMatches(rels, attr, groupFilter) { + if (!attr.comparison) throw new Error('ECL attribute without a comparison is not supported'); + const n = this.countMatches(rels, attr, groupFilter); + return attr.cardinality ? accepts(attr.cardinality, n) : n >= 1; + } + + countMatches(rels, attr, groupFilter) { + let res = attr._native; + if (!res) { + res = { types: this.attributeTypes(attr.name) }; + if (attr.comparison.type === ECLNodeType.EXPRESSION_COMPARISON) res.values = this.evalNode(attr.comparison.value); + else res.concrete = concreteMatcher(attr.comparison); + attr._native = res; + } + const matched = new Set(); + if (res.concrete) { + for (const rel of rels) { + if (!rel.concrete || (res.types && !res.types.has(rel.relType))) continue; + if (groupFilter !== null && rel.group !== groupFilter) continue; + if (res.concrete(rel.concrete)) matched.add(rel.group + ':' + JSON.stringify(rel.concrete.value)); + } + return matched.size; + } + const notEquals = attr.comparison.operator === ECLTokenType.NOT_EQUALS; + const reverse = !!attr.reverse; + if (reverse && rels.inbound && !rels._inboundRead) { rels.push(...rels.inbound()); rels._inboundRead = true; } + for (const rel of rels) { + if (!rel.active || rel.concrete || !!rel.inbound !== reverse) continue; + if (res.types && !res.types.has(rel.relType)) continue; + if (groupFilter !== null && rel.group !== groupFilter) continue; + const v = reverse ? rel.source : rel.target; + if (res.values.has(v) !== notEquals) matched.add(rel.group + ':' + v); + } + return matched.size; + } + + attributeTypes(name) { + if (name.type === ECLNodeType.WILDCARD) return null; + if (name.type === ECLNodeType.CONCEPT_REFERENCE) { + const id = this.id(name.conceptId); + if (id == null) throw new Error(`The SNOMED CT Concept ${name.conceptId} is not known`); + return new Set([id]); + } + return new Set(this.evalNode(name).toArray()); + } + + groupMatches(rels, group) { + const groups = new Set(rels.filter((r) => r.active && r.group > 0).map((r) => r.group)); + let n = 0; + for (const g of groups) { + if (group.attributes.every((a) => this.inGroup(rels, a, g))) { + n++; + if (!group.cardinality) return true; + } + } + return group.cardinality ? accepts(group.cardinality, n) : false; + } +} + +function accepts(card, n) { + if (card.min != null && n < card.min) return false; + if (card.max != null && card.max !== '*' && n > card.max) return false; + return true; +} + +function concreteOf(p, v) { + if (p.type === 'boolean') return { kind: 'boolean', value: v === 1 || v === '1' || v === 'true' }; + if (p.type === 'string') return { kind: 'string', value: String(v) }; + return { kind: 'number', value: Number(v) }; +} + +function concreteMatcher(c) { + const cmp = (a, op, b) => ({ '=': a === b, '!=': a !== b, '<': a < b, '<=': a <= b, '>': a > b, '>=': a >= b })[op]; + const opOf = { [ECLTokenType.EQUALS]: '=', [ECLTokenType.NOT_EQUALS]: '!=', [ECLTokenType.LT]: '<', [ECLTokenType.LTE]: '<=', [ECLTokenType.GT]: '>', [ECLTokenType.GTE]: '>=' }; + const op = opOf[c.operator] || c.operator; + if (c.type === ECLNodeType.NUMERIC_COMPARISON) { const n = Number(c.value); return (v) => v.kind === 'number' && cmp(v.value, op, n); } + if (c.type === ECLNodeType.BOOLEAN_COMPARISON) return (v) => v.kind === 'boolean' && ((op === '=') === (v.value === c.value)); + const vals = (c.values || []).map((x) => (typeof x === 'object' ? x : { kind: 'exact', value: x })); + const test = (s) => vals.some((x) => { + if (x.kind === 'wild') return wildTermMatcher(String(x.value))(s); // main's matcher: see compile.js termMatcher + if (x.kind === 'match') { const w = x.value.toLowerCase().split(/\s+/).filter(Boolean); const tw = s.toLowerCase().split(/[^\p{L}\p{N}]+/u); return w.every((a) => tw.some((b) => b.startsWith(a))); } + return s === x.value; + }); + return (v) => v.kind === 'string' && (op === '=' ? test(v.value) : !test(v.value)); +} + +/** + * Normal forms at import: every active, fully defined concept whose normal form differs from its + * own id, rendered in the minimal form (as main stores them), each through opts.write(id, nf) + * (the importer's derived-by-importer ix_key rows: sct-v2-common.js derivedIndexes). + * @returns {{written: number, failed: number}} + */ +function buildNormalForms(store, db, log = () => { }, opts = {}) { + const ins = { run: opts.write }; + const svc = new NativeExpressionServices(store, { building: true }); + const ids = store.active().toArray(); + let n = 0; + let failed = 0; + db.exec('BEGIN'); + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + try { + if (svc.isPrimitive(id)) continue; + const nf = svc.createNormalForm(id); + const rendered = svc.renderExpression(nf, E.SnomedServicesRenderOption.Minimal); + if (rendered !== svc.getConceptId(id)) { ins.run(id, rendered); n++; } + } catch (e) { + failed++; + } + if (svc.facts.size > 200000) { svc.facts.clear(); } + if (i % 50000 === 0 && i) log(` normal forms: ${i.toLocaleString()} / ${ids.length.toLocaleString()}`); + } + db.exec('COMMIT'); + return { written: n, failed }; +} + +module.exports = { NativeExpressionServices, buildNormalForms, ROOT }; diff --git a/tx/sqlite-v2/settings.js b/tx/sqlite-v2/settings.js new file mode 100644 index 00000000..19f4760d --- /dev/null +++ b/tx/sqlite-v2/settings.js @@ -0,0 +1,38 @@ +'use strict'; +// The providers' limits. Nothing in the server configuration sets them: these are the values +// every sqlite-v2 provider runs with (a test may change one for its run). +// +// maxScanRows planner estimate of fact rows a request may read (text/regex scans, +// relation images, per-candidate probes); beyond it the request is +// too-costly before any work is done. 5,000,000. +// +// Response sizes are upstream's (expand.js limitCount): a provider-selected page is added +// through the same includeCode as every other code. Totals come from set cardinalities and +// pages are by position (cs-api processSelection). The providers keep one cache, of built +// supplement layers (supplementLayerCacheMB); otherwise every request plans and evaluates, reading +// stored sets from SQLite (SQLite's page cache and the OS page cache under mmap). +// +// supplementLayerCacheMB memory for built supplement layers kept between requests (layers.js +// LayerCache, one per process): their SQLite pages, about 120 bytes per +// concept with one designation, 360 with five. 64: about 530k such +// concepts, two layers the size of all of LOINC (257k) or hundreds of the IG +// corpus's (99% have 1,001 concepts or fewer). Least recently used layers are +// dropped to stay under it; a layer bigger than the whole bound is built per +// request and not kept. 0 = keep none. +// sqliteCacheKB SQLite page cache per connection. 2,048 (2 MiB): reads use mmap. +// mmapMB SQLite mmap window per file. 2047: the whole file (SQLite maps no more +// than the file, and at most 2 GiB). File-backed: the pages are the OS page cache, +// shared by every process that reads the file, and reclaimable. A smaller window +// sends reads beyond it through pread() into the 2 MiB page cache, which a +// SNOMED CT file (700+ MiB) misses on most requests. + +const settings = { maxScanRows: 5000000, supplementLayerCacheMB: 64, sqliteCacheKB: 2048, mmapMB: 2047 }; + +class TooCostly extends Error { + constructor(message) { + super(message); + this.tooCostly = true; + } +} + +module.exports = { settings, TooCostly }; diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js new file mode 100644 index 00000000..fdd5356b --- /dev/null +++ b/tx/sqlite-v2/snomed.js @@ -0,0 +1,981 @@ +'use strict'; +// SNOMED CT on sqlite-v2: editions and versions, display and designation rules, $lookup +// properties, ECL error reporting, implicit value sets (?fhir_vs...) and the implicit concept +// maps of the historical association reference sets (?fhir_cm=...). Semantics follow +// tx/cs/cs-snomed.js; membership comes from the engine like every other system. + +const { SqliteV2Provider, SqliteV2Factory } = require('./provider'); +const { KIND } = require('./store'); +const { Issue } = require('../library/operation-outcome'); +const { ECLLexer, ECLParser } = require('../sct/ecl'); +const { ConceptMap } = require('../library/conceptmap'); +const { editionName, editionCode } = require('../sct/editions'); +const { formatDateMMDDYYYY } = require('../../library/utilities'); + +const SCT = 'http://snomed.info/sct'; +const FSN = '900000000000003001'; +const SYNONYM = '900000000000013009'; +const PREFERRED = '900000000000548007'; +const IS_A = '116680003'; +const ASSOCIATIONS = { + '900000000000523009': ['POSSIBLY EQUIVALENT TO', 'inexact'], + '900000000000526001': ['REPLACED BY', 'equivalent'], + '900000000000527005': ['SAME AS', 'equal'], + '900000000000530003': ['ALTERNATIVE', 'inexact'] +}; +const IDENTIFIER_SCHEMES = { '30051010000102': { system: 'http://loinc.org', property: 'loinc' } }; +// whether props names this property explicitly (property=* does not count) +const askedFor = (props, name) => !!props && props.some((p) => p && String(p).toLowerCase() === name.toLowerCase()); +// cs-snomed.js stringToIdOrZero: a code is a concept id when BigInt() reads it as a number other +// than 0 (digits with spaces or leading zeros, but also +22298006 or 0x1543d96); anything else is +// an expression. The id as stored, or null +const sctIdOf = (code) => { + const s = String(code); + if (!s.trim()) return null; + try { + const n = BigInt(s); + return n === 0n ? null : n.toString(); + } catch { + return null; + } +}; +const isConceptId = (code) => sctIdOf(code) != null; +// post-coordinated expressions and the edition / identifier translations: sct-native.js, over +// this file (stored normal forms, MRCM from the file) +const native = require('./sct-native'); +const E = require('../sct/expressions'); +const { cannotDetermineSubsumption } = require('../cs/cs-api'); +const { DesignationUse } = require('../library/designations'); +const { LANGUAGE_REFSET_DIALECTS } = require('../cs/cs-snomed'); + +/** an expression located natively */ +class NativeExprContext { + constructor(source, expression) { + this.source = source; + this.code = source; + this.expression = expression; + } + isComplex() { return this.expression.isComplex(); } + getReference() { return this.expression.concepts[0].reference; } +} + +class SnomedV2Provider extends SqliteV2Provider { + name() { return `SNOMED CT ${editionName(this.f.edition()) || 'Unknown Edition'}`; } + description() { return this.name(); } + lookupName() { return this.name(); } + versionAlgorithm() { return 'url'; } + isNotClosed() { return true; } + hasParents() { return true; } + hasMultiHierarchy() { return true; } + + versionIsMoreDetailed(check, actual) { + return !!actual && !!check && actual.startsWith(check); + } + + hasAnyDisplays(languages) { + const langs = this._ensureLanguages(languages); + if (this._hasAnySupplementDisplays(langs)) return true; + return langs.isEnglishOrNothing(); + } + + normaliseCode(code) { + // as BigInt(code) (sctIdOf) + const id = sctIdOf(code); + return id != null ? id : String(code).trim(); + } + + /** a concept id as stored: an expression, or an id with spaces or leading zeros, goes through locate() */ + _plainListedCode(code) { return typeof code === 'string' && /^[1-9]\d*$/.test(code); } + + /** native expression services for this request */ + _native() { + if (!this._nativeSvc) { + this._nativeSvc = new native.NativeExpressionServices(this.store, { + compilerFor: () => { const c = this._compiler(); c.engineFor = () => this.engine; return c; } + }); + } + return this._nativeSvc; + } + + async _locate(code, prefetched = null) { + if (code == null || code === '') return { context: null, message: 'Empty code' }; + if (!isConceptId(code)) return this._nativeLocate(String(code)); + const r = await super._locate(code, prefetched); + if (r.context) r.context.code = r.context.row ? r.context.row.code : r.context.code; + return r; + } + + isDisplay(d) { + return !!(d && d.use && d.use.system === SCT && (d.use.code === SYNONYM || d.use.code === FSN)); + } + + /** + * Each designation's acceptability as [[refset id, acceptability id], ...] (d.accs). The + * designations come with their rank and not their acceptability (store.designationRows); the + * dialect rules below need to know which language reference set prefers which term, so the + * concept's acceptability rows are read here, in one statement, for the concepts that have two + * preferred terms in one language or an edition with more than one display reference set. + */ + _needAcceptability(c) { + if (c.accsRead) return; + c.accsRead = true; + const parse = (acc) => (acc ? String(acc).split(',').map((x) => x.split(':').map(Number)) : []); + if (!this.store.hasAcceptability || c.desigs.every((d) => d.acc != null)) { + for (const d of c.desigs) d.accs = parse(d.acc); + return; + } + const by = this.store.acceptabilityOfConcept(c.id); + for (const d of c.desigs) d.accs = by.get(d.id) || []; + } + + /** + * As cs-snomed.js designations(): English dialects. Where the International edition's US and GB + * English reference sets prefer different terms, both are preferred synonyms in language 'en'. + * The one preferred in the edition's display reference set stands for the language (and is the + * display); the other is reported under its dialect's tag (en-GB), so that a request for that + * dialect gets it. + */ + async _designations(context, displays, significantOnly = false) { + const c = await this._ensure(context); + if (!c) return; + if (!c.desigs && c.displayOnly && !this._displayOnlyNeedsDialects()) { + this._displayOnly(c, displays); + return; + } + this._needDesigs(c); + const refsets = this.f.displayRefsetIds(); + const preferred = this.f.preferredId(); + const isPreferredIn = (d, ids) => !!d.acc && d.acc.split(',').some((a) => { const [r, v] = a.split(':'); return v === String(preferred) && (!ids || ids.includes(Number(r))); }); + // the rank the builder derived (0 preferred in a display refset, 1 in another, 2 not); from the + // acceptability where an item has none + const rankOf = (d) => (d.rank != null ? d.rank : (!d.use || d.use.code !== SYNONYM ? 2 : isPreferredIn(d, refsets) ? 0 : isPreferredIn(d, null) ? 1 : 2)); + const use = (d) => (d.use ? { system: SCT, code: d.use.code, display: d.use.display } : null); + // the active preferred synonyms; which reference set prefers which matters when a language + // has two of them, or the edition has more than one display reference set to choose between + const prefs = c.desigs.filter((d) => d.active && d.use && d.use.code === SYNONYM && rankOf(d) <= 1); + const dialects = this.f.dialectRefsets(); + const detailed = refsets.length > 1 || new Set(prefs.map((d) => d.language)).size < prefs.length; + if (detailed) this._needAcceptability(c); + const prefersIn = (d, refset) => d.accs.some(([r, v]) => r === refset && v === preferred); + // the position of the first display reference set that prefers the designation (cs-snomed.js _displayRefsetRank) + const displayRank = (d) => { + if (!detailed) return rankOf(d) === 0 ? 0 : Infinity; + const i = refsets.findIndex((r) => prefersIn(d, r)); + return i < 0 ? Infinity : i; + }; + // the dialects a designation is the preferred term of (cs-snomed.js _preferredDialects) + const dialectsOf = (d) => (detailed ? dialects.filter((x) => x.lang === d.language && prefersIn(d, x.id)).map((x) => x.tag) : []); + if (significantOnly) { + // the display's tag: the dialect of the display reference set that chose it, or else the + // language of the term (cs-snomed.js getDisplayNameEx, with its fallbacks: a synonym + // preferred in any reference set, the FSN, the first active description) + const tagOf = (d, x) => (x && x.lang === d.language ? x.tag : d.language === 'en' ? 'en-US' : d.language); + let tag = null; + for (let i = 0; i < refsets.length && !tag; i++) { + const d = prefs.find((x) => (detailed ? prefersIn(x, refsets[i]) : rankOf(x) === 0)); + if (d) tag = tagOf(d, dialects.find((e) => e.id === refsets[i])); + } + if (!tag) { + const live = c.desigs.filter((d) => d.active); + const d = prefs[0] || live.find((x) => x.use && x.use.code === FSN) || live[0]; + if (d) tag = tagOf(d, null); + } + displays.addDesignation(true, 'active', tag || 'en-US', null, c.row.display || ''); + const seenFsn = new Set(); + for (const d of c.desigs) { + if (!d.active || !d.use) continue; + if (d.use.code === FSN && !seenFsn.has(d.language)) { + seenFsn.add(d.language); + displays.addDesignation(false, 'active', d.language, use(d), d.term); + } + } + // per language, the preferred synonym the display reference sets put first; then each + // other dialect's preferred term, under the dialect's tag, where it is a different term + const prefSyns = new Map(); + const dialectSyns = new Map(); + for (const d of prefs) { + const rank = displayRank(d); + const cur = prefSyns.get(d.language); + if (!cur || rank < cur.rank) prefSyns.set(d.language, { d, rank }); + for (const t of dialectsOf(d)) if (!dialectSyns.has(t)) dialectSyns.set(t, d); + } + for (const { d } of prefSyns.values()) displays.addDesignation(false, 'active', d.language, use(d), d.term); + for (const [t, d] of dialectSyns) { + if (d.term !== prefSyns.get(d.language).d.term) displays.addDesignation(false, 'active', t, use(d), d.term); + } + } else { + // each designation ranked once, not in every comparison: preferred in a display reference + // set (in their order), then preferred in another, then the rest + const other = refsets.length; + const fine = (d) => { + const r = rankOf(d); + if (r !== 0) return other + r - 1; + const dr = displayRank(d); + return dr < other ? dr : 0; + }; + const list = c.desigs.map((d, i) => ({ d, i, r: fine(d) })).sort((a, b) => (a.r - b.r) || (a.i - b.i)); + // the first preferred synonym of a language stands for it; another is reported in its dialect + const languageTerms = new Map(); + for (const { d, r } of list) { + let language = d.language; + if (d.active && r <= other) { + const tags = dialectsOf(d); + const taken = languageTerms.get(language); + if (!taken) languageTerms.set(language, tags); + else language = tags.find((t) => !taken.includes(t)) || language; + } + displays.addDesignation(false, d.active ? 'active' : 'inactive', language, use(d), d.term); + } + } + this._listSupplementDesignations(c.code, displays); + } + + /** + * A page read for its displays only (an English-or-default request) shows the edition's display. + * That answers en-US only when the edition's display reference set is US English: an edition + * whose display is another dialect's (the UK editions: GB English) reads the designations for + * a request that names en-US, to find the US preferred term. + */ + _displayOnlyNeedsDialects() { + const d = this.f.displayDialect(); + if (!d || d === 'en-US') return false; + const langs = this.opContext && this.opContext.langs; + return !!langs && (langs.languages || []).some((l) => l.code && l.code !== '*' && l.code !== d.split('-')[0]); + } + + /** the concept's text definition (900000000000550004), as the release states it */ + async definition(context) { + const c = await this._ensure(context); + return c && c.row ? c.row.definition || null : null; + } + + async getStatus(context) { + const c = await this._ensure(context); + return c.row.active ? 'active' : 'inactive'; + } + + async isDeprecated() { return false; } + + async _extendLookup(context, props, params, noNormalForm = false) { + const c = await this._ensure(context); + if (!c) return; + const S = this.store; + const st = this._stats(); + const links = S.linksFrom([c.id], null, true, st); + // in release order where the file has it (cs-snomed.js: parents and relationships in + // relationship-file order); otherwise as read + const seqs = S.linkSeqFrom(c.id); + if (seqs) { + const at = (l) => seqs.get(l.p + ':' + (l.g || 0) + ':' + l.t) ?? Infinity; + links.sort((a, b) => at(a) - at(b)); + } + const lits = S.literalsOf([c.id], true, st); + const hid = S.hierarchy.id; + const children = S.getSet(KIND.prop, hid, c.id, st).toArray(); + const childOrder = S.linkSourcesInOrder(hid, c.id); + const want = new Set([...links.map((l) => l.t), ...children]); + const attrCodes = [...new Set(links.map((l) => S.propsById.get(l.p)).filter((p) => p && p.attribute).map((p) => p.code))]; + const attrIds = S.resolveCodes(attrCodes, st); + for (const id of attrIds.values()) want.add(id); + want.delete(undefined); + want.delete(null); + const rows = S.conceptRows([...want], st); + const disp = (id) => (rows.get(id) ? rows.get(id).display : null); + const code = (id) => (rows.get(id) ? rows.get(id).code : null); + if (this._hasProp(props, 'effectiveTime', true)) { + const et = lits.find((r) => S.propsById.get(r.p).code === 'effectiveTime'); + if (et) this._addDateTimeProperty(params, 'property', 'effectiveTime', fmtDate(String(et.v))); + } + if (this._hasProp(props, 'parent', true)) { + for (const l of links) if (l.p === hid) this._addCodeProperty(params, 'property', 'parent', code(l.t), null, disp(l.t)); + } + if (this._hasProp(props, 'child', true)) { + const byCode = (a, b) => (code(a).length - code(b).length) || (code(a) < code(b) ? -1 : code(a) > code(b) ? 1 : 0); + // release order (cs-snomed.js getConceptChildren: inbound is-a rows by row), else by code + let ordered = [...children].sort(byCode); + if (childOrder) { + const kids = new Set(children); + const inOrder = [...new Set(childOrder.filter((id) => kids.has(id)))]; + const placed = new Set(inOrder); + ordered = [...inOrder, ...ordered.filter((id) => !placed.has(id))]; + } + for (const id of ordered) this._addCodeProperty(params, 'property', 'child', code(id), null, disp(id)); + } + // moduleId, as the SNOMED CT on FHIR page names it ("module" asked for by name is still + // understood, and answered as moduleId), as main (#331) + if (this._hasProp(props, 'moduleId', true) || askedFor(props, 'module')) { + const m = links.find((l) => S.propsById.get(l.p).code === 'moduleId'); + if (m) this._addCodeProperty(params, 'property', 'moduleId', code(m.t), null, disp(m.t)); + } + // returned for property=* or by name, not by default + if (this._hasProp(props, 'sufficientlyDefined', false)) { + // SNOMED CT on FHIR: true when the concept is fully defined (definitionStatus 900000000000073002) + const ds = links.find((l) => S.propsById.get(l.p).code === 'definitionStatusId'); + if (ds) { + const dsCode = S.conceptRows([ds.t], st).get(ds.t); + params.push({ name: 'property', part: [{ name: 'code', valueCode: 'sufficientlyDefined' }, { name: 'value', valueBoolean: !!dsCode && dsCode.code === '900000000000073002' }] }); + } + } + if (this._hasProp(props, 'semanticTag', false)) { + // the bracketed suffix of the concept's active fully specified name + this._needDesigs(c); + for (const d of c.desigs || []) { + if (!d.active || !d.use || d.use.code !== FSN) continue; + const m = /\(([^()]+)\)\s*$/.exec(d.term || ''); + if (m) { + params.push({ name: 'property', part: [{ name: 'code', valueCode: 'semanticTag' }, { name: 'value', valueString: m[1] }] }); + break; + } + } + } + const seen = new Set(); + for (const l of links) { + const p = S.propsById.get(l.p); + if (!p || !p.attribute || p.code === IS_A || !this._hasProp(props, p.code, true)) continue; + const k = p.code + ':' + code(l.t); + if (seen.has(k)) continue; + seen.add(k); + const pr = this._addCodeProperty(params, 'property', p.code, code(l.t), null, disp(l.t)); + const tid = attrIds.get(p.code); + pr.part.push({ name: 'code-display', valueString: rows.get(tid) ? rows.get(tid).display : p.display || p.code }); + } + // concrete values (literal attributes), when asked for by id: typed as the attribute's range + // in the MRCM says (int / dec), booleans and strings as stored + const concreteLits = lits.filter((l) => { const p = S.propsById.get(l.p); return p && p.attribute && this._hasProp(props, p.code, true); }) + .sort((a, b) => (S.propsById.get(a.p).code < S.propsById.get(b.p).code ? -1 : 1)); + for (const l of concreteLits) { + const p = S.propsById.get(l.p); + const aid = S.idOf(p.code); + const adisp = aid != null && S.conceptRows([aid], st).get(aid) ? S.conceptRows([aid], st).get(aid).display : p.display || p.code; + let value; + if (p.type === 'boolean') value = { valueBoolean: l.v === 1 || l.v === 'true' || l.v === '1' }; + else if (p.type === 'string') value = { valueString: String(l.v) }; + else value = this._concreteIsInteger(p.code) ? { valueInteger: Math.round(Number(l.v)) } : { valueDecimal: Number(l.v) }; + params.push({ name: 'property', part: [{ name: 'code', valueCode: p.code }, { name: 'value', ...value }, { name: 'code-display', valueString: adisp }] }); + } + const ids = S.alternateIdsOf(c.id); + for (const r of ids) { + const scheme = IDENTIFIER_SCHEMES[r.scheme]; + if (scheme && this._hasProp(props, scheme.property, true)) { + params.push({ name: 'property', part: [{ name: 'code', valueCode: scheme.property }, { name: 'value', valueCoding: { system: scheme.system, code: r.identifier } }] }); + } + } + if (!noNormalForm) this._addNormalForms(c.id, null, props, params); + } + + /** + * normalForm (with terms) and normalFormTerse (without), for a concept or an expression: only + * when asked for by name (not by default, not by property=*), as main (#331) + */ + _addNormalForms(id, expression, props, params) { + const wantFull = askedFor(props, 'normalForm'); + const wantTerse = askedFor(props, 'normalFormTerse'); + if (!wantFull && !wantTerse) return; + const svc = this._native(); + const nf = expression ? svc.normaliseExpression(expression) : svc.createNormalForm(id); + if (wantFull) params.push({ name: 'property', part: [{ name: 'code', valueCode: 'normalForm' }, { name: 'value', valueString: svc.renderExpression(nf, E.SnomedServicesRenderOption.FillMissing) }] }); + if (wantTerse) params.push({ name: 'property', part: [{ name: 'code', valueCode: 'normalFormTerse' }, { name: 'value', valueString: svc.renderExpression(nf, E.SnomedServicesRenderOption.Minimal) }] }); + } + + /** whether a concrete attribute's MRCM range (refset 723562003) is an integer: int(...) */ + _concreteIsInteger(attrCode) { + const S = this.store; + const rs = S.idOf('723562003'); + const a = S.idOf(attrCode); + if (rs == null || a == null) return false; + const r = S.refsetMemberRows(rs, a)[0]; + return !!r && /^\s*int\(/i.test(JSON.parse(r.fields || '[]')[0] || ''); + } + + async subsumesTest(codeA, codeB) { + if (!isConceptId(codeA) || !isConceptId(codeB)) return this._nativeSubsumes(codeA, codeB); + return super.subsumesTest(codeA, codeB); + } + + // ---- native post-coordination ----------------------------------------------------------- + + async _nativeLocate(code) { + const svc = this._native(); + try { + const exp = new E.SnomedExpressionParser().parse(code); + await svc.checkExpression(exp); // async in main since 1.0.5 (the MRCM range check runs ECL) + if (exp.isSimple() && !exp.concepts[0].literal) { + // a single concept (with its term, say): the concept itself + return super._locate(exp.concepts[0].code); + } + return { context: new NativeExprContext(code, exp), message: null }; + } catch (e) { + return { context: null, message: `Not a valid expression: ${e.message}` }; + } + } + + async _nativeSubsumes(codeA, codeB) { + const svc = this._native(); + try { + const a = new E.SnomedExpressionParser(svc.conceptList).parse(codeA); + const b = new E.SnomedExpressionParser(svc.conceptList).parse(codeB); + if (a.isSimple() && b.isSimple()) { + const ra = a.concepts[0].reference; + const rb = b.concepts[0].reference; + if (ra === rb) return 'equivalent'; + if (svc.subsumes(ra, rb)) return 'subsumes'; + if (svc.subsumes(rb, ra)) return 'subsumed-by'; + return 'not-subsumed'; + } + const b1 = svc.expressionSubsumes(a, b); + const b2 = svc.expressionSubsumes(b, a); + if (b1 && b2) return 'equivalent'; + if (b1) return 'subsumes'; + if (b2) return 'subsumed-by'; + throw cannotDetermineSubsumption('Unable to determine the subsumption relationship between ' + + `'${codeA}' and '${codeB}': at least one is a postcoordinated expression and no ` + + 'relationship follows from comparing their normal forms. Establishing that there ' + + 'is no relationship would require classification, which this server does not do, ' + + 'so no outcome is returned rather than one that may be wrong'); + } catch (error) { + if (error.statusCode) throw error; + throw new Error(`Error in subsumption test: ${error.message}`); + } + } + + /** an expression's membership of a filter set, natively (as main decides it) */ + async _nativeMember(set, ctxt) { + const svc = this._native(); + const specs = set.specs || []; + for (const f of specs) { + if (f.prop === 'expressions' && f.op === '=') { + if (String(f.value) === 'false' && ctxt.isComplex()) return false; + continue; + } + if (f.prop === 'constraint' && f.op === '=' && ctxt.isComplex()) { + let ast; + try { ast = new ECLParser(new ECLLexer(String(f.value)).tokenize()).parse(); } catch (e) { return false; } + if (!svc.exprSatisfies(ctxt.expression, ast)) return false; + continue; + } + // any other filter: its focus concept is tested (as main does) + const node = await this._compiled(() => this._compiler().filter(f.prop, f.op, f.value)); + if (!this.engine.contains(node, ctxt.getReference(), this._trace)) return false; + } + return true; + } + + async _nativeLookup(ctxt, props, params) { + if (ctxt.expression.concepts.length === 1) { + const r = await super._locate(ctxt.expression.concepts[0].code); + if (r.context) await this._extendLookup(r.context, props, params, true); + } + this._addNormalForms(null, ctxt.expression, props, params); + const svc = this._native(); + const add = async (refinement) => { + const value = new NativeExprContext('', refinement.value); + const code = value.isComplex() ? svc.renderExpression(refinement.value, E.SnomedServicesRenderOption.Minimal) : refinement.value.concepts[0].code; + const description = value.isComplex() ? svc.renderExpression(refinement.value, E.SnomedServicesRenderOption.FillMissing) : svc.getDisplayName(refinement.value.concepts[0].reference); + const p = this._addCodeProperty(params, 'property', refinement.name.code, code, null, description); + p.part.push({ name: 'code-display', valueString: svc.getDisplayName(refinement.name.code) }); + }; + for (const r of ctxt.expression.refinements) await add(r); + for (const g of ctxt.expression.refinementGroups) for (const r of g.refinements) await add(r); + } + + /** translation by alternate identifier (e.g. the LOINC Extension's LOINC codes), both ways */ + async _nativeByIdentifier(map, coding, target) { + const { schemes } = map.jsonObj.identifierMap; + const targetSystem = target ? target.split('|')[0] : null; + const S = this.store; + const out = []; + if (coding.system === SCT) { + const id = S.idOf(this.normaliseCode(coding.code)); + if (id == null) return []; + for (const r of S.alternateIdsOf(id)) { + const scheme = IDENTIFIER_SCHEMES[r.scheme]; + if (scheme && schemes.includes(r.scheme) && (!targetSystem || targetSystem === scheme.system)) { + out.push({ map: map.vurl, system: scheme.system, code: r.identifier, relationship: 'equivalent' }); + } + } + } else if (!targetSystem || targetSystem === SCT) { + for (const schemeId of schemes) { + const scheme = IDENTIFIER_SCHEMES[schemeId]; + if (!scheme || scheme.system !== coding.system) continue; + const sid = S.idOf(schemeId); + if (sid == null) continue; + for (const code of S.codesByAlternateId(sid, coding.code)) { + out.push({ map: map.vurl, system: SCT, version: this.version(), code, display: await this.display(code), relationship: 'equivalent' }); + } + } + } + return out; + } + + /** translation to an edition this one depends on, from the definitions (as main does it) */ + async _nativeToEdition(map, coding) { + const ed = map.jsonObj.editionTranslation; + const svc = this._native(); + const S = this.store; + const src = S.idOf(this.normaliseCode(coding.code)); + if (src == null) return []; + const inTarget = (id) => ed.modules.has(svc.moduleOf(id)); + const name = (id) => svc.getDisplayName(id); + const mk = (code, display, relationship) => ({ map: map.vurl, system: SCT, version: ed.version, code, display, relationship }); + const named = (id) => `${svc.getConceptId(id)} |${name(id)}|`; + if (inTarget(src)) return [mk(svc.getConceptId(src), name(src), 'equivalent')]; + if (!svc.isActive(src)) { + const out = []; + for (const [refset, relationship] of [['900000000000527005', 'equivalent'], ['900000000000526001', 'equivalent'], + ['900000000000523009', 'related-to'], ['900000000000530003', 'related-to']]) { + const rid = S.idOf(refset); + if (rid == null) continue; + for (const fields of S.refsetRows(rid, src)) { + const t = fields.length ? S.idOf(String(fields[0])) : null; + if (t != null && inTarget(t)) out.push(mk(svc.getConceptId(t), name(t), relationship)); + } + } + return out; + } + if (!svc.isPrimitive(src)) { + const nf = svc.createNormalForm(src); + const used = []; + const walk = (e) => { + for (const c of e.concepts) if (c.reference != null && c.reference !== E.NO_REFERENCE) used.push(c.reference); + for (const r of [...e.refinements, ...e.refinementGroups.flatMap((g) => g.refinements)]) { + if (r.name && r.name.reference != null && r.name.reference !== E.NO_REFERENCE) used.push(r.name.reference); + if (r.value) walk(r.value); + } + }; + walk(nf); + if (used.every(inTarget)) { + // a concept of the target edition with the same normal form (lowest id, as main's index) + const rendered = svc.renderExpression(nf, E.SnomedServicesRenderOption.Minimal); + const same = S.conceptsWithNormalForm(rendered) + .filter((r) => r.concept_id !== src && inTarget(r.concept_id)).sort((a, b) => (BigInt(a.code) < BigInt(b.code) ? -1 : 1))[0]; + if (same) return [mk(same.code, name(same.concept_id), 'equivalent')]; + const out = svc.ungroupNeverGroupedRefinements(nf); + return [mk(svc.renderExpression(out, E.SnomedServicesRenderOption.Minimal), svc.renderExpression(out, E.SnomedServicesRenderOption.FillMissing), 'equivalent')]; + } + } + // proximal ancestors in the target edition + const result = []; + const seen = new Set(); + const todo = [...svc.getConceptParents(src)]; + while (todo.length) { + const p = todo.shift(); + if (seen.has(p)) continue; + seen.add(p); + if (inTarget(p)) result.push(p); else todo.push(...svc.getConceptParents(p)); + } + const ancestors = result.filter((a) => !result.some((b) => b !== a && svc.subsumes(a, b))); + if (!ancestors.length) return []; + const root = S.idOf(native.ROOT); + const depth = (a) => (a === root ? 0 : svc.getConceptParents(a).includes(root) ? 1 : 2); + const useful = ancestors.filter((a) => depth(a) >= 2); + if (!useful.length) { + const list = ancestors.map(named); + const msgId = list.length === 1 ? 'TRANSLATE_SCT_EDITION_TOP_LEVEL_ONE' : 'TRANSLATE_SCT_EDITION_TOP_LEVEL_MANY'; + return [{ message: this.opContext.i18n.translate(msgId, this.opContext.langs, [editionName(ed.moduleId) || 'Unknown Edition', named(src), list.join(', ')]) }]; + } + return useful.map((a) => mk(svc.getConceptId(a), name(a), 'source-is-narrower-than-target')); + } + + /** the key an extension-codes supplement uses for an expression: as given, else its minimal form */ + _nativeExtKey(ctxt) { + if (ctxt.source && this._extensionCodeDisplay(ctxt.source)) return ctxt.source; + return this._native().renderExpression(ctxt.expression, E.SnomedServicesRenderOption.Minimal); + } + + /** a native expression context's own answers */ + _nativeAnswer(m, ctxt, rest) { + const svc = this._native(); + switch (m) { + case 'code': return ctxt.isComplex() ? svc.renderExpression(ctxt.expression, E.SnomedServicesRenderOption.Minimal) : ctxt.source; + case 'display': { + const sup = this._displayFromSupplements(ctxt.source); + if (sup) return sup; + const ext = this._extensionCodeDisplay(this._nativeExtKey(ctxt)); + if (ext) return ext; + return svc.renderExpression(ctxt.expression, E.SnomedServicesRenderOption.FillMissing); + } + case 'designations': { + const displays = rest[0]; + // an extension-codes supplement's display first (the preferred one), then the generated one + if (displays) this._listSupplementDesignations(this._nativeExtKey(ctxt), displays, true); + const d = svc.renderExpression(ctxt.expression, E.SnomedServicesRenderOption.FillMissing); + if (d && displays) displays.addDesignation(true, 'active', 'en-US', DesignationUse.PREFERRED, d); + return null; + } + case 'extendLookup': return this._nativeLookup(ctxt, rest[0], rest[1]); + case 'isAbstract': case 'isInactive': case 'isDeprecated': return false; + case 'properties': return []; + case 'expansionCode': return rest[0]; + default: return null; + } + } + + async _filterLocate(prep, set, code) { + if (code != null && !isConceptId(code)) { + const r = await this._nativeLocate(String(code)); + if (!r.context) return r.message; + if (!(r.context instanceof NativeExprContext)) return super._filterLocate(prep, set, r.context.code); + return (await this._nativeMember(set, r.context)) ? r.context : null; + } + return super._filterLocate(prep, set, code); + } + + async filterCheck(prep, set, concept) { + if (concept instanceof NativeExprContext) return this._nativeMember(set, concept); + return super.filterCheck(prep, set, concept); + } + + async _subsumesTest(codeA, codeB) { + const a = await this.locate(codeA); + const b = await this.locate(codeB); + if (!a.context) throw new Error(a.message || `Unknown code ${codeA}`); + if (!b.context) throw new Error(b.message || `Unknown code ${codeB}`); + return super._subsumesTest(a.context, b.context); + } + + /** ECL failures are reported as upstream does: INVALID_ECL / UNSUPPORTED_ECL, 400 */ + filterError(e, prop, op, value) { + if (prop === 'constraint' && op === '=' && (e.unsupported || e.eclSyntax || e.eclUnknown || e.filterError)) { + const id = e.eclSyntax || e.eclUnknown || /is not known/.test(e.message) ? 'INVALID_ECL' : 'UNSUPPORTED_ECL'; + return new Issue('error', 'invalid', null, id, this.opContext.i18n.translate(id, this.opContext.langs, [value, e.message]), 'vs-invalid').handleAsOO(400); + } + // concept is-a / in / ... naming a concept the edition does not have: the request is invalid + // (400, as an unknown concept in ECL is: tx-ecosystem snomed-expand-ecl-unknown-concept), not a 500 + if (e.unknownConcept) return new Issue('error', 'invalid', null, null, e.message, 'vs-invalid').handleAsOO(400); + return super.filterError(e); + } + + async getTranslations(map, coding, target, reverse) { + if (map && map.jsonObj.identifierMap) return this._nativeByIdentifier(map, coding, target); + if (map && map.jsonObj.editionTranslation) return reverse ? [] : this._nativeToEdition(map, coding); + if (!map || reverse) return []; + if (target && target !== SCT) return []; + const refset = this.store.idOf(map.id); + const src = this.store.idOf(this.normaliseCode(coding.code)); + if (refset == null || src == null) return []; + const out = []; + for (const fields of this.store.refsetRows(refset, src)) { + if (!fields.length) continue; + const tgt = String(fields[0]); + out.push({ map: map.vurl, code: tgt, system: SCT, version: this.version(), display: await this.display(tgt), relationship: map.jsonObj.relationship }); + } + return out; + } +} + +function fmtDate(v) { + return /^\d{8}$/.test(v) ? v.substring(0, 4) + '-' + v.substring(4, 6) + '-' + v.substring(6, 8) : v; +} + +const LOADED = new Set(); + +class SnomedV2Factory extends SqliteV2Factory { + edition() { return this.store.cs.edition; } + + name() { + return this.version().includes('xsct') ? 'SNOMED CT Test Set' : `SCT ${editionCode(this.edition()) || 'Unknown Edition'}`; + } + nameBase() { return 'SCT'; } + description() { return `SNOMED CT ${editionName(this.edition()) || 'Unknown Edition'}`; } // (cs-snomed.js getEditionName) + lookupName() { return this.description(); } + versionAlgorithm() { return 'url'; } + + getPartialVersion() { + const v = this.version(); + return v.includes('/version') ? v.substring(0, v.indexOf('/version')) : null; + } + + /** + * As cs-snomed.js id(), byte for byte: 'SCT--', or null without a dated version. + * Main's test-edition branch (snomed.info/xsct) prefixes 'x' to the match array, which makes it + * a string, so its [1] and [2] are the characters 'h' and 't': every xsct edition has the id + * 'SCT-h-t'. Kept so CodeSystem/x- reads and search ids are the same on both engines. + */ + /** as cs-snomed.js SnomedServicesFactory.id(): SCT--, or xSCT-- for an xsct edition */ + id() { + let prefix = ''; + let match = this.version().match(/^http:\/\/snomed\.info\/sct\/(\d+)(?:\/version\/(\d{8}))?$/); + if (!match) { + match = this.version().match(/^http:\/\/snomed\.info\/xsct\/(\d+)(?:\/version\/(\d{8}))?$/); + if (match) prefix = 'x'; + } + return match && match[1] && match[2] ? prefix + 'SCT-' + match[1] + '-' + match[2] : null; + } + + describeVersion(version) { + const m = String(version).match(/^http:\/\/snomed\.info\/sct\/(\d+)(?:\/version\/(\d{8}))?$/); + if (!m) return version; + const ed = editionName(m[1]); + if (!m[2]) return ed; + return ed + ' ' + formatDateMMDDYYYY(m[2].substring(4, 6) + m[2].substring(6, 8) + m[2].substring(0, 4)); + } + + isMyEdition(version) { + const mine = this.version(); + return version === mine || mine.startsWith(version + '/version/'); + } + + idOfCode(code) { return this.store.idOf(code); } + + preferredId() { return this._preferredId; } + + displayRefsetIds() { return this._displayRefsets; } + + /** the dialect language reference sets this file has: [{id, lang, tag}] (cs-snomed.js LANGUAGE_REFSET_DIALECTS) */ + dialectRefsets() { return this._dialectRefsets; } + + /** the dialect (en-GB) of the edition's first display reference set, or null when it is not a known dialect's */ + displayDialect() { return this._displayDialect; } + + /** another loaded version of this edition is later than this one */ + laterVersionLoaded() { + const mine = this.version(); + for (const f of LOADED) { + if (f !== this && f.edition() === this.edition() && f.version() > mine) return true; + } + return false; + } + + async load() { + await super.load(); + LOADED.add(this); // the SNOMED files this server loaded (load-time data, for edition-only URLs) + // data read at load (no caches): the acceptability and display refset ids + this._preferredId = this.store.idOf(PREFERRED); + this._displayRefsets = [].concat(this.store.displayRefsets || ['900000000000509007']) + .map((c) => this.store.idOf(String(c))).filter((x) => x != null); + this._dialectRefsets = LANGUAGE_REFSET_DIALECTS + .map((d) => ({ id: this.store.idOf(String(d.refset)), lang: d.lang, tag: d.tag })).filter((d) => d.id != null); + const first = this._dialectRefsets.find((d) => d.id === this._displayRefsets[0]); + this._displayDialect = first ? first.tag : null; + } + + async build(opContext, supplements) { + this.recordUse(); + return new SnomedV2Provider(opContext, supplements, this); + } + + /** + * Whether url is an implicit value set of this edition, and in which form (as main's + * cs-snomed.js, #331; the provider chooses the version with library/implicit-valuesets.js): + * generic - http://snomed.info/sct?fhir_vs... (any edition) + * edition - http://snomed.info/sct/?fhir_vs... (this edition, no version given) + * version - http://snomed.info/sct//version/?fhir_vs... (this version) + * The edition and version forms are also recognised under this version's own base + * (http://snomed.info/xsct/... for the test edition). + * @returns {{form: string, query: string}|null} + */ + implicitValueSetForm(url) { + if (!url || !this.store) return null; + const q = url.indexOf('?fhir_vs'); + if (q < 0) return null; + const head = url.substring(0, q); + const query = url.substring(q); + if (query !== '?fhir_vs' && !query.startsWith('?fhir_vs=')) return null; + const mine = this.version(); + const edition = this.edition(); + const m = /\/version\/(\d{8})$/.exec(mine); + const editionBases = new Set([`${SCT}/${edition}`, this.getPartialVersion()]); + const versionBases = new Set([mine, m ? `${SCT}/${edition}/version/${m[1]}` : mine]); + if (head === SCT) return { form: 'generic', query }; + if (editionBases.has(head)) return { form: 'edition', query }; + if (versionBases.has(head)) return { form: 'version', query }; + return null; + } + + async buildKnownValueSet(url, version) { + if (!url.startsWith('http://snomed.info/')) return null; + if (version != null && !this.version().startsWith(version)) return null; + const form = this.implicitValueSetForm(url); + if (!form) return null; + // an edition-only URL means the latest loaded version of that edition, as a version + // parameter naming only the edition does; other versions decline + if (form.form === 'edition' && this.laterVersionLoaded()) return null; + const now = new Date().toISOString(); + const vs = this._knownValueSet(url, form.query, now); + // a URL that names this edition (http://snomed.info/sct/[/version/]?fhir_vs...) + // expands against this edition, not the server's default one + if (vs && form.form !== 'generic') for (const inc of vs.compose.include) inc.version = this.version(); + return vs; + } + + _knownValueSet(url, id, now) { + const base = { resourceType: 'ValueSet', url, status: 'active', date: now }; + if (id === '?fhir_vs') { + return { ...base, name: 'ALLSNOMEDCT', title: 'SNOMED CT Reference Set (All of SNOMED CT)', description: 'SNOMED CT Reference Set (All of SNOMED CT)', compose: { include: [{ system: SCT }] } }; + } + if (id === '?fhir_vs=refset') { + const codes = this.store.codesOf(this.store.refsetIds()).sort(); + return { ...base, name: 'SNOMEDCTReferenceSetList', title: 'SNOMED CT Reference Set List', description: 'Reference Sets defined in this SNOMED-CT version', compose: { include: [{ system: SCT, concept: codes.map((code) => ({ code })) }] } }; + } + if (id.startsWith('?fhir_vs=refset/')) { + const code = id.substring(16); + const cid = this.store.idOf(code); + if (cid == null || !this.store.getSet(KIND.refset, 0, cid).size) return null; + const row = this.store.conceptRows([cid]).get(cid); + return { ...base, name: 'SNOMEDCTRefSet' + code, title: 'SNOMED CT Reference Set ' + code, description: row.display, compose: { include: [{ system: SCT, filter: [{ property: 'concept', op: 'in', value: code }] }] } }; + } + if (id.startsWith('?fhir_vs=isa/')) { + const code = id.substring(13); + const cid = this.store.idOf(code); + if (cid == null) return null; + const row = this.store.conceptRows([cid]).get(cid); + return { ...base, name: 'SNOMEDCTConcept' + code, title: 'SNOMED CT Concept ' + code + ' and descendants', description: 'All Snomed CT concepts for ' + row.display, compose: { include: [{ system: SCT, filter: [{ property: 'concept', op: 'is-a', value: code }] }] } }; + } + if (id.startsWith('?fhir_vs=ecl/')) { + const ecl = decodeURIComponent(id.substring(13)); + return { ...base, name: 'SNOMEDCTECL', title: 'SNOMED CT ECL ' + ecl, description: 'SNOMED CT concepts matching ' + ecl, compose: { include: [{ system: SCT, filter: [{ property: 'constraint', op: '=', value: ecl }] }] } }; + } + return null; + } + + /** + * The implicit maps main defines from an edition's content: to an edition it depends on + * (?fhir_cm=edition/), and those of a module's alternate identifiers (?fhir_cm=, + * e.g. LOINC codes), computed from this file; the maps point back here. + */ + async findImplicitConceptMaps(conceptMaps, source, sourceVersion, dest) { + if (!dest) return; + return this._nativeImplicitMaps(conceptMaps, source, sourceVersion, dest); + } + + // ---- implicit maps defined by content, natively -------------------------------------- + + /** the module this edition is published under (from its version URI) */ + _editionModuleCode() { + const m = /^http:\/\/snomed\.info\/x?sct\/(\d+)/.exec(this.version()); + return m ? m[1] : null; + } + + /** module -> [{module, targetEffectiveTime}] (meta moduleDependencies) */ + _moduleDeps(code) { + return (this.store.moduleDependencies || []).filter((r) => r[0] === code).map((r) => ({ module: r[1], sourceEffectiveTime: r[2], targetEffectiveTime: r[3] })); + } + + _editionDependency(targetEdition) { + const m = /^http:\/\/snomed\.info\/x?sct\/(\d+)(?:\/version\/(\d{8}))?$/.exec(targetEdition || ''); + const mine = this._editionModuleCode(); + if (!m || !mine || this.store.idOf(m[1]) == null) return null; + for (const d of this._moduleDeps(mine)) { + if (d.module === m[1] && (!m[2] || m[2] === d.targetEffectiveTime)) { + const modules = new Set(); + const todo = [m[1]]; + while (todo.length) { + const x = todo.pop(); + if (modules.has(x)) continue; + modules.add(x); + for (const dd of this._moduleDeps(x)) todo.push(dd.module); + } + const ids = new Set([...modules].map((c) => this.store.idOf(c)).filter((x) => x != null)); + const version = d.targetEffectiveTime ? `http://snomed.info/sct/${m[1]}/version/${d.targetEffectiveTime}` : `http://snomed.info/sct/${m[1]}`; + return { moduleId: m[1], version, modules: ids }; + } + } + return null; + } + + _editionTranslationMap(dep) { + const target = editionName(dep.moduleId) || 'Unknown Edition'; + return new ConceptMap({ + resourceType: 'ConceptMap', internalSource: this, editionTranslation: dep, + url: `${this.version()}?fhir_cm=edition/${dep.moduleId}`, + name: `SNOMED CT ${this.describeVersion(this.version())} to ${target} Concept Map`, + description: `The translation implied by the concept definitions of the edition ${this.version()} to the ${target} that it depends on`, + status: 'active', group: [{ source: SCT, target: SCT }] + }); + } + + /** modules carrying alternate identifiers, with their schemes: module code -> Set of scheme codes */ + _identifierModules() { + const S = this.store; + const mp = S.props.get('moduleId'); + const out = new Map(); + if (!mp) return out; + const rows = S.identifierModules(mp.id); + for (const r of rows) { if (!out.has(r.module)) out.set(r.module, new Set()); out.get(r.module).add(r.scheme); } + return out; + } + + _identifierMap(moduleId, mods) { + const schemes = [...((mods || this._identifierModules()).get(moduleId) || [])].filter((x) => IDENTIFIER_SCHEMES[x]); + if (!schemes.length) return null; + const systems = schemes.map((x) => IDENTIFIER_SCHEMES[x].system); + const mid = this.store.idOf(moduleId); + const moduleName = mid != null ? (this.store.conceptRows([mid]).get(mid).display || moduleId) : moduleId; + return new ConceptMap({ + resourceType: 'ConceptMap', internalSource: this, identifierMap: { module: moduleId, schemes }, + url: `${this.version()}?fhir_cm=${moduleId}`, name: `SNOMED CT ${moduleName} Concept Map`, + description: `The concept map implied by the alternate identifiers (${systems.join(', ')}) of the module ${moduleId} |${moduleName}| in ${this.version()}`, + status: 'active', + group: [...systems.map((x) => ({ source: SCT, target: x })), ...systems.map((x) => ({ source: x, target: SCT }))] + }); + } + + async _nativeImplicitMaps(conceptMaps, source, sourceVersion, dest) { + const bar = dest.indexOf('|'); + const destSystem = bar < 0 ? dest : dest.substring(0, bar); + const destVersion = bar < 0 ? null : dest.substring(bar + 1); + const fromMe = source === SCT && sourceVersion && this.isMyEdition(sourceVersion); + const toMe = destSystem === SCT && destVersion && this.isMyEdition(destVersion); + const ident = fromMe ? destSystem : toMe ? source : null; + if (ident && this.store.hasAlternateIds()) { + const mods = this._identifierModules(); + for (const [moduleId, schemes] of mods) { + if ([...schemes].some((x) => IDENTIFIER_SCHEMES[x] && IDENTIFIER_SCHEMES[x].system === ident)) { + const cm = this._identifierMap(moduleId, mods); + if (cm && !conceptMaps.some((m) => m.url === cm.url)) conceptMaps.push(cm); + } + } + } + if (!fromMe || destSystem !== SCT || !destVersion) return; + const dep = this._editionDependency(destVersion); + if (dep) { + const cm = this._editionTranslationMap(dep); + if (!conceptMaps.some((m) => m.url === cm.url)) conceptMaps.push(cm); + } + } + + async findImplicitConceptMap(url, version) { + if (version && version !== this.version()) return null; + if (url && url.includes('?fhir_cm=') && !url.startsWith(SCT + '?fhir_cm=')) { + const q = url.indexOf('?fhir_cm='); + if (!this.isMyEdition(url.substring(0, q))) return null; + const id = url.substring(q + '?fhir_cm='.length); + if (id.startsWith('edition/')) { + const dep = this._editionDependency(`http://snomed.info/sct/${id.substring('edition/'.length)}`); + return dep ? this._editionTranslationMap(dep) : null; + } + return this._identifierMap(id); + } + if (!url || !url.startsWith(SCT + '?fhir_cm=')) return null; + const id = url.substring(url.indexOf('=') + 1); + const a = ASSOCIATIONS[id]; + if (!a) return null; + return new ConceptMap({ + resourceType: 'ConceptMap', internalSource: this, relationship: a[1], id, url: `${SCT}?fhir_cm=${id}`, version: this.version(), + name: `SNOMED CT ${a[0]} Concept Map`, description: `The concept map implicitly defined by the ${a[0]} Association Reference Set`, + copyright: 'This value set includes content from SNOMED CT, which is copyright © 2002+ International Health Terminology Standards Development Organisation (SNOMED International), and distributed by agreement between SNOMED International and HL7', + status: 'active', sourceUri: `${SCT}?fhir_vs`, targetUri: `${SCT}?fhir_vs`, group: [{ source: SCT, target: SCT }] + }); + } + + webSource() { return this.version(); } +} + + +// an expression context is answered natively +for (const m of ['code', 'display', 'definition', 'isAbstract', 'isInactive', 'isDeprecated', 'getStatus', 'itemWeight', + 'parent', 'designations', 'extensions', 'properties', 'incompleteValidationMessage', 'extendLookup', 'expansionCode']) { + const own = SnomedV2Provider.prototype[m]; + SnomedV2Provider.prototype[m] = async function (context, ...rest) { + if (context instanceof NativeExprContext) return this._nativeAnswer(m, context, rest); + if (typeof context === 'string' && context !== '' && !isConceptId(context)) { + const r = await this._nativeLocate(context); + if (!r.context) throw new Error(r.message); + if (r.context instanceof NativeExprContext) return this._nativeAnswer(m, r.context, rest); + return own.call(this, r.context, ...rest); + } + return own.call(this, context, ...rest); + }; +} + +module.exports = { SnomedV2Provider, SnomedV2Factory }; diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js new file mode 100644 index 00000000..3e93d87f --- /dev/null +++ b/tx/sqlite-v2/store.js @@ -0,0 +1,1134 @@ +'use strict'; +// One terminology file (tx/importers/sqlite-v2/schema.sql, meta format tx-terminology/1), opened +// read-only: every SQL statement the providers, engine and terminology adapters run. The FHIR-facing +// code (provider.js, snomed.js, dialects.js, engine/) holds none. +// +// What a property is and how to read it comes from the catalog (`property`), never from probing: +// - its access path: shape (link / literal / both / union / record / identifier), subject_kind, +// inverse_of and property_member (inverse and union properties), closure_from (explicit +// ancestor pairs), ordered (a list whose order is part of the answer), role ('language': the +// relations that rank displays), by_target (which links ix_in holds), by_subject (which +// identifier rows ix_by_subject holds); +// - release facts from code_system and meta (default language, compositional, display contexts, +// module dependencies, languages). +// How a server presents the system (where both servers that read these files would do the same) +// is in the file too: meta behaviour.* keys (BEHAVIOUR below; an unknown key or value is an error +// at open) and the catalog columns filter_ops and report. +// +// The stored sets (ix_set) are read in batches through loadSets, with the evaluation's working +// set and counters; text search is text-index.js over the file's word index. + +const Database = require('better-sqlite3'); +const { RoaringBitmap32 } = require('roaring'); + +const FORMAT = 'tx-terminology/1'; +const USER_VERSION = 1; + +const KIND = Object.freeze({ all: 1, active: 2, leaf: 3, descendants: 4, prop: 5, hasProp: 6, refset: 7 }); + +let ownerSeq = 0; + +/** every open store and engine, for //stats */ +const registry = { stores: new Set(), engines: new Set() }; + +const EMPTY = Object.freeze(new RoaringBitmap32()); + +function primaryLang(l) { return String(l || 'en').toLowerCase().split('-')[0]; } + +/** + * Count one statement in a trace's counters (stats is the tracer's; callers check it is set). + * With a trace, the tracer also records what the statement read: database, table, index and + * statement shape (trace.js). + */ +function count(stats, store, st, rows) { + stats.statements++; + stats.rows += rows; + if (stats.read) stats.read(store, st, rows); +} + +/** + * A read-only connection to a file that is never written in place (rollback journal: terminology, + * package and supplement files are built aside and renamed into place): hold the shared lock for + * the life of the connection (locking_mode EXCLUSIVE, which for a reader is a SHARED lock never + * released) instead of taking and dropping it, and re-checking for a journal, around every + * statement: 7 system calls (4 fcntl, 2 stat, 1 fstat) per statement otherwise. Other readers are + * not affected; a writer would be blocked, and there is none. A WAL file (VSAC's content file, + * which its sync writes in place) keeps normal locking. + */ +function holdReadLock(db) { + if (String(db.pragma('journal_mode', { simple: true })).toLowerCase() !== 'wal') db.pragma('locking_mode = EXCLUSIVE'); +} + +/** + * A source id or identifier value as the file stores it: a canonical decimal integer as an INTEGER + * (bound as BigInt: better-sqlite3 binds a JS number as REAL), anything else as text + */ +function idValue(v) { + const s = String(v); + return /^(0|[1-9][0-9]{0,18})$/.test(s) && BigInt(s) <= 9223372036854775807n ? BigInt(s) : s; +} + +/** the evaluation working-set key of a stored set; vk: the value kind where a property has two */ +function setKey(kind, pid, value, vk = 0) { + return kind + ':' + pid + ':' + (vk ? vk + ':' : '') + (typeof value === 'string' ? 's' + value : value); +} + + +/** + * The behaviour settings a file may carry (meta 'behaviour.', JSON values): key -> {values + * (allowed values, or a check), default}. An importer writes those that differ from the default. + * grammar the code grammar the server applies: 'snomed' (SNOMED CT expressions + * and ECL), 'icd11'; null: codes are plain codes + * lookupName the name $lookup reports: the code system's 'name' or its 'title' + * description the description a provider reports: 'name' or 'title' + * versionAlgorithm CodeSystem.versionAlgorithm the provider reports ('natural', 'date', ...) + * expansionOrder the order of an expansion: 'ids' (concept ids), 'stored' (ix_order + * rank, walk for the whole system), 'stored-self-first' (as 'stored', and + * an is-a / << filter lists its concept first) + * designationUses 'keep': a designation reports its use; 'drop': none does + * distinctDesignationTexts true: a concept's designations are its items' distinct texts (RxNorm: + * cs-rxnorm.js lists each STR once; the file keeps every atom) + * lookupSkipsMixedLinks true: the links of a property that also has literals (shape 'both') + * are left out where no property is named ($lookup, main's ECL over the + * store). SNOMED CT: cs-snomed.js keeps one value kind per attribute and + * never reads them; a filter or ECL refinement naming the attribute does + * aliasProperty, aliasExtension identifier aliases (resolves 1) echoed as a $validate-code output + * parameter / checked in a Coding extension (ICD-11 files): the code or URL + * that names them; read by no system this server serves from a file yet + * preferredForLanguage true: a designation whose item has preferred = 1 and no use is reported + * with the use preferredForLanguage in its own language (ICD-11, NDC files) + * aliasLiterals property code -> value: the literal values a concept reports when read + * through an identifier code (resolves 1 or 2) instead of its own values of + * those properties; '{code}' is the concept's code (NDC files) + * filters null, or the only filters the system understands, as FHIR + * CodeSystem.filter: [{code, operator: [...], values?: [...]}]; code is a + * catalog property or 'inactive' (concept status) (NDC files) + * The last three are read by no system this server serves from a file yet; they are checked so a file + * means the same to every reader. + */ +const BEHAVIOUR = { + grammar: { values: [null, 'snomed', 'icd11'], default: null }, + lookupName: { values: ['name', 'title'], default: 'name' }, + description: { values: ['name', 'title'], default: 'title' }, + versionAlgorithm: { check: (v) => v === null || typeof v === 'string', default: null }, + expansionOrder: { values: ['ids', 'stored', 'stored-self-first'], default: 'ids' }, + designationUses: { values: ['keep', 'drop'], default: 'keep' }, + distinctDesignationTexts: { values: [false, true], default: false }, + lookupSkipsMixedLinks: { values: [false, true], default: false }, + aliasProperty: { check: (v) => v === null || typeof v === 'string', default: null }, + aliasExtension: { check: (v) => v === null || typeof v === 'string', default: null }, + preferredForLanguage: { values: [false, true], default: false }, + aliasLiterals: { check: (v) => isPlainObject(v) && Object.values(v).every((x) => typeof x === 'string'), default: {} }, + filters: { check: (v) => v === null || (Array.isArray(v) && v.every(isFilterSpec)), default: null }, +}; +function isPlainObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); } +const isStrings = (a) => Array.isArray(a) && a.every((x) => typeof x === 'string'); +/** one entry of behaviour.filters: {code, operator: [FHIR filter operators], values?: [strings]} */ +function isFilterSpec(f) { + if (!isPlainObject(f) || typeof f.code !== 'string' || !isStrings(f.operator) || !f.operator.length) return false; + if (!f.operator.every((o) => FILTER_OPS.has(o))) return false; + if (f.values !== undefined && !isStrings(f.values)) return false; + return Object.keys(f).every((k) => k === 'code' || k === 'operator' || k === 'values'); +} +const FILTER_OPS = new Set(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'exists']); +const REPORT = new Set([null, 'named', 'always']); + +/** meta behaviour.* -> settings object (every key, defaults filled); throws on an unknown key or value */ +function readBehaviour(meta, file) { + const out = {}; + for (const [k, d] of Object.entries(BEHAVIOUR)) out[k] = d.default; + for (const [key, raw] of meta) { + if (!key.startsWith('behaviour.')) continue; + const k = key.substring('behaviour.'.length); + const d = BEHAVIOUR[k]; + if (!d) throw new Error(`${file}: unknown behaviour setting ${key} (this server knows ${Object.keys(BEHAVIOUR).join(', ')})`); + let v; + try { v = JSON.parse(raw); } catch (e) { throw new Error(`${file}: ${key} is not JSON: ${raw}`); } + if (d.values ? !d.values.includes(v) : !d.check(v)) throw new Error(`${file}: ${key} = ${raw} is not a value this server knows`); + out[k] = v; + } + return Object.freeze(out); +} + +const NODE_SHAPES = new Set(['link', 'union']); +const FILTER_SHAPES = new Set(['link', 'literal', 'both', 'union']); +const VK = { none: 0, node: 1, literal: 2 }; +// items that are designations: terms, and definitions that carry a use (SNOMED CT text definitions; +// an ICD-11 definition has none) -- in the SQL below as (kind = 0 OR use_id IS NOT NULL) + +const json = (a) => JSON.stringify(Array.from(a)); + +/** + * The file's format, checked before anything else is read: a terminology file of this format, or + * an error that says what the file is and what to do (an operator re-imports older files). + */ +function checkFormat(db, file) { + const name = typeof file === 'string' ? file : 'the file'; + const uv = db.pragma('user_version', { simple: true }); + const has = (t) => !!db.prepare("SELECT 1 FROM main.sqlite_master WHERE type = 'table' AND name = ?").get(t); + const f = uv === USER_VERSION && has('meta') ? db.prepare("SELECT value FROM main.meta WHERE key = 'format'").pluck().get() : null; + if (f === FORMAT) return; + if (uv === 5 || (has('cs_config') && has('concept_set'))) { + throw new Error(`${name} was built by an earlier version of the sqlite-v2 importers (the v5 schema), which this server no longer reads: ` + + 're-import it from the release with tx-import (snomed-v2, snomed-v2-from-cache, loinc-v2, loinc-v2-classic or rxnorm-v2)'); + } + const other = has('meta') ? db.prepare("SELECT value FROM main.meta WHERE key = 'format'").pluck().get() : null; + if (typeof other === 'string' && other.startsWith('tx-terminology/')) { + throw new Error(`${name} is a terminology file in format ${other}; this server reads ${FORMAT}: re-import it with tx-import`); + } + throw new Error(`${name} is not a sqlite-v2 terminology file (no meta format ${FORMAT})`); +} + +class Store { + /** + * @param {string} file path, or ':memory:' style handle for a layer + * @param {object} [opts] { db: an already open better-sqlite3 handle, stmts: a statement map + * shared by stores of one file, unregistered } + */ + + constructor(file, opts = {}) { + this.file = file; + this.db = opts.db || new Database(file, { readonly: true, fileMustExist: true }); + if (!opts.db) { + this.db.pragma('query_only = 1'); + // a small SQLite page cache per connection; reads go through mmap and the OS page cache + const { settings } = require('./settings'); + this.db.pragma(`cache_size = -${settings.sqliteCacheKB}`); + this.db.pragma(`mmap_size = ${settings.mmapMB * 1048576}`); + holdReadLock(this.db); + } + this._stmts = opts.stmts || new Map(); + this.uid = ++ownerSeq; + try { + checkFormat(this.db, file); + this._loadMeta(); + } catch (e) { + if (!opts.db) this.db.close(); + throw e; + } + if (!opts.unregistered) registry.stores.add(this); + } + + close() { + registry.stores.delete(this); + try { this.db.close(); } catch (e) { /* already closed */ } + } + + /** + * Run a whole-table read (load-time data) through SQLite's page cache instead of the mmap + * window, so it does not leave hundreds of MiB of the file mapped into the process. + */ + withoutMmap(fn) { + const before = this.db.pragma('mmap_size', { simple: true }); + this.db.pragma('mmap_size = 0'); + try { + return fn(); + } finally { + this.db.pragma(`mmap_size = ${before}`); + } + } + + stmt(sql) { + let s = this._stmts.get(sql); + if (!s) { + s = this.db.prepare(sql); + this._stmts.set(sql, s); + } + return s; + } + + // ---- sets ------------------------------------------------------------------------------- + + /** + * Load sets for many keys of one (kind, property): one statement whatever the number of keys + * (the format's _readSets). Missing rows are empty sets. Returns Map(value -> bitmap). Nothing is + * kept between requests: `local` is the caller's working set for one evaluation (each set read + * once per evaluation). + * @param {object} [stats] counters to add to (statements, rows, bytes, loaded, us) + * @param {Map} [local] key -> bitmap already read in this evaluation + * @param {number} [vk] the value kind (1 node, 2 literal) for a property that has both + */ + loadSets(kind, pid, values, stats, local, vk = 0) { + const out = new Map(); + const miss = []; + for (const v of values) { + const b = local && local.get(setKey(kind, pid, v, vk)); + if (b) out.set(v, b); + else miss.push(v); + } + if (miss.length) { + const t0 = stats ? process.hrtime.bigint() : 0n; + const { q, rows } = this._readSets(kind, pid, miss, vk); + let bytes = 0; + const named = stats && stats.sets ? [] : null; + for (const r of rows) { + const b = r.bm || RoaringBitmap32.deserialize(r.data, 'portable'); + const len = r.data ? r.data.length : 0; + bytes += len; + out.set(r.value, b); + if (local) local.set(setKey(kind, pid, r.value, vk), b); + if (named) named.push({ value: r.value, card: b.size, bytes: len }); + } + for (const v of miss) { + if (!out.has(v)) { + out.set(v, EMPTY); + if (local) local.set(setKey(kind, pid, v, vk), EMPTY); + } + } + if (stats) { + if (q) count(stats, this, q, rows.length); + if (named) stats.sets(this, kind, pid, named); + stats.setsLoaded += rows.length; + stats.setBytes += bytes; + stats.setLoadUs += Number(process.hrtime.bigint() - t0) / 1000; + } + } + return out; + } + + getSet(kind, pid, value, stats, local, vk = 0) { + return this.loadSets(kind, pid, [value], stats, local, vk).get(value); + } + + all(stats, local) { return this.getSet(KIND.all, 0, 0, stats, local); } + active(stats, local) { return this.getSet(KIND.active, 0, 0, stats, local); } + leaf(stats, local) { return this.getSet(KIND.leaf, 0, 0, stats, local); } + + // ---- codes ------------------------------------------------------------------------------ + + idOf(code, stats) { + return this.resolveCodes([code], stats).get(code); + } + + /** ancestors by walking the hierarchy's direct links upward (the format may know them directly) */ + _walkUp(id, stats) { + const seen = new Set(); + let frontier = [id]; + const pids = new Set([this.hierarchy ? this.hierarchy.id : -1]); + while (frontier.length) { + const next = []; + for (const r of this.linksFrom(frontier, pids, true, stats)) if (!seen.has(r.t)) { seen.add(r.t); next.push(r.t); } + frontier = next; + } + return seen; + } + + /** + * Map a set of another file's ids (same system, other release) to this file's ids by code: + * the members' codes there, then one batched lookup here. Per request (nothing is kept): the + * cost follows the size of the set, not of the files. Chunks of 20,000 ids, codes only. + */ + translateFrom(other, bm, stats) { + const out = new RoaringBitmap32(); + for (let i = 0; i < bm.size; i += 20000) { + const chunk = bm.rangeUint32Array(i, 20000); + const codes = other.codesOf(Array.from(chunk), stats); + for (const id of this.resolveCodes(codes, stats).values()) if (id != null) out.add(id); + } + return out; + } + + // ---- text ------------------------------------------------------------------------------- + + /** + * Text filter ($expand filter): the concepts a text filter matches, by the rules every built-in + * provider follows since #398 (tx/library/text-match.js), with each one's names (text-index.js): + * mode 'designation' : SNOMED CT (sctTextSearch) + * mode 'rxnorm' : RxNorm (rxTextSearch) + * mode 'display' : LOINC (loincTextSearch) + * default : cs-cs.js's rules (genericTextSearch) + * `lang` (a primary language subtag) is the one language a text filter searches + * (CodeSystemProvider.searchLanguage). A designation with no language is in `defLang`. + */ + searchText(text, stats, mode, lang = null, defLang = 'en') { + const g = this.searchTextG(text, stats, mode, lang, defLang); + let r = g.next(); + while (!r.done) r = g.next(); + return r.value; + } + + /** + * searchText as an evaluation step (engine/evaluate.js): a generator with a bare yield at its + * pause points, so a broad filter's ranking does not hold the event loop + */ + * searchTextG(text, stats, mode, lang = null, defLang = 'en') { + const t = String(text == null ? '' : text); + if (!t.trim()) return null; + const ti = require('./text-index'); + const def = primaryLang(this.defaultLanguage); + if (mode === 'designation') return (yield* ti.sctTextSearchG(this, t, lang || def, this.ordinal || ((id) => id), stats)).bm; + if (mode === 'rxnorm') return (yield* ti.rxTextSearchG(this, t, ti.rxSearchable(this, stats), stats)).bm; + if (mode === 'display') return (yield* ti.loincTextSearchG(this, t, lang || 'en', this.ordinal || ((id) => id), stats)).bm; + return (yield* ti.genericTextSearchG(this, t, lang || primaryLang(defLang), defLang, stats)).bm; + } + + + // ---- metadata and catalog ----------------------------------------------------------------- + + _loadMeta() { + const db = this.db; + const cs = db.prepare('SELECT * FROM main.code_system WHERE served = 1').get(); + if (!cs) throw new Error(`${this.file}: no served code_system row (not a terminology file?)`); + this.meta = new Map(db.prepare("SELECT key, value FROM main.meta WHERE key NOT LIKE 'provenance.%'").raw().all()); + this.format = this.meta.get('format'); + this.csId = cs.cs_id; + this.cs = { id: cs.cs_id, uri: cs.uri, version: cs.version, name: cs.name, title: cs.title, description: cs.description, + release_date: cs.release_date, content: cs.content, edition: this.meta.get('edition') ?? null, + concept_count: cs.concept_count, active_count: cs.active_count, case_sensitive: cs.case_sensitive, hierarchy_meaning: cs.hierarchy_meaning }; + this.system = cs.uri; + this.version = cs.version; + this.conceptCount = cs.concept_count; + this.activeCount = cs.active_count; + this.lo = 1; + this.hi = cs.concept_count; + this.behaviour = readBehaviour(this.meta, this.file); + // a compositional system's expansions are never closed (post-coordinated expressions are codes) + this.notClosed = cs.compositional === 1; + this.defaultLanguage = cs.default_language || null; + this.caseSensitive = cs.case_sensitive !== 0; + const metaJson = (k, d) => (this.meta.has(k) ? JSON.parse(this.meta.get(k)) : d); + const dc = metaJson('displayContexts', null); + this.displayRefsets = dc && dc.relations ? dc.relations.map(String) : null; + this.moduleDependencies = metaJson('moduleDependencies', []); + this._loadCatalog(); + this.uses = new Map(); + for (const u of db.prepare('SELECT use_id, system, code, display FROM main.item_use').all()) this.uses.set(u.use_id, { system: u.system, code: u.code, display: u.display }); + this.hasFts = true; + this.hasAcceptability = this.langRelations.size > 0; + this.hasRank = true; + // a concept shows a definition (the kind 1 item with preferred = 1): one probe of a partial index + this.hasDefinitions = !!db.prepare('SELECT 1 FROM main.item WHERE kind = 1 AND preferred = 1 LIMIT 1').get(); + // identifiers accepted as codes (ICD-11 short codes, NDC 11-digit forms): one probe at open + this.hasCodeIdentifiers = !!db.prepare('SELECT 1 FROM main.identifier WHERE resolves > 0 LIMIT 1').get(); + // children in source order: the hierarchy's links by target (ix_in, in seq order) + this.hasLinkOrder = !!(this.hierarchy && this.hierarchy.byTarget); + } + + _loadCatalog() { + const rows = this.db.prepare('SELECT * FROM main.property WHERE cs_id = ? ORDER BY id').all(this.csId); + this.catalog = new Map(); // code -> def (every catalog row) + this.propsById = new Map(); // id -> def + for (const r of rows) { + const def = { + id: r.id, code: r.code, uri: r.uri, display: r.display, type: r.fhir_type || 'code', shape: r.shape, + // the value kind: node-valued (link, union) or literal; a 'both' property is read as literal + // unless a filter value names a node (compile.js) + kind: NODE_SHAPES.has(r.shape) ? 'concept' : r.shape === 'record' || r.shape === 'identifier' ? r.shape : 'literal', + subjectKind: r.subject_kind, targetKind: r.target_kind, n: r.n_rows, conceptId: r.concept_id, + isHierarchy: !!r.subsumption, closureFrom: r.closure_from, filterable: !!r.filterable, refinable: !!r.refinable, + wildcard: !!r.wildcard, byTarget: !!r.by_target, bySubject: !!r.by_subject, ordered: !!r.ordered, role: r.role, + attribute: !!r.refinable, // (the SNOMED CT adapters' "attribute": a row ECL refines by) + fields: r.fields ? JSON.parse(r.fields) : null, inverseOfId: r.inverse_of, members: null, reverses: null, + // the operators a filter on it accepts (null: the dialect's), and when $lookup reports it + filterOps: r.filter_ops ? JSON.parse(r.filter_ops) : null, report: r.report ?? null, + }; + if (def.filterOps && !(Array.isArray(def.filterOps) && def.filterOps.every((o) => FILTER_OPS.has(o)))) { + throw new Error(`${this.file}: property ${def.code} has filter_ops ${r.filter_ops}, not a list of FHIR filter operators`); + } + if (!REPORT.has(def.report)) throw new Error(`${this.file}: property ${def.code} has report ${def.report} (named, always or NULL)`); + this.catalog.set(def.code, def); + this.propsById.set(def.id, def); + } + for (const [a, c] of this.db.prepare('SELECT parent_id, child_id FROM main.property_member ORDER BY parent_id, child_id').raw().all()) { + const p = this.propsById.get(a), m = this.propsById.get(c); + if (p && m) (p.members || (p.members = [])).push(m); + } + const stored = (d) => (d.members ? d.members.flatMap(stored) : [d]); + for (const d of this.catalog.values()) { + if (d.inverseOfId != null) d.reverses = stored(this.propsById.get(d.inverseOfId)); + } + const closureSources = new Set([...this.catalog.values()].map((d) => d.closureFrom).filter((x) => x != null)); + // the properties a filter or a lookup reads by name: link, literal, both and filterable + // unions; not the inverse rows, nor a closure source (its pairs are the descendants sets) + this.props = new Map(); + for (const d of this.catalog.values()) { + if (!FILTER_SHAPES.has(d.shape) || d.reverses || closureSources.has(d.id)) continue; + if (d.shape === 'union' && !d.filterable) continue; + this.props.set(d.code, d); + } + this.hierarchy = [...this.catalog.values()].find((d) => d.isHierarchy) || null; + this.closure = this.hierarchy && this.hierarchy.closureFrom != null ? this.hierarchy.closureFrom : null; + // link properties linksFrom reads when none is named: not a closure source (its pairs are the + // descendants sets), and not a 'both' one where the file says so (behaviour.lookupSkipsMixedLinks) + const skipBoth = this.behaviour.lookupSkipsMixedLinks; + this.hiddenLinks = [...this.catalog.values()].filter((d) => (skipBoth && d.shape === 'both') || closureSources.has(d.id)).map((d) => d.id); + // the reference sets: record relations by their concept; the language ones rank displays + this.relations = new Map(); + this.langRelations = new Map(); // relation id -> refset concept id + for (const d of this.catalog.values()) { + if (d.shape !== 'record') continue; + if (d.conceptId != null) this.relations.set(d.conceptId, d); + if (d.role === 'language') this.langRelations.set(d.id, d.conceptId); + } + this.langRelIds = json(this.langRelations.keys()); + // identifier schemes by their concept + this.schemes = new Map(); + for (const d of this.catalog.values()) if (d.shape === 'identifier' && d.conceptId != null) this.schemes.set(d.conceptId, d); + // RxNorm atom-level relationships (an optional build): identifier rows under AUI: + this.hasAtomRelationships = [...this.catalog.values()].some((d) => d.shape === 'identifier' && d.code.startsWith('AUI:')); + // an ordered list property (LOINC Answer): a list's members are its targets in seq order + this.listProp = [...this.catalog.values()].find((d) => d.ordered && d.shape === 'link') || null; + } + + /** the inverse rows: [{code, reverses (the stored properties reversed)}] */ + inverses() { return [...this.catalog.values()].filter((d) => d.reverses); } + + /** the catalog row a FHIR filter may name (filterable, statement-valued), or undefined */ + filterProp(code) { + const d = this.catalog.get(code); + return d && d.filterable && FILTER_SHAPES.has(d.shape) ? d : undefined; + } + + /** value -> display of a literal property's values (value_label) */ + valueLabels(p) { + if (!this._labels) { + this._labels = new Map(); + for (const [pid, v, d] of this.db.prepare('SELECT property_id, value, display FROM main.value_label').raw().all()) { + if (!this._labels.has(pid)) this._labels.set(pid, {}); + this._labels.get(pid)[v] = d; + } + } + return this._labels.get(p.id) || null; + } + + /** the languages of the served system's items (meta, a release fact) */ + languages() { return JSON.parse(this.meta.get('languages') || '[]'); } + + /** the built-in answer order (ix_order rank / ids / walk), read array by array */ + systemOrder(kind) { return require('./orders').storedOrder(this, kind); } + + hierarchyOrderOf(id) { + if (this._hierOrder === undefined) this._hierOrder = require('./orders').hierarchyOrder(this); + return this._hierOrder ? this._hierOrder.of(id) : null; + } + + /** the source order of a concept's active links ("property:group:target" -> seq) */ + linkSeqFrom(id) { + if (!this.hasLinkOrder) return null; + const m = new Map(); + for (const [p, g, t, seq] of this.stmt('SELECT property_id, group_id, target_id, seq FROM main.link WHERE subject_id = +? AND active = 1 AND seq IS NOT NULL').raw().all(id)) m.set(p + ':' + g + ':' + t, seq); + return m; + } + + /** the concepts with an active group-0 link of a by-target property to the concept, in source order */ + linkSourcesInOrder(propertyId, id) { + const d = this.propsById.get(propertyId); + if (!d || !d.byTarget) return null; + return this.stmt('SELECT subject_id FROM main.ix_in WHERE target_id = +? AND property_id = +? AND active = 1 AND group_id = 0 ORDER BY seq').pluck().all(id, propertyId); + } + + // ---- sets ------------------------------------------------------------------------------- + + /** ix_set value_kind of a (kind, property) key: 1 node, 2 literal, 0 none */ + _vk(kind, pid, vk) { + if (vk) return vk; + if (kind === KIND.descendants) return VK.node; + if (kind !== KIND.prop) return VK.none; + const p = this.propsById.get(pid); + return p && p.kind === 'concept' ? VK.node : VK.literal; + } + + _readSets(kind, pid, vals, vkIn) { + const p = pid ? this.propsById.get(pid) : null; + if (p && p.members && (kind === KIND.prop || kind === KIND.hasProp)) { + // a union's sets are its members' (never stored): OR them + const by = new Map(); + for (const m of p.members) { + for (const [v, b] of this.loadSets(kind, m.id, vals, null, null, vkIn)) if (b.size) { if (!by.has(v)) by.set(v, []); by.get(v).push(b); } + } + return { q: null, rows: [...by].map(([value, bs]) => ({ value, bm: RoaringBitmap32.orMany(bs) })) }; + } + if (kind === KIND.refset) return this._members(vals); + const vk = this._vk(kind, pid, vkIn); + let q, rows; + if (vals.length === 1) { + // +?: no re-prepare per value where a file has sqlite_stat4 (built before stat1-only), 16 -> 7 us per set + q = this.stmt('SELECT value, data FROM main.ix_set WHERE kind = +? AND property_id = +? AND value = +? AND value_kind = +?'); + const r = q.get(kind, pid, vals[0], vk); + rows = r ? [r] : []; + } else { + q = this.stmt('SELECT value, data FROM main.ix_set WHERE kind = +? AND property_id = +? AND value IN (SELECT value FROM json_each(?)) AND value_kind = +?'); + rows = q.all(kind, pid, JSON.stringify(vals), vk); + } + return { q, rows }; + } + + /** + * The members of each concept as a "reference set": a record relation's concept: its member + * set (ix_set kind 7); else, in a file with an ordered list property, the list's targets + */ + _members(vals) { + const rel = new Map(); + const lists = []; + for (const v of vals) { const d = this.relations.get(v); if (d) rel.set(d.id, v); else if (this.listProp) lists.push(v); } + const rows = []; + let q = null; + if (rel.size) { + q = this.stmt('SELECT property_id, data FROM main.ix_set WHERE kind = 7 AND property_id IN (SELECT value FROM json_each(?)) AND value = 0 AND value_kind = 0'); + for (const r of q.raw().all(json(rel.keys()))) rows.push({ value: rel.get(r[0]), data: r[1] }); + } + if (lists.length) { + q = this.stmt('SELECT subject_id, target_id FROM main.link WHERE subject_id IN (SELECT value FROM json_each(?)) AND property_id = +? AND active = 1'); + const by = new Map(); + for (const [l, m] of q.raw().all(json(lists), this.listProp.id)) { if (!by.has(l)) by.set(l, []); by.get(l).push(m); } + for (const [value, m] of by) rows.push({ value, bm: new RoaringBitmap32(m) }); + } + return { q, rows }; + } + + /** keys (values) of the stored prop sets of one property, with their cardinalities */ + propValues(pid, stats, vk = 0) { + const p = this.propsById.get(pid); + if (p && p.members) { + const by = new Map(); + for (const m of p.members) for (const r of this.propValues(m.id, stats, vk)) by.set(r.value, (by.get(r.value) || 0) + r.card); + return [...by].map(([value, card]) => ({ value, card })); + } + const q = this.stmt('SELECT value, card FROM main.ix_set WHERE kind = 5 AND property_id = +? AND value_kind = +?'); + const r = q.all(pid, this._vk(KIND.prop, pid, vk)); + if (stats) count(stats, this, q, r.length); + return r; + } + + /** the reference sets with concept members, by concept id */ + refsetIds() { + const ids = this.stmt('SELECT property_id FROM main.ix_set WHERE kind = 7').pluck().all() + .map((pid) => this.propsById.get(pid)).filter((d) => d && d.conceptId != null).map((d) => d.conceptId); + return ids.sort((a, b) => a - b); + } + + // ---- codes ------------------------------------------------------------------------------ + + resolveCodes(codes, stats) { + const out = new Map(); + const want = [...new Set(codes.filter((c) => c != null).map(String))]; + if (!want.length) return out; + const q = want.length === 1 + ? this.stmt('SELECT id, code FROM main.concept WHERE cs_id = +? AND code = ?') + : this.stmt('SELECT id, code FROM main.concept WHERE cs_id = +? AND code IN (SELECT value FROM json_each(?))'); + const rows = q.raw().all(this.csId, want.length === 1 ? want[0] : JSON.stringify(want)); + for (const [id, code] of rows) out.set(code, id); + for (const c of want) if (!out.has(c)) out.set(c, null); + if (stats) count(stats, this, q, rows.length); + return out; + } + + codesOf(ids, stats) { + const q = this.stmt('SELECT code FROM main.concept WHERE id IN (SELECT value FROM json_each(?))').pluck(); + const r = q.all(json(ids)); + if (stats) count(stats, this, q, r.length); + return r; + } + + /** the row columns (concept_id, code, active, display, definition) of a concept statement */ + get _rowCols() { + return this.hasDefinitions + ? 'c.id AS concept_id, c.code, c.active, c.display, (SELECT d.text FROM main.item d WHERE d.concept_id = c.id AND d.kind = 1 AND d.preferred = 1 LIMIT 1) AS definition' + : 'c.id AS concept_id, c.code, c.active, c.display, NULL AS definition'; + } + + rowsForCodes(codes, stats) { + const out = new Map(); + const want = [...new Set(codes.filter((c) => c != null).map(String))]; + if (!want.length) return out; + const q = this.stmt(`SELECT ${this._rowCols} FROM json_each(?) j JOIN main.concept c ON c.cs_id = ${this.csId} AND c.code = j.value`); + const rows = q.all(JSON.stringify(want)); + for (const r of rows) out.set(r.code, r); + if (stats) count(stats, this, q, rows.length); + return out; + } + + rowForCode(code, stats) { + const q = this.stmt(`SELECT ${this._rowCols} FROM main.concept c WHERE c.cs_id = ${this.csId} AND c.code = ?`); + const r = q.get(String(code)) || null; + if (stats) count(stats, this, q, r ? 1 : 0); + return r; + } + + /** + * The concept an identifier accepted as a code names (identifier resolves 1 or 2), with its row + * and resolves, or null; the lowest resolves first, then the lowest property and subject id + */ + identifierAsCode(value, stats) { + const q = this.stmt(`SELECT ${this._rowCols}, i.resolves FROM main.identifier i JOIN main.concept c ON c.id = i.subject_id AND c.cs_id = ${this.csId} + WHERE i.value = ? AND i.resolves > 0 ORDER BY i.resolves, i.property_id, i.subject_id LIMIT 1`); + const r = q.get(idValue(value)) || null; + if (stats) count(stats, this, q, r ? 1 : 0); + return r; + } + + idOfNoCase(code) { + const r = this.stmt('SELECT id FROM main.concept WHERE cs_id = +? AND code = ? COLLATE NOCASE LIMIT 1').pluck().get(this.csId, code); + return r ?? null; + } + + codesInRange(low, high) { + return this.stmt('SELECT id, code FROM main.concept WHERE cs_id = +? AND code >= ? AND code < ?').raw().all(this.csId, low, high); + } + + codesUpToLength(n) { + return this.stmt('SELECT id, code FROM main.concept WHERE cs_id = +? AND length(code) <= ?').raw().all(this.csId, n); + } + + displayIdsNoCase(v) { + let ids = null; + if (String(v).length >= 3) { + try { + ids = this.stmt('SELECT id FROM main.concept WHERE id IN (SELECT rowid FROM main.ix_text_display WHERE ix_text_display MATCH ?) AND display = ? COLLATE NOCASE') + .pluck().all('"' + String(v).replace(/"/g, '""') + '"', v); + } catch (e) { ids = null; } + } + if (!ids) ids = this.stmt('SELECT id FROM main.concept WHERE display = ? COLLATE NOCASE AND id <= ?').pluck().all(v, this.hi); + return ids; + } + + /** + * Items by their source id (a SNOMED CT description id, an RXAUI), as {item, concept}; the + * source id is compared as text (an integer one is stored as INTEGER: bound as BigInt) + */ + itemsByExternalId(value) { + return this.stmt('SELECT id AS item, concept_id AS concept FROM main.item WHERE external_id = ?').all(idValue(value)); + } + + // ---- rows ------------------------------------------------------------------------------- + + ftsDisplayIds(query, stats) { + const q = this.stmt('SELECT rowid FROM main.ix_text_display WHERE ix_text_display MATCH ?'); + const ids = q.pluck().all(query); + if (stats) count(stats, this, q, ids.length); + return new RoaringBitmap32(ids); + } + + ftsDesignationConcepts(query, stats) { + const q = this.stmt('SELECT DISTINCT i.concept_id FROM main.ix_text_item s JOIN main.item i ON i.id = s.rowid WHERE ix_text_item MATCH ? AND i.cs_id = +?').pluck(); + const r = q.all(query, this.csId); + if (stats) count(stats, this, q, r.length); + return r; + } + + ftsDesignationRows(query, stats) { + const q = this.stmt('SELECT i.concept_id, i.text, i.language, i.use_id, i.active FROM main.ix_text_item s JOIN main.item i ON i.id = s.rowid WHERE ix_text_item MATCH ? AND i.cs_id = +?').raw(); + const r = q.all(query, this.csId); + if (stats) count(stats, this, q, r.length); + return r; + } + + conceptColumn(col, a, b) { + return this.stmt(`SELECT id, ${col === 'code' ? 'code' : 'display'} AS v FROM main.concept WHERE id BETWEEN ? AND ?`).raw().all(a, b); + } + + designationRange(a, b, lang = null) { + if (lang == null) return this.stmt('SELECT concept_id, text, language, use_id, active FROM main.item WHERE active = 1 AND cs_id = +? AND (kind = 0 OR use_id IS NOT NULL) AND concept_id BETWEEN ? AND ?').raw().all(this.csId, a, b); + return this.stmt("SELECT concept_id, text, language, use_id, active FROM main.item WHERE active = 1 AND cs_id = +? AND (kind = 0 OR use_id IS NOT NULL) AND concept_id BETWEEN ? AND ? AND (lower(language) = ? OR lower(language) LIKE ? || '-%')").raw().all(this.csId, a, b, lang, lang); + } + + designationsRaw(ids, stats) { + const q = this.stmt('SELECT concept_id, text, language, use_id, active FROM main.item WHERE concept_id IN (SELECT value FROM json_each(?)) AND cs_id = +? AND (kind = 0 OR use_id IS NOT NULL)').raw(); + const r = q.all(json(ids), this.csId); + if (stats) count(stats, this, q, r.length); + return r; + } + + conceptRows(ids, stats) { + const out = new Map(); + if (!ids.length) return out; + const q = ids.length === 1 + ? this.stmt(`SELECT ${this._rowCols} FROM main.concept c WHERE c.id = ?`) + : this.stmt(`SELECT ${this._rowCols} FROM main.concept c WHERE c.id IN (SELECT value FROM json_each(?))`); + const rows = ids.length === 1 ? [q.get(ids[0])].filter(Boolean) : q.all(json(ids)); + for (const r of rows) out.set(r.concept_id, r); + if (stats) count(stats, this, q, rows.length); + return out; + } + + /** + * A concept's designations (the served system's items), in item order: Map(concept id -> + * [{id, language, use, term, active, preferred, rank, acc}]). opts: skipUse, + * onlyUse, withAcc: acc = "refset:acceptability,..." from the language relations), and + * withExternalId: sctid, the item's source id (a description SCTID) as text. + */ + designationRows(ids, stats, opts = {}) { + const out = new Map(); + if (!ids.length) return out; + const useCond = opts.onlyUse != null ? `AND use_id = ${Number(opts.onlyUse)}` : opts.skipUse != null ? `AND use_id IS NOT ${Number(opts.skipUse)}` : ''; + const one = ids.length === 1; + const q = this.stmt(`SELECT id, concept_id, language, use_id, text, active, preferred, rank${opts.withExternalId ? ', CAST(external_id AS TEXT)' : ''} FROM main.item + WHERE concept_id ${one ? '= +?' : 'IN (SELECT value FROM json_each(?))'} AND cs_id = ${this.csId} AND (kind = 0 OR use_id IS NOT NULL) ${useCond} ORDER BY id`).raw(true); + const rows = q.all(one ? ids[0] : json(ids)); + const distinct = this.behaviour.distinctDesignationTexts; + let l = null, lid = null, seen = null; + for (const r of rows) { + if (r[1] !== lid) { + lid = r[1]; + l = out.get(lid); + if (!l) out.set(lid, l = []); + if (distinct) seen = new Set(l.map((d) => d.term)); + } + if (distinct) { if (seen.has(r[4])) continue; seen.add(r[4]); } + l.push({ id: r[0], language: r[2], use: r[3] != null ? this.uses.get(r[3]) : null, term: r[4], active: !!r[5], preferred: !!r[6], acc: null, rank: r[7], + ...(opts.withExternalId ? { sctid: r[8] } : {}) }); + } + if (stats) count(stats, this, q, rows.length); + if (opts.withAcc && this.hasAcceptability) { + const items = []; + for (const list of out.values()) for (const d of list) items.push(d.id); + const acc = this._acceptability(items, stats); + for (const list of out.values()) for (const d of list) { const a = acc.get(d.id); d.acc = a ? a.map(([r, v]) => r + ':' + v).join(',') : null; } + } + return out; + } + + /** item id -> [[refset concept id, acceptability id], ...] from the language relations (active rows) */ + _acceptability(items, stats) { + const out = new Map(); + if (!items.length) return out; + const q = this.stmt(`SELECT subject_id, relation_id, target_id FROM main.record WHERE relation_id IN (SELECT value FROM json_each(?)) + AND subject_id IN (SELECT value FROM json_each(?)) AND active = 1 AND target_id IS NOT NULL ORDER BY relation_id, subject_id, seq`).raw(); + const rows = q.all(this.langRelIds, json(items)); + for (const [s, r, t] of rows) { if (!out.has(s)) out.set(s, []); out.get(s).push([this.langRelations.get(r), t]); } + if (stats) count(stats, this, q, rows.length); + return out; + } + + acceptabilityOfConcept(id) { + if (!this.hasAcceptability) return new Map(); + return this._acceptability(this.stmt('SELECT id FROM main.item WHERE concept_id = +?').pluck().all(id)); + } + + designationById(did) { + const r = this.stmt('SELECT id, concept_id, language, use_id, text, active, CAST(external_id AS TEXT) AS x FROM main.item WHERE id = ?').get(did); + if (!r) return null; + return { id: r.id, conceptId: r.concept_id, language: r.language, useId: r.use_id, term: r.text, active: !!r.active, sctid: r.x, accs: this._acceptability([did]).get(did) || [] }; + } + + designationIdsOf(id) { + return this.stmt('SELECT id FROM main.item WHERE concept_id = +? AND cs_id = +? AND (kind = 0 OR use_id IS NOT NULL) ORDER BY id').pluck().all(id, this.csId); + } + + isLanguageRefset(rid) { + const d = this.relations.get(rid); + return !!d && d.role === 'language'; + } + + literalValues(ids, pid, stats) { + const out = new Map(); + if (!ids.length) return out; + const q = ids.length === 1 + ? this.stmt('SELECT subject_id, value FROM main.literal WHERE subject_id = +? AND property_id = +? AND active = 1') + : this.stmt('SELECT subject_id, value FROM main.literal WHERE subject_id IN (SELECT value FROM json_each(?)) AND property_id = +? AND active = 1'); + const rows = q.raw().all(ids.length === 1 ? ids[0] : json(ids), pid); + for (const [s, v] of rows) if (!out.has(s)) out.set(s, v); + if (stats) count(stats, this, q, rows.length); + return out; + } + + literalRows(pids) { + return this.stmt(`SELECT subject_id AS concept_id, property_id, group_id, value FROM main.literal WHERE active = 1 + AND property_id IN (SELECT value FROM json_each(?)) AND subject_id <= ?`).all(json(pids), this.hi); + } + + /** + * Node-valued facts about concepts (one statement): rows {s, p, g, t, active}; pids (a Set) the + * properties to read, else every link property but the closure sources and the 'both' ones (a + * 'both' property's links are read when it is named: an ECL attribute with a concept value) + */ + linksFrom(ids, pids = null, activeOnly = true, stats) { + if (!ids.length) return []; + const act = activeOnly ? 'AND active = 1' : ''; + let q, rows; + if (pids) { + const want = [...pids].filter((p) => p != null && p !== this.closure); + if (!want.length) return []; + q = this.stmt(`SELECT subject_id AS s, property_id AS p, group_id AS g, target_id AS t, active FROM main.link + WHERE subject_id IN (SELECT value FROM json_each(?)) AND property_id IN (SELECT value FROM json_each(?)) ${act} AND target_id <= ?`); + rows = q.all(json(ids), JSON.stringify(want), this.hi); + } else { + q = this.stmt(`SELECT subject_id AS s, property_id AS p, group_id AS g, target_id AS t, active FROM main.link + WHERE subject_id IN (SELECT value FROM json_each(?)) AND property_id NOT IN (SELECT value FROM json_each(?)) ${act} AND target_id <= ?`); + rows = q.all(json(ids), JSON.stringify(this.hiddenLinks), this.hi); + } + if (stats) count(stats, this, q, rows.length); + return rows; + } + + /** links to a concept of the by-target properties (ix_in): rows {s, p, g, active} */ + linksTo(id, activeOnly = true) { + return this.stmt(`SELECT subject_id AS s, property_id AS p, group_id AS g, active FROM main.ix_in WHERE target_id = +? ${activeOnly ? 'AND active = 1' : ''}`).all(id); + } + + literalsOf(ids, activeOnly = true, stats) { + if (!ids.length) return []; + const q = this.stmt(`SELECT subject_id AS c, property_id AS p, group_id AS g, value AS v, active FROM main.literal + WHERE subject_id IN (SELECT value FROM json_each(?)) ${activeOnly ? 'AND active = 1' : ''}`); + const rows = q.all(json(ids)); + if (stats) count(stats, this, q, rows.length); + return rows; + } + + parentsOf(id, stats) { + if (!this.hierarchy) return []; + const q = this.stmt('SELECT target_id FROM main.link WHERE subject_id = +? AND property_id = +? AND active = 1'); + const r = q.pluck().all(id, this.hierarchy.id); + if (stats) count(stats, this, q, r.length); + return r; + } + + /** all ancestors: the explicit pairs (catalog closure_from), else a walk up the hierarchy */ + ancestorsOf(id, stats) { + if (this.closure == null) return [...this._walkUp(id, stats)]; + const q = this.stmt('SELECT target_id FROM main.link WHERE subject_id = +? AND property_id = +? AND active = 1'); + const r = q.pluck().all(id, this.closure); + if (stats) count(stats, this, q, r.length); + return r; + } + + // ---- ordered lists (catalog `ordered`: LOINC answer lists) ----------------------------------- + + sequenceOf(listId) { + if (!this.listProp) return null; + const r = this.stmt('SELECT target_id FROM main.link WHERE subject_id = +? AND property_id = +? AND active = 1 ORDER BY seq, target_id').pluck().all(listId, this.listProp.id); + return r.length ? r : null; + } + + sequencesOf(listIds) { + const out = new Map(listIds.map((id) => [id, []])); + if (!listIds.length || !this.listProp) return out; + for (const [l, m] of this.stmt('SELECT subject_id, target_id FROM main.link WHERE subject_id IN (SELECT value FROM json_each(?)) AND property_id = +? AND active = 1 ORDER BY subject_id, seq, target_id') + .raw().all(json(listIds), this.listProp.id)) out.get(l).push(m); + return out; + } + + sequenceIn(pairs) { + const out = new Map(); + if (!pairs.length || !this.listProp) return out; + const rows = this.stmt("SELECT l.target_id, l.seq FROM json_each(?) j JOIN main.link l ON l.subject_id = json_extract(j.value, '$[0]') AND l.property_id = ? AND l.group_id = 0 AND l.target_id = json_extract(j.value, '$[1]') AND l.active = 1") + .raw().all(JSON.stringify(pairs), this.listProp.id); + for (const [m, s] of rows) if (!out.has(m) || s < out.get(m)) out.set(m, s); + return out; + } + + // ---- reference sets (record relations) ------------------------------------------------------ + + refsetRows(refsetId, conceptId) { + return this.refsetMemberRows(refsetId, conceptId).map((r) => JSON.parse(r.fields)); + } + + /** + * The member rows of a reference set (of one concept, when subjectId is given), active rows: + * {concept_id (the subject; for a row about an item, the item's concept), fields (JSON array of + * the refset's own columns: node ids as codes, values as text), effective_time, module_id}, + * decoded by the relation's columns (property.fields; the target column from record.target_id). + * opts.raw: no codes looked up; `f` is the own columns as an array, a node column's value its + * node id (a number) where it is a node of this file (ECL member filters compare ids). + * opts.targetIn: only the rows whose target column is one of these node ids (in SQL) + */ + refsetMemberRows(refsetId, subjectId = null, opts = {}) { + const rel = this.relations.get(refsetId); + if (!rel) return []; + // rows about items (a refset of descriptions) are projected to the items' concepts, in item order + const onItems = rel.role !== 'language' && (rel.subjectKind === 'item' || rel.subjectKind === 'both'); + let rows; + if (subjectId != null) { + rows = this.stmt('SELECT subject_id, target_id, fields FROM main.record WHERE relation_id = ? AND subject_id = ? AND active = 1 ORDER BY seq').raw().all(rel.id, subjectId); + if (onItems) { + rows = rows.concat(this.stmt(`SELECT i.concept_id, r.target_id, r.fields FROM main.item i JOIN main.record r ON r.relation_id = ? AND r.subject_id = i.id + WHERE i.concept_id = ? AND r.active = 1 ORDER BY i.id, r.seq`).raw().all(rel.id, subjectId)); + } + } else if (opts.targetIn) { + const t = JSON.stringify(opts.targetIn); + rows = this.stmt(`SELECT subject_id, target_id, fields FROM main.record WHERE relation_id = ? AND active = 1 AND subject_id <= ? + AND target_id IN (SELECT value FROM json_each(?)) ORDER BY subject_id, seq`).raw().all(rel.id, this.hi, t); + if (onItems) { + rows = rows.concat(this.stmt(`SELECT i.concept_id, r.target_id, r.fields FROM main.record r JOIN main.item i ON i.id = r.subject_id + WHERE r.relation_id = ? AND r.active = 1 AND r.subject_id > ? AND r.target_id IN (SELECT value FROM json_each(?)) + ORDER BY i.concept_id, r.subject_id, r.seq`).raw().all(rel.id, this.hi, t)); + } + } else { + rows = this.stmt('SELECT subject_id, target_id, fields FROM main.record WHERE relation_id = ? AND active = 1 AND subject_id <= ? ORDER BY subject_id, seq').raw().all(rel.id, this.hi); + if (onItems) { + rows = rows.concat(this.stmt(`SELECT i.concept_id, r.target_id, r.fields FROM main.record r JOIN main.item i ON i.id = r.subject_id + WHERE r.relation_id = ? AND r.active = 1 AND r.subject_id > ? ORDER BY i.concept_id, r.subject_id, r.seq`).raw().all(rel.id, this.hi)); + } + } + const cols = rel.fields || []; + const hasTarget = cols.some((c) => c.target); + const decoded = rows.map(([subject, target, fields]) => { + const rest = fields ? JSON.parse(fields) : []; + const tail = target == null && hasTarget ? rest.pop() : undefined; + let k = 0; + const vals = cols.map((c) => ({ c, v: c.target ? (target != null ? target : tail) : rest[k++], node: c.target ? target != null : (c.type === 'c' || c.type === 'n') })); + return { subject, vals }; + }); + if (opts.raw) { + return decoded.map(({ subject, vals }) => { + const out = { concept_id: subject, f: [], effective_time: null, module_id: null }; + for (const { c, v, node } of vals) { + if (c.name === 'effectiveTime' && c.type === 't') out.effective_time = v ?? null; + else if (c.name === 'moduleId' && !c.target) out.module_id = typeof v === 'number' ? v : null; + else out.f.push(v == null ? '' : node && typeof v === 'number' ? v : String(v)); + } + return out; + }); + } + const ids = new Set(); + for (const r of decoded) for (const x of r.vals) if (x.node && typeof x.v === 'number') ids.add(x.v); + const code = this._codesOfNodes([...ids]); + return decoded.map(({ subject, vals }) => { + const out = { concept_id: subject, fields: null, effective_time: null, module_id: null }; + const extra = []; + for (const { c, v, node } of vals) { + if (c.name === 'effectiveTime' && c.type === 't') out.effective_time = v ?? null; + else if (c.name === 'moduleId' && !c.target) out.module_id = typeof v === 'number' ? v : null; + else extra.push(v == null ? '' : node && typeof v === 'number' ? (code.get(v) ?? '') : String(v)); + } + out.fields = JSON.stringify(extra); + return out; + }); + } + + /** node id -> code (a concept's code, an item's external id), in chunks */ + codesOfNodes(ids) { return this._codesOfNodes(ids); } + + _codesOfNodes(ids) { + const out = new Map(); + const c = this.stmt('SELECT id, code FROM main.concept WHERE id IN (SELECT value FROM json_each(?))').raw(); + const i = this.stmt('SELECT id, CAST(external_id AS TEXT) FROM main.item WHERE id IN (SELECT value FROM json_each(?))').raw(); + for (let k = 0; k < ids.length; k += 20000) { + const part = JSON.stringify(ids.slice(k, k + 20000)); + for (const [id, v] of c.all(part)) out.set(id, v); + for (const [id, v] of i.all(part)) out.set(id, v == null ? null : String(v)); + } + return out; + } + + /** a relation's own columns (not effectiveTime / moduleId): {names, types}, or null without any */ + _ownColumns(d) { + if (!d || d.role === 'language') return null; + const own = (d.fields || []).filter((f) => f.name !== 'effectiveTime' && f.name !== 'moduleId'); + return own.length ? { names: own.map((f) => f.name), types: own.map((f) => f.type) } : null; + } + + refsetDef(rid) { return this._ownColumns(this.relations.get(rid)); } + + /** the name of a reference set's target column (record.target_id), or null */ + refsetTargetField(rid) { + const d = this.relations.get(rid); + const c = d && (d.fields || []).find((f) => f.target); + return c ? c.name : null; + } + + refsetDefs() { + const out = new Map(); + for (const [rid, d] of this.relations) { const x = this._ownColumns(d); if (x) out.set(rid, x); } + return out; + } + + // ---- identifiers, normal forms, maps ------------------------------------------------------ + + /** the concepts of identifier rows of a property (a union: of its members) with any of the values, sorted */ + subjectsOfIdentifiers(def, values, stats) { + const pids = def.members ? def.members.map((m) => m.id) : [def.id]; + // values as stored: a canonical integer is an INTEGER (json_each gives it as one), text otherwise + const vals = values.map((v) => (idValue(v) === String(v) ? String(v) : Number(v))); + const q = this.stmt(`SELECT DISTINCT subject_id FROM main.identifier WHERE property_id IN (SELECT value FROM json_each(?)) + AND value IN (SELECT value FROM json_each(?)) ORDER BY 1`).pluck(); + const r = q.all(JSON.stringify(pids), JSON.stringify(vals)); + if (stats) count(stats, this, q, r.length); + return r; + } + + /** a concept's identifiers of the by_subject = 1 schemes (SNOMED CT alternate identifiers), from ix_by_subject */ + alternateIdsOf(id) { + return this.stmt('SELECT property_id, value FROM main.ix_by_subject WHERE subject_id = ?').raw().all(id) + .map(([p, value]) => ({ scheme: this.propsById.get(p).code, identifier: String(value) })); + } + + codesByAlternateId(schemeId, value) { + const d = this.schemes.get(schemeId); + if (!d) return []; + return this.stmt('SELECT c.code FROM main.identifier i JOIN main.concept c ON c.id = i.subject_id WHERE i.property_id = ? AND i.value = ?').pluck().all(d.id, idValue(value)); + } + + conceptsWithScheme(schemeId) { + const d = this.schemes.get(schemeId); + if (!d) return []; + return this.stmt('SELECT DISTINCT subject_id FROM main.identifier WHERE property_id = ? ORDER BY 1').pluck().all(d.id); + } + + hasAlternateIds() { return this.schemes.size > 0 && !!this.stmt('SELECT 1 FROM main.identifier LIMIT 1').get(); } + + allAlternateIds() { + return this.stmt('SELECT subject_id, property_id, value FROM main.identifier').raw().all() + .map(([s, p, v]) => ({ concept_id: s, scheme_id: this.propsById.get(p).conceptId, identifier: String(v) })); + } + + identifierModules(moduleProp) { + return this.stmt(`SELECT DISTINCT m.code AS module, p.code AS scheme FROM main.identifier i JOIN main.property p ON p.id = i.property_id + JOIN main.link l ON l.subject_id = i.subject_id AND l.property_id = ? JOIN main.concept m ON m.id = l.target_id`).all(moduleProp); + } + + normalFormOf(id) { + return this.stmt("SELECT key FROM main.ix_key WHERE name = 'normalForm' AND id = ?").pluck().get(id) ?? null; + } + + conceptsWithNormalForm(nf) { + return this.stmt("SELECT k.id AS concept_id, c.code FROM main.ix_key k JOIN main.concept c ON c.id = k.id WHERE k.name = 'normalForm' AND k.key = ? AND c.active = 1").all(nf); + } + + externalMaps(id, system = null) { + return system == null + ? this.stmt('SELECT system, version, code, display, relationship AS equivalence FROM main.mapping WHERE concept_id = ? ORDER BY system, code').all(id) + : this.stmt('SELECT system, version, code, display, relationship AS equivalence FROM main.mapping WHERE concept_id = ? AND system = ? ORDER BY code').all(id, system); + } + + mapsTo(system, code) { + return this.stmt('SELECT c.code, c.display, m.relationship AS equivalence FROM main.mapping m JOIN main.concept c ON c.id = m.concept_id WHERE m.system = ? AND m.code = ? ORDER BY c.code').all(system, code); + } + + hasMap(id, system, code) { + return !!((id != null && this.stmt('SELECT 1 FROM main.mapping WHERE concept_id = ? AND system = ? LIMIT 1').get(id, system)) + || this.stmt('SELECT 1 FROM main.mapping WHERE system = ? AND code = ? LIMIT 1').get(system, code)); + } + + // ---- text ------------------------------------------------------------------------------- + + textIndex() { + if (this._textIndex === undefined) { + const words = require('./text-index').FORMAT; + this._textIndex = this.meta.get('ix.ix_word.format') === words ? new (require('./text-index').WordIndex)(this) : null; + } + return this._textIndex; + } + + /** + * fn(id, lang, term) for every name a system's text search reads, in concept order (the index + * builder's word index, or one built in memory): SNOMED CT every active description; LOINC the + * display and the designations but RELATEDNAMES2; RxNorm the atoms of concepts in RXNCONSO + */ + eachSearchName(dialect, fn) { + require('./text-index').eachSearchName(this, dialect, fn); + } + + searchNames(dialect, ids, fn) { + return require('./text-index').searchNamesOf(this, dialect, ids, fn); + } + + activeLanguages() { + return this.db.prepare('SELECT DISTINCT language FROM main.item WHERE active = 1 AND cs_id = ?').pluck().all(this.csId); + } + + blockDesignations() { + return this.stmt('SELECT concept_id, language, text FROM main.item WHERE cs_id = +? AND (kind = 0 OR use_id IS NOT NULL) ORDER BY concept_id, id').raw().all(this.csId); + } + + blockConcepts(a, b) { + return this.stmt('SELECT id, code, display FROM main.concept WHERE id BETWEEN ? AND ? ORDER BY id').raw().all(a, b); + } +} + +/** open a terminology file (opts as the Store constructor's) */ +function openStore(file, opts = {}) { + return new Store(file, opts); +} + +module.exports = { Store, openStore, checkFormat, readBehaviour, BEHAVIOUR, FORMAT, KIND, EMPTY, VK, setKey, registry, count, holdReadLock, primaryLang }; diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js new file mode 100644 index 00000000..146ed8bf --- /dev/null +++ b/tx/sqlite-v2/text-index.js @@ -0,0 +1,671 @@ +'use strict'; +// $expand filter= (a text filter) as the built-in providers answer it since #398: the rules of +// tx/library/text-match.js (TextQuery, the same code), and each provider's own choice of names, +// code match and order: +// +// SNOMED CT (cs-snomed.js searchFilter, tx/sct/text-index.js rankMatches) +// names: the concept's active descriptions in the search language. Codes: an identifier +// that starts with the filter's digits (the concept itself 100, then the others, in +// identifier order), first. Then the text matches: a filter of one word, the +// RANK_REFINE_LIMIT concepts with the fewest distinct words (all of them tied at the cut) +// by their best description (TextQuery.nameRank, at least 10), the rest in concept order; a +// filter of several words, every concept with a description that has all of them, by its +// best description. Ties by concept order. +// LOINC (cs-loinc.js searchFilter with TextIndex, tx/importers/loinc-text-index.js) +// names: in English the display and every English description, in another language its +// descriptions; never RELATEDNAMES2. The codes in TextQuery.codeRanges (codeRank) and the +// concepts with a name that ranks (TextQuery.nameRank of the name as the index holds it: +// its distinct words, indexedName), each by its best; the best first (#399), then by display +// (String.localeCompare), then the file's concept order (CodeKey). +// RxNorm (cs-rxnorm.js #textSearchFilter and #rank, tx/importers/rxnorm-text-index.js) +// names: every RXNORM atom of the concept, in English. A name match or a code in +// TextQuery.codeRanges, among the concepts with an RXNCONSO atom other than SY; the best +// first (nameRank of the best name, as for LOINC, or codeRank), then in RXCUI order (as text). +// +// The searches are generators with a bare yield at their pause points (engine/evaluate.js): +// ranking a broad filter's names takes seconds (most of it stemming, in TextQuery.nameRank), as +// in the built-in providers, which let other work run while they rank (bestRanks). +// anything else (cs-cs.js searchFilter): see contentTextSearch. +// +// Which concepts have a name with a word is a word index, one per language (primary subtag) of +// the names: ix_word(lang, word, stem, ids), every word (text-match words: folded letters, marks +// and digits) with its stem in that language and the concepts that have it (portable Roaring +// bitmap of concept ids), and for SNOMED CT the row with word '', the distinct words of each +// concept (Uint16 by concept id). A filter word matches the words it is the start of and those +// with its stem, a single letter or digit only itself; a filter of several words is then checked +// name by name (TextQuery.nameMatches), as every word has to be in one name. +// +// The index builder writes it (tx/importers/sqlite-v2/indexes.js), with meta 'ix.ix_word.format' +// naming the rules it was made by (FORMAT); a file without one made by these rules has it built in +// memory on the first search, as the built-in providers do. + +const { RoaringBitmap32 } = require('roaring'); +const { TextQuery, words: textWords, stem: stemOf, languageOf } = require('../library/text-match'); + +const FORMAT = 'text-match/1'; +const RANK_REFINE_LIMIT = 200; +const SEARCH_CACHE = 8; +// pause points (evaluate.js runAsync): concepts whose names are read and ranked per statement, +// comparisons per sort step, concepts rated, and concept rows read per statement (blockConcepts) +const NAMES_CHUNK = 500; +const SORT_CHUNK = 20000; +const RATE_CHUNK = 2000; +const ROW_CHUNK = 20000; +// blockConcepts yields this between its chunks, for rateConceptsG to pause at +const PAUSE = Symbol('pause'); +const MAX = '\u{10FFFF}'; + +function primaryLanguage(code, defLang) { + return languageOf(code || null, defLang || 'en'); +} + +// ---- the names ------------------------------------------------------------------------------ + +/** the RELATEDNAMES2 item use (LOINC: never a searched name), or -1 */ +function relatedUse(store) { + if (store._relatedUse === undefined) { + store._relatedUse = -1; + for (const [id, u] of store.uses) if (u.code === 'RELATEDNAMES2') store._relatedUse = id; + } + return store._relatedUse; +} + +/** fn(id, lang, term) for every name the system's search reads, in concept order (one statement) */ +function eachSearchName(store, dialect, fn) { + const db = store.db; + const defLang = store.defaultLanguage || 'en'; + if (dialect === 'snomed') { + for (const [id, language, term] of db.prepare('SELECT concept_id, language, text FROM main.item WHERE active = 1 AND cs_id = ? AND (kind = 0 OR use_id IS NOT NULL) ORDER BY concept_id').raw().iterate(store.csId)) { + fn(id, primaryLanguage(language, defLang), term); + } + } else if (dialect === 'loinc') { + const q = db.prepare(`SELECT id, NULL, display FROM main.concept WHERE display IS NOT NULL AND display <> '' + UNION ALL SELECT concept_id, coalesce(language, @def), text FROM main.item WHERE cs_id = @cs AND use_id IS NOT @rel AND text <> '' ORDER BY 1`).raw(); + for (const [id, language, term] of q.iterate({ def: defLang, rel: relatedUse(store), cs: store.csId })) fn(id, language == null ? 'en' : primaryLanguage(language, defLang), term); + } else if (dialect === 'rxnorm') { + // the concepts in RXNCONSO (a SUPPRESS literal), as cs-rxnorm.js searches only those + const sup = store.props.get('SUPPRESS'); + const q = sup + ? db.prepare('SELECT concept_id, text FROM main.item WHERE cs_id = ? AND concept_id IN (SELECT DISTINCT subject_id FROM main.literal WHERE property_id = ? AND subject_id <= ?) ORDER BY concept_id').raw() + : db.prepare('SELECT concept_id, text FROM main.item WHERE cs_id = ? ORDER BY concept_id').raw(); + for (const [id, term] of (sup ? q.iterate(store.csId, sup.id, store.hi) : q.iterate(store.csId))) fn(id, 'en', term); + } +} + +/** fn(id, lang, term) for the names of some concepts the system's search reads; the rows read */ +function searchNamesOf(store, dialect, ids, fn) { + const def = store.defaultLanguage || 'en'; + const j = JSON.stringify(ids); + let rows = 0; + if (dialect === 'snomed') { + for (const [id, language, term] of store.stmt('SELECT concept_id, language, text FROM main.item WHERE concept_id IN (SELECT value FROM json_each(?)) AND active = 1 AND cs_id = +? AND (kind = 0 OR use_id IS NOT NULL) ORDER BY id').raw().iterate(j, store.csId)) { + rows++; + fn(id, primaryLanguage(language, def), term); + } + } else if (dialect === 'loinc') { + for (const [id, display] of store.stmt("SELECT id, display FROM main.concept WHERE id IN (SELECT value FROM json_each(?)) AND display IS NOT NULL AND display <> ''").raw().iterate(j)) { + rows++; + fn(id, 'en', display); + } + for (const [id, language, term] of store.stmt('SELECT concept_id, language, text FROM main.item WHERE concept_id IN (SELECT value FROM json_each(?)) AND cs_id = +? AND use_id IS NOT ?').raw().iterate(j, store.csId, relatedUse(store))) { + rows++; + fn(id, primaryLanguage(language, def), term); + } + } else { + for (const [id, term] of store.stmt('SELECT concept_id, text FROM main.item WHERE concept_id IN (SELECT value FROM json_each(?)) AND cs_id = +?').raw().iterate(j, store.csId)) { + rows++; + fn(id, 'en', term); + } + } + return rows; +} + + +/** the dialects with a word index */ +function indexed(dialect) { + return dialect === 'snomed' || dialect === 'loinc' || dialect === 'rxnorm'; +} + +/** + * The index of a list of names: each(fn) calls fn(id, lang, term) in id order. + * @returns {Map, counts: Uint16Array|null}>} by language + */ +function computeTextIndexFrom(each, dialect, n) { + const byLang = new Map(); + const counting = dialect === 'snomed'; + const of = (lang) => { + let x = byLang.get(lang); + if (!x) { + x = { words: new Map(), counts: counting ? new Uint16Array(n + 1) : null }; + byLang.set(lang, x); + } + return x; + }; + each((id, lang, term) => { + const x = of(lang); + for (const w of textWords(term)) { + let list = x.words.get(w); + if (!list) { list = []; x.words.set(w, list); } + if (list[list.length - 1] !== id) { + list.push(id); + if (counting && x.counts[id] < 0xFFFF) x.counts[id]++; + } + } + }); + return byLang; +} + +// ---- reading the index ------------------------------------------------------------------------ + +/** the word index the index builder stored (ix_word) */ +class WordIndex { + constructor(store) { + this.store = store; + this.langs = new Set(store.db.prepare("SELECT DISTINCT lang FROM main.ix_word WHERE word <> ''").pluck().all()); + this._counts = new Map(); + } + + counts(lang) { + let c = this._counts.get(lang); + if (!c) { + const b = this.store.stmt("SELECT ids FROM main.ix_word WHERE lang = ? AND word = ''").pluck().get(lang); + c = b ? new Uint16Array(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)) : new Uint16Array(0); + this._counts.set(lang, c); + } + return c; + } + + /** the languages with per-concept counts (every language of the names, where counts are kept), or null */ + languages() { + const l = this.store.db.prepare("SELECT lang FROM main.ix_word WHERE word = ''").pluck().all(); + return l.length ? l : null; + } + + conceptsFor(lang, token, stats) { + const rows = token.whole + ? this.store.stmt('SELECT ids FROM main.ix_word WHERE lang = ? AND word = ?').pluck().all(lang, token.word) + : this.store.stmt(`SELECT ids FROM main.ix_word WHERE lang = @lang AND word >= @w AND word < @hi + UNION ALL SELECT ids FROM main.ix_word WHERE lang = @lang AND stem = @stem AND word <> '' AND NOT (word >= @w AND word < @hi)`) + .pluck().all({ lang, w: token.word, hi: token.word + MAX, stem: token.stem }); + if (stats) { stats.statements++; stats.rows += rows.length; } + const bm = new RoaringBitmap32(); + for (const b of rows) bm.orInPlace(RoaringBitmap32.deserialize(b, 'portable')); + return bm; + } + + bytes() { + let n = 0; + for (const c of this._counts.values()) n += c.byteLength; + return n; + } + + close() {} +} + +/** a file without a stored index: built in memory on its first search, as the built-in providers do */ +class MemoryTextIndex { + constructor(byLang) { + this.langs = new Set(byLang.keys()); + this._byLang = new Map(); + for (const [lang, x] of byLang) { + const words = [...x.words.keys()].sort(); + const postings = words.map((w) => Uint32Array.from(x.words.get(w))); + const stems = new Map(); + words.forEach((w, i) => { + const s = stemOf(w, lang); + if (!stems.has(s)) stems.set(s, []); + stems.get(s).push(i); + }); + this._byLang.set(lang, { words, postings, stems, counts: x.counts || new Uint16Array(0) }); + } + } + + counts(lang) { const x = this._byLang.get(lang); return x ? x.counts : new Uint16Array(0); } + + conceptsFor(lang, token) { + const x = this._byLang.get(lang); + const bm = new RoaringBitmap32(); + if (!x) return bm; + let lo = 0, hi = x.words.length; + while (lo < hi) { const mid = (lo + hi) >>> 1; if (x.words[mid] < token.word) lo = mid + 1; else hi = mid; } + const ids = new Set(); + if (token.whole) { + if (lo < x.words.length && x.words[lo] === token.word) ids.add(lo); + } else { + for (let i = lo; i < x.words.length && x.words[i].startsWith(token.word); i++) ids.add(i); + for (const i of x.stems.get(token.stem) || []) ids.add(i); + } + for (const i of ids) bm.addMany(x.postings[i]); + return bm; + } + + bytes() { + let n = 0; + for (const x of this._byLang.values()) { + n += x.counts.byteLength; + for (const p of x.postings) n += p.byteLength; + } + return n; + } + + close() {} +} + +/** the file's index: stored in the file, else built in memory now */ +function textIndexOf(store, dialect) { + const stored = store.textIndex(); + if (stored) return stored; + // built in memory, for the names of the dialect asked for (a file serves one) + const built = store._textIndexBuilt || (store._textIndexBuilt = new Map()); + if (!built.has(dialect)) { + built.set(dialect, new MemoryTextIndex(store.withoutMmap(() => computeTextIndexFrom((fn) => store.eachSearchName(dialect, fn), dialect, store.conceptCount)))); + } + return built.get(dialect); +} + +/** the concepts with a word for each token (before checking that they are in one name) */ +function* candidates(index, lang, tokens, stats) { + let bm = null; + for (let i = 0; i < tokens.length && (!bm || bm.size); i++) { + if (i) yield; + const t = index.conceptsFor(lang, tokens[i], stats); + bm = bm ? bm.andInPlace(t) : t; + } + return bm || new RoaringBitmap32(); +} + +/** fn(id, lang, term) for the names of some concepts the built-in provider searches (the store's searchNames) */ +function namesOf(store, dialect, ids, stats, fn) { + if (!ids.length) return; + const rows = store.searchNames(dialect, ids, fn); + if (stats) { stats.statements++; stats.rows += rows; } +} + +/** + * namesOf for many concepts, NAMES_CHUNK at a time, pausing (a bare yield: evaluate.js runAsync) + * between them: ranking a broad filter's names (TextQuery.nameRank, stemming each word) takes + * seconds, as it does in the built-in providers (bestRanks, which lets other work run every 20 ms) + */ +function* namesOfG(store, dialect, ids, stats, fn) { + for (let i = 0; i < ids.length; i += NAMES_CHUNK) { + if (i) yield; + namesOf(store, dialect, ids.slice(i, i + NAMES_CHUNK), stats, fn); + } +} + +/** the candidates with a name (in lang) that has every word of the filter */ +function* inOneName(store, dialect, bm, q, lang, stats) { + const ok = new RoaringBitmap32(); + yield* namesOfG(store, dialect, bm.toArray(), stats, (id, l, term) => { + if (l === lang && !ok.has(id) && q.nameMatches(term, lang)) ok.add(id); + }); + return ok; +} + +/** a generator straight through (the sync API) */ +function runSync(g) { + let r = g.next(); + while (!r.done) r = g.next(); + return r.value; +} + +/** + * A sort that pauses: merge sort (stable, as Array.prototype.sort), a bare yield every + * SORT_CHUNK comparisons. A broad LOINC filter sorts ~100,000 matches by String.localeCompare + */ +function* sortG(arr, cmp) { + let a = arr.slice(); + let b = new Array(a.length); + let n = 0; + for (let w = 1; w < a.length; w *= 2) { + for (let lo = 0; lo < a.length; lo += 2 * w) { + const mid = Math.min(lo + w, a.length); + const hi = Math.min(lo + 2 * w, a.length); + let i = lo, j = mid, k = lo; + while (i < mid && j < hi) { + b[k++] = cmp(a[j], a[i]) < 0 ? a[j++] : a[i++]; + if (++n % SORT_CHUNK === 0) yield; + } + while (i < mid) b[k++] = a[i++]; + while (j < hi) b[k++] = a[j++]; + } + [a, b] = [b, a]; + } + return a; +} + +function* cached(store, key, fn) { + const cache = store._textSearches || (store._textSearches = new Map()); + if (cache.has(key)) { + const hit = cache.get(key); + cache.delete(key); + cache.set(key, hit); + return hit; + } + const result = yield* fn(); + cache.set(key, result); + while (cache.size > SEARCH_CACHE) cache.delete(cache.keys().next().value); + return result; +} + +/** the concepts whose code is in one of the ranges [low, high): ids in code order */ +function codesInRanges(store, ranges, stats) { + if (!ranges.length) return []; + const seen = new Set(); + const rows = []; + for (const [low, high] of ranges) { + for (const r of store.codesInRange(low, high)) { + if (!seen.has(r[0])) { seen.add(r[0]); rows.push(r); } + } + } + if (stats) { stats.statements += ranges.length; stats.rows += rows.length; } + // binary order, as SQLite compares text: by UTF-8 bytes, which is code point order + rows.sort((a, b) => cmpBinary(a[1], b[1])); + return rows.map((r) => r[0]); +} + +// SQLite's BINARY order (UTF-8 bytes, so code points); JavaScript's < is UTF-16 units, which is the +// same unless a string has a character outside the BMP +const ASTRAL = /[\uD800-\uDFFF]/; +function cmpBinary(x, y) { + if (x === y) return 0; + if (!ASTRAL.test(x) && !ASTRAL.test(y)) return x < y ? -1 : 1; + return Buffer.compare(Buffer.from(x, 'utf8'), Buffer.from(y, 'utf8')); +} + +/** + * A name as a database text index holds it (text-match.js indexColumns: its distinct words, in + * order), which is what cs-loinc.js and cs-rxnorm.js rank (bestRanks over the words column) + */ +function indexedName(term) { + return [...new Set(textWords(term))].join(' '); +} + +// ---- SNOMED CT -------------------------------------------------------------------------------- + +/** + * cs-snomed.js #addCodeMatches: active concepts whose identifier starts with the filter's digits, + * the concept itself first, then in identifier order. main takes the digits as a number p and + * selects, for each identifier length L from the filter's length to 18, the identifiers in + * [p * 10^(L - n), (p + 1) * 10^(L - n)): for digits without a leading zero, the identifiers that + * start with them; with leading zeros, those that start with p's digits and have at most + * 18 - n + (p's length) digits (p = 0: every identifier of at most 18 - n digits) + */ +function sctCodeMatches(store, q, active, stats) { + if (!/^[0-9]{1,18}$/.test(q.code)) return []; + const n = q.code.length; + const p = BigInt(q.code); + const digits = p === 0n ? '' : p.toString(); + const maxLen = 18 - n + digits.length; + const rows = digits ? store.codesInRange(digits, digits + MAX) : store.codesUpToLength(maxLen); + if (stats) { stats.statements++; stats.rows += rows.length; } + const found = rows.filter(([id, code]) => active.has(id) && code.length <= maxLen && /^[1-9][0-9]*$/.test(code)); + // identifier order (as numbers: shorter first), the concept itself in front + found.sort((a, b) => (a[1] === q.code ? 0 : 1) - (b[1] === q.code ? 0 : 1) || a[1].length - b[1].length || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)); + return found.map((r) => r[0]); +} + +/** + * The concepts a SNOMED CT text filter matches, and their order (see the top of this file). + * @param {object} store Store of a SNOMED CT file + * @param {string} text the filter + * @param {string} lang the search language (primary subtag) + * @param {function} ordinal concept id -> its place in the built-in concept order + * @returns {{bm: RoaringBitmap32, ids: Uint32Array}} active matches; ids best first + */ +function* sctTextSearchG(store, text, lang, ordinal, stats = null) { + return yield* cached(store, 'sct\u0000' + lang + '\u0000' + text, function* () { + const q = new TextQuery(text); + const tokens = q.tokens(lang); + const active = store.active(stats); + let ranked = []; + if (tokens.length) { + const index = textIndexOf(store, 'snomed'); + const bm = (yield* candidates(index, lang, tokens, stats)).andInPlace(active); + const kept = Array.from(bm.toUint32Array()).sort((a, b) => ordinal(a) - ordinal(b)); + yield; + ranked = yield* rankSct(store, kept, ordinal, index.counts(lang), q, lang, tokens.length > 1, stats); + } + const codes = sctCodeMatches(store, q, active, stats); + const ids = codes.length ? (() => { const have = new Set(codes); return codes.concat(ranked.filter((id) => !have.has(id))); })() : ranked; + return { bm: new RoaringBitmap32(ids), ids: Uint32Array.from(ids) }; + }); +} + +/** tx/sct/text-index.js rankMatches; kept: the active candidates in concept order */ +function* rankSct(store, kept, ordinal, counts, q, lang, several, stats) { + if (!kept.length) return []; + const rate = function* (ids) { + const best = new Map(ids.map((id) => [id, 0])); + yield* namesOfG(store, 'snomed', ids, stats, (id, l, term) => { + if (l !== lang) return; + const r = q.nameRank(term, lang); + if (r > best.get(id)) best.set(id, r); + }); + return best; + }; + const byRank = (best) => (a, b) => best.get(b) - best.get(a) || ordinal(a) - ordinal(b); + if (several) { + // every word in one description: each candidate is rated, those without such a description dropped + const best = yield* rate(kept); + return yield* sortG(kept.filter((id) => best.get(id) > 0), byRank(best)); + } + const wc = (id) => counts[id] || 1; + const byCount = new Map(); + for (const id of kept) { const c = wc(id); byCount.set(c, (byCount.get(c) || 0) + 1); } + const distinct = [...byCount.keys()].sort((a, b) => a - b); + let cutoff = distinct[distinct.length - 1]; + let running = 0; + for (const c of distinct) { + running += byCount.get(c); + if (running >= RANK_REFINE_LIMIT) { cutoff = c; break; } + } + const head = [], tail = []; + for (const id of kept) (wc(id) <= cutoff ? head : tail).push(id); + const best = yield* rate(head); + for (const id of head) best.set(id, Math.max(best.get(id), 10)); + return head.sort(byRank(best)).concat(tail); +} + +/** + * The languages the file has active descriptions in (primary subtags), once per file. A stored + * index has one count row for each of them (computeTextIndexFrom: every name eachSearchName lists, words + * or none), so it answers at once; a file without one reads every description (0.1-0.3 s on a + * national edition), which only a text or display regex filter asks for. + */ +function sctTextLanguages(store) { + if (!store._textLangs) { + const idx = store.textIndex(); + const stored = idx ? idx.languages() : null; + if (stored) store._textLangs = new Set(stored); + else { + const defLang = store.defaultLanguage || 'en'; + store._textLangs = new Set(store.activeLanguages().map((l) => primaryLanguage(l, defLang))); + } + } + return store._textLangs; +} + +/** + * RxNorm: the concepts cs-rxnorm.js's text search selects from, those with an RXNCONSO atom + * (a SUPPRESS literal) of a term type other than SY + */ +function rxSearchable(store, stats) { + if (!store._rxSearchable) { + const { KIND } = require('./store'); + const sup = store.props.get('SUPPRESS'), tty = store.props.get('TTY'); + const bm = sup ? store.getSet(KIND.hasProp, sup.id, 0, stats).clone() : store.active(stats).clone(); + if (tty) { + const types = new RoaringBitmap32(); + for (const r of store.propValues(tty.id, stats)) if (r.value !== 'SY') types.orInPlace(store.getSet(KIND.prop, tty.id, r.value, stats)); + bm.andInPlace(types); + } + store._rxSearchable = bm; + } + return store._rxSearchable; +} + +// ---- LOINC ------------------------------------------------------------------------------------ + +/** + * The concepts a LOINC text filter matches, in the built-in provider's order (see the top). + * @param {string} lang the search language (primary subtag) + * @param {function} ordinal concept id -> the file's concept order (CodeKey) + * @returns {{bm: RoaringBitmap32, ids: Uint32Array}} + */ +function* loincTextSearchG(store, text, lang, ordinal, stats = null) { + return yield* cached(store, 'loinc\u0000' + lang + '\u0000' + text, function* () { + const q = new TextQuery(text); + const rank = new Map(); // concept -> rank (cs-loinc.js: codeRank, then a better nameRank) + const codes = codesInRanges(store, q.codeRanges(text), stats); + const codeRows = store.conceptRows(codes, stats); + for (const id of codes) rank.set(id, q.codeRank(codeRows.get(id).code)); + const tokens = q.tokens(lang); + if (tokens.length) { + const index = textIndexOf(store, 'loinc'); + if (index.langs.has(lang)) { + // every candidate's names in the search language, ranked as main ranks the TextIndex rows + // that match (bestRanks over their words column); a candidate none of whose names ranks is + // left out, as there + const bm = yield* candidates(index, lang, tokens, stats); + yield* namesOfG(store, 'loinc', bm.toArray(), stats, (id, l, term) => { + if (l !== lang) return; + const r = q.nameRank(indexedName(term), lang); + if (r > (rank.get(id) ?? 0)) rank.set(id, r); + }); + } + } + yield; + const rows = store.conceptRows([...rank.keys()], stats); + const disp = (id) => String(rows.get(id).display ?? ''); + // the best first; then by display (String.localeCompare, as cs-loinc.js), then CodeKey + const ids = yield* sortG([...rank.keys()], (a, b) => (rank.get(b) - rank.get(a)) || disp(a).localeCompare(disp(b)) || ordinal(a) - ordinal(b)); + return { bm: new RoaringBitmap32(ids), ids: Uint32Array.from(ids) }; + }); +} + +// ---- RxNorm ----------------------------------------------------------------------------------- + +/** + * RxNorm text filter as cs-rxnorm.js answers it (see the top). + * @param {RoaringBitmap32} eligible the concepts with an RXNCONSO atom other than SY + * @returns {{bm: RoaringBitmap32, ids: Uint32Array}} ids in RXCUI order (as text) + */ +function* rxTextSearchG(store, text, eligible, stats = null) { + return yield* cached(store, 'rx\u0000' + text, function* () { + const q = new TextQuery(text); + const tokens = q.tokens('en'); + let bm = new RoaringBitmap32(); + if (tokens.length) { + bm = (yield* candidates(textIndexOf(store, 'rxnorm'), 'en', tokens, stats)).andInPlace(eligible); + if (tokens.length > 1 && bm.size) bm = yield* inOneName(store, 'rxnorm', bm, q, 'en', stats); + } + const best = new Map(); // concept -> its best name's rank (bestRanks over RXNTEXT's words) + if (tokens.length && bm.size) { + yield* namesOfG(store, 'rxnorm', bm.toArray(), stats, (id, l, term) => { + const r = q.nameRank(indexedName(term), 'en'); + if (r > (best.get(id) ?? 0)) best.set(id, r); + }); + } + for (const id of codesInRanges(store, q.codeRanges(text), stats)) if (eligible.has(id)) bm.add(id); + yield; + const rows = store.conceptRows(bm.toArray(), stats); + const code = (id) => rows.get(id).code; + const rank = new Map([...rows.keys()].map((id) => [id, Math.max(best.get(id) ?? 0, q.codeRank(code(id)))])); + // cs-rxnorm.js #rank: the best first (nameRank or codeRank), then in RXCUI order (as text) + const ids = yield* sortG(bm.toArray(), (a, b) => (rank.get(b) - rank.get(a)) || cmpBinary(code(a), code(b))); + return { bm, ids: Uint32Array.from(ids) }; + }); +} + +// ---- other code systems (cs-cs.js) ------------------------------------------------------------ + +/** + * cs-cs.js searchFilter: a concept's rating is its best name in the search language that has every + * word of the filter (TextQuery.nameRank, less 10 for a designation that is not the display; at + * least 1), or for a code that starts with the filter (TextQuery.codeRank: 100 the code, 90 a code it + * starts), whichever is better; codes a supplement in use matches (and nothing else did) 10. In + * rating order, ties in the code system's order. + * @param {Iterable<{id, code, display, names: Array<[lang, text]>}>} concepts in the code system's order; + * names: the display (in the code system's language) and each designation (in its language or that one) + * @param {TextQuery} q + * @param {string} lang the search language (primary subtag) + * @param {Set} [supplementCodes] + * @returns {Array<{id, rating, supplement?, code?}>} sorted; supplement: rated by supplementCodes alone + */ +function rateConcepts(concepts, q, lang, supplementCodes = null) { + return runSync(rateConceptsG(concepts, q, lang, supplementCodes)); +} + +/** rateConcepts, pausing every RATE_CHUNK concepts; concepts may be a generator that pauses too */ +function* rateConceptsG(concepts, q, lang, supplementCodes = null) { + const hits = []; + let n = 0; + for (const c of concepts) { + if (c === PAUSE) { yield; continue; } + if (++n % RATE_CHUNK === 0) yield; + let rating = 0; + let named = false; + for (const [l, t] of c.names) { + if (l !== lang || !t) continue; + const r = q.nameRank(t, lang); + if (r > 0) { + named = true; + rating = Math.max(rating, r - (t === c.display ? 0 : 10)); + } + } + if (named) rating = Math.max(1, rating); + const cr = q.codeRank(c.code); + if (cr > 0) rating = Math.max(rating, cr); + if (rating > 0) hits.push({ id: c.id, rating }); + else if (supplementCodes && supplementCodes.has(c.code)) hits.push({ id: c.id, rating: 10, supplement: true, code: c.code }); + } + return yield* sortG(hits, (a, b) => b.rating - a.rating); +} + +/** the concepts of a file, for rateConcepts: display and designations */ +function* blockConcepts(store, csLang, stats) { + const lang = primaryLanguage(csLang, 'en'); + // two statements read side by side: a better-sqlite3 iterator holds its connection, so the + // designations are read whole first + const desRows = store.blockDesignations(); + let di = 0; + const des = { next: () => (di < desRows.length ? { done: false, value: desRows[di++] } : { done: true }) }; + let d = des.next(); + let rows = 0; + // read in chunks (no statement iterator is held across a pause: evaluate.js) + for (let from = store.lo; from <= store.hi; from += ROW_CHUNK) { + if (from > store.lo) yield PAUSE; + for (const [id, code, display] of store.blockConcepts(from, Math.min(from + ROW_CHUNK - 1, store.hi))) { + rows++; + const names = display ? [[lang, display]] : []; + while (!d.done && d.value[0] < id) d = des.next(); + while (!d.done && d.value[0] === id) { rows++; names.push([primaryLanguage(d.value[1], lang), d.value[2]]); d = des.next(); } + yield { id, code, display, names }; + } + } + if (stats) { stats.statements += 2; stats.rows += rows; } +} + +/** any other code system: cs-cs.js's rules over its concepts (rateConcepts) */ +function* genericTextSearchG(store, text, lang, csLang, stats = null, supplementCodes = null) { + const run = function* () { + const hits = yield* rateConceptsG(blockConcepts(store, csLang, stats), new TextQuery(text), lang, supplementCodes); + const ids = hits.map((h) => h.id); + return { bm: new RoaringBitmap32(ids), ids: Uint32Array.from(ids) }; + }; + return supplementCodes && supplementCodes.size ? yield* run() : yield* cached(store, 'gen\u0000' + lang + '\u0000' + csLang + '\u0000' + text, run); +} + +// the sync API (runSync): the same searches straight through +const sctTextSearch = (...a) => runSync(sctTextSearchG(...a)); +const loincTextSearch = (...a) => runSync(loincTextSearchG(...a)); +const rxTextSearch = (...a) => runSync(rxTextSearchG(...a)); +const genericTextSearch = (...a) => runSync(genericTextSearchG(...a)); + +module.exports = { + FORMAT, WordIndex, blockConcepts, indexed, eachSearchName, searchNamesOf, rxSearchable, + computeTextIndexFrom, textIndexOf, primaryLanguage, + sctTextSearch, sctTextLanguages, loincTextSearch, rxTextSearch, genericTextSearch, rateConcepts, + sctTextSearchG, loincTextSearchG, rxTextSearchG, genericTextSearchG +}; diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 0080b283..16ca243b 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -1151,6 +1151,11 @@ class ValueSetExpander { && !(this.count > 0 && this.count <= this.limitCount)) { throw new Issue("error", "too-costly", null, 'VALUESET_TOO_COSTLY', this.tooCostlyCountMessage(vsSrc.vurl || vsSrc.url, selection.total, this.limitCount), null, 422).withDiagnostics(this.worker.opContext.diagnostics()); } + // count=0 with a filter: the usual path walks the selection to count it, and refuses at the walk + // limit (#checkLimit); only a whole-system include is counted without a walk (countAllCodes) + if (!wholeSystemInclude && this.count === 0 && this.walkLimit > 0 && selection.total > this.walkLimit) { + throw new Issue("error", "too-costly", null, 'VALUESET_TOO_COSTLY', this.tooCostlyMessage(vsSrc.url, '>' + this.walkLimit), null, 422).withDiagnostics(this.worker.opContext.diagnostics()); + } for (const cset of [...includes, ...excludes]) { this.worker.checkSupplements(cs, cset, this.requiredSupplements, this.usedSupplements); @@ -1161,7 +1166,11 @@ class ValueSetExpander { notClosed.value = true; const wholeSystem = includes.some(cset => !(cset.filter || []).length); if (wholeSystem && cs.isNotClosed() && !Extensions.has(expansion, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason")) { - // as the usual path says for a whole grammar-based code system + // as the usual path says for a whole grammar-based code system, in its order: unclosed, + // then the reason + if (!Extensions.has(expansion, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed")) { + Extensions.addBoolean(expansion, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed", true); + } Extensions.addString(expansion, "http://hl7.org/fhir/StructureDefinition/valueset-unclosed-reason", "The code System '" + cs.system() + "' has a grammar and so has infinite members"); } } @@ -1191,14 +1200,48 @@ class ValueSetExpander { } } } - if (selection.total != null && selection.total >= 0) { + // the total as the usual path reports it: always for count=0; otherwise only for a selection + // within the response limit (#finishIfPageFilled: a paged walk that reaches the limit has no + // total, so the whole of LOINC or SNOMED CT with count=3 has none), or one whose page is never + // filled (the walk then runs to the end and counts everything: an offset past the last page) + if (selection.total != null && selection.total >= 0 && (this.count === 0 || this.limitCount <= 0 || selection.total < this.limitCount + || (this.count > 0 && selection.total - Math.max(this.offset, 0) < this.count))) { this.addToTotal(selection.total); } else { this.noTotal(); } + // where the walk ends with the expansion finished (#finishIfPageFilled), it skips what follows + // the compose in expand(), such as the required-supplement check: the same here, so a value set + // naming a supplement that no code system takes gets the walk's answer + if (this.#walkFinishesAfterPage(compose, cs, excludeInactive, selection.total)) { + throw new Issue('information', 'informational', null, null, null, null).setFinished(); + } return true; } + /** + * Whether the usual path's paged walk of this compose would stop with the expansion finished + * (#finishIfPageFilled, after each code it adds or counts): its page is full, and either the + * walk took the provider's size as the total (#useProviderSize: one include, the whole system or + * one filter, #sizeIsTotal), or the codes it has walked reach the response limit. Otherwise it + * counts every code to the end, and the expansion goes on as an unpaged one does. + * @param {number} total - the selection's total (null or -1: not counted) + */ + #walkFinishesAfterPage(compose, cs, excludeInactive, total) { + if (!(this.count > 0 && this.offset >= 0) || this.fullList.length < this.count) { + return false; + } + if (total == null || total < 0 || this.limitCount <= 0 || total >= this.limitCount) { + return true; + } + const includes = compose.include || []; + if (includes.length !== 1 || !this.#sizeIsTotal(compose, cs, excludeInactive)) { + return false; + } + const filters = includes[0].filter || []; + return filters.length === 0 ? !this.params.excludeNotForUI && !cs.isNotClosed() : filters.length === 1; + } + async includeCodes(cset, path, vsSrc, compose, filter, expansion, excludeInactive, notClosed) { await this.worker.checkAndYield('processCodes#1'); const valueSets = [];