diff --git a/library/server/config-check.js b/library/server/config-check.js index 35e54382..b860de38 100644 --- a/library/server/config-check.js +++ b/library/server/config-check.js @@ -889,7 +889,8 @@ const RETIRED_SOURCE_TYPES = { rxnorm: 'is no longer a source type: RxNorm is served from a sqlite-v2 file - import the release with tx-import rxnorm-v2, and load it with rxnorm-v2: (tx/importers/readme.md)' }; const SOURCE_TYPES = ['internal', 'ucum', 'loinc', 'ndc', 'unii', 'snomed', 'cpt', 'omop', 'icd11', - 'snomed-v2', 'loinc-v2', 'rxnorm-v2', 'npm', 'npm/cs', 'url', 'url/cs', 'ocl', 'folder', 'file']; + 'sqlite-v2', 'snomed-v2', 'loinc-v2', 'rxnorm-v2', 'ndc-v2', 'unii-v2', 'cpt-v2', + 'npm', 'npm/cs', 'url', 'url/cs', 'ocl', 'folder', 'file']; /** * The tx library yml: it parses, has a base url, and its sources are type[!]:details[=prefix] diff --git a/tests/cs/code-links.test.js b/tests/cs/code-links.test.js index b7909e33..06c50a10 100644 --- a/tests/cs/code-links.test.js +++ b/tests/cs/code-links.test.js @@ -86,11 +86,14 @@ describe('codeLink', () => { }); describe('sqlite-v2 files: the links main\'s providers give', () => { - // a factory with only what codeLink reads: the file's system and version - const v2 = (cls, system, version = '1') => factory(cls, { store: { system, version, cs: {} } }); + // a factory with only what codeLink reads: the file's system, version and meta codeLink (the + // template the importer writes; the `snomed` grammar has its own links) + const v2 = (cls, system, version = '1', codeLink = null) => factory(cls, { store: { system, version, cs: {}, codeLink } }); + const { LOINC_READING } = require('../../tx/importers/import-loinc-v2.module'); + const { RXNORM_READING } = require('../../tx/importers/import-rxnorm-v2.module'); test('LOINC: codes, parts and answers link to loinc.org', () => { - const f = v2(SqliteV2Factory, 'http://loinc.org', '2.83'); + const f = v2(SqliteV2Factory, 'http://loinc.org', '2.83', LOINC_READING.meta.codeLink); expect(f.codeLink(new V2Concept(1, '2345-7'))).toBe('https://loinc.org/2345-7/'); expect(f.codeLink(new V2Concept(2, 'LP14355-9'))).toBe('https://loinc.org/LP14355-9/'); expect(f.codeLink(new V2Concept(3, 'LA6576-8'))).toBe('https://loinc.org/LA6576-8/'); @@ -98,7 +101,7 @@ describe('codeLink', () => { }); test('RxNorm links to RxNav', () => { - const f = v2(SqliteV2Factory, 'http://www.nlm.nih.gov/research/umls/rxnorm', '11022026'); + const f = v2(SqliteV2Factory, 'http://www.nlm.nih.gov/research/umls/rxnorm', '11022026', RXNORM_READING.meta.codeLink); expect(f.codeLink(new V2Concept(1, '161'))).toBe('https://mor.nlm.nih.gov/RxNav/search?searchBy=RXCUI&searchTerm=161'); expect(f.codeLink(new V2Concept(1, null))).toBeUndefined(); expect(f.codeLink(null)).toBeUndefined(); @@ -106,6 +109,10 @@ describe('codeLink', () => { test('any other system in a sqlite-v2 file: no link', () => { expect(v2(SqliteV2Factory, 'http://example.org/cs').codeLink(new V2Concept(1, 'x'))).toBeUndefined(); + // the link is the file's, not the system's: a LOINC file without meta codeLink has none + expect(v2(SqliteV2Factory, 'http://loinc.org', '2.83').codeLink(new V2Concept(1, '2345-7'))).toBeUndefined(); + expect(v2(SqliteV2Factory, 'http://example.org/cs', '1', 'https://example.org/c/{code}').codeLink(new V2Concept(1, 'a b/c'))) + .toBe('https://example.org/c/a%20b%2Fc'); }); describe('SNOMED CT: as cs-snomed.js', () => { diff --git a/tests/library/server/config-check.test.js b/tests/library/server/config-check.test.js index 7c71ce9d..46d0e72b 100644 --- a/tests/library/server/config-check.test.js +++ b/tests/library/server/config-check.test.js @@ -227,6 +227,11 @@ describe('config-check', () => { expect(report.errors.map(e => e.message)).toEqual([expect.stringContaining('\'rxnorm\' is no longer a source type: RxNorm is served from a sqlite-v2 file')]); }); + test('the library: sqlite-v2, ndc-v2, unii-v2, and cpt-v2 source types are accepted', () => { + const report = check(txConfig({ librarySource: library('base:\n url: https://example.org\nsources:\n - sqlite-v2:omop.db\n - ndc-v2!:ndc.db\n - unii-v2:unii.db\n - cpt-v2:cpt.db\n') })); + expect(report.errors).toEqual([]); + }); + test('the library: no base url, and YAML that doesn\'t parse', () => { expect(check(txConfig({ librarySource: library('sources:\n - internal:lang\n') })).errors[0].message).toContain('no base: url:'); expect(check(txConfig({ librarySource: library('base: [\n') })).errors[0].message).toContain('can\'t be read'); diff --git a/tests/tx/library-sqlite-v2.test.js b/tests/tx/library-sqlite-v2.test.js index b7718e29..323e9ec3 100644 --- a/tests/tx/library-sqlite-v2.test.js +++ b/tests/tx/library-sqlite-v2.test.js @@ -98,5 +98,14 @@ describe('Library: sqlite-v2 source lines', () => { 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/); + await expect(load([`ndc-v2:${NAME}`])).rejects.toThrow(/holds http:\/\/snomed.info\/sct, not http:\/\/hl7.org\/fhir\/sid\/ndc/); + await expect(load([`unii-v2:${NAME}`])).rejects.toThrow(/holds http:\/\/snomed.info\/sct, not http:\/\/fdasis.nlm.nih.gov/); + await expect(load([`cpt-v2:${NAME}`])).rejects.toThrow(/holds http:\/\/snomed.info\/sct, not http:\/\/www.ama-assn.org\/go\/cpt/); + }); + + test('sqlite-v2 accepts any code system file', async () => { + const library = await load([`sqlite-v2!:${NAME}`]); + const factory = library.codeSystemFactories.get('http://snomed.info/sct'); + expect(factory.constructor.name).toBe('SnomedV2Factory'); }); }); diff --git a/tests/tx/sqlite-v2-alias-literals.test.js b/tests/tx/sqlite-v2-alias-literals.test.js new file mode 100644 index 00000000..6fd05c95 --- /dev/null +++ b/tests/tx/sqlite-v2-alias-literals.test.js @@ -0,0 +1,211 @@ +'use strict'; + +// property.alias_literals (README.md "Alternate codes"): an identifier scheme whose identifiers with +// resolves = 2 are codes in their own right (NDC's 11-digit forms of its 10-digit package codes). +// A code read through such an identifier reports the scheme's alias_literals instead of the concept's +// stored values ({code}: the concept's own code); a filter `=` the template's value on one of those +// properties lists the scheme's identifiers, in the order of their concepts; a membership check of +// such a code tests those properties by the template and every other property by its concept. The +// fixture is a small file of the same shape as the NDC importer's, nothing in it real. + +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 URI = 'http://example.org/packages'; +let app, tx, dir, factory; + +function build(file) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: URI, version: '20260101', name: 'Packages' }); + const codeType = b.property({ code: 'code-type', shape: 'literal', fhirType: 'string', lookupRank: 1 }); + const synonym = b.property({ code: 'synonym', shape: 'literal', fhirType: 'string', lookupRank: 2 }); + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'string', lookup: 'never', expansion: 'never' }); + const active = b.property({ code: 'active', shape: 'literal', fhirType: 'string', lookupRank: 6 }); + const category = b.property({ code: 'category', shape: 'literal', fhirType: 'string', lookupRank: 11 }); + const code11 = b.property({ code: 'code11', shape: 'identifier', lookup: 'never', expansion: 'never', + aliasLiterals: { 'code-type': '11-digit', synonym: '{code}' } }); + const rows = [ + // code, kind, code-type, 11-digit form, active, category + ['1111-222', 'product', 'product', null, true, 'A'], + ['1111-222-33', 'package', '10-digit', '01111022233', true, 'A'], + ['1111-222-44', 'package', '10-digit', '01111022244', false, 'A'], + ['5555-666', 'product', 'product', null, true, 'B'], + ['5555-666-77', 'package', '10-digit', '05555066677', true, 'B'], + ]; + for (const [code, k, type, c11, act, cat] of rows) { + const c = b.concept(code, { display: `${k} ${code}` }); + b.item(c, { language: 'en', text: `${k} ${code}`, preferred: true }); + b.literal(c, kind, k); + b.literal(c, codeType, type); + b.literal(c, active, act ? 'true' : 'false'); + b.literal(c, category, cat); + if (c11) { + b.literal(c, synonym, c11); + b.identifier(code11, c11, c, { resolves: 2 }); + } + } + b.reading({ + meta: { conceptStatus: [{ property: 'active', values: { false: ['inactive'] } }], version: { match: 'prefix' } }, + filters: [ + { code: 'inactive', operators: ['='], reads: 'inactive', allowedValues: ['true', 'false'] }, + { code: 'kind', operators: ['='], reads: 'kind', allowedValues: ['product', 'package'], valueCase: 'exact' }, + { code: 'category', operators: ['=', 'in'], reads: 'category', valueCase: 'exact' }, + { code: 'code-type', operators: ['='], reads: 'code-type', allowedValues: ['10-digit', '11-digit', 'product'], valueCase: 'exact' }, + ], + }); + b.finish(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-alias-')); + const file = path.join(dir, 'packages.db'); + build(file); + app = await getTestApp(); + tx = getTxModule(); + factory = await loadSqliteV2Factory(tx.i18n, file); + const p = tx.endpoints[0].provider; + p.codeSystemFactories.set(URI, factory); + p.codeSystemFactories.set(URI + '|20260101', factory); +}, 60000); + +afterAll(async () => { + factory.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +const vs = (include) => ({ resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: URI, ...include }] } }); + +async function post(op, parameter) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + return request(app).post(`/tx/r5/${op}`).send({ resourceType: 'Parameters', parameter }); +} + +async function expand(include, extras = []) { + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(include) }, ...extras]); + expect(res.status).toBe(200); + return (res.body.expansion.contains || []).map((c) => c.code); +} + +async function expandRaw(include, extras = []) { + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(include) }, ...extras]); + expect(res.status).toBe(200); + return res.body.expansion; +} + +async function lookup(code) { + const res = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: code }]); + expect(res.status).toBe(200); + return { + display: res.body.parameter.find((p) => p.name === 'display').valueString, + props: res.body.parameter.filter((p) => p.name === 'property' && p.part[0].valueCode !== 'inactive').map((p) => [p.part[0].valueCode, p.part[1].valueString ?? p.part[1].valueCode]), + }; +} + +async function validate(code, include) { + const parameter = [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: code }]; + if (include) parameter.push({ name: 'valueSet', resource: vs(include) }); + const res = await post(include ? 'ValueSet/$validate-code' : 'CodeSystem/$validate-code', parameter); + expect(res.status).toBe(200); + const p = (n) => (res.body.parameter.find((x) => x.name === n) || {}); + return { result: p('result').valueBoolean, code: p('code').valueCode, display: p('display').valueString }; +} + +const f = (property, op, value) => ({ property, op, value }); + +test('the file loads: alias_literals is read, not refused', () => { + expect(factory.store.aliasSchemes.map((d) => [d.code, d.aliasLiterals])).toEqual([['code11', { 'code-type': '11-digit', synonym: '{code}' }]]); +}); + +test('$lookup of an 11-digit form: the code as written, the template values in place of the stored ones', async () => { + const r = await lookup('01111022233'); + expect(r.display).toBe('package 1111-222-33'); + expect(r.props).toEqual([['code-type', '11-digit'], ['synonym', '1111-222-33'], ['active', 'true'], ['category', 'A']]); + const own = await lookup('1111-222-33'); + expect(own.props).toEqual([['code-type', '10-digit'], ['synonym', '01111022233'], ['active', 'true'], ['category', 'A']]); +}); + +test('$validate-code against the system: the 11-digit form is a code, answered as written', async () => { + expect(await validate('05555066677')).toEqual({ result: true, code: '05555066677', display: 'package 5555-666-77' }); + expect((await validate('05555066678')).result).toBe(false); +}); + +test('code-type = 11-digit lists the 11-digit forms, in their concepts\' order; other filters cut them by their concept', async () => { + // (concept id order: the inactive package is numbered after the active concepts) + expect(await expand({ filter: [f('code-type', '=', '11-digit')] })).toEqual(['01111022233', '05555066677', '01111022244']); + expect(await expand({ filter: [f('code-type', '=', '11-digit'), f('inactive', '=', 'false')] })).toEqual(['01111022233', '05555066677']); + expect(await expand({ filter: [f('code-type', '=', '11-digit'), f('category', '=', 'B')] })).toEqual(['05555066677']); + // the other code types list the concepts' own codes only + expect(await expand({ filter: [f('code-type', '=', '10-digit')] })).toEqual(['1111-222-33', '5555-666-77', '1111-222-44']); + expect(await expand({ filter: [f('kind', '=', 'package'), f('inactive', '=', 'false')] })).toEqual(['1111-222-33', '5555-666-77']); +}); + +test('membership of an 11-digit form: the template decides code-type, its concept the rest', async () => { + expect((await validate('01111022233', { filter: [f('code-type', '=', '11-digit')] })).result).toBe(true); + expect((await validate('01111022233', { filter: [f('code-type', '=', '10-digit')] })).result).toBe(false); + expect((await validate('01111022233', { filter: [f('kind', '=', 'package')] })).result).toBe(true); + expect((await validate('01111022244', { filter: [f('code-type', '=', '11-digit'), f('inactive', '=', 'false')] })).result).toBe(false); + expect((await validate('1111-222-33', { filter: [f('code-type', '=', '11-digit')] })).result).toBe(false); +}); + +test('an include that lists an 11-digit form expands it as written', async () => { + expect(await expand({ concept: [{ code: '05555066677' }, { code: '1111-222' }] })).toEqual(['05555066677', '1111-222']); + expect((await validate('05555066677', { concept: [{ code: '05555066677' }] })).result).toBe(true); +}); + +test('whole code system $expand (#485): count=0, paged, and full walk list all products and 10-digit packages', async () => { + const counted = await expandRaw({}, [{ name: 'count', valueInteger: 0 }]); + expect(counted.total).toBe(5); + expect(counted.contains).toBeUndefined(); + + const page = await expandRaw({}, [{ name: 'count', valueInteger: 2 }]); + expect(page.total).toBe(5); + expect(page.contains.length).toBe(2); + + const offsetPage = await expandRaw({}, [{ name: 'offset', valueInteger: 2 }, { name: 'count', valueInteger: 2 }]); + expect(offsetPage.total).toBe(5); + expect(offsetPage.contains.length).toBe(2); + + const full = await expandRaw({}); + expect(full.total).toBe(5); + expect(full.contains.map((c) => c.code).sort()).toEqual(['1111-222', '1111-222-33', '1111-222-44', '5555-666', '5555-666-77']); +}); + +test('combined category + code-type = 11-digit in either order (#484): expand, count=0, paging, and validate-code', async () => { + const catFirst = [f('category', '=', 'A'), f('code-type', '=', '11-digit')]; + const typeFirst = [f('code-type', '=', '11-digit'), f('category', '=', 'A')]; + for (const filter of [catFirst, typeFirst]) { + const exp = await expandRaw({ filter }); + expect(exp.total).toBe(2); + expect(exp.contains.map((c) => c.code)).toEqual(['01111022233', '01111022244']); + const counted = await expandRaw({ filter }, [{ name: 'count', valueInteger: 0 }]); + expect(counted.total).toBe(2); + const page = await expandRaw({ filter }, [{ name: 'count', valueInteger: 1 }]); + expect(page.total).toBe(2); + expect(page.contains.map((c) => c.code)).toEqual(['01111022233']); + // 11-digit form is in, 10-digit form is not + expect((await validate('01111022233', { filter })).result).toBe(true); + expect((await validate('1111-222-33', { filter })).result).toBe(false); + } + // contradictory 10-digit and 11-digit together: empty + const both = [f('code-type', '=', '10-digit'), f('code-type', '=', '11-digit')]; + const empty = await expandRaw({ filter: both }); + expect(empty.total).toBe(0); + expect(empty.contains).toBeUndefined(); + expect((await validate('01111022233', { filter: both })).result).toBe(false); + expect((await validate('1111-222-33', { filter: both })).result).toBe(false); +}); + +test('$expand with property=* on code-type = 11-digit reports template code-type and synonym', async () => { + const exp = await expandRaw({ filter: [f('category', '=', 'B'), f('code-type', '=', '11-digit')] }, [{ name: 'property', valueCode: '*' }]); + expect(exp.contains.length).toBe(1); + const props = new Map(exp.contains[0].property.map((p) => [p.code, p.valueString ?? p.valueCode])); + expect(props.get('code-type')).toBe('11-digit'); + expect(props.get('synonym')).toBe('5555-666-77'); + expect(props.get('category')).toBe('B'); +}); diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js index 9b721515..8f67e502 100644 --- a/tests/tx/sqlite-v2-builder.test.js +++ b/tests/tx/sqlite-v2-builder.test.js @@ -3,7 +3,9 @@ // 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. +// accepted as codes, the FHIR reading an importer declares (reading columns, item_use, filter rows, +// meta keys, concept.active from conceptStatus, the word index from search) and the format checks a +// reader makes before it reads a table. const fs = require('fs'); const os = require('os'); @@ -31,11 +33,13 @@ afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }); }); function buildFixture(dest, { explicitPairs = null } = {}) { const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); + // filters on colour, size and site (note: none, so no property = value sets) + b.reading({ filters: [{ each: { codes: ['colour', 'size', 'site'] }, operators: ['=', 'in'] }] }); 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 note = b.property({ code: 'note', shape: 'literal', fhirType: 'string' }); 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']) { @@ -62,7 +66,7 @@ function buildFixture(dest, { explicitPairs = 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 }); + const anc = b.property({ code: 'ancestor', shape: 'link' }); b.setClosureFrom(isa, anc); for (const [d, a] of explicitPairs) b.link(c[d], anc, c[a]); } @@ -127,11 +131,19 @@ describe('sqlite-v2 terminology file builder', () => { 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('the catalog\'s computed fields: subject kind, by_target for the hierarchy; the reading columns\' defaults', () => { + const row = (code) => db.prepare('SELECT shape, subject_kind, by_target, lookup, expansion, internal FROM property WHERE code = ?').get(code); + const dflt = { lookup: 'default', expansion: 'asked', internal: 0 }; + expect(row('isa')).toEqual({ shape: 'link', subject_kind: 'concept', by_target: 1, ...dflt }); + expect(row('colour')).toEqual({ shape: 'literal', subject_kind: 'concept', by_target: 0, ...dflt }); + expect(row('S1')).toEqual({ shape: 'record', subject_kind: 'concept', by_target: 0, ...dflt }); + // the filter rows of the reading: one per property the generator names, in property id order + expect(db.prepare('SELECT id, code, operators, reads, value_case FROM filter ORDER BY id').raw().all()).toEqual([ + [1, 'colour', '["=","in"]', '"colour"', 'any'], [2, 'size', '["=","in"]', '"size"', 'any'], [3, 'site', '["=","in"]', '"site"', 'any']]); + // no removed column; requires the revision + const cols = db.prepare('PRAGMA table_info(property)').all().map((c) => c.name); + for (const c of ['filterable', 'filter_ops', 'report', 'reported_as', 'named_links', 'default_value']) expect(cols).not.toContain(c); + expect(db.prepare("SELECT value FROM meta WHERE key = 'requires'").pluck().get()).toBe('["identifier-text","fhir-reading"]'); }); test('descendant sets equal the closure recomputed with a recursive CTE', () => { @@ -159,7 +171,7 @@ describe('sqlite-v2 terminology file builder', () => { 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', () => { + test('prop sets (the properties a filter row reads 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'])); @@ -352,44 +364,223 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check 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', () => { + test('meta keys: defaults, the ones a file sets, a malformed value or a key of an earlier revision refused at open, an unknown key ignored', () => { const S = openStore(file, { unregistered: true }); try { - expect(S.behaviour).toMatchObject({ grammar: null, expansionOrder: 'ids', lookupName: 'name', distinctDesignationTexts: false }); + expect(S.conceptStatus).toEqual([]); + expect(S.order).toEqual({}); + expect(S.versionRule).toEqual({ match: 'exact' }); + expect(S.search).toBeNull(); + expect(S.grammar).toBeNull(); } finally { S.close(); } - const bad = (key, value, msg) => { - const f = path.join(dir, 'behaviour.db'); + const withMeta = (name, rows) => { + const f = path.join(dir, name); fs.copyFileSync(file, f); const w = new Database(f); - w.prepare('INSERT INTO meta VALUES (?, ?)').run(key, value); + for (const [k, v] of rows) w.prepare('INSERT OR REPLACE INTO meta VALUES (?, ?)').run(k, v); w.close(); - expect(() => openStore(f)).toThrow(msg); + return f; }; - 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 }); + const bad = (key, value, msg) => expect(() => openStore(withMeta('bad-meta.db', [[key, value]]))).toThrow(msg); + bad('order', '{"expansion": ["sideways"]}', /meta order = .* is not a value this server knows/); + bad('version', '{"match": "fuzzy"}', /meta version = .* is not a value/); + bad('grammar', 'snomed', /is not JSON/); + bad('compatibility', '{"colour": true}', /meta compatibility = .* is not a value/); + bad('behaviour.grammar', '"snomed"', /behaviour.grammar is a key of an earlier revision/); + bad('ix.ix_word.names', '{}', /ix.ix_word.names is a key of an earlier revision/); + bad('requires', '["identifier-text"]', /written before the fhir-reading revision/); + const G = openStore(withMeta('meta-ok.db', [['colour', '"red"'], ['version', '{"match": "prefix"}']]), { 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']); + expect(G.versionRule).toEqual({ match: 'prefix' }); + expect(G.meta.get('colour')).toBe('"red"'); } finally { G.close(); } - const b = new TerminologyBuilder(path.join(dir, 'never.db'), { overwrite: true, importer: 'test' }); + // the builder refuses a key it does not know and a malformed value of one it knows + const never = (fn, msg) => { + 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'); + fn(b); + expect(() => b.finish()).toThrow(msg); + }; + never((b) => b.reading({ meta: { version: { match: 'nickname' } } }), /meta version = .* is not a value/); + never((b) => b.reading({ meta: { colour: 'red' } }), /meta colour is not a key this builder knows/); + }); +}); + +describe('sqlite-v2 the FHIR reading an importer declares', () => { + // A: status retired (inactive), B: status old (inactive and deprecated; the inactive reading + // ignored by compatibility), C: status hidden (unlisted), D: no status, stated inactive by the + // importer, E: stated inactive, status active + let file, db; + const reading = { + meta: { + conceptStatus: [{ property: 'status', values: { retired: ['inactive'], old: ['inactive', 'deprecated'], hidden: ['unlisted'] } }], + order: { expansion: ['id'], searchTies: ['code'] }, + search: { names: { items: { designations: true } }, shortlist: 10 }, + version: { match: 'prefix' }, + implicitMaps: { base: 'http://example.org/cm/', maps: [['http://example.org/m', 'm']] }, + compatibility: { statusReadingsIgnored: [{ property: 'status', values: { old: ['inactive'] } }], displayDesignation: 'once' }, + }, + rows: [ + { codeContains: '@', internal: true }, + { code: 'parent', fhirCode: 'broader', lookupRank: 1 }, + { valueSystem: 'http://example.org/other', fhirCode: 'other' }, + { code: 'status', lookup: 'never', expansion: 'never' }, + { shape: 'link', lookup: 'named', alsoAskedAs: ['linked'] }, + { shape: 'mapping', lookupRank: 9 }, + ], + newProperties: [ + { code: 'RELATED', shape: 'item-use', fhirType: 'string' }, + { code: 'UNUSED', shape: 'item-use', fhirType: 'string' }, + { code: 'm', shape: 'mapping', fhirType: 'Coding' }, + ], + uses: [ + { code: 'syn', role: 'display', languageDisplayRank: 1 }, + { code: 'rel', asProperty: 'RELATED' }, + { code: 'absent', asProperty: 'UNUSED' }, + ], + mappingsByImplicitMaps: true, + filters: [ + { each: { shapes: ['link', 'union'] }, operators: ['=', 'in'], valuePrefix: 'X:', linksAsDisplay: true }, + { code: 'kind', operators: ['='], reads: 'kind', valueCase: 'exact', whereLiteral: { status: 'active' } }, + { codePattern: '^p:(.+)$', operators: ['exists'], reads: '{1}' }, + { code: 'concept', operators: ['is-a', '='], reads: 'concept' }, + ], + }; + beforeAll(() => { + file = path.join(dir, 'reading.db'); + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/reading', version: '1' }); + b.reading(reading); + const parent = b.property({ code: 'parent', shape: 'link', subsumption: true, uri: 'http://example.org/parent' }); + const status = b.property({ code: 'status', shape: 'literal', fhirType: 'code', role: 'status' }); + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'code' }); + const rel = b.property({ code: 'rel', shape: 'link' }); + const relAt = b.property({ code: 'rel@x', shape: 'link', uri: 'http://example.org/rel' }); + const grp = b.property({ code: 'grp', shape: 'link' }); + b.propertyMember(grp, relAt); + const alt = b.property({ code: 'alt', shape: 'identifier', valueSystem: 'http://example.org/other' }); + const c = {}; + for (const [code, active] of [['A', true], ['B', true], ['C', true], ['D', false], ['E', false], ['R', true]]) c[code] = b.concept(code, { active, display: `display ${code}` }); + for (const code of ['A', 'B', 'C', 'D', 'E']) b.link(c[code], parent, c.R); + b.literal(c.A, status, 'retired'); + b.literal(c.B, status, 'old'); + b.literal(c.C, status, 'hidden'); + b.literal(c.E, status, 'active'); + b.literal(c.R, status, 'active'); + b.literal(c.A, kind, 'k1'); + b.link(c.A, rel, c.R); + b.link(c.B, relAt, c.R); + b.identifier(alt, 'Z1', c.A); + b.item(c.A, { language: 'en', use: { system: 's', code: 'syn' }, text: 'alpha name' }); + b.item(c.C, { language: 'en', use: { system: 's', code: 'syn' }, text: 'hidden name' }); + b.item(c.A, { language: 'en', use: { system: 's', code: 'rel' }, text: 'related words' }); + b.mapping(c.A, { system: 'http://example.org/m', code: 'M1', relationship: 'equivalent' }); + b.mapping(c.A, { system: 'http://example.org/unmapped', code: 'U1', relationship: 'equivalent' }); + b.finish(); + db = new Database(file, { readonly: true }); + }); + afterAll(() => db.close()); + + test('concept.active from conceptStatus: inactive exactly where a reading is inactive (less the ignored readings), active first', () => { + const rows = Object.fromEntries(db.prepare('SELECT code, active FROM concept').raw().all()); + expect(rows).toEqual({ A: 0, B: 1, C: 1, D: 1, E: 1, R: 1 }); + expect(db.prepare('SELECT active_count FROM code_system').pluck().get()).toBe(5); + expect(db.prepare("SELECT id FROM concept WHERE code = 'A'").pluck().get()).toBe(6); + }); + + test('the reading columns: the first rule that selects a row; internal rows never reported and without a uri', () => { + const cols = 'code, shape, fhir_code, also_asked_as, lookup, expansion, lookup_rank, internal, uri, subject_kind'; + const row = (code) => db.prepare(`SELECT ${cols} FROM property WHERE code = ?`).get(code); + expect(row('parent')).toMatchObject({ fhir_code: 'broader', lookup: 'default', lookup_rank: 1, also_asked_as: null }); + expect(row('rel')).toMatchObject({ shape: 'link', lookup: 'named', also_asked_as: '["linked"]' }); + expect(row('rel@x')).toMatchObject({ internal: 1, lookup: 'never', expansion: 'never', uri: null }); + expect(row('grp')).toMatchObject({ shape: 'union', lookup: 'default' }); + expect(row('alt')).toMatchObject({ fhir_code: 'other' }); + expect(row('status')).toMatchObject({ lookup: 'never', expansion: 'never' }); + // the rows the reading adds, after the importer's; an item-use row only where a use names it + expect(db.prepare('SELECT code, shape, fhir_type, lookup_rank, subject_kind FROM property WHERE id > 7 ORDER BY id').raw().all()) + .toEqual([['RELATED', 'item-use', 'string', null, 'concept'], ['m', 'mapping', 'Coding', 9, 'concept']]); + }); + + test('item_use, mapping.property_id by the implicit maps', () => { + expect(db.prepare('SELECT code, role, as_property, language_display_rank FROM item_use ORDER BY use_id').raw().all()) + .toEqual([['syn', 'display', null, 1], ['rel', null, 'RELATED', null]]); + const m = db.prepare("SELECT id FROM property WHERE code = 'm'").pluck().get(); + expect(db.prepare('SELECT code, property_id FROM mapping ORDER BY code').raw().all()).toEqual([['M1', m], ['U1', null]]); + }); + + test('the filter rows, in order: the generator (not internal rows), then the explicit ones', () => { + expect(db.prepare('SELECT code, code_pattern, operators, reads, value_prefix, value_case, value_as_display, where_literal FROM filter ORDER BY id').raw().all()).toEqual([ + ['parent', null, '["=","in"]', '"parent"', 'X:', 'any', 1, null], + ['rel', null, '["=","in"]', '"rel"', 'X:', 'any', 1, null], + ['grp', null, '["=","in"]', '"grp"', 'X:', 'any', 0, null], + ['kind', null, '["="]', '"kind"', null, 'exact', 0, '{"status":"active"}'], + [null, '^p:(.+)$', '["exists"]', '"{1}"', null, 'any', 0, null], + ['concept', null, '["is-a","="]', '"concept"', null, 'any', 0, null]]); + }); + + test('ix_set kind 5 sets: the properties a filter row reads (union members, {1} captures), where_literal, conceptStatus', () => { + const { setPropertyIds } = require('../../tx/importers/sqlite-v2/indexes'); + const code = (id) => db.prepare('SELECT code FROM property WHERE id = ?').pluck().get(id); + expect([...setPropertyIds(db)].map(code).sort()).toEqual(['alt', 'grp', 'kind', 'parent', 'rel', 'rel@x', 'status']); + const withSets = db.prepare('SELECT DISTINCT p.code FROM ix_set x JOIN property p ON p.id = x.property_id WHERE x.kind = 5 ORDER BY 1').pluck().all(); + // (parent: the hierarchy; alt: an identifier, never a property = value set) + expect(withSets).toEqual(['kind', 'parent', 'rel', 'rel@x', 'status']); + }); + + test('the word index from search.names, without the unlisted concepts; the counts row with search.shortlist', () => { + const words = db.prepare("SELECT word FROM ix_word WHERE word <> '' ORDER BY 1").pluck().all(); + expect(words).toContain('alpha'); + expect(words).not.toContain('hidden'); + expect(words).toContain('related'); // (excludeUses not stated: every designation and item) + expect(db.prepare("SELECT length(ids) FROM ix_word WHERE word = ''").pluck().get()).toBe(2 * 7); + expect(db.prepare("SELECT count(*) FROM meta WHERE key LIKE 'ix.ix_word.%'").pluck().get()).toBe(2); + }); + + test('the reader opens it; verify finds every contract kept', () => { + const S = openStore(file, { unregistered: true }); + try { + expect(S.filters.map((f) => f.code ?? String(f.pattern))).toHaveLength(6); + expect(S.catalog.get('RELATED').use.code).toBe('rel'); + } finally { S.close(); } + const { verifyFile } = require('../../tx/importers/sqlite-v2/verify'); + expect(verifyFile(file).filter((r) => !r.ok)).toEqual([]); + }); + + test('without search: no word index and no ix.ix_word keys; without a reading: no filter rows', () => { + const f = path.join(dir, 'nosearch.db'); + const b = new TerminologyBuilder(f, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/x', version: '1' }); + const a = b.concept('a', { display: 'some words' }); + b.item(a, { language: 'en', text: 'more words' }); + b.finish(); + const d = new Database(f, { readonly: true }); + try { + expect(d.prepare('SELECT count(*) FROM ix_word').pluck().get()).toBe(0); + expect(d.prepare("SELECT count(*) FROM meta WHERE key LIKE 'ix.ix_word.%'").pluck().get()).toBe(0); + expect(d.prepare('SELECT count(*) FROM filter').pluck().get()).toBe(0); + } finally { d.close(); } + }); + + test('refused: a property spec of an earlier revision, an unknown reading member, a filter named by an internal row', () => { + const b = new TerminologyBuilder(path.join(dir, 'never2.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/); + expect(() => b.property({ code: 'p', shape: 'literal', fhirType: 'string', filterable: false })).toThrow(/filterable belong to an earlier revision/); + expect(() => b.property({ code: 'q', shape: 'link', report: 'never' })).toThrow(/report belong to an earlier revision/); + expect(() => b.reading({ behaviour: {} })).toThrow(/unknown member behaviour/); + const c = new TerminologyBuilder(path.join(dir, 'never3.db'), { overwrite: true, importer: 'test' }); + c.codeSystem({ uri: 'http://example.org/x', version: '1' }); + c.reading({ rows: [{ code: 'secret', internal: true }], filters: [{ code: 'secret', operators: ['='], reads: 'secret' }] }); + c.property({ code: 'secret', shape: 'literal', fhirType: 'string' }); + c.concept('a'); + expect(() => c.finish()).toThrow(/named by the internal property secret/); + // a filter of another name may read it + const d = new TerminologyBuilder(path.join(dir, 'never4.db'), { overwrite: true, importer: 'test' }); + d.codeSystem({ uri: 'http://example.org/x', version: '1' }); + d.reading({ rows: [{ code: 'secret', internal: true }], filters: [{ code: 'open', operators: ['='], reads: 'secret' }] }); + d.property({ code: 'secret', shape: 'literal', fhirType: 'string' }); + d.concept('a'); + expect(() => d.finish()).not.toThrow(); }); }); diff --git a/tests/tx/sqlite-v2-cpt-grammar.test.js b/tests/tx/sqlite-v2-cpt-grammar.test.js new file mode 100644 index 00000000..9075466a --- /dev/null +++ b/tests/tx/sqlite-v2-cpt-grammar.test.js @@ -0,0 +1,175 @@ +'use strict'; + +// meta grammar `cpt` (README.md "Grammar", tx/sqlite-v2/cpt.js): a code may be a base code followed +// by `:`-separated modifiers, valid by upstream's rule set (tx/cs/cs-cpt.js, run through that +// provider); `modified = true` selects no concept and admits expressions (an expansion stays open), +// `modified = false` every concept; $lookup of an expression lists the copyright, the base code's +// lookup, and each modifier with its first designation. The fixture is invented: its codes are not +// CPT's (the rules name a few modifier codes, 25, 59 and 95, which it uses), its texts made up. + +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 URI = 'http://example.org/procedures'; +let app, tx, dir, factory; + +function build(file) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: URI, version: '2023', name: 'Procedures', resource: { resourceType: 'CodeSystem', id: 'procedures', copyright: 'Test copyright notice' } }); + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'string', lookupRank: 0 }); + const tele = b.property({ code: 'telemedicine', shape: 'literal', fhirType: 'string' }); + const modifier = b.property({ code: 'modifier', shape: 'literal', fhirType: 'string', lookup: 'never', expansion: 'never' }); + const concepts = [ + ['A0001', 'code', false, 'Visit of one kind', true], + ['A0002', 'code', false, 'Visit of another kind', false], + ['25', 'general', true, 'Separate service on the same day', false], + ['59', 'general', true, 'Distinct procedural service', false], + ['95', 'general', true, 'Service rendered remotely', false], + ]; + for (const [code, k, mod, text, remote] of concepts) { + const c = b.concept(code, { display: text }); + b.literal(c, kind, k); + b.literal(c, modifier, mod ? 'true' : 'false'); + if (remote) b.literal(c, tele, 'true'); + b.item(c, { language: 'en', text, use: { code: 'display', display: 'display' }, preferred: true }); + b.item(c, { language: 'en', text: text.toUpperCase(), use: { code: 'upper', display: 'upper' } }); + } + b.reading({ + meta: { + conceptStatus: [{ property: 'kind', values: { metadata: ['notSelectable'] } }], + expansionLimits: { maxCodes: 1000 }, version: { match: 'prefix' }, grammar: 'cpt', + compatibility: { designationUse: 'none', typedDesignationsInLookup: true, lookupListsCopyright: true }, + }, + filters: [ + { code: 'kind', operators: ['='], reads: 'kind', valueCase: 'exact' }, + { code: 'modifier', operators: ['='], reads: 'modifier', allowedValues: ['true', 'false'] }, + { code: 'modified', operators: ['='], reads: 'grammar', allowedValues: ['true', 'false'] }, + ], + }); + b.finish(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-cpt-')); + const file = path.join(dir, 'procedures.db'); + build(file); + app = await getTestApp(); + tx = getTxModule(); + factory = await loadSqliteV2Factory(tx.i18n, file); + const p = tx.endpoints[0].provider; + p.codeSystemFactories.set(URI, factory); + p.codeSystemFactories.set(URI + '|2023', factory); +}, 60000); + +afterAll(async () => { + factory.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +const vs = (include) => ({ resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: URI, ...include }] } }); +const f = (property, op, value) => ({ property, op, value }); + +async function post(op, parameter) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + return request(app).post(`/tx/r5/${op}`).send({ resourceType: 'Parameters', parameter }); +} + +async function validate(code, include) { + const parameter = [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: code }]; + if (include) parameter.push({ name: 'valueSet', resource: vs(include) }); + const res = await post(include ? 'ValueSet/$validate-code' : 'CodeSystem/$validate-code', parameter); + expect(res.status).toBe(200); + const p = (n) => (res.body.parameter.find((x) => x.name === n) || {}); + // (the locate message is one of the issues' texts) + return { result: p('result').valueBoolean, message: JSON.stringify(res.body) }; +} + +async function expand(include) { + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(include) }]); + expect(res.status).toBe(200); + const open = (res.body.expansion.extension || []).some((e) => /valueset-unclosed/.test(e.url) && e.valueBoolean); + return { codes: (res.body.expansion.contains || []).map((c) => c.code), open }; +} + +test('the file loads: the grammar cpt is served', () => { + expect(factory.constructor.grammar).toBe('cpt'); +}); + +test('an expression the rules allow is a code; one they do not is not, with the rule\'s message', async () => { + expect((await validate('A0001:95')).result).toBe(true); + const remote = await validate('A0002:95'); + expect(remote.result).toBe(false); + expect(remote.message).toMatch(/The modifier 95 cannot be used with the code A0002 as it is not designated for telemedicine/); + const both = await validate('A0001:25:59'); + expect(both.result).toBe(false); + expect(both.message).toMatch(/There can only be one modifier in the set 25, 57, 59/); + expect((await validate('A0001:ZZ')).message).toMatch(/Modifier CPT code 'ZZ' not found/); + expect((await validate('ZZ:95')).message).toMatch(/Base CPT Code 'ZZ' not found/); +}); + +test('$lookup of an expression: the copyright, the base code\'s lookup (its copyright again), each modifier', async () => { + const res = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: 'A0001:95' }]); + expect(res.status).toBe(200); + const props = res.body.parameter.filter((p) => p.name === 'property' && p.part[0].valueCode !== 'inactive').map((p) => [p.part[0].valueCode, p.part[1].valueString ?? p.part[1].valueCode]); + expect(props).toEqual([['copyright', 'Test copyright notice'], ['copyright', 'Test copyright notice'], ['kind', 'code'], ['telemedicine', 'true'], + ['modifier', '95'], ['modifier-definition', 'Service rendered remotely']]); + // the base code's typed designations + const typed = res.body.parameter.filter((p) => p.name === 'designation').map((p) => p.part.map((x) => x.valueCode ?? x.valueString)); + expect(typed).toEqual([['display', 'Visit of one kind', 'en'], ['upper', 'VISIT OF ONE KIND', 'en']]); +}); + +test('$lookup of an expression with property=*: the notSelectable of the expression after the modifiers, not the base code\'s', async () => { + const res = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: 'A0001:95' }, { name: 'property', valueCode: '*' }]); + expect(res.status).toBe(200); + const props = res.body.parameter.filter((p) => p.name === 'property').map((p) => p.part[0].valueCode); + expect(props).toEqual(['inactive', 'copyright', 'copyright', 'kind', 'telemedicine', 'modifier', 'modifier-definition', 'notSelectable']); + expect(res.body.parameter.filter((p) => p.name === 'property' && p.part[0].valueCode === 'notSelectable')[0].part[1].valueBoolean).toBe(false); + // a plain code: its own notSelectable, after its properties + const plain = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: 'A0001' }, { name: 'property', valueCode: '*' }]); + expect(plain.body.parameter.filter((p) => p.name === 'property').map((p) => p.part[0].valueCode).slice(-1)).toEqual(['notSelectable']); +}); + +test('modified = true: no concept, an open expansion; an expression is a member only of filters that are all modified = true', async () => { + expect(await expand({ filter: [f('modified', '=', 'true')] })).toEqual({ codes: [], open: true }); + const all = await expand({ filter: [f('modified', '=', 'false')] }); + expect(all.codes.sort()).toEqual(['25', '59', '95', 'A0001', 'A0002']); + expect(all.open).toBe(false); + expect((await expand({ filter: [f('modifier', '=', 'true')] })).codes.sort()).toEqual(['25', '59', '95']); + expect((await validate('A0001:95', { filter: [f('modified', '=', 'true')] })).result).toBe(true); + expect((await validate('A0001:95', { filter: [f('kind', '=', 'code')] })).result).toBe(false); + expect((await validate('A0001:95', { filter: [f('modified', '=', 'false')] })).result).toBe(false); + expect((await validate('A0001:95', { filter: [f('modifier', '=', 'true')] })).result).toBe(false); + expect((await validate('A0001:95', { filter: [f('modifier', '=', 'false')] })).result).toBe(false); + expect((await validate('A0001:95', { filter: [f('modified', '=', 'true'), f('kind', '=', 'code')] })).result).toBe(false); + expect((await validate('A0001', { filter: [f('modified', '=', 'true')] })).result).toBe(false); + expect((await validate('A0001', { filter: [f('modified', '=', 'false')] })).result).toBe(true); +}); + +test('invalid expressions against open vs closed filters (#486): open reports the parse reason, closed does not', async () => { + // open filter (modified = true): expression parse error is reported + const badModOpen = await validate('A0001:ZZ', { filter: [f('modified', '=', 'true')] }); + expect(badModOpen.result).toBe(false); + expect(badModOpen.message).toMatch(/Modifier CPT code 'ZZ' not found/); + const badBaseOpen = await validate('ZZ:95', { filter: [f('modified', '=', 'true')] }); + expect(badBaseOpen.result).toBe(false); + expect(badBaseOpen.message).toMatch(/Base CPT Code 'ZZ' not found/); + const exclOpen = await validate('A0001:25:59', { filter: [f('modified', '=', 'true')] }); + expect(exclOpen.result).toBe(false); + expect(exclOpen.message).toMatch(/There can only be one modifier in the set 25, 57, 59/); + + // closed filters (modified = false, kind = code, modifier = false): do not parse expressions + for (const flt of [f('modified', '=', 'false'), f('kind', '=', 'code'), f('modifier', '=', 'false')]) { + const badBaseClosed = await validate('ZZ:95', { filter: [flt] }); + expect(badBaseClosed.result).toBe(false); + expect(badBaseClosed.message).not.toMatch(/Base CPT Code 'ZZ' not found/); + const badModClosed = await validate('A0001:ZZ', { filter: [flt] }); + expect(badModClosed.result).toBe(false); + expect(badModClosed.message).not.toMatch(/Modifier CPT code 'ZZ' not found/); + } +}); diff --git a/tests/tx/sqlite-v2-cs-ids.test.js b/tests/tx/sqlite-v2-cs-ids.test.js index b3e79eb2..f37b14f2 100644 --- a/tests/tx/sqlite-v2-cs-ids.test.js +++ b/tests/tx/sqlite-v2-cs-ids.test.js @@ -98,17 +98,22 @@ describe('main\'s id() and the engine\'s, over a table of versions', () => { const mainLoinc = (v) => Object.assign(Object.create(LoincServicesFactory.prototype), { _sharedData: { _version: v } }); const mainRxNorm = (v) => ({ id: () => rxnormV1('cs-ids', 'id ' + v) }); // main's, recorded const mainSct = (v, edition) => Object.assign(Object.create(SnomedServicesFactory.prototype), { _sharedData: { versionUri: v, edition } }); + // the engine's id is the stored CodeSystem resource's id, which the importers form (their + // catalog-id functions, compared here with main's over the table), and the factory reads + const { loincCatalogId } = require('../../tx/importers/import-loinc-v2.module'); + const { rxnormCatalogId } = require('../../tx/importers/import-rxnorm-v2.module'); + const { sctCatalogId, sctCatalogName } = require('../../tx/importers/sct-v2-common'); + const resource = (id, name) => JSON.stringify({ resourceType: 'CodeSystem', ...(id ? { id: 'x-' + id } : {}), ...(name ? { name } : {}) }); 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); + expect(loincCatalogId(v)).toBe(mainLoinc(v).id()); + expect(v2(SqliteV2Factory, LOINC, v, { resource: resource(loincCatalogId(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); + expect(rxnormCatalogId(v)).toBe(mainRxNorm(v).id()); + expect(v2(SqliteV2Factory, RXNORM, v, { name: 'RxNorm', resource: resource(rxnormCatalogId(v)) }).id()).toBe('RxNorm-' + v); }); test.each([ @@ -122,15 +127,17 @@ describe('main\'s id() and the engine\'s, over a table of versions', () => { ['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(sctCatalogId(v)).toBe(mainSct(v, edition).id()); + const engine = v2(SnomedV2Factory, SCT, v, { edition, resource: resource(sctCatalogId(v), sctCatalogName(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' }); + const at = (v) => v2(SnomedV2Factory, SCT, v, { edition: '31000003106', resource: resource(sctCatalogId(v)) }); + const a = at('http://snomed.info/xsct/31000003106/version/20250909'); + const b = at('http://snomed.info/xsct/31000003106/version/20240909'); 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 index 9ca36d4e..0713bf59 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -11,7 +11,6 @@ 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'); @@ -29,6 +28,15 @@ let rx; function buildFixture(dest) { const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); + // the filters this system understands (a filter that is no row is not understood) + const all = ['=', 'is-a', 'descendent-of', 'is-not-a', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'regex']; + const ops = ['=', 'in', 'not-in', 'exists', 'regex']; + // the display listed first among the designations (compatibility.displayDesignation once) + b.reading({ meta: { compatibility: { displayDesignation: 'once' } }, filters: [ + { code: 'concept', operators: all, reads: 'concept' }, { code: 'code', operators: all, reads: 'concept' }, + { code: 'colour', operators: ops, reads: 'colour' }, { code: 'site', operators: ops, reads: 'site' }, + { code: 'laterality', operators: ops, reads: 'laterality' }, { code: 'display', operators: ['=', 'in', 'regex'], reads: 'display' }, + ] }); 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 @@ -55,13 +63,25 @@ function buildRx(dest) { 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 hpiRN = b.property({ code: 'has_precise_ingredient@RN', shape: 'link', internal: true }); 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'); + // the listed concepts: 1-4; 5 is archived (status archived: inactive and unlisted, in the file, never selected) + const status = b.property({ code: 'status', shape: 'literal', fhirType: 'code', role: 'status' }); + b.literal(c['5'], status, 'archived'); + const rels = ['has_precise_ingredient', 'has_ingredient', 'RN', 'RO']; + b.reading({ + meta: { conceptStatus: [{ property: 'status', values: { archived: ['inactive', 'deprecated', 'unlisted'] } }] }, + filters: [ + { code: 'TTY', operators: ['=', 'in'], reads: 'TTY', codeAnyCase: true }, + ...rels.map((r) => ({ code: r, operators: ['=', 'in'], reads: r, valuePrefix: 'CUI:' })), + { code: 'concept', operators: ['=', 'in'], reads: 'concept' }, { code: 'code', operators: ['=', 'in'], reads: 'concept' }, + ], + }); 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 @@ -96,7 +116,7 @@ function codesOf(S, ids) { 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 c = new Compiler({ store: S, grammar: S.grammar === 'snomed' ? require('../../tx/sqlite-v2/snomed').SnomedV2Factory.grammarRules : {}, layers }); const r = e.run(c.selection(includes, excludes, activeOnly), { offset, count }); return { r, codes: codesOf(S, r.page(offset, count)) }; } @@ -125,12 +145,12 @@ describe('sqlite-v2 engine: filters as set algebra', () => { 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']); + test('a filter is a row of the file: designation (no row) is not understood; display and code regex match the whole text', () => { + expect(() => expand(store, [inc([f('designation', '=', 'effervescent thing')])])).toThrow('not understood or supported'); + // regex matches the whole text (tx-ecosystem simple-expand-regex, expand-regex-bad) + expect(expand(store, [inc([f('display', 'regex', 'display')])]).codes).toEqual([]); + expect(expand(store, [inc([f('display', 'regex', 'display [DF]')])]).codes.sort()).toEqual(['D', 'F']); + expect(expand(store, [inc([f('display', '=', 'display D')])]).codes).toEqual(['D']); 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([]); }); @@ -140,7 +160,7 @@ describe('sqlite-v2 engine: filters as set algebra', () => { const saved = settings.maxScanRows; settings.maxScanRows = 3; try { - expect(() => expand(store, [inc([f('designation', 'regex', 'x')])])).toThrow(/estimated cost/); + expect(() => expand(store, [inc([f('display', 'regex', '.')])])).toThrow(/estimated cost/); } finally { settings.maxScanRows = saved; } @@ -162,7 +182,7 @@ describe('sqlite-v2 engine: filters as set algebra', () => { }); 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 ev = (text) => codesOf(store, new Engine(store).evaluate(new Compiler({ store, grammar: {} }).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 @@ -177,12 +197,12 @@ describe('sqlite-v2 engine: filters as set algebra', () => { test('ECL: refinements, groups, cardinality, reverse, dotted', () => { const ecl = (text) => { - const c = new Compiler({ store, dialect: {} }); + const c = new Compiler({ store, grammar: {} }); 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 c = new Compiler({ store, grammar: {} }); 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 }); @@ -204,7 +224,7 @@ describe('sqlite-v2 engine: filters as set algebra', () => { 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 c = new Compiler({ store, grammar: {} }); 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); @@ -213,7 +233,7 @@ describe('sqlite-v2 engine: filters as set algebra', () => { 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 c = new Compiler({ store, grammar: {} }); 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 }); @@ -259,6 +279,17 @@ describe('sqlite-v2 supplement layers', () => { expect(expand(store, [inc([f('concept', 'is-a', 'D'), f('flavour', 'exists', 'false')])], { layers }).codes).toEqual([]); }); + test('non-enumerable supplement-only filters (not-in, exists=false alone) are refused as FILTER_NOT_UNDERSTOOD', () => { + const layers = new LayerSet([{ json: supp, build: () => ({ layer: buildLayer(store, supp), entry: null }) }]); + expect(() => expand(store, [inc([f('flavour', 'not-in', 'sweet')])], { layers })) + .toThrow('The filter "flavour not-in sweet" is not understood or supported'); + expect(() => expand(store, [inc([f('flavour', 'exists', 'false')])], { layers })) + .toThrow('The filter "flavour exists false" is not understood or supported'); + // combined with an enumerable supplement filter or a base filter: allowed + expect(expand(store, [inc([f('flavour', 'exists', 'true'), f('flavour', 'not-in', 'sweet')])], { layers }).codes).toEqual(['D']); + expect(expand(store, [inc([f('concept', 'is-a', 'D'), f('flavour', 'not-in', 'sweet')])], { layers }).codes).toEqual(['D']); + }); + describe('the layer cache', () => { const { SupplementLayers, layerCache } = require('../../tx/sqlite-v2/layers'); const { settings } = require('../../tx/sqlite-v2/settings'); @@ -339,7 +370,7 @@ describe('sqlite-v2 supplement layers', () => { 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`); } } }); + const c = new Compiler({ store, grammar: { 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'); }); }); @@ -350,14 +381,23 @@ describe('sqlite-v2 SNOMED concept in / code in', () => { 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 ops = ['=', 'is-a', 'descendent-of', 'child-of', 'generalizes', 'in', 'is-not-a', 'descendent-leaf']; + b.reading({ meta: { grammar: 'snomed' }, filters: [{ code: 'concept', operators: ops, reads: 'concept' }, { code: 'code', operators: ops, reads: 'concept' }] }); 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']); + for (const code of ['138875005', '1001001', '1002001', '1003001', '1004001', '9001001', '9002001', '9003001', '900000000000548007']) c[code] = b.concept(code, { active: true, display: 'c ' + code }); + for (const k of ['1001001', '1002001', '1003001', '1004001', '9001001', '9002001', '9003001', '900000000000548007']) 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']); + // a reference set with no active members + const empty = b.property({ code: '9002001', shape: 'record', concept: c['9002001'], fields: [] }); + b.record(empty, c['1003001'], { active: false }); + // a language reference set: its members are descriptions (items) + const lang = b.property({ code: '9003001', shape: 'record', role: 'language', concept: c['9003001'], fields: [{ name: 'acceptabilityId', type: 'c', target: true }] }); + b.record(lang, b.item(c['1004001'], { language: 'nl', text: 'term 1004001' }), { target: c['900000000000548007'] }); + b.setMeta('displayContexts', { relations: [], preferred: '900000000000548007' }); b.finish(); sct = openStore(path.join(dir, 'sct.db')); }); @@ -375,14 +415,24 @@ describe('sqlite-v2 SNOMED concept in / code in', () => { } expect(() => expand(sct, [sinc([f('code', 'in', '1003001,41000147108')])])).toThrow('The SNOMED CT Concept 41000147108 is not known'); }); + + test('a refset with no active members is none; a language refset (description members) is refused, as ECL ^ is', () => { + expect(expand(sct, [sinc([f('concept', 'in', '9002001')])]).codes).toEqual([]); + expect(expand(sct, [sinc([f('concept', 'in', '9002001,1004001')])]).codes).toEqual(['1004001']); + const refused = 'The members of reference set 9003001 are descriptions, not concepts, so concept in cannot be evaluated for it'; + expect(() => expand(sct, [sinc([f('concept', 'in', '9003001')])])).toThrow(refused); + expect(() => expand(sct, [sinc([f('concept', 'in', '1001001,9003001')])])).toThrow(refused); + expect(() => new Compiler({ store: sct, grammar: {} }).ecl('^ 9003001')).toThrow('The members of reference set 9003001 are descriptions, not concepts, so ^ cannot be evaluated for it'); + }); }); 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 fake = { store: { ...store, valueLabels: (p) => (p.code === 'colour' ? { red: 'Clinical class' } : null), propValues: store.propValues.bind(store), props: store.props, compat: store.compat, resolveCodes: store.resolveCodes.bind(store), idOf: store.idOf.bind(store), hierarchy: store.hierarchy, system: store.system }, grammar: {} }; const c = new C(fake); - const n = c.filter('colour', '=', 'clinical CLASS'); + // a filter row with value_as_display: a value may be a value label + const n = c.propertyFilter(store.catalog.get('colour'), '=', 'clinical CLASS', { asDisplay: true, exactCase: false }); expect(new Engine(store).evaluate(n).size).toBe(2); // 'red' (F) and 'Red' (G): literal values match without case, as upstream }); }); @@ -565,7 +615,7 @@ describe('sqlite-v2 provider (cs-api contract)', () => { 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 inc = [{ system: 'http://example.org/cs', filter: [{ property: 'display', op: 'regex', value: '.' }] }]; const saved = settings.maxScanRows; settings.maxScanRows = 3; try { @@ -593,7 +643,7 @@ describe('sqlite-v2 provider (cs-api contract)', () => { 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'); + await expect(p.filter(it, true, 'nonsense', '=', 'x')).rejects.toThrow('not understood or supported'); }); test('filter API: a chunk\'s designations are read when one of its codes first needs them, in one statement', async () => { @@ -633,10 +683,13 @@ describe('sqlite-v2 provider (cs-api contract)', () => { // 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' }); + // one file per selection of names (meta search.names): LOINC's (the display and the names but + // RELATEDNAMES2) and SNOMED CT's (active designations) + let ts, td; + const build = (name, names) => { + const b = new TerminologyBuilder(path.join(dir, name), { overwrite: true, importer: 'test' }); b.codeSystem({ uri: 'http://example.org/text', version: '1' }); + b.reading({ meta: { search: names } }); 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' }); @@ -644,24 +697,28 @@ describe('text filter in one language (store.searchText)', () => { 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')); + return openStore(path.join(dir, name)); + }; + beforeAll(() => { + td = build('text.db', { names: { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } } }); + ts = build('text-desig.db', { names: { items: { active: true, designations: true } }, shortlist: 200 }); }); - afterAll(() => ts.close()); - const ids = (bm) => bm.toArray().map((id) => ts.conceptRows([id]).get(id).code).sort(); + afterAll(() => { ts.close(); td.close(); }); + const ids = (bm, s = ts) => bm.toArray().map((id) => s.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']); + test('the display and the names but RELATEDNAMES2: English searches displays, German the German names but not RELATEDNAMES2', () => { + expect(ids(td.searchText('volumen', null, 'en'), td)).toEqual([]); + expect(ids(td.searchText('volumen', null, 'de'), td)).toEqual(['G']); + expect(ids(td.searchText('glucose', null, 'en'), td)).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([]); + expect(ids(td.searchText('hgb', null, 'en'), td)).toEqual(['H']); + expect(ids(td.searchText('blut', null, 'de'), td)).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']); + test('designations only: those in the language', () => { + expect(ids(ts.searchText('volumen', null, 'de'))).toEqual(['G', 'H']); + expect(ids(ts.searchText('volumen', null, 'en'))).toEqual([]); + expect(ids(ts.searchText('hgb', null, 'en'))).toEqual(['H']); + expect(ids(ts.searchText('hgb', null, null))).toEqual(['H']); }); }); diff --git a/tests/tx/sqlite-v2-expansion-limit.test.js b/tests/tx/sqlite-v2-expansion-limit.test.js new file mode 100644 index 00000000..b54ed0cd --- /dev/null +++ b/tests/tx/sqlite-v2-expansion-limit.test.js @@ -0,0 +1,77 @@ +'use strict'; + +// meta expansionLimits.maxCodes through the real $expand: a file that caps how many of its codes an +// expansion lists is expanded as expand.js expands any provider whose expandLimitation() is set +// (#overSystemCap / #noteCapCut, as tests/tx/expand-deep-paging.test.js checks for another +// provider): the codes up to the cap, the total all of them, and the expansion-issue +// VALUESET_EXPANSION_CODESYSTEM_LIMITED when the page asked for was cut short by the cap. + +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 URI = 'http://example.org/capped'; +const CAP = 3; +const CODES = ['C1', 'C2', 'C3', 'C4', 'C5', 'C6']; +let app, tx, dir, factory; + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-cap-')); + const file = path.join(dir, 'capped.db'); + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: URI, version: '1', name: 'Capped' }); + for (const c of CODES) b.concept(c, { display: `display ${c}` }); + b.reading({ meta: { expansionLimits: { maxCodes: CAP } } }); + b.finish(); + app = await getTestApp(); + tx = getTxModule(); + factory = await loadSqliteV2Factory(tx.i18n, file); + const p = tx.endpoints[0].provider; + p.codeSystemFactories.set(URI, factory); + p.codeSystemFactories.set(URI + '|1', factory); +}, 60000); + +afterAll(async () => { + factory.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +async function expand(extra = {}) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + const parameter = [{ name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: URI }] } } }]; + for (const [name, v] of Object.entries(extra)) parameter.push({ name, valueInteger: v }); + const res = await request(app).post('/tx/r5/ValueSet/$expand').send({ resourceType: 'Parameters', parameter }); + expect(res.status).toBe(200); + const issues = (res.body.contained || []).filter((r) => r.resourceType === 'OperationOutcome').flatMap((o) => o.issue) + .map((i) => (i.extension || []).find((e) => e.url.endsWith('operationoutcome-message-id')).valueString); + return { codes: (res.body.expansion.contains || []).map((c) => c.code), total: res.body.expansion.total, issues }; +} + +test('the provider reports the cap and leaves the compose to expand.js', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const p = await factory.build(new OperationContext('en', tx.i18n), []); + expect(p.expandLimitation()).toBe(CAP); + expect(p.handlesSelecting()).toBe(false); +}); + +test('the whole system: the first codes up to the cap, the total all of them, and the issue that says why', async () => { + const r = await expand(); + expect(r.codes).toEqual(CODES.slice(0, CAP)); + expect(r.total).toBe(CODES.length); + expect(r.issues).toEqual(['VALUESET_EXPANSION_CODESYSTEM_LIMITED']); +}); + +test('a page within the cap: its codes and no issue; a page across the cap stops at it, with the issue', async () => { + const within = await expand({ count: 2 }); + expect(within.codes).toEqual(CODES.slice(0, 2)); + expect(within.total).toBe(CODES.length); + expect(within.issues).toEqual([]); + const across = await expand({ offset: 2, count: 3 }); + expect(across.codes).toEqual(CODES.slice(2, CAP)); + expect(across.issues).toEqual(['VALUESET_EXPANSION_CODESYSTEM_LIMITED']); +}); diff --git a/tests/tx/sqlite-v2-expansion-nesting.test.js b/tests/tx/sqlite-v2-expansion-nesting.test.js new file mode 100644 index 00000000..40ff5804 --- /dev/null +++ b/tests/tx/sqlite-v2-expansion-nesting.test.js @@ -0,0 +1,81 @@ +'use strict'; + +// compatibility.expansionNeverNests through the real $expand: a file with a hierarchy nests the rows +// of a whole-system expansion under their parents (expand.js walks the hierarchy), unless the file +// says its expansions never nest (SNOMED CT, LOINC): then the rows are listed flat, whatever +// excludeNested says. The provider says so by hasParents(), which expand.js reads. + +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 NESTS = 'http://example.org/nests'; +const FLAT = 'http://example.org/never-nests'; +let app, tx, dir; +const factories = {}; + +/** root > A > C, root > B */ +function build(file, uri, compatibility) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri, version: '1', name: 'Tree', hierarchyMeaning: 'is-a' }); + const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); + const c = {}; + for (const code of ['root', 'A', 'B', 'C']) c[code] = b.concept(code, { display: `display ${code}` }); + b.link(c.A, isa, c.root); + b.link(c.B, isa, c.root); + b.link(c.C, isa, c.A); + // (expansionLimits: the provider leaves the compose to expand.js's usual path, which walks the + // hierarchy; the provider's own selection lists a whole-system include flat: only an include of one + // filter is nested there, by each row's first parent) + b.reading({ meta: { expansionLimits: { maxCodes: 100 }, ...(compatibility ? { compatibility } : {}) } }); + b.finish(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-nest-')); + build(path.join(dir, 'nests.db'), NESTS, null); + build(path.join(dir, 'flat.db'), FLAT, { expansionNeverNests: true }); + app = await getTestApp(); + tx = getTxModule(); + const p = tx.endpoints[0].provider; + for (const [uri, f] of [[NESTS, 'nests.db'], [FLAT, 'flat.db']]) { + factories[uri] = await loadSqliteV2Factory(tx.i18n, path.join(dir, f)); + p.codeSystemFactories.set(uri, factories[uri]); + p.codeSystemFactories.set(uri + '|1', factories[uri]); + } +}, 60000); + +afterAll(async () => { + for (const f of Object.values(factories)) f.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +/** the expansion's rows as a tree: [code, [children]] */ +async function expand(uri, excludeNested) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + const parameter = [{ name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: uri }] } } }]; + if (excludeNested !== undefined) parameter.push({ name: 'excludeNested', valueBoolean: excludeNested }); + const res = await request(app).post('/tx/r5/ValueSet/$expand').send({ resourceType: 'Parameters', parameter }); + expect(res.status).toBe(200); + const tree = (list) => (list || []).map((c) => (c.contains ? [c.code, tree(c.contains)] : c.code)); + return tree(res.body.expansion.contains); +} + +test('the provider: hasParents() is false where the file says its expansions never nest', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const op = new OperationContext('en', tx.i18n); + expect((await factories[NESTS].build(op, [])).hasParents()).toBe(true); + expect((await factories[FLAT].build(op, [])).hasParents()).toBe(false); +}); + +test('a whole-system expansion nests by the hierarchy without the member, and is flat with it', async () => { + expect(await expand(NESTS)).toEqual([['root', [['A', ['C']], 'B']]]); + expect(await expand(NESTS, true)).toEqual(['root', 'A', 'C', 'B']); + expect(await expand(FLAT)).toEqual(['root', 'A', 'C', 'B']); + expect(await expand(FLAT, false)).toEqual(['root', 'A', 'C', 'B']); +}); diff --git a/tests/tx/sqlite-v2-format-cases.test.js b/tests/tx/sqlite-v2-format-cases.test.js index 8b4fce2a..67ebcdaf 100644 --- a/tests/tx/sqlite-v2-format-cases.test.js +++ b/tests/tx/sqlite-v2-format-cases.test.js @@ -157,15 +157,14 @@ describe('1. SNOMED CT description ids', () => { 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'); + expect(sct.store.catalog.get(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} = 1: Invalid concept ID, as main (an attribute filter's value is a concept id; concrete values through ECL)`, async () => { + for (const v of ['1', '#1', '7']) { + const r = await expand(SCT, [[COUNT_OF_BASE, '=', v]]); + expect([v, r.status, r.text]).toEqual([v, 500, `Invalid concept ID: ${v}`]); + } }); test(`${COUNT_OF_BASE} = : the concepts linked to it`, async () => { @@ -202,6 +201,7 @@ describe('4. RxNorm atom-level relationships (importer option atomRelationships) const run = async (f, filters) => { use(RX, f); try { return await expand(RX, filters); } finally { use(SCT, sct); } }; const main = (filters) => rxnormV1('format-cases', JSON.stringify(filters)); // cs-rxnorm.js's answer, recorded + // AUI: values read the name's AUI: union by value (a second filter row, value prefix AUI:) test.each(AUI)('every source\'s atom rows: as main (cs-rxnorm.js) %j', async (...filters) => { const want = main(filters); expect(want.status).toBe(200); @@ -212,8 +212,8 @@ describe('4. RxNorm atom-level relationships (importer option atomRelationships) 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']]); + // 2002 -> 5001 (concept 500, no RxNorm atom) is left out; values are stored as text (identifier-text) + 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:'], @@ -221,8 +221,32 @@ describe('4. RxNorm atom-level relationships (importer option atomRelationships) expect(db.prepare("SELECT count(*) FROM item WHERE external_id IN ('1003', '2002', '3002')").pluck().get()).toBe(0); }); + test('a relationship with no atom-level rows takes AUI: values and selects nothing; the default build refuses them', async () => { + // tradename_of has concept-level rows only; RB is its REL + for (const f of [[['tradename_of', '=', 'AUI:2002']], [['RB', 'in', 'AUI:3001,AUI:2002']]]) { + expect(await run(rxAtoms, f)).toEqual({ status: 200, codes: [] }); + expect((await run(rx, f)).status).toBe(422); + } + // a value with neither prefix, or a list with one such value, is not understood + for (const f of [[['has_ingredient', '=', '2002']], [['has_ingredient', 'in', 'AUI:2002,2002']], [['has_ingredient', 'in', 'AUI:2002,XUI:1']]]) { + expect((await run(rxAtoms, f)).status).toBe(422); + } + expect(await run(rxAtoms, [['has_ingredient', 'in', 'AUI:9999,AUI:2002']])).toEqual({ status: 200, codes: ['100'] }); + expect(await run(rxAtoms, [['has_active_ingredient', 'in', 'CUI:200,AUI:2002']])).toEqual({ status: 200, codes: ['300'] }); + }); + + test('the filter rows: a relationship\'s CUI: row and its AUI: row, reading the name\'s atom-level rows', () => { + const rows = (f) => f.store.db.prepare("SELECT code, operators, reads, value_prefix FROM filter WHERE code IN ('has_ingredient', 'RB', 'tradename_of') ORDER BY id").raw().all(); + expect(rows(rx).sort()).toEqual([['RB', '["=","in"]', '"RB"', 'CUI:'], ['has_ingredient', '["=","in"]', '"has_ingredient"', 'CUI:'], + ['tradename_of', '["=","in"]', '"tradename_of"', 'CUI:']]); + expect(rows(rxAtoms).filter((r) => r[3] === 'AUI:').sort()).toEqual([['RB', '["=","in"]', '"AUI:RB"', 'AUI:'], + ['has_ingredient', '["=","in"]', '"AUI:has_ingredient"', 'AUI:'], ['tradename_of', '["=","in"]', '"AUI:tradename_of"', 'AUI:']]); + const shape = (code) => rxAtoms.store.catalog.get(code); + expect([shape('AUI:has_ingredient').shape, shape('AUI:has_ingredient').kind, shape('AUI:tradename_of').shape]).toEqual(['union', 'identifier', 'identifier']); + expect(rxAtoms.store.filterRows('has_ingredient', '=').map((h) => h.row.prefix)).toEqual(['CUI:', 'AUI:']); + }); + 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(main([['has_ingredient', '=', 'CUI:200']])); diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js new file mode 100644 index 00000000..9ff15218 --- /dev/null +++ b/tests/tx/sqlite-v2-format.test.js @@ -0,0 +1,981 @@ +'use strict'; + +// The terminology file format, revision fhir-reading (tx/sqlite-v2/README.md), on small generic +// fixtures: identification and the meta rule; identifier text; the word index from meta search; +// concept status and the compatibility switch; how properties are reported; item uses; filter rows; +// designations; text search, versions, implicit value sets and maps, expansion limits; grammars; +// the builder's contracts and integrity facts. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('../../library/sql/better-sqlite3'); +const { TerminologyBuilder } = require('../../tx/importers/sqlite-v2/builder'); +const { openStore } = require('../../tx/sqlite-v2/store'); +const { readMeta } = require('../../tx/sqlite-v2/meta'); +const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); +const { Engine } = require('../../tx/sqlite-v2/engine/engine'); + +let dir; +let op; +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-format-')); + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); +}); +afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + +const ALL_OPS = ['=', 'is-a', 'descendent-of', 'is-not-a', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf']; +const PROP_OPS = ['=', 'in', 'not-in', 'exists', 'regex']; + +let seq = 0; +/** + * a small file: a hierarchy, a literal, designations; build(b, c) adds to it; reading: the file's + * FHIR reading (TerminologyBuilder.reading), by default the concept and colour filters + */ +function fixture(build = null, { uri = 'http://example.org/cs', reading = undefined } = {}) { + const dest = path.join(dir, `f${++seq}.db`); + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri, version: '1', name: 'Example', title: 'The Example System', caseSensitive: true, hierarchyMeaning: 'is-a', defaultLanguage: 'en' }); + const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); + const colour = b.property({ code: 'colour', shape: 'literal', fhirType: 'string' }); + const c = {}; + for (const code of ['root', 'A', 'B', 'C', 'X']) c[code] = b.concept(code, { active: code !== 'X', display: `display ${code}` }); + for (const ch of ['A', 'B']) b.link(c[ch], isa, c.root); + b.link(c.C, isa, c.A); + b.literal(c.A, colour, 'red'); + b.literal(c.B, colour, 'blue'); + const syn = { system: 'http://example.org/use', code: 'syn', display: 'Synonym' }; + b.item(c.A, { language: 'en', use: syn, text: 'apple tree' }); + b.item(c.A, { language: 'de', use: syn, text: 'Apfelbaum' }); + b.item(c.B, { language: 'en', use: syn, text: 'banana tree' }); + b.item(c.B, { language: 'en', use: syn, text: 'banana tree' }); + if (build) build(b, c); + b.reading(reading !== undefined ? reading : { + filters: [{ code: 'concept', operators: ALL_OPS, reads: 'concept' }, { code: 'colour', operators: PROP_OPS, reads: 'colour' }], + }); + b.finish(); + return dest; +} + +/** a copy of a file with meta rows set (value null: deleted) */ +function withMeta(file, rows) { + const f = path.join(dir, `m${++seq}.db`); + fs.copyFileSync(file, f); + const w = new Database(f); + for (const [k, v] of Object.entries(rows)) { + if (v === null) w.prepare('DELETE FROM meta WHERE key = ?').run(k); + else w.prepare('INSERT OR REPLACE INTO meta VALUES (?, ?)').run(k, typeof v === 'string' ? v : JSON.stringify(v)); + } + w.close(); + return f; +} + +/** a copy of a file changed by sql */ +function withSql(file, sql) { + const f = path.join(dir, `s${++seq}.db`); + fs.copyFileSync(file, f); + const w = new Database(f); + w.exec(sql); + w.close(); + return f; +} + +function withStore(file, fn) { + const S = openStore(file, { unregistered: true }); + try { return fn(S); } finally { S.close(); } +} + +const factories = []; +afterAll(() => { for (const f of factories) f.store.close(); }); +/** a provider over a file (the generic factory, or the grammar's) */ +async function provider(file) { + const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); + const f = await loadSqliteV2Factory(op.i18n, file); + factories.push(f); + return { f, p: await f.build(op, []) }; +} + +/** $lookup properties as "name=value" */ +async function lookup(p, code, props = []) { + const params = []; + await p.extendLookup((await p.locate(code)).context, props, params); + return params.filter((x) => x.name === 'property').map((x) => { + const v = x.part.find((y) => y.name === 'value'); + const k = Object.keys(v).find((y) => y.startsWith('value')); + return x.part.find((y) => y.name === 'code').valueCode + '=' + (typeof v[k] === 'object' ? v[k].code : v[k]); + }); +} + +/** the codes a filter selects, sorted */ +function select(S, prop, opName, value, grammar = {}) { + const n = new Compiler({ store: S, grammar }).filter(prop, opName, value); + return new Engine(S).evaluate(n).toArray().map((id) => S.conceptRows([id]).get(id).code).sort(); +} + +async function designations(p, code) { + const { Designations } = require('../../tx/library/designations'); + const ds = new Designations(op.i18n.languageDefinitions); + await p.designations((await p.locate(code)).context, ds); + return ds.designations.map((d) => [d.value, d.language ? d.language.code : null, d.use ? d.use.code : null, d.status || 'active']); +} + +describe('identification and the meta rule', () => { + let base; + beforeAll(() => { base = fixture(); }); + + test('the builder writes requires identifier-text and fhir-reading', () => { + withStore(base, (S) => expect(S.requires).toEqual(['identifier-text', 'fhir-reading'])); + }); + + test('a file written before the revision is refused with a message to re-import it', () => { + for (const r of ['["identifier-text"]', '[]', null]) { + expect(() => openStore(withMeta(base, { requires: r }))).toThrow(/a terminology file written before the fhir-reading revision; re-import it/); + } + }); + + test('a required feature this reader does not know refuses the file, naming it; requires is a list of distinct strings', () => { + expect(() => openStore(withMeta(base, { requires: '["identifier-text", "fhir-reading", "time-travel"]' }))).toThrow(/requires the feature time-travel, which this server does not know/); + expect(() => openStore(withMeta(base, { requires: '"fhir-reading"' }))).toThrow(/meta requires = "fhir-reading" is not a value/); + }); + + test('a key or column of the earlier revision is refused (a writer\'s mistake)', () => { + for (const k of ['behaviour.grammar', 'behaviour.anything', 'linkOrder', 'searchTieBreak', 'propertyUris', 'ix.ix_word.names']) { + expect(() => openStore(withMeta(base, { [k]: '"x"' }))).toThrow(new RegExp(`meta ${k.replace('.', '\\.')} is a key of an earlier revision`)); + } + expect(() => openStore(withSql(base, 'ALTER TABLE property ADD COLUMN filterable INTEGER'))).toThrow(/property has the columns filterable of an earlier revision/); + expect(() => openStore(withSql(base, 'ALTER TABLE item_use ADD COLUMN reported_as TEXT'))).toThrow(/item_use has the column reported_as of an earlier revision/); + }); + + test('an unknown meta key is ignored; a known key with a malformed value is refused, naming key and value', () => { + const f = withMeta(base, { 'colour.of.the.day': 'blue', 'ix.ix_word.someday': '{' }); + withStore(f, (S) => expect(S.system).toBe('http://example.org/cs')); + const m = readMeta(new Database(f, { readonly: true }).prepare('SELECT key, value FROM meta').raw().all(), f); + expect(m.ignored.sort()).toEqual(['colour.of.the.day', 'ix.ix_word.someday']); + expect(() => openStore(withMeta(base, { order: '{"expansion": ["sideways"]}' }))).toThrow(/meta order = .* is not a value this server knows/); + expect(() => openStore(withMeta(base, { conceptStatus: '[{"property": "colour", "values": {"red": ["retired"]}}]' }))).toThrow(/meta conceptStatus = .* is not a value/); + expect(() => openStore(withMeta(base, { version: 'prefix' }))).toThrow(/meta version = prefix is not JSON/); + expect(() => openStore(withMeta(base, { languages: '"en"' }))).toThrow(/meta languages = "en" is not a value/); + expect(() => openStore(withMeta(base, { 'ix.ix_order.walk.reached': '-1' }))).toThrow(/meta ix.ix_order.walk.reached = -1 is not a value/); + expect(() => openStore(withMeta(base, { codeLink: '"https://example.org/c/"' }))).toThrow(/meta codeLink = .* is not a value/); + }); + + test('hierarchyMeaning: code_system.hierarchy_meaning, null when the file does not say', async () => { + expect((await provider(base)).p.hierarchyMeaning()).toBe('is-a'); + expect((await provider(withSql(base, 'UPDATE code_system SET hierarchy_meaning = NULL'))).p.hierarchyMeaning()).toBeNull(); + expect((await provider(withSql(base, "UPDATE code_system SET hierarchy_meaning = 'part-of'"))).p.hierarchyMeaning()).toBe('part-of'); + }); + + test('codeLink: the link a page gives a code, the template with the code URI-encoded; none without it', async () => { + const link = async (file) => { const { f, p } = await provider(file); return f.codeLink((await p.locate('A')).context); }; + expect(await link(base)).toBeUndefined(); + expect(await link(withMeta(base, { codeLink: '"https://example.org/c/{code}?x={code}"' }))).toBe('https://example.org/c/A?x=A'); + }); + + test('the members and keys of the final revision are known: expansionNeverNests, translationDisplayIsSourceDisplay, implicitMaps.forwardOnly', () => { + const f = withMeta(base, { compatibility: '{"expansionNeverNests": true, "translationDisplayIsSourceDisplay": true}', + implicitMaps: '{"base": "http://x/", "maps": [], "forwardOnly": true}' }); + withStore(f, (S) => { + expect(S.compat.expansionNeverNests).toBe(true); + expect(S.compat.translationDisplayIsSourceDisplay).toBe(true); + expect(S.implicitMapsSpec.forwardOnly).toBe(true); + }); + withStore(base, (S) => expect([S.compat.expansionNeverNests, S.compat.translationDisplayIsSourceDisplay, !!S.implicitMapsSpec.forwardOnly]).toEqual([false, false, false])); + expect(() => openStore(withMeta(base, { compatibility: '{"expansionNeverNests": "yes"}' }))).toThrow(/meta compatibility = .* is not a value/); + expect(() => openStore(withMeta(base, { implicitMaps: '{"base": "http://x/", "maps": [], "forwardOnly": 1}' }))).toThrow(/meta implicitMaps = .* is not a value/); + expect(() => openStore(withMeta(base, { implicitValueSets: '[{"url": "http://x/vs", "include": {}, "name": "All {code}"}]' }))).toThrow(/meta implicitValueSets = .* is not a value/); + }); + + test('an unknown compatibility member is refused; the members of the final revision are read', () => { + expect(() => openStore(withMeta(base, { compatibility: '{"keepEverything": true}' }))).toThrow(/meta compatibility = .* is not a value/); + withStore(withMeta(base, { compatibility: '{"expansionKeepsRepeatedDesignations": true}' }), (S) => expect(S.compat.expansionKeepsRepeatedDesignations).toBe(true)); + withStore(withMeta(base, { implicitMaps: '{"base": "http://x/", "maps": [], "used": "to-"}' }), (S) => expect(S.implicitMapsSpec.used).toBe('to-')); + // the alias columns: on an identifier row only, and alias_literals an object of templates + expect(() => openStore(withSql(base, "UPDATE property SET alias_literals = '{}' WHERE code = 'colour'"))).toThrow(/property colour has alias_literals, which only an identifier row may have/); + }); + + test('the builder refuses to finish a file with a key it does not know; provenance.* is free-form', () => { + 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.setMeta('dispalyContexts', { relations: [], preferred: 'x' }); + expect(() => b.finish()).toThrow(/meta dispalyContexts is not a key this builder knows/); + const b2 = new TerminologyBuilder(path.join(dir, 'prov.db'), { overwrite: true, importer: 'test' }); + b2.codeSystem({ uri: 'http://example.org/x', version: '1' }); + b2.concept('a'); + b2.setMeta('provenance.anything', 'goes'); + b2.finish(); + withStore(path.join(dir, 'prov.db'), (S) => expect(S.conceptCount).toBe(1)); + }); + + test('the grammar registry: plain codes, snomed, cpt and icd11 served; any other grammar refused, whatever the system', async () => { + const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); + const plain = await loadSqliteV2Factory(op.i18n, base); + plain.store.close(); + const cpt = await loadSqliteV2Factory(op.i18n, withMeta(base, { grammar: '"cpt"' })); + expect(cpt.constructor.grammar).toBe('cpt'); + cpt.store.close(); + // icd11 reads its record relations: a file without them is refused, naming what is missing + await expect(loadSqliteV2Factory(op.i18n, withMeta(base, { grammar: '"icd11"' }))).rejects.toThrow(/the grammar icd11 reads the record relation postcoordinationAxis, which the file does not have/); + for (const g of ['klingon']) { + await expect(loadSqliteV2Factory(op.i18n, withMeta(base, { grammar: JSON.stringify(g) }))).rejects.toThrow(new RegExp(`its codes are in the grammar ${g} \\(meta grammar\\), which this server does not implement`)); + } + expect(() => openStore(withMeta(base, { implicitValueSets: '[{"grammar": "fhir_vs"}]' }))).toThrow(/a grammar template, but the file has no grammar/); + }); +}); + +describe('identifier values are TEXT', () => { + let file; + beforeAll(() => { + file = fixture((b, c) => { + const ndc = b.property({ code: 'alias', shape: 'identifier' }); + b.identifier(ndc, '00123', c.A, { resolves: 2 }); + b.identifier(ndc, '123', c.B, { resolves: 2 }); + b.identifier(ndc, 456, c.C); // a number: stored as text too + }); + }); + + test('every stored value is text', () => { + const db = new Database(file, { readonly: true }); + try { + expect(db.prepare('SELECT DISTINCT typeof(value) FROM identifier').pluck().all()).toEqual(['text']); + expect(db.prepare('SELECT value FROM identifier ORDER BY value').pluck().all()).toEqual(['00123', '123', '456']); + } finally { db.close(); } + }); + + test('probes with integer-looking values match, one by one and as a list through json_each', () => { + withStore(file, (S) => { + expect(S.identifierAsCode('123').code).toBe('B'); + expect(S.identifierAsCode('00123').code).toBe('A'); + const def = S.catalog.get('alias'); + expect(S.subjectsOfIdentifiers(def, ['123', '456', '00123'])).toEqual([S.idOf('A'), S.idOf('B'), S.idOf('C')].sort((a, b) => a - b)); + expect(S.subjectsOfIdentifiers(def, [456])).toEqual([S.idOf('C')]); + }); + }); +}); + +describe('the word index: meta search.names, stemmers per language, little-endian counts', () => { + const ti = require('../../tx/sqlite-v2/text-index'); + const { stemmerName } = require('../../tx/library/text-match'); + // A: display, en syn 'apple tree', de syn 'Apfelbaum', an inactive en syn, a definition without a + // use, a related name, an item with no language; C: an item with no language + const rich = (search) => fixture((b, c) => { + b.item(c.A, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'withered tree', active: false }); + b.item(c.A, { kind: 1, language: 'en', text: 'a definition without use' }); + b.item(c.A, { language: 'en', use: { system: 'u', code: 'RELATED' }, text: 'related wording' }); + b.item(c.C, { use: { system: 'u', code: 'syn' }, text: 'unlabelled cherry' }); + }, { reading: search === undefined ? {} : { meta: { search } } }); + const names = (file) => withStore(file, (S) => { + const out = []; + S.eachSearchName((id, lang, term) => out.push([S.conceptRows([id]).get(id).code, lang, term])); + return out.sort((x, y) => String(x).localeCompare(String(y))); + }); + + test('display: every non-empty display under the stated language; no items', () => { + const got = names(rich({ names: { display: 'en-GB' } })); + expect(got).toEqual(['A', 'B', 'C', 'X', 'root'].map((c) => [c, 'en', `display ${c}`]).sort((x, y) => String(x).localeCompare(String(y)))); + }); + + test('items: every item in its own language (none: the default language); active, designations, excludeUses, includeUses, language', () => { + const got = names(rich({ names: { items: {} } })); + expect(got.filter((r) => r[0] === 'A').map((r) => r[2]).sort()).toEqual(['Apfelbaum', 'a definition without use', 'apple tree', 'related wording', 'withered tree']); + expect(got.find((r) => r[2] === 'Apfelbaum')[1]).toBe('de'); + expect(got.find((r) => r[2] === 'unlabelled cherry')[1]).toBe('en'); + expect(names(rich({ names: { items: { active: true } } })).map((r) => r[2])).not.toContain('withered tree'); + expect(names(rich({ names: { items: { designations: true } } })).map((r) => r[2])).not.toContain('a definition without use'); + const ex = names(rich({ names: { items: { excludeUses: ['RELATED', 'not-a-use'] } } })).map((r) => r[2]); + expect(ex).not.toContain('related wording'); + expect(ex).toContain('apple tree'); + expect(names(rich({ names: { items: { includeUses: ['RELATED', null] } } })).map((r) => r[2]).sort()).toEqual(['a definition without use', 'related wording']); + expect(new Set(names(rich({ names: { items: { language: 'fr' } } })).map((r) => r[1]))).toEqual(new Set(['fr'])); + }); + + test('a file without meta search has no names, no word index, and refuses a text filter', async () => { + const f = rich(undefined); + expect(names(f)).toEqual([]); + const db = new Database(f, { readonly: true }); + try { + expect(db.prepare('SELECT count(*) FROM ix_word').pluck().get()).toBe(0); + expect(db.prepare("SELECT count(*) FROM meta WHERE key LIKE 'ix.ix_word.%'").pluck().get()).toBe(0); + } finally { db.close(); } + const { p } = await provider(f); + await expect(p.searchFilter(await p.getPrepContext(true), 'apple')).rejects.toMatchObject({ statusCode: 422, msgId: 'TEXT_SEARCH_NOT_SUPPORTED' }); + }); + + test('the index builder writes the stemmer of each language, and the counts row (2 * (N + 1) bytes, little-endian) exactly with search.shortlist', () => { + const f = rich({ names: { items: { active: true, designations: true } }, shortlist: 200 }); + const db = new Database(f, { readonly: true }); + try { + const meta = (k) => db.prepare('SELECT value FROM meta WHERE key = ?').pluck().get(k); + expect(JSON.parse(meta('ix.ix_word.stemmers'))).toEqual({ de: stemmerName('de'), en: stemmerName('en') }); + const n = db.prepare('SELECT concept_count FROM code_system WHERE served = 1').pluck().get(); + const row = db.prepare("SELECT ids FROM ix_word WHERE lang = 'en' AND word = ''").pluck().get(); + expect(row.length).toBe(2 * (n + 1)); + const B = db.prepare("SELECT id FROM concept WHERE code = 'B'").pluck().get(); + const A = db.prepare("SELECT id FROM concept WHERE code = 'A'").pluck().get(); + expect(row.readUInt16LE(2 * B)).toBe(2); // banana, tree + expect(row.readUInt16LE(2 * A)).toBe(4); // apple, tree, related, wording + expect([...ti.countsToLE(Uint16Array.from([258]))]).toEqual([2, 1]); + } finally { db.close(); } + const g = rich({ names: { items: {} } }); + const dg = new Database(g, { readonly: true }); + try { expect(dg.prepare("SELECT count(*) FROM ix_word WHERE word = ''").pluck().get()).toBe(0); } finally { dg.close(); } + }); + + test('a language whose stemmer is not this server\'s is searched without the stored index, the others with it', () => { + const f = rich({ names: { items: { active: true, designations: true } }, shortlist: 200 }); + const g = withMeta(f, { 'ix.ix_word.stemmers': JSON.stringify({ de: 'snowball:german', en: stemmerName('en') }) }); + const w = new Database(g); + const empty = Buffer.from(new (require('roaring-js').RoaringBitmap32)().serialize('portable')); + w.prepare("UPDATE ix_word SET ids = ? WHERE lang = 'de' AND word <> ''").run(empty); + w.prepare("UPDATE ix_word SET ids = ? WHERE lang = 'en' AND word = 'banana'").run(empty); + w.close(); + withStore(g, (S) => { + expect(ti.textIndexOf(S).memLangs).toEqual(new Set(['de'])); + const codes = (bm) => bm.toArray().map((id) => S.conceptRows([id]).get(id).code); + expect(codes(S.searchText('apfelbaum', null, 'de'))).toEqual(['A']); + expect(codes(S.searchText('apple', null, 'en'))).toEqual(['A']); + expect(codes(S.searchText('banana', null, 'en'))).toEqual([]); + }); + withStore(f, (S) => expect(ti.textIndexOf(S)).toBeInstanceOf(ti.WordIndex)); + }); + + test('a malformed search is refused', () => { + const f = rich({ names: { items: {} } }); + expect(() => openStore(withMeta(f, { search: '{"names": {"items": {"active": "yes"}}}' }))).toThrow(/meta search = .* is not a value/); + expect(() => openStore(withMeta(f, { search: '{"names": {}, "algorithm": "snomed"}' }))).toThrow(/meta search = .* is not a value/); + }); +}); + +describe('text search: the procedure\'s parameters', () => { + // codes 10, 100, 1001, 20; names: 10 'aspirin tablet', 100 'aspirin', 1001 'aspirin', 20 'tablet' + const file = (search, order) => { + const dest = path.join(dir, `t${++seq}.db`); + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/t', version: '1', defaultLanguage: 'en' }); + const tty = b.property({ code: 'TTY', shape: 'literal', fhirType: 'code' }); + const names = { 10: 'aspirin tablet', 100: 'aspirin', 1001: 'aspirin aspirin', 20: 'tablet' }; + for (const [code, text] of Object.entries(names)) { + const c = b.concept(code, { display: text }); + b.item(c, { language: 'en', use: { system: 'u', code: 'n' }, text }); + b.literal(c, tty, code === '1001' ? 'SY' : 'X'); + } + b.reading({ meta: { search, ...(order ? { order } : {}) } }); + b.finish(); + return dest; + }; + const hits = (f, q) => withStore(f, (S) => { + const r = require('../../tx/sqlite-v2/text-index').search(S, q, 'en'); + return Array.from(r.ids).map((id) => S.conceptRows([id]).get(id).code); + }); + + test('names, candidates (hasLiteral), ties by code', () => { + const names = { items: { designations: true } }; + expect(hits(file({ names }, { searchTies: ['code'] }), 'aspirin')).toEqual(['100', '1001', '10']); + // a candidate with a TTY other than SY only + expect(hits(file({ names, candidates: { hasLiteral: { property: 'TTY', except: ['SY'] } } }, { searchTies: ['code'] }), 'aspirin')).toEqual(['100', '10']); + // nameScore as-written: the repeated word makes 1001 no exact name + expect(hits(file({ names, nameScore: 'as-written' }, { searchTies: ['code'] }), 'aspirin')).toEqual(['100', '10', '1001']); + }); + + test('codes: text-prefix merged with the names; number-prefix listed first by code number', () => { + const names = { items: { designations: true } }; + expect(hits(file({ names }, { searchTies: ['code'] }), '10')).toEqual(['10', '100', '1001']); + expect(hits(file({ names, codeMatch: 'number-prefix', codeHits: 'first' }, { searchTies: ['code-number'] }), '10')).toEqual(['10', '100', '1001']); + expect(hits(file({ names, codeMatch: 'number-prefix', codeHits: 'first' }, { searchTies: ['code-number'] }), '010')).toEqual(['10', '100', '1001']); + expect(hits(file({ names }, { searchTies: ['code'] }), '010')).toEqual([]); + }); +}); + +describe('concept status (meta conceptStatus) and compatibility.statusReadingsIgnored', () => { + // a LOINC-like file: STATUS ACTIVE / DEPRECATED / DISCOURAGED / NotStated(no row); kind 'header' + // not selectable; status 'gone' unlisted + const build = (compat) => fixture((b, c) => { + const status = b.property({ code: 'STATUS', shape: 'literal', fhirType: 'string', role: 'status' }); + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'code' }); + b.literal(c.A, status, 'ACTIVE'); + b.literal(c.B, status, 'DEPRECATED'); + b.literal(c.C, status, 'DISCOURAGED'); + b.literal(c.X, status, 'gone'); + b.literal(c.root, kind, 'header'); + }, { reading: { + meta: { + conceptStatus: [ + { property: 'STATUS', values: { DISCOURAGED: ['inactive'], DEPRECATED: ['inactive', 'deprecated'], gone: ['inactive', 'unlisted'] } }, + { property: 'kind', values: { header: ['notSelectable'] } }, + ], + ...(compat ? { compatibility: { statusReadingsIgnored: [{ property: 'STATUS', values: { DEPRECATED: ['inactive'] } }] } } : {}), + }, + filters: [{ code: 'concept', operators: ALL_OPS, reads: 'concept' }], + } }); + const answers = async (file) => { + const { p } = await provider(file); + const out = {}; + for (const code of ['A', 'B', 'C', 'X', 'root']) { + const ctx = (await p.locate(code)).context; + out[code] = [await p.isInactive(ctx), await p.isDeprecated(ctx), await p.getStatus(ctx), await p.isAbstract(ctx)]; + } + return out; + }; + + test('with the compatibility member: DEPRECATED is active and deprecated (upstream\'s answer); without it, inactive and not deprecated', async () => { + const kept = await answers(build(true)); + const plain = await answers(build(false)); + // [inactive, deprecated, status text, notSelectable] + expect(kept).toEqual({ A: [false, false, 'ACTIVE', false], B: [false, true, 'DEPRECATED', false], C: [true, false, 'DISCOURAGED', false], + X: [true, false, 'gone', false], root: [false, false, null, true] }); + expect(plain).toEqual({ ...kept, B: [true, false, 'DEPRECATED', false] }); + // concept.active is derived: the builder stores it from the readings + withStore(build(true), (S) => expect(S.activeCount).toBe(3)); + withStore(build(false), (S) => expect(S.activeCount).toBe(2)); + }); + + test('unlisted: found by $lookup and by code, never by a filter, the whole system or the count', async () => { + const f = build(true); + const { p } = await provider(f); + expect((await p.locate('X')).context).toBeTruthy(); + withStore(f, (S) => { + expect(select(S, 'concept', 'is-a', 'root')).toEqual(['A', 'B', 'C', 'root']); + const sel = new Compiler({ store: S }).selection([{ system: 'http://example.org/cs' }], [], false); + expect(new Engine(S).run(sel, { offset: 0, count: -1 }).page(0, -1).length).toBe(4); + }); + expect(p.totalCount()).toBe(4); + }); + + test('a conceptStatus naming no literal property, or an ignored reading without its entry, is refused', () => { + const f = build(true); + expect(() => openStore(withMeta(f, { conceptStatus: '[{"property": "parent", "values": {"x": ["inactive"]}}]' }))).toThrow(/conceptStatus names parent, which is no literal property/); + expect(() => openStore(withMeta(f, { compatibility: '{"statusReadingsIgnored": [{"property": "kind", "values": {"header": ["inactive"]}}]}', conceptStatus: '[{"property": "STATUS", "values": {}}]' }))) + .toThrow(/statusReadingsIgnored names kind, which conceptStatus does not/); + }); +}); + +describe('how properties are reported (property columns, order)', () => { + let file; + beforeAll(() => { + file = fixture((b, c) => { + const site = b.property({ code: 'site', shape: 'link', presentation: { parts: ['description'] } }); + const area = b.property({ code: 'area', shape: 'link', fhirCode: 'region', alsoAskedAs: ['zone'], lookupRank: 1 }); + const flag = b.property({ code: 'flag', shape: 'link', trueValue: 'C', lookup: 'named' }); + const hidden = b.property({ code: 'hidden', shape: 'literal', fhirType: 'string', lookup: 'never', expansion: 'never' }); + const store = b.property({ code: 'store@x', shape: 'link', internal: true }); + const code = b.property({ code: 'alt', shape: 'identifier', valueSystem: 'http://other.org' }); + // links of A: area -> B (seq 1), site -> root (seq 2), site -> C (seq 0), site -> B (seq 3) + b.link(c.A, area, c.B, { seq: 1 }); + b.link(c.A, site, c.root, { seq: 2 }); + b.link(c.A, site, c.C, { seq: 0 }); + b.link(c.A, site, c.B, { seq: 3 }); + b.link(c.A, flag, c.C); + b.link(c.B, flag, c.A); + b.link(c.A, store, c.B); + b.literal(c.A, hidden, 'secret'); + b.identifier(code, 'Z9', c.A); + b.mapping(c.A, { system: 'http://m.org', code: 'M1', relationship: 'equivalent' }); + b.item(c.A, { language: 'en', use: { system: 'u', code: 'rel' }, text: 'related one' }); + }, { reading: { + meta: { implicitMaps: { base: 'http://example.org/cm/', maps: [['http://m.org', 'm']] } }, + rows: [{ code: 'parent', lookupRank: 0 }, { code: 'colour', lookupRank: 2 }], + newProperties: [{ code: 'related', shape: 'item-use', fhirType: 'string' }, { code: 'm', shape: 'mapping', fhirType: 'Coding' }], + uses: [{ code: 'rel', asProperty: 'related' }], + mappingsByImplicitMaps: true, + filters: [{ code: 'concept', operators: ALL_OPS, reads: 'concept' }], + } }); + }); + + test('$lookup: ranked rows first, links before literals before the rest; order.links by default property id, group, code', async () => { + const { p } = await provider(file); + // (then identifiers, mappings, item-use values) + expect(await lookup(p, 'A')).toEqual(['parent=root', 'region=B', 'colour=red', 'site=B', 'site=C', 'site=root', 'alt=Z9', 'm=M1', 'related=related one']); + }); + + test('order.links stored: by link.seq', async () => { + const { p } = await provider(withMeta(file, { order: '{"links": ["stored", "property-id", "group", "code"]}' })); + expect((await lookup(p, 'A')).filter((x) => x.startsWith('site'))).toEqual(['site=C', 'site=root', 'site=B']); + }); + + test('fhir_code and also_asked_as; lookup named and never; true_value a boolean; internal never', async () => { + const { p } = await provider(file); + expect(await lookup(p, 'A', ['zone'])).toEqual(['region=B']); + expect(await lookup(p, 'A', ['area'])).toEqual([]); + expect(await lookup(p, 'A', ['flag'])).toEqual(['flag=true']); + expect(await lookup(p, 'B', ['flag'])).toEqual(['flag=false']); + expect(await lookup(p, 'A', ['hidden'])).toEqual([]); + expect(await lookup(p, 'A', ['*'])).toContain('flag=true'); + expect((await lookup(p, 'A', ['*'])).some((x) => x.startsWith('store@x') || x.startsWith('hidden'))).toBe(false); + }); + + test('presentation: the target\'s display as description; an item-use row is no designation; a mapping row a Coding', async () => { + const { p } = await provider(file); + const params = []; + await p.extendLookup((await p.locate('A')).context, ['site', 'm'], params); + expect(params[0].part).toEqual([{ name: 'code', valueCode: 'site' }, { name: 'value', valueCode: 'B' }, { name: 'description', valueString: 'display B' }]); + expect(params.find((x) => x.part[0].valueCode === 'm').part[1]).toEqual({ name: 'value', valueCoding: { system: 'http://m.org', code: 'M1' } }); + expect((await designations(p, 'A')).map((d) => d[0])).not.toContain('related one'); + }); + + test('presentation of a mapping row: version and equivalence only where its parts say; neither part on another shape', async () => { + const v = withSql(file, "UPDATE mapping SET version = '2024'"); + const value = async (f) => { + const { p } = await provider(f); + const params = []; + await p.extendLookup((await p.locate('A')).context, ['m'], params); + return params[0].part.slice(1); + }; + expect(await value(v)).toEqual([{ name: 'value', valueCoding: { system: 'http://m.org', code: 'M1' } }]); + expect(await value(withSql(v, `UPDATE property SET presentation = '{"parts":["equivalence","version"]}' WHERE code = 'm'`))).toEqual([ + { name: 'value', valueCoding: { system: 'http://m.org', version: '2024', code: 'M1' } }, + { name: 'subproperty', part: [{ name: 'code', valueCode: 'equivalence' }, { name: 'value', valueCode: 'equivalent' }] }]); + expect(() => openStore(withSql(file, `UPDATE property SET presentation = '{"parts":["version"]}' WHERE code = 'site'`))).toThrow(/property site: presentation/); + }); + + test('expansion rows: named in request order; * by expansion_rank then the $lookup order; always on every row', async () => { + const f = withSql(file, "UPDATE property SET expansion_rank = 0 WHERE code = 'colour'; UPDATE property SET expansion = 'always' WHERE code = 'parent'"); + const { p } = await provider(f); + const ctx = (await p.locate('A')).context; + expect((await p.properties(ctx, ['colour', 'zone'])).map((x) => x.code)).toEqual(['colour', 'region', 'parent']); + expect((await p.properties(ctx, ['*'])).map((x) => x.code).slice(0, 2)).toEqual(['colour', 'parent']); + expect(p.mandatoryExpansionProperties()).toEqual(['parent']); + }); + + test('a malformed reporting column is refused', () => { + expect(() => openStore(withSql(file, "UPDATE property SET lookup = 'sometimes' WHERE code = 'site'"))).toThrow(/property site: lookup sometimes/); + expect(() => openStore(withSql(file, "UPDATE property SET internal = 1 WHERE code = 'site'"))).toThrow(/property site: internal, and reported/); + expect(() => openStore(withSql(file, "UPDATE property SET also_asked_as = '\"zone\"' WHERE code = 'area'"))).toThrow(/property area: also_asked_as/); + }); +}); + +describe('item uses: display role, the display in a requested language', () => { + test('a use with role display is a display; language_display_rank gives the display in another language', async () => { + const f = fixture((b, c) => { + b.item(c.C, { language: 'de', use: { system: 'u', code: 'short' }, text: 'Kirsche kurz' }); + b.item(c.C, { language: 'de', use: { system: 'u', code: 'long' }, text: 'Kirsche lang' }); + }, { reading: { uses: [{ code: 'long', role: 'display', languageDisplayRank: 1 }, { code: 'short', languageDisplayRank: 2 }] } }); + const { p } = await provider(f); + const ctx = (await p.locate('C')).context; + expect(p.isDisplay({ use: { system: 'u', code: 'long' } })).toBe(true); + expect(p.isDisplay({ use: { system: 'u', code: 'short' } })).toBe(false); + expect(await p.display(ctx)).toBe('display C'); + const { Languages } = require('../../library/i18n/languages'); + p.displayLanguages = () => Languages.fromAcceptLanguage('de', op.i18n.languageDefinitions); + expect(await p.display(ctx)).toBe('Kirsche lang'); + }); +}); + +describe('filter rows', () => { + let file; + beforeAll(() => { + file = fixture((b, c) => { + const has = b.property({ code: 'has', shape: 'link' }); + const list = b.property({ code: 'member', shape: 'link', ordered: true }); + const std = b.property({ code: 'standard', shape: 'literal', fhirType: 'code' }); + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'code' }); + b.link(c.A, has, c.C); + b.link(c.B, has, c.root); + b.link(c.root, list, c.B, { seq: 1 }); + b.link(c.root, list, c.A, { seq: 2 }); + b.literal(c.A, std, 'S'); + b.literal(c.B, std, 'S'); + b.literal(c.A, kind, 'Big'); + b.literal(c.C, kind, 'big'); + b.valueLabel(kind, 'Big', 'Large kind'); + }, { reading: { + meta: { compatibility: { missingValueFiltersAs: { standard: 'none' } } }, + filters: [ + { code: 'concept', operators: ALL_OPS, reads: 'concept' }, + { code: 'has', operators: ['=', 'in', 'exists', 'regex'], reads: 'has', valuePrefix: 'ID:', valueAsDisplay: true }, + { code: 'KIND', operators: ['=', 'in'], reads: 'kind', codeAnyCase: true }, + { code: 'kindExact', operators: ['='], reads: 'kind', valueCase: 'exact', valueAsDisplay: true }, + { code: 'tint', operators: ['=', 'in'], reads: 'colour', whereLiteral: { standard: 'S' }, allowedValues: ['red', 'blue'] }, + { code: 'standard', operators: ['='], reads: 'standard' }, + { code: 'list', operators: ['='], reads: 'concept', thenLink: 'member', allowedValues: 'codes' }, + { codePattern: 'p:(.*)', operators: ['exists'], reads: '{1}' }, + ], + } }); + }); + + test('a filter that is no row, or an operator no row of the name takes, is not understood', () => { + withStore(file, (S) => { + expect(() => select(S, 'colour', '=', 'red')).toThrow('The filter "colour = red" is not understood or supported'); + expect(() => select(S, 'KIND', 'regex', 'x')).toThrow('not understood or supported'); + }); + }); + + test('values: in with only empty items, exists other than true/false, a value outside allowed_values or without the prefix: not understood', () => { + withStore(file, (S) => { + expect(() => select(S, 'KIND', 'in', ' , ')).toThrow('not understood'); + expect(() => select(S, 'has', 'exists', 'yes')).toThrow('not understood'); + expect(() => select(S, 'tint', '=', 'green')).toThrow('not understood'); + expect(() => select(S, 'has', '=', 'C')).toThrow('not understood'); + expect(() => select(S, 'list', '=', 'nope')).toThrow('not understood'); + }); + }); + + test('value_prefix, value_as_display (a target\'s display), code_any_case, value_case, value labels, where_literal, missingValueFiltersAs', () => { + withStore(file, (S) => { + expect(select(S, 'has', '=', 'ID:C')).toEqual(['A']); + expect(select(S, 'has', '=', 'ID:display root')).toEqual(['B']); + expect(select(S, 'has', 'regex', 'ID:display r.*')).toEqual(['B']); + expect(select(S, 'has', 'exists', 'false')).toEqual(['C', 'X', 'root']); + expect(select(S, 'kind', '=', 'big')).toEqual(['A', 'C']); + expect(select(S, 'kindExact', '=', 'big')).toEqual(['C']); + expect(select(S, 'kindExact', '=', 'large KIND')).toEqual(['A']); + expect(select(S, 'tint', 'in', 'red,blue')).toEqual(['A', 'B']); + expect(select(S, 'standard', '=', 'none')).toEqual(['C', 'X', 'root']); + }); + }); + + test('then_link: the targets of the links from what the row read; a code_pattern capture names the property', () => { + withStore(file, (S) => { + expect(select(S, 'list', '=', 'root')).toEqual(['A', 'B']); + expect(select(S, 'p:has', 'exists', 'true')).toEqual(['A', 'B']); + expect(select(S, 'p:nothing', 'exists', 'true')).toEqual([]); + }); + }); + + test('operator of: taken in a row\'s operators, never a filter; a row with only of names no filter', () => { + const f = withSql(file, `UPDATE filter SET operators = '["=","in","of"]' WHERE code = 'standard'; + INSERT INTO filter (id, code, operators, reads, value_case) VALUES (99, 'up', '["of"]', '"parent"', 'any')`); + withStore(f, (S) => { + expect(select(S, 'standard', '=', 'S')).toEqual(['A', 'B']); + expect(() => select(S, 'standard', 'of', 'S')).toThrow('not understood'); + expect(() => select(S, 'up', '=', 'root')).toThrow('The filter "up = root" is not understood or supported'); + expect(() => select(S, 'up', 'of', 'root')).toThrow('not understood'); + }); + }); + + test('a malformed row is refused at open', () => { + expect(() => openStore(withSql(file, "UPDATE filter SET reads = '\"nothing\"' WHERE code = 'standard'"))).toThrow(/reads nothing, which is no property of the catalog/); + expect(() => openStore(withSql(file, "UPDATE filter SET operators = '[\"sideways\"]' WHERE code = 'standard'"))).toThrow(/operators/); + expect(() => openStore(withSql(file, "INSERT INTO filter (id, code, operators, reads) VALUES (99, 'standard', '[\"=\"]', '\"standard\"')"))).toThrow(/shares an operator/); + }); +}); + +describe('filter rows told apart by value_prefix; identifier rows read by value', () => { + let file; + beforeAll(() => { + file = fixture((b, c) => { + const rel = b.property({ code: 'rel', shape: 'link' }); + b.link(c.A, rel, c.C); + b.link(c.B, rel, c.root); + // two identifier schemes (internal: storage only) and their union; one scheme with no rows + const x1 = b.property({ code: 'X:rel:1', shape: 'identifier', bySubject: false }); + const x2 = b.property({ code: 'X:rel:2', shape: 'identifier', bySubject: false }); + const u = b.property({ code: 'X:rel', shape: 'union' }); + b.propertyMember(u, x1); + b.propertyMember(u, x2); + b.property({ code: 'X:other', shape: 'identifier', bySubject: false }); + b.identifier(x1, '77', c.B); + b.identifier(x2, '77', c.C); + b.identifier(x2, '78', c.A); + b.property({ code: 'other', shape: 'link' }); + }, { reading: { + rows: [{ codeContains: 'X:', internal: true }], + filters: [ + { code: 'concept', operators: ALL_OPS, reads: 'concept' }, + { each: { codes: ['rel', 'other'] }, operators: ['=', 'in', 'not-in'], valuePrefix: 'C:' }, + { each: { codes: ['rel', 'other'] }, operators: ['=', 'in', 'not-in'], valuePrefix: 'X:', reads: 'X:{code}' }, + ], + } }); + }); + + test('each value is read by the row whose prefix it has; in is the union, not-in its complement', () => { + withStore(file, (S) => { + expect(S.filterRows('rel', '=').map((h) => [h.row.prefix, h.row.reads])).toEqual([['C:', ['rel']], ['X:', ['X:rel']]]); + expect(select(S, 'rel', '=', 'C:C')).toEqual(['A']); + expect(select(S, 'rel', '=', 'X:77')).toEqual(['B', 'C']); + expect(select(S, 'rel', '=', 'X:78')).toEqual(['A']); + expect(select(S, 'rel', '=', 'X:79')).toEqual([]); + expect(select(S, 'rel', 'in', 'C:root,X:78')).toEqual(['A', 'B']); + expect(select(S, 'rel', 'not-in', 'C:root,X:78')).toEqual(['C', 'X', 'root']); + expect(select(S, 'other', '=', 'X:77')).toEqual([]); + for (const [op, v] of [['=', '77'], ['in', 'X:77,77'], ['in', 'Y:1'], ['=', '']]) expect(() => select(S, 'rel', op, v)).toThrow('not understood'); + // the internal rows are no filter's name + expect(() => select(S, 'X:rel', '=', 'X:77')).toThrow('not understood'); + }); + }); + + test('rows of one name sharing an operator need prefixes no value has both of; a union of identifier and other rows is refused', () => { + const add = (prefix, ops = '["="]') => withSql(file, `INSERT INTO filter (id, code, operators, reads, value_prefix) VALUES (99, 'rel', '${ops}', '"rel"', ${prefix == null ? 'NULL' : `'${prefix}'`})`); + expect(() => withStore(add('Z:'), () => null)).not.toThrow(); + expect(() => openStore(add(null))).toThrow(/values could be read by both/); + expect(() => openStore(add('X:7'))).toThrow(/values could be read by both/); + expect(() => openStore(add('Z:', '["exists"]'))).not.toThrow(); + expect(() => openStore(withSql(file, "INSERT INTO filter (id, code, operators, reads) VALUES (99, 'X:rel', '[\"=\"]', '\"X:rel\"')"))).toThrow(/named by the internal property X:rel/); + const mixed = withSql(file, "INSERT INTO property_member SELECT u.id, l.id FROM property u, property l WHERE u.code = 'X:rel' AND l.code = 'rel'"); + expect(() => openStore(mixed)).toThrow(/a union of identifier and other rows/); + // the builder refuses to finish such files + expect(() => fixture((b) => { + const u = b.property({ code: 'u', shape: 'union' }); + b.propertyMember(u, b.property({ code: 'i', shape: 'identifier', bySubject: false })); + b.propertyMember(u, b.property({ code: 'l', shape: 'link' })); + })).toThrow(/a union of identifier and other rows/); + expect(() => fixture(null, { reading: { filters: [{ code: 'colour', operators: ['='], reads: 'colour', valuePrefix: 'A' }, + { code: 'colour', operators: ['='], reads: 'colour', valuePrefix: 'AB' }] } })).toThrow(/values could be read by both/); + }); +}); + +describe('designations (compatibility.displayDesignation, designationUse)', () => { + const build = (compat) => fixture((b, c) => { + b.item(c.C, { language: 'en', text: 'cherry preferred', preferred: true }); + b.item(c.C, { language: 'en', use: { system: 'http://example.org/use', code: 'syn', display: 'Synonym' }, text: 'display C' }); + b.item(c.C, { language: 'en', use: { system: 'http://example.org/use', code: 'syn', display: 'Synonym' }, text: 'old cherry', active: false }); + }, { reading: { meta: compat ? { compatibility: compat } : {} } }); + + test('none (default): the items, preferredForLanguage for a preferred item without a use, inactive ones marked', async () => { + const { p } = await provider(build(null)); + expect(await designations(p, 'C')).toEqual([['cherry preferred', 'en', 'preferredForLanguage', 'active'], ['display C', 'en', 'syn', 'active'], ['old cherry', 'en', 'syn', 'inactive']]); + expect(await designations(p, 'B')).toEqual([['banana tree', 'en', 'syn', 'active'], ['banana tree', 'en', 'syn', 'active']]); + }); + + test('once: the display first, a repeated text dropped; always: the display first, then every item', async () => { + const once = (await provider(build({ displayDesignation: 'once' }))).p; + expect((await designations(once, 'C')).map((d) => d[0])).toEqual(['display C', 'cherry preferred', 'old cherry']); + expect((await designations(once, 'B')).map((d) => d[0])).toEqual(['display B', 'banana tree']); + const always = (await provider(build({ displayDesignation: 'always' }))).p; + expect((await designations(always, 'C')).map((d) => d[0])).toEqual(['display C', 'cherry preferred', 'display C', 'old cherry']); + // the display designation's language: code_system.default_language + expect((await designations(always, 'C'))[0][1]).toBe('en'); + }); + + test('designationUse none: no use from the item\'s kind (a preferred item still preferredForLanguage)', async () => { + const { p } = await provider(build({ designationUse: 'none' })); + expect((await designations(p, 'C')).map((d) => d[2])).toEqual(['preferredForLanguage', null, null]); + }); +}); + +describe('versions, implicit value sets and maps, expansion limits, lookup name', () => { + test('version: exact by default; prefix; partial; describe release-date', async () => { + const exact = (await provider(fixture())).p; + expect(exact.versionMatches('1')).toBe(true); + expect(exact.versionMatches('')).toBe(false); + const f = fixture((b) => { b.systems[0].version = '2.81'; b.systems[0].releaseDate = '2026-03-02'; }, + { reading: { meta: { version: { match: 'prefix', describe: 'release-date' } } } }); + const { f: fac, p } = await provider(f); + expect(p.versionMatches('2.8')).toBe(true); + expect(p.versionMatches('2.9')).toBe(false); + expect(p.versionIsMoreDetailed('2.8', '2.81')).toBe(false); + expect(fac.getPartialVersion()).toBeNull(); + expect(fac.describeVersion('2.81')).toBe('02-Mar 2026'); + const g = fixture((b) => { b.systems[0].version = 'http://e.org/7/version/2025'; }, { reading: { meta: { version: { match: 'prefix', partial: '/version/' } } } }); + const { f: gf, p: gp } = await provider(g); + expect(gf.getPartialVersion()).toBe('http://e.org/7'); + expect(gp.versionIsMoreDetailed('http://e.org/7', 'http://e.org/7/version/2025')).toBe(true); + }); + + test('implicitValueSets: the first template whose url and v match; mustBeCode; include with {v}; enumerate in the filter\'s order', async () => { + const f = fixture((b, c) => { + const list = b.property({ code: 'member', shape: 'link', ordered: true }); + b.link(c.root, list, c.B, { seq: 1 }); + b.link(c.root, list, c.A, { seq: 2 }); + b.concept('A-1', { display: 'display A-1' }); + }, { reading: { + meta: { implicitValueSets: [ + { url: 'http://example.org/vs', name: 'All', include: {} }, + { url: 'http://example.org/vs/{v}', v: '^r', mustBeCode: true, enumerate: { property: 'list', op: '=', value: '{v}' } }, + { url: 'http://example.org/vs/{v}', mustBeCode: true, name: 'Below{v_}', description: 'below {display}', include: { filter: [{ property: 'concept', op: 'is-a', value: '{v}' }] } }, + ] }, + filters: [{ code: 'concept', operators: ALL_OPS, reads: 'concept' }, { code: 'list', operators: ['='], reads: 'concept', thenLink: 'member' }], + } }); + const { f: fac } = await provider(f); + const allVs = await fac.buildKnownValueSet('http://example.org/vs'); + expect(allVs).toMatchObject({ name: 'All', version: '1', compose: { include: [{ system: 'http://example.org/cs' }] } }); + expect(allVs.compose.include[0].version).toBeUndefined(); + const rootVs = await fac.buildKnownValueSet('http://example.org/vs/root'); + expect(rootVs.compose.include[0].concept).toEqual([{ code: 'B' }, { code: 'A' }]); + expect(rootVs.compose.include[0].version).toBeUndefined(); + const aVs = await fac.buildKnownValueSet('http://example.org/vs/A'); + expect(aVs).toMatchObject({ name: 'BelowA', description: 'below display A', + compose: { include: [{ filter: [{ property: 'concept', op: 'is-a', value: 'A' }] }] } }); + expect(aVs.compose.include[0].version).toBeUndefined(); + expect(await fac.buildKnownValueSet('http://example.org/vs/A-1')).toMatchObject({ name: 'BelowA_1', description: 'below display A-1' }); + expect(await fac.buildKnownValueSet('http://example.org/vs/nope')).toBeNull(); + }); + + test('captured filter row for unknown property: exists false selects all concepts, exists true selects none', async () => { + const f = fixture((b, c) => { + const s = b.property({ code: 'known', shape: 'identifier', fhirType: 'code' }); + b.identifier(s, 'id-a', c.A); + }, { reading: { + filters: [{ codePattern: '^mapped:([a-z0-9]+)$', operators: ['exists'], reads: '{1}' }], + } }); + const { p } = await provider(f); + const run = async (prop, v) => { + const prep = await p.getPrepContext(true); + await p.filter(prep, true, prop, 'exists', v); + const [set] = await p.executeFilters(prep); + return set.bm.size; + }; + const total = p.store.conceptCount; + expect(await run('mapped:known', 'true')).toBe(1); + expect(await run('mapped:known', 'false')).toBe(total - 1); + expect(await run('mapped:unknown', 'true')).toBe(0); + expect(await run('mapped:unknown', 'false')).toBe(total); + }); + + test('implicitMaps maps: {base}{key} over the mapping rows of the system, both ways', async () => { + const f = fixture((b, c) => { + b.mapping(c.A, { system: 'http://m.org', code: 'M1', display: 'em one', relationship: 'equivalent' }); + }, { reading: { meta: { implicitMaps: { base: 'http://example.org/cm/', maps: [['http://m.org', 'm']] } }, newProperties: [{ code: 'm', shape: 'mapping', fhirType: 'Coding' }], mappingsByImplicitMaps: true } }); + const { f: fac, p } = await provider(f); + const cm = await fac.findImplicitConceptMap('http://example.org/cm/m'); + expect(cm.url).toBe('http://example.org/cm/m'); + expect(await p.getTranslations(cm, { system: 'http://example.org/cs', code: 'A' })).toEqual([{ map: cm.vurl, system: 'http://m.org', code: 'M1', display: 'em one', relationship: 'equivalent' }]); + expect((await p.getTranslations(cm, { system: 'http://m.org', code: 'M1' })).map((t) => t.code)).toEqual(['A']); + expect(await fac.findImplicitConceptMap('http://example.org/cm/x')).toBeNull(); + // forwardOnly: from this system only; translationDisplayIsSourceDisplay: the translated concept's display + const g = withMeta(f, { implicitMaps: '{"base": "http://example.org/cm/", "maps": [["http://m.org", "m"]], "forwardOnly": true}', + compatibility: '{"translationDisplayIsSourceDisplay": true}' }); + const { f: gac, p: q } = await provider(g); + const gm = await gac.findImplicitConceptMap('http://example.org/cm/m'); + expect(gm.jsonObj.group.map((x) => [x.source, x.target])).toEqual([['http://example.org/cs', 'http://m.org']]); + expect(await q.getTranslations(gm, { system: 'http://example.org/cs', code: 'A' })).toEqual([{ map: gm.vurl, system: 'http://m.org', code: 'M1', display: 'display A', relationship: 'equivalent' }]); + expect(await q.getTranslations(gm, { system: 'http://m.org', code: 'M1' })).toEqual([]); + const maps = []; + await gac.findImplicitConceptMaps(maps, 'http://m.org', null, 'http://example.org/cs'); + expect(maps).toEqual([]); + await gac.findImplicitConceptMaps(maps, 'http://example.org/cs', null, 'http://m.org'); + expect(maps.map((m) => m.url)).toEqual(['http://example.org/cm/m']); + }); + + test('expansionLimits: maxCodes is the expandLimitation (the usual path counts it); wholeSystem refuse: 500 with the compatibility text, repeated as diagnostics', async () => { + const limited = (await provider(fixture(null, { reading: { meta: { expansionLimits: { maxCodes: 2 } } } }))).p; + expect(limited.expandLimitation()).toBe(2); + expect(limited.handlesSelecting()).toBe(false); + const refusing = (await provider(fixture(null, { reading: { meta: { expansionLimits: { wholeSystem: 'refuse' }, compatibility: { wholeSystemRefusalMessage: 'not {system} as a whole' } } } }))).p; + await expect(refusing.processSelection({}, [{ system: 'http://example.org/cs' }], [], false, 0, 10)).rejects.toMatchObject({ statusCode: 500, message: 'not http://example.org/cs as a whole', diagnostics: 'not http://example.org/cs as a whole' }); + expect(await refusing.processSelection({}, [{ system: 'http://example.org/cs' }], [], false, 0, 0)).toBeNull(); + }); + + test('lookupNameIsTitle; unknownCodeMessage; lookupOmitsTextDefinitions; generalizesLeavesOutFocus', async () => { + const f = fixture((b, c) => b.item(c.A, { kind: 1, language: 'en', text: 'a definition', preferred: true }), { reading: { + meta: { compatibility: { lookupNameIsTitle: true, unknownCodeMessage: "No code '{code}'" } }, + filters: [{ code: 'concept', operators: ALL_OPS, reads: 'concept' }] } }); + const { p } = await provider(f); + expect(p.lookupName()).toBe('The Example System'); + expect((await p.locate('nope')).message).toBe("No code 'nope'"); + expect(await p.definition((await p.locate('A')).context)).toBe('a definition'); + const g = withMeta(f, { compatibility: '{"lookupOmitsTextDefinitions": true, "generalizesLeavesOutFocus": true}' }); + const q = (await provider(g)).p; + expect(q.lookupName()).toBe('Example'); + expect(await q.definition((await q.locate('A')).context)).toBeNull(); + withStore(f, (S) => expect(select(S, 'concept', 'generalizes', 'C')).toEqual(['A', 'C', 'root'])); + withStore(g, (S) => expect(select(S, 'concept', 'generalizes', 'C')).toEqual(['A', 'root'])); + }); +}); + +describe('contracts checked by the builder; cheap id checks at open', () => { + const { checkContracts } = require('../../tx/importers/sqlite-v2/builder'); + let base; + beforeAll(() => { base = fixture(null, { reading: { meta: { search: { names: { items: {} }, shortlist: 200 } }, filters: [{ code: 'colour', operators: PROP_OPS, reads: 'colour' }] } }); }); + /** a writable copy changed by sql, its contracts checked */ + const broken = (sql) => { + const f = path.join(dir, `c${++seq}.db`); + fs.copyFileSync(base, f); + const w = new Database(f); + if (typeof sql === 'function') sql(w); else w.exec(sql); + return () => { try { checkContracts(w); } finally { w.close(); } }; + }; + + test('a finished file keeps every contract', () => { + const db = new Database(base, { readonly: true }); + try { expect(checkContracts(db)).toBe(true); } finally { db.close(); } + }); + + test('each contract a builder checks', () => { + expect(broken('UPDATE concept SET id = 99 WHERE id = (SELECT max(id) FROM concept)')).toThrow(/contract: concept ids are not exactly 1\.\.5/); + expect(broken('UPDATE concept SET active = 0 WHERE id = 1')).toThrow(/contract: the active concepts are not exactly 1\.\.4/); + expect(broken('UPDATE property SET subsumption = 1')).toThrow(/contract: more than one property with subsumption = 1/); + expect(broken("UPDATE ix_word SET ids = x'0000' WHERE word = '' AND lang = 'en'")).toThrow(/contract: ix_word counts row of en is 2 bytes, not 12/); + expect(broken("DELETE FROM meta WHERE key = 'ix.ix_word.stemmers'")).toThrow(/contract: ix_word language .* has no entry in meta ix.ix_word.stemmers/); + expect(broken("DELETE FROM meta WHERE key = 'search'")).toThrow(/ix_word rows in a file without meta search/); + expect(broken("INSERT OR REPLACE INTO meta VALUES ('order', '{\"expansion\": [\"stored\"]}')")).toThrow(/uses the stored order without ix_order rank and ids/); + expect(broken("INSERT OR REPLACE INTO meta VALUES ('behaviour.grammar', '\"snomed\"')")).toThrow(/meta keys of an earlier revision: behaviour.grammar/); + expect(broken("UPDATE meta SET value = '[\"identifier-text\"]' WHERE key = 'requires'")).toThrow(/meta requires is not/); + expect(broken("UPDATE property SET internal = 1 WHERE code = 'colour'")).toThrow(/internal, and reported/); + expect(broken("UPDATE filter SET reads = '\"nothing\"'")).toThrow(/reads nothing, which is no property/); + expect(broken('DROP INDEX item_concept')).toThrow(/contract: the index item_concept is missing/); + // node:sqlite's SQLite has no STAT4, so ANALYZE writes sqlite_stat1 only; a file analyzed by a + // SQLite with STAT4 has the table, made here as that SQLite makes it + expect(broken((w) => { + w._db.enableDefensive(false); + w.exec('PRAGMA writable_schema = ON; CREATE TABLE sqlite_stat4(tbl, idx, neq, nlt, ndlt, sample); PRAGMA writable_schema = OFF'); + })).toThrow(/contract: sqlite_stat4 is present/); + }); + + test('the builder refuses to finish a file that breaks one (a kind 4 set holding its own anchor)', () => { + const descendants = broken((w) => { + const { RoaringBitmap32 } = require('roaring-js'); + const [value] = w.prepare('SELECT value FROM ix_set WHERE kind = 4 LIMIT 1').raw().get(); + const bm = new RoaringBitmap32([value]); + w.prepare('UPDATE ix_set SET data = ?, card = 1 WHERE kind = 4 AND value = ?').run(Buffer.from(bm.serialize('portable')), value); + }); + expect(descendants).toThrow(/include the concept itself/); + }); + + test('code_system keeps case_sensitive, hierarchy_meaning, release_date; isCaseSensitive reads case_sensitive', () => { + const insensitive = fixture((b) => { b.systems[0].caseSensitive = false; }); + withStore(insensitive, (S) => expect(S.caseSensitive).toBe(false)); + withStore(base, (S) => expect(S.caseSensitive).toBe(true)); + }); + + test('a reader refuses a file whose concept or item ids are out of range', () => { + expect(() => openStore(withSql(base, 'UPDATE code_system SET concept_count = concept_count + 1 WHERE served = 1'))).toThrow(/concept ids are not 1\.\.6 \(concept_count\)/); + }); +}); + +describe('integrity facts written by the builder; verify.js checks a file on request', () => { + const { spawnSync } = require('child_process'); + const VERIFY = path.join(__dirname, '../../tx/importers/sqlite-v2/verify.js'); + const run = (file) => spawnSync(process.execPath, [VERIFY, file], { encoding: 'utf8' }); + let base; + beforeAll(() => { base = fixture(); }); + + test('the builder writes meta integrity: items, schema and catalog digests (the catalog with the filter rows)', () => { + const db = new Database(base, { readonly: true }); + try { + const v = JSON.parse(db.prepare("SELECT value FROM meta WHERE key = 'integrity'").pluck().get()); + expect(Object.keys(v)).toEqual(['items', 'schema', 'catalog']); + expect(v.items).toBe(db.prepare('SELECT count(*) FROM item').pluck().get()); + const I = require('../../tx/sqlite-v2/integrity'); + expect(v.schema).toBe(I.schemaDigest(db)); + expect(I.CATALOG.map(([t]) => t)).toContain('filter'); + } finally { db.close(); } + }); + + test('a finished file passes; corrupted copies fail with a non-zero exit, naming the check', () => { + const r = run(base); + expect(r.stdout).toMatch(/^ok {3}contracts/m); + expect(r.status).toBe(0); + const filterRow = withSql(base, "UPDATE filter SET operators = '[\"=\"]' WHERE code = 'colour'"); + expect(run(filterRow).stdout).toMatch(/^FAIL integrity: catalog digest/m); + expect(run(filterRow).status).toBe(1); + const meta = withMeta(base, { order: '{"expansion": ["sideways"]}' }); + expect(run(meta).stdout).toMatch(/^FAIL meta: .*meta order = .*sideways/m); + expect(run(path.join(dir, 'no-such.db')).status).toBe(1); + }); +}); + +describe('catalog id and name; a file without a hierarchy', () => { + test('the stored id as it is is the CodeSystem id (x-...); its name the catalog name; none without an id', async () => { + const a = (await provider(fixture((b) => { b.systems[0].resource = { resourceType: 'CodeSystem', id: 'x-example-1', name: 'EX 1' }; }))).f; + const n = (await provider(fixture())).f; + expect('x-' + a.id()).toBe('x-example-1'); + expect(a.name()).toBe('EX 1'); + expect(n.id()).toBeNull(); + expect(n.name()).toBe('Example'); + }); + + test('a file with no hierarchy property: not-subsumed, even for the same code; no ancestors', async () => { + const dest = path.join(dir, 'flat.db'); + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/flat', version: '1' }); + b.concept('a'); + b.concept('b'); + b.finish(); + const { p } = await provider(dest); + expect(await p.subsumesTest('a', 'a')).toBe('not-subsumed'); + expect(await p.subsumesTest('a', 'b')).toBe('not-subsumed'); + expect([...(await p.ancestorsOf('a'))]).toEqual([]); + }); +}); diff --git a/tests/tx/sqlite-v2-icd11-grammar.test.js b/tests/tx/sqlite-v2-icd11-grammar.test.js new file mode 100644 index 00000000..4f08ca56 --- /dev/null +++ b/tests/tx/sqlite-v2-icd11-grammar.test.js @@ -0,0 +1,193 @@ +'use strict'; + +// meta grammar `icd11` (README.md "Grammar", tx/sqlite-v2/icd11.js) and the alias columns +// alias_parameter and alias_extension (README.md "Alternate codes"): postcoordinated expressions +// parsed, bound and normalised by upstream's parser (tx/cs/icd11-expressions.js) over the record +// relations postcoordinationAxis and postcoordinationRoot ($validate-code reports the normal form as +// normalized-code); the classification-code form of a code +// (its identifier of the scheme with alias_parameter) as $validate-code's classificationCode, and the +// Coding extension alias_extension names checked against it. The fixture is invented, in the shape +// of the ICD-11 importer's files: its codes and texts are not WHO's. + +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 URI = 'http://example.org/classification'; +const EXT = 'http://example.org/extension/classificationCode'; +let app, tx, dir, factory; + +function build(file) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: URI, version: '2026-01', name: 'Classification', title: 'A classification', compositional: true }); + const parent = b.property({ code: 'parent', shape: 'link', subsumption: true, lookupRank: 8 }); + const code = b.property({ code: 'code', shape: 'literal', fhirType: 'code', lookupRank: 0, expansionRank: 0 }); + const cc = b.property({ code: 'classificationCode', shape: 'literal', fhirType: 'code', lookupRank: 1, expansion: 'always' }); + const shortCode = b.property({ code: 'shortCode', shape: 'identifier', lookup: 'never', expansion: 'never', aliasParameter: 'classificationCode', aliasExtension: EXT }); + const axis = b.property({ code: 'postcoordinationAxis', shape: 'record', fields: [{ name: 'axis', type: 's' }, { name: 'axisCode', type: 's' }, + { name: 'required', type: 'i' }, { name: 'allowMultiple', type: 's' }, { name: 'valueSet', type: 's' }] }); + const root = b.property({ code: 'postcoordinationRoot', shape: 'record', fields: [{ name: 'root', type: 'c', target: true }, { name: 'axisSeq', type: 'i' }] }); + const c = {}; + for (const [id, short, display, up] of [['100', 'AA00', 'Stem disease', null], ['200', 'BB00', 'Other disease', null], + ['500', 'XS', 'Severity', null], ['501', 'XS1', 'Mild', '500'], ['502', 'XS2', 'Severe', '500'], + ['600', 'XA', 'Anatomy', null], ['601', 'XA1', 'Arm', '600']]) { + c[id] = b.concept(id, { display }); + b.item(c[id], { language: 'en', text: display, preferred: true }); + b.literal(c[id], code, id); + b.literal(c[id], cc, short); + b.identifier(shortCode, short, c[id], { resolves: 1 }); + if (up) b.link(c[id], parent, c[up]); + } + // Spanish names for two codes (the file has names in es; its displays are English) + b.item(c['100'], { language: 'es', text: 'Enfermedad troncal', preferred: true }); + b.item(c['501'], { language: 'es', text: 'Leve', preferred: true }); + // 100's axes: hasSeverity (record seq 0, values under 500), specificAnatomy (seq 1, required, values under 600) + b.record(axis, c['100'], { fields: ['http://example.org/axis/hasSeverity', 'hasSeverity', 0, 'NotAllowed', null] }); + b.record(axis, c['100'], { fields: ['http://example.org/axis/specificAnatomy', 'specificAnatomy', 1, 'AllowAlways', 'http://example.org/vs/anatomy'] }); + b.record(root, c['100'], { target: c['500'], fields: [0] }); + b.record(root, c['100'], { target: c['600'], fields: [1] }); + b.reading({ + meta: { grammar: 'icd11', version: { match: 'prefix' }, compatibility: { lookupNameIsTitle: true, expansionKeepsRepeatedDesignations: true } }, + filters: [{ code: 'concept', operators: ['is-a', 'descendent-of'], reads: 'concept' }], + }); + b.finish(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-icd11-')); + const file = path.join(dir, 'classification.db'); + build(file); + app = await getTestApp(); + tx = getTxModule(); + factory = await loadSqliteV2Factory(tx.i18n, file); + const p = tx.endpoints[0].provider; + p.codeSystemFactories.set(URI, factory); + p.codeSystemFactories.set(URI + '|2026-01', factory); +}, 60000); + +afterAll(async () => { + factory.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +const vs = (include) => ({ resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: URI, ...include }] } }); + +async function post(op, parameter) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + return request(app).post(`/tx/r5/${op}`).send({ resourceType: 'Parameters', parameter }); +} + +const param = (body, n) => (body.parameter || []).find((x) => x.name === n) || {}; +const issues = (body) => { + const oo = param(body, 'issues').resource; + return ((oo && oo.issue) || []).map((i) => [i.severity, ((i.extension || []).find((e) => /message-id/.test(e.url)) || {}).valueString]); +}; + +async function validate(coding, include) { + const parameter = [{ name: 'coding', valueCoding: { system: URI, ...coding } }]; + if (include) parameter.push({ name: 'valueSet', resource: vs(include) }); + const res = await post(include ? 'ValueSet/$validate-code' : 'CodeSystem/$validate-code', parameter); + return { status: res.status, body: res.body, result: param(res.body, 'result').valueBoolean, code: param(res.body, 'normalized-code').valueCode || param(res.body, 'code').valueCode, + display: param(res.body, 'display').valueString, classificationCode: param(res.body, 'classificationCode').valueCode, issues: issues(res.body) }; +} + +async function lookup(code, extra = []) { + const res = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: code }, ...extra]); + expect(res.status).toBe(200); + return res.body.parameter; +} + +test('the file loads: the grammar icd11 and the alias columns are served', () => { + expect(factory.constructor.grammar).toBe('icd11'); + expect(factory.store.aliasParameterScheme.code).toBe('shortCode'); + expect(factory.store.aliasExtensionScheme.aliasExtension).toBe(EXT); +}); + +test('an expression in entity ids: valid, in its normal form, with its classification-code form and its display', async () => { + const r = await validate({ code: '100&601&501' }); + expect(r.result).toBe(true); + expect(r.code).toBe('100&501&601'); + expect(r.classificationCode).toBe('AA00&XS1&XA1'); + expect(r.display).toBe('Stem disease [Arm] [Mild]'); + // written with short codes: the same expression; no classificationCode (it is written in that form) + const short = await validate({ code: 'AA00&XS1&XA1' }); + expect([short.result, short.code, short.classificationCode]).toEqual([true, '100&501&601', undefined]); +}); + +test('a qualifier on no axis of its code, a code with no axes: an error naming them', async () => { + const off = await validate({ code: '100&200' }); + expect(JSON.stringify(off.body)).toMatch(/ICD11_PC_VALUE_NOT_ON_AXIS|is not a permitted value on any postcoordination axis/); + const none = await validate({ code: '200&501' }); + expect(JSON.stringify(none.body)).toMatch(/ICD11_PC_NO_AXES|declares no postcoordination axes/); +}); + +test('a required axis left empty is a warning; two values on an axis that takes one, too', async () => { + expect((await validate({ code: '100' })).issues).toContainEqual(['warning', 'ICD11_PC_REQUIRED_AXIS_EMPTY']); + expect((await validate({ code: '100&501' })).issues).toContainEqual(['warning', 'ICD11_PC_REQUIRED_AXIS_EMPTY']); + expect((await validate({ code: '100&501&601' })).issues.map((i) => i[1])).not.toContain('ICD11_PC_REQUIRED_AXIS_EMPTY'); + expect((await validate({ code: '100&501&502&601' })).issues).toContainEqual(['warning', 'ICD11_PC_AXIS_NOT_MULTIPLE']); +}); + +test('a short code is accepted as a code and answered with its concept\'s code; the classificationCode for the entity id', async () => { + const s = await validate({ code: 'XS1' }); + expect([s.result, s.code]).toEqual([true, '501']); + const id = await validate({ code: '501' }); + expect([id.result, id.code, id.classificationCode]).toEqual([true, '501', 'XS1']); +}); + +test('the classificationCode extension: right, wrong, beside a short code', async () => { + const ext = (v) => [{ url: EXT, valueCode: v }]; + expect((await validate({ code: '501', extension: ext('XS1') })).result).toBe(true); + const wrong = await validate({ code: '501', extension: ext('XS2') }); + expect(wrong.result).toBe(false); + expect(JSON.stringify(wrong.body)).toMatch(/ICD11_CLASSIFICATION_CODE_WRONG/); + const notId = await validate({ code: 'XS1', extension: ext('XS1') }); + expect(JSON.stringify(notId.body)).toMatch(/ICD11_CLASSIFICATION_CODE_NOT_ID/); +}); + +test('$lookup of an expression: code, classificationCode, stem, the valued axes; of a plain code with post-coordination-metadata: its axes', async () => { + const ps = await lookup('100&601&501'); + const code = (p) => p.part[0].valueCode; + const props = ps.filter((p) => p.name === 'property' && code(p) !== 'inactive'); + expect(props.map(code)).toEqual(['code', 'classificationCode', 'stem', 'postcoordination', 'postcoordination']); + expect(props[0].part[1].valueCode).toBe('100&501&601'); + expect(props[2].part[1].valueCoding).toEqual({ system: URI, code: '100', display: 'Stem disease' }); + const axisOf = (p) => p.part.find((x) => x.name === 'subproperty' && x.part[0].valueCode === 'axis').part[1].valueCoding.code; + const valuesOf = (p) => p.part.filter((x) => x.name === 'subproperty' && x.part[0].valueCode === 'value').map((x) => x.part[1].valueCoding.code); + expect(props.slice(3).map((p) => [axisOf(p), valuesOf(p)])).toEqual([['hasSeverity', ['501']], ['specificAnatomy', ['601']]]); + const plain = (await lookup('100', [{ name: 'post-coordination-metadata', valueBoolean: true }])).filter((p) => p.name === 'property' && p.part[0].valueCode === 'postcoordination'); + expect(plain.map(axisOf)).toEqual(['hasSeverity', 'specificAnatomy']); + const required = (p) => p.part.find((x) => x.name === 'subproperty' && x.part[0].valueCode === 'required').part[1].valueBoolean; + expect(plain.map(required)).toEqual([false, true]); + expect((await lookup('100')).filter((p) => p.name === 'property' && p.part[0].valueCode === 'postcoordination')).toEqual([]); +}); + +test('$lookup of an expression with displayLanguage=es: the display is its parts\' (English) displays, in language en, with a warning', async () => { + const ps = await lookup('100&501', [{ name: 'displayLanguage', valueCode: 'es' }]); + expect(param({ parameter: ps }, 'display').valueString).toBe('Stem disease [Mild]'); + const des = ps.filter((p) => p.name === 'designation').map((p) => [p.part.find((x) => x.name === 'language').valueCode, p.part.find((x) => x.name === 'value').valueString]); + expect(des).toEqual([['en', 'Stem disease [Mild]']]); + expect(ps.filter((p) => p.name === 'warning').map((p) => p.valueString)).toEqual([expect.stringMatching(/no display in the language 'es'.*default language 'en'/)]); + // a plain code: its Spanish name, no warning + const plain = await lookup('100', [{ name: 'displayLanguage', valueCode: 'es' }]); + expect(param({ parameter: plain }, 'display').valueString).toBe('Enfermedad troncal'); + expect(plain.filter((p) => p.name === 'warning')).toEqual([]); +}); + +test('filters select concepts only: an expression is in no filtered include; a filter value may be a short code', async () => { + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs({ filter: [{ property: 'concept', op: 'is-a', value: 'XS' }] }) }]); + expect(res.status).toBe(200); + // (the rows nested under their parent, as an expansion of one filter that fits its page is) + expect(res.body.expansion.contains.map((x) => [x.code, (x.contains || []).map((y) => y.code)])).toEqual([['500', ['501', '502']]]); + expect((await validate({ code: '501' }, { filter: [{ property: 'concept', op: 'is-a', value: '500' }] })).result).toBe(true); + expect((await validate({ code: '100&501&601' }, { filter: [{ property: 'concept', op: 'is-a', value: '100' }] })).result).toBe(false); + // an include that lists an expression and a short code: the codes as the system answers them + const listed = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs({ concept: [{ code: 'AA00&XS1&XA1' }, { code: 'XS2' }] }) }]); + expect(listed.status).toBe(200); + expect(listed.body.expansion.contains.map((x) => x.code)).toEqual(['100&501&601', '502']); +}); diff --git a/tests/tx/sqlite-v2-icd11-reading.test.js b/tests/tx/sqlite-v2-icd11-reading.test.js new file mode 100644 index 00000000..d16f9ae9 --- /dev/null +++ b/tests/tx/sqlite-v2-icd11-reading.test.js @@ -0,0 +1,142 @@ +'use strict'; + +// How the generic reader and the grammar `icd11` answer from an ICD-11-shaped file, where upstream's +// ICD-11 provider (tx/cs/cs-icd11.js) answers so: +// - a designation use without a display in item_use is a Coding without `display` (never null); +// - `child` values in $lookup: inverse links of one seq in the stored order of the links by target +// (ix_in: then the subject, which numbering puts in the release's order), not by code; +// - an expansion of one filter that fits its page nests each row under its first parent (the +// hierarchy link first in order.links), as the usual path of expand.js does; +// - a postcoordination scale value set: the one a postcoordinationAxis row names in its field +// valueSet, an include `concept is-a ` per postcoordinationRoot of the axis; +// - a located code that an include of one filter does not select: the grammar's reason, the code as +// the classification writes it. +// The fixture is invented, in the shape of the ICD-11 importer's files: its codes and texts are not +// WHO's. + +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 URI = 'http://example.org/icd/release/mms'; +const SCHEMA = 'http://example.org/icd/schema'; +const SCALE = `${URI}/300/postcoordinationScale/hasSeverity`; +let app, tx, dir, factory; + +function build(file) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: URI, version: '2026-01', name: 'Classification', title: 'A classification', compositional: true }); + const parent = b.property({ code: 'parent', shape: 'link', subsumption: true, byTarget: true, lookupRank: 8 }); + b.property({ code: 'child', shape: 'link', inverseOf: parent, lookup: 'named', lookupRank: 9 }); + const shortCode = b.property({ code: 'shortCode', shape: 'identifier', lookup: 'never', expansion: 'never', aliasParameter: 'classificationCode' }); + const axis = b.property({ code: 'postcoordinationAxis', shape: 'record', fields: [{ name: 'axis', type: 's' }, { name: 'axisCode', type: 's' }, + { name: 'required', type: 'i' }, { name: 'allowMultiple', type: 's' }, { name: 'valueSet', type: 's' }] }); + const root = b.property({ code: 'postcoordinationRoot', shape: 'record', fields: [{ name: 'root', type: 'c', target: true }, { name: 'axisSeq', type: 'i' }] }); + const c = {}; + // [code, short code, display, parent, release order]: under 100 the release lists 300 before 200 + for (const [code, short, display, up, order] of [['100', 'AA', 'A block', null, 1], ['300', 'AA03', 'Third disease', '100', 2], + ['310', 'AA03.1', 'Third disease, mild', '300', 3], ['200', 'AA02', 'Second disease', '100', 4], + ['500', 'XS', 'Severity', null, 5], ['502', 'XS2', 'Severe', '500', 6], ['501', 'XS1', 'Mild', '500', 7]]) { + c[code] = b.concept(code, { display, sortKey: order }); + b.item(c[code], { language: 'en', text: display, preferred: true }); + b.item(c[code], { language: 'en', text: `${display} (index)`, use: { system: SCHEMA, code: 'indexTerm' } }); + b.identifier(shortCode, short, c[code], { resolves: 1 }); + if (up) b.link(c[code], parent, c[up]); + } + b.record(axis, c['300'], { fields: [`${SCHEMA}/hasSeverity`, 'hasSeverity', 0, 'AllowAlways', SCALE] }); + b.record(root, c['300'], { target: c['500'], fields: [0] }); + b.reading({ + meta: { grammar: 'icd11', order: { searchTies: ['id'], links: ['property-id', 'stored', 'code'] }, + compatibility: { lookupNameIsTitle: true, expansionKeepsRepeatedDesignations: true } }, + filters: [{ code: 'concept', operators: ['is-a', 'descendent-of'], reads: 'concept' }], + }); + b.finish(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-icd11-reading-')); + const file = path.join(dir, 'classification.db'); + build(file); + app = await getTestApp(); + tx = getTxModule(); + factory = await loadSqliteV2Factory(tx.i18n, file); + const p = tx.endpoints[0].provider; + p.codeSystemFactories.set(URI, factory); + p.codeSystemFactories.set(URI + '|2026-01', factory); +}, 60000); + +afterAll(async () => { + factory.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +const vs = (include) => ({ resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: URI, ...include }] } }); +const isA = (value) => ({ filter: [{ property: 'concept', op: 'is-a', value }] }); +const param = (body, n) => (body.parameter || []).find((x) => x.name === n) || {}; + +async function post(op, parameter) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + return request(app).post(`/tx/r5/${op}`).send({ resourceType: 'Parameters', parameter }); +} + +async function lookup(code, extra = []) { + const res = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: code }, ...extra]); + expect(res.status).toBe(200); + return res.body.parameter; +} + +/** an expansion's rows as a tree: code, or [code, [children]] */ +const tree = (list) => (list || []).map((x) => (x.contains ? [x.code, tree(x.contains)] : x.code)); + +test('a designation use with no display in item_use: a Coding with system and code, no display key', async () => { + const uses = (await lookup('300')).filter((p) => p.name === 'designation').map((p) => (p.part.find((x) => x.name === 'use') || {}).valueCoding).filter(Boolean); + expect(uses).toContainEqual({ system: SCHEMA, code: 'indexTerm' }); + for (const u of uses) expect(Object.values(u)).not.toContain(null); +}); + +test('$lookup lists child values in the stored order of the links by target, not by code', async () => { + const children = (await lookup('100', [{ name: 'property', valueCode: '*' }])).filter((p) => p.name === 'property' && p.part[0].valueCode === 'child'); + expect(children.map((p) => p.part[1].valueCode)).toEqual(['300', '200']); +}); + +test('the provider\'s parent(): the first hierarchy link of the concept; none for a root', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const p = await factory.build(new OperationContext('en', tx.i18n), []); + expect(p.hasParents()).toBe(true); + expect(await p.parent((await p.locate('310')).context)).toBe('300'); + expect(await p.parent((await p.locate('100')).context)).toBeNull(); +}); + +test('an expansion of one filter that fits its page nests rows under their parents; paged or excludeNested, flat', async () => { + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(isA('100')) }]); + expect(res.status).toBe(200); + expect(tree(res.body.expansion.contains)).toEqual([['100', [['300', ['310']], '200']]]); + const paged = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(isA('100')) }, { name: 'count', valueInteger: 2 }]); + expect(tree(paged.body.expansion.contains)).toEqual(['100', '300']); + const flat = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(isA('100')) }, { name: 'excludeNested', valueBoolean: true }]); + expect(tree(flat.body.expansion.contains)).toEqual(['100', '300', '310', '200']); +}); + +test('a postcoordination scale value set: named by an axis row\'s valueSet, is-a each root of the axis', async () => { + const res = await request(app).get('/tx/r5/ValueSet/$expand').query({ url: SCALE }); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ url: SCALE, version: '2026-01', name: 'ICD11_mms_300_hasSeverity', title: 'hasSeverity for AA03', status: 'active' }); + expect(tree(res.body.expansion.contains)).toEqual([['500', ['502', '501']]]); + const inScale = await request(app).get('/tx/r5/ValueSet/$validate-code').query({ url: SCALE, system: URI, code: 'XS1' }); + expect(param(inScale.body, 'result').valueBoolean).toBe(true); + // a URL no axis row names is no value set + const none = await request(app).get('/tx/r5/ValueSet/$expand').query({ url: `${URI}/300/postcoordinationScale/other` }); + expect(none.status).toBe(422); +}); + +test('a located code an include of one filter does not select: the grammar\'s reason, the code as the classification writes it', async () => { + const res = await post('ValueSet/$validate-code', [{ name: 'valueSet', resource: vs(isA('100')) }, { name: 'system', valueUri: URI }, { name: 'code', valueCode: '501' }]); + expect(res.status).toBe(200); + expect(param(res.body, 'result').valueBoolean).toBe(false); + expect(param(res.body, 'message').valueString).toMatch(/^'XS1' is not in the value set; /); +}); diff --git a/tests/tx/sqlite-v2-implicit-maps-used.test.js b/tests/tx/sqlite-v2-implicit-maps-used.test.js new file mode 100644 index 00000000..7759218f --- /dev/null +++ b/tests/tx/sqlite-v2-implicit-maps-used.test.js @@ -0,0 +1,120 @@ +'use strict'; + +// meta implicitMaps.used (README.md "Implicit maps"): the maps {base}{key} are offered for a +// translation between the file's system and the map's system whether or not they translate the code, +// and a translation reports the map it used as `{base}{used}{key}|{version}`. With forwardOnly a +// translation into the file's system finds nothing (the map is still offered: used-system), and with +// compatibility.translationDisplayIsSourceDisplay a target carries the display of the concept +// translated. The fixture has the shape of the OMOP importer's file, nothing in it real. + +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 URI = 'http://example.org/vocabularies'; +const TARGET = 'http://example.org/target-system'; +const BASE = URI + '/ConceptMap/'; +let app, tx, dir, factory; + +function build(file, used) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: URI, version: '20240101', name: 'Vocabularies' }); + const c100 = b.concept('100', { display: 'Thing one' }); + b.literal(c100, b.property({ code: 'valid-start-date', shape: 'literal', fhirType: 'string' }), '1970-01-01'); + b.concept('200', { display: 'Thing two' }); + b.reading({ + meta: { + implicitMaps: { base: BASE, maps: [[TARGET, '777']], ...(used ? { used: 'to-' } : {}), forwardOnly: true }, + compatibility: { translationDisplayIsSourceDisplay: true }, + }, + newProperties: [{ code: 'source-concept-code', shape: 'mapping', fhirType: 'Coding' }], + }); + b.mapping(c100, { property: b.propertyId('source-concept-code'), system: TARGET, code: 'T1', display: 'Target one', relationship: 'equivalent' }); + b.finish(); + // fhir_type date (OMOP's dates; the JS builder writes no such type) + const Database = require('../../library/sql/better-sqlite3'); + const db = new Database(file); + db.prepare("UPDATE property SET fhir_type = 'date' WHERE code = 'valid-start-date'").run(); + db.close(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-used-')); + const file = path.join(dir, 'vocab.db'); + build(file, true); + build(path.join(dir, 'plain.db'), false); + app = await getTestApp(); + tx = getTxModule(); + factory = await loadSqliteV2Factory(tx.i18n, file); + const p = tx.endpoints[0].provider; + p.codeSystemFactories.set(URI, factory); + p.codeSystemFactories.set(URI + '|20240101', factory); +}, 60000); + +afterAll(async () => { + factory.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +async function translate(system, code, target) { + const res = await request(app).post('/tx/r5/ConceptMap/$translate').send({ resourceType: 'Parameters', parameter: [ + { name: 'system', valueUri: system }, { name: 'sourceCode', valueCode: code }, { name: 'targetSystem', valueUri: target }] }); + expect(res.status).toBe(200); + const ps = res.body.parameter || []; + return { + result: (ps.find((p) => p.name === 'result') || {}).valueBoolean, + usedSystem: ps.filter((p) => p.name === 'used-system').map((p) => p.valueUri), + usedMap: ps.filter((p) => p.name === 'used-conceptmap').map((p) => p.valueUri), + matches: ps.filter((p) => p.name === 'match').map((m) => m.part.find((x) => x.name === 'concept').valueCoding), + }; +} + +test('the file loads: implicitMaps.used is read, not refused', () => { + expect(factory.store.implicitMapsSpec.used).toBe('to-'); +}); + +test('a translation reports the map as {base}{used}{key}|{version}, the target with the source concept\'s display', async () => { + const r = await translate(URI, '100', TARGET); + expect(r.result).toBe(true); + expect(r.usedMap).toEqual([BASE + 'to-777|20240101']); + expect(r.matches).toEqual([{ system: TARGET, code: 'T1', display: 'Thing one' }]); +}); + +test('the map is offered whether or not it translates the code: a code without a row, and the reverse direction', async () => { + const none = await translate(URI, '200', TARGET); + expect(none.result).toBe(false); + expect(none.usedSystem).toEqual([URI + '|20240101']); + expect(none.matches).toEqual([]); + const back = await translate(TARGET, 'T1', URI); + expect(back.result).toBe(false); + expect(back.usedSystem).toEqual([URI + '|20240101']); + expect(back.matches).toEqual([]); +}); + +test('without used: the map is offered only where it translates, and named by its own URL', async () => { + const plain = await loadSqliteV2Factory(tx.i18n, path.join(dir, 'plain.db')); + try { + const maps = []; + await plain.findImplicitConceptMaps(maps, URI, null, TARGET, '200'); + expect(maps).toEqual([]); + await plain.findImplicitConceptMaps(maps, TARGET, null, URI, 'T1'); + expect(maps).toEqual([]); + await plain.findImplicitConceptMaps(maps, URI, null, TARGET, '100'); + expect(maps.map((m) => m.url)).toEqual([BASE + '777']); + } finally { + plain.store.close(); + } +}); + +test('a literal of fhir_type date is reported as a dateTime (as cs-omop.js reports valid-start-date)', async () => { + const res = await request(app).post('/tx/r5/CodeSystem/$lookup').send({ resourceType: 'Parameters', parameter: [ + { name: 'system', valueUri: URI }, { name: 'code', valueCode: '100' }] }); + expect(res.status).toBe(200); + const p = res.body.parameter.find((x) => x.name === 'property' && x.part[0].valueCode === 'valid-start-date'); + expect(p.part[1]).toEqual({ name: 'value', valueDateTime: '1970-01-01' }); +}); diff --git a/tests/tx/sqlite-v2-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js index 8e9a7472..61503566 100644 --- a/tests/tx/sqlite-v2-loinc.test.js +++ b/tests/tx/sqlite-v2-loinc.test.js @@ -215,14 +215,50 @@ describe('LOINC v2 importer over the test fixture', () => { expect(status.all(id('LP7786-9'))).toEqual(['ACTIVE']); }); + test('the FHIR reading: meta keys, the catalog\'s reading columns, item uses, filter rows, mappings by map key', () => { + const meta = Object.fromEntries(db.prepare("SELECT key, value FROM meta WHERE key NOT LIKE 'provenance.%'").raw().all()); + expect(JSON.parse(meta.requires)).toEqual(['identifier-text', 'fhir-reading']); + expect(JSON.parse(meta.conceptStatus)).toEqual([{ property: 'STATUS', values: { DISCOURAGED: ['inactive'], DEPRECATED: ['inactive', 'deprecated'] } }]); + expect(JSON.parse(meta.order)).toEqual({ expansion: ['stored'], searchTies: ['display', 'stored'], links: ['stored', 'property-id', 'group', 'code'] }); + expect(JSON.parse(meta.search)).toEqual({ names: { display: 'en', items: { designations: true, excludeUses: ['RELATEDNAMES2'] } } }); + expect(JSON.parse(meta.compatibility).statusReadingsIgnored).toEqual([{ property: 'STATUS', values: { DEPRECATED: ['inactive'] } }]); + expect(JSON.parse(meta.codeLink)).toBe('https://loinc.org/{code}/'); + expect(Object.keys(meta).filter((k) => k.startsWith('behaviour.') || ['linkOrder', 'searchTieBreak', 'ix.ix_word.names'].includes(k))).toEqual([]); + const col = (code) => db.prepare('SELECT shape, lookup, expansion, lookup_rank, internal, also_asked_as FROM property WHERE code = ?').get(code); + expect(col('CLASS')).toMatchObject({ lookup: 'default', lookup_rank: 0 }); + expect(col('METHOD_TYP')).toMatchObject({ lookup_rank: 60 }); + expect(col('Answer')).toMatchObject({ lookup_rank: 80, also_asked_as: '["answer-list"]' }); + expect(col('answers-for')).toMatchObject({ lookup_rank: 85 }); + expect(col('child')).toMatchObject({ lookup_rank: 90 }); + expect(col('STATUS')).toMatchObject({ lookup_rank: 110 }); + expect(col('CLASSTYPE')).toMatchObject({ lookup_rank: 100 }); + expect(col('ancestor')).toMatchObject({ lookup: 'never', expansion: 'never', lookup_rank: null }); + expect(col('Answer|answers-for')).toMatchObject({ shape: 'union', internal: 1, lookup: 'never' }); + expect(col('RELATEDNAMES2')).toMatchObject({ shape: 'item-use', lookup_rank: 120 }); + expect(col('sct')).toMatchObject({ shape: 'mapping', lookup_rank: 130 }); + expect(db.prepare('SELECT code, role, as_property, language_display_rank FROM item_use WHERE role IS NOT NULL OR as_property IS NOT NULL OR language_display_rank IS NOT NULL ORDER BY code').raw().all()) + .toEqual([['DisplayName', null, null, 3], ['LONG_COMMON_NAME', 'display', null, 1], ['LinguisticVariantDisplayName', 'display', null, null], + ['RELATEDNAMES2', null, 'RELATEDNAMES2', null], ['SHORTNAME', 'display', null, 2]]); + // 52 rows, one per link and literal, then LOINC's own nine + const filters = db.prepare('SELECT code, operators, reads, then_link FROM filter ORDER BY id').raw().all(); + expect(filters).toHaveLength(61); + expect(filters.slice(52).map((f) => f[0])).toEqual(['answers-for', 'answers-for', 'STATUS', 'copyright', 'ancestor', 'concept', 'code', 'LIST', 'answer-list']); + expect(filters[52]).toEqual(['answers-for', '["=","in"]', '["concept","answers-for"]', 'Answer']); + // every mapping row of a mapped system belongs to its map key's row + expect(db.prepare(`SELECT count(*) FROM mapping m LEFT JOIN property p ON p.id = m.property_id + WHERE m.system = 'http://snomed.info/sct' AND (p.code IS NOT 'sct')`).pluck().get()).toBe(0); + expect(db.prepare("SELECT count(*) FROM mapping WHERE system = 'http://snomed.info/sct'").pluck().get()).toBeGreaterThan(0); + }); + 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 }); + const row = (code) => db.prepare(`SELECT p.code, i.code AS inverse_of, (SELECT count(*) FROM filter f WHERE f.code = p.code) AS filters, p.ordered + 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', filters: 1, ordered: 0 }); + expect(row('AnswerList')).toEqual({ code: 'AnswerList', inverse_of: 'Answer|answers-for', filters: 1, ordered: 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'); @@ -290,7 +326,7 @@ describe('LOINC v2 importer over the test fixture', () => { 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.stored, o.selfFirst, o.hasWalk]).toEqual([true, false, true]); expect([...o.rank]).toEqual(arr('rank')); expect([...o.ids]).toEqual(arr('ids')); expect([...o.walk]).toEqual(arr('walk')); @@ -312,6 +348,13 @@ describe('LOINC v2 dialect against main\'s provider (same fixture)', () => { } finally { sel.mockRestore(); } }); + test('a code\'s link: its page at loinc.org, as main\'s provider gives it', async () => { + const { V2Concept } = require('../../tx/sqlite-v2/provider'); + for (const code of ['2345-7', 'LP14355-9', 'LA6576-8']) { + expect(v2.codeLink(new V2Concept(1, code))).toBe(classic.codeLink({ code })); + } + }); + 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}`); @@ -837,4 +880,18 @@ describe('LOINC v2 provider filter API against main\'s', () => { const outside = (await p2.locate('LP432695-7')).context; expect(!!(await p2.filterCheck(a.prep, a.set, outside))).toBe(a.out.includes('LP432695-7')); }); + + test('iterator(null) follows the stored walk order (matching classic LOINC whole-system order)', async () => { + const firstN = async (prov, n) => { + const it = await prov.iterator(null); + const out = []; + for (let i = 0; i < n; i++) { + const c = await prov.nextContext(it); + if (!c) break; + out.push(await prov.code(c)); + } + return out; + }; + expect(await firstN(p2, 10)).toEqual(await firstN(pc, 10)); + }); }); diff --git a/tests/tx/sqlite-v2-mixed-providers.test.js b/tests/tx/sqlite-v2-mixed-providers.test.js index 37062c13..b30a5f43 100644 --- a/tests/tx/sqlite-v2-mixed-providers.test.js +++ b/tests/tx/sqlite-v2-mixed-providers.test.js @@ -33,6 +33,9 @@ const VALIDATE = '/tx/r5/ValueSet/$validate-code'; function buildV2(dest) { const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); b.codeSystem({ uri: V2, version: '1' }); + // the hierarchy filter (a filter that is no row of the file is not understood); the display is + // listed first among the designations (the expansion's display is the preferred designation) + b.reading({ meta: { compatibility: { displayDesignation: 'once' } }, filters: [{ code: 'concept', operators: ['is-a', 'descendent-of', '='], reads: 'concept' }] }); const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); const c = {}; for (const code of ['root', 'A', 'A1', 'A2', 'A3', 'B', 'B1']) { @@ -49,6 +52,7 @@ 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 }); + b.reading({ filters: [{ code: 'concept', operators: ['is-a', 'descendent-of', '='], reads: 'concept' }] }); 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}` }); @@ -253,6 +257,36 @@ describe('sqlite-v2 in mixed value sets (custom-code providers alongside the eng expect(unclosed(await expand(vs(inc(V2OPEN, { filters: [['concept', 'is-a', 'X'], ['tier', '=', 'gold']] })), supp))).toBe(true); }); + test('non-enumerable supplement-only filter (not-in / exists=false alone): 422 on $expand, 200 on $validate-code', async () => { + const supp = [{ name: 'tx-resource', resource: SUPP_TIER }, { name: 'useSupplement', valueCanonical: SUPP_TIER.url }]; + const vs = (...include) => ({ resourceType: 'ValueSet', status: 'active', compose: { include } }); + + // single-system $expand (processSelection path): 422 FILTER_NOT_UNDERSTOOD with expression + for (const [op, val] of [['not-in', 'gold'], ['exists', 'false']]) { + const res = await post(EXPAND, [{ name: 'valueSet', resource: vs(inc(V2OPEN, { filters: [['tier', op, val]] })) }, ...supp]); + expect(res.status).toBe(422); + expect(res.body.resourceType).toBe('OperationOutcome'); + expect(res.body.issue[0].code).toBe('not-supported'); + expect(res.body.issue[0].expression).toEqual(['ValueSet.compose.include[0].filter']); + expect(res.body.issue[0].details.coding[0].code).toBe('vs-invalid'); + expect(res.body.issue[0].extension[0].valueString).toBe('FILTER_NOT_UNDERSTOOD'); + } + + // multi-system $expand (includeCodes fallback path): also 422 FILTER_NOT_UNDERSTOOD + const mixedRes = await post(EXPAND, [{ name: 'valueSet', resource: vs(inc(V2OPEN, { filters: [['tier', 'not-in', 'gold']] }), inc(UCUM, { codes: ['mg'] })) }, ...supp]); + expect(mixedRes.status).toBe(422); + expect(mixedRes.body.issue[0].extension[0].valueString).toBe('FILTER_NOT_UNDERSTOOD'); + + // combined with a base filter on $expand: 200 OK + const withBase = await expand(vs(inc(V2OPEN, { filters: [['concept', 'is-a', 'X'], ['tier', 'not-in', 'gold']] })), supp); + expect(flat(withBase.expansion.contains).map(([, code]) => code).sort()).toEqual(['X', 'X2']); + + // $validate-code with not-in alone: 200 OK (membership check does not enumerate) + const vsNotIn = vs(inc(V2OPEN, { filters: [['tier', 'not-in', 'gold']] })); + expect(named(await validate(vsNotIn, V2OPEN, 'X2', supp), 'result').valueBoolean).toBe(true); + expect(named(await validate(vsNotIn, V2OPEN, 'X1', supp), 'result').valueBoolean).toBe(false); + }); + 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' }] }] }, diff --git a/tests/tx/sqlite-v2-regex.test.js b/tests/tx/sqlite-v2-regex.test.js index 4988c7ff..5508fd8a 100644 --- a/tests/tx/sqlite-v2-regex.test.js +++ b/tests/tx/sqlite-v2-regex.test.js @@ -73,7 +73,6 @@ describe('sqlite-v2 display regex (generic code system): prefilter on and off gi 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; @@ -81,6 +80,8 @@ describe('sqlite-v2 display regex (generic code system): prefilter on and off gi 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' }); + // the display filter: reads concept.display + b.reading({ filters: [{ code: 'display', operators: ['regex'], reads: 'display' }] }); 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', @@ -94,7 +95,7 @@ describe('sqlite-v2 display regex (generic code system): prefilter on and off gi afterAll(() => { S.close(); fs.rmSync(dir, { recursive: true, force: true }); }); const run = (re, strip) => { - const c = new Compiler({ store: S, dialect: dialectFor(SCT) }); + const c = new Compiler({ store: S }); 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); @@ -125,7 +126,6 @@ describe('sqlite-v2 display regex on the SNOMED CT test edition (tx/data/snomed 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; @@ -168,7 +168,7 @@ describe('sqlite-v2 display regex on the SNOMED CT test edition (tx/data/snomed '.*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 c = new Compiler({ store: S, grammar: require('../../tx/sqlite-v2/snomed').SnomedV2Factory.grammarRules }); const mk = () => c.selection([{ system: SCT, filter: [{ property: 'display', op: 'regex', value: p }] }], [], false); const selOn = mk(); const selOff = mk(); diff --git a/tests/tx/sqlite-v2-rxnorm-filters.test.js b/tests/tx/sqlite-v2-rxnorm-filters.test.js index c7cdf0bc..1d617c82 100644 --- a/tests/tx/sqlite-v2-rxnorm-filters.test.js +++ b/tests/tx/sqlite-v2-rxnorm-filters.test.js @@ -215,7 +215,7 @@ describe('sqlite-v2 RxNorm filters, as main', () => { 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])); + const rows = Object.fromEntries(db.prepare('SELECT p.code, p.shape, p.wildcard, (SELECT count(*) FROM link l WHERE l.property_id = p.id) FROM property p').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 diff --git a/tests/tx/sqlite-v2-rxnorm-status.test.js b/tests/tx/sqlite-v2-rxnorm-status.test.js index aedbd00a..19c4a97d 100644 --- a/tests/tx/sqlite-v2-rxnorm-status.test.js +++ b/tests/tx/sqlite-v2-rxnorm-status.test.js @@ -2,8 +2,10 @@ // 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. +// includes, not deprecated); one found only in RXNATOMARCHIVE is inactive, 'archived' (its +// deprecated reading has no effect on an inactive concept), and never selected. The importer +// writes the status literal on every concept (active, obsolete, archived); meta conceptStatus +// gives the meanings, and concept.active follows it. const fs = require('fs'); const os = require('os'); @@ -12,7 +14,7 @@ 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 Database = require('../../library/sql/better-sqlite3'); const RX = 'http://www.nlm.nih.gov/research/umls/rxnorm'; let dir, db; @@ -44,11 +46,27 @@ beforeAll(async () => { afterAll(() => fs.rmSync(dir, { recursive: true, force: true })); describe('sqlite-v2 RxNorm obsolete and archived concepts', () => { + test('the file: a status literal on every concept, concept.active from conceptStatus, archive atoms stored active', () => { + const d = new Database(db, { readonly: true }); + try { + expect(d.prepare(`SELECT c.code, c.active, l.value FROM concept c JOIN literal l ON l.subject_id = c.id + JOIN property p ON p.id = l.property_id WHERE p.code = 'status' ORDER BY c.code`).raw().all()) + .toEqual([['100', 1, 'active'], ['200', 0, 'obsolete'], ['300', 1, 'active'], ['400', 0, 'archived']]); + expect(JSON.parse(d.prepare("SELECT value FROM meta WHERE key = 'conceptStatus'").pluck().get())) + .toEqual([{ property: 'status', values: { obsolete: ['inactive'], archived: ['inactive', 'deprecated', 'unlisted'] } }]); + expect(d.prepare("SELECT text, active FROM item WHERE concept_id = (SELECT id FROM concept WHERE code = '400')").raw().all()).toEqual([['archived drug', 1]]); + expect(d.prepare("SELECT role, lookup, expansion FROM property WHERE code = 'status'").raw().get()).toEqual(['status', 'never', 'never']); + // the word index leaves out the unlisted (archived) concepts + expect(d.prepare("SELECT count(*) FROM ix_word WHERE word = 'archived'").pluck().get()).toBe(0); + expect(d.prepare("SELECT count(*) FROM ix_word WHERE word = 'obsolete'").pluck().get()).toBe(1); + } finally { d.close(); } + }); + 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 c = new Compiler({ store: S }); 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(); @@ -75,10 +93,14 @@ describe('sqlite-v2 RxNorm obsolete and archived concepts', () => { 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]); + // (the status text is the stored status value, `active` included: README.md "Concept status"; + // expand.js and validate.js leave it out of their answers for an active concept) + expect(await facts('100')).toEqual([false, 'active', 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]); + expect(await facts('300')).toEqual([false, 'active', false]); + // (archived means deprecated too, but a concept is deprecated only while active: README.md + // "Concept status"; the inactive status text is what is reported) + expect(await facts('400')).toEqual([true, 'archived', false]); const all = await p.iteratorAll(); expect(all.total).toBe(3); } finally { diff --git a/tests/tx/sqlite-v2-sct-concrete-type-relationship.test.js b/tests/tx/sqlite-v2-sct-concrete-type-relationship.test.js index 0020d9e3..c8073ced 100644 --- a/tests/tx/sqlite-v2-sct-concrete-type-relationship.test.js +++ b/tests/tx/sqlite-v2-sct-concrete-type-relationship.test.js @@ -4,8 +4,8 @@ // 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. +// relationships: the reader reads active links only, so $lookup is main's (the format has no +// column that hides a 'both' property's links: an inactive row is the only such link). const fs = require('fs'); const os = require('os'); @@ -56,8 +56,9 @@ function rows(db, code) { const S = openStore(db, { unregistered: true }); try { const unnamed = S.linksFrom([S.idOf(SOURCE)], null, false).filter((l) => l.p === p.id).length; + const unnamedActive = S.linksFrom([S.idOf(SOURCE)], null, true).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 }; + return { shape: p.shape, links, literals, unnamed, unnamedActive, named }; } finally { S.close(); } } @@ -72,12 +73,12 @@ beforeAll(async () => { 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 () => { +test('RF2: the inactive row is a link of the attribute (shape both), not read by a lookup (active links only)', 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 }); + expect(rows(db, COUNT_OF_BASE)).toEqual({ shape: 'both', links: 1, literals: 4, unnamed: 1, unnamedActive: 0, named: 1 }); }, 120000); test('cache: the same row from main\'s cache, the same way', async () => { @@ -90,5 +91,5 @@ test('cache: the same row from main\'s cache, the same way', async () => { 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 }); + expect(rows(db, COUNT_OF_BASE)).toEqual({ shape: 'both', links: 1, literals: 4, unnamed: 1, unnamedActive: 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 index 14145e18..efc2f95c 100644 --- a/tests/tx/sqlite-v2-sct-default-language.test.js +++ b/tests/tx/sqlite-v2-sct-default-language.test.js @@ -169,17 +169,17 @@ describe('SNOMED CT default language', () => { const saved = store._textLangs; try { store._textLangs = new Set(['en', 'no']); - expect(p._sctFilterLanguage(['nb'])).toBe('no'); - expect(p._sctFilterLanguage(['nn-NO'])).toBe('no'); + expect(p._fileSearchLanguage(['nb'])).toBe('no'); + expect(p._fileSearchLanguage(['nn-NO'])).toBe('no'); store._textLangs = new Set(['en', 'nb']); - expect(p._sctFilterLanguage(['no'])).toBe('nb'); - expect(p._sctFilterLanguage(['de', 'nb'])).toBe('nb'); + expect(p._fileSearchLanguage(['no'])).toBe('nb'); + expect(p._fileSearchLanguage(['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'); + expect(p._fileSearchLanguage([])).toBe('en'); store._textLangs = new Set(['nb', 'fr']); - expect(p._sctFilterLanguage([])).toBe('fr'); + expect(p._fileSearchLanguage([])).toBe('fr'); store._textLangs = new Set(['nl', 'en']); - expect(p._sctFilterLanguage([])).toBe('nl'); + expect(p._fileSearchLanguage([])).toBe('nl'); } finally { store._textLangs = saved; } diff --git a/tests/tx/sqlite-v2-sct-ecl.test.js b/tests/tx/sqlite-v2-sct-ecl.test.js index 432203ff..c688e5c8 100644 --- a/tests/tx/sqlite-v2-sct-ecl.test.js +++ b/tests/tx/sqlite-v2-sct-ecl.test.js @@ -14,6 +14,10 @@ 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 { importSnomedV2FromCache } = require('../../tx/importers/import-sct-v2-cache.module'); +const { TerminologyBuilder } = require('../../tx/importers/sqlite-v2/builder'); +const { openStore } = require('../../tx/sqlite-v2/store'); +const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); +const { Engine } = require('../../tx/sqlite-v2/engine/engine'); const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); const { OperationContext } = require('../../tx/operation-context'); const { TestUtilities } = require('../test-utilities'); @@ -99,6 +103,29 @@ describe('SNOMED CT ECL description filters and compound ECL, as cs-snomed.js', '(<< 159033005 {{ term = "renal" }}) OR (<< 159033005 {{ term = "liver" }})', '<< 159033005 MINUS (<< 159033005 {{ term = "renal" }})']) await same(e); expect((await same('<< 309413008 OR << 159033005'))[0]).toBe('309413008'); }); + + test('{{ + HISTORY-* }} preserves focus-first ordering before added inactive concepts, as cs-snomed.js', async () => { + for (const e of [ + '<< 404684003 {{ + HISTORY-MIN }}', + '<< 404684003 {{ + HISTORY-MOD }}', + '<< 404684003 {{ + HISTORY-MAX }}', + ]) { + const got = await same(e); + expect(got[0]).toBe('404684003'); + } + }); + + test('?fhir_vs=refset lists the same reference sets as cs-snomed.js (including language refsets)', async () => { + // In this minimal test edition, 900000000000534007 (Module dependency refset) has no concept row, + // so main's cache stores definition=0 (concept index 0 = 192008); every real refset matches. + const want = (await main.buildKnownValueSet('http://snomed.info/sct?fhir_vs=refset', null)).compose.include[0].concept + .map((c) => c.code).filter((c) => c !== '192008').sort(); + const got = (await engine.buildKnownValueSet('http://snomed.info/sct?fhir_vs=refset', null)).compose.include[0].concept + .map((c) => c.code).sort(); + expect(got).toEqual(want); + expect(got).toContain('900000000000509007'); + expect(got).toContain('900000000000508004'); + }); }); describe('SNOMED CT ECL reversed is-a (triage B6), as cs-snomed.js', () => { @@ -129,9 +156,89 @@ describe('SNOMED CT ECL the engine hands to main\'s ECL (sct-main-ecl.js)', () = } }); + test('member filters {{ M ... }} inside fallback ECL match cs-snomed.js (getMemberKindsAndValues / getMember)', async () => { + // Role-group OR / cardinality / != triggers eclFallback to sct-main-ecl.js; inside it, + // cs-snomed.js indexes = filters on integer/string member fields via getMemberKindsAndValues + getMember. + const positiveCases = [ + '(< 404684003 : { [1..2] 363698007 = << 123037004 OR 116676008 = * }) OR (^ 1000901000003102 {{ M mapGroup = #1, mapPriority = #1 }})', + '(< 404684003 : { [1..2] 363698007 != << 123037004 OR 363698007 != (^ 1000901000003102 {{ M mapGroup = #1, mapPriority = #1 }}) })', + '(< 404684003 : { [1..2] 363698007 = << 123037004 OR 116676008 = * }) OR (^ 1000901000003102 {{ M mapTarget = "S36.115" }})', + '(^ 1000901000003102 {{ M mapGroup = #2, mapTarget = "Y92.9" }}) : { [0..1] 363698007 = * }' + ]; + for (const text of positiveCases) { + const want = await same(text); + expect([text, want.length > 0]).toEqual([text, true]); + expect(engine.store._mainEcl && engine.store._mainEcl.has(text)).toBe(true); + } + expect(await same('(^ 1000901000003102 {{ M mapGroup = #2, mapTarget = "Y92.9" }}) : { [0..1] 363698007 = * }')).toEqual(['262797004']); + + // Empty-result case matching Seed 7 shape + const emptyCase = '(^ 1000901000003102 {{ M mapGroup = #1, mapPriority = #1 }}) : { [1..2] 363698007 != * OR 116676008 != (^ 1000901000003102 {{ M mapGroup = #1, mapPriority = #1 }}) }, { 363698007 = 1000901000003102 }'; + expect(await same(emptyCase)).toEqual([]); + expect(engine.store._mainEcl && engine.store._mainEcl.has(emptyCase)).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(); }); }); + +describe('{{ + HISTORY-* }} ignores description-level association refsets (item subjects)', () => { + test('HISTORY-MAX skips 900000000000531004 |REFERS TO| and item rows in mixed association refsets', () => { + const dbPath = path.join(dir, 'history-item-refset.db'); + const b = new TerminologyBuilder(dbPath, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://snomed.info/sct', version: 'http://snomed.info/sct/900000000000207008/version/20260701' }); + b.reading({ + meta: { grammar: 'snomed' }, + filters: [{ code: 'constraint', operators: ['='], reads: 'grammar' }] + }); + const isa = b.property({ code: '116680003', shape: 'link', subsumption: true, refinable: true }); + const c = { + histRoot: b.concept('900000000000522004', { active: true, display: 'Historical association' }), + sameAs: b.concept('900000000000527005', { active: true, display: 'SAME AS association reference set' }), + wasA: b.concept('900000000000528000', { active: true, display: 'WAS A association reference set' }), + refersTo: b.concept('900000000000531004', { active: true, display: 'REFERS TO concept association reference set' }), + mod: b.concept('900000000000207008', { active: true, display: 'SNOMED CT core module' }), + asthma: b.concept('195967001', { active: true, display: 'Asthma' }), + asthmaticEos: b.concept('233691007', { active: true, display: 'Asthmatic pulmonary eosinophilia' }), + pulmEos: b.concept('367542003', { active: true, display: 'Pulmonary eosinophilia' }), + oldAsthma: b.concept('100001', { active: false, display: 'Old asthma' }), + oldEos: b.concept('100002', { active: false, display: 'Old asthmatic pulmonary eosinophilia' }) + }; + b.link(c.sameAs, isa, c.histRoot); + b.link(c.wasA, isa, c.histRoot); + b.link(c.refersTo, isa, c.histRoot); + b.link(c.asthmaticEos, isa, c.asthma); + const fields = [{ name: 'effectiveTime', type: 't' }, { name: 'moduleId', type: 'c' }, { name: 'targetComponentId', type: 'c', target: true }]; + const pSameAs = b.property({ code: '900000000000527005', concept: c.sameAs, shape: 'record', fields }); + const pWasA = b.property({ code: '900000000000528000', concept: c.wasA, shape: 'record', fields }); + const pRefersTo = b.property({ code: '900000000000531004', concept: c.refersTo, shape: 'record', fields }); + const inactiveDesc1 = b.item(c.pulmEos, { language: 'en', text: 'Eosinophilic asthma', active: false }); + const inactiveDesc2 = b.item(c.pulmEos, { language: 'en', text: 'Asthma-like eosinophilia', active: false }); + b.record(pSameAs, c.oldAsthma, { target: c.asthma, fields: ['20220228', c.mod] }); + b.record(pWasA, c.oldEos, { target: c.asthmaticEos, fields: ['20220228', c.mod] }); + b.record(pWasA, inactiveDesc2, { target: c.asthma, fields: ['20220228', c.mod] }); + b.record(pRefersTo, inactiveDesc1, { target: c.asthmaticEos, fields: ['20220228', c.mod] }); + b.finish(); + + const s = openStore(dbPath); + try { + const eng = new Engine(s); + const evalEcl = (text) => { + const comp = new Compiler({ store: s, grammar: {} }); + const bm = eng.evaluate(comp.ecl(text)); + const rows = s.conceptRows(bm.toArray()); + return bm.toArray().map((id) => rows.get(id).code).sort(); + }; + expect(evalEcl('<< 195967001 {{ + HISTORY-MAX }}')).toEqual(['100001', '100002', '195967001', '233691007']); + expect(evalEcl('<< 195967001 {{ + HISTORY (900000000000531004) }}')).toEqual(['195967001', '233691007']); + expect(evalEcl('<< 195967001 {{ + HISTORY (900000000000528000) }}')).toEqual(['100002', '195967001', '233691007']); + expect(s.refsetMemberRows(s.idOf('900000000000531004'), null, { conceptsOnly: true })).toEqual([]); + expect(() => evalEcl('(<< 195967001).1166760')).toThrow('The SNOMED CT Concept 1166760 is not known'); + } finally { + s.close(); + } + }); +}); diff --git a/tests/tx/sqlite-v2-sct-from-cache.test.js b/tests/tx/sqlite-v2-sct-from-cache.test.js index dd5f4455..3b34e79f 100644 --- a/tests/tx/sqlite-v2-sct-from-cache.test.js +++ b/tests/tx/sqlite-v2-sct-from-cache.test.js @@ -186,9 +186,9 @@ describe('the system order (ix_order, tx/sqlite-v2/orders.js)', () => { 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); + const stored = storedOrder(s1); expect(stored.loadedBytes()).toBe(0); - expect([stored.selfFirst, stored.hasWalk]).toEqual([true, true]); + expect(stored.hasWalk).toBe(true); const n = stored.rank.length; expect(stored.loadedBytes()).toBe(stored.rank.byteLength); expect(stored.ids.length).toBe(n); diff --git a/tests/tx/sqlite-v2-sct-lookup.test.js b/tests/tx/sqlite-v2-sct-lookup.test.js index 5788fe00..ce077070 100644 --- a/tests/tx/sqlite-v2-sct-lookup.test.js +++ b/tests/tx/sqlite-v2-sct-lookup.test.js @@ -97,6 +97,34 @@ describe('sqlite-v2 SNOMED CT $lookup and implicit value sets, as main', () => { expect(generic.compose.include[0].version).toBeUndefined(); }); + test('?fhir_vs=refset includes language refsets and module dependency refset when present', async () => { + const vs = await factory.buildKnownValueSet('http://snomed.info/sct?fhir_vs=refset', null); + const codes = vs.compose.include[0].concept.map((c) => c.code); + expect(codes).toEqual([...new Set(codes)].sort()); + // concept-member refset + expect(codes).toContain('723264001'); + // language refsets (stored in record on items, not ix_set kind=7) + expect(codes).toContain('900000000000509007'); + expect(codes).toContain('900000000000508004'); + // module dependency refset (900000000000534007): included whenever the concept exists and moduleDependencies is non-empty + const origIdOf = factory.store.idOf.bind(factory.store); + const sentinel = origIdOf('138875005'); // not itself a refset + expect(codes).not.toContain('138875005'); + const spy = jest.spyOn(factory.store, 'idOf').mockImplementation((c) => (c === '900000000000534007' ? sentinel : origIdOf(c))); + const savedMd = factory.store.moduleDependencies; + try { + expect(savedMd.length).toBeGreaterThan(0); + const vsWithMd = await factory.buildKnownValueSet('http://snomed.info/sct?fhir_vs=refset', null); + expect(vsWithMd.compose.include[0].concept.map((c) => c.code)).toContain('138875005'); + factory.store.moduleDependencies = []; + const vsNoMd = await factory.buildKnownValueSet('http://snomed.info/sct?fhir_vs=refset', null); + expect(vsNoMd.compose.include[0].concept.map((c) => c.code)).not.toContain('138875005'); + } finally { + factory.store.moduleDependencies = savedMd; + spy.mockRestore(); + } + }); + 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 @@ -111,9 +139,102 @@ describe('sqlite-v2 SNOMED CT $lookup and implicit value sets, as main', () => { }); 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); + const { evaluateEcl, resolveMainEcl, mainEclResult } = require('../../tx/sqlite-v2/sct-main-ecl'); + const expr = '< 64572001 : 363698007 = << 10200004'; + const bm = await evaluateEcl(factory.store, expr, null); expect(bm.size).toBeGreaterThan(0); + await resolveMainEcl(factory.store, expr); + const kept = mainEclResult(factory.store, expr); + expect(Array.isArray(kept.order)).toBe(true); + expect(kept.order.length).toBe(bm.size); + }); + + test('doesFilter accepts constraint = so filter() reports 400 INVALID_ECL', async () => { + const p = await factory.build(op, []); + expect(await p.doesFilter('constraint', '=', '!!< << 64572001')).toBe(true); + const prep = await p.getPrepContext(false); + await expect(p.filter(prep, false, 'constraint', '=', '!!< << 64572001')).rejects.toMatchObject({ + statusCode: 400, + msgId: 'INVALID_ECL', + }); + }); + + test('Evaluator._mat on a group node does not recurse via filterG', () => { + const { Evaluator } = require('../../tx/sqlite-v2/engine/evaluate'); + const S = factory.store; + const site = S.props.get('363698007').id; + const ev = new Evaluator(S); + const groupNode = { + t: 'group', + attrs: [{ pids: [site], values: { t: 'all' } }], + min: 2, + max: 3, + }; + const origFilterG = ev.filterG.bind(ev); + let groupFilterCalls = 0; + ev.filterG = function* (n, cand) { + if (n === groupNode) groupFilterCalls++; + return yield* origFilterG(n, cand); + }; + const res = ev.mat(groupNode); + expect(groupFilterCalls).toBe(0); + expect(res.has(S.idOf('51292008'))).toBe(true); + }); + + test('implicit ?fhir_vs=ecl/ returns null when empty and tolerates invalid % escapes', async () => { + expect(await factory.buildKnownValueSet('http://snomed.info/sct?fhir_vs=ecl/', null)).toBeNull(); + expect(await factory.buildKnownValueSet('http://snomed.info/sct?fhir_vs=ecl/%20%20', null)).toBeNull(); + const vs = await factory.buildKnownValueSet('http://snomed.info/sct?fhir_vs=ecl/%ZZ', null); + expect(vs).not.toBeNull(); + expect(vs.compose.include[0].filter[0].value).toBe('%ZZ'); + }); + + test('NativeExpressionServices.exprRels preserves concrete refinements for ECL matching', () => { + const E = require('../../tx/sct/expressions'); + const { ECLLexer, ECLParser } = require('../../tx/sct/ecl'); + const { NativeExpressionServices } = require('../../tx/sqlite-v2/sct-native'); + const svc = new NativeExpressionServices(factory.store); + const expr = new E.SnomedExpressionParser(svc.conceptList).parse('64572001 : 363698007 = #500'); + const astPass = new ECLParser(new ECLLexer('<< 64572001 : 363698007 >= #100').tokenize()).parse(); + const astFail = new ECLParser(new ECLLexer('<< 64572001 : 363698007 < #100').tokenize()).parse(); + expect(svc.exprSatisfies(expr, astPass)).toBe(true); + expect(svc.exprSatisfies(expr, astFail)).toBe(false); + }); + + test('post-coordinated SCG membership against dotted ECL returns false/true cleanly without 500', async () => { + const E = require('../../tx/sct/expressions'); + const { ECLLexer, ECLParser } = require('../../tx/sct/ecl'); + const p = await factory.build(op, []); + const member = async (ecl, code) => { + const prep = await p.getPrepContext(true); + await p.filter(prep, true, 'constraint', '=', ecl); + const [set] = await p.executeFilters(prep); + const loc = await p.filterLocate(prep, set, code); + return loc != null && typeof loc === 'object'; + }; + + // Complex SCG with refinements against single-hop and multi-hop dotted ECL -> false (no throw/500) + expect(await member('(<< 40468003).363698007', '40468003:{363698007=181268008}')).toBe(false); + expect(await member('(<< 404684003).363698007.272741003', '40468003:{363698007=181268008}')).toBe(false); + // Compound ECL containing a dotted branch evaluates cleanly for a complex SCG + expect(await member('((<< 40468003).363698007) OR (<< 404684003)', '40468003:{363698007=181268008}')).toBe(true); + // Equivalent simple expression matching a dotted target -> true; non-target -> false + expect(await member('(<< 40468003).363698007', '=== 10200004')).toBe(true); + expect(await member('(<< 40468003).363698007', '=== 64572001')).toBe(false); + + // Direct exprSatisfies coverage for DottedExpressionConstraint and << (DottedExpressionConstraint) + const svc = p._native(); + const parseExpr = (s) => new E.SnomedExpressionParser(svc.conceptList).parse(s); + const parseEcl = (s) => new ECLParser(new ECLLexer(s).tokenize()).parse(); + const dottedAst = parseEcl('(<< 40468003).363698007'); + const belowDottedAst = parseEcl('<< ((<< 40468003).363698007)'); + expect(svc.exprSatisfies(parseExpr('40468003:{363698007=181268008}'), dottedAst)).toBe(false); + expect(svc.exprSatisfies(parseExpr('10200004:{272741003=182353008}'), dottedAst)).toBe(false); + expect(svc.exprSatisfies(parseExpr('10200004:{272741003=182353008}'), belowDottedAst)).toBe(true); + expect(svc.exprSatisfies(parseExpr('181268008:{272741003=182353008}'), belowDottedAst)).toBe(true); + expect(svc.exprSatisfies(parseExpr('=== 10200004'), dottedAst)).toBe(true); + expect(svc.exprSatisfies(parseExpr('=== 64572001'), dottedAst)).toBe(false); + expect(svc.exprSatisfies(parseExpr('<<< 10200004'), dottedAst)).toBe(false); }); }); diff --git a/tests/tx/sqlite-v2-sct-parity-http.test.js b/tests/tx/sqlite-v2-sct-parity-http.test.js index 7ced467c..7ccb710f 100644 --- a/tests/tx/sqlite-v2-sct-parity-http.test.js +++ b/tests/tx/sqlite-v2-sct-parity-http.test.js @@ -147,6 +147,28 @@ describe('SNOMED CT concept in / not-in with an unknown concept', () => { }); }); +describe('SNOMED CT a reference set whose members are descriptions (1000601000003105, the Dutch language reference set)', () => { + // ECL ^ R: refused by both, the same 400; concept in R: v2 refuses it for the same reason (main + // lists description indexes as codes: a known difference) + const expand = async (filter) => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: SCT, filter: [filter] }] } }; + const res = await call('post', '/tx/r5/ValueSet/$expand', { resourceType: 'Parameters', parameter: [{ name: 'valueSet', resource: vs }, { name: 'count', valueInteger: 20 }] }); + return { status: res.status, codes: ((res.body.expansion || {}).contains || []).map((c) => c.code), issues: issuesOf(res.body) }; + }; + const WHY = 'The members of reference set 1000601000003105 are descriptions, not concepts, so'; + test('^ 1000601000003105: refused, as main', async () => { + const r = await both(() => expand({ property: 'constraint', op: '=', value: '^ 1000601000003105' })); + expect(r.v2).toEqual(r.main); + expect(r.v2.status).toBe(400); + expect(r.v2.issues[0][2]).toContain(`${WHY} ^ cannot be evaluated for it`); + }); + test('concept in 1000601000003105: refused for the same reason, 400 invalid', async () => { + use(v2); + expect(await expand({ property: 'concept', op: 'in', value: '1000601000003105' })).toEqual({ status: 400, codes: [], + issues: [['error', 'invalid', `${WHY} concept in cannot be evaluated for it`]] }); + }); +}); + 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']; @@ -213,3 +235,66 @@ describe('SNOMED CT closedness of unions and excludes, as main', () => { expect(r.v2.unclosed).toBe(unclosed); }); }); + +describe('SNOMED CT row order of ancestor and is-a filters, as main', () => { + // main lists ancestors level by level from the concept's parents (cs-snomed.js filterGeneralizes; + // ECL >> adds the concept last), and walks an include's first filter, the others narrowing it + // 129249002 |Needle biopsy|, 86273004 |Biopsy|, 192008 (several levels of ancestors) + const f = (property, op, value) => ({ property, op, value }); + const cases = [ + ['generalizes', [f('concept', 'generalizes', '129249002')]], + ['generalizes, deep', [f('concept', 'generalizes', '192008')]], + ['ECL >', [f('constraint', '=', '> 192008')]], + ['ECL >>', [f('constraint', '=', '>> 192008')]], + ['generalizes + expressions = false', [f('concept', 'generalizes', '192008'), f('expressions', '=', 'false')]], + ['is-a + expressions = false', [f('concept', 'is-a', '86273004'), f('expressions', '=', 'false')]], + ['is-a + expressions = true', [f('concept', 'is-a', '86273004'), f('expressions', '=', 'true')]], + ['is-a + inactive = false', [f('concept', 'is-a', '86273004'), f('inactive', '=', 'false')]], + ]; + test.each(cases)('%s', async (name, filter) => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: SCT, filter }] } }; + const r = await both(async () => { + const res = await call('post', '/tx/r5/ValueSet/$expand', { resourceType: 'Parameters', parameter: [{ name: 'valueSet', resource: vs }, { name: 'count', valueInteger: 50 }] }); + return { status: res.status, codes: ((res.body.expansion || {}).contains || []).map((c) => c.code) }; + }); + expect(r.v2).toEqual(r.main); + expect(r.v2.status).toBe(200); + expect(r.v2.codes.length).toBeGreaterThan(1); + }); +}); + +describe('SNOMED CT expressions in $validate-code and $lookup, as main (<<< kept, triage B8)', () => { + // 64572001 |Disease|; 128241005 |Inflammatory disease of liver|, 363698007 |Finding site|, 181268008 |Entire liver|. + // A single concept written <<< X has the code << ({ resourceType: 'Parameters', parameter }); + + test.each(codes)('$validate-code %j', async (code) => { + const r = await both(async () => { + const res = await call('post', '/tx/r5/CodeSystem/$validate-code', P({ name: 'url', valueUri: SCT }, { name: 'code', valueCode: code })); + return { status: res.status, body: res.body }; + }); + expect(r.v2.status).toBe(200); + expect(r.v2).toEqual(r.main); + }); + + test.each([['<<<64572001', 'Disease'], ['<<<64572001', 'Not the display']])('$validate-code %j with display %j', async (code, display) => { + const r = await both(async () => { + const res = await call('post', '/tx/r5/CodeSystem/$validate-code', P({ name: 'url', valueUri: SCT }, { name: 'code', valueCode: code }, { name: 'display', valueString: display })); + return { status: res.status, body: res.body }; + }); + expect(r.v2.status).toBe(200); + expect(r.v2).toEqual(r.main); + }); + + test.each(codes)('$lookup %j', async (code) => { + const r = await both(async () => { + const res = await call('post', '/tx/r5/CodeSystem/$lookup', P({ name: 'system', valueUri: SCT }, { name: 'code', valueCode: code }, + { name: 'property', valueCode: 'inactive' }, { name: 'property', valueCode: 'parent' }, { name: 'property', valueCode: 'designation' })); + return { status: res.status, body: res.body }; + }); + expect(r.v2.status).toBe(200); + expect(r.v2).toEqual(r.main); + }); +}); diff --git a/tests/tx/sqlite-v2-sct-postcoord.test.js b/tests/tx/sqlite-v2-sct-postcoord.test.js index 8a6eb5aa..1255b67d 100644 --- a/tests/tx/sqlite-v2-sct-postcoord.test.js +++ b/tests/tx/sqlite-v2-sct-postcoord.test.js @@ -98,15 +98,55 @@ describe('sqlite-v2 SNOMED CT post-coordination (native) and ECL fallback', () = test('mapped: exists: concepts with (or without) an alternate identifier', async () => { const p = await factory.build(op, []); - const count = async (v) => { + const count = async (scheme, v) => { const prep = await p.getPrepContext(true); - await p.filter(prep, true, 'mapped:30051010000102', 'exists', v); + await p.filter(prep, true, `mapped:${scheme}`, 'exists', v); const [set] = await p.executeFilters(prep); return set.bm.size; }; - const yes = await count('true'); + const yes = await count('30051010000102', 'true'); expect(yes).toBeGreaterThan(0); - expect(yes + (await count('false'))).toBe(factory.store.conceptCount); + expect(yes + (await count('30051010000102', 'false'))).toBe(factory.store.conceptCount); + // unknown scheme (no identifier property in the edition): exists true -> 0, exists false -> all concepts + expect(await count('447562003', 'true')).toBe(0); + expect(await count('447562003', 'false')).toBe(factory.store.conceptCount); + }); + + test('concrete-domain SCG $lookup emits typed concrete refinement properties without crashing on NO_REFERENCE', async () => { + const p = await factory.build(op, []); + const lookupProps = async (expr) => { + const r = await p.locate(expr); + expect([expr, r.message || null]).toEqual([expr, null]); + const params = []; + await p.extendLookup(r.context, ['*'], params); + return params.filter((x) => x.name === 'property'); + }; + const intProps = await lookupProps('763158003 : 1142139005 = #1'); + const countProp = intProps.find((x) => x.part.some((y) => y.name === 'code' && y.valueCode === '1142139005')); + expect(countProp).toBeTruthy(); + expect(countProp.part.find((y) => y.name === 'value')).toEqual({ name: 'value', valueInteger: 1 }); + expect(countProp.part.find((y) => y.name === 'code-display').valueString).toMatch(/Count of base/i); + + const decProps = await lookupProps('763158003 : { 1142135004 = #2.5 }'); + const strengthProp = decProps.find((x) => x.part.some((y) => y.name === 'code' && y.valueCode === '1142135004')); + expect(strengthProp).toBeTruthy(); + expect(strengthProp.part.find((y) => y.name === 'value')).toEqual({ name: 'value', valueDecimal: 2.5 }); + }); + + test('ECL description moduleId / effectiveTime filters return 400 UNSUPPORTED_ECL instead of silent empty fallback', async () => { + const p = await factory.build(op, []); + for (const ecl of [ + '<< 404684003 {{ D moduleId = 900000000000207008 }}', + '<< 404684003 {{ D effectiveTime >= "20200101" }}', + '(< 404684003 : { [1..1] 363698007 = << 123037004 }) AND (<< 404684003 {{ D moduleId = 900000000000207008 }})', + ]) { + const prep = await p.getPrepContext(true); + const err = await p.filter(prep, true, 'constraint', '=', ecl).then(() => null, (e) => e); + expect(err).toBeTruthy(); + expect(err.statusCode).toBe(400); + expect(err.msgId).toBe('UNSUPPORTED_ECL'); + expect(err.asIssue()).toMatchObject({ severity: 'error', code: 'invalid' }); + } }); test('refset members keep effectiveTime, module and RF2 order; ECL member filters use them natively', async () => { diff --git a/tests/tx/sqlite-v2-stored-orders.test.js b/tests/tx/sqlite-v2-stored-orders.test.js new file mode 100644 index 00000000..dd193cf8 --- /dev/null +++ b/tests/tx/sqlite-v2-stored-orders.test.js @@ -0,0 +1,202 @@ +'use strict'; + +// The source orders a file stores (README.md "Order"): order.literals `stored` lists a concept's +// values of one property by literal.seq (the release's row order), not by value; order.expansion +// `stored` lists a literal filter's selection (a `where_literal` row, as OMOP's `domain`) in +// ix_order rank order, not by concept id; an include of the whole system walks the stored `walk` +// (also when compatibility.wholeSystemIncludeActiveOnly leaves the inactive concepts out). A file +// without those words keeps the defaults. The fixtures have the shapes of the NDC, OMOP and SNOMED CT +// importers' files, nothing in them real. + +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 { writeOrderArray } = require('../../tx/importers/sqlite-v2/indexes'); +const { loadSqliteV2Factory } = require('../../tx/sqlite-v2'); + +const PACKAGES = 'http://example.org/packages'; +const PLAIN = 'http://example.org/packages-plain'; +const VOCAB = 'http://example.org/vocabulary'; +const TREE = 'http://example.org/tree'; +const TREE_ALL = 'http://example.org/tree-all'; +let app, tx, dir; +const factories = []; + +// one product with four `upc` values, written in the release's row order (not value order), one repeated +const UPC = ['0300000000502', '0300000000106', '0300000000403', '0300000000205']; + +function buildPackages(file, uri, stored) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri, version: '20260101', name: 'Packages' }); + const upc = b.property({ code: 'upc', shape: 'literal', fhirType: 'string', lookupRank: 1 }); + const nui = b.property({ code: 'nui', shape: 'literal', fhirType: 'string', lookupRank: 2 }); + const c = b.concept('1111-222', { display: 'Product 1111-222' }); + b.item(c, { language: 'en', text: 'Product 1111-222', preferred: true }); + UPC.forEach((v, seq) => b.literal(c, upc, v, { seq })); + b.literal(c, upc, UPC[0], { group: 1, seq: 4 }); + b.literal(c, nui, 'N2', { seq: 0 }); + b.literal(c, nui, 'N1', { seq: 1 }); + b.reading({ meta: stored ? { order: { literals: ['property-id', 'stored', 'value'] } } : {} }); + b.finish(); +} + +// six standard concepts of two domains and one non-standard; the release's row order is not code order +const ROWS = [ + // code, domain, standard, row order + ['3003181', 'Measurement', 'S', 3], + ['3000483', 'Measurement', 'S', 1], + ['4043089', 'Measurement', 'S', 5], + ['3000001', 'Measurement', null, 2], + ['2000002', 'Condition', 'S', 4], + ['4000004', 'Measurement', 'S', 0], +]; + +function buildVocabulary(file) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: VOCAB, version: '20240101', name: 'Vocabulary' }); + const domain = b.property({ code: 'domain-id', shape: 'literal', fhirType: 'code' }); + const standard = b.property({ code: 'standard-concept', shape: 'literal', fhirType: 'code' }); + for (const [code, d, s] of ROWS) { + const c = b.concept(code, { display: `Concept ${code}` }); + b.item(c, { language: 'en', text: `Concept ${code}`, preferred: true }); + b.literal(c, domain, d); + if (s) b.literal(c, standard, s); + } + // the stored order (rank, ids): the release's row order, written by the importer + b.setMeta('derived-by-importer', [{ table: 'ix_order', name: 'rank' }, { table: 'ix_order', name: 'ids' }]); + b.deriveFacts((db, n) => { + const idOf = new Map(db.prepare('SELECT code, id FROM main.concept').raw().all()); + const byRow = ROWS.slice().sort((x, y) => x[3] - y[3]).map((r) => idOf.get(r[0])); + const rank = new Uint32Array(n + 1), ids = new Uint32Array(n + 1); + byRow.forEach((id, k) => { rank[id] = k; ids[k] = id; }); + db.exec('CREATE TABLE IF NOT EXISTS ix_order (name TEXT, block INTEGER, data BLOB, PRIMARY KEY (name, block)) WITHOUT ROWID'); + writeOrderArray(db, 'rank', rank); + writeOrderArray(db, 'ids', ids); + }); + b.reading({ + meta: { order: { expansion: ['stored'] } }, + filters: [{ code: 'domain', operators: ['='], reads: 'domain-id', whereLiteral: { 'standard-concept': 'S' }, valueCase: 'exact' }], + }); + b.finish(); +} + +// a hierarchy whose walk from the root is not code order: root R (code last of the active ones), its +// children B then A in release order, A's child C; X inactive (no is-a: the walk does not reach it) +const TREE_LINKS = [['B', 'R'], ['A', 'R'], ['C', 'A']]; + +function buildTree(file, uri, compatibility) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri, version: '1', name: 'Tree', hierarchyMeaning: 'is-a' }); + const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); + const c = {}; + for (const code of ['A', 'B', 'C', 'R', 'X']) { + c[code] = b.concept(code, { active: code !== 'X', display: `Concept ${code}` }); + b.item(c[code], { language: 'en', text: `Concept ${code}`, preferred: true }); + } + TREE_LINKS.forEach(([child, parent], seq) => b.link(c[child], isa, c[parent], { seq })); + // the stored orders, written by the importer: rank / ids by code; the walk from the root, depth + // first, children in release order, then the concepts it does not reach (reached: 4) + b.setMeta('derived-by-importer', [{ table: 'ix_order', name: 'rank' }, { table: 'ix_order', name: 'ids' }, { table: 'ix_order', name: 'walk' }]); + b.deriveFacts((db, n) => { + const idOf = new Map(db.prepare('SELECT code, id FROM main.concept').raw().all()); + const rank = new Uint32Array(n + 1), ids = new Uint32Array(n + 1); + ['A', 'B', 'C', 'R', 'X'].forEach((code, k) => { rank[idOf.get(code)] = k; ids[k] = idOf.get(code); }); + const walk = Uint32Array.from(['R', 'B', 'A', 'C', 'X'].map((code) => idOf.get(code))); + walk.reached = 4; + db.exec('CREATE TABLE IF NOT EXISTS ix_order (name TEXT, block INTEGER, data BLOB, PRIMARY KEY (name, block)) WITHOUT ROWID'); + writeOrderArray(db, 'rank', rank); + writeOrderArray(db, 'ids', ids); + writeOrderArray(db, 'walk', walk); + }); + b.reading({ meta: { order: { expansion: ['stored'] }, compatibility: { expansionNeverNests: true, ...compatibility } } }); + b.finish(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-stored-orders-')); + const files = [[PACKAGES, '20260101', 'packages.db'], [PLAIN, '20260101', 'plain.db'], [VOCAB, '20240101', 'vocab.db']]; + buildPackages(path.join(dir, 'packages.db'), PACKAGES, true); + buildPackages(path.join(dir, 'plain.db'), PLAIN, false); + buildVocabulary(path.join(dir, 'vocab.db')); + buildTree(path.join(dir, 'tree.db'), TREE, { wholeSystemIncludeActiveOnly: true }); + buildTree(path.join(dir, 'tree-all.db'), TREE_ALL, {}); + files.push([TREE, '1', 'tree.db'], [TREE_ALL, '1', 'tree-all.db']); + app = await getTestApp(); + tx = getTxModule(); + const p = tx.endpoints[0].provider; + for (const [uri, version, name] of files) { + const factory = await loadSqliteV2Factory(tx.i18n, path.join(dir, name)); + factories.push(factory); + p.codeSystemFactories.set(uri, factory); + p.codeSystemFactories.set(`${uri}|${version}`, factory); + } +}, 60000); + +afterAll(async () => { + for (const f of factories) f.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +async function post(op, parameter) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + return request(app).post(`/tx/r5/${op}`).send({ resourceType: 'Parameters', parameter }); +} + +async function lookupValues(system, code, property) { + const res = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: system }, { name: 'code', valueCode: code }, + { name: 'property', valueCode: '*' }]); + expect(res.status).toBe(200); + return res.body.parameter.filter((p) => p.name === 'property' && p.part[0].valueCode === property) + .map((p) => p.part[1].valueString ?? p.part[1].valueCode); +} + +async function expand(filter) { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: VOCAB, filter: [filter] }] } }; + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }]); + expect(res.status).toBe(200); + return (res.body.expansion.contains || []).map((c) => c.code); +} + +test('the builder writes literal.seq', () => { + const rows = factories[0].store.db.prepare(`SELECT value, group_id, seq FROM main.literal l JOIN main.property p ON p.id = l.property_id + WHERE p.code = 'upc' ORDER BY seq`).raw().all(); + expect(rows).toEqual([...UPC.map((v, seq) => [v, 0, seq]), [UPC[0], 1, 4]]); +}); + +test('order.literals stored: $lookup lists a property\'s values in literal.seq order, a repeated value again', async () => { + expect(await lookupValues(PACKAGES, '1111-222', 'upc')).toEqual([...UPC, UPC[0]]); + expect(await lookupValues(PACKAGES, '1111-222', 'nui')).toEqual(['N2', 'N1']); +}); + +test('without the word: by group, then value (the default), the same seq stored', async () => { + expect(await lookupValues(PLAIN, '1111-222', 'upc')).toEqual([...UPC.slice().sort(), UPC[0]]); + expect(await lookupValues(PLAIN, '1111-222', 'nui')).toEqual(['N1', 'N2']); +}); + +test('order.expansion stored: a where_literal filter lists its selection in ix_order rank order', async () => { + expect(await expand({ property: 'domain', op: '=', value: 'Measurement' })).toEqual(['4000004', '3000483', '3003181', '4043089']); + expect(await expand({ property: 'domain', op: '=', value: 'Condition' })).toEqual(['2000002']); +}); + +/** the codes of an $expand of the whole system, with count / offset when given */ +async function expandWhole(system, { count, offset } = {}) { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system }] } }; + const parameter = [{ name: 'valueSet', resource: vs }]; + if (count != null) parameter.push({ name: 'count', valueInteger: count }); + if (offset != null) parameter.push({ name: 'offset', valueInteger: offset }); + const res = await post('ValueSet/$expand', parameter); + expect(res.status).toBe(200); + return (res.body.expansion.contains || []).map((c) => c.code); +} + +test('order.expansion stored: an include of the whole system walks the stored walk, paged or not', async () => { + for (const system of [TREE_ALL, TREE]) { + expect(await expandWhole(system)).toEqual(['R', 'B', 'A', 'C']); + expect(await expandWhole(system, { count: 2, offset: 0 })).toEqual(['R', 'B']); + expect(await expandWhole(system, { count: 2, offset: 1 })).toEqual(['B', 'A']); + } +}); diff --git a/tests/tx/sqlite-v2-unii.test.js b/tests/tx/sqlite-v2-unii.test.js new file mode 100644 index 00000000..a239c23c --- /dev/null +++ b/tests/tx/sqlite-v2-unii.test.js @@ -0,0 +1,149 @@ +'use strict'; + +// UNII-shaped sqlite-v2 file (http://fdasis.nlm.nih.gov): flat case-sensitive code system with +// preferred display + multiple synonyms (UniiDesc), no filters, whole-system $expand (#487), +// $lookup, $validate-code (display & synonym matching, case sensitivity, unknownCodeMessage), and +// supplement displays. + +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 URI = 'http://fdasis.nlm.nih.gov'; +const VERSION = '2024-06-22'; +let app, tx, dir, factory, hadBefore, prevFactory; + +function build(file) { + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ + uri: URI, + version: VERSION, + name: 'UNII Codes', + description: 'UNII Codes', + caseSensitive: true, + defaultLanguage: 'en', + resource: { resourceType: 'CodeSystem', id: 'x-unii', url: URI, version: VERSION, status: 'active', content: 'complete' }, + }); + const rows = [ + ['0001H6R5H1', 'CERIUM, TRIS(2-(HYDROXY-.KAPPA.O)BENZOATO-.KAPPA.O)-', ['CEROUS SALICYLATE', 'CERIUM, TRIS(SALICYLATO)-']], + ['2T8Q726O95', 'SUCROSE', ['SUGAR', 'TABLE SUGAR']], + ['R16CO5Y76E', 'ASPIRIN', ['ACETYLSALICYLIC ACID', 'ASA']], + ['W0X9457M59', 'ACETAMINOPHEN', ['PARACETAMOL', 'APAP']], + ['3G6A5W338E', 'CAFFEINE', ['1,3,7-TRIMETHYLXANTHINE']], + ]; + for (const [code, display, others] of rows) { + const c = b.concept(code, { display }); + b.item(c, { language: 'en', text: display, preferred: true }); + for (const o of others) b.item(c, { language: 'en', text: o }); + } + b.reading({ + meta: { + version: { match: 'prefix' }, + compatibility: { unknownCodeMessage: "UNII Code '{code}' not found" }, + }, + filters: [], + }); + b.finish(); +} + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-unii-')); + const file = path.join(dir, 'unii.db'); + build(file); + app = await getTestApp(); + tx = getTxModule(); + factory = await loadSqliteV2Factory(tx.i18n, file); + const p = tx.endpoints[0].provider; + hadBefore = p.codeSystemFactories.has(URI); + prevFactory = p.codeSystemFactories.get(URI); + p.codeSystemFactories.set(URI, factory); + p.codeSystemFactories.set(`${URI}|${VERSION}`, factory); +}, 60000); + +afterAll(async () => { + const p = tx.endpoints[0].provider; + p.codeSystemFactories.delete(`${URI}|${VERSION}`); + if (hadBefore) p.codeSystemFactories.set(URI, prevFactory); + else p.codeSystemFactories.delete(URI); + factory.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +async function post(op, parameter) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + return request(app).post(`/tx/r5/${op}`).send({ resourceType: 'Parameters', parameter }); +} + +describe('sqlite-v2 UNII (#487)', () => { + test('whole-system $expand: count=0, paged, offset, includeDesignations, and full walk', async () => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: URI }] } }; + + const r0 = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }, { name: 'count', valueInteger: 0 }]); + expect(r0.status).toBe(200); + expect(r0.body.expansion.total).toBe(5); + expect(r0.body.expansion.contains).toBeUndefined(); + + const rPage = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }, { name: 'count', valueInteger: 2 }]); + expect(rPage.status).toBe(200); + expect(rPage.body.expansion.total).toBe(5); + expect(rPage.body.expansion.contains.length).toBe(2); + + const rOff = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }, { name: 'offset', valueInteger: 2 }, { name: 'count', valueInteger: 2 }]); + expect(rOff.status).toBe(200); + expect(rOff.body.expansion.total).toBe(5); + expect(rOff.body.expansion.contains.length).toBe(2); + + const rFull = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }, { name: 'includeDesignations', valueBoolean: true }]); + expect(rFull.status).toBe(200); + expect(rFull.body.expansion.total).toBe(5); + expect(new Set(rFull.body.expansion.contains.map((c) => c.code)).size).toBe(5); + const aspirin = rFull.body.expansion.contains.find((c) => c.code === 'R16CO5Y76E'); + expect(aspirin.display).toBe('ASPIRIN'); + expect((aspirin.designation || []).map((d) => d.value)).toEqual(expect.arrayContaining(['ACETYLSALICYLIC ACID', 'ASA'])); + }); + + test('$lookup returns display and synonyms; unknown code returns UNII unknownCodeMessage', async () => { + const r = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: 'R16CO5Y76E' }]); + expect(r.status).toBe(200); + expect(r.body.parameter.find((p) => p.name === 'display').valueString).toBe('ASPIRIN'); + const desigs = r.body.parameter.filter((p) => p.name === 'designation').map((p) => p.part.find((x) => x.name === 'value').valueString); + expect(desigs).toEqual(expect.arrayContaining(['ACETYLSALICYLIC ACID', 'ASA'])); + + const miss = await post('CodeSystem/$lookup', [{ name: 'system', valueUri: URI }, { name: 'code', valueCode: 'ZZZZZZZZZZ' }]); + expect(miss.status).toBe(404); + expect(JSON.stringify(miss.body)).toContain("UNII Code 'ZZZZZZZZZZ' not found"); + }); + + test('$validate-code: primary display, synonym display, wrong display, case sensitivity, version prefix, and unknown code', async () => { + const val = async (extra) => { + const res = await post('CodeSystem/$validate-code', [{ name: 'system', valueUri: URI }, ...extra]); + expect(res.status).toBe(200); + const p = (n) => res.body.parameter.find((x) => x.name === n); + return { result: p('result').valueBoolean, display: p('display')?.valueString, message: p('message')?.valueString }; + }; + + expect((await val([{ name: 'code', valueCode: 'R16CO5Y76E' }, { name: 'display', valueString: 'ASPIRIN' }])).result).toBe(true); + expect((await val([{ name: 'code', valueCode: 'R16CO5Y76E' }, { name: 'display', valueString: 'ACETYLSALICYLIC ACID' }])).result).toBe(true); + expect((await val([{ name: 'code', valueCode: 'R16CO5Y76E' }, { name: 'display', valueString: 'WRONG' }])).result).toBe(false); + // case sensitive + expect((await val([{ name: 'code', valueCode: 'r16co5y76e' }])).result).toBe(false); + // exact version match and mismatch + expect((await val([{ name: 'code', valueCode: 'R16CO5Y76E' }, { name: 'version', valueString: VERSION }])).result).toBe(true); + expect((await val([{ name: 'code', valueCode: 'R16CO5Y76E' }, { name: 'version', valueString: '2023-01-01' }])).result).toBe(false); + // unknown code + const miss = await val([{ name: 'code', valueCode: 'ZZZZZZZZZZ' }]); + expect(miss.result).toBe(false); + expect(miss.message).toContain("Unknown code 'ZZZZZZZZZZ'"); + }); + + test('unsupported filter on UNII returns 422 FILTER_NOT_UNDERSTOOD', async () => { + const vs = { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: URI, filter: [{ property: 'foo', op: '=', value: 'bar' }] }] } }; + const r = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs }]); + expect(r.status).toBe(422); + }); +}); diff --git a/tests/tx/sqlite-v2-version-check.test.js b/tests/tx/sqlite-v2-version-check.test.js new file mode 100644 index 00000000..27ecf4c7 --- /dev/null +++ b/tests/tx/sqlite-v2-version-check.test.js @@ -0,0 +1,78 @@ +'use strict'; + +// Version matching through a real request (check-system-version on $expand): meta version.match +// (exact by default, or prefix); a file without meta version matches exactly, whatever versionAlgorithm +// its stored CodeSystem resource declares (no other rule; no guess from the version string). + +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'); + +let app, tx, dir; +const factories = []; +const FILES = { + 'http://example.org/v-none': {}, + 'http://example.org/v-prefix': { version: { match: 'prefix' } }, + 'http://example.org/v-resource': { resource: { resourceType: 'CodeSystem', versionAlgorithmString: 'semver' } }, +}; + +beforeAll(async () => { + dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-ver-')); + app = await getTestApp(); + tx = getTxModule(); + let k = 0; + for (const [uri, o] of Object.entries(FILES)) { + const file = path.join(dir, `f${++k}.db`); + const b = new TerminologyBuilder(file, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri, version: '1.2.3', name: 'V', ...(o.resource ? { resource: o.resource } : {}) }); + b.concept('A', { display: 'a' }); + if (o.version) b.reading({ meta: { version: o.version } }); + b.finish(); + const f = await loadSqliteV2Factory(tx.i18n, file); + factories.push(f); + const p = tx.endpoints[0].provider; + p.codeSystemFactories.set(uri, f); + p.codeSystemFactories.set(uri + '|1.2.3', f); + } +}, 60000); + +afterAll(async () => { + for (const f of factories) f.store.close(); + await shutdownTestApp(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +async function status(uri, criteria) { + for (const e of tx.endpoints) e.expansionCache.clearAll(); + const res = await request(app).post('/tx/r5/ValueSet/$expand').send({ resourceType: 'Parameters', parameter: [ + { name: 'valueSet', resource: { resourceType: 'ValueSet', status: 'active', compose: { include: [{ system: uri }] } } }, + { name: 'check-system-version', valueCanonical: `${uri}|${criteria}` }] }); + return res.status; +} + +test('no versionAlgorithm in the file or its resource: only the exact version matches', async () => { + const u = 'http://example.org/v-none'; + expect(await status(u, '1.2.3')).toBe(200); + expect(await status(u, '1.2')).toBe(400); + expect(await status(u, '1.2.x')).toBe(400); +}); + +test('versionAlgorithm semver in the stored resource, no meta version: only the exact version matches', async () => { + const u = 'http://example.org/v-resource'; + expect(await status(u, '1.2.3')).toBe(200); + expect(await status(u, '1.2.x')).toBe(400); + expect(await status(u, '1.3.x')).toBe(400); +}); + +test('meta version.match prefix: a start of the version matches', async () => { + const u = 'http://example.org/v-prefix'; + expect(await status(u, '1.2.3')).toBe(200); + expect(await status(u, '1.2')).toBe(200); + expect(await status(u, '1.3')).toBe(400); +}); + +// (a file cannot state semver matching: meta version.match is exact or prefix, README.md "Versions") diff --git a/tests/tx/syndication-store.test.js b/tests/tx/syndication-store.test.js index f1af9a88..87be59d5 100644 --- a/tests/tx/syndication-store.test.js +++ b/tests/tx/syndication-store.test.js @@ -293,15 +293,52 @@ describe('binaries', () => { expect(store.entries).toHaveLength(0); }); - test('the full CPT database is never syndicated; the fragment is', async () => { + test('the full CPT database is never syndicated; the fragment is (classic, cpt-v2, and sqlite-v2)', async () => { const full = binary('CodeSystem-cpt.db', 'full'); const frag = binary('cpt-2023-fragment-0.1.db', 'frag'); - const fetch = fakeFetch({ [`${base}/CodeSystem-cpt.db`]: { length: 4 }, [`${base}/cpt-2023-fragment-0.1.db`]: { length: 4 } }); + const fullV2 = binary('cpt-2023.v2.db', 'fullv2'); + const fragV2 = binary('cpt-2023-fragment.v2.db', 'fragv2'); + const fullGen = binary('cpt-2023-gen.db', 'fullgen'); + const fetch = fakeFetch({ + [`${base}/CodeSystem-cpt.db`]: { length: 4 }, + [`${base}/cpt-2023-fragment-0.1.db`]: { length: 4 }, + [`${base}/cpt-2023.v2.db`]: { length: 6 }, + [`${base}/cpt-2023-fragment.v2.db`]: { length: 6 }, + [`${base}/cpt-2023-gen.db`]: { length: 7 } + }); const store = makeStore(fetch); await store.inductBinary({ sourceType: 'cpt', filePath: full, baseUrl: base, system: 'http://www.ama-assn.org/go/cpt', version: '2023' }); await store.inductBinary({ sourceType: 'cpt', filePath: frag, baseUrl: base, system: 'http://www.ama-assn.org/go/cpt', version: '2023' }); - expect(store.entries.map(e => e.link.href)).toEqual([`${base}/cpt-2023-fragment-0.1.db`]); + await store.inductBinary({ sourceType: 'cpt-v2', filePath: fullV2, baseUrl: base, system: 'http://www.ama-assn.org/go/cpt', version: '2023' }); + await store.inductBinary({ sourceType: 'cpt-v2', filePath: fragV2, baseUrl: base, system: 'http://www.ama-assn.org/go/cpt', version: '2023' }); + await store.inductBinary({ sourceType: 'sqlite-v2', filePath: fullGen, baseUrl: base, system: 'http://www.ama-assn.org/go/cpt', version: '2023' }); + expect(store.entries.map(e => e.link.href)).toEqual([ + `${base}/cpt-2023-fragment-0.1.db`, + `${base}/cpt-2023-fragment.v2.db` + ]); expect(fetch.calls.map(c => c.url)).not.toContain(`${base}/CodeSystem-cpt.db`); + expect(fetch.calls.map(c => c.url)).not.toContain(`${base}/cpt-2023.v2.db`); + expect(fetch.calls.map(c => c.url)).not.toContain(`${base}/cpt-2023-gen.db`); + }); + + test('ndc-v2, unii-v2, and generic sqlite-v2 files syndicate as TX_TERMINOLOGY_DB', async () => { + const ndc = binary('ndc-20261117.v2.db', 'ndcv2'); + const unii = binary('unii-2024-06-22.v2.db', 'uniiv2'); + const sct = binary('sct-generic.v2.db', 'sctv2'); + const store = makeStore(fakeFetch({ + [`${base}/ndc-20261117.v2.db`]: { length: 5 }, + [`${base}/unii-2024-06-22.v2.db`]: { length: 6 }, + [`${base}/sct-generic.v2.db`]: { length: 5 } + })); + await store.inductBinary({ sourceType: 'ndc-v2', filePath: ndc, baseUrl: base, system: 'http://hl7.org/fhir/sid/ndc', version: '20261117', name: 'NDC' }); + await store.inductBinary({ sourceType: 'unii-v2', filePath: unii, baseUrl: base, system: 'http://fdasis.nlm.nih.gov', version: '2024-06-22', name: 'UNII' }); + await store.inductBinary({ sourceType: 'sqlite-v2', filePath: sct, baseUrl: base, system: 'http://snomed.info/sct', version: 'http://snomed.info/sct/900000000000207008/version/20250201', name: 'SCT' }); + expect(store.entries.map(e => [e.category.term, e.identifier])).toEqual([ + ['TX_TERMINOLOGY_DB', 'http://hl7.org/fhir/sid/ndc'], + ['TX_TERMINOLOGY_DB', 'http://fdasis.nlm.nih.gov'], + ['TX_TERMINOLOGY_DB', 'http://snomed.info/sct/900000000000207008'] + ]); + expect(store.entries[2].rights).toMatch(/SNOMED CT/); }); test('a rebuilt binary (new file name) is a new entry; the old one stays', async () => { diff --git a/tx/README.md b/tx/README.md index 83a05443..b9c13a52 100644 --- a/tx/README.md +++ b/tx/README.md @@ -361,7 +361,7 @@ from the IG). One store serves all the endpoints. |--------|-------|------|----------| | `npm:` / `url:` packages, and each endpoint's core package | the package | `https://npm.fhir.org/web/{id}-{version}.tgz` (a `url:` source: its url) | `FHIR_Package` | | `file:` / `folder:` | each resource that has a version | a copy in the store | `FHIR_CodeSystem` / `FHIR_ValueSet` / `FHIR_ConceptMap` | -| `snomed`, `loinc`, `ndc`, `unii`, `omop`, `icd11`, `cpt` (fragment only), and the sqlite-v2 files (`snomed-v2`, `loinc-v2`, `rxnorm-v2`) | the file | `base.url` + file name | `SNOMED_CACHE`, `LOINC_DB` ... (`TX_TERMINOLOGY_DB` for a sqlite-v2 file) in `http://healthintersections.com.au/syndication/fhirsmith/1.0.0` | +| `snomed`, `loinc`, `ndc`, `unii`, `omop`, `icd11`, `cpt` (fragment only), and the sqlite-v2 files (`sqlite-v2`, `snomed-v2`, `loinc-v2`, `rxnorm-v2`, `ndc-v2`, `unii-v2`, `cpt-v2` (fragment only)) | the file | `base.url` + file name | `SNOMED_CACHE`, `LOINC_DB` ... (`TX_TERMINOLOGY_DB` for a sqlite-v2 file) in `http://healthintersections.com.au/syndication/fhirsmith/1.0.0` | Not syndicated: `internal:` sources (including VSAC), OCL, `#current`/build packages, resources without a version, the full CPT database, and binaries that are not published at `base.url` @@ -648,12 +648,15 @@ How the cache files are loaded is a deployment choice, so it is set in `config.j tx module's `snomed` block), not here - see [Loading SNOMED CT](#loading-snomed-ct). -#### `snomed-v2`, `loinc-v2`, `rxnorm-v2` - SNOMED CT, LOINC and RxNorm from sqlite-v2 files +#### `sqlite-v2`, `snomed-v2`, `loinc-v2`, `rxnorm-v2`, `ndc-v2`, `unii-v2`, `cpt-v2` - code systems from sqlite-v2 files -Serve one release of SNOMED CT or LOINC from a sqlite-v2 terminology file instead of the `snomed` -or `loinc` file of the same release; each line is chosen on its own, and `!` works as on the other -types. RxNorm is only served this way: there is no `rxnorm` type any more (its provider and -importer were removed once `rxnorm-v2` was live). The format, the importers that build the files +Serve one release of a code system from a sqlite-v2 terminology file: `sqlite-v2:` takes a file +of any code system (SNOMED CT, LOINC, RxNorm, UNII, NDC, OMOP, CPT, ICD-11: the file names its +system); `snomed-v2:`, `loinc-v2:`, `rxnorm-v2:`, `ndc-v2:`, `unii-v2:` and `cpt-v2:` also check +that the file holds that system, and serve it instead of the classic file of the same release. +RxNorm is only served this way: there is no `rxnorm` type any more (its provider and importer were +removed once `rxnorm-v2` was live). Each line is chosen on its own, and `!` works as on the other +types. The format, the importers that build the files (from the release, or from the `.cache` / `.db` a server already has) and the known differences from the built-in providers are in [sqlite-v2/README.md](sqlite-v2/README.md). @@ -661,6 +664,10 @@ from the built-in providers are in [sqlite-v2/README.md](sqlite-v2/README.md). - loinc-v2!:loinc-2.83.db - snomed-v2!:sct-intl-20260701.db - rxnorm-v2:rxnorm-03022026.db +- ndc-v2:ndc-20261117.db +- unii-v2:unii-2024-06-22.db +- cpt-v2:cpt-2023-fragment.db +- sqlite-v2:omop-20240716.db ``` #### `cpt` - CPT (Current Procedural Terminology) diff --git a/tx/importers/import-loinc-v2-classic.module.js b/tx/importers/import-loinc-v2-classic.module.js index 996c00af..d8ffb19e 100644 --- a/tx/importers/import-loinc-v2-classic.module.js +++ b/tx/importers/import-loinc-v2-classic.module.js @@ -35,7 +35,7 @@ const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqli const Database = require('../../library/sql/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'); +const { loincCatalog, loincCodeSystem, loincWalk, writeOrders, hierarchyCheck, KIND, LOINC, loincItemRank } = 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' }; @@ -194,7 +194,7 @@ async function importLoincV2FromClassic(cfg) { 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' }); + preferred: use === 'LONG_COMMON_NAME' && language === 'en-US', rank: loincItemRank(use, language) }); n++; } return n; diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index a0a15ede..8e74cc35 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -20,8 +20,10 @@ // 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) +// `Answer|answers-for` (a union, internal), `AnswerList` (inverse_of that union), +// `ancestor` (the closure source), the relationship types without rows, `copyright`; +// the FHIR reading (LOINC_READING) adds RELATEDNAMES2 (item-use) and one mapping row +// per implicit map key, and states the filter rows and meta keys // 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). @@ -150,37 +152,163 @@ const CLASSTYPE = { 1: 'Laboratory class', 2: 'Clinical class', 3: 'Claims attac * 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. + * Answer and answers-for, which no filter reads); `ancestor`, the PATH_TO_ROOT pairs the + * hierarchy's descendants come from (closure_from); the relationship types without rows; the + * `copyright` literal; the CLASSTYPE value labels; and the FHIR reading (LOINC_READING). */ function loincCatalog(b) { - const link = (code, extra = {}) => b.property({ code, uri: `${PROP}/${code}`, shape: 'link', display: code, ...extra }); + // every link: reported with the target's display as its description + const link = (code, extra = {}) => b.property({ code, uri: `${PROP}/${code}`, shape: 'link', display: code, + presentation: code === 'CLASS' ? { value: 'display', parts: ['partCode'] } : { parts: ['description'] }, ...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 }); + // STATUS is the concept's status (role 'status') + const lit = Object.fromEntries(LITERALS.map(([c]) => [c, b.property({ code: c, uri: `${PROP}/${c}`, shape: 'literal', fhirType: 'string', display: c, + presentation: c === 'CLASSTYPE' ? { value: 'string', parts: ['description'] } : { value: 'string' }, + ...(c === 'STATUS' ? { role: 'status' } : {}) })])); + // Answer is also asked for as answer-list + const answer = link('Answer', { ordered: true, alsoAskedAs: ['answer-list'] }); 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.property({ code: 'child', uri: `${PROP}/child`, shape: 'link', display: 'child', inverseOf: parent, presentation: { parts: ['description'] } }); + const listLinks = b.property({ code: 'Answer|answers-for', shape: 'union', display: 'Answer and answers-for' }); b.propertyMember(listLinks, answer); b.propertyMember(listLinks, answersFor); - b.property({ code: 'AnswerList', uri: `${PROP}/AnswerList`, shape: 'link', display: 'AnswerList', inverseOf: listLinks }); + b.property({ code: 'AnswerList', uri: `${PROP}/AnswerList`, shape: 'link', display: 'AnswerList', inverseOf: listLinks, presentation: { parts: ['description'] } }); const ancestor = b.property({ code: 'ancestor', uri: `${PROP}/ancestor`, shape: 'link', display: 'ancestor (PATH_TO_ROOT)' }); b.setClosureFrom(parent, ancestor); + // the relationship types cs-loinc.js knows that the release has no rows of: they select nothing + for (const code of LOINC_UNUSED_RELATIONSHIPS) link(code); + // copyright: LOINC's own, or 3rdParty for a code with an external copyright notice + const copyright = b.property({ code: 'copyright', uri: `${PROP}/copyright`, shape: 'literal', fhirType: 'code', display: 'copyright' }); + b.deriveFacts((db) => db.prepare(`INSERT INTO literal (subject_id, property_id, group_id, value, active) SELECT c.id, ?, 0, + CASE WHEN EXISTS (SELECT 1 FROM literal l WHERE l.subject_id = c.id AND l.property_id = ?) THEN '3rdParty' ELSE 'LOINC' END, 1 + FROM concept c`).run(copyright, lit.Copyright).changes); + b.reading(LOINC_READING); for (const [v, d] of Object.entries(CLASSTYPE)) b.valueLabel(lit.CLASSTYPE, String(v), d); return { link, parent, partProp, lit, answer, answersFor, ancestor }; } +/** + * A designation's item.rank: its place in cs-loinc.js's designation order (by use, then en-US + * first; ties in item order). A part's PartName rows (the linguistic variants' part files) come + * after its DisplayName (Part.csv), as main's Descriptions rows do (import order) + */ +const LOINC_DESIGNATION_ORDER = ['LONG_COMMON_NAME', 'SHORTNAME', 'ConsumerName', 'RELATEDNAMES2', 'DisplayName', 'LinguisticVariantDisplayName', 'PartName']; +function loincItemRank(useCode, language) { + const i = useCode ? LOINC_DESIGNATION_ORDER.indexOf(useCode) : -1; + return (i < 0 ? 99 : i) * 2 + (language === 'en-US' ? 0 : 1); +} + +/** relationship types cs-loinc.js knows that the release has no rows of (catalog rows that select nothing) */ +const LOINC_UNUSED_RELATIONSHIPS = ['N/A', 'adjustment', 'challenge', 'count', 'analyte-divisor', 'analyte-gene', 'analyte-suffix', + 'super-system', 'time-modifier']; + +/** LOINC's implicit concept maps (cs-loinc.js): [target system, key]; http://loinc.org/cm/ */ +const LOINC_MAPS = [ + ['http://loinc.org', 'loinc'], ['http://pubchem.ncbi.nlm.nih.gov', 'ncbi'], ['http://snomed.info/sct', 'sct'], + ['http://www.cms.gov/Medicare/Coding/HCPCSReleaseCodeSets', 'hcpcs'], ['http://www.genenames.org', 'gene-names'], + ['http://www.nlm.nih.gov/research/umls/rxnorm', 'rxnorm'], ['https://www.ebi.ac.uk/chebi', 'chebi'], + ['https://www.ncbi.nlm.nih.gov/clinvar', 'ncbi-clinvar'], ['https://www.ncbi.nlm.nih.gov/gene', 'ncbi-gene'], + ['https://www.ncbi.nlm.nih.gov/taxonomy', 'ncbi-taxo'], ['urn:iso:std:iso:11073:10101', 'mdc'], ['urn:oid:2.16.840.1.113883.6.238', 'race'], +]; + +/** the Loinc.csv literals other than STATUS ($lookup lists them after the links) */ +const LOINC_REPORTED_LITERALS = LITERALS.map(([c]) => c).filter((c) => c !== 'STATUS'); +const LOINC_STATUS_VALUES = ['NotStated', 'ACTIVE', 'DEPRECATED', 'TRIAL', 'DISCOURAGED', 'EXAMPLE', 'PREFERRED', 'Primary', 'DocumentOntology', + 'Radiology', 'NORMATIVE']; +const LOINC_FILTER_OPS = ['=', 'in', 'regex', 'exists']; + +/** + * LOINC's FHIR reading (tx/sqlite-v2/README.md; as cs-loinc.js presents LOINC): STATUS + * DISCOURAGED inactive, DEPRECATED deprecated; the stored order (the upstream importer's key + * order and walk); $lookup's properties by rank (the axes, the other links, answers-for, parent + * and child, the literals, STATUS, RELATEDNAMES2, the mappings); RELATEDNAMES2 items reported as a + * property, not designations; the display in another language from the display uses; one filter + * per link and literal (a link's value may be its target's display), plus LOINC's own. + */ +const LOINC_READING = { + meta: { + conceptStatus: [{ property: 'STATUS', values: { DISCOURAGED: ['inactive'], DEPRECATED: ['inactive', 'deprecated'] } }], + order: { expansion: ['stored'], searchTies: ['display', 'stored'], links: ['stored', 'property-id', 'group', 'code'] }, + // text search reads the display (English) and every name but RELATEDNAMES2 + search: { names: { display: 'en', items: { designations: true, excludeUses: ['RELATEDNAMES2'] } } }, + version: { match: 'prefix' }, + // a code's page (org.hl7.fhir.core LoincLinker): codes, parts, answers and groups + codeLink: 'https://loinc.org/{code}/', + implicitValueSets: [ + // (the texts as cs-loinc.js gives them) + { url: 'http://loinc.org/vs', include: {}, name: 'LOINC Value Set - all LOINC codes', description: 'All LOINC codes' }, + { url: 'http://loinc.org/vs/{v}', v: '^LP', mustBeCode: true, include: { filter: [{ property: 'ancestor', op: '=', value: '{v}' }] }, + name: 'LOINCValueSetFor{v_}', description: 'LOINC value set for code {v}: {display}' }, + { url: 'http://loinc.org/vs/{v}', v: '^LL', mustBeCode: true, enumerate: { property: 'LIST', op: '=', value: '{v}' }, + name: 'LOINCAnswerList{v_}', description: 'LOINC Answer list for code {v}: {display}' }, + ], + implicitMaps: { base: 'http://loinc.org/cm/', maps: LOINC_MAPS }, + // cs-loinc.js: a DEPRECATED code is not inactive (only DISCOURAGED is); the display listed first + // and then every designation; $lookup's name the title; no expansion.property declarations; its + // message for a code a filter check cannot locate; STATUS = NotStated also selects codes with none + compatibility: { + statusReadingsIgnored: [{ property: 'STATUS', values: { DEPRECATED: ['inactive'] } }], + displayDesignation: 'always', lookupNameIsTitle: true, expansionDeclaresProperties: false, expansionNeverNests: true, + filterUnknownCodeMessage: 'Not a valid code: {code}', missingValueFiltersAs: { STATUS: 'NotStated' }, + }, + }, + rows: [ + { code: 'CLASS', lookupRank: 0 }, { code: 'COMPONENT', lookupRank: 10 }, { code: 'PROPERTY', lookupRank: 20 }, + { code: 'TIME_ASPCT', lookupRank: 30 }, { code: 'SYSTEM', lookupRank: 40 }, { code: 'SCALE_TYP', lookupRank: 50 }, + { code: 'METHOD_TYP', lookupRank: 60 }, + { code: 'answers-for', lookupRank: 85 }, + { codes: ['parent', 'child'], lookupRank: 90 }, + { code: 'ancestor', lookup: 'never', expansion: 'never' }, + { code: 'copyright', lookup: 'never', expansion: 'never' }, + { code: 'Answer|answers-for', internal: true }, + { code: 'STATUS', lookupRank: 110 }, + { codes: LOINC_REPORTED_LITERALS, lookupRank: 100 }, + { code: 'RELATEDNAMES2', lookupRank: 120 }, + { shape: 'mapping', lookupRank: 130 }, + // every other link row (Answer, AnswerList, document-*, rad-*, the types without rows) + { shape: 'link', lookupRank: 80 }, + ], + newProperties: [ + { code: 'RELATEDNAMES2', shape: 'item-use', fhirType: 'string' }, + // each map value with its version and equivalence (cs-loinc.js) + ...LOINC_MAPS.map(([, key]) => ({ code: key, shape: 'mapping', fhirType: 'Coding', presentation: { parts: ['equivalence', 'version'] } })), + ], + uses: [ + { code: 'LONG_COMMON_NAME', role: 'display', languageDisplayRank: 1 }, + { code: 'SHORTNAME', role: 'display', languageDisplayRank: 2 }, + { code: 'DisplayName', languageDisplayRank: 3 }, + { code: 'LinguisticVariantDisplayName', role: 'display' }, + { code: 'RELATEDNAMES2', asProperty: 'RELATEDNAMES2' }, + ], + mappingsByImplicitMaps: true, + filters: [ + // every link and literal (a link's value may be its target's code or display, cs-loinc.js + // matching relationships by Codes.Description; CLASSTYPE's value its label) + { each: { shapes: ['link', 'literal'] }, except: ['STATUS', 'copyright', 'ancestor', 'answers-for'], operators: LOINC_FILTER_OPS, + linksAsDisplay: true, labelsAsDisplay: true }, + // answers-for = / in: the terms of the list, and those of the lists the value is an answer of + { code: 'answers-for', operators: ['=', 'in'], reads: ['concept', 'answers-for'], thenLink: 'Answer' }, + { code: 'answers-for', operators: ['regex', 'exists'], reads: 'answers-for', valueAsDisplay: true }, + { code: 'STATUS', operators: ['='], reads: 'STATUS', allowedValues: LOINC_STATUS_VALUES }, + { code: 'copyright', operators: ['='], reads: 'copyright', allowedValues: ['LOINC', '3rdParty'] }, + { code: 'ancestor', operators: ['=', 'in'], reads: 'ancestor' }, + { code: 'concept', operators: ['is-a', 'descendent-of', '=', 'in'], reads: 'concept' }, + { code: 'code', operators: ['is-a', 'descendent-of', '='], reads: 'concept' }, + { code: 'LIST', operators: ['='], reads: 'concept', thenLink: 'Answer', allowedValues: 'codes' }, + { code: 'answer-list', operators: ['='], reads: 'Answer', valueAsDisplay: true }, + ], +}; + +/** the catalog id of a LOINC version, as cs-loinc.js forms it */ +const loincCatalogId = (version) => `loinc${version}`; + /** 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'); + description, caseSensitive: true, hierarchyMeaning: 'is-a', defaultLanguage: 'en-US', + // the catalog id, as cs-loinc.js forms it (CodeSystem/x-loinc) + resource: { resourceType: 'CodeSystem', id: 'x-' + loincCatalogId(version) } }); } /** @param {object} cfg { source, dest, version, overwrite, log, hierarchyArrays: 'auto' | 'always' | 'never' } */ @@ -197,7 +325,7 @@ async function importLoincV2(cfg) { 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 }); + term && b.item(i, { language, use: use(code), text: term.trim(), active: true, preferred, rank: loincItemRank(code, language) }); const stats = { classLinksMissing: 0, partLinksSkipped: 0, hierarchyNodes: 0, ancestorPairs: 0 }; // upstream's code key order and walk, by concept handle @@ -534,4 +662,4 @@ class LoincV2Module extends BaseTerminologyModule { } module.exports = { LoincV2Module, importLoincV2, loincCatalog, loincCodeSystem, loincWalk, writeOrders, hierarchyCheck, files, status, - KIND, LOINC, ORDER_TYPE, ORDER_STAGE, ORDER, LITERALS, PART_LINK }; + KIND, LOINC, ORDER_TYPE, ORDER_STAGE, ORDER, LITERALS, PART_LINK, loincCatalogId, loincItemRank, LOINC_READING }; diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 88cdcf8b..47c9b7d7 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -4,17 +4,21 @@ // 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.active is derived from the status literal: meta conceptStatus) // 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. +// Archived concepts: their RXNATOMARCHIVE atoms, also active (an atom's own +// status is not reported; the concept's is). // 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). +// with an atom for it), SUPPRESS (each flag of its RXNORM atoms), STY (RXNSTY TUI), +// status (every concept: active, obsolete = inactive in RXNCONSO, archived = only in +// RXNATOMARCHIVE). // 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 +// at any level - those without concept-level RXNORM rows have no rows (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 @@ -24,8 +28,11 @@ // 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. +// internal); `AUI:` and `AUI:` are unions of the pairs; a REL or RELA +// RXNREL names with no atom-level rows has `AUI:` as an identifier row with +// no statements. Each relationship filter gets a second row, value prefix `AUI:`, +// that reads its `AUI:` by value. 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. @@ -34,7 +41,8 @@ const fs = require('fs'); const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options'); const path = require('path'); const { BaseTerminologyModule } = require('./tx-import-base'); -const { TerminologyBuilder } = require('./sqlite-v2/builder'); +const Database = require('../../library/sql/better-sqlite3'); +const { TerminologyBuilder, vacuumFile, analyze } = require('./sqlite-v2/builder'); const { lines } = require('./sqlite-v2/text'); const RXNORM = 'http://www.nlm.nih.gov/research/umls/rxnorm'; @@ -48,7 +56,57 @@ async function* rrf(file) { for await (const l of lines(file)) if (l) yield l.split('|'); } +/** cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships */ +const EQ_IN = ['=', 'in']; + +/** + * RxNorm's FHIR reading (tx/sqlite-v2/README.md; as cs-rxnorm.js presents RxNorm), for a build with + * or without the atom-level relationships: status obsolete + * inactive, archived inactive, deprecated and unlisted (answers never select an RXNATOMARCHIVE-only + * concept); by RXCUI as text (the stored order); text search over the atoms of the concepts with a + * non-SY atom, ties by code; versions MMDDYYYY described by the release date; each atom text once, + * no designation uses; $lookup TTY, STY, SAB, the relationships only when asked for; filters on + * TTY, STY, SAB (named in any case) and the relationships (values CUI:; with the atom-level + * relationships also AUI:, a second row of the same name told apart by its value prefix). + */ +const rxnormReading = (atomRelationships) => ({ + meta: { + conceptStatus: [{ property: 'status', values: { obsolete: ['inactive'], archived: ['inactive', 'deprecated', 'unlisted'] } }], + order: { expansion: ['stored'], searchTies: ['code'], links: ['property', 'code'] }, + search: { names: { items: { designations: true, language: 'en' } }, candidates: { hasLiteral: { property: 'TTY', except: ['SY'] } } }, + version: { match: 'prefix', describe: 'release-date' }, + // a concept's page (org.hl7.fhir.core DataRenderer.getLinkForCode): RxNav + codeLink: 'https://mor.nlm.nih.gov/RxNav/search?searchBy=RXCUI&searchTerm={code}', + compatibility: { displayDesignation: 'once', designationUse: 'none', expansionDeclaresProperties: false }, + }, + rows: [ + // the qualified (`@`) storage rows: union members only + { codeContains: '@', internal: true }, + // the atom-level rows (--atom-relationships): never reported; the AUI: filter rows read them + { codeContains: 'AUI:', internal: true }, + { code: 'TTY', lookupRank: 0 }, { code: 'STY', lookupRank: 1 }, { code: 'SAB', lookupRank: 2 }, + { shape: 'union', lookup: 'never', expansion: 'never' }, + { code: 'SUPPRESS', lookup: 'never', expansion: 'never' }, + { code: 'status', lookup: 'never', expansion: 'never' }, + // the relationships: only when asked for by name or * + { shape: 'link', lookup: 'named' }, + ], + filters: [ + { each: { codes: ['TTY', 'STY', 'SAB'] }, operators: EQ_IN, codeAnyCase: true }, + { each: { shapes: ['link', 'union'] }, operators: EQ_IN, valuePrefix: 'CUI:' }, + // REL / RELA = AUI:: the concepts owning the atoms RXAUI2 of the name's atom-level rows + // whose RXAUI1 is the value + ...(atomRelationships ? [{ each: { shapes: ['link', 'union'] }, operators: EQ_IN, valuePrefix: 'AUI:', reads: 'AUI:{code}' }] : []), + { code: 'concept', operators: EQ_IN, reads: 'concept' }, + { code: 'code', operators: EQ_IN, reads: 'concept' }, + ], +}); +const RXNORM_READING = rxnormReading(false); + /** @param {object} cfg { source (rrf dir), dest, version (MMDDYYYY), overwrite, log, atomRelationships } */ +/** the catalog id of an RxNorm version, as cs-rxnorm.js forms it */ +const rxnormCatalogId = (version) => `RxNorm-${version}`; + async function importRxNormV2(cfg) { const log = cfg.log || console.log; const f = (n) => path.join(cfg.source, n); @@ -59,21 +117,14 @@ async function importRxNormV2(cfg) { 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']; + caseSensitive: true, defaultLanguage: 'en-US', + // the catalog id, as cs-rxnorm.js forms it (CodeSystem/x-RxNorm-) + resource: { resourceType: 'CodeSystem', id: 'x-' + rxnormCatalogId(v) } }); + b.reading(rxnormReading(!!cfg.atomRelationships)); - 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 lit = (code, display) => b.property({ code, uri: `${RXNORM}/${code}`, shape: 'literal', fhirType: 'code', display }); + // SUPPRESS: source material, never reported and no filter (cs-rxnorm.js filters TTY, STY, SAB) + const TTY = lit('TTY', 'Term Type'), SAB = lit('SAB', 'Source'), SUPPRESS = lit('SUPPRESS', 'Suppress flag'), 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(); @@ -122,9 +173,10 @@ async function importRxNormV2(cfg) { // RXNATOMARCHIVE: RXAUI|AUI|STR|ARCHIVE_TIMESTAMP|CREATED_TIMESTAMP|UPDATED_TIMESTAMP|CODE|IS_BRAND|LAT| // LAST_RELEASED|SAUI|VSAB|RXCUI|SAB|TTY|MERGED_TO_RXCUI + // (the concepts after the first `live` are the archived ones) + const live = b.codes.length; 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'))) { @@ -137,7 +189,8 @@ async function importRxNormV2(cfg) { 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 }); + // (stored active: the concept is archived, its atoms are listed like any other) + b.item(i, { externalId: c[0], language: 'en-US', use: use(tty), text: str, active: true }); n++; } for (let i = live; i < b.codes.length; i++) if (b.display[i] === null) b.setDisplay(i, b.codes[i]); @@ -157,15 +210,16 @@ async function importRxNormV2(cfg) { }); // 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 }); + const relProp = (rel) => b.property({ code: rel, uri: `${RXNORM}/${rel}`, shape: 'link', display: rel, wildcard: false }); + const relaProp = (rela) => b.property({ code: rela, uri: `${RXNORM}/${rela}`, shape: 'link', display: rela, wildcard: true }); // 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 }); + // (storage for the REL's union: never reported under its own code) + p = b.property({ code: `@${rel}`, uri: `${RXNORM}/${rel}`, shape: 'link', display: `${rel} (no RELA)`, wildcard: false }); b.propertyMember(relProp(rel), p); noRelaOf.set(rel, p); } @@ -177,7 +231,7 @@ async function importRxNormV2(cfg) { 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 }); + u = b.property({ code: `AUI:${name}`, uri: `${RXNORM}/${name}`, shape: 'union', display: `${name}, atom-level rows` }); atomUnion.set(name, u); } return u; @@ -189,7 +243,7 @@ async function importRxNormV2(cfg) { 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 }); + display: `${rel} ${rela}, atom-level rows (RXAUI1 -> the concept of RXAUI2)` }); if (rel) b.propertyMember(atomUnionOf(rel), p); if (rela) b.propertyMember(atomUnionOf(rela), p); atomPair.set(code, p); @@ -242,7 +296,7 @@ async function importRxNormV2(cfg) { 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 }); + q = b.property({ code, uri: `${RXNORM}/${rela}`, shape: 'link', display: `${rela} (REL ${rel})`, wildcard: false }); qualified.set(code, q); } b.link(relRows[k], q, relRows[k + 1]); @@ -256,9 +310,21 @@ async function importRxNormV2(cfg) { // 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); + // with the atom-level rows, an AUI: value on any relationship is understood (cs-rxnorm.js): a + // name with no atom-level rows has an AUI: scheme with no statements (selects nothing) + if (atomCui) { + for (const name of [...names.rel, ...names.rela]) { + if (!atomUnion.has(name)) b.property({ code: `AUI:${name}`, uri: `${RXNORM}/${name}`, shape: 'identifier', bySubject: false, display: `${name}, atom-level rows (none)` }); + } + } return n; }); + // the status of every concept (role 'status', never reported; meta conceptStatus reads it): + // active, obsolete (inactive, still in RXNCONSO) or archived (RXNATOMARCHIVE only) + const STATUS = b.property({ code: 'status', uri: `${RXNORM}/status`, shape: 'literal', fhirType: 'code', display: 'Status', role: 'status' }); + for (let i = 0; i < b.codes.length; i++) b.literal(i, STATUS, i >= live ? 'archived' : b.active[i] ? 'active' : 'obsolete'); + await b.stage('ordering keys', async () => { const n = b.codes.length; const NONE = 1e6; @@ -281,7 +347,23 @@ async function importRxNormV2(cfg) { return n; }); - return b.finish(stats); + // the system order (ix_order rank and ids): by RXCUI as text (cs-rxnorm.js), written here + b.setMeta('derived-by-importer', [{ table: 'ix_order', name: 'rank' }, { table: 'ix_order', name: 'ids' }]); + const summary = b.finish(stats, { vacuum: false }); + const db = new Database(cfg.dest); + try { + const { computeOrder } = require('../sqlite-v2/orders'); + const { writeOrderArray } = require('./sqlite-v2/indexes'); + const n = db.prepare('SELECT concept_count FROM main.code_system WHERE served = 1').pluck().get(); + const order = computeOrder(db, 'rxnorm', n); + db.exec('BEGIN'); + writeOrderArray(db, 'rank', order.rank); + writeOrderArray(db, 'ids', order.ids); + db.exec('COMMIT'); + analyze(db, 'main.ix_order'); + } finally { db.close(); } + vacuumFile(cfg.dest); + return summary; } class RxNormV2Module extends BaseTerminologyModule { @@ -305,4 +387,4 @@ class RxNormV2Module extends BaseTerminologyModule { } } -module.exports = { RxNormV2Module, importRxNormV2 }; +module.exports = { RxNormV2Module, importRxNormV2, rxnormCatalogId, RXNORM_READING, rxnormReading }; diff --git a/tx/importers/readme.md b/tx/importers/readme.md index 717d7198..1c8ff464 100644 --- a/tx/importers/readme.md +++ b/tx/importers/readme.md @@ -530,7 +530,8 @@ Importer-specific options: `tx-import snomed-v2-from-cache inspect ` checks caches for those defects without importing - `rxnorm-v2`: `--atom-relationships` also stores RXNREL's atom-level rows, for `REL` / `RELA` = - `AUI:` filters (refused otherwise) + `AUI:` filters (a file built without it refuses them; see the format's "Per-system + content") Each importer keeps its working tables in `.stage` beside the destination (so the disk needs room for both). An existing destination is deleted when the import starts, so an import that diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index d0728736..180277d9 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -27,12 +27,12 @@ // 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 +// definitionStatusId / effectiveTime (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, semanticTag // code_system compositional = 1 (post-coordinated expressions are codes too, so an // expansion is never closed) -// behaviour grammar 'snomed', expansionOrder 'stored-self-first', lookupSkipsMixedLinks +// reading SNOMED_READING: grammar 'snomed', the stored order, the filter rows, ... // 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 @@ -49,6 +49,8 @@ const { firstLine, walk } = require('./sqlite-v2/text'); const SCT = 'http://snomed.info/sct'; const IS_A = '116680003'; const FSN = '900000000000003001'; +/** identifier schemes whose values are codes of another system: scheme -> the system */ +const SCHEME_SYSTEMS = { '30051010000102': 'http://loinc.org' }; const SYNONYM = '900000000000013009'; const DEFINITION = '900000000000550004'; const PREFERRED = '900000000000548007'; @@ -69,6 +71,69 @@ const DISPLAY_REFSETS = { '21000210109': ['271000210107', GB_ENGLISH, US_ENGLISH], // New Zealand '11000220105': ['21000220103', GB_ENGLISH, US_ENGLISH] // Irish }; +/** the eight operators cs-snomed.js takes on a concept filter */ +const CONCEPT_OPS = ['=', 'is-a', 'descendent-of', 'child-of', 'generalizes', 'in', 'is-not-a', 'descendent-leaf']; +const LITERAL_OPS = ['=', 'in', 'not-in', 'exists', 'regex']; + +/** + * SNOMED CT's FHIR reading (tx/sqlite-v2/README.md; as cs-snomed.js presents it): the snomed + * grammar (expressions, ECL, ?fhir_vs URLs); the stored order, an is-a selection's focus first; + * text search over the active designations with the shortlist, code hits first, ties as numbers; + * versions by edition URI with partial versions; generalizes without the focus; whole-system + * selections active only; no text definition in $lookup; $lookup ranks effectiveTime, parent, + * child, moduleId, sufficientlyDefined, semanticTag; the association reference sets as implicit + * concept maps; the filters cs-snomed.js understands (an attribute by its SCTID: the patterns). + */ +const SNOMED_READING = { + meta: { + order: { expansion: ['stored'], searchTies: ['code-number'], links: ['stored', 'property-id', 'group', 'code'], literals: ['property', 'value'] }, + search: { names: { items: { active: true, designations: true } }, candidates: { active: true }, codeMatch: 'number-prefix', codeHits: 'first', + nameScore: 'as-written', shortlist: 200, supplementsChooseLanguage: false }, + version: { match: 'prefix', partial: '/version/' }, + implicitValueSets: [{ grammar: 'fhir_vs' }], + grammar: 'snomed', + compatibility: { generalizesLeavesOutFocus: true, wholeSystemIncludeActiveOnly: true, isAListsFocusFirst: true, + lookupOmitsTextDefinitions: true, expansionDeclaresProperties: false, expansionNeverNests: true }, + }, + // (an entry for each association reference set the file has rows of) + associations: [ + { relation: '900000000000523009', equivalence: 'inexact', relationship: 'related-to' }, + { relation: '900000000000526001', equivalence: 'equivalent', relationship: 'equivalent' }, + { relation: '900000000000527005', equivalence: 'equal', relationship: 'equivalent' }, + { relation: '900000000000530003', equivalence: 'inexact', relationship: 'related-to' }, + ], + rows: [ + { code: 'effectiveTime', lookupRank: 0 }, + { code: IS_A, fhirCode: 'parent', lookupRank: 1 }, + { code: 'child', lookupRank: 2 }, + { code: 'moduleId', alsoAskedAs: ['module'], lookupRank: 3 }, + // the definition status as the boolean sufficientlyDefined (true for fully defined), only when asked for + { code: 'definitionStatusId', fhirCode: 'sufficientlyDefined', trueValue: '900000000000073002', lookup: 'named', lookupRank: 4 }, + { code: 'semanticTag', lookup: 'named', lookupRank: 5 }, + { valueSystem: 'http://loinc.org', fhirCode: 'loinc' }, + ], + uses: [ + { code: SYNONYM, role: 'synonym' }, + { code: FSN, role: 'fsn' }, + { code: DEFINITION }, + ], + filters: [ + { code: 'concept', operators: CONCEPT_OPS, reads: 'concept' }, + { code: 'code', operators: CONCEPT_OPS, reads: 'concept' }, + { code: 'inactive', operators: ['='], reads: 'inactive', allowedValues: ['true', 'false'] }, + { code: 'display', operators: ['regex'], reads: 'designations' }, + { code: 'moduleId', operators: ['=', 'of'], reads: 'moduleId' }, + { code: 'definitionStatusId', operators: LITERAL_OPS, reads: 'definitionStatusId' }, + { code: 'effectiveTime', operators: LITERAL_OPS, reads: 'effectiveTime' }, + { code: 'constraint', operators: ['='], reads: 'grammar' }, + { code: 'expressions', operators: ['='], reads: 'grammar' }, + { codePattern: '^([0-9]{6,18})$', operators: ['=', 'of'], reads: '{1}' }, + { codePattern: '^mapped:([0-9]{6,18})$', operators: ['exists'], reads: '{1}' }, + // VCL `of` and set-valued `in` over parent and child; no filter of these names (cs-snomed.js) + { code: 'parent', operators: ['of'], reads: IS_A }, + { code: 'child', operators: ['of'], reads: 'child' }, + ], +}; const displayRefsetsFor = (edition) => DISPLAY_REFSETS[edition] || [US_ENGLISH, GB_ENGLISH]; /** @@ -159,7 +224,48 @@ function concrete(raw) { } -const DERIVED = [{ table: 'ix_key', name: 'normalForm' }, { table: 'ix_order', name: 'walk' }]; +const DERIVED = [{ table: 'ix_key', name: 'normalForm' }, { table: 'ix_order', name: 'rank' }, { table: 'ix_order', name: 'ids' }, { table: 'ix_order', name: 'walk' }]; + +/** + * The semantic tag of each concept as a literal (property semanticTag, group 0, active): among the + * concept's active items with the FSN use, any language, in order of rank (unranked last) then item + * id, the first whose text ends with ')' and contains '(': the text between the last '(' and that + * final ')' + */ +function semanticTags(db, propertyId) { + const fsn = db.prepare('SELECT use_id FROM item_use WHERE code = ?').pluck().get(FSN); + if (fsn == null) return 0; + const ins = db.prepare('INSERT INTO literal (subject_id, property_id, group_id, value, active) VALUES (?, ?, 0, ?, 1)'); + const tags = []; + let last = null; + for (const [concept, text] of db.prepare(`SELECT concept_id, text FROM item WHERE use_id = ? AND active = 1 + ORDER BY concept_id, rank IS NULL, rank, id`).raw().iterate(fsn)) { + if (concept === last || !text.endsWith(')')) continue; + const open = text.lastIndexOf('('); + if (open < 0) continue; + tags.push([concept, text.substring(open + 1, text.length - 1)]); + last = concept; + } + for (const [concept, tag] of tags) ins.run(concept, propertyId, tag); + return tags.length; +} + +/** the catalog name of a SNOMED CT edition, as cs-snomed.js forms it */ +function sctCatalogName(version, edition) { + const { editionCode } = require('../sct/editions'); + return String(version || '').includes('xsct') ? 'SNOMED CT Test Set' : `SCT ${editionCode(edition) || 'Unknown Edition'}`; +} + +/** the catalog id of a SNOMED CT version URI, as cs-snomed.js forms it, or null without a dated version */ +function sctCatalogId(version) { + let prefix = ''; + let match = String(version || '').match(/^http:\/\/snomed\.info\/sct\/(\d+)(?:\/version\/(\d{8}))?$/); + if (!match) { + match = String(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; +} class SnomedSink { /** @@ -171,13 +277,15 @@ class SnomedSink { 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 }); + // the catalog id and name (code_system.resource id and name), as cs-snomed.js forms them: CodeSystem + // x-SCT-- (x-xSCT- for an xsct edition; none for an undated version), named + // SCT (SNOMED CT Test Set for an xsct edition) + const version = cfg.codeSystem && cfg.codeSystem.version; + const catalogId = sctCatalogId(version); + b.codeSystem({ caseSensitive: true, hierarchyMeaning: 'is-a', compositional: true, + resource: { resourceType: 'CodeSystem', ...(catalogId ? { id: 'x-' + catalogId } : {}), name: sctCatalogName(version, cfg.edition) }, ...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.reading(SNOMED_READING); 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, @@ -185,9 +293,13 @@ class SnomedSink { // 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 }); + // (how $lookup reports them: SNOMED_READING) + this.isA = b.property({ code: IS_A, uri: `${SCT}/${IS_A}`, shape: 'link', subsumption: true, refinable: true, wildcard: false, + presentation: { parts: ['description'] } }); + this.module = b.property({ code: 'moduleId', shape: 'link', display: 'Module', refinable: false, wildcard: false, + presentation: { parts: ['description'] } }); + this.defStatus = b.property({ code: 'definitionStatusId', shape: 'link', display: 'Definition status', refinable: false, wildcard: false, + presentation: { parts: ['description', 'code-display'] } }); 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] @@ -266,7 +378,7 @@ class SnomedSink { setConcreteTypes(map) { this.concreteTypes = map; } _attr(type) { - return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: 'link', refinable: true, wildcard: true }); + return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: 'link', refinable: true, wildcard: true, presentation: { parts: ['description', 'code-display'] } }); } /** a relationship row (inferred); s, t: concept handles */ @@ -283,7 +395,9 @@ class SnomedSink { 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 attribute with relationship rows and concrete values: shape both + return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: both ? 'both' : 'literal', fhirType, refinable: true, wildcard: true, + presentation: { parts: ['code-display'] } }); } /** an active inferred concrete value row; s: concept handle; raw: the RF2 value (#n, "s", true) */ @@ -303,8 +417,9 @@ class SnomedSink { } 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 }); + // (no filter of this name, cs-snomed.js takes none: its filter row offers VCL `of` only) + this.b.property({ code: 'child', shape: 'link', display: 'Child', inverseOf: this.isA, refinable: false, wildcard: false, + presentation: { parts: ['description'] } }); // language refset rows, now that the descriptions are items const L = this.lang; for (let k = 0; k < L.key.length; k++) { @@ -333,7 +448,10 @@ class SnomedSink { 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 }); + // the LOINC scheme's values are LOINC codes (reported as the property loinc: SNOMED_READING) + const valueOf = SCHEME_SYSTEMS[schemeCode]; + p = this.b.property({ code: schemeCode, uri: `${SCT}/${schemeCode}`, shape: 'identifier', concept: scheme, refinable: false, wildcard: false, + ...(valueOf ? { valueSystem: valueOf } : {}) }); this.schemes.set(schemeCode, p); } this.b.identifier(p, value, c); @@ -406,6 +524,9 @@ class SnomedSink { // 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); + // semanticTag (the last catalog row): stored, one value per concept that has one (semanticTags below) + const tagProp = b.property({ code: 'semanticTag', shape: 'literal', fhirType: 'string', refinable: false, wildcard: false }); + b.deriveFacts((db) => semanticTags(db, tagProp)); 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); @@ -435,9 +556,13 @@ function derivedIndexes(file, log = () => {}, normalForms = true) { 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; + // the system order: by concept id as a number (cs-snomed.js), and the walk + const order = computeOrder(db, 'snomed', n); + const walk = order.walk; db.exec('BEGIN'); - db.prepare("DELETE FROM main.ix_order WHERE name = 'walk'").run(); + db.prepare("DELETE FROM main.ix_order WHERE name IN ('rank', 'ids', 'walk')").run(); + writeOrderArray(db, 'rank', order.rank); + writeOrderArray(db, 'ids', order.ids); out.walk = { rows: writeOrderArray(db, 'walk', walk), reached: walk.reached, seconds: (Date.now() - t) / 1000 }; out.activeOrderRows = writeActiveOrder(db); db.exec('COMMIT'); @@ -463,4 +588,4 @@ function derivedIndexes(file, log = () => {}, normalForms = true) { } 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 }; + DISPLAY_REFSETS, EDITION_NAMES, EDITION_LANGUAGES, MODULE_DEPENDENCY, SCT, IS_A, PREFERRED, US_ENGLISH, INFERRED, sctCatalogId, sctCatalogName }; diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index dc37e2c8..e0199d4d 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -5,17 +5,25 @@ // 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(): +// provisional handles in a scratch SQLite file. The FHIR reading of the system (tx/sqlite-v2/README.md: +// the reading columns of the catalog, item_use roles, the filter rows, meta conceptStatus, order, +// search, version, ...) is data the importer declares with reading(); the builder writes it. finish(): +// 0. writes the reading's meta keys, adds its new catalog rows (item-use, mapping), and derives +// concept.active from meta conceptStatus when some value there means inactive (README.md +// "Concept status": active = 0 exactly for the concepts whose readings contain inactive); // 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; +// 3. fills the catalog's computed fields (subject_kind; 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; the reading's rules for the catalog's +// reading columns, its item_use rows and its filter rows; // 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). +// 5. writes meta (format, provenance), ANALYZE (sqlite_stat1 only: analyze()), finishes the file +// (finishFile: checks every meta key against the list this builder knows) and VACUUMs (unless +// the importer still writes derived-by-importer rows: then it calls vacuumFile() after them, +// which finishes the file). // // Handles: a concept is its 0-based arrival index (>= 0); an item is -(its staging row id) (< 0). @@ -25,6 +33,8 @@ const crypto = require('crypto'); const Database = require('../../../library/sql/better-sqlite3'); const { numberConcepts } = require('../sqlite-v2/numbering'); const { buildIndexes } = require('./indexes'); +const { readMeta, WRITTEN_FEATURES, FILTER_ROW_OPERATORS } = require('../../sqlite-v2/meta'); +const { computeIntegrity, integrityValue } = require('../../sqlite-v2/integrity'); const SCHEMA_PATH = path.join(__dirname, 'schema.sql'); const FORMAT = 'tx-terminology/1'; @@ -32,8 +42,28 @@ const FORMAT = 'tx-terminology/1'; // 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']); +const SHAPES = new Set(['link', 'literal', 'both', 'identifier', 'record', 'union', 'item-use', 'mapping', 'reading']); +/** the shapes without rows of their own (README.md "property"): rows a reading adds */ +const READING_SHAPES = new Set(['item-use', 'mapping', 'reading']); +const ROLES = new Set(['language', 'status']); +const USE_ROLES = new Set(['fsn', 'synonym', 'display']); +const LOOKUP = new Set(['default', 'named', 'never']); +const EXPANSION = new Set(['asked', 'always', 'never']); +const READING_CODES = new Set(['inactive', 'deprecated', 'notSelectable']); +/** property spec keys of an earlier revision: refused, so an importer that still states one is caught */ +const REMOVED_SPEC = ['filterable', 'filterOps', 'report', 'reportedAs', 'namedLinks', 'nameAnyCase', 'valueAnyCase', + 'defaultValue', 'matchDisplay', 'selectsMembers']; +/** the reading columns a property spec (or a rule of reading().rows) may set: spec key -> column */ +const READING_COLUMNS = { + fhirCode: 'fhir_code', alsoAskedAs: 'also_asked_as', lookup: 'lookup', expansion: 'expansion', lookupRank: 'lookup_rank', + expansionRank: 'expansion_rank', trueValue: 'true_value', internal: 'internal', aliasParameter: 'alias_parameter', + aliasExtension: 'alias_extension', aliasLiterals: 'alias_literals', +}; +/** property columns of an earlier revision: a file of this revision has none of them */ +const REMOVED_COLUMNS = ['filterable', 'filter_ops', 'report', 'reported_as', 'named_links', 'name_any_case', 'value_any_case', + 'default_value', 'match_display', 'selects_members', 'n_rows', 'target_kind']; +/** what a filter row may read besides a property code (README.md "filter") */ +const FILTER_READS = new Set(['concept', 'inactive', 'display', 'designations', 'grammar', '{1}']); /** * 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 @@ -88,7 +118,7 @@ class TerminologyBuilder { 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_literal (subject INTEGER, prop INTEGER, grp INTEGER, value, active INTEGER, seq 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); @@ -98,7 +128,7 @@ class TerminologyBuilder { 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 (?,?,?,?,?)'), + 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 (?,?,?,?,?,?,?)'), @@ -140,9 +170,42 @@ class TerminologyBuilder { 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)); + /** + * The system's FHIR reading (tx/sqlite-v2/README.md), as data; one call, before finish(). + * { + * meta: {key: JSON value}: conceptStatus, expansionLimits, order, search, version, + * implicitValueSets, implicitMaps, grammar, compatibility; + * associations: [{relation, equivalence, relationship}]: implicitMaps.associations entries, kept + * for the relations the file has (a record relation of that code with rows); + * rows: [rule]: the reading columns of the catalog rows a rule selects ({code} | {codes} | {shape} + * | {shapes} | {codeContains} | {valueSystem}, then any of fhirCode, alsoAskedAs, lookup, + * expansion, lookupRank, expansionRank, trueValue, internal, aliasParameter, aliasExtension, + * aliasLiterals); the first rule that selects a row applies, over what property() gave it; + * newProperties: [{code, shape: 'item-use' | 'mapping' | 'reading', fhirType, presentation}]: catalog rows after + * the importer's (an item-use row only where a use of the file names it in uses); + * uses: [{code, role, asProperty, languageDisplayRank}]: item_use columns of the uses of that code; + * filters: [row | {each: selector, except, operators, reads, codeAnyCase, valuePrefix, linksAsDisplay, + * labelsAsDisplay}]: the filter rows in order; a row is {code | codePattern, operators, reads, + * codeAnyCase, description, allowedValues, valuePrefix, valueCase, valueAsDisplay, whereLiteral, + * thenLink}; `each` makes one row per catalog row the selector names (property id order; not + * internal, not record), named by that row and reading it, or (reads: a template with {code}, + * the row's code) the catalog row the template names (RxNorm `AUI:{code}`); + * mappingsByImplicitMaps: true: a mapping row without a property gets the mapping-shape row named + * by the key of the implicitMaps.maps entry of its system + * } + */ + reading(r) { + if (this._reading) throw new Error('reading() is called once'); + const known = ['meta', 'associations', 'rows', 'newProperties', 'uses', 'filters', 'mappingsByImplicitMaps']; + for (const k of Object.keys(r)) if (!known.includes(k)) throw new Error(`reading: unknown member ${k}`); + for (const rule of r.rows || []) checkReadingColumns(rule, `reading rule ${JSON.stringify(selectorOf(rule))}`); + for (const p of r.newProperties || []) { + if (!READING_SHAPES.has(p.shape)) throw new Error(`reading: new property ${p.code}: shape ${p.shape} (item-use, mapping or reading)`); + } + for (const u of r.uses || []) { + if (u.role != null && !USE_ROLES.has(u.role)) throw new Error(`reading: item use ${u.code}: bad role ${u.role}`); + } + this._reading = r; } /** a release fact without a column (displayContexts, moduleDependencies, ...): JSON for objects */ @@ -161,13 +224,15 @@ class TerminologyBuilder { /** * 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) } + * closureFrom, 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, 'language': a record relation on items that ranks displays, by meta + * displayContexts; 'status': the literal that holds the concept's status text), presentation, + * valueSystem; the reading columns (README.md "property"): fhirCode, alsoAskedAs, lookup, + * expansion, lookupRank, expansionRank, trueValue, internal, aliasParameter, aliasExtension, + * aliasLiterals (a rule of reading().rows that selects the row applies over these) } */ property(spec) { const cs = spec.cs || 1; @@ -177,25 +242,34 @@ class TerminologyBuilder { if (known.shape !== spec.shape) throw new Error(`property ${spec.code}: shape ${known.shape}, not ${spec.shape}`); return known.id; } + const old = REMOVED_SPEC.filter((k) => spec[k] !== undefined); + if (old.length) throw new Error(`property ${spec.code}: ${old.join(', ')} belong to an earlier revision (the filter rows and reading columns of reading() replace them)`); 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.role === 'status' && spec.shape !== 'literal') throw new Error(`property ${spec.code}: the status role is for a literal property`); 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}`); } + checkReadingColumns(spec, `property ${spec.code}`); + if (spec.shape !== 'identifier' && ['aliasParameter', 'aliasExtension', 'aliasLiterals'].some((k) => spec[k] != null)) { + throw new Error(`property ${spec.code}: alias columns are for identifier rows`); + } 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, + 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, + valueSystem: spec.valueSystem ?? null, + presentation: spec.presentation ? JSON.stringify(spec.presentation) : null, + reading: readingColumns(spec), // 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) : [], }; @@ -234,6 +308,14 @@ class TerminologyBuilder { setDisplay(i, display) { this.display[i] = display; } setSortKey(i, key) { this.sortKey[i] = key; } + /** + * fn(db, n): writes fact rows an importer derives from the final rows (final ids, item.rank), after + * the facts are rewritten and before the catalog and the indexes are computed from them + */ + deriveFacts(fn) { + (this.derivers || (this.derivers = [])).push(fn); + } + /** an item_use coding; returns its use_id */ use({ system = null, code, display = null }) { const k = `${system || ''}|${code}`; @@ -272,9 +354,10 @@ class TerminologyBuilder { this._tick(); } - literal(subject, property, value, { group = 0, active = true } = {}) { + /** seq: the value's source order among the subject's values of the property (order.literals stored) */ + literal(subject, property, value, { group = 0, active = true, seq = null } = {}) { if (value === null || value === undefined || value === '') return; - this.ins.literal.run(subject, property, group, this._typed(property, value), active ? 1 : 0); + this.ins.literal.run(subject, property, group, this._typed(property, value), active ? 1 : 0, seq); this._count('literals'); this._tick(); } @@ -394,6 +477,39 @@ class TerminologyBuilder { 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' }; } + /** + * concept.active from meta conceptStatus (README.md "Concept status"), when some value there + * means inactive: 0 exactly for the concepts whose status literals (active or not) have a value + * that means inactive, after compatibility.statusReadingsIgnored. Returns {inactive, changed} + * (changed: concepts whose importer flag differed), or null: concept.active is the importer's. + */ + _deriveActive() { + const cs = this.meta.has('conceptStatus') ? JSON.parse(this.meta.get('conceptStatus')) : []; + if (!cs.some((e) => Object.values(e.values || {}).some((m) => m.includes('inactive')))) return null; + const compat = this.meta.has('compatibility') ? JSON.parse(this.meta.get('compatibility')) : {}; + const ignored = new Map((compat.statusReadingsIgnored || []).map((e) => [e.property, e.values || {}])); + const n = this.codes.length; + const inactive = new Uint8Array(n); + const q = this.st.prepare(`SELECT DISTINCT subject FROM s_literal WHERE prop = ? AND subject >= 0 + AND CAST(value AS TEXT) IN (SELECT value FROM json_each(?))`).pluck(); + for (const e of cs) { + const ign = ignored.get(e.property) || {}; + const values = Object.entries(e.values).filter(([v, ms]) => ms.includes('inactive') && !(ign[v] || []).includes('inactive')).map(([v]) => v); + if (!values.length) continue; + const d = this.propertyByKey.get(`1|${e.property}`); + if (!d || d.shape !== 'literal') throw new Error(`meta conceptStatus names ${e.property}, which is no literal property`); + for (const sub of q.iterate(d.id, JSON.stringify(values))) inactive[sub] = 1; + } + let count = 0, changed = 0; + for (let i = 0; i < n; i++) { + const a = inactive[i] ? 0 : 1; + if (!a) count++; + if (this.active[i] !== a) { changed++; this.active[i] = a; } + } + if (changed) this.log(` concept status: ${changed.toLocaleString()} concepts take the active flag conceptStatus gives them`); + return { inactive: count, changed }; + } + /** * @param {object} [extra] importer stats, kept in meta 'provenance.importer' * @param {object} [opts] { vacuum: false when the importer writes derived-by-importer rows after @@ -405,6 +521,20 @@ class TerminologyBuilder { 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`); + const reading = this._reading || {}; + + // 0. the reading: its meta keys, its new catalog rows, concept.active from conceptStatus + for (const [k, v] of Object.entries(reading.meta || {})) this.meta.set(k, JSON.stringify(v)); + const useCodes = new Set([...this.uses.values()].map((u) => u.code)); + for (const np of reading.newProperties || []) { + // an item-use row only where a use of the file is reported as it + if (np.shape === 'item-use' && !(reading.uses || []).some((u) => u.asProperty === np.code && useCodes.has(u.code))) continue; + if (this.propertyByKey.has(`1|${np.code}`)) throw new Error(`reading: new property ${np.code} is already in the catalog`); + const id = this.property({ code: np.code, shape: np.shape, fhirType: np.fhirType ?? null, uri: np.uri, display: np.display, presentation: np.presentation }); + this.properties[id - 1].added = true; + } + const status = this._time('concept status', () => this._deriveActive()); + if (status) this.counts.statusDerived = status; // 1. numbering: concepts over the active subsumption links between concepts const hier = this.properties.filter((p) => p.subsumption).map((p) => p.id); @@ -445,8 +575,13 @@ class TerminologyBuilder { 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); + // item_use, with the reading's columns for the uses of each code + const insUse = db.prepare('INSERT INTO item_use (use_id, system, code, display, role, as_property, language_display_rank) VALUES (?,?,?,?,?,?,?)'); + const useReading = new Map((reading.uses || []).map((u) => [u.code, u])); + for (const u of this.uses.values()) { + const r = useReading.get(u.code) || {}; + insUse.run(u.id, u.system, u.code, u.display, r.role ?? null, r.asProperty ?? null, r.languageDisplayRank ?? null); + } const insConcept = db.prepare('INSERT INTO concept VALUES (?,?,?,?,?)'); this._time('rewrite concept', () => { @@ -460,25 +595,44 @@ class TerminologyBuilder { 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`); + // (a literal in several rows keeps its first seq, as a link does) + run('literal', `INSERT INTO literal (subject_id, property_id, group_id, value, active, seq) SELECT m.new, l.prop, l.grp, l.value, l.active, min(l.seq) FROM st.s_literal l + JOIN st.s_node m ON m.old = l.subject GROUP BY 1, 2, 3, 4, 5 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 + // a mapping row without a property: the mapping-shape row of its system's implicit map, where + // the reading says so + db.exec('CREATE TABLE st.s_map_system (system TEXT PRIMARY KEY, prop INTEGER NOT NULL)'); + if (reading.mappingsByImplicitMaps) { + const maps = ((reading.meta || {}).implicitMaps || {}).maps || []; + const insMap = db.prepare('INSERT OR IGNORE INTO st.s_map_system VALUES (?, ?)'); + for (const [system, key] of maps) { + const d = this.propertyByKey.get(`1|${key}`); + if (!d || d.shape !== 'mapping') throw new Error(`reading: implicitMaps key ${key} has no mapping-shape property`); + insMap.run(system, d.id); + } + } + run('mapping', `INSERT OR IGNORE INTO mapping SELECT m.new, coalesce(x.prop, (SELECT ms.prop FROM st.s_map_system ms WHERE ms.system = x.system)), + 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)); + // facts an importer derives from the final rows (deriveFacts), before the catalog counts them + for (const fn of this.derivers || []) this._time('derived facts', () => fn(db, n)); 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 insProp = db.prepare(`INSERT INTO property (id, cs_id, code, fhir_code, also_asked_as, uri, display, concept_id, shape, role, fhir_type, + subject_kind, subsumption, closure_from, refinable, wildcard, inverse_of, by_target, by_subject, ordered, lookup, expansion, lookup_rank, + expansion_rank, true_value, presentation, value_system, internal, alias_parameter, alias_extension, alias_literals, fields) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); const parents = new Set(this.members.map(([a]) => a)); + const written = []; 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 }; + // subject_kind NULL for a catalog row with no rows; 'concept' for a row the reading adds (its + // values are about concepts: items, mapping rows, the status reading) + const c = computed.get(p.id) || { subjectKind: p.added ? 'concept' : null, n: 0 }; // shape 'union': a link row whose only rows are its members' let shape = p.shape; if (parents.has(p.id)) { @@ -488,9 +642,30 @@ class TerminologyBuilder { } 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); + // the reading columns: the property's own, then the first rule of the reading that selects it + const rule = (reading.rows || []).find((r) => selects(r, { code: p.code, shape, valueSystem: p.valueSystem })); + const rc = { lookup: 'default', expansion: 'asked', internal: 0, ...p.reading, ...(rule ? readingColumns(rule) : {}) }; + // an internal row is storage only: never reported or declared + let uri = p.uri; + if (rc.internal) { rc.lookup = 'never'; rc.expansion = 'never'; uri = null; } + insProp.run(p.id, p.cs, p.code, rc.fhir_code ?? null, rc.also_asked_as ?? null, uri, p.display, nodeId(p.concept), shape, p.role, p.fhirType, + c.subjectKind, p.subsumption, p.closureFrom, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, rc.lookup, rc.expansion, + rc.lookup_rank ?? null, rc.expansion_rank ?? null, rc.true_value ?? null, p.presentation, p.valueSystem, rc.internal ? 1 : 0, + rc.alias_parameter ?? null, rc.alias_extension ?? null, rc.alias_literals ?? null, p.fields); + written.push({ id: p.id, code: p.code, shape, valueSystem: p.valueSystem, internal: !!rc.internal }); + } + // the filter rows (README.md "filter"), in the reading's order + this._time('filter rows', () => writeFilters(db, reading.filters || [], written)); + // implicitMaps.associations: the entries for the relations the file has rows of + if (reading.associations && reading.associations.length) { + const present = reading.associations.filter((a) => { + const d = this.propertyByKey.get(`1|${a.relation}`); + return d && d.shape === 'record' && !!db.prepare('SELECT 1 FROM main.record WHERE relation_id = ? LIMIT 1').get(d.id); + }); + if (present.length) { + const im = this.meta.has('implicitMaps') ? JSON.parse(this.meta.get('implicitMaps')) : {}; + this.meta.set('implicitMaps', JSON.stringify({ ...im, associations: present })); + } } const insMember = db.prepare('INSERT OR IGNORE INTO property_member VALUES (?, ?)'); for (const [a, b] of this.members) insMember.run(a, b); @@ -499,9 +674,11 @@ class TerminologyBuilder { 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); + // meta: format and provenance (release facts were set by the importer), checked here as this + // builder knows them (finishFile checks the whole table again) + // requires: identifier-text (identifier.value is declared TEXT: every value is stored as text) + this.meta.set('requires', JSON.stringify(WRITTEN_FEATURES)); + readMeta(this.meta, this.dest, { writer: true }); 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); @@ -521,7 +698,10 @@ class TerminologyBuilder { 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'); }); + if (opts.vacuum !== false) { + this._time('finish', () => finishFile(db, this.dest)); + 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']) { @@ -536,25 +716,129 @@ class TerminologyBuilder { } } -/** per property: n_rows, subject_kind, target_kind from the fact rows (ids <= n are concepts) */ +/** the selector of a reading rule: one of code, codes, shape, shapes, codeContains, valueSystem */ +const SELECTORS = ['code', 'codes', 'shape', 'shapes', 'codeContains', 'valueSystem']; +function selectorOf(rule) { + const keys = SELECTORS.filter((k) => rule[k] !== undefined); + if (keys.length !== 1) throw new Error(`reading rule ${JSON.stringify(rule)}: exactly one selector (${SELECTORS.join(', ')})`); + return { [keys[0]]: rule[keys[0]] }; +} + +/** whether a rule's selector names a catalog row {code, shape, valueSystem} */ +function selects(rule, p) { + if (rule.code !== undefined) return p.code === rule.code; + if (rule.codes !== undefined) return rule.codes.includes(p.code); + if (rule.shape !== undefined) return p.shape === rule.shape; + if (rule.shapes !== undefined) return rule.shapes.includes(p.shape); + if (rule.codeContains !== undefined) return p.code.includes(rule.codeContains); + if (rule.valueSystem !== undefined) return p.valueSystem === rule.valueSystem; + return false; +} + +/** checks the reading columns of a property spec or a reading rule (README.md "property") */ +function checkReadingColumns(x, what) { + if (x.lookup !== undefined && !LOOKUP.has(x.lookup)) throw new Error(`${what}: lookup ${x.lookup} (default, named or never)`); + if (x.expansion !== undefined && !EXPANSION.has(x.expansion)) throw new Error(`${what}: expansion ${x.expansion} (asked, always or never)`); + for (const k of ['lookupRank', 'expansionRank']) { + if (x[k] !== undefined && x[k] !== null && !(Number.isSafeInteger(x[k]) && x[k] >= 0)) throw new Error(`${what}: ${k} ${x[k]}`); + } + if (x.alsoAskedAs !== undefined && x.alsoAskedAs !== null + && !(Array.isArray(x.alsoAskedAs) && x.alsoAskedAs.every((v) => typeof v === 'string' && v) && new Set(x.alsoAskedAs).size === x.alsoAskedAs.length)) { + throw new Error(`${what}: alsoAskedAs is a list of distinct names`); + } + if (x.fhirCode !== undefined && x.fhirCode !== null && !(typeof x.fhirCode === 'string' && x.fhirCode)) throw new Error(`${what}: fhirCode ${x.fhirCode}`); + if (x.aliasLiterals !== undefined && x.aliasLiterals !== null && !(typeof x.aliasLiterals === 'object' && !Array.isArray(x.aliasLiterals))) { + throw new Error(`${what}: aliasLiterals is an object {fhir code: template}`); + } +} + +/** the reading columns a spec or rule states, as column -> value (absent: not stated) */ +function readingColumns(x) { + const out = {}; + for (const [k, col] of Object.entries(READING_COLUMNS)) { + if (x[k] === undefined) continue; + const v = x[k]; + if (v === null) out[col] = null; + else if (k === 'alsoAskedAs') out[col] = v.length ? JSON.stringify(v) : null; + else if (k === 'aliasLiterals') out[col] = JSON.stringify(v); + else if (k === 'internal') out[col] = v ? 1 : 0; + else if (k === 'trueValue') out[col] = String(v); + else out[col] = v; + } + return out; +} + +/** the text of the first capturing group of a regular expression, or null */ +function firstGroup(pattern) { + for (let i = 0; i < pattern.length; i++) { + const ch = pattern[i]; + if (ch === '\\') { i++; continue; } + if (ch === '(' && pattern[i + 1] !== '?') { + let depth = 0; + for (let j = i; j < pattern.length; j++) { + if (pattern[j] === '\\') { j++; continue; } + if (pattern[j] === '(') depth++; + else if (pattern[j] === ')' && --depth === 0) return pattern.slice(i + 1, j); + } + return null; + } + } + return null; +} + +/** + * The filter table from the reading's filter list: explicit rows, and `each` generators (one row + * per catalog row the selector names, property id order; not internal, not record). props: the + * written catalog rows [{id, code, shape, valueSystem, internal}] + */ +function writeFilters(db, filters, props) { + const labelled = new Set(db.prepare('SELECT DISTINCT property_id FROM main.value_label').pluck().all()); + const rows = []; + for (const f of filters) { + if (f.each === undefined) { rows.push(f); continue; } + const sel = f.each; + selectorOf(sel); + for (const p of props) { + if (!selects(sel, p) || (f.except || []).includes(p.code) || p.internal || p.shape === 'record') continue; + // reads: the row itself, or a template naming another row by this one's code ({code}) + const reads = f.reads === undefined ? p.code : f.reads.split('{code}').join(p.code); + if (!props.some((q) => q.code === reads)) throw new Error(`filter ${p.code}: reads ${reads}, which is no property`); + rows.push({ code: p.code, operators: f.operators, reads, codeAnyCase: f.codeAnyCase, valuePrefix: f.valuePrefix, + valueAsDisplay: p.shape === 'link' ? !!f.linksAsDisplay : (p.shape === 'literal' || p.shape === 'both') ? !!f.labelsAsDisplay && labelled.has(p.id) : false }); + } + } + const ins = db.prepare(`INSERT INTO main.filter (id, code, code_pattern, code_any_case, description, operators, reads, allowed_values, + value_prefix, value_case, value_as_display, where_literal, then_link) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`); + const known = ['code', 'codePattern', 'codeAnyCase', 'description', 'operators', 'reads', 'allowedValues', 'valuePrefix', 'valueCase', + 'valueAsDisplay', 'whereLiteral', 'thenLink']; + rows.forEach((r, k) => { + for (const key of Object.keys(r)) if (!known.includes(key)) throw new Error(`filter ${r.code ?? r.codePattern}: unknown member ${key}`); + if (!Array.isArray(r.operators) || !r.operators.length) throw new Error(`filter ${r.code ?? r.codePattern}: operators is a non-empty list`); + ins.run(k + 1, r.code ?? null, r.codePattern ?? null, r.codeAnyCase ? 1 : 0, r.description ?? null, JSON.stringify(r.operators), + JSON.stringify(r.reads), r.allowedValues == null ? null : JSON.stringify(r.allowedValues), r.valuePrefix ?? null, r.valueCase ?? 'any', + r.valueAsDisplay ? 1 : 0, r.whereLiteral == null ? null : JSON.stringify(r.whereLiteral), r.thenLink ?? null); + }); + return rows.length; +} + +/** + * per property: its number of rows (n: a union has none of its own) and subject_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: [] }; + const merge = (pid, rows, sLo, sHi) => { + const c = out.get(pid) || { n: 0, s: [] }; 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 link 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 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); + for (const r of db.prepare('SELECT relation_id p, count(*) c, min(subject_id) a, max(subject_id) b FROM record GROUP BY 1').all()) merge(r.p, r.c, r.a, r.b); 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 }); - } + for (const [pid, c] of out) res.set(pid, { n: c.n, subjectKind: kind(Math.min(...c.s), Math.max(...c.s)) }); return res; } @@ -594,10 +878,260 @@ function analyze(db, what = null) { db.exec('DROP TABLE IF EXISTS sqlite_stat4'); } -/** VACUUM a built file (after the importer's derived-by-importer rows), without sqlite_stat4 */ +/** + * Finish a built file (after the importer's derived-by-importer rows) and VACUUM it, 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(); } + try { + db.exec('DROP TABLE IF EXISTS sqlite_stat4'); + finishFile(db, file); + db.exec('VACUUM'); + } finally { db.close(); } +} + +/** + * The step that finishes a file, after every other table, meta row and ANALYZE: the contracts of the + * format hold (checkContracts), meta integrity states the file's facts (tx/sqlite-v2/integrity.js), + * and every meta key is one this builder knows, with a value a reader accepts (tx/sqlite-v2/meta.js; a typo in a key is + * caught here, not by the readers, which ignore a key they do not know). Run again whenever a tool + * rewrites a finished file. + */ +function finishFile(db, file = db.name) { + db.exec('DROP TABLE IF EXISTS sqlite_stat4'); + checkContracts(db); + // the integrity facts (optional in the format; verify.js checks them on request), written last + db.prepare("INSERT OR REPLACE INTO main.meta VALUES ('integrity', ?)").run(integrityValue(computeIntegrity(db))); + readMeta(db.prepare('SELECT key, value FROM main.meta').raw().all(), file, { writer: true }); +} + +/** the secondary indexes of schema.sql (fact indexes and ix), by name -> unique */ +function schemaIndexes() { + const out = new Map(); + for (const m of fs.readFileSync(SCHEMA_PATH, 'utf8').matchAll(/^CREATE (UNIQUE )?INDEX (\w+)/gm)) out.set(m[2], !!m[1]); + return out; +} + +/** + * The contracts of the format (tx/sqlite-v2/README.md "Contracts") that a builder checks before it + * finishes a file; throws `contract: ...` on the first one broken. Reads every identifier row, every + * kind 4 set and the ix_order block lengths: build time only. + */ +function checkContracts(db) { + const one = (sql, ...a) => db.prepare(sql).pluck().get(...a); + const fail = (m) => { throw new Error(`contract: ${m}`); }; + const cs = db.prepare('SELECT concept_count n, active_count a FROM main.code_system WHERE served = 1').get(); + if (!cs) fail('no served code_system row'); + const { n, a } = cs; + // concepts 1..N, 1..A active + const [clo, chi, cn] = db.prepare('SELECT min(id), max(id), count(*) FROM main.concept').raw().get(); + if (cn !== n || (n > 0 && (clo !== 1 || chi !== n))) fail(`concept ids are not exactly 1..${n} (min ${clo}, max ${chi}, ${cn} rows)`); + if (one(`SELECT count(*) FROM main.concept WHERE active <> (id <= ${a})`)) fail(`the active concepts are not exactly 1..${a}`); + // items N+1..N+M + const [ilo, ihi, m] = db.prepare('SELECT min(id), max(id), count(*) FROM main.item').raw().get(); + if (m > 0 && (ilo !== n + 1 || ihi !== n + m)) fail(`item ids are not exactly ${n + 1}..${n + m} (min ${ilo}, max ${ihi})`); + // the catalog + if (one('SELECT count(*) FROM main.property WHERE subsumption = 1') > 1) fail('more than one property with subsumption = 1'); + if (one("SELECT count(*) FROM main.property WHERE ordered = 1 AND shape = 'link'") > 1) fail('more than one ordered link property'); + // ix_set keys + const badKeys = one(`SELECT count(*) FROM main.ix_set WHERE (kind IN (1, 2, 3) AND (property_id <> 0 OR value <> 0 OR value_kind <> 0)) + OR (kind IN (6, 7) AND (value <> 0 OR value_kind <> 0)) OR (kind = 4 AND value_kind <> 1)`); + if (badKeys) fail(`${badKeys} ix_set rows break the key conventions of their kind`); + // bitmaps: concept ids only; a kind 4 set without its anchor; all and active sets of N and A + const { RoaringBitmap32 } = require('roaring-js'); + const card = (kind) => one('SELECT card FROM main.ix_set WHERE kind = ? AND property_id = 0 AND value = 0 AND value_kind = 0', kind) ?? 0; + if (card(1) !== n) fail(`the all set (ix_set kind 1) has ${card(1)} members, concept_count ${n}`); + if (card(2) !== a) fail(`the active set (ix_set kind 2) has ${card(2)} members, active_count ${a}`); + for (const [kind, value, c, data] of db.prepare('SELECT kind, value, card, data FROM main.ix_set WHERE kind IN (1, 2, 4)').raw().iterate()) { + const bm = RoaringBitmap32.deserialize(data, 'portable'); + if (bm.size !== c) fail(`ix_set kind ${kind} value ${value}: card ${c}, ${bm.size} members`); + if (bm.size && (bm.minimum() < 1 || bm.maximum() > n)) fail(`ix_set kind ${kind} value ${value} holds an id outside 1..${n}`); + if (kind === 4 && bm.has(value)) fail(`the descendants of concept ${value} (ix_set kind 4) include the concept itself`); + } + // ix_in and ix_by_subject: exactly the rows of the by_target / by_subject properties + const inRows = one('SELECT count(*) FROM main.link WHERE property_id IN (SELECT id FROM main.property WHERE by_target = 1)'); + if (one('SELECT count(*) FROM main.ix_in') !== inRows) fail(`ix_in does not hold exactly the ${inRows} links of the by_target properties`); + const bySubject = one('SELECT count(*) FROM main.identifier WHERE property_id IN (SELECT id FROM main.property WHERE by_subject = 1)'); + if (one('SELECT count(*) FROM main.ix_by_subject') !== bySubject) fail(`ix_by_subject does not hold exactly the ${bySubject} identifier rows of the by_subject properties`); + // ix_order arrays: full 1,024-entry blocks 0..k but the last; rank / ids N+1 entries, walk / active at most N + const arrays = new Map(); + for (const [name, block, len] of db.prepare('SELECT name, block, length(data) FROM main.ix_order ORDER BY name, block').raw().iterate()) { + const x = arrays.get(name) || { blocks: 0, entries: 0, short: false }; + if (block !== x.blocks || x.short || len % 4 !== 0 || len === 0 || len > 4096) fail(`ix_order ${name}: block ${block} (${len} bytes) is out of place`); + x.blocks++; x.entries += len / 4; x.short = len < 4096; + arrays.set(name, x); + } + for (const name of ['rank', 'ids']) { + if (arrays.has(name) && arrays.get(name).entries !== n + 1) fail(`ix_order ${name} has ${arrays.get(name).entries} entries, not ${n + 1}`); + } + for (const name of ['walk', 'active']) { + if (arrays.has(name) && arrays.get(name).entries > n) fail(`ix_order ${name} has ${arrays.get(name).entries} entries, more than ${n}`); + } + const reached = one("SELECT value FROM main.meta WHERE key = 'ix.ix_order.walk.reached'"); + if (reached != null && !(arrays.has('walk') && Number(reached) <= arrays.get('walk').entries)) fail(`ix.ix_order.walk.reached ${reached} is more than the walk's length`); + // ix_word: the counts rows; a stemmer for every language + for (const [lang, len] of db.prepare("SELECT lang, length(ids) FROM main.ix_word WHERE word = ''").raw().iterate()) { + if (len !== 2 * (n + 1)) fail(`ix_word counts row of ${lang} is ${len} bytes, not ${2 * (n + 1)}`); + } + const langs = db.prepare('SELECT DISTINCT lang FROM main.ix_word').pluck().all(); + if (langs.length) { + const st = one("SELECT value FROM main.meta WHERE key = 'ix.ix_word.stemmers'"); + const stemmers = st ? JSON.parse(st) : {}; + for (const l of langs) if (!stemmers[l]) fail(`ix_word language ${l} has no entry in meta ix.ix_word.stemmers`); + } + // the reading (README.md "Contracts") + const metaOf = (k) => { const v = one('SELECT value FROM main.meta WHERE key = ?', k); return v == null ? undefined : JSON.parse(v); }; + if (one("SELECT value FROM main.meta WHERE key = 'requires'") !== JSON.stringify(['identifier-text', 'fhir-reading'])) { + fail('meta requires is not ["identifier-text","fhir-reading"]'); + } + const oldKeys = db.prepare(`SELECT key FROM main.meta WHERE key LIKE 'behaviour.%' OR key IN ('linkOrder', 'searchTieBreak', 'propertyUris', 'ix.ix_word.names')`).pluck().all(); + if (oldKeys.length) fail(`meta keys of an earlier revision: ${oldKeys.join(', ')}`); + const propCols = new Set(db.prepare('PRAGMA main.table_info(property)').all().map((c) => c.name)); + const oldCols = REMOVED_COLUMNS.filter((c) => propCols.has(c)); + if (oldCols.length) fail(`property has the columns of an earlier revision: ${oldCols.join(', ')}`); + // an order member that is the stored order for concepts has its arrays + const order = metaOf('order') || {}; + if ((['expansion', 'searchTies'].some((m) => (order[m] || []).includes('stored'))) && !(arrays.has('rank') && arrays.has('ids'))) { + fail(`meta order ${JSON.stringify(order)} uses the stored order without ix_order rank and ids`); + } + // order.literals stored reads literal.seq + if ((order.literals || []).includes('stored') && !db.prepare('PRAGMA main.table_info(literal)').all().some((c) => c.name === 'seq')) { + fail('meta order.literals names stored but literal has no seq column'); + } + // the word index exactly with search; its counts row exactly with search.shortlist + const search = metaOf('search'); + if (!search && langs.length) fail('ix_word rows in a file without meta search'); + const countsRows = one("SELECT count(*) FROM main.ix_word WHERE word = ''"); + if (search && search.shortlist == null && countsRows) fail('an ix_word counts row without search.shortlist'); + if (search && search.shortlist != null && langs.length && countsRows !== langs.length) fail('search.shortlist without an ix_word counts row for every language'); + if (!search && one("SELECT count(*) FROM main.meta WHERE key LIKE 'ix.ix_word.%'")) fail('meta ix.ix_word.* in a file without search'); + // the catalog (README.md "property") + const props = db.prepare('SELECT * FROM main.property WHERE cs_id = (SELECT cs_id FROM main.code_system WHERE served = 1) ORDER BY id').all(); + const byCode = new Map(props.map((p) => [p.code, p])); + const names = new Map(); + for (const p of props) { + if (!SHAPES.has(p.shape)) fail(`property ${p.code}: shape ${p.shape}`); + if (!LOOKUP.has(p.lookup) || !EXPANSION.has(p.expansion)) fail(`property ${p.code}: lookup ${p.lookup}, expansion ${p.expansion}`); + if (p.role != null && !ROLES.has(p.role)) fail(`property ${p.code}: role ${p.role}`); + if (p.internal && (p.lookup !== 'never' || p.expansion !== 'never' || p.uri != null)) fail(`property ${p.code}: internal, and reported or with a uri`); + if ((p.alias_parameter != null || p.alias_extension != null || p.alias_literals != null) && p.shape !== 'identifier') fail(`property ${p.code}: alias columns on a ${p.shape} row`); + if (p.shape === 'reading') { + if (!READING_CODES.has(p.code) || p.fhir_type !== 'boolean') fail(`property ${p.code}: a reading row is inactive, deprecated or notSelectable, of type boolean`); + } + if (READING_SHAPES.has(p.shape)) { + for (const t of ['link', 'literal', 'identifier']) if (one(`SELECT 1 FROM main.${t} WHERE property_id = ? LIMIT 1`, p.id)) fail(`property ${p.code}: shape ${p.shape} with ${t} rows`); + } + if (!p.internal && p.shape !== 'record') { + const name = p.fhir_code ?? p.code; + if (names.has(name)) fail(`properties ${names.get(name)} and ${p.code} are both reported as ${name}`); + names.set(name, p.code); + } + } + for (const p of props) { + for (const x of p.also_asked_as ? JSON.parse(p.also_asked_as) : []) { + if (names.has(x) && names.get(x) !== p.code) fail(`property ${p.code}: also asked as ${x}, the name of ${names.get(x)}`); + } + } + // a union's rows are all identifier rows (read by value) or none + const byId = new Map(props.map((p) => [p.id, p])); + const membersOf = new Map(); + for (const [a, c] of db.prepare('SELECT parent_id, child_id FROM main.property_member').raw().all()) { + if (!membersOf.has(a)) membersOf.set(a, []); + membersOf.get(a).push(c); + } + const storedOf = (id) => (membersOf.has(id) ? membersOf.get(id).flatMap(storedOf) : [id]); + for (const p of props) { + if (p.shape !== 'union' || !membersOf.has(p.id)) continue; + const ident = storedOf(p.id).map((id) => (byId.get(id) || {}).shape === 'identifier'); + if (ident.some((x) => x) && !ident.every((x) => x)) fail(`property ${p.code}: a union of identifier and other rows`); + } + if (props.filter((p) => p.alias_parameter != null || p.alias_extension != null || p.alias_literals != null).length > 1) fail('more than one property with alias columns'); + const status = props.filter((p) => p.role === 'status'); + if (status.length > 1) fail('more than one property with role status'); + if (status.length && status[0].shape !== 'literal') fail(`the status property ${status[0].code} is not a literal`); + // item_use (README.md "item_use") + const asProperty = new Set(); + for (const u of db.prepare('SELECT code, role, as_property, language_display_rank FROM main.item_use').all()) { + if (u.role != null && !USE_ROLES.has(u.role)) fail(`item use ${u.code}: role ${u.role}`); + if (u.as_property != null) { + const d = byCode.get(u.as_property); + if (!d || d.shape !== 'item-use') fail(`item use ${u.code}: as_property ${u.as_property} is no item-use property`); + if (asProperty.has(u.as_property)) fail(`two item uses name as_property ${u.as_property}`); + asProperty.add(u.as_property); + } + } + for (const p of props) if (p.shape === 'item-use' && !asProperty.has(p.code)) fail(`property ${p.code}: shape item-use, and no item use names it`); + const badMap = one("SELECT count(*) FROM main.mapping m LEFT JOIN main.property p ON p.id = m.property_id WHERE m.property_id IS NOT NULL AND (p.id IS NULL OR p.shape <> 'mapping')"); + if (badMap) fail(`${badMap} mapping rows name a property that is no mapping-shape row`); + // the filter rows (README.md "filter") + const grammar = metaOf('grammar'); + const filters = db.prepare('SELECT * FROM main.filter ORDER BY id').all(); + for (const f of filters) { + const what = `filter ${f.id} (${f.code ?? f.code_pattern})`; + if ((f.code == null) === (f.code_pattern == null)) fail(`${what}: exactly one of code and code_pattern`); + // an internal row may be read, never named: no filter has its code + if (f.code != null && (byCode.get(f.code) || {}).internal) fail(`${what}: named by the internal property ${f.code}`); + if (f.code_pattern != null) { try { new RegExp(f.code_pattern); } catch (e) { fail(`${what}: code_pattern is not a regular expression`); } } + const ops = JSON.parse(f.operators); + if (!(Array.isArray(ops) && ops.length && new Set(ops).size === ops.length && ops.every((o) => FILTER_ROW_OPERATORS.includes(o)))) fail(`${what}: operators ${f.operators}`); + let reads = JSON.parse(f.reads); + if (typeof reads === 'string') reads = [reads]; + if (!(Array.isArray(reads) && reads.length)) fail(`${what}: reads ${f.reads}`); + for (const x of reads) { + if (FILTER_READS.has(x)) { + if (x === 'grammar' && grammar == null) fail(`${what}: reads grammar without meta grammar`); + if (x === '{1}' && !(f.code_pattern != null && firstGroup(f.code_pattern) != null)) fail(`${what}: reads {1} without a capture group`); + continue; + } + if (!byCode.get(x)) fail(`${what}: reads ${x}, which is no property`); + } + if (!['any', 'exact'].includes(f.value_case)) fail(`${what}: value_case ${f.value_case}`); + if (f.then_link != null && !['link', 'both', 'union'].includes((byCode.get(f.then_link) || {}).shape)) fail(`${what}: then_link ${f.then_link} is no link property`); + if (f.where_literal != null) { + for (const k of Object.keys(JSON.parse(f.where_literal))) if ((byCode.get(k) || {}).shape !== 'literal') fail(`${what}: where_literal names ${k}, no literal property`); + } + // rows of one code share an operator only when value prefixes tell them apart (not exists) + for (const g of filters) { + if (!(g.id < f.id && g.code != null && g.code === f.code)) continue; + const shared = JSON.parse(g.operators).filter((o) => ops.includes(o)); + if (!shared.length) continue; + const a = g.value_prefix, b = f.value_prefix; + if (!(a != null && b != null && !a.startsWith(b) && !b.startsWith(a) && !shared.includes('exists'))) fail(`${what}: shares an operator with filter ${g.id}, and values could be read by both`); + } + } + // conceptStatus names literal rows; concept.active agrees with it when it gives inactive + const conceptStatus = metaOf('conceptStatus') || []; + for (const e of conceptStatus) if ((byCode.get(e.property) || {}).shape !== 'literal') fail(`meta conceptStatus names ${e.property}, which is no literal property`); + const { conceptsMeaningSql } = require('./indexes'); + const inactiveSql = conceptStatus.some((e) => Object.values(e.values || {}).some((m) => m.includes('inactive'))) ? conceptsMeaningSql(db, 'inactive') : null; + if (inactiveSql != null) { + const k = one(`SELECT count(*) FROM main.concept WHERE active <> (id NOT IN (${inactiveSql}))`); + if (k) fail(`concept.active disagrees with meta conceptStatus on ${k} concepts`); + } + // kind 5 sets only for the properties a filter, a refinement or conceptStatus reads + const { setPropertyIds } = require('./indexes'); + const allowed = setPropertyIds(db); + const extra = db.prepare('SELECT DISTINCT property_id FROM main.ix_set WHERE kind = 5').pluck().all().filter((p) => !allowed.has(p)); + if (extra.length) fail(`ix_set kind 5 sets of properties no filter, refinement or conceptStatus reads: ${extra.join(', ')}`); + // a grammar template needs a grammar + if ((metaOf('implicitValueSets') || []).some((t) => t.grammar !== undefined) && grammar == null) fail('a grammar template in implicitValueSets without meta grammar'); + if (((metaOf('compatibility') || {}).lookupListsCopyright)) { + const r = one('SELECT resource FROM main.code_system WHERE served = 1'); + let c = null; + try { c = r ? JSON.parse(r).copyright : null; } catch (e) { c = null; } + if (!c) fail('compatibility.lookupListsCopyright without code_system.resource.copyright'); + } + // the secondary indexes of the schema; sqlite_stat1 and no sqlite_stat4 + for (const [name, unique] of schemaIndexes()) { + const sql = one("SELECT sql FROM main.sqlite_master WHERE type = 'index' AND name = ?", name); + if (sql == null) fail(`the index ${name} is missing`); + if (unique && !/^CREATE UNIQUE INDEX/.test(sql)) fail(`the index ${name} is not unique`); + } + if (one("SELECT count(*) FROM main.sqlite_master WHERE name = 'sqlite_stat1'") !== 1) fail('no sqlite_stat1'); + if (one("SELECT count(*) FROM main.sqlite_master WHERE name = 'sqlite_stat4'")) fail('sqlite_stat4 is present'); + return true; } -module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, analyze, externalIdValue }; + +module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, finishFile, checkContracts, analyze, externalIdValue, firstGroup }; diff --git a/tx/importers/sqlite-v2/diff.js b/tx/importers/sqlite-v2/diff.js index cc70d6db..8f1506b2 100644 --- a/tx/importers/sqlite-v2/diff.js +++ b/tx/importers/sqlite-v2/diff.js @@ -18,7 +18,7 @@ const fs = require('fs'); const Database = require('../../../library/sql/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']; +const FACTS = ['concept', 'item', 'item_use', 'property', 'property_member', 'filter', '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) { @@ -43,10 +43,14 @@ function keyed(db) { 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('item_use', 'SELECT system, code, display, role, as_property, language_display_rank FROM item_use', (r) => r); + view('property', `SELECT code, uri, display, concept_id, shape, role, fhir_type, subject_kind, subsumption, + closure_from, refinable, wildcard, inverse_of, by_target, by_subject, ordered, fields, fhir_code, also_asked_as, lookup, expansion, + lookup_rank, expansion_rank, true_value, presentation, value_system, internal, alias_parameter, alias_extension, alias_literals FROM property`, + (r) => { r[3] = key(r[3]); r[9] = r[9] == null ? null : pcode.get(r[9]); r[12] = r[12] == null ? null : pcode.get(r[12]); return r; }); + // (in order: a filter row's id is its place in CodeSystem.filter) + view('filter', `SELECT id, code, code_pattern, code_any_case, description, operators, reads, allowed_values, value_prefix, value_case, + value_as_display, where_literal, then_link FROM filter`, (r) => 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]); diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index 4aa0d8de..1bef06ce 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -8,8 +8,8 @@ // // 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 / +// property = value (for the properties a filter row, a refinement or conceptStatus +// reads: setPropertyIds) 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) @@ -17,15 +17,17 @@ // 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_order nothing computed here: the system order (rank, ids, walk) is written by the importer (derived-by-importer), kept across a rebuild +// ix_word the word index (tx/sqlite-v2/text-index.js rules) over the names meta +// search.names selects (of the listed concepts: not unlisted), with meta ix.ix_word.format and ix.ix_word.stemmers (each +// language's stemmer, tx/library/text-match.js stemmerName); the counts row +// (little-endian) exactly when search.shortlist is set. A file without meta +// search gets no word index // ix_key nothing generic (SNOMED normal forms are derived-by-importer) const Database = require('../../../library/sql/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 }; @@ -66,6 +68,8 @@ function dropIndexes(db) { 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); } + // the integrity facts no longer hold: the step that finishes the file writes them again + db.prepare("DELETE FROM meta WHERE key = 'integrity'").run(); } /** @@ -74,6 +78,9 @@ function dropIndexes(db) { */ function buildIndexes(db, opts = {}) { const time = opts.time || ((name, fn) => fn()); + // the word index reads meta search (none: no word index) + const searchRaw = db.prepare("SELECT value FROM main.meta WHERE key = 'search'").pluck().get(); + const search = searchRaw == null ? null : JSON.parse(searchRaw); 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(); @@ -91,21 +98,23 @@ function buildIndexes(db, opts = {}) { 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'); + const { computeTextIndexFrom, eachSearchName, FORMAT } = require('../../sqlite-v2/text-index'); + const { stem, stemmerName } = 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)) { + // ix_order: only the rows an importer wrote (derived-by-importer, kept above): the order rule is + // the importer's, never computed here by system + if (search != null) { + const setMeta = db.prepare('INSERT OR REPLACE INTO main.meta VALUES (?, ?)'); 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 names of the listed concepts (an unlisted concept is never a text-search candidate) + const unlisted = new Set(db.prepare(conceptsMeaningSql(db, 'unlisted')).pluck().all()); + const each = unlisted.size ? (fn) => eachSearchName(store, (id, lang, term) => { if (!unlisted.has(id)) fn(id, lang, term); }) : (fn) => eachSearchName(store, fn); + const byLang = computeTextIndexFrom(each, search.shortlist != null, n); + stats.words = time('ix_word', () => writeWords(db, byLang, stem)); + setMeta.run('ix.ix_word.format', FORMAT); + // the stemmer that made each language's stems + setMeta.run('ix.ix_word.stemmers', JSON.stringify(Object.fromEntries([...byLang.keys()].sort().map((l) => [l, stemmerName(l)])))); } // the 'active' order from a walk an importer kept (derived-by-importer); importers that write // the walk after this call it again @@ -114,6 +123,70 @@ function buildIndexes(db, opts = {}) { return stats; } +/** + * The properties with ix_set kind 5 sets (README.md "Contracts"): those a filter row reads by code + * (a `{1}` row: every link, literal, both, union or identifier row whose code its pattern's first + * group matches in full), the literals a where_literal names, the refinable properties and the + * properties meta conceptStatus names; with the members of every union among them. A Set of ids. + */ +function setPropertyIds(db) { + const { firstGroup } = require('./builder'); + const props = db.prepare('SELECT id, code, shape, refinable FROM main.property WHERE cs_id = (SELECT cs_id FROM main.code_system WHERE served = 1)').all(); + const byCode = new Map(props.map((p) => [p.code, p.id])); + const out = new Set(); + const hasFilter = db.prepare("SELECT 1 FROM main.sqlite_master WHERE type = 'table' AND name = 'filter'").get(); + for (const f of hasFilter ? db.prepare('SELECT code_pattern, reads, where_literal FROM main.filter').all() : []) { + let reads = JSON.parse(f.reads); + if (typeof reads === 'string') reads = [reads]; + for (const r of reads) { + if (r === '{1}') { + const g = f.code_pattern != null ? firstGroup(f.code_pattern) : null; + if (g == null) throw new Error(`filter ${f.code_pattern}: reads {1} without a capture group`); + const re = new RegExp(`^(?:${g})$`); + for (const p of props) if (['link', 'literal', 'both', 'union', 'identifier'].includes(p.shape) && re.test(p.code)) out.add(p.id); + } else if (byCode.has(r)) out.add(byCode.get(r)); + } + if (f.where_literal != null) for (const k of Object.keys(JSON.parse(f.where_literal))) if (byCode.has(k)) out.add(byCode.get(k)); + } + for (const p of props) if (p.refinable) out.add(p.id); + // the hierarchy property: its sets are each concept's children (child-of, the hierarchy walk); + // (the spec's list, section 10, names it only where a filter row reads it by code) + for (const id of db.prepare('SELECT id FROM main.property WHERE subsumption = 1').pluck().all()) out.add(id); + // the literal text search's candidates are cut by (search.candidates.hasLiteral; not in the spec's + // list, section 10) + const search = db.prepare("SELECT value FROM main.meta WHERE key = 'search'").pluck().get(); + const has = search ? ((JSON.parse(search).candidates || {}).hasLiteral || null) : null; + if (has && byCode.has(has.property)) out.add(byCode.get(has.property)); + const cs = db.prepare("SELECT value FROM main.meta WHERE key = 'conceptStatus'").pluck().get(); + for (const e of cs ? JSON.parse(cs) : []) if (byCode.has(e.property)) out.add(byCode.get(e.property)); + // the members of a union a filter reads (a REL's RELAs) + 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 (out.has(a) && !out.has(c)) { out.add(c); grew = true; } + } + return out; +} + +/** + * SQL selecting the ids of the concepts whose readings (README.md "Concept status": meta + * conceptStatus over the literal rows, less compatibility.statusReadingsIgnored) contain the + * meaning; 'SELECT NULL WHERE 0' when no value has it + */ +function conceptsMeaningSql(db, meaning) { + const metaJson = (k, d) => { const v = db.prepare('SELECT value FROM main.meta WHERE key = ?').pluck().get(k); return v == null ? d : JSON.parse(v); }; + const ignored = new Map(((metaJson('compatibility', {}) || {}).statusReadingsIgnored || []).map((e) => [e.property, e.values || {}])); + const parts = []; + for (const e of metaJson('conceptStatus', [])) { + const ign = ignored.get(e.property) || {}; + const values = Object.entries(e.values).filter(([v, ms]) => ms.includes(meaning) && !(ign[v] || []).includes(meaning)).map(([v]) => v); + const pid = db.prepare('SELECT id FROM main.property WHERE code = ? AND cs_id = (SELECT cs_id FROM main.code_system WHERE served = 1)').pluck().get(e.property); + if (!values.length || pid == null) continue; + parts.push(`SELECT subject_id FROM main.literal WHERE property_id = ${Number(pid)} AND CAST(value AS TEXT) IN (${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(',')})`); + } + return parts.length ? parts.join(' UNION ') : 'SELECT NULL WHERE 0'; +} + function buildSets(db, n, activeCount) { const ins = db.prepare('INSERT INTO ix_set VALUES (?, ?, ?, ?, ?, ?)'); const stats = {}; @@ -165,14 +238,9 @@ function buildSets(db, n, activeCount) { 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; } - } + // kind 5 sets only for what a filter row, a refinement or conceptStatus reads (setPropertyIds); + // has-property sets for every property + const named = setPropertyIds(db); 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} @@ -242,17 +310,6 @@ function buildSets(db, n, activeCount) { * 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++) { @@ -290,8 +347,9 @@ function toLE(a) { return buf; } -/** computeTextIndex's Map(lang -> {words, counts}) -> ix_word rows; the counts in the row with word '' */ +/** computeTextIndex's Map(lang -> {words, counts}) -> ix_word rows; the counts (little-endian) in the row with word '' */ function writeWords(db, byLang, stem) { + const { countsToLE } = require('../../sqlite-v2/text-index'); const ins = db.prepare('INSERT INTO ix_word VALUES (?, ?, ?, ?)'); let words = 0; for (const [lang, x] of byLang) { @@ -300,7 +358,7 @@ function writeWords(db, byLang, stem) { 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)); + if (x.counts) ins.run(lang, '', '', countsToLE(x.counts)); } return words; } @@ -311,9 +369,10 @@ function intPairs(stmt) { return [Int32Array.from(a), Int32Array.from(b)]; } -module.exports = { buildIndexes, dropIndexes, ixTables, derivedByImporter, writeOrderArray, writeActiveOrder, KIND, VK }; +module.exports = { buildIndexes, dropIndexes, ixTables, derivedByImporter, writeOrderArray, writeActiveOrder, setPropertyIds, conceptsMeaningSql, KIND, VK }; -// node indexes.js [--drop-only]: rebuild (or only drop) the ix_* tables of a built file +// node indexes.js [--drop-only]: rebuild (or only drop) the ix_* tables of a built file, then +// finish it as the builder does (builder.js finishFile) if (require.main === module) { const [file, flag] = process.argv.slice(2); const db = new Database(file); @@ -322,7 +381,10 @@ if (require.main === module) { 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); + const { analyze, finishFile } = require('./builder'); + analyze(db); + // the contracts and the meta keys, as the builder checks a file it finishes + finishFile(db, file); console.log(JSON.stringify({ seconds: (Date.now() - t0) / 1000, ...s })); } db.close(); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 1941df72..38786669 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -12,6 +12,14 @@ -- -- 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. +-- +-- Contracts (tx/sqlite-v2/README.md "Contracts"; the builder checks them before it finishes a file): +-- concept ids exactly 1..N (N = concept_count), 1..A active (A = active_count); item ids exactly +-- N+1..N+M; at most one subsumption = 1 property and one ordered = 1 link property; codes unique per +-- system and matched exactly; ix_set key conventions, kind 4 sets without their anchor; ix_in / +-- ix_by_subject exactly the rows of the by_target / by_subject properties; ix_order arrays +-- little-endian u32 in full 1,024-entry blocks but the last; ix_word counts rows 2 * (N + 1) bytes; +-- the secondary indexes below exist. -- @facts CREATE TABLE code_system ( @@ -25,12 +33,13 @@ CREATE TABLE code_system ( 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. +-- and provenance, facts about indexes (ix.*), and the FHIR reading (conceptStatus, expansionLimits, order, +-- search, version, implicitValueSets, implicitMaps, grammar, compatibility: JSON values; meanings and +-- defaults in tx/sqlite-v2/README.md "Meta keys"). `requires` (JSON list) names the features the content +-- uses that a reader must understand: ["identifier-text", "fhir-reading"]; a reader refuses a file that +-- requires one it does not know, or lacks fhir-reading. A reader ignores a key it does not know and +-- refuses a malformed value of one it knows; a builder refuses to finish a file with a key it does not +-- know. provenance.* is free-form. CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID; CREATE TABLE concept ( @@ -51,21 +60,30 @@ CREATE TABLE item ( 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 item_use (use_id INTEGER PRIMARY KEY, system TEXT, code TEXT NOT NULL, display TEXT, + role TEXT, -- NULL; 'fsn', 'synonym' (SNOMED CT description types); 'display': the texts + -- of this use are accepted as a display + as_property TEXT, -- code of a property row of shape 'item-use': the items of this use are that + -- property's values, not designations; NULL: designations + language_display_rank INTEGER); -- order among the uses that give the display in a requested language; NULL: none -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, +CREATE TABLE property ( -- the catalog: one row per source property, relation, scheme; plus FHIR-reading rows + id INTEGER PRIMARY KEY, cs_id INTEGER NOT NULL, + code TEXT NOT NULL, -- the source's name + fhir_code TEXT, -- the name it is reported under and asked for by; NULL: code + also_asked_as TEXT, -- JSON list of further names a $lookup / expansion request may use; NULL: [] + uri TEXT, display TEXT, -- as CodeSystem.property.uri / description 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) + -- | 'item-use' | 'mapping' | 'reading' (no rows of their own: README.md) + role TEXT, -- NULL; 'language': a record relation on items that ranks displays; + -- 'status': the literal that holds the concept's status text (at most one) + fhir_type TEXT, -- CodeSystem.property.type of its values + subject_kind TEXT, -- 'concept' | 'item' | 'both' (computed at build; NULL when it has no rows, + -- which 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) @@ -74,10 +92,19 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat -- 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 + lookup TEXT NOT NULL DEFAULT 'default', -- $lookup: 'default' (listed unless properties are named), 'named' (only + -- when asked for by name or *), 'never' + expansion TEXT NOT NULL DEFAULT 'asked', -- expansion rows: 'asked' (when asked for), 'always' (every row), 'never' + lookup_rank INTEGER, -- place among the properties $lookup lists; NULL: after every ranked row + expansion_rank INTEGER, -- place in an expansion that asks for '*'; NULL: after the ranked rows + true_value TEXT, -- reported as a boolean: true when its value (a link's target code, a + -- literal's value) equals this; NULL: reported with its own value + presentation TEXT, -- JSON {value?: code|string|display|coding, parts?: [description|code-display|partCode]} + value_system TEXT, -- an identifier property's values are codes of this system + internal INTEGER NOT NULL DEFAULT 0, -- 1: storage only; never reported, declared or a filter's name (a filter may read it) + alias_parameter TEXT, -- identifier rows only: the output parameter that restates the alias form + alias_extension TEXT, -- identifier rows only: the Coding extension that restates the alias form + alias_literals TEXT, -- identifier rows only: JSON {fhir_code: template} reported through an alias 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` @@ -85,6 +112,22 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat -- in order) UNIQUE (cs_id, code) ); +CREATE TABLE filter ( -- CodeSystem.filter, complete: a filter that is no row is not understood + id INTEGER PRIMARY KEY, -- order in which CodeSystem.filter lists them + code TEXT, -- the filter's name (exactly one of code / code_pattern) + code_pattern TEXT, -- a regular expression (full match) a name may match instead + code_any_case INTEGER NOT NULL DEFAULT 0, -- 1: the name may be written in any case + description TEXT, -- CodeSystem.filter.description + operators TEXT NOT NULL, -- JSON list of FHIR filter operators + reads TEXT NOT NULL, -- JSON string or list of strings: what the filter reads + allowed_values TEXT, -- JSON list of the only values accepted, or the string "codes"; NULL: any + value_prefix TEXT, -- every value must start with this; it is removed before matching. Rows of one + -- code sharing an operator: each value is read by the row with its prefix + value_case TEXT NOT NULL DEFAULT 'any', -- 'any' | 'exact': how a value matches a stored literal value + value_as_display INTEGER NOT NULL DEFAULT 0,-- 1: a value may also be a link target's display or a literal's value label + where_literal TEXT, -- JSON {property code: value} that must also hold + then_link TEXT -- a link property code: the result is the targets of these links from what was read +); 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 @@ -98,12 +141,15 @@ CREATE TABLE link ( 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, + seq INTEGER, -- source order among the subject's values of the property (order.literals stored) 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 + value TEXT NOT NULL, -- text (TEXT affinity: SQLite stores whatever is bound as text). A file + -- written before this column was declared TEXT, and that does not + -- require identifier-text, may hold INTEGER for a canonical decimal integer 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 @@ -153,6 +199,7 @@ CREATE INDEX item_definition ON item(concept_id) WHERE kind = 1 AND preferred = -- 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); +CREATE INDEX filter_code ON filter(code); -- @ix -- Rows that need terminology logic to build are written by the importer and listed in @@ -163,8 +210,10 @@ CREATE INDEX resource_url ON resource(type, url, version); -- 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. +-- only for: the properties a filter row reads by code (members of a union it reads included; a `{1}` row: +-- every link, literal, both, union or identifier row whose code its capture group matches), the literals a +-- where_literal names, the refinable properties and the properties conceptStatus names; 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. @@ -175,7 +224,7 @@ CREATE TABLE ix_in (target_id INTEGER NOT NULL, property_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, +CREATE TABLE ix_by_subject (subject_id INTEGER NOT NULL, property_id INTEGER NOT NULL, value TEXT 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), @@ -184,10 +233,12 @@ CREATE TABLE ix_by_subject (subject_id INTEGER NOT NULL, property_id INTEGER NOT 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. +-- word index (tx/sqlite-v2/text-index.js rules; format in meta 'ix.ix_word.format', the names meta +-- search.names selects, of the listed concepts; each language's stemmer in 'ix.ix_word.stemmers'; +-- README.md "Word index"; no rows without meta search): 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 (unsigned 16-bit little-endian by concept id 0..N: 2 * (N + 1) +-- bytes), exactly when meta search.shortlist is set. 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); diff --git a/tx/importers/sqlite-v2/verify.js b/tx/importers/sqlite-v2/verify.js new file mode 100644 index 00000000..af0f3675 --- /dev/null +++ b/tx/importers/sqlite-v2/verify.js @@ -0,0 +1,72 @@ +'use strict'; + +// node verify.js : check a terminology file on request, read-only (tx/sqlite-v2/README.md +// "Contracts" and "Integrity facts"): the format, the meta values a reader checks, the id ranges and +// every contract the builder checks, and the integrity facts in meta `integrity` where the file +// states them. Prints each check; exits 1 when one fails, the file cannot be read included. +// Readers make none of these checks but the cheap id ranges (tx/sqlite-v2/store.js). + +const fs = require('fs'); +const Database = require('../../../library/sql/better-sqlite3'); + +/** + * The checks, in order: [{check, ok, detail}]. Stops the contract checks at the first one broken + * (checkContracts throws), and goes on with the others. + * @param {string} file + */ +function verifyFile(file) { + const { checkFormat } = require('../../sqlite-v2/store'); + const { readMeta } = require('../../sqlite-v2/meta'); + const { checkIntegrity } = require('../../sqlite-v2/integrity'); + const { checkContracts } = require('./builder'); + const out = []; + const step = (check, fn) => { + try { + const detail = fn(); + out.push({ check, ok: true, detail: detail == null ? '' : String(detail) }); + } catch (e) { + out.push({ check, ok: false, detail: e.message }); + } + }; + if (!fs.existsSync(file)) throw new Error(`${file}: no such file`); + const db = new Database(file, { readonly: true, fileMustExist: true }); + try { + db.pragma('query_only = 1'); + step('format', () => { checkFormat(db, file); return 'tx-terminology/1'; }); + if (!out[0].ok) return out; + let meta = null; + step('meta', () => { + meta = readMeta(db.prepare('SELECT key, value FROM main.meta').raw().all(), file); + return `requires ${JSON.stringify(meta.requires)}${meta.ignored.length ? `; keys this reader does not know (ignored): ${meta.ignored.join(', ')}` : ''}`; + }); + step('contracts', () => { checkContracts(db); return 'id ranges, catalog, index layout, statistics'; }); + const integrity = meta && meta.values.get('integrity'); + if (integrity) { + for (const r of checkIntegrity(db, file, integrity)) out.push({ check: `integrity: ${r.check}`, ok: r.ok, detail: r.detail }); + } else { + out.push({ check: 'integrity', ok: true, detail: 'the file states no integrity facts (meta integrity is optional)' }); + } + } finally { + db.close(); + } + return out; +} + +module.exports = { verifyFile }; + +if (require.main === module) { + const file = process.argv[2]; + if (!file) { + console.error('usage: node verify.js '); + process.exit(1); + } + let results; + try { + results = verifyFile(file); + } catch (e) { + console.error(e.message); + process.exit(1); + } + for (const r of results) console.log(`${r.ok ? 'ok ' : 'FAIL'} ${r.check}${r.detail ? ': ' + r.detail : ''}`); + process.exit(results.every((r) => r.ok) ? 0 : 1); +} diff --git a/tx/library.js b/tx/library.js index a2836821..74767c3c 100644 --- a/tx/library.js +++ b/tx/library.js @@ -78,11 +78,16 @@ 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) +// the code system each sqlite-v2 source type's file must hold (loadSqliteV2); `sqlite-v2`: any, +// the one the file names const SQLITE_V2_SYSTEMS = { + 'sqlite-v2': null, 'snomed-v2': 'http://snomed.info/sct', 'loinc-v2': 'http://loinc.org', - 'rxnorm-v2': 'http://www.nlm.nih.gov/research/umls/rxnorm' + 'rxnorm-v2': 'http://www.nlm.nih.gov/research/umls/rxnorm', + 'ndc-v2': 'http://hl7.org/fhir/sid/ndc', + 'unii-v2': 'http://fdasis.nlm.nih.gov', + 'cpt-v2': 'http://www.ama-assn.org/go/cpt' }; class Library { @@ -508,9 +513,13 @@ class Library { await this.loadIcd11(details, isDefault, mode); break; + case 'sqlite-v2': case 'snomed-v2': case 'loinc-v2': case 'rxnorm-v2': + case 'ndc-v2': + case 'unii-v2': + case 'cpt-v2': await this.loadSqliteV2(type, details, isDefault, mode); break; @@ -1115,8 +1124,9 @@ class Library { } /** - * 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). + * A file in the sqlite-v2 format (tx/sqlite-v2; source syntax `sqlite-v2:` for a file of + * any code system, or `snomed-v2:`, `loinc-v2:`, `rxnorm-v2:`, `ndc-v2:`, `unii-v2:`, `cpt-v2:`, + * which also check the system the file holds; 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. */ @@ -1128,7 +1138,7 @@ class Library { const { loadSqliteV2Factory } = require('./sqlite-v2'); const factory = await loadSqliteV2Factory(this.i18n, fn); const expected = SQLITE_V2_SYSTEMS[type]; - if (factory.system() !== expected) { + if (expected != null && factory.system() !== expected) { throw new Error(`${type}:${details}: the file holds ${factory.system()}, not ${expected}`); } this.registerProvider(fn, factory, isDefault); diff --git a/tx/library/text-match.js b/tx/library/text-match.js index 08a043a6..a8321313 100644 --- a/tx/library/text-match.js +++ b/tx/library/text-match.js @@ -46,25 +46,26 @@ const MAX_WORDS = 10; const WORD_RE = /[\p{L}\p{M}\p{N}]+/gu; const ACCENTED = /([\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}])\p{M}+/gu; -// The stemmers, by primary language subtag: the best that the natural package has. A language -// that isn't here isn't stemmed -const STEMMERS = { - en: natural.PorterStemmer, - de: natural.PorterStemmerDe, - es: natural.PorterStemmerEs, - fa: natural.PorterStemmerFa, - fr: natural.PorterStemmerFr, - id: natural.StemmerId, - it: natural.PorterStemmerIt, - nb: natural.PorterStemmerNo, - nl: natural.PorterStemmerNl, - nn: natural.PorterStemmerNo, - no: natural.PorterStemmerNo, - pt: natural.PorterStemmerPt, - ru: natural.PorterStemmerRu, - sv: natural.PorterStemmerSv, - uk: natural.PorterStemmerUk +// The stemmers, by primary language subtag: the best that the natural package has, by class name. A +// language that isn't here isn't stemmed +const STEMMER_CLASSES = { + en: 'PorterStemmer', + de: 'PorterStemmerDe', + es: 'PorterStemmerEs', + fa: 'PorterStemmerFa', + fr: 'PorterStemmerFr', + id: 'StemmerId', + it: 'PorterStemmerIt', + nb: 'PorterStemmerNo', + nl: 'PorterStemmerNl', + nn: 'PorterStemmerNo', + no: 'PorterStemmerNo', + pt: 'PorterStemmerPt', + ru: 'PorterStemmerRu', + sv: 'PorterStemmerSv', + uk: 'PorterStemmerUk' }; +const STEMMERS = Object.fromEntries(Object.entries(STEMMER_CLASSES).map(([lang, cls]) => [lang, natural[cls]])); const NO_STEMMER = { stem: (word) => word }; @@ -97,6 +98,18 @@ function hasStemmer(lang) { return Object.prototype.hasOwnProperty.call(STEMMERS, languageOf(lang)); } +/** + * The name of the stemmer for a language, as a terminology file's word index records it (meta + * ix.ix_word.stemmers): 'natural:' for a stemmer of the natural package, 'none' for a + * language without one (a word is its own stem) + * @param {string|Object|null} lang - a tag or a Language + * @returns {string} + */ +function stemmerName(lang) { + const l = languageOf(lang); + return Object.prototype.hasOwnProperty.call(STEMMER_CLASSES, l) ? 'natural:' + STEMMER_CLASSES[l] : 'none'; +} + /** * A text in lower case without accents (see the module comment) * @param {string} text @@ -574,6 +587,6 @@ function lowerBound(sorted, value) { module.exports = { STOP_WORDS, MAX_TEXT, MAX_WORDS, TEXT_INDEX_TOKENIZE, - languageOf, stemmerFor, hasStemmer, fold, words, stem, + languageOf, stemmerFor, hasStemmer, stemmerName, fold, words, stem, TextQuery, NameIndex, indexColumns, createTextIndexSql, isTextIndexSql, lowerBound, bestRanks }; diff --git a/tx/sct/structures.js b/tx/sct/structures.js index 7b292483..6d84f677 100644 --- a/tx/sct/structures.js +++ b/tx/sct/structures.js @@ -240,7 +240,24 @@ class SnomedReferences { post() { if (this.builder) { - this.master = Buffer.concat([this.master, ...this.builder]); + // Append into a buffer with spare capacity. Buffer.concat here copied the whole of master + // on every call, and the closure build calls this once per concept + const used = this.master.length; + let pending = 0; + for (const record of this.builder) { + pending += record.length; + } + if (!this.store || this.store.buffer !== this.master.buffer || used + pending > this.store.length) { + const grown = Buffer.allocUnsafe(Math.max((used + pending) * 2, 1 << 20)); + this.master.copy(grown, 0); + this.store = grown; + } + let at = used; + for (const record of this.builder) { + record.copy(this.store, at); + at += record.length; + } + this.master = this.store.subarray(0, at); this.builder = []; this.currentOffset = this.master.length; // UPDATE: offset to new master length } @@ -253,6 +270,7 @@ class SnomedReferences { this.master = Buffer.concat([this.master, ...this.builder]); this.builder = null; + this.store = null; // the spare capacity post() kept this.currentOffset = 0; // RESET: for potential future builds } diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 27eb14db..85aa391a 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -1,9 +1,12 @@ -# sqlite-v2: terminology files +# sqlite-v2: terminology files (tx-terminology/1, revision fhir-reading) -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`. +A terminology file holds one code system version in one SQLite file. The importers in +`tx/importers/` write it; the providers in `tx/sqlite-v2/` serve it. The schema is +`tx/importers/sqlite-v2/schema.sql`. + +This document is the format. It describes the revision named `fhir-reading`: every file of it says +`format` = `tx-terminology/1`, `PRAGMA user_version = 1`, and `requires` = +`["identifier-text", "fhir-reading"]`. Files written before it are refused (see "Identification"). RxNorm is served only this way. Its earlier provider (`tx/cs/cs-rxnorm.js`) and importer (`tx/importers/import-rxnorm.module.js`, with `rxnorm-text-index.js`) were removed once @@ -12,9 +15,40 @@ behaviour that was carried over from it (git history has the file). The tests th two now compare sqlite-v2 with that provider's answers, recorded before it was removed (`tests/data/rxnorm-v1-answers.json`). -## The model +## Layers + +Each fact in a file belongs to one of four layers. + +| layer | what it is | where | who writes it | can a tool rebuild it | +|---|---|---|---|---| +| source material | what the release says, under the release's own names and values | `concept` (id, code), `item`, `link`, `literal`, `identifier`, `record`, `mapping`, `value_label`, `code_system`, `resource`, `node_extra` | importer | no | +| the FHIR reading | how the source material maps to FHIR notions, one place per notion, the same shape for every terminology | `property` (reporting columns), `item_use`, `filter`, meta `conceptStatus`, `expansionLimits`, `order`, `search`, `version`, `implicitValueSets`, `implicitMaps`, `grammar`, `compatibility`, `codeLink` | importer | no | +| derived | computed from the two layers above | `concept.active` (when `conceptStatus` gives any value the meaning `inactive`), `concept.display`, `item.rank`, the concept numbering (active first), every `ix_*` table | importer and index builder | yes | +| named procedures | what needs an algorithm, named in the file | `grammar` values, the text-match rules (`ix.ix_word.format`), stemmer names | reader code | n/a | + +A reader has general rules only. It has no table, fallback or branch keyed on a code system's +URI or name: what differs between terminologies is in the file. A reader obeys every key and +column it accepts, or refuses the file. + +The FHIR reading maps these FHIR notions: + +| FHIR notion | where the file maps it | maps from | +|---|---|---| +| concept status (`inactive`, `deprecated`, `notSelectable`, and `unlisted`) | meta `conceptStatus` | values of a source literal | +| `CodeSystem.property` and how `$lookup` / expansions report it | `property` rows | source properties | +| `designation.use`, which names are displays | `item_use` rows | the source's kinds of name | +| `CodeSystem.filter` | `filter` rows | source properties, the hierarchy, the display | +| version matching, answer order, text search, expansion limits, implicit value sets and maps, code links | one meta key each | | +| an upstream provider's answer where it differs from FHIR | meta `compatibility` | | + +RxNorm is served only this way. Its earlier provider (`tx/cs/cs-rxnorm.js`) and importer +(`tx/importers/import-rxnorm.module.js`, with `rxnorm-text-index.js`) were removed once +`rxnorm-v2` was live (Dec 2026). The comments here that say "as cs-rxnorm.js" describe the +behaviour that was carried over from it (git history has the file). The tests that compared the +two now compare sqlite-v2 with that provider's answers, recorded before it was removed +(`tests/data/rxnorm-v1-answers.json`). -A file holds one code system version as **nodes**, a **catalog** and **statements**. +## The model - **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 @@ -26,31 +60,50 @@ A file holds one code system version as **nodes**, a **catalog** and **statement |---|---|---|---| | 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) | + | 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 | | 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. + a `record`. A property can have both links and literals (shape `both`). +- **The catalog** (`property`) has one row per source property, reference set, identifier scheme + and relation, plus rows that exist only in the FHIR reading (shapes `item-use`, `mapping`, + `reading`). It says where the rows are (shape, `inverse_of`, unions through `property_member`, + `closure_from`, `ordered`, `by_target`, `by_subject`, a record's field schema) and how the + property is reported (below). Readers never probe tables to find out. +- **Facts and indexes.** The `ix_*` tables are derived and can be dropped and rebuilt from the facts + (`tx/importers/sqlite-v2/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`. +- **Statistics.** A file carries `sqlite_stat1` and no `sqlite_stat4`: with stat4 SQLite re-plans a + `col = ?` statement on every bind. Readers never run `ANALYZE` or `PRAGMA optimize`. + +## Identification + +- meta `format` = `tx-terminology/1`, `PRAGMA user_version = 1`. +- meta `requires` (JSON list) names the features a reader must understand. A reader refuses a file + that requires a feature it does not know, and says which. This revision's files require exactly + two: + + | feature | meaning | + |---|---| + | `identifier-text` | `identifier.value` (and `ix_by_subject.value`) is declared `TEXT`: every value is text. A reader binds identifier probes as text, lists passed through `json_each` included. | + | `fhir-reading` | the file has the tables, columns and meta keys of this document, and none of the earlier revision's. | + +- A file whose `requires` lacks `fhir-reading` is refused: `: a terminology file written + before the fhir-reading revision; re-import it with the importers (tx-import), or upgrade it`. + There is no reading of the earlier keys. +- A file of this revision with any meta key starting `behaviour.`, or `linkOrder`, + `searchTieBreak`, `propertyUris`, `ix.ix_word.names`, or with a `property` column `filterable`, + `filter_ops`, `report`, `reported_as`, `named_links`, `name_any_case`, `value_any_case`, + `default_value`, `match_display`, `selects_members`, `n_rows`, `target_kind`, or an `item_use` + column `reported_as`, is refused: that is a writer's mistake. +- A reader ignores a meta key it does not know. A known key with a malformed value refuses the file, + naming key and value. `provenance.*` is free-form and never read. +- A reader that does not implement a value this document allows (a `grammar` it has no code for, a + `compatibility` member, ...) refuses the file and names the key and value. It never reads the file + with that key ignored. +- A builder checks every key it writes against its own list and refuses to finish a file with a key + it does not know. ## Tables @@ -58,111 +111,671 @@ 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 | +| `code_system` | the served system (`served = 1`; other rows only for sources that contribute items): uri, version, name, title, description, `release_date`, content, `case_sensitive`, `hierarchy_meaning` (CodeSystem.hierarchyMeaning; a value other than `is-a` makes `$subsumes` refuse, as upstream does), `default_language`, `compositional` (codes may be expressions: no expansion is closed), counts, `resource` (a CodeSystem resource without concepts: the id a server serves the system under is `resource.id` as it is, its catalog name `resource.name`, else `name`; `resource.copyright` is what `compatibility.lookupListsCopyright` lists) | +| `meta` | key -> text: the format, `requires`, release facts with no column, the FHIR reading's keys, facts about indexes (`ix.*`), `provenance.*` | +| `concept` | id, code, active (see "Concept status"), display (derived by the importer) | +| `item` | id (> N), concept, kind (0 term, 1 definition), external id (description SCTID, RXAUI: INTEGER when a canonical decimal integer, else TEXT), language, use (`item_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 | +| `item_use` | the kinds of name (below) | +| `property`, `property_member` | the catalog (below); a union property's members | +| `filter` | the filters the system understands (below) | | `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) | +| `literal` | subject, property, role group, value, active, seq (source order among the subject's values of the property; NULL as 0; read only through `order.literals` `stored`, so a file written before the column is read as before) | +| `identifier` | property (the scheme), value (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. A probe for codes that are identifiers says `resolves > 0` as well as `value = ?` (the partial index `identifier_code`) | +| `record` | relation, subject, seq, 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 number is a node id of this file, a string a code that is not in it) | +| `value_label` | displays of literal values (LOINC CLASSTYPE `1` = `Laboratory class`) | +| `mapping` | maps to other systems: concept, `property_id` (the `mapping`-shape row that reports it in `$lookup`; NULL: not reported), system, version, code, display, `relationship` (FHIR R4 ConceptMap equivalence: `equivalent`, `wider`, `narrower`, `relatedto`, ...) | +| `resource` | resources the release defines that cannot be derived from its facts | +| `node_extra` | FHIR extensions of a node, for round trip | 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_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, 6 has property (for an inverse row: the targets of what it reverses), 7 record members. Kind 5 sets exist for: the properties a `filter` row reads by code (the members of a union it reads too; a `{1}` row: every link, literal, both, union or identifier row whose code its capture group matches), the literals a `where_literal` names, the `refinable` properties, the hierarchy property (`subsumption = 1`: its sets are each concept's children, for `child-of` and the hierarchy walk), and the properties `conceptStatus` names. A closure source (LOINC `ancestor`) has none: its pairs are the kind 4 sets | +| `ix_in` | links by target, for the properties with `by_target = 1` (`seq`: `link.seq`, or 0) | +| `ix_by_subject` | identifier rows by subject, for the properties with `by_subject = 1` | +| `ix_order` | per-concept arrays in 1,024-entry blocks (little-endian u32): `rank`, `ids` (the stored order), `walk` (the whole system in the stored walk order; `ix.ix_order.walk.reached` in meta), `active`, `hier_start` / `hier` (LOINC parent and child entries) | | `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_word` | the text-search word index per language over the names `search.names` selects: word, stem, concept bitmap; with `search.shortlist`, the row with word `''` holds per-concept distinct-word counts (unsigned 16-bit little-endian, `2 * (N + 1)` bytes) | | `ix_text_display`, `ix_text_item` | FTS5 trigram indexes over displays and item texts (regex prefilter) | -## Behaviour settings +## property: the catalog -`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). +One row per source property, relation and identifier scheme, under the source's name (`code`), plus +rows that exist only to report something (shapes `item-use`, `mapping`, `reading`). -| key | values | default | written by | +| column | values | NULL / default | meaning | |---|---|---|---| -| `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 did) | -| `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 | +| `code` | text | required | the source's name (`116680003`, `STATUS`, `TTY`) | +| `fhir_code` | text | `code` | the name it is reported under and asked for by (SNOMED CT `116680003` is reported as `parent`) | +| `also_asked_as` | JSON list of names | `[]` | further names a `$lookup` or expansion request may use for it (SNOMED CT `moduleId` also as `module`); never a filter name | +| `uri`, `display` | text | none | `CodeSystem.property.uri` / `description`; `display` is also the `code-display` part (below) | +| `shape` | `link`, `literal`, `both`, `identifier`, `record`, `union`, `item-use`, `mapping`, `reading` | required | where its values are | +| `role` | `language`, `status` | none | `language`: a relation on items that ranks displays (SNOMED CT language reference sets); `status`: the literal that holds the status text (at most one row) | +| `fhir_type` | FHIR type | `code` | `CodeSystem.property.type`; a literal without a `presentation` is reported in this type (`dateTime`: an 8-digit `YYYYMMDD` as `YYYY-MM-DD`; `date` (OMOP) as a `dateTime`: a concept property has no date value) | +| `lookup` | `default`, `named`, `never` | `default` | `$lookup`: listed with no `property` parameter (`default`), only when asked for by name or `*` (`named`), not at all (`never`) | +| `expansion` | `asked`, `always`, `never` | `asked` | expansion rows: when asked for by name or `*`, on every row, or never | +| `lookup_rank` | integer >= 0 | after every ranked row | its place among the properties `$lookup` lists | +| `expansion_rank` | integer >= 0 | after the ranked rows | its place in an expansion that asks for `*` | +| `true_value` | text | none | reported as a boolean: true when the value (a link's target code, a literal's value) equals this (SNOMED CT `definitionStatusId` -> `sufficientlyDefined` true for `900000000000073002`) | +| `presentation` | JSON `{value?: code, string, display, coding; parts?: [description, code-display, partCode, equivalence, version]}` | none | the value's form and extra parts: `description` the target's display (or a literal's `value_label`), `code-display` what the property is called (`display`, else the display of the concept whose code is the property's code, else the code), `partCode` the target's code; on a `mapping` row only: `equivalence` (each value carries the subproperty `equivalence`, the row's `mapping.relationship`), `version` (the Coding carries `mapping.version` when the row has one) | +| `value_system` | a system URI | none | an identifier scheme's values are codes of this system (reported as a Coding) | +| `internal` | 0, 1 | 0 | 1: storage only (RxNorm `has_precise_ingredient@RN`, `AUI:has_ingredient`); never reported or declared, and never a filter's name (a filter row may read it) | +| `alias_parameter`, `alias_extension`, `alias_literals` | text / JSON | none | identifier rows only: how a code read through an alias identifier is reported (ICD-11, NDC); see "Alternate codes" | +| structural columns | `concept_id`, `subject_kind`, `subsumption`, `closure_from`, `refinable`, `wildcard`, `inverse_of`, `by_target`, `by_subject`, `ordered`, `fields` | | the hierarchy (`subsumption = 1`, at most one row), explicit ancestor pairs (`closure_from`), ECL attributes (`refinable`, `wildcard`), virtual inverse rows (`inverse_of`), an ordered list property (`ordered = 1`, at most one link row), record field schemas | + +The three shapes without rows of their own: + +- `item-use`: the values are the texts of the active items whose use has `item_use.as_property` = + this row's `code`, each with its language, in item rank then id order. Example: LOINC + `RELATEDNAMES2`, so `$lookup` of `2160-0` lists `{"code": "RELATEDNAMES2", "value": "Creat; ...", "language": "en-US"}` and no such designation. +- `mapping`: the values are the `mapping` rows whose `property_id` is this row, each a Coding + (`system`, `code`, `display`), ordered by system then code; with the `presentation` part `version` + the Coding carries the row's `version` when it has one, with the part `equivalence` each value + carries the subproperty `equivalence`. Example: LOINC `sct` (12 such rows, one per implicit map key, + each with both parts). +- `reading`: a FHIR status property computed from `conceptStatus` (`code` `inactive`, `deprecated` + or `notSelectable`, `fhir_type` `boolean`): `true` when the concept has that meaning, no value + otherwise (ICD-11 `notSelectable`). + +## item_use: kinds of name + +| column | meaning | |---|---| -| 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 | +| `system`, `code`, `display` | the use's Coding, as a designation reports it | +| `role` | `fsn`, `synonym` (SNOMED CT description types: the `display regex` filter reads these designations), `display` (the use's texts are accepted as a display by `$validate-code`; LOINC `LONG_COMMON_NAME`, `SHORTNAME`, `LinguisticVariantDisplayName`); NULL: none | +| `as_property` | the code of an `item-use` property row: the items of this use are that property's values, not designations (LOINC `RELATEDNAMES2`); at most one use per row | +| `language_display_rank` | the use gives the display in a requested language, in this order (LOINC `LONG_COMMON_NAME` 1, `SHORTNAME` 2, `DisplayName` 3; see "Display in a requested language") | + +## filter: the filters a system understands + +`CodeSystem.filter`, complete: a filter that no row understands is `FILTER_NOT_UNDERSTOOD` (422, +`The filter "{name} {op} {value}" is not understood or supported`). Filter names never come from +`property.also_asked_as`. + +| column | values | NULL / default | meaning | +|---|---|---|---| +| `id` | integer | | the order `CodeSystem.filter` lists them in | +| `code` | text | | the filter's name (exactly one of `code`, `code_pattern`) | +| `code_pattern` | regular expression | | a name matching it in full; group 1 is the capture `{1}` (SNOMED CT `^([0-9]{6,18})$`: an attribute named by its id) | +| `code_any_case` | 0, 1 | 0 | the name may be written in any case (RxNorm `tty`) | +| `description` | text | | `CodeSystem.filter.description` | +| `operators` | JSON list of FHIR filter operators, and `of` | required | the operators this row takes; two rows with one `code` have disjoint operators (LOINC `answers-for`), or share operators other than `exists` and have value prefixes no value has both of (neither starts with the other; RxNorm `CUI:` and `AUI:`). `of` is no filter operator: it offers VCL `of` and set-valued `in` on the row (below); a filter with the operator `of` is never understood by it | +| `reads` | JSON string or list | required | what the filter selects by (below); a list is the union | +| `allowed_values` | JSON list, or `"codes"` | any value | the only values accepted; `"codes"`: every value must be a code of the file | +| `value_prefix` | text | none | every value starts with this, removed before matching (RxNorm `CUI:`). Rows of one name that share an operator: each value is read by the row whose prefix it has (RxNorm `has_ingredient = AUI:828` by the `AUI:` row) | +| `value_case` | `any`, `exact` | `any` | a value matches a stored literal ignoring case, or exactly | +| `value_as_display` | 0, 1 | 0 | a value may also be a link target's display, or a literal's value label (ignoring case) | +| `where_literal` | JSON `{literal property: value}` | none | the selection is also cut to concepts with each value (exact) | +| `then_link` | a link property code | none | the result is the targets of these links from what was read, in the order of what was read, then `link.seq` | + +Values: `in` / `not-in` take a comma-separated list (items trimmed, empty ones dropped; at least one +must remain); every other operator one non-empty value; `exists` takes `true` or `false`. A value +outside `allowed_values`, or (operators other than `exists`) without the `value_prefix`, is not understood; +where several rows take the name and operator, a value with none of their prefixes is not understood, +and `in` (`not-in`) is the union of (the listed concepts minus) each row's selection of its values. + +What a row reads, for one value x (`in`: the union over the values; `not-in`: the listed concepts +minus the `in` selection; every selection is cut to the listed concepts, see "Concept status"): + +| `reads` | `=` | `exists` | `regex` (whole text, case-sensitive) | hierarchy operators | +|---|---|---|---|---| +| a link, union or inverse property | concepts with a link to the concept coded x (with `value_as_display`, else to the concepts whose display is x, ignoring case) | with / without a link | the targets' displays | | +| a closure source (`closure_from` of the hierarchy) | the strict descendants of x (its pairs are the descendants sets) | | | | +| a literal property | concepts whose value is x (by `value_case`; labels with `value_as_display`; FHIR search prefixes `ge5` on integer, decimal, dateTime) | with / without a value | the stored values, or their labels where the property has `value_label` rows | | +| a `both` property | a code of the file: as a link; else as a literal | | | | +| an identifier property, or a union of identifier properties | the subjects of its identifiers whose value is x (a union: of each member's) | with / without an identifier of the scheme (not a union) | | | +| `concept` | the concept x (`in`: a concept that defines a record relation contributes its members, none when it has no active ones; one whose relation has role `language`, whose members are items, is refused, 400 `invalid`, as ECL `^` is for it) | | the code | `is-a`, `descendent-of`, `is-not-a`, `descendent-leaf`, `child-of`, `generalizes` by the hierarchy | +| `inactive` | `true`: inactive concepts; `false`: active ones | | | | +| `display` | `concept.display` is x | | `concept.display` | | +| `designations` | | | an active designation whose use has role `fsn` or `synonym`, in the text-search language | | +| `grammar` | what the grammar defines (SNOMED CT `constraint` = ECL, `expressions`) | | | | +| `{1}` | as the property whose code is the captured text; none, or another shape: nothing | | | | + +An unknown concept x on a `concept` row selects nothing (the server's expansion notes it), unless the +grammar makes it an error. + +`then_link` order: a row whose `reads` names a property (LOINC `answers-for`) lists the concepts it +read in `order.expansion` order, each one's links by `link.seq`, a target reached twice once, at its +first place; a row that reads `concept` alone (LOINC `LIST`) lists its selection in the order of any +other selection (LOINC: the stored rank, as cs-loinc.js's `LIST =`); the `enumerate` of an implicit +value set lists the list's targets in `link.seq` order. + +VCL `of` and set-valued `in` are offered for a row whose `operators` contain `in` or `of` and whose +`reads` is one property code (link, union, literal, both), `{1}` or `concept`; nothing else. A row whose +only operator is `of` names no filter and is not listed in a generated `CodeSystem.filter`, which lists +one `filter` per row with `code`, its operators without `of`. (The JS server hands VCL `of` to the code +system as the filter `=` with the R6 operator extension, which it does not read: VCL `of` is not +implemented by this server.) + +Example, LOINC (`answers-for` as two rows): + +``` +code operators reads other +answers-for ["=","in"] ["concept","answers-for"] then_link Answer +answers-for ["regex","exists"] "answers-for" value_as_display 1 +STATUS ["="] "STATUS" allowed_values ["NotStated","ACTIVE","DEPRECATED",...] +LIST ["="] "concept" allowed_values "codes", then_link Answer +``` + +`answers-for = LL6136-7` reads the list itself and the lists that answer it, then their `Answer` +links: the list's answers in their sequence. `STATUS = Active` (not one of the allowed values) is not +understood, and neither is `refset = LL6136-7` (no row has that name; upstream's LOINC provider has no +such filter, so a list's answers are asked for with `LIST` or `answers-for`). + +## Meta keys + +Every value below is JSON. An absent key has the default. + +| key | default | section | +|---|---|---| +| `conceptStatus` | `[]` | Concept status | +| `expansionLimits` | `{}` | Expansion limits | +| `order` | `{}`: each member its default | Order | +| `search` | absent: no text search | Text search | +| `version` | `{"match": "exact"}` | Versions | +| `implicitValueSets` | `[]` | Implicit value sets | +| `implicitMaps` | `{}` | Implicit maps | +| `grammar` | absent: plain codes | Grammar | +| `compatibility` | `{}` | Compatibility | +| `codeLink` | absent: no link | Code links | + +Release facts and facts about indexes: + +| key | value | meaning | |---|---|---| -| `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. +| `languages` | JSON list of tags | the languages of the served system's items | +| `displayContexts` | JSON `{relations, preferred, use}` | the language relations that rank displays (SNOMED CT; read by the `snomed` grammar) | +| `moduleDependencies` | JSON list of `[module, target module, effective time, target effective time]` | SNOMED CT module dependencies | +| `edition` | text | the SNOMED CT edition (module id) | +| `titles` | JSON object, language -> title | the system's title per language | +| `derived-by-importer` | JSON list of `{table, name}` | index rows the importer writes (`ix_order` arrays, `ix_key` normal forms) | +| `integrity` | JSON `{items, schema, catalog}` | facts a tool checks on request (below) | +| `ix.ix_word.format` | text | the word index's rules (`text-match/1`) | +| `ix.ix_word.stemmers` | JSON object, language -> stemmer name | the stemmer that made each language's `stem` column | +| `ix.ix_order..reached` | decimal integer | how many concepts a stored walk reaches | +| `ix.ix_key..stats` | JSON | informational (SNOMED CT normal forms written, failed, seconds) | + +## Concept status + +```json +"conceptStatus": [{"property": "", "values": {"": ["", ...]}}] +``` + +Each entry names a literal property; each listed value has meanings: `inactive`, `deprecated`, +`notSelectable` (FHIR's concept properties) and `unlisted`. A value not listed means nothing; a +concept without a row of the property gets nothing from that entry. At most one entry per property. + +A concept's **readings** are the meanings of the values of its rows of each entry's property, minus +those `compatibility.statusReadingsIgnored` lists. + +- **inactive**: `concept.active = 0`. When some entry gives a value the meaning `inactive`, the + writer stores `concept.active = 0` for exactly the concepts whose readings contain it (derived: + after an edit of `conceptStatus` or `statusReadingsIgnored` the file is rebuilt, which renumbers + the concepts, active first). Otherwise `concept.active` is source material (SNOMED CT's RF2 flag). +- **deprecated**: the readings contain `deprecated` and the concept is not inactive. +- **notSelectable**: the readings contain it. It is the concept's `abstract` in `$lookup` and + `$validate-code`; `excludeNotForUI` leaves it out. +- **unlisted**: the readings contain it. The concept is found by `$lookup`, by `$validate-code` + against the code system, and by a compose include that lists it by code. It is never in an + include of the whole system in `$expand`, a filtered include, a count of the system's concepts, a + hierarchy walk, or a text search. +- **Status text**: the value of the concept's `role = 'status'` literal as stored when it has one + (LOINC `ACTIVE` included); else `inactive` for an inactive concept; else none. Where an operation + reports it is the operation's rule, not the file's: an expansion row's `status` is the status text + unless it is `active` (ignoring case), and `deprecated` when none is reported and the concept is + deprecated; `$validate-code` reports it as `status` for an inactive concept unless it is + `inactive`, and the `INACTIVE_CONCEPT_FOUND` text names it. + +Examples: + +```json +// LOINC: DISCOURAGED is inactive, DEPRECATED inactive and deprecated +[{"property": "STATUS", "values": {"DISCOURAGED": ["inactive"], "DEPRECATED": ["inactive", "deprecated"]}}] +// with "compatibility": {"statusReadingsIgnored": [{"property": "STATUS", "values": {"DEPRECATED": ["inactive"]}}]} + +// RxNorm: obsolete concepts are inactive; archived ones (only in RXNATOMARCHIVE) also unlisted +[{"property": "status", "values": {"obsolete": ["inactive"], "archived": ["inactive", "deprecated", "unlisted"]}}] + +// ICD-11 MMS: blocks, chapters and windows cannot be selected +[{"property": "classKind", "values": {"block": ["notSelectable"], "chapter": ["notSelectable"], "window": ["notSelectable"]}}] +``` + +What LOINC's entry makes a server answer: `$validate-code` of `101155-0` (STATUS `DISCOURAGED`, +stored inactive) returns `inactive` true and `status` `DISCOURAGED`; of `14320-6` (STATUS +`DEPRECATED`) returns no `inactive` and `status` `deprecated`, because the compatibility member +removes the `inactive` reading of `DEPRECATED` (upstream's LOINC provider treats only DISCOURAGED as +inactive) and the concept is stored active. Removing that member, and rebuilding the file, makes the +6,018 DEPRECATED concepts of LOINC 2.83 inactive (and so not deprecated). + +## Designations and display + +**The designation list** of a concept: its items with `kind = 0` or a use, whose use has no +`as_property`, in item `rank` order (NULL last), then item id; active and inactive (an inactive item is +listed with status inactive and is a retired display for `$validate-code`). Each designation has the +item's text and language, and as use the use's Coding (with `compatibility.designationUse` `source`, +the default), else `preferredForLanguage` +(`http://terminology.hl7.org/CodeSystem/hl7TermMaintInfra`) for an item with `preferred = 1`, else +none. + +**The display designation**: `concept.display`, use none in the list (`preferredForLanguage` where a +designation needs one), language `code_system.default_language`, else `en`. No item is consulted: an +item equal to the display may be in another language (LOINC 2.83 part LP7786-9 "CHEM" has a `cs-CZ` +PartName equal to its display; upstream answers `en-US`). On the built files: `en-US` for LOINC, +RxNorm and SNOMED CT (which lists no display designation), `en` for UNII, CPT, NDC, OMOP and ICD-11. + +`compatibility.displayDesignation` places it: + +| value | the list | +|---|---| +| `none` (default) | the designations only | +| `once` | the display designation first; a later designation with the same text as one already listed is dropped | +| `always` | the display designation first, then every designation | + +**Definitions**: the text of the concept's first `kind = 1` item with `preferred = 1`, unless +`compatibility.lookupOmitsTextDefinitions`. + +**Display in a requested language**: `concept.display` is the display. When the request asks for +display languages, some use has `language_display_rank`, and a requested language is not the +display designation's (by primary subtag): the candidates are the display designation, then the +items whose use has `language_display_rank`, in that rank. For exact matching, then by primary +subtag, for each requested language in order, the first candidate in that language is the display. +Example: LOINC `$lookup` of `2160-0` with `displayLanguage=de` returns the German +`LONG_COMMON_NAME` item where there is one. A grammar may rank displays itself (SNOMED CT: +`displayContexts`). + +**`$validate-code` display check**: a display is valid when it equals, ignoring case, +`concept.display` or a designation in a requested language. The alternatives listed in an error are +the designations with no use, `preferredForLanguage`, or a use with role `display`, `fsn` or +`synonym`. + +## Properties in `$lookup` and expansions + +Which rows are reported: + +- never a row with `internal = 1`, shape `record`, or role `language`; +- `$lookup` with no `property` parameter: the rows with `lookup = 'default'`; with `property` + parameters, the rows whose `fhir_code` (else `code`) or an `also_asked_as` name equals one + (ignoring ASCII case), and with `*` every row with `lookup` `default` or `named`; +- expansion rows: the rows asked for by name or `*` with `expansion` `asked` or `always`, plus every + `always` row. + +A row is reported under its `fhir_code` (else `code`); a property lists one target once. + +**`$lookup` order**: every reported value gets one key, compared in order: + +1. the row's `lookup_rank` (unranked after every ranked row); +2. links (inverse links too), then literals, identifiers, mappings, item-use values, readings; +3. links by meta `order.links`, literals by `order.literals`, identifiers by name then value, + mappings by system then code, item-use values by item rank then id; +4. the reported name, then the value, as binary text. + +`compatibility.lookupRankWhenConceptHas` changes a row's rank for some concepts (NDC: a package lists +its FDA rows before its product's). + +Example, LOINC: `CLASS` 0, `COMPONENT` 10 ... `METHOD_TYP` 60, every other link 80, `answers-for` 85, +`parent` and `child` 90, the literals 100, `STATUS` 110, `RELATEDNAMES2` 120, the twelve map keys +130; `order.links` `["stored", "property-id", "group", "code"]` lists an answer list's answers in their +sequence (`link.seq`; an inverse link takes the seq of the link it reverses). + +**Expansion rows**: properties named in the request are listed in the request's order; `*` lists the +rows with `expansion_rank` first, then the rest in the `$lookup` order. An expansion declares +(`expansion.property`) each listed row that has a `uri`, unless +`compatibility.expansionDeclaresProperties` is false. + +## Alternate codes + +An identifier with `resolves` 1 or 2 is accepted as a code wherever a code is (a concept code +always wins): by `$lookup`, `$validate-code`, a compose's `concept` list and a filter value. With +`resolves` 1 (an alias: ICD-11 short codes) the code is answered with its concept's code (an +expansion lists the concept's code); with 2 (a code in its own right: NDC's 11-digit forms) as +written. The identifier's scheme (its `property` row) carries how such a code is reported: + +- `alias_literals` (JSON `{fhir code: template}`; NDC `{"code-type": "11-digit", "synonym": "{code}"}`): + a code read through an identifier of the scheme with `resolves` 2 reports these values for those + properties instead of its concept's stored ones (`{code}`: the concept's own code). A filter on + such a property whose value is a template's (one without `{code}`: `code-type = 11-digit`) lists + the scheme's identifiers with `resolves` 2 for which every filter of the include holds (on such a + property: the template's value; on any other: the concept's own), in the order of their concepts + (the expansion order), then by value, after the concepts the filters select by their stored + values (NDC: none). A membership check of such a code tests the same way, filter by filter: a + package's 11-digit form is in `kind = package` and `code-type = 11-digit`, and not in + `code-type = 10-digit`. +- `alias_parameter` (the name of an output parameter; this server reports `classificationCode` + only, and refuses another name): the concept's identifier of this scheme with `resolves` 1 (the + least value) is the code's classification-code form. `$validate-code` of a code written as its + concept's code (an expression: every part so written) returns it as that parameter, and an + expansion's membership check of a code written another way reports the normal form. +- `alias_extension` (a URL): a Coding extension of this URL restates the code's alias form, and + `$validate-code` checks it: `ICD11_CLASSIFICATION_CODE_SYSTEM` when no scheme of the file has + `alias_parameter` (ICD-11 Foundation), `_NOT_ID` beside a code not written as its concept's code, + `_NONE` for a code without an alias form, `_WRONG` when it differs. + +## Expansion limits + +```json +"expansionLimits": {"maxCodes": 1000, "wholeSystem": "refuse"} +``` + +| member | values | default | meaning | +|---|---|---|---| +| `maxCodes` | integer >= 1 | none | an expansion lists or walks at most this many codes of the system; the rest are dropped with the warning `VALUESET_EXPANSION_CODESYSTEM_LIMITED` (CPT 1000) | +| `wholeSystem` | `list`, `refuse` | `list` | `refuse`: an `$expand` with an include of the whole system is refused (500, `exception`), with the text of `compatibility.wholeSystemRefusalMessage` or `The code system {system} cannot be expanded as a whole`, also as the issue's `diagnostics`; `count=0` of one include and no exclude is still counted (OMOP) | + +## Order + +```json +"order": {"expansion": ["stored"], "searchTies": ["display", "stored"], "links": ["stored", "property-id", "group", "code"], "literals": ["property-id", "group", "value"]} +``` + +Each member is a list of words compared left to right; a final tie makes the order total. + +| member | words | default | final tie | +|---|---|---|---| +| `expansion` | `id`, `stored`, `code` | `["id"]` | concept id | +| `searchTies` | `id`, `stored`, `code`, `code-number`, `display` | `["id"]` | concept id | +| `links` | `property-id`, `property`, `group`, `stored`, `code`, `code-number` | `["property-id", "group", "code"]` | property id, group, target code, target id | +| `literals` | `property-id`, `property`, `group`, `stored`, `value` | `["property-id", "group", "value"]` | property id, group, value | + +| word | concepts | links | literals | +|---|---|---|---| +| `id` | concept id | | | +| `stored` | `ix_order` `rank` (the file must have `rank` and `ids`) | `link.seq` (NULL as 0); an inverse link takes the seq of the link it reverses, and inverse links of one seq keep the order of the links by target (`ix_in`: then the subject's id) | `literal.seq` (NULL as 0; the file must have the column) | +| `code` | code as binary text | target code as binary text | | +| `code-number` | code as an unsigned integer: shorter digit strings (without leading zeros) first, then binary text | the same on the target code | | +| `display` | `concept.display` in the Unicode root collation | | | +| `property-id` | | property id | property id | +| `property` | | the reported name as binary text | the same | +| `group` | | role group | role group | +| `value` | | | numbers numerically, text as binary text | + +An expansion nests a row under its parent where expand.js would (the system has a hierarchy and not +`expansionNeverNests`, no `excludeNested`, no offset, every row on the page; the JS reader's own +selection: each include and exclude with one filter): the parent is the concept's first hierarchy link +by `order.links` (ICD-11 `is-a` lists a block with its codes inside it). + +Expansions: with `["stored"]`, an include of the whole system walks the stored `walk` (up to +`reached`) where the file has one; every other selection is listed in `rank` order. `["id"]`: +concept id; `["code"]`: code. A list of concepts written in the compose is listed in its own order. +With `compatibility.isAListsFocusFirst`, an `is-a` (or ECL `<<`) selection lists its focus first, +`child-of` lists the children in `ix_in` seq order, and `generalizes` (or ECL `>`) lists the ancestors +level by level from the concept's parents, each concept's parents in `link` seq order (ECL `>>`: the +concept last). When an include has several filters, the first one's order holds if it is one of these. Example: SNOMED CT `["stored"]` and +`isAListsFocusFirst`: `concept is-a 86273004` lists 86273004, then its descendants by code number. + +## Text search + +Absent `search`: the system has no text search, and an `$expand` with a text `filter` is refused +(422 `not-supported`, `TEXT_SEARCH_NOT_SUPPORTED`, `Text search is not supported for the code +system '{system}'`). + +```json +"search": {"names": {"display": "en", "items": {"active": true, "designations": true, "includeUses": [null, "x"], "excludeUses": ["y"], "language": "en"}}, + "candidates": {"active": true, "hasLiteral": {"property": "TTY", "except": ["SY"]}}, + "codeMatch": "number-prefix", "codeHits": "first", "nameScore": "as-written", + "shortlist": 200, "supplementsChooseLanguage": false} +``` + +| member | values | default | meaning | +|---|---|---|---| +| `names` | `display` (a language tag: each concept's display is a name in it), `items` {`active`, `designations` (only `kind = 0` or with a use), `includeUses` (use codes, `null` for no use), `excludeUses`, `language` (every item under this language; else its own, NULL as `code_system.default_language`)} | `{}`: no names | which texts are names | +| `candidates` | `active` (bool), `hasLiteral` {`property`, `except`} | every listed concept | which concepts may be hits (names and codes) | +| `codeMatch` | `text-prefix`, `number-prefix` | `text-prefix` | the query as a code prefix (written in upper and in lower case; identifiers with `resolves > 0` too), or as digits: the codes of digits whose value starts with the query's value (leading zeros ignored) | +| `codeHits` | `merged`, `first` | `merged` | an exact code scores 100, a prefix 90, combined with the name score by maximum; or code hits first (exact first, then by `code-number`) | +| `nameScore` | `distinct-words`, `as-written` | `distinct-words` | a name is scored on its distinct words, or as stored | +| `shortlist` | integer >= 1 | none | a one-word query scores only the candidates with the fewest distinct words (up to the n-th smallest count; at least 10); the others follow with score 0. The word index keeps the per-concept counts exactly when it is set | +| `supplementsChooseLanguage` | bool | `true` | whether a supplement in use can choose the search language | + +The procedure (rules of `tx/library/text-match.js`, named by `ix.ix_word.format` `text-match/1`): +the query's words in the search language; candidate concepts that have a name with every word (a +word matches the words it starts and those with its stem; one character only itself); a name scores 0 +unless it contains every word, 90 for an exact name, else 60/45/30/20 plus up to 10; a concept scores +its best name; concepts that score 0 are not hits (except the shortlist's tail); hits by score, then +`order.searchTies`. + +The search language: the first requested language the file has names in (or, with +`supplementsChooseLanguage`, an applied supplement has), else `code_system.default_language`, else +`en`. + +Examples: + +| system | `search` | ties | +|---|---|---| +| SNOMED CT | names: active designations; candidates active; `number-prefix`, codes `first`, `as-written`, shortlist 200, supplements do not choose the language | `["code-number"]` | +| LOINC | names: the display (en) and designations but `RELATEDNAMES2` | `["display", "stored"]` | +| RxNorm | names: designations, in `en`; candidates with a TTY other than SY | `["code"]` | +| UNII, CPT, NDC, OMOP | none (no text search) | | + +`ix.ix_word.stemmers` names, for each language of the word index, the stemmer that made its `stem` +column: `none`, `natural:` (`natural:PorterStemmer` for en), `snowball:`. A +reader that cannot reproduce a language's stemmer searches that language over the same names in +memory; the other languages keep the stored index. + +## Versions + +```json +"version": {"match": "prefix", "partial": "/version/", "describe": "release-date"} +``` + +| member | values | default | meaning | +|---|---|---|---| +| `match` | `exact`, `prefix` | `exact` | a requested version matches the file's when equal, or (`prefix`) when the file's starts with it (`2.8` matches `2.81`); no other rule (a file without `version` matches exactly, whatever `versionAlgorithm` its stored CodeSystem resource declares) | +| `partial` | a separator | none | a request whose version does not contain the separator names this file when the file's version starts with it followed by the separator (SNOMED CT: `http://snomed.info/sct/731000124108` names `.../version/20250901`); such a version is "less detailed" | +| `describe` | `release-date` | none | the version is described to people by `code_system.release_date` as `DD-Mon YYYY` (RxNorm `03022026` -> `02-Mar 2026`) | + +## Implicit value sets + +A list of templates, tried in order; the first whose `url` and `v` match answers. + +```json +[{"url": "http://loinc.org/vs", "include": {}, "name": "LOINC Value Set - all LOINC codes", "description": "All LOINC codes"}, + {"url": "http://loinc.org/vs/{v}", "v": "^LP", "mustBeCode": true, + "include": {"filter": [{"property": "ancestor", "op": "=", "value": "{v}"}]}, + "name": "LOINCValueSetFor{v_}", "description": "LOINC value set for code {v}: {display}"}, + {"url": "http://loinc.org/vs/{v}", "v": "^LL", "mustBeCode": true, "enumerate": {"property": "LIST", "op": "=", "value": "{v}"}, + "name": "LOINCAnswerList{v_}", "description": "LOINC Answer list for code {v}: {display}"}] +``` + +| member | meaning | +|---|---| +| `url` | the value set URL; `{v}` stands for the rest of the requested URL | +| `v` | a regular expression `{v}` must match (search) | +| `mustBeCode` | `{v}` must be a code of the file, else the URL names no value set | +| `include` | the compose include (system the file's; no `version` unless the template sets one, so `system-version` overrides apply), `{v}` substituted in every string | +| `enumerate` | instead of `include`: one filter whose concepts, in the filter's order (a `then_link` row: the list's `link.seq` order), are listed as `include.concept` | +| `name`, `title`, `description` | the resource's texts: the reader substitutes `{v}`, `{v_}` (`{v}` with each `-` written `_`, as cs-loinc.js), `{display}` (the display of concept `{v}`) and `{version}` (the file's version); no other `{...}` placeholder is allowed; absent: the reader's own text | +| `grammar` | alone: the grammar answers the URLs of its form (SNOMED CT `{"grammar": "fhir_vs"}`: `?fhir_vs`, `?fhir_vs=isa/`, `refset/`, `ecl/`, on the system, an edition or a version URI) | + +So `http://loinc.org/vs/LL6136-7` is the list's answers, enumerated in sequence; `http://loinc.org/vs/LP14355-9` everything with an `ancestor` link to the part. + +## Implicit maps + +```json +{"base": "http://loinc.org/cm/", "maps": [["http://snomed.info/sct", "sct"], ...]} +{"base": "https://fhir-terminology.ohdsi.org/ConceptMap/", "maps": [...], "used": "to-", "forwardOnly": true} +{"associations": [{"relation": "900000000000526001", "equivalence": "equivalent", "relationship": "equivalent"}]} +``` + +- `base` and `maps`: the map `{base}{key}` (`http://loinc.org/cm/sct`) translates over the `mapping` + rows of that system, whatever their `property_id`, both ways. How a mapping row is reported by + `$lookup` is decided by its `property_id` only. +- `forwardOnly` (bool, default false): the maps translate this system's concepts into the other + systems only; a `$translate` of a code of another system into this one finds nothing (OMOP). +- `used` (text): the maps are offered for a translation between this system and the map's system + whether or not they translate the code (both ways; with `forwardOnly` a translation into this + system still finds nothing, so it answers no match), and a translation names the map it used + (`used-conceptmap`) `{base}{used}{key}|{version}` (OMOP: `.../ConceptMap/to-44819097|20240716`). +- `associations` (SNOMED CT): each entry is the map `?fhir_cm=` over the active + `record` rows of that relation (subject -> target, in seq order), forward only, with R4 + `equivalence` and R5 `relationship`. `$translate` of `307530000` with + `http://snomed.info/sct?fhir_cm=900000000000526001` gives its REPLACED BY target. + +## Code links + +Meta `codeLink` is a JSON string, a URL with `{code}`: the link a rendered page (a value set's or +code system's list of codes) gives a code, with `{code}` replaced by the code, URI-encoded +(`encodeURIComponent`). Absent: codes have no link. LOINC writes `https://loinc.org/{code}/` +(codes, parts, answers and groups, as org.hl7.fhir.core's LoincLinker), RxNorm +`https://mor.nlm.nih.gov/RxNav/search?searchBy=RXCUI&searchTerm={code}`. A grammar may give its +own links instead (`snomed`). + +## Grammar + +A grammar name: the expression syntax of the codes, the filters whose `reads` is `grammar`, and the +value checks below. A reader holds its implementations by name and refuses a file whose grammar it +does not implement. There is no fallback by system URI. + +| name | used by | defines | JS reader | +|---|---|---|---| +| `snomed` | SNOMED CT | expressions and ECL; filters `constraint =` (ECL), `expressions =`; a `concept` or attribute value that is not 6-18 digits is `Invalid concept ID` (422); an unknown concept on a `concept` row is `The SNOMED CT Concept {x} is not known`; the display ranking from `displayContexts`; the MRCM typing of concrete values; `?fhir_vs`; code links (a concept to snomed.info, in its edition when snomed.info knows it, `tx/sct/editions.js` snomedCodeLink; an expression of more than one concept to the browser's home page) | implemented (`snomed.js`) | +| `icd11` | ICD-11 MMS, ICF | postcoordinated expressions over the record relations `postcoordinationAxis` (fields `axis`, `axisCode`, `required`, `allowMultiple`, `valueSet`; `seq` the axis) and `postcoordinationRoot` (target the root of an axis's values, field `axisSeq`); an expression's display (its parts' displays; its designation in their language where they share one, else the display designation's), `$lookup` (`stem`, `postcoordination`) and validation issues; a plain code's axes in `$lookup` with `post-coordination-metadata`; no filter selects an expression; the value set an axis row names in `valueSet` (a postcoordination scale: an include `concept is-a ` per root of the axis, upstream's names and texts); a located code an include of one filter does not select: `'' is not in the value set`, the code in its `alias_parameter` form | implemented (`icd11.js`, with upstream's parser `tx/cs/icd11-expressions.js`) | +| `cpt` | CPT | codes with modifiers (`:...`, valid by upstream's rules: `tx/cs/cs-cpt.js`, run over the parts' literals and items); `modified =` (`true`: no concept, an open selection; `false`: every concept); an expression is a member only of filters that are all `modified = true` | implemented (`cpt.js`) | + +## Compatibility + +Meta `compatibility` is a JSON object. Each member reproduces one upstream provider's answer where +it differs from FHIR or from the other providers; it is no fact about the terminology. An absent +member has the default, which is the plain behaviour of the sections above. Removing a member +switches the file to the plain behaviour (for `statusReadingsIgnored`, after a rebuild). A reader +refuses a file with a member it does not implement, and refuses an unknown member. + +| member | values | default | set in | what happens | +|---|---|---|---|---| +| `statusReadingsIgnored` | list, shape of `conceptStatus` | `[]` | LOINC `DEPRECATED: inactive`; OMOP `invalid-reason D, U: inactive` | the listed readings are removed before the status is read, so the derived `concept.active` is computed without them | +| `generalizesLeavesOutFocus` | bool | false | SNOMED CT | `generalizes` selects the ancestors without the focus concept | +| `wholeSystemIncludeActiveOnly` | bool | false | SNOMED CT | an include of the whole system holds active concepts only, listed in the same order (the stored `walk` where there is one); `count=0` still counts every concept (the active ones with `activeOnly`) | +| `isAListsFocusFirst` | bool | false | SNOMED CT | with `order.expansion` `stored`: `is-a` lists its focus first; `child-of` in `ix_in` seq order; `generalizes` nearest ancestors first | +| `wholeSystemIncludeEmpty` | bool | false | UNII | an `$expand` include of the whole system has no codes | +| `wholeSystemRefusalMessage` | text, `{system}` substituted | none | OMOP | the text of the whole-system refusal | +| `lookupOmitsTextDefinitions` | bool | false | SNOMED CT | `$lookup` lists no `definition` | +| `displayDesignation` | `none`, `once`, `always` | `none` | RxNorm, UNII `once`; LOINC `always` | see "Designations and display" | +| `designationUse` | `source`, `none` | `source` | RxNorm, CPT `none` | designations report no use from the item's kind | +| `typedDesignationsInLookup` | bool | false | CPT | `$lookup` lists each item with a use again as a designation with parts `code` (the use's code), `value`, `language` | +| `lookupListsCopyright` | bool | false | CPT | `$lookup` lists `code_system.resource.copyright` as a property `copyright` (refused without one) | +| `lookupNameIsTitle` | bool | false | LOINC, ICD-11, OMOP | `$lookup` `name` is the title (meta `titles` in the requested language, else `code_system.title`) | +| `expansionDeclaresProperties` | bool | true | SNOMED CT, LOINC, RxNorm false | no `expansion.property` declarations | +| `expansionKeepsRepeatedDesignations` | bool | false | ICD-11 | an expansion row keeps a designation that repeats another exactly. (The JS server's expansion code lists every designation a provider gives, repeats included, for every system: a file that sets it is served as it says; the default, dropping repeats, is not what this server's expansions do for any system) | +| `expansionNeverNests` | bool | false | SNOMED CT, LOINC | an expansion never nests a row under its parent, whatever `excludeNested` says (the rows are listed flat, as for a system without a hierarchy); the JS provider then says it has no parents (`hasParents()`), which the expansion code reads | +| `unknownCodeMessage` | text with `{code}` | none | UNII `UNII Code '{code}' not found` | the reason for a code the system does not have | +| `filterUnknownCodeMessage` | text with `{code}` | none | LOINC `Not a valid code: {code}`; OMOP | the reason for a code a value-set filter check cannot locate | +| `filterRejectMessage` | text with `{code}` | none | OMOP | the reason for a located code a filter does not select | +| `missingValueFiltersAs` | `{property: value}` | `{}` | LOINC `{"STATUS": "NotStated"}` | a filter `= value` on that property also selects the concepts with no row of it | +| `translationDisplayIsSourceDisplay` | bool | false | OMOP | a translation by `implicitMaps` gives each target Coding the display of the concept translated, not the target's own | +| `lookupRankWhenConceptHas` | list of `{property, rank, when}` | `[]` | NDC | for a concept with a value of `when`, the row `property` takes `rank` | + +## Per-system content + +What each importer writes (the reader knows none of it): + +| | SNOMED CT | LOINC | RxNorm | UNII | +|---|---|---|---|---| +| `conceptStatus` | none (`concept.active` is the RF2 flag) | `STATUS`: DISCOURAGED inactive; DEPRECATED inactive, deprecated | `status`: obsolete inactive; archived inactive, deprecated, unlisted | none | +| `order` | expansion stored; ties code-number; links stored, property-id, group, code; literals property, value | expansion stored; ties display, stored; links stored, property-id, group, code | expansion stored; ties code; links property, code | default | +| `search` | yes (above) | yes | yes | none | +| `version` | prefix, partial `/version/` | prefix | prefix, describe release-date | prefix | +| `implicitValueSets` | `{"grammar": "fhir_vs"}` | `/vs`, `/vs/LP...`, `/vs/LL...`, with upstream's names and descriptions | none | none | +| `implicitMaps` | the association relations the file has | the twelve map keys | none | none | +| `grammar` | `snomed` | none | none | none | +| `codeLink` | none (the grammar's) | `https://loinc.org/{code}/` | RxNav | none | +| `compatibility` | generalizesLeavesOutFocus, wholeSystemIncludeActiveOnly, isAListsFocusFirst, lookupOmitsTextDefinitions, expansionDeclaresProperties false, expansionNeverNests | statusReadingsIgnored, displayDesignation always, lookupNameIsTitle, expansionDeclaresProperties false, expansionNeverNests, filterUnknownCodeMessage, missingValueFiltersAs | displayDesignation once, designationUse none, expansionDeclaresProperties false | displayDesignation once, wholeSystemIncludeEmpty, unknownCodeMessage | +| `filter` rows | 13 (concept, code, inactive, display, moduleId `=` `of`, definitionStatusId, effectiveTime, constraint, expressions, attribute pattern `=` `of`, `mapped:` pattern, parent `of`, child `of`) | 61 | 61 (TTY, STY, SAB any case; relationships with `CUI:`; concept, code); built with `--atom-relationships`, each relationship also with `AUI:`, reading `AUI:` (below) | none | +| `item_use` | synonym, fsn roles | display roles, `language_display_rank`, `RELATEDNAMES2` as property | the term types | none | +| `presentation` | `116680003`, `child`, `moduleId`: description; other SCTID links: description, code-display; concrete values: code-display | the twelve map rows: equivalence, version | | | + +RxNorm atom-level relationships (`rxnorm-v2 import --atom-relationships`): RXNREL's rows between +atoms (STYPE `AUI`, any source) are identifier statements, value RXAUI1, subject the concept that +owns RXAUI2 (in RXNCONSO, any source), under one internal identifier row per (REL, RELA) pair +`AUI::`; `AUI:` and `AUI:` are internal unions of the pairs, and a REL or RELA +with no atom-level rows has `AUI:` as an identifier row with no statements. Each relationship +filter has a second row, value prefix `AUI:`, that reads `AUI:`, so `has_ingredient = AUI:828` +selects the concepts owning an atom RXAUI2 of a `has_ingredient` row whose RXAUI1 is 828 (as the +concept-level rows: the subject is the second concept), and `in` may mix `CUI:` +and `AUI:` values. A file built without the option has no `AUI:` rows: such values are not understood. + +The other systems of this format (ICD-11, CPT, NDC, OMOP) are written by other importers; their +content is in the same keys. + +## What the JS reader serves + +It reads every file of this revision, whatever the system: the library loads a file of any code +system from a `sqlite-v2:` source line (and `snomed-v2:`, `loinc-v2:`, `rxnorm-v2:`, `ndc-v2:`, +`unii-v2:`, `cpt-v2:` lines, which also check the system). The file's grammar chooses the +provider (index.js): none, the generic provider (`provider.js`); `snomed` (`snomed.js`), `cpt` +(`cpt.js`), `icd11` (`icd11.js`). It refuses a file with a key or value it does not implement, +naming it; no file of the installed editions has one. + +| file | the keys beyond the generic provider's | where | +|---|---|---| +| SNOMED CT | `grammar` `snomed` | `snomed.js` | +| ICD-11 MMS, ICF | `grammar` `icd11`; `alias_parameter`, `alias_extension` on `shortCode`; `compatibility.expansionKeepsRepeatedDesignations` | `icd11.js`; "Alternate codes"; "Compatibility" | +| ICD-11 Foundation | `alias_extension` on `shortCode` (no `alias_parameter`, no identifier rows: every extension is `ICD11_CLASSIFICATION_CODE_SYSTEM`); `compatibility.expansionKeepsRepeatedDesignations` | "Alternate codes" | +| CPT | `grammar` `cpt` | `cpt.js` | +| NDC | `alias_literals` on `code11` (11-digit codes as codes in their own right) | "Alternate codes" | +| OMOP | `implicitMaps.used`, with `forwardOnly` and `compatibility.translationDisplayIsSourceDisplay` | "Implicit maps" | + +## Not settled in the revision + +The revision leaves these open; the JS reader's answer at each: + +| point | this reader | +|---|---| +| a SNOMED CT filter value that is not 6-18 digits | `Invalid concept ID: ` (the `snomed` grammar's value check, as upstream's filter throws); the other implementation keeps an empty selection until upstream's answer is checked | +| a supplement's designation as an expansion row's display (`displayDesignation` `none`) | as for any code system: the row may take the supplement's designation in the requested language as the display and leave it out of its designations (not checked on ICD-11, NDC, OMOP or CPT) | +| the LOINC supplement-designation dedupe | none here: every supplement designation is listed, a supplement display that some designation already has dropped (cs-api.js `_listSupplementDesignations`); no file fact keys it | +| a value set's `include.concept.display` in `$validate-code` | upstream's rule for every system: the code system's designations, then the include's display; the reported display is the preferred one (the native display). No file fact separates systems; upstream's answer for systems other than SNOMED CT and LOINC was not checked by a run | +| `ix_set` kind 5 sets | written for the properties the filter rows read, the `where_literal` literals, the `refinable` properties, the `conceptStatus` properties, the property of `search.candidates.hasLiteral`, and the hierarchy property where a `concept` row offers `child-of` (the JS index builder writes the hierarchy's sets whether or not such a row exists) | + +## Contracts + +What every file keeps, and every reader may rely on. The builder checks those marked before it +finishes a file (`builder.js` `checkContracts`); `node tx/importers/sqlite-v2/verify.js ` checks +them on request. + +| contract | checked by the builder | +|---|---| +| concept ids are exactly 1..N (N = `concept_count`); concepts 1..A active (A = `active_count`), A+1..N inactive | yes | +| item ids are exactly N+1..N+M | yes | +| at most one property with `subsumption = 1`, at most one `ordered = 1` link property, at most one `role = 'status'` row (a literal) | yes | +| codes are unique per system and matched exactly (the unique index `concept_code`) | yes | +| `requires` = `["identifier-text", "fhir-reading"]`; no `behaviour.*`, `linkOrder`, `searchTieBreak`, `propertyUris`, `ix.ix_word.names` key; none of the removed columns; every meta key one the builder knows, every value well-formed | yes | +| `concept.active` agrees with "Concept status" when `conceptStatus` gives any value the meaning `inactive` | yes | +| `property`: `fhir_code` (else `code`) unique among reportable rows; a union's members (through nested unions) all identifier rows or none; `lookup`, `expansion`, `shape`, `role` in their lists; an `internal` row has `lookup` and `expansion` `never` and no `uri`; `alias_*` only on identifier rows; a `reading` row is `inactive`, `deprecated` or `notSelectable`, boolean, with no fact rows | yes | +| `item_use`: `role` in its list; `as_property` names an `item-use` row, at most one use per row; every `item-use` row is named by one use | yes | +| `filter`: exactly one of `code`, `code_pattern`; `operators` a non-empty list of FHIR operators; rows of one code with disjoint operators, or told apart by value prefixes (above); no row named by an `internal` property's code; `reads` names catalog properties or `concept`, `inactive`, `display`, `designations`, `grammar` (needs meta `grammar`), `{1}` (a pattern with a group); `then_link` a link property; `where_literal` literal properties | yes | +| `conceptStatus` names literal rows; `compatibility` members known and well-formed; `lookupListsCopyright` needs `code_system.resource.copyright`; every non-NULL `mapping.property_id` names a `mapping` row; an `implicitValueSets` grammar template needs meta `grammar` | yes | +| `ix_set` keys: kinds 1, 2, 3 property 0, value 0, value kind 0; kinds 6, 7 value 0, value kind 0; kind 4 value kind 1, without its anchor; kind 5 sets only for the properties of `ix_set` above | yes | +| `ix_in` holds exactly the links of the `by_target = 1` properties; `ix_by_subject` exactly the identifier rows of the `by_subject = 1` properties | yes | +| `ix_order` arrays: little-endian u32 in 1,024-entry blocks, all full but the last; `rank` and `ids` N+1 entries; an `order` member that uses `stored` for concepts needs `rank` and `ids` | yes | +| `order.literals` that uses `stored` needs the column `literal.seq` | yes | +| `ix_word` rows exist exactly when `search` does; the counts row (`2 * (N + 1)` bytes) exactly when `search.shortlist` does; every language has an `ix.ix_word.stemmers` entry | yes | +| the secondary indexes of `schema.sql` exist; `sqlite_stat1` exists and `sqlite_stat4` does not | yes | + +At open the JS reader checks the id ranges it relies on (three rowid probes), the meta values, and +the `property`, `item_use` and `filter` columns and values listed above; nothing else. + +## Integrity facts + +meta `integrity` (optional) = `{"items": M, "schema": "", "catalog": ""}`, +written by the step that finishes a file (`builder.js` `finishFile`, also after `node indexes.js +`), after every other table, meta row and ANALYZE; a tool that rewrites a finished file writes +it again (the index builder removes it when it drops the indexes). + +- `items`: the number of `item` rows. +- `schema`: SHA-256 (lower-case hex) of the UTF-8 text made from `SELECT type, name, tbl_name, sql + FROM sqlite_master ORDER BY type, name`: each row as `type TAB name TAB tbl_name TAB sql` (NULL + sql as the empty string), rows joined by LF, no trailing LF. +- `catalog`: SHA-256 (lower-case hex) of the UTF-8 text made from these tables in this order: + `code_system` (ORDER BY cs_id), `meta` (ORDER BY key; leaving out keys that start with + `provenance.` and the key `integrity`), `property` (ORDER BY id), `property_member` (ORDER BY + parent_id, child_id), `item_use` (ORDER BY use_id), `filter` (ORDER BY id), `value_label` (ORDER BY + property_id, value). + Each row is the table name, TAB, then every column in `PRAGMA table_info` order as SQLite's + `quote(column)`, joined by `,`; all rows of all tables joined by LF, no trailing LF. + +`node tx/importers/sqlite-v2/verify.js ` checks a file on request, read-only: the format, the +meta values, the contracts above (id ranges included), and, where the file states them, the +integrity facts (file length = `page_count * page_size`, both digests, the item count). It prints +each check and exits 1 when one fails, the file cannot be read included (non-zero for every failure). Readers do not check digests. ## Importers @@ -186,23 +799,21 @@ then numbers the concepts, writes the fact tables in key order, builds the index 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. +A file of the earlier sqlite-v2 schema (user_version 5), and a tx-terminology/1 file written before +the fhir-reading revision, is refused at start-up with a message to re-import it. ## Known differences from main -| case | main | sqlite-v2 | +Each row is a request that main's providers (`snomed` on a cache from its importer; `ndc`, `cpt`, +`unii`, `icd11`, `loinc` on databases from its importers, ICD-11 with its text index; `rxnorm-v2` on a +file from main's importer) and this reader, on files of the same release, answer differently. SNOMED CT +rows are on the test edition (31000003106, 20250909). + +| request | 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 | +| SNOMED CT `$expand`, `concept is-not-a 22298006` (a concept not in the edition) | 500, `exception`: "The SNOMED CT Concept 22298006 is not known" | 400, `invalid`, the same text | +| SNOMED CT `$expand`, `concept in 1000601000003105` (a reference set whose members are descriptions) | six codes that are not concept ids (327640, 327680, ...), each marked inactive | 400, `invalid`: "The members of reference set 1000601000003105 are descriptions, not concepts, so concept in cannot be evaluated for it", the refusal of ECL `^ 1000601000003105`, which both give (400, `UNSUPPORTED_ECL`) | +| SNOMED CT `$expand` of the whole system with `filter=0` and `count=0` | total 20,184 | total 2,227 | +| SNOMED CT `$expand`, `concept in 1000901000003102,1000891000003103` | the first set's members, then the second's: 262797004, 262798009, 16763008, 262796008 | by concept id: 16763008, 262796008, 262797004, 262798009 | +| SNOMED CT `$expand`, `expressions = true` (or `= false`) as the only filter | no codes, total 0 | every concept, total 2,286 | +| RxNorm `$expand`, a `=` filter value with white space around it: `has_ingredient = " CUI:161"` (or `" AUI:828"`, `"AUI:828 "`), `TTY = "SBD "`, `STY = " T200"` | the value trimmed first (cs-rxnorm.js), then the prefix removed: the same answer as without the white space | the value as written: a leading space before `CUI:` / `AUI:` is 422 FILTER_NOT_UNDERSTOOD; a trailing one is ignored after `CUI:` (codes are looked up trimmed), not after `AUI:` (no codes); `TTY` / `STY` select no codes. No file fact says a system's values are trimmed | diff --git a/tx/sqlite-v2/cpt.js b/tx/sqlite-v2/cpt.js new file mode 100644 index 00000000..c313c621 --- /dev/null +++ b/tx/sqlite-v2/cpt.js @@ -0,0 +1,196 @@ +'use strict'; +// The grammar `cpt` (README.md "Grammar"): a code may be a base code followed by `:`-separated +// modifier codes (`::`). Which combinations are valid is the rule set of +// upstream's CPT provider (tx/cs/cs-cpt.js #validateExpression), which this grammar runs through +// that provider's own locate(), handing it the parts as CPTConcepts made from this file (each +// part's literals as its properties, its named items in id order as its designations). The filter +// that reads `grammar` is `modified =`: `true` selects no concept and leaves an expansion open, +// `false` every concept; a valid expression is in a filtered include only when every filter of the +// include is `modified = true`. Everything about plain codes is the generic reader's. + +const { SqliteV2Provider, SqliteV2Factory } = require('./provider'); +const { CPTServices, CPTConcept } = require('../cs/cs-cpt'); + +/** a valid expression: the code as written, its base concept and its modifiers (V2Concepts) */ +class CptExpression { + constructor(code, focus, modifiers) { + this.code = code; + this.focus = focus; + this.modifiers = modifiers; + } +} + +/** the code is written as an expression of the grammar */ +const isExpression = (code) => typeof code === 'string' && code.includes(':'); + +/** a filter of the grammar that selects expressions: modified = true */ +const selectsExpressions = (f) => f.prop === 'modified' && f.op === '=' && String(f.value) === 'true'; + +class CptV2Provider extends SqliteV2Provider { + async _locate(code, prefetched = null) { + if (!isExpression(code)) return super._locate(code, prefetched); + return this._locateExpression(String(code)); + } + + /** an expression, validated by upstream's rules over the parts as this file has them */ + async _locateExpression(code) { + const parts = code.split(':'); + const S = this.store; + const rows = S.rowsForCodes([...new Set(parts.filter(Boolean))], this._stats()); + const ids = [...rows.values()].map((r) => r.concept_id); + const literals = ids.length ? S.literalsOf(ids, true, this._stats()) : []; + const items = ids.length ? S.designationRows(ids, this._stats()) : new Map(); + const conceptMap = new Map(); + for (const [c, r] of rows) { + const cc = new CPTConcept(c, false); + for (const l of literals) if (l.c === r.concept_id) cc.addProperty(S.propsById.get(l.p).code, String(l.v)); + const its = [...(items.get(r.concept_id) || [])].filter((d) => d.use).sort((a, b) => a.id - b.id); + for (const d of its) cc.addDesignation(d.use.code, d.term); + conceptMap.set(c, cc); + } + const svc = new CPTServices(this.opContext, [], null, { _version: this.version(), conceptMap, conceptList: [], baseList: [], modifierList: [] }); + const r = await svc.locate(code); + if (!r.context) return { context: null, message: r.message }; + const concept = (c) => { + const row = rows.get(c.code); + const v = this._concept(row.concept_id, row); + v.cpt = c; + return v; + }; + return { context: new CptExpression(r.context.expression(), concept(r.context.focus), r.context.modifiers.map(concept)), message: null }; + } + + async _ensure(context) { + if (context instanceof CptExpression) return context; + return super._ensure(context); + } + + async code(context) { + const c = await this._ensure(context); + return c instanceof CptExpression ? c.code : super.code(c); + } + + async display(context) { + const c = await this._ensure(context); + if (!(c instanceof CptExpression)) return super.display(c); + // an expression has no text of its own + return this._displayFromSupplements(c.code) || ''; + } + + async definition(context) { + const c = await this._ensure(context); + return c instanceof CptExpression ? null : super.definition(c); + } + + async isAbstract(context) { + const c = await this._ensure(context); + return c instanceof CptExpression ? false : super.isAbstract(c); + } + + async isInactive(context) { + const c = await this._ensure(context); + return c instanceof CptExpression ? false : super.isInactive(c); + } + + async isDeprecated(context) { + const c = await this._ensure(context); + return c instanceof CptExpression ? false : super.isDeprecated(c); + } + + async getStatus(context) { + const c = await this._ensure(context); + return c instanceof CptExpression ? null : super.getStatus(c); + } + + async _designations(context, displays, significantOnly) { + const c = await this._ensure(context); + // an expression has no designations + if (c instanceof CptExpression) return; + return super._designations(c, displays, significantOnly); + } + + /** + * $lookup of an expression (cs-cpt.js extendLookup): the copyright, the base code's lookup, then + * per modifier its code and its first designation (`modifier`, `modifier-definition`). The base + * code's notSelectable is not the expression's: the lookup reports the expression's own (never + * abstract) after everything the provider lists + */ + async _extendLookup(context, props, params) { + const c = await this._ensure(context); + if (!(c instanceof CptExpression)) return super._extendLookup(c, props, params); + if (this.store.copyright != null) this._addStringProperty(params, 'property', 'copyright', this.store.copyright); + const before = params.length; + await super._extendLookup(c.focus, props, params); + for (let i = params.length - 1; i >= before; i--) { + const p = params[i]; + if (p.name === 'property' && (p.part || []).some((x) => x.name === 'code' && x.valueCode === 'notSelectable')) params.splice(i, 1); + } + for (const m of c.modifiers) { + this._addStringProperty(params, 'property', 'modifier', m.code); + if (m.cpt && m.cpt.designations.length) this._addStringProperty(params, 'property', 'modifier-definition', m.cpt.designations[0].value); + } + } + + async properties(context, names) { + const c = await this._ensure(context); + return c instanceof CptExpression ? [] : super.properties(c, names); + } + + /** an expression is in a filter set when every filter of it is modified = true */ + _expressionMember(set) { + const specs = set.specs || []; + return specs.length > 0 && specs.every(selectsExpressions); + } + + async _filterLocate(prep, set, code) { + if (!isExpression(code)) return super._filterLocate(prep, set, code); + // only an open filter (modified = true) admits expressions; closed filters do not parse them (#486) + if (!this._expressionMember(set)) return null; + const r = await this.locate(code); + if (!r.context) return r.message; + return r.context; + } + + async filterCheck(prep, set, concept) { + if (concept instanceof CptExpression) return this._expressionMember(set); + return super.filterCheck(prep, set, concept); + } + + /** a filtered include is open when a filter of it is modified = true (it admits expressions) */ + async filtersNotClosed(prep) { + return (prep.specs || []).some(selectsExpressions); + } + + async subsumesTest(codeA, codeB) { + const a = await this._ensure(codeA); + const b = await this._ensure(codeB); + if (a instanceof CptExpression || b instanceof CptExpression) return 'not-subsumed'; + return super.subsumesTest(a, b); + } + + async ancestorsOf(code) { + if (isExpression(code)) return null; + return super.ancestorsOf(code); + } +} + +/** the grammar's filter rules (engine/compile.js term.grammar): the filter that reads `grammar` */ +const CPT_RULES = Object.freeze({ + filter(c, prop, op, value) { + // modified = true: no concept (expressions only); false: every concept + if (prop === 'modified' && op === '=') return String(value) === 'true' ? { t: 'empty' } : { t: 'all' }; + return null; + }, +}); + +class CptV2Factory extends SqliteV2Factory { + static grammar = 'cpt'; + static grammarRules = CPT_RULES; + + async build(opContext, supplements) { + this.recordUse(); + return new CptV2Provider(opContext, supplements, this); + } +} + +module.exports = { CptV2Factory, CptV2Provider, CptExpression, CPT_RULES }; diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js deleted file mode 100644 index 4a06bfdf..00000000 --- a/tx/sqlite-v2/dialects.js +++ /dev/null @@ -1,367 +0,0 @@ -'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/utils/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 index bf0ad6d6..bfa5e35c 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -1,9 +1,10 @@ '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: +// A filter is understood when a row of the file's filter table names it (README.md "filter"); the +// row says what it reads (the concept hierarchy, a catalog property, the display, designations, the +// status) and how its values match. What only an algorithm can do (SNOMED CT ECL and expressions) +// is the file's grammar (`term.grammar`: the rules snomed.js supplies). 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 @@ -14,6 +15,20 @@ const { KIND } = require('../store'); // an ECL wild: term: main's matcher (cs-snomed.js wildTermMatcher), linear with no regex const { wildTermMatcher } = require('../../sct/ecl'); +const regexUtilities = require('../../../library/utils/regex-utilities'); + +/** + * A filter no filter row understands (README.md "filter"): 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] }); +} + +/** whether a supplement-layer filter selects codes the supplement lists (supplement-filters.js) */ +function isEnumerableLayer(n) { + return n.op !== 'not-in' && !(n.op === 'exists' && String(n.value).toLowerCase() === 'false'); +} class FilterError extends Error { constructor(message, extra = {}) { @@ -23,6 +38,14 @@ class FilterError extends Error { } } +/** + * A reference set whose members are descriptions (a language relation) where concepts are wanted: + * `^ R` (main's text, cs-snomed.js) and `concept in R`. invalid: the request is wrong (400) + */ +function descriptionMembers(code, what) { + return new FilterError(`The members of reference set ${code} are descriptions, not concepts, so ${what} cannot be evaluated for it`, { invalid: true }); +} + function splitList(v) { return String(v).split(',').map((s) => s.trim()).filter(Boolean); } @@ -33,14 +56,16 @@ function uniqSorted(ids) { class Compiler { /** - * @param {object} term { store, dialect, layers: [{store, ...}] } + * @param {object} term { store, grammar (the grammar's filter rules, or none), layers: [{store, ...}] } * @param {object} [opts] { stats } */ constructor(term, opts = {}) { this.term = term; this.store = term.store; - this.dialect = term.dialect || {}; + this.grammar = term.grammar || {}; this.stats = opts.stats || null; + // then_link rows over an ordered list property in the list's order (implicitValueSets enumerate) + this.listOrder = !!opts.listOrder; this.codeMap = new Map(); // codes resolved while compiling this request (one statement for all) } @@ -48,7 +73,7 @@ class Compiler { 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); + if (miss.length) for (const [c, id] of this.store.resolveCodes(miss, this.stats, { identifiers: true })) 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; @@ -60,11 +85,11 @@ class Compiler { return this.ids([c]).get(c); } - /** concept ids for a filter value: the code, or a dialect-specific alternative (LOINC part names) */ - valueIds(v) { + /** concept ids for a filter value: the code, or the targets with that display where the filter row says so (value_as_display) */ + valueIds(v, asDisplay = false) { const id = this.id(v); if (id != null) return [id]; - return this.dialect.valuesByName ? this.dialect.valuesByName(this, v) : []; + return asDisplay ? this.store.displayIdsNoCase(v) : []; } // ---- compose ------------------------------------------------------------------------------- @@ -85,22 +110,22 @@ class Compiler { selection(includes, excludes, activeOnly) { this.prefetch([...includes, ...excludes]); return { - includes: includes.map((inc) => this.include(inc)), - excludes: excludes.map((inc) => this.include(inc)), + includes: includes.map((inc, i) => this.include(inc, 'ValueSet.compose.include[' + i + ']')), + excludes: excludes.map((inc) => this.include(inc, 'ValueSet.compose.exclude')), activeOnly: !!activeOnly }; } - include(inc) { + include(inc, path = null) { 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 }); + const oc = new Compiler({ store: other, grammar: inc.provider.grammarRules }, { stats: this.stats }); oc.prefetch([inc]); - const parts = oc.include({ ...inc, otherVersion: false }); + const parts = oc.include({ ...inc, otherVersion: false }, path); 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) { @@ -108,15 +133,26 @@ class Compiler { // 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 }); + const own = this.include({ ...inc, imports: undefined }, path); 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 }); + // an include of the whole code system: refused as too costly (expansionLimits.wholeSystem), + // empty (compatibility.wholeSystemIncludeEmpty), its listed concepts, or its active ones + // (compatibility.wholeSystemIncludeActiveOnly) + const S = this.store; + if (S.expansionLimits.wholeSystem === 'refuse') { + const msg = (S.compat.wholeSystemRefusalMessage || 'The code system {system} cannot be expanded as a whole').split('{system}').join(S.system); + throw new FilterError(msg, { wholeSystemRefused: true }); + } + if (S.compat.wholeSystemIncludeEmpty) parts.push({ node: { t: 'empty' }, order: null }); + else { + const all = this.domain({ t: 'all', whole: true }); + parts.push({ node: S.compat.wholeSystemIncludeActiveOnly ? { t: 'and', items: [all, { t: 'active' }], whole: true } : all, order: null }); + } return { parts }; } if (inc.concept && inc.concept.length) { @@ -129,17 +165,33 @@ class Compiler { 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 }; + let order = null; + if (items.every((n) => n.t === 'layer')) { + const driver = items.find(isEnumerableLayer); + if (!driver) { + // not-in / exists = false select codes by what the supplement doesn't say, so cannot + // drive an expansion on their own (expand.js #supplementFilterConcepts) + const f = inc.filter[0]; + throw new FilterError(`The filter "${f.property} ${f.op} ${f.value}" is not understood or supported`, { + notUnderstood: [f.property, f.op, f.value], + supplementNotEnumerable: true, + filterPath: path ? path + '.filter' : null + }); + } + if (driver.layer && driver.layer.conceptOrder) order = driver.layer.conceptOrder; + } // upstream adds an include's concepts and its filters separately (expand.js includeCodes) - parts.push({ node: this.domain(node), order: null }); + parts.push({ node: this.domain(node), order }); } return { parts }; } - /** the concepts a filter can select at all (RxNorm: never archived concepts) */ + /** the concepts a filter can select at all: the listed ones (not unlisted: README.md "Concept status") */ 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] }; + const u = this.store.readingValues('unlisted'); + if (!u.length) return node; + const listed = { t: 'listed' }; + return node.t === 'all' ? { ...listed, whole: !!node.whole } : { t: 'and', items: [node, listed] }; } /** an imported value set's compose as one node: its includes minus its excludes */ @@ -154,51 +206,202 @@ class Compiler { return node; } - // ---- filters ------------------------------------------------------------------------------- + // ---- filters --------------------------------------------------------------------------- + /** + * A filter as a request names it (README.md "filter"): the filter row that understands its name + * and operator. No row: a property only a supplement in use defines (a supplement layer), else + * FILTER_NOT_UNDERSTOOD. + */ filter(prop, op, value) { - if (this.dialect.filter) { - const n = this.dialect.filter(this, prop, op, value); + const hits = this.store.filterRows(prop, op); + const nu = () => notUnderstood(this.grammar.filterName ? this.grammar.filterName(this, prop) : prop, op, value); + if (!hits.length) { + const n = this.term.layers ? this.term.layers.filterNode(this, prop, op, value) : null; if (n) return n; + // (a grammar may name the filter otherwise in the message: SNOMED CT reports code as concept) + throw nu(); + } + if (hits.length === 1) return this.rowFilter(hits[0].row, hits[0].capture, prop, op, value); + // rows told apart by value_prefix (RxNorm CUI: and AUI:): each value is read by the row whose + // prefix it has; `in` is the union over the values, `not-in` its complement + const listOp = op === 'in' || op === 'not-in'; + const vals = listOp ? splitList(value) : value == null || String(value) === '' ? [] : [String(value)]; + if (!vals.length) throw nu(); + const groups = new Map(); + for (const v of vals) { + const h = hits.find((x) => v.startsWith(x.row.prefix)); + if (!h) throw nu(); + if (!groups.has(h)) groups.set(h, []); + groups.get(h).push(v); } - 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 (!listOp) return this.rowFilter(hits.find((h) => groups.has(h)).row, null, prop, op, vals[0]); + const items = [...groups].map(([h, vs]) => this.rowFilter(h.row, h.capture, prop, 'in', vs.join(','))); + const node = items.length === 1 ? items[0] : { t: 'or', items }; + return op === 'not-in' ? { t: 'minus', a: { t: 'all' }, b: node } : node; + } + + /** the selection of one filter row (README.md "What a row reads") */ + rowFilter(row, capture, prop, op, value) { + const S = this.store; + const nu = () => notUnderstood(this.grammar.filterName ? this.grammar.filterName(this, prop) : prop, op, value); + // the values (README.md "filter": values) + let vals; + if (op === 'in' || op === 'not-in') { + vals = splitList(value); + if (!vals.length) throw nu(); + } else { + if (value == null || String(value) === '') throw nu(); + vals = [String(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); + if (op === 'exists' && vals[0] !== 'true' && vals[0] !== 'false') throw nu(); + if (Array.isArray(row.allowed) && !vals.every((v) => row.allowed.includes(v))) throw nu(); + if (row.allowed === 'codes') { + const m = this.ids(vals); + if (!vals.every((v) => m.get(v.trim()) != null)) throw nu(); } - // 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); + // (exists takes true or false: the prefix is for the values of the other operators) + if (row.prefix != null && op !== 'exists') { + if (!vals.every((v) => v.startsWith(row.prefix))) throw nu(); + vals = vals.map((v) => v.substring(row.prefix.length)); } - return this.propertyFilter(p, op, value); + // the grammar's checks of a value (README.md "grammar") + if (this.grammar.checkValues) this.grammar.checkValues(this, row, op, vals); + // the union over the row's reads, for one value; `in` the union over the values, `not-in` its complement + const one = (v) => { + // (not-in: the complement of the `in` selection, below) + const selOp = op === 'not-in' ? 'in' : op; + const items = row.reads.map((x) => this.readSelection(row, x === '{1}' ? capture : x, x === '{1}', selOp, v, prop)); + return items.length === 1 ? items[0] : { t: 'or', items }; + }; + const listOp = op === 'in' || op === 'not-in'; + let node; + if (listOp && !this._selectsLists(row)) { + const items = vals.map(one); + node = items.length === 1 ? items[0] : { t: 'or', items }; + } else node = one(listOp ? vals.join(',') : vals[0]); + if (op === 'not-in') node = { t: 'minus', a: { t: 'all' }, b: node }; + // where_literal: every named literal value also holds (exact) + if (row.where) { + const where = Object.entries(row.where).map(([k, v]) => ({ t: 'set', kind: KIND.prop, pid: S.catalog.get(k).id, value: v })); + node = { t: 'and', items: [node, ...where] }; + } + // then_link P: the targets of P's links from what was read (an ordered list property: by + // list, in the order of the lists, each in its link.seq order) + if (row.then) { + const of = node; + // (README.md "What a row reads", then_link: a row that reads only `concept` (LOINC LIST = LL...) + // lists its selection in the order of any other selection, as cs-loinc.js (ORDER BY TargetKey: + // the stored rank); the other then_link rows (answers-for) in the order of the lists; an + // implicit value set's `enumerate` in the list's order: this.listOrder) + const listOrder = row.then.ordered && (this.listOrder || (op === '=' && !(row.reads.length === 1 && row.reads[0] === 'concept'))); + node = { t: 'propOf', pids: pidsOf(row.then), sources: of, ...(listOrder ? { order: 'lists', of } : {}) }; + } + return node; } - /** display = / in / regex (the concept's display; FHIR's "display" filter property) */ - displayFilter(op, value) { + /** rows whose reads take the whole value list at once (concept in X,Y: one rule over the list) */ + _selectsLists(row) { + return row.reads.length === 1 && row.reads[0] === 'concept'; + } + + /** + * What one element of a row's reads selects for a value (an array for `in` / `not-in` on a + * concept row): README.md "What a row reads" + * @param {boolean} captured the element is `{1}`: x is the captured text, a property code + */ + readSelection(row, x, captured, op, v, prop) { + const S = this.store; + const nu = () => notUnderstood(prop, op, Array.isArray(v) ? v.join(',') : v); + if (captured) { + const d = x != null ? S.catalog.get(x) : null; + if (!d || !['link', 'literal', 'both', 'union', 'identifier'].includes(d.shape) || d.internal) { + return op === 'exists' && String(v).toLowerCase() === 'false' ? { t: 'all' } : { t: 'empty' }; + } + return this.propertyRead(row, d, op, v, prop); + } + switch (x) { + case 'concept': return this.conceptFilter(op, v, prop); + case 'inactive': + if (op !== '=' || (v !== 'true' && v !== 'false')) throw nu(); + return v === 'true' ? { t: 'inactive' } : { t: 'active' }; + case 'display': + return this.displayFilter(op, v, prop); + case 'designations': { + if (op !== 'regex') throw nu(); + // some active designation whose use has role fsn or synonym, in the request's text-search language + const lits = this.store.hasFts ? requiredLiterals(v) : []; + const lang = (this.term && this.term.lang) || 'en'; + const uses = [...S.uses.values()].filter((u) => u.role === 'fsn' || u.role === 'synonym').map((u) => u.code); + return { t: 'desigRegex', re: String(v), lang, uses, ...(lits.length ? { lits } : {}), label: `display (${lang}) ~ /${v}/` }; + } + case 'grammar': { + const n = this.grammar.filter ? this.grammar.filter(this, prop, op, v) : null; + if (!n) throw nu(); + return n; + } + default: { + const d = S.catalog.get(x); + return this.propertyRead(row, d, op, v, prop); + } + } + } + + /** a filter row's read of a catalog property (link, union, inverse, both, literal, identifier) */ + propertyRead(row, d, op, v, prop) { + const S = this.store; + const nu = () => notUnderstood(prop, op, v); + if (d.kind === 'identifier') { + // = / in: the subjects of the identifiers with the value (of every member, for a union) + if (op === '=' || op === 'in') { + const vals = op === 'in' ? splitList(v) : [String(v)]; + return { t: 'ids', ids: S.subjectsOfIdentifiers(d, vals), label: `${d.code} ${op} ${vals.join(',')}` }; + } + if (op !== 'exists' || d.shape !== 'identifier') throw nu(); + const has = { t: 'ids', ids: S.subjectsOfScheme(d), label: `${d.code} exists` }; + return v === 'true' ? has : { t: 'minus', a: { t: 'all' }, b: has }; + } + if (!['link', 'literal', 'both', 'union'].includes(d.shape)) throw nu(); + // a closure source (LOINC ancestor): its pairs are the descendants sets + if (S.closure != null && d.id === S.closure && (op === '=' || op === 'in')) { + const id = this.id(v); + return id == null ? { t: 'empty' } : { t: 'set', kind: KIND.descendants, pid: 0, value: id }; + } + return this.propertyFilter(d, op, v, row); + } + + /** display = / in / regex (the concept's display) */ + displayFilter(op, value, prop = 'display') { 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 vals = Array.isArray(value) ? value : [String(value)]; const esc = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return { t: 'text', field: 'display', re: '^(?:' + vals.map(esc).join('|') + ')$' }; } - throw this.notSupported('display', op, value); + throw notUnderstood(prop, 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}`); + /** + * concept in X,Y,...: a concept that defines a record relation (catalog relations: a reference + * set) contributes its members, none when it has none; any other concept itself. A language + * relation's members are items (descriptions), which no concept set holds: refused as ECL ^ is + * (descriptionMembers), not answered as an empty set or as the concept itself + */ + conceptIn(ids, op = 'in') { + const S = this.store; + const items = []; + const plain = []; + for (const id of ids) { + if (!(S.relations && S.relations.has(id))) plain.push(id); + else if (S.isLanguageRefset(id)) throw descriptionMembers(S.codesOf([id])[0], `concept ${op}`); + else items.push({ t: 'set', kind: KIND.refset, pid: 0, value: id }); + } + if (plain.length) items.push({ t: 'ids', ids: plain }); + return items.length === 1 ? items[0] : items.length ? { t: 'or', items } : { t: 'ids', ids: [] }; } conceptFilter(op, value, prop = 'concept') { @@ -207,17 +410,19 @@ class Compiler { 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 }; + // a concept the file does not have: the grammar may make it an error (SNOMED CT) + if (unknown.length && this.grammar.unknownConcept) this.grammar.unknownConcept(this, op, unknown[0]); + const ordered = [...new Set(vals.map((v) => m.get(v)).filter((x) => x != null))]; + const ids = uniqSorted(ordered); + const n = this.conceptIn(ids, op); + if (op === 'in' && S.compat.isAListsFocusFirst && n.t === 'ids' && ordered.length > 1) n.order = ordered; 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); + if (op === 'exists') throw notUnderstood(prop, op, value); const id = this.id(value); if (id == null) { - if (this.dialect.unknownConcept) return this.dialect.unknownConcept(this, op, value); + if (this.grammar.unknownConcept) return this.grammar.unknownConcept(this, op, value); return { t: 'empty', why: 'unknown code ' + value }; } const desc = { t: 'set', kind: KIND.descendants, pid: 0, value: id }; @@ -226,10 +431,10 @@ class Compiler { 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 'generalizes': return { t: 'anc', id, self: !S.compat.generalizesLeavesOutFocus }; 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); + default: throw notUnderstood(prop, op, value); } } @@ -243,9 +448,11 @@ class Compiler { * '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); + propertyFilter(p, op, value, row = null) { + if (p.reverses) return this.inverseFilter(p, op, value, row); const pids = pidsOf(p); + const asDisplay = !!(row && row.asDisplay); + const exact = !!(row && row.exactCase); switch (op) { case '=': case 'in': @@ -253,32 +460,46 @@ class Compiler { const vals = op === '=' ? [String(value)] : splitList(value); let node; if (p.kind === 'concept') { - node = this.nodeSets(pids, uniqSorted(vals.flatMap((v) => this.valueIds(v)))); + node = this.nodeSets(pids, uniqSorted(vals.flatMap((v) => this.valueIds(v, asDisplay)))); } 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)); + node = litSets(p.id, this.literalKeys(p, vals, exact, asDisplay)); + // compatibility.missingValueFiltersAs: a concept with no row of the property has that value + const missing = this.store.compat.missingValueFiltersAs[p.code]; + if (missing != null && vals.includes(missing)) { + node = { t: 'or', items: [{ t: 'minus', a: { t: 'all' }, b: { t: 'set', kind: KIND.hasProp, pid: p.id, value: 0 } }, node] }; + } } 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); + if (v !== 'true' && v !== 'false') throw notUnderstood(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 } }; + // regex over the target's display: match the target keys, then their sources + return { t: 'propIn', pids, values: { t: 'text', field: 'display', re: value } }; + } + { + // the stored values; the labels instead where the property has value_label rows + const labels = this.store.valueLabels(p); + if (labels) { + const re = regexUtilities.compile('^(?:' + value + ')$'); + const keys = Object.keys(labels).filter((k) => re.test(String(labels[k]))); + return litSets(p.id, this.store.propValues(p.id, this.stats).map((r) => r.value).filter((x) => keys.includes(String(x)))); + } } return { t: 'litMatch', pid: p.id, re: value }; default: - throw this.notSupported(p.code, op, value); + throw notUnderstood(p.code, op, value); } } @@ -316,7 +537,7 @@ class Compiler { } /** 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) { + inverseFilter(p, op, value, row = null) { const rev = p.reverses; const hier = rev.filter((q) => q.isHierarchy); const other = rev.filter((q) => !q.isHierarchy).map((q) => q.id); @@ -330,30 +551,38 @@ class Compiler { 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))) }); + const node = of({ t: 'ids', ids: uniqSorted(vals.flatMap((v) => this.valueIds(v, !!(row && row.asDisplay)))) }); 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); + if (v !== 'true' && v !== 'false') throw notUnderstood(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); + default: throw notUnderstood(p.code, op, value); } } - /** map literal filter values onto stored keys (case-insensitive for strings) */ - literalKeys(p, vals) { + /** + * literal filter values -> the stored keys they match: ignoring case (Unicode simple folding), + * or exactly (filter.value_case exact); with value_as_display, a value may be a value label + * (ignoring case) + */ + literalKeys(p, vals, exact = false, asDisplay = false) { 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); + const labels = asDisplay ? this.store.valueLabels(p) : null; + const fold = (x) => String(x).toLowerCase(); + for (const v of vals) { + const want = [v]; + if (labels) for (const [k, d] of Object.entries(labels)) if (fold(d) === fold(v)) want.push(k); + for (const r of keys) { + const sv = String(r.value); + if (want.some((w) => (exact ? sv === w : fold(sv) === fold(w)))) out.add(r.value); + } } return [...out]; } @@ -373,9 +602,9 @@ class Compiler { try { return this.eclNode(ast); } catch (e) { - // a feature the engine does not evaluate: the dialect may hand the expression on (SNOMED CT: + // a feature the engine does not evaluate: the grammar 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); + if (e.unsupported && this.grammar.eclFallback) return this.grammar.eclFallback(this, text, e); throw e; } } @@ -439,10 +668,8 @@ class Compiler { } 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`); - } + // a language reference set: its members are descriptions (as main reports it) + if (this.store.isLanguageRefset(rid)) throw descriptionMembers(f.refSet.conceptId, '^'); base = { t: 'set', kind: KIND.refset, pid: 0, value: rid }; } else if (f.refSet.type === 'Wildcard') { throw new Unsupported('ecl-feature', '^ *'); @@ -506,8 +733,8 @@ class Compiler { 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); + // effectiveTime: not refinable) + const row = [...S.props.values()].find((d) => d.code.toLowerCase() === field && !d.refinable); if (field === 'moduleid' || field === 'definitionstatusid') { if (!row) return { t: 'empty' }; return not({ t: 'propIn', pids: [row.id], values: this.eclNode(f.value) }); @@ -544,7 +771,9 @@ class Compiler { })); } 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); + else if (field === 'moduleid' || field === 'effectivetime') { + throw new FilterError(`Unsupported ECL description filter ${f.field}: the edition files hold no description ${field === 'moduleid' ? 'modules' : 'effective times'}`); + } 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) @@ -578,7 +807,7 @@ class Compiler { 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 }; + return { t: 'history', of: node, refsets, eclOrder: 'history' }; } eclRefinement(r) { @@ -766,7 +995,9 @@ class Compiler { const S = this.store; if (name.type === 'ConceptReference') { const p = S.props.get(name.conceptId); - return p && p.refinable ? [p.id] : []; + if (p) return p.refinable ? [p.id] : []; + this.eclConcept(name.conceptId); + return []; } if (name.type === 'Wildcard') { // any attribute, is-a included: it is an attribute (a 246061005 |Attribute|) like the others, @@ -864,4 +1095,4 @@ function collectIds(n, out) { } } -module.exports = { Compiler, FilterError, Unsupported, splitList, uniqSorted, litSets, pidsOf }; +module.exports = { Compiler, FilterError, Unsupported, notUnderstood, isEnumerableLayer, splitList, uniqSorted, litSets, pidsOf }; diff --git a/tx/sqlite-v2/engine/engine.js b/tx/sqlite-v2/engine/engine.js index 82681225..079298ab 100644 --- a/tx/sqlite-v2/engine/engine.js +++ b/tx/sqlite-v2/engine/engine.js @@ -61,6 +61,18 @@ class Result { } } +/** + * The node whose own order a part lists its members in (compatibility.isAListsFocusFirst): an is-a + * or generalizes filter, alone or the first of an include's filters (the others only narrow it: + * cs-snomed.js walks the first filter's list) + */ +function orderedBy(node) { + if (node.t === 'self' || node.t === 'anc' || node.t === 'parents') return node; + if (node.t !== 'and') return null; + const first = node.items.find((n) => !(n.t === 'all' && !n.whole)); + return first && (first.t === 'self' || first.t === 'anc' || first.t === 'parents') ? first : null; +} + class Engine { constructor(store, opts = {}) { this.store = store; @@ -149,10 +161,11 @@ class Engine { 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 explicitOrder = p.order || (Array.isArray(p.node.order) ? p.node.order : null); + if (explicitOrder) { 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); } + for (const id of explicitOrder) 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) }); @@ -169,8 +182,10 @@ class Engine { const ordered = [...new Set(this.store.linkSourcesInOrder(p.node.pid, p.node.value).filter((id) => 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, + } else if (p.node.whole && this._order && this._order.hasWalk) { + // (an include of the whole code system, whatever node compile.js made of it (all, its listed + // concepts, or its active ones with compatibility.wholeSystemIncludeActiveOnly; b holds just + // those): 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) @@ -186,10 +201,10 @@ class Engine { } 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)) { + } else if (this._order && this._order.selfFirst && orderedBy(p.node)) { // (SNOMED CT is-a, ECL <<: the concept, then its descendants in the system order; <: the ancestors nearest first) + r.add({ list: yield* this._eclOrdered(ev, orderedBy(p.node), b) }); } else if (this._order) { r.add({ list: this._ordered(b) }); } else { @@ -288,8 +303,44 @@ class Engine { const right = yield* this._eclOrdered(ev, node.items[1], RoaringBitmap32.andNot(b, inLeft)); return left.concat(right); } + case 'history': { + const inBase = RoaringBitmap32.and(b, yield* ev.matG(node.of)); + const base = yield* this._eclOrdered(ev, node.of, inBase); + const added = this._ordered(RoaringBitmap32.andNot(b, inBase)); + return base.concat(added); + } default: break; } + if (node.t === 'anc') { + // level by level from the concept's parents, each concept's parents in release order; the + // concept itself (>>) last: as cs-snomed.js filterGeneralizes and ecl.js list them + const out = []; + const seen = new Set(); + let level = this.store.parentsInOrder(node.id); + while (level.length) { + const next = []; + for (const id of level) { + if (seen.has(id)) continue; + seen.add(id); + if (b.has(id)) out.push(id); + next.push(...this.store.parentsInOrder(id)); + } + level = next; + } + if (out.length < b.size) out.push(...this._ordered(RoaringBitmap32.andNot(b, new RoaringBitmap32(out)))); + return out; + } + if (node.t === 'parents') { + // direct parents in release order; self (>>!) first, as cs-snomed.js lists them + const out = []; + const seen = new Set(); + if (node.self && b.has(node.id)) { seen.add(node.id); out.push(node.id); } + for (const id of this.store.parentsInOrder(node.id)) { + if (!seen.has(id) && b.has(id)) { seen.add(id); out.push(id); } + } + if (out.length < b.size) out.push(...this._ordered(RoaringBitmap32.andNot(b, new RoaringBitmap32(out)))); + return out; + } if (node.t === 'self' && b.has(node.id)) { const rest = b.clone(); rest.remove(node.id); return [node.id, ...(node.of ? yield* this._eclOrdered(ev, node.of, rest) : this._ordered(rest))]; diff --git a/tx/sqlite-v2/engine/evaluate.js b/tx/sqlite-v2/engine/evaluate.js index a248504a..c2e74614 100644 --- a/tx/sqlite-v2/engine/evaluate.js +++ b/tx/sqlite-v2/engine/evaluate.js @@ -76,7 +76,7 @@ function* spanG(trace, label, kind, system, g) { } } -const FREE = new Set(['all', 'active', 'inactive', 'leaf', 'empty', 'ids', 'set']); +const FREE = new Set(['listed', 'all', 'active', 'inactive', 'leaf', 'empty', 'ids', 'set']); class Unsupported extends Error { constructor(reason, detail) { @@ -199,6 +199,8 @@ class Evaluator { 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)); + // the listed concepts (README.md "Concept status": not unlisted) + case 'listed': return S.listed(st) || S.all(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); @@ -273,8 +275,8 @@ class Evaluator { 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 'search': return (yield* S.searchTextG(node.text, st, node.lang || null)) || new RoaringBitmap32(); + case 'group': return yield* this._group(node, yield* this.matG({ t: 'and', items: node.attrs.map(attrNode) }), true); case 'attrCard': { const has = yield* this.matG(node.base); // at least one occurrence const counted = yield* this._attrCard(node, has); @@ -559,13 +561,19 @@ class Evaluator { 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); + // Concept-valued association reference sets only (as cs-snomed.js _historyIndex: concept + // subjects with a concept target). Description-level refsets such as 900000000000531004 + // |REFERS TO| reference inactivated descriptions, not inactive concepts. + const def = S.refsetDef(refsetId); + if (def && def.types[0] === 'c') { + const rows = S.refsetMemberRows(refsetId, null, { raw: true, conceptsOnly: true }); + for (const r of rows) { + const raw = r.f[0]; + const t = typeof raw === 'number' ? raw : (raw ? S.idOf(String(raw)) : null); + if (t == null || t > S.hi) continue; + if (!m.has(t)) m.set(t, []); + m.get(t).push(r.concept_id); + } } this.history.set(refsetId, m); } @@ -598,32 +606,39 @@ class Evaluator { * 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) { + * _group(node, cand, preFiltered = false) { let pre = cand; - for (const a of node.attrs) pre = yield* this.filterG(attrNode(a), pre); + if (!preFiltered) { + 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++; + this.spend(pre.size * 8, 'group count'); + const ids = pre.toArray(); + for (let i = 0; i < ids.length; i += 50000) { + if (i) yield; + const rows = this.store.linksFrom(ids.slice(i, i + 50000), allPids, true, this.stats); + 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); + } + for (const [s, groups] of bySource) { + let n = 0; + for (const g of groups.values()) { + if (node.attrs.every((a, j) => g.some((r) => a.pids.includes(r.p) && valueSets[j].has(r.t)))) n++; + } + if (n >= min && n <= max) out.add(s); } - if (n >= min && n <= max) out.add(s); } return out; } diff --git a/tx/sqlite-v2/icd11.js b/tx/sqlite-v2/icd11.js new file mode 100644 index 00000000..ec8045aa --- /dev/null +++ b/tx/sqlite-v2/icd11.js @@ -0,0 +1,442 @@ +'use strict'; +// The grammar `icd11` (README.md "Grammar"): postcoordinated expressions (1A00&XN8P1, +// NA00.2&XK8G/PG50, ICF's d5409.qp3). Parsing, binding to axes, the normal form and the validation +// issues are upstream's (tx/cs/icd11-expressions.js parseExpression, plainCodeIssues), run over this +// file: the grammar reads the axes a code declares from the record relation `postcoordinationAxis` +// (fields axis, axisCode, required, allowMultiple, valueSet; seq the axis's place) and the roots of +// an axis's permitted values from `postcoordinationRoot` (target the root, field axisSeq), a value +// being permitted when it is a root or one of its descendants. A part of an expression is a concept +// code or an identifier the file accepts as a code; its classification-code form is its alias of the +// scheme with alias_parameter. What an expression answers ($lookup's stem and postcoordination +// entries, its display from its parts' displays) is upstream's cs-icd11.js, as code here. No filter +// selects an expression, and the filters' selections are closed. Everything about plain codes is the +// generic reader's, but a plain code's postcoordination axes in $lookup with +// post-coordination-metadata, and its validation issues (a required axis left empty). + +const { SqliteV2Provider, SqliteV2Factory, V2Concept } = require('./provider'); +const { ICD11Expression, parseExpression, plainCodeIssues, axisLabel, SCHEMA_NS } = require('../cs/icd11-expressions'); +const { CodeSystem } = require('../library/codesystem'); +const { KIND } = require('./store'); + +/** the record relations the grammar reads, and the fields it reads of each */ +const AXES = { relation: 'postcoordinationAxis', fields: ['axis', 'axisCode', 'required', 'allowMultiple', 'valueSet'] }; +const ROOTS = { relation: 'postcoordinationRoot', fields: ['axisSeq'], target: 'root' }; +const ALLOW_MULTIPLE_CS = `${SCHEMA_NS}/allowMultipleValues`; + +/** a part of an expression, as upstream's parser reads one (ICD11Concept's fields) */ +class Icd11Part { + constructor(v2, shortCode) { + this.v2 = v2; + this.id = v2.id; + this.entityId = v2.code; + this.code = shortCode; + } + get canonicalCode() { return this.entityId; } +} + +/** the positions of a record relation's fields (non-target fields, in schema order), or a reason it lacks one */ +function fieldPositions(d, spec) { + const fields = d.fields || []; + const own = fields.filter((f) => !f.target); + const pos = {}; + for (const name of spec.fields) { + const i = own.findIndex((f) => f.name === name); + if (i < 0) return { missing: name }; + pos[name] = i; + } + if (spec.target && !fields.some((f) => f.target && f.name === spec.target)) return { missing: spec.target }; + return { pos }; +} + +class Icd11V2Provider extends SqliteV2Provider { + // ---- expressions ------------------------------------------------------------------------- + + /** what upstream's parser reads: a code as a part, a code's axes, whether a value is permitted on an axis */ + _expressionContext() { + const S = this.store; + const g = this.f.icd11; + const st = this._stats(); + const axisById = new Map(); + const axesOf = (conceptId) => { + const rows = S.recordRowsOf(g.axes.id, conceptId).map((r) => { + const f = r.fields; + const axis = { id: `${conceptId}/${r.seq}`, concept: conceptId, seq: r.seq, axis: f[g.axesPos.axis], axis_name: f[g.axesPos.axisCode], + required: Number(f[g.axesPos.required]) ? 1 : 0, allow_multiple: f[g.axesPos.allowMultiple] ?? null, value_set_uri: f[g.axesPos.valueSet] ?? null }; + axisById.set(axis.id, axis); + return axis; + }); + // in binding preference: required axes first, then definition order + return rows.sort((a, b) => (b.required - a.required) || (a.seq - b.seq)); + }; + const permitted = (axisId, valueId) => { + const axis = axisById.get(axisId); + if (!axis) return false; + for (const r of S.recordRowsOf(g.roots.id, axis.concept)) { + if (r.target == null || Number(r.fields[g.rootsPos.axisSeq]) !== axis.seq) continue; + if (r.target === valueId || S.getSet(KIND.descendants, 0, r.target, st).has(valueId)) return true; + } + return false; + }; + return { + resolve: async (text) => this._part(text), + // upstream's parser asks two questions of its database, as SQL over its tables: the axes of a + // code (pc_scale) and whether a value is under a root of an axis (pc_scale_entity) + all: async (sql, params) => { + if (/\bFROM pc_scale\b/.test(sql)) return axesOf(params[0]); + throw new Error('icd11 grammar: an unexpected query of the expression parser'); + }, + get: async (sql, params) => { + if (/\bpc_scale_entity\b/.test(sql)) return permitted(params[0], params[1]) ? { ok: 1 } : undefined; + throw new Error('icd11 grammar: an unexpected query of the expression parser'); + }, + translate: (msgId, params) => this.opContext.i18n.translate(msgId, this.opContext.langs, params), + }; + } + + /** a code (a concept code, or an identifier accepted as a code) as a part of an expression, or null */ + async _part(text) { + const S = this.store; + const n = this.normaliseCode(text); + let row = S.rowForCode(n, this._stats()); + if (!row && S.hasCodeIdentifiers) row = S.identifierAsCode(n, this._stats()); + if (!row) return null; + const c = this._concept(row.concept_id, row); + return new Icd11Part(c, await this.classificationCode(c)); + } + + async _locate(code, prefetched = null) { + const r = await super._locate(code, prefetched); + if (r.context || typeof code !== 'string' || !/[&/.]/.test(code)) return r; + // not a code as written: a postcoordinated expression? (null: it does not resolve; an Issue is + // thrown when it resolves but is wrong: a qualifier on no axis of the code it qualifies) + const expr = await parseExpression(this._expressionContext(), code); + return expr ? { context: expr, message: null } : r; + } + + /** a listed code with the grammar's separators may be an expression: the usual path locates it */ + _plainListedCode(code) { return super._plainListedCode(code) && !/[&/.]/.test(code); } + + async _ensure(context) { + if (context instanceof ICD11Expression) return context; + return super._ensure(context); + } + + async code(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? c.canonicalCode : super.code(c); + } + + async classificationCode(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? (c.classificationCode || null) : super.classificationCode(c); + } + + /** an expression written with entity ids only (in any order) is reported with its classification-code form */ + async reportedClassificationCode(context, code) { + const c = await this._ensure(context); + if (!(c instanceof ICD11Expression)) return super.reportedClassificationCode(c, code); + return c.tokens.every((t) => t.text === t.concept.canonicalCode) ? this.classificationCode(c) : null; + } + + /** an expression's issues; a plain code's: a required axis is left empty */ + async codeIssues(context, code) { + const c = await this._ensure(context); + if (c instanceof ICD11Expression) return c.issues; + if (!(c instanceof V2Concept) || c.alias) return []; + return plainCodeIssues(this._expressionContext(), new Icd11Part(c, null), code || c.code); + } + + /** the display of a part: the concept's display (in a requested language where the file gives one) */ + async _title(part) { + const c = await this._ensure(part.v2); + return c ? this._displayOf(c).term || null : null; + } + + /** + * An expression's display (cs-icd11.js #expressionDisplay): the members as written, each value in + * brackets after its code. Its language is the language of its parts' displays where they all + * have one and the same; else (parts in different languages, or a supplement's display, whose + * language is not known) the display designation's (_displayLanguageOf) + * @returns {{text: string, language: string}} + */ + async _expressionDisplayOf(expr) { + const languages = new Set(); + const title = async (token) => { + const c = await this._ensure(token.concept.v2); + const got = c ? this._displayOf(c) : { term: '', language: null }; + if (!got.term) return token.text; + languages.add(got.language); + return got.term; + }; + const parts = []; + for (const m of expr.members) { + let text = await title(m.head); + for (const t of m.tail) text += ` [${await title(t)}]`; + parts.push(text); + } + const [only] = languages; + return { text: parts.join(' / '), language: languages.size === 1 && only ? only : this._displayLanguageOf(null) }; + } + + async display(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? (await this._expressionDisplayOf(c)).text : super.display(c); + } + + async definition(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? null : super.definition(c); + } + + async isAbstract(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? false : super.isAbstract(c); + } + + async isInactive(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? false : super.isInactive(c); + } + + async isDeprecated(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? false : super.isDeprecated(c); + } + + async getStatus(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? null : super.getStatus(c); + } + + /** an expression has one designation: its display, in the language of its text */ + async _designations(context, displays, significantOnly) { + const c = await this._ensure(context); + if (!(c instanceof ICD11Expression)) return super._designations(c, displays, significantOnly); + // labelled with the language its text is in, not the one asked for: a request for es of a file + // whose parts' displays are English is answered in en, and the lookup warns there is no es display + const { text, language } = await this._expressionDisplayOf(c); + if (text) displays.addDesignation(true, 'active', language, CodeSystem.makeUseForDisplay(), text); + } + + async properties(context, names) { + const c = await this._ensure(context); + if (!(c instanceof ICD11Expression)) return super.properties(c, names); + const out = [{ code: 'code', valueCode: c.canonicalCode }]; + if (c.classificationCode) out.push({ code: 'classificationCode', valueCode: c.classificationCode }); + return out; + } + + async iterator(context) { + const c = await this._ensure(context); + if (c instanceof ICD11Expression) return { ids: [], pos: 0, total: 0 }; + return super.iterator(c); + } + + async subsumesTest(codeA, codeB) { + const a = await this._ensure(codeA); + const b = await this._ensure(codeB); + // an expression has no place in the hierarchy + if (a instanceof ICD11Expression || b instanceof ICD11Expression) return 'not-subsumed'; + return super.subsumesTest(a, b); + } + + // ---- filters: no filter selects an expression, and the selections are closed --------------- + + /** + * the grammar's reason for a located code that a filter does not select (cs-icd11.js filterCheck): + * `'' is not in the value set`, the code as the classification writes it (its alias of the + * scheme with alias_parameter), else the concept's code; for an include of one filter (with more, + * the general reason) + */ + async _filterLocate(prep, set, code) { + const r = await this.locate(code); + if (r.context instanceof ICD11Expression) return `'${r.context.canonicalCode}' is not in the value set`; + const found = await super._filterLocate(prep, set, code); + if (found != null || !(r.context instanceof V2Concept) || (set.specs || []).length !== 1) return found; + const scheme = this.store.aliasParameterScheme; + const written = (scheme && this.store.aliasValuesOf(scheme, r.context.id)[0]) || r.context.code; + return `'${written}' is not in the value set`; + } + + async filterCheck(prep, set, concept) { + if (concept instanceof ICD11Expression) return false; + return super.filterCheck(prep, set, concept); + } + + async filtersNotClosed() { return false; } + + // ---- $lookup --------------------------------------------------------------------------------- + + async extendLookup(context, props, params, txParams) { + this._pcMetadata = !!(txParams && txParams.postCoordinationMetadata); + return super.extendLookup(context, props, params); + } + + /** + * $lookup (cs-icd11.js extendLookup): an expression's code, classificationCode, stem and + * postcoordination entries; a plain code's properties, then with post-coordination-metadata its + * axes, unvalued + */ + async _extendLookup(context, props, params) { + const c = await this._ensure(context); + const meta = !!this._pcMetadata; + if (c instanceof ICD11Expression) { + if (this._hasProp(props, 'code', true)) this._addCodeProperty(params, 'property', 'code', c.canonicalCode); + if (c.classificationCode && this._hasProp(props, 'classificationCode', true)) this._addCodeProperty(params, 'property', 'classificationCode', c.classificationCode); + const root = c.stems[0]; + if (this._hasProp(props, 'stem', true)) { + params.push({ name: 'property', part: [{ name: 'code', valueCode: 'stem' }, { name: 'value', valueCoding: await this._coding(root.stem.concept) }] }); + } + if (this._hasProp(props, 'postcoordination', true)) { + for (const part of await this._postcoordination(c, root, true, meta)) params.push({ name: 'property', part }); + } + return; + } + await super._extendLookup(c, props, params); + if (meta && c instanceof V2Concept && this._hasProp(props, 'postcoordination', true)) { + const ctx = this._expressionContext(); + const axes = (await ctx.all('SELECT FROM pc_scale WHERE concept = ?', [c.id])).sort((a, b) => a.seq - b.seq); + for (const axis of axes) params.push({ name: 'property', part: this._axisEntry(axis, true) }); + } + } + + /** a part as a Coding of this system, with its display */ + async _coding(part) { + const c = { system: this.system(), code: part.canonicalCode }; + const label = await this._title(part); + if (label) c.display = label; + return c; + } + + /** the postcoordination entries of a code of an expression (cs-icd11.js #postcoordination) */ + async _postcoordination(expr, st, isRoot, meta) { + const pos = (t) => expr.tokens.indexOf(t); + const out = []; + for (const axis of [...st.axes].sort((a, b) => a.seq - b.seq)) { + const values = st.bindings.filter((b) => b.axis === axis).map((b) => b.token).sort((a, b) => pos(a) - pos(b)); + if (!meta && values.length === 0) continue; + const part = this._axisEntry(axis, meta); + for (const t of values) part.push(await this._valuePart(expr, t, meta)); + out.push(part); + } + if (isRoot) { + // `/` members on no axis of the root still qualify it + const loose = expr.tokens.filter((t) => t.sep === '/' && !t.axis); + if (loose.length) { + const part = [{ name: 'code', valueCode: 'postcoordination' }]; + for (const t of loose) part.push(await this._valuePart(expr, t, meta)); + out.push(part); + } + } + return out; + } + + /** the start of a postcoordination entry: the axis, and with the metadata its rules (cs-icd11.js #axisEntry) */ + _axisEntry(axis, meta) { + const sub = (code, value) => ({ name: 'subproperty', part: [{ name: 'code', valueCode: code }, { name: 'value', ...value }] }); + const part = [{ name: 'code', valueCode: 'postcoordination' }, + sub('axis', { valueCoding: { system: SCHEMA_NS, code: axis.axis_name, display: axisLabel(axis.axis_name) } })]; + if (!meta) return part; + part.push(sub('required', { valueBoolean: !!axis.required })); + if (axis.allow_multiple) part.push(sub('allowMultipleValues', { valueCoding: { system: ALLOW_MULTIPLE_CS, code: axis.allow_multiple } })); + if (axis.value_set_uri) part.push(sub('valueSet', { valueString: axis.value_set_uri })); + return part; + } + + /** one value subproperty; a `/` member carries its own axes inside it (cs-icd11.js #valuePart) */ + async _valuePart(expr, token, meta) { + const part = [{ name: 'code', valueCode: 'value' }, { name: 'value', valueCoding: await this._coding(token.concept) }]; + const member = token.sep === '/' ? expr.stems.find((st) => st.stem === token) : null; + if (member) for (const p of await this._postcoordination(expr, member, false, meta)) part.push({ name: 'subproperty', part: p }); + return { name: 'subproperty', part }; + } +} + +class Icd11V2Factory extends SqliteV2Factory { + static grammar = 'icd11'; + + async load() { + await super.load(); + // the record relations the grammar reads, with the fields it reads: a file without them is refused + const S = this.store; + const rel = (spec) => { + const d = S.catalog.get(spec.relation); + if (!d || d.shape !== 'record') throw new Error(`${this.file}: the grammar icd11 reads the record relation ${spec.relation}, which the file does not have`); + const r = fieldPositions(d, spec); + if (r.missing) throw new Error(`${this.file}: the grammar icd11 reads the field ${r.missing} of ${spec.relation}, which the relation does not have`); + return { d, pos: r.pos }; + }; + try { + const axes = rel(AXES); + const roots = rel(ROOTS); + this.icd11 = { axes: axes.d, axesPos: axes.pos, roots: roots.d, rootsPos: roots.pos }; + } catch (e) { + S.close(); + throw e; + } + } + + async build(opContext, supplements) { + this.recordUse(); + return new Icd11V2Provider(opContext, supplements, this); + } + + /** + * The file's implicit value sets, then the grammar's: the value set a postcoordinationAxis row + * names in its field valueSet (a postcoordination scale), as upstream's cs-icd11.js + * buildKnownValueSet makes it: one include per root of the axis (postcoordinationRoot rows whose + * axisSeq is the axis's seq, in seq order), each `concept is-a `; named after the system's + * last path segment, the stem's code and the axis code, titled with the stem's classification code + * (its alias of the scheme with alias_parameter), else its code + */ + async buildKnownValueSet(url, version) { + const vs = await super.buildKnownValueSet(url, version); + if (vs || !url || (version && version !== this.version())) return vs; + const S = this.store; + const g = this.icd11; + const stemCode = url.startsWith(`${S.system}/`) && url.includes('/postcoordinationScale/') + ? url.substring(S.system.length + 1, url.indexOf('/postcoordinationScale/')) : null; + const stemId = stemCode != null ? S.idOf(stemCode) : null; + let axis = null; + if (stemId != null) { + const r = S.recordRowsOf(g.axes.id, stemId).find((x) => x.fields[g.axesPos.valueSet] === url); + if (r) axis = { subject: stemId, seq: r.seq, fields: r.fields }; + } else if (stemCode == null) { + // a URL of another form: the first row (by subject, then seq) that names it + const r = S.stmt(`SELECT subject_id, seq, fields FROM main.record WHERE relation_id = ? AND active = 1 + AND json_extract(fields, '$[${g.axesPos.valueSet}]') = ? ORDER BY subject_id, seq LIMIT 1`).get(g.axes.id, url); + if (r) axis = { subject: r.subject_id, seq: r.seq, fields: JSON.parse(r.fields) }; + } + if (!axis) return null; + const stem = S.conceptRows([axis.subject]).get(axis.subject); + if (!stem) return null; + const axisName = axis.fields[g.axesPos.axisCode]; + const roots = S.recordRowsOf(g.roots.id, axis.subject).filter((r) => r.target != null && Number(r.fields[g.rootsPos.axisSeq]) === axis.seq); + const rootCodes = S.conceptRows(roots.map((r) => r.target)); + const scheme = S.aliasParameterScheme; + const label = (scheme && S.aliasValuesOf(scheme, axis.subject)[0]) || stem.code; + const slug = `${S.system.split('/').pop()}-${stem.code}-${axisName}`.replace(/\//g, '-'); + return { + resourceType: 'ValueSet', + id: `icd11-${slug}`.slice(0, 64), + url, + version: this.version(), + name: `ICD11_${slug.replace(/[^A-Za-z0-9_]/g, '_')}`, + title: `${axisName} for ${label}`, + status: 'active', + experimental: false, + date: this.version(), + publisher: 'World Health Organization', + description: `The values WHO permits on the ${axisName} postcoordination axis of ${label}.`, + compose: { + include: roots.filter((r) => rootCodes.has(r.target)).map((r) => ({ + system: S.system, + version: this.version(), + filter: [{ property: 'concept', op: 'is-a', value: rootCodes.get(r.target).code }], + })), + }, + }; + } +} + +module.exports = { Icd11V2Factory, Icd11V2Provider }; diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js index b3d4ab91..0057742e 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -1,13 +1,38 @@ 'use strict'; // sqlite-v2 terminology files: provider registration entry point. // -// A library source line `snomed-v2:`, `loinc-v2:` or `rxnorm-v2:` loads one file +// A library source line `sqlite-v2:` (any code system), `snomed-v2:`, `loinc-v2:`, +// `rxnorm-v2:`, `ndc-v2:`, `unii-v2:` or `cpt-v2:` loads one file // (Library.loadSqliteV2). Without such a line nothing here, nor roaring, is loaded. const Database = require('../../library/sql/better-sqlite3'); const { SqliteV2Factory } = require('./provider'); const { SnomedV2Factory } = require('./snomed'); +const { CptV2Factory } = require('./cpt'); +const { Icd11V2Factory } = require('./icd11'); const { checkFormat } = require('./store'); +const { readMeta } = require('./meta'); + +/** + * The code grammars this server implements, by name (meta grammar): the factory that + * serves a file whose codes have it. A file without a grammar has plain codes (SqliteV2Factory); a + * grammar not here refuses the file. + */ +const GRAMMARS = Object.freeze({ + // SNOMED CT expressions and ECL (snomed.js) + snomed: SnomedV2Factory, + // codes with modifiers (cpt.js) + cpt: CptV2Factory, + // ICD-11 postcoordinated expressions (icd11.js) + icd11: Icd11V2Factory, +}); + +/** the factory class for a grammar; throws for a grammar this server does not implement */ +function factoryForGrammar(grammar, file) { + if (grammar == null) return SqliteV2Factory; + if (Object.prototype.hasOwnProperty.call(GRAMMARS, grammar)) return GRAMMARS[grammar]; + throw new Error(`${file}: its codes are in the grammar ${grammar} (meta grammar), which this server does not implement`); +} /** a factory for the file, chosen by the grammar it says its codes have */ async function loadSqliteV2Factory(i18n, file, opts = {}) { @@ -15,14 +40,16 @@ async function loadSqliteV2Factory(i18n, file, opts = {}) { let grammar; try { checkFormat(db, file); - grammar = JSON.parse(db.prepare("SELECT value FROM main.meta WHERE key = 'behaviour.grammar'").pluck().get() || 'null'); + // the revision first (a file written before fhir-reading names its grammar elsewhere) + readMeta(db.prepare("SELECT key, value FROM main.meta WHERE key NOT LIKE 'provenance.%'").raw().all(), file); + grammar = JSON.parse(db.prepare("SELECT value FROM main.meta WHERE key = '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); + const Factory = factoryForGrammar(grammar, file); + const factory = new Factory(i18n, file, opts); await factory.load(); return factory; } -module.exports = { loadSqliteV2Factory }; +module.exports = { loadSqliteV2Factory, factoryForGrammar, GRAMMARS }; diff --git a/tx/sqlite-v2/integrity.js b/tx/sqlite-v2/integrity.js new file mode 100644 index 00000000..9f5a746e --- /dev/null +++ b/tx/sqlite-v2/integrity.js @@ -0,0 +1,84 @@ +'use strict'; +// Integrity facts of a terminology file (meta `integrity`, optional; README.md "Integrity facts"): +// written by the step that finishes a file (tx/importers/sqlite-v2/builder.js finishFile), checked on +// request by tx/importers/sqlite-v2/verify.js (checkIntegrity). Readers do not check them. +// +// items the number of item rows (item ids are exactly N+1 .. N+M) +// schema SHA-256 (lower-case hex) of `type TAB name TAB tbl_name TAB sql` for every row of +// sqlite_master ORDER BY type, name (NULL sql as ''), rows joined by LF +// catalog SHA-256 of the catalog tables' rows, in CATALOG order: each row is the table name, TAB, +// then every column (PRAGMA table_info order) as SQLite's quote(), joined by ','; rows of +// all tables joined by LF. meta leaves out provenance.* and integrity + +const crypto = require('crypto'); +const fs = require('fs'); + +/** the catalog tables, in digest order, with their row order */ +const CATALOG = Object.freeze([ + ['code_system', 'cs_id'], + ['meta', 'key'], + ['property', 'id'], + ['property_member', 'parent_id, child_id'], + ['item_use', 'use_id'], + ['filter', 'id'], + ['value_label', 'property_id, value'], +]); + +const sha256 = (s) => crypto.createHash('sha256').update(s, 'utf8').digest('hex'); + +/** the text the schema digest is made of */ +function schemaText(db) { + return db.prepare('SELECT type, name, tbl_name, sql FROM main.sqlite_master ORDER BY type, name').raw().all() + .map(([type, name, tbl, sql]) => `${type}\t${name}\t${tbl}\t${sql ?? ''}`).join('\n'); +} + +/** the text the catalog digest is made of */ +function catalogText(db) { + const lines = []; + for (const [table, order] of CATALOG) { + const cols = db.prepare(`PRAGMA main.table_info("${table}")`).all().sort((a, b) => a.cid - b.cid).map((c) => c.name); + const expr = cols.map((c) => `quote("${c.replace(/"/g, '""')}")`).join(" || ',' || "); + const where = table === 'meta' ? " WHERE substr(key, 1, 11) <> 'provenance.' AND key <> 'integrity'" : ''; + for (const row of db.prepare(`SELECT ${expr} FROM main."${table}"${where} ORDER BY ${order}`).pluck().iterate()) lines.push(`${table}\t${row}`); + } + return lines.join('\n'); +} + +const schemaDigest = (db) => sha256(schemaText(db)); +const catalogDigest = (db) => sha256(catalogText(db)); + +/** the facts as a finished file states them (meta integrity); counts every item row */ +function computeIntegrity(db) { + return { items: db.prepare('SELECT count(*) FROM main.item').pluck().get(), schema: schemaDigest(db), catalog: catalogDigest(db) }; +} + +/** meta integrity's text, as writers write it */ +function integrityValue(facts) { + return JSON.stringify({ items: facts.items, schema: facts.schema, catalog: facts.catalog }); +} + +/** + * Check the facts against the file: its length, the schema and catalog digests, the item count. + * Returns [{check, ok, detail}]. + * @param {Database} db an open connection to the file + * @param {string|null} file its path (null: no length check) + * @param {{items, schema, catalog}} stored meta integrity + */ +function checkIntegrity(db, file, stored) { + const out = []; + const add = (check, ok, detail) => out.push({ check, ok, detail }); + if (file) { + const size = fs.statSync(file).size; + const pages = db.pragma('main.page_count', { simple: true }) * db.pragma('main.page_size', { simple: true }); + add('file length', size === pages, `${size} bytes, page_count * page_size = ${pages}`); + } + const schema = schemaDigest(db); + add('schema digest', schema === stored.schema, `${schema}, meta integrity says ${stored.schema}`); + const catalog = catalogDigest(db); + add('catalog digest', catalog === stored.catalog, `${catalog}, meta integrity says ${stored.catalog}`); + const items = db.prepare('SELECT count(*) FROM main.item').pluck().get(); + add('item count', items === stored.items, `${items} item rows, meta integrity says ${stored.items}`); + return out; +} + +module.exports = { CATALOG, schemaText, catalogText, schemaDigest, catalogDigest, computeIntegrity, integrityValue, checkIntegrity }; diff --git a/tx/sqlite-v2/layers.js b/tx/sqlite-v2/layers.js index 7b0f21d1..01eafd3f 100644 --- a/tx/sqlite-v2/layers.js +++ b/tx/sqlite-v2/layers.js @@ -39,10 +39,11 @@ const LITERAL_TYPE = { code: 'code', string: 'string', integer: 'integer', decim let layerSeq = 0; class Layer { - constructor(store, info) { + constructor(store, info, conceptOrder = null) { this.id = ++layerSeq; this.store = store; this.info = info; // { url, version, concepts, unknownCodes, buildMs, properties } + this.conceptOrder = conceptOrder; } } @@ -71,10 +72,12 @@ function fillLayer(db, base, json) { 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 insUse = db.prepare('INSERT INTO item_use (use_id, system, code, display) VALUES (?, ?, ?, ?)'); // (reported_as: NULL) 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 conceptOrder = []; + const seenConcept = new Set(); const tx = db.transaction(() => { const prop = (code, uri, type) => { let pid = props.get(code); @@ -91,6 +94,7 @@ function fillLayer(db, base, json) { for (const c of concepts) { const id = ids.get(c.code); if (id == null) { unknown++; continue; } + if (!seenConcept.has(id)) { seenConcept.add(id); conceptOrder.push(id); } insConcept.run(id, c.code, c.display || null); for (const d of c.designation || []) { if (d.value == null || d.value === '') continue; @@ -117,9 +121,9 @@ function fillLayer(db, base, json) { // 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); + const insProp = db.prepare(`INSERT INTO property (id, cs_id, code, uri, shape, fhir_type, subject_kind) + VALUES (?, 1, ?, ?, 'literal', ?, ?)`); + for (const [pid, t] of types) insProp.run(pid, t.code, t.uri, t.type, counts.get(pid) ? 'concept' : null); // 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)); }; @@ -145,10 +149,11 @@ function fillLayer(db, base, json) { 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); + db.prepare("INSERT INTO meta (key, value) VALUES ('requires', ?)").run(JSON.stringify(require('./meta').WRITTEN_FEATURES)); }); tx(); db.pragma('user_version = 1'); - return { concepts, unknown, props }; + return { concepts, unknown, props, conceptOrder }; } /** @@ -160,14 +165,14 @@ 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 { concepts, unknown, props, conceptOrder } = 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()]) })); + buildMs: Math.round(ms * 10) / 10, bytes, properties: Object.freeze([...props.keys()]) }), conceptOrder); } /** sha-256 of a supplement's content; computed once per resource object (resources are not mutated) */ @@ -283,8 +288,8 @@ class LayerSet { 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}` }; + const node = new Compiler({ store: l.store, grammar: {} }, { stats: compiler.stats }).propertyFilter(def, op, value); + return { t: 'layer', layer: l, node, op, value, label: `supplement ${l.info.url} ${prop} ${op} ${value}` }; } return null; } diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js new file mode 100644 index 00000000..0da74e47 --- /dev/null +++ b/tx/sqlite-v2/meta.js @@ -0,0 +1,279 @@ +'use strict'; +// The meta table of a terminology file (tx-terminology/1, revision fhir-reading; tx/sqlite-v2/README.md "Meta"): +// +// - `requires` lists the features the file's content uses that a reader must understand; a +// reader refuses a file that requires a feature it does not know. Every file of this revision +// requires `identifier-text` and `fhir-reading`; a file without `fhir-reading` was written +// before it and is refused (there is no reading of the earlier keys). +// - A reader ignores a key it does not know (a writer that adds something every reader must +// understand names a feature in `requires`). A known key with a malformed value is refused, +// and so is a key of the earlier revisions (behaviour.*, linkOrder, searchTieBreak, +// propertyUris, ix.ix_word.names): in a file that says fhir-reading it is a writer's mistake. +// - A builder checks every key it writes against its own list (KEYS here, plus WRITER_KEYS) and +// refuses to finish a file with a key it does not know, so a typo is caught when it is made. +// `provenance.*` is free-form. +// +// readMeta is the one check; the reader (store.js) and the builder (tx/importers/sqlite-v2/builder.js) +// both run it. + +const FORMAT = 'tx-terminology/1'; + +/** the features a file may require (README.md "Identification") */ +const KNOWN_FEATURES = Object.freeze(['identifier-text', 'fhir-reading']); + +/** the features every file this builder writes requires */ +const WRITTEN_FEATURES = Object.freeze(['identifier-text', 'fhir-reading']); + +/** the marker of this revision */ +const REVISION = 'fhir-reading'; + +/** the FHIR filter operators (a filter row's operators; an implicit value set template's op) */ +const FILTER_OPERATORS = Object.freeze(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'exists']); + +/** + * the words of filter.operators: the FHIR filter operators and `of`, which is no filter operator: it + * offers VCL `of` and set-valued `in` on the row (README.md "filter") + */ +const FILTER_ROW_OPERATORS = Object.freeze([...FILTER_OPERATORS, 'of']); + +/** the meanings conceptStatus may give a value (README.md "conceptStatus") */ +const STATUS_MEANINGS = Object.freeze(['inactive', 'deprecated', 'notSelectable', 'unlisted']); + +/** the words of each order member, and the member's default (README.md "order") */ +const ORDER_WORDS = Object.freeze({ + expansion: { words: ['id', 'stored', 'code'], default: ['id'] }, + searchTies: { words: ['id', 'stored', 'code', 'code-number', 'display'], default: ['id'] }, + links: { words: ['property-id', 'property', 'group', 'stored', 'code', 'code-number'], default: ['property-id', 'group', 'code'] }, + literals: { words: ['property-id', 'property', 'group', 'stored', 'value'], default: ['property-id', 'group', 'value'] }, +}); + +/** meta keys of the earlier revisions: a file of this revision that has one is refused */ +const REMOVED_KEYS = Object.freeze(['linkOrder', 'searchTieBreak', 'propertyUris', 'ix.ix_word.names']); + +const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); +const isString = (v) => typeof v === 'string'; +const isText = (v) => typeof v === 'string' && v !== ''; +const isStrings = (a) => Array.isArray(a) && a.every(isString); +const isTexts = (a) => Array.isArray(a) && a.every(isText); +const isDistinct = (a) => new Set(a).size === a.length; +const onlyKeys = (o, keys) => Object.keys(o).every((k) => keys.includes(k)); +const isBool = (v) => v === true || v === false; +const isHex64 = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v); +const isCount = (v) => Number.isSafeInteger(v) && v >= 0; +const isPositive = (v) => Number.isSafeInteger(v) && v >= 1; +const opt = (v, check) => v === undefined || check(v); +const DECIMAL = /^(0|[1-9][0-9]*)$/; + +/** conceptStatus (and compatibility.statusReadingsIgnored): [{property, values: {value: [meaning, ...]}}], one entry per property */ +const isStatusReadings = (v) => Array.isArray(v) && isDistinct(v.map((e) => e && e.property)) + && v.every((e) => isPlainObject(e) && onlyKeys(e, ['property', 'values']) && isText(e.property) && isPlainObject(e.values) + && Object.values(e.values).every((m) => Array.isArray(m) && m.length > 0 && isDistinct(m) && m.every((x) => STATUS_MEANINGS.includes(x)))); + +/** expansionLimits: {maxCodes?, wholeSystem?} */ +const isExpansionLimits = (v) => isPlainObject(v) && onlyKeys(v, ['maxCodes', 'wholeSystem']) + && opt(v.maxCodes, isPositive) && opt(v.wholeSystem, (x) => x === 'list' || x === 'refuse'); + +/** order: each member a list of its words */ +const isOrder = (v) => isPlainObject(v) && onlyKeys(v, Object.keys(ORDER_WORDS)) + && Object.entries(v).every(([k, l]) => Array.isArray(l) && l.length > 0 && isDistinct(l) && l.every((w) => ORDER_WORDS[k].words.includes(w))); + +/** search: {names?, candidates?, codeMatch?, codeHits?, nameScore?, shortlist?, supplementsChooseLanguage?} */ +const isSearchNames = (v) => isPlainObject(v) && onlyKeys(v, ['display', 'items']) && opt(v.display, isText) + && opt(v.items, (it) => isPlainObject(it) && onlyKeys(it, ['active', 'designations', 'includeUses', 'excludeUses', 'language']) + && opt(it.active, isBool) && opt(it.designations, isBool) && opt(it.excludeUses, isTexts) && opt(it.language, isText) + && opt(it.includeUses, (u) => Array.isArray(u) && u.every((x) => x === null || isText(x)))); +const isSearch = (v) => isPlainObject(v) + && onlyKeys(v, ['names', 'candidates', 'codeMatch', 'codeHits', 'nameScore', 'shortlist', 'supplementsChooseLanguage']) + && opt(v.names, isSearchNames) + && opt(v.candidates, (c) => isPlainObject(c) && onlyKeys(c, ['active', 'hasLiteral']) && opt(c.active, isBool) + && opt(c.hasLiteral, (h) => isPlainObject(h) && onlyKeys(h, ['property', 'except']) && isText(h.property) && opt(h.except, isStrings))) + && opt(v.codeMatch, (x) => x === 'text-prefix' || x === 'number-prefix') + && opt(v.codeHits, (x) => x === 'merged' || x === 'first') + && opt(v.nameScore, (x) => x === 'distinct-words' || x === 'as-written') + && opt(v.shortlist, isPositive) && opt(v.supplementsChooseLanguage, isBool); + +/** version: {match?, partial?, describe?} */ +const isVersion = (v) => isPlainObject(v) && onlyKeys(v, ['match', 'partial', 'describe']) + && opt(v.match, (x) => x === 'exact' || x === 'prefix') && opt(v.partial, isText) && opt(v.describe, (x) => x === 'release-date'); + +/** implicitValueSets: a list of templates, each {url, v?, mustBeCode?, include | enumerate, name?, title?, description?} or {grammar} */ +const isFilterSpec = (f) => isPlainObject(f) && onlyKeys(f, ['property', 'op', 'value']) && isText(f.property) && FILTER_OPERATORS.includes(f.op) && isString(f.value); +const isValidRegex = (s) => { try { new RegExp(s); return true; } catch (e) { return false; } }; +/** a template text: a string whose placeholders are {v}, {v_}, {display}, {version} only */ +const isTemplateText = (s) => isString(s) && (s.match(/\{[^}]*\}/g) || []).every((x) => ['{v}', '{v_}', '{display}', '{version}'].includes(x)); +const isTemplate = (t) => isPlainObject(t) && (Object.keys(t).length === 1 && isText(t.grammar) + || (onlyKeys(t, ['url', 'v', 'mustBeCode', 'include', 'enumerate', 'name', 'title', 'description']) && isText(t.url) + && opt(t.v, (x) => isString(x) && isValidRegex(x)) && opt(t.mustBeCode, isBool) + && ((t.include !== undefined) !== (t.enumerate !== undefined)) + && opt(t.include, isPlainObject) && opt(t.enumerate, isFilterSpec) + && opt(t.name, isTemplateText) && opt(t.title, isTemplateText) && opt(t.description, isTemplateText))); +const isImplicitValueSets = (v) => Array.isArray(v) && v.every(isTemplate); + +/** implicitMaps: {base?, maps?, used?, forwardOnly?, associations?} */ +const isImplicitMaps = (v) => isPlainObject(v) && onlyKeys(v, ['base', 'maps', 'used', 'forwardOnly', 'associations']) + && ((v.base === undefined) === (v.maps === undefined)) + && opt(v.base, isText) + && opt(v.maps, (m) => Array.isArray(m) && m.every((x) => Array.isArray(x) && x.length === 2 && isText(x[0]) && isText(x[1]))) + && opt(v.used, isText) && opt(v.forwardOnly, isBool) + && opt(v.associations, (a) => Array.isArray(a) && a.every((x) => isPlainObject(x) && onlyKeys(x, ['relation', 'equivalence', 'relationship']) + && isText(x.relation) && isText(x.equivalence) && isText(x.relationship))); + +/** compatibility: each member and its check (README.md "compatibility"); an unknown member is refused */ +const COMPATIBILITY = Object.freeze({ + statusReadingsIgnored: isStatusReadings, + generalizesLeavesOutFocus: isBool, + wholeSystemIncludeActiveOnly: isBool, + isAListsFocusFirst: isBool, + wholeSystemIncludeEmpty: isBool, + wholeSystemRefusalMessage: isText, + lookupOmitsTextDefinitions: isBool, + displayDesignation: (x) => ['none', 'once', 'always'].includes(x), + designationUse: (x) => x === 'source' || x === 'none', + typedDesignationsInLookup: isBool, + lookupListsCopyright: isBool, + lookupNameIsTitle: isBool, + expansionDeclaresProperties: isBool, + expansionKeepsRepeatedDesignations: isBool, + expansionNeverNests: isBool, + unknownCodeMessage: (x) => isString(x) && x.includes('{code}'), + filterUnknownCodeMessage: (x) => isString(x) && x.includes('{code}'), + filterRejectMessage: (x) => isString(x) && x.includes('{code}'), + missingValueFiltersAs: (x) => isPlainObject(x) && Object.values(x).every(isString), + translationDisplayIsSourceDisplay: isBool, + lookupRankWhenConceptHas: (x) => Array.isArray(x) && x.every((e) => isPlainObject(e) && onlyKeys(e, ['property', 'rank', 'when']) + && isText(e.property) && isCount(e.rank) && isText(e.when)), +}); +const COMPATIBILITY_DEFAULTS = Object.freeze({ + statusReadingsIgnored: [], generalizesLeavesOutFocus: false, wholeSystemIncludeActiveOnly: false, isAListsFocusFirst: false, + wholeSystemIncludeEmpty: false, wholeSystemRefusalMessage: null, lookupOmitsTextDefinitions: false, displayDesignation: 'none', + designationUse: 'source', typedDesignationsInLookup: false, lookupListsCopyright: false, lookupNameIsTitle: false, + expansionDeclaresProperties: true, expansionKeepsRepeatedDesignations: false, expansionNeverNests: false, unknownCodeMessage: null, + filterUnknownCodeMessage: null, filterRejectMessage: null, missingValueFiltersAs: {}, translationDisplayIsSourceDisplay: false, + lookupRankWhenConceptHas: [], +}); +const isCompatibility = (v) => isPlainObject(v) && Object.entries(v).every(([k, x]) => Object.prototype.hasOwnProperty.call(COMPATIBILITY, k) && COMPATIBILITY[k](x)); + +/** a JSON value: the text parses and the value passes; text: the text itself passes */ +const json = (check, dflt) => ({ json: true, check, default: dflt }); +const text = (check, dflt) => ({ json: false, check, default: dflt }); + +/** The keys this reader knows: key -> {json, check, default}. A key that is absent has its default. */ +const KEYS = Object.freeze({ + format: text((v) => v === FORMAT), + requires: json((v) => isStrings(v) && isDistinct(v), []), + // optional facts a tool checks on request (integrity.js, verify.js); readers do not + integrity: json((v) => isPlainObject(v) && onlyKeys(v, ['items', 'schema', 'catalog']) && isCount(v.items) && isHex64(v.schema) && isHex64(v.catalog), null), + // release facts with no column + languages: json(isStrings, []), + displayContexts: json((v) => isPlainObject(v) && isStrings(v.relations) && isString(v.preferred) + && (v.use == null || (isPlainObject(v.use) && isString(v.use.code))), null), + moduleDependencies: json((v) => Array.isArray(v) && v.every((r) => Array.isArray(r) && r.length === 4), []), + edition: text((v) => v !== '', null), + titles: json((v) => isPlainObject(v) && Object.values(v).every(isString), {}), + 'derived-by-importer': json((v) => Array.isArray(v) && v.every((d) => isPlainObject(d) && isString(d.table) && isString(d.name)), []), + // the FHIR reading (README.md "Meta keys") + conceptStatus: json(isStatusReadings, []), + expansionLimits: json(isExpansionLimits, {}), + order: json(isOrder, {}), + search: json(isSearch, null), + version: json(isVersion, { match: 'exact' }), + implicitValueSets: json(isImplicitValueSets, []), + implicitMaps: json(isImplicitMaps, {}), + // an open name: a reader refuses a grammar it does not implement (index.js) + grammar: json(isText, null), + compatibility: json(isCompatibility, {}), + // the link a page gives a code: a URL with {code}, the code URI-encoded (README.md "Code links") + codeLink: json((v) => isString(v) && v.includes('{code}'), null), + // facts about indexes + 'ix.ix_word.format': text((v) => v !== '', null), + 'ix.ix_word.stemmers': json((v) => isPlainObject(v) && Object.values(v).every((x) => isString(x) && x !== ''), null), +}); + +/** key patterns this reader knows (one entry per family): [test, spec] */ +const KEY_PATTERNS = Object.freeze([ + // the number of concepts a stored walk reaches (orders.js) + [(k) => /^ix\.ix_order\.[^.]+\.reached$/.test(k), text((v) => DECIMAL.test(v) && Number.isSafeInteger(Number(v)), null)], + // statistics of an ix_key index an importer writes (SNOMED CT normal forms; informational) + [(k) => /^ix\.ix_key\.[^.]+\.stats$/.test(k), json(isPlainObject, null)], +]); + +/** keys a builder of this repository writes that no reader reads (informational) */ +const WRITER_KEYS = Object.freeze({}); +const WRITER_PATTERNS = Object.freeze([]); + +const isProvenance = (key) => key.startsWith('provenance.'); + +function specOf(key) { + if (Object.prototype.hasOwnProperty.call(KEYS, key)) return KEYS[key]; + for (const [test, spec] of KEY_PATTERNS) if (test(key)) return spec; + return null; +} + +/** the message for a file written before this revision */ +function beforeRevision(name) { + return `${name}: a terminology file written before the fhir-reading revision; re-import it with the importers (tx-import), or upgrade it`; +} + +/** + * Check a file's meta and return the values of the keys this reader knows, defaults filled in. + * Throws, naming key and value, on a malformed value of a known key, on a key of an earlier + * revision, on a required feature this reader does not know, and on a file without fhir-reading. + * @param {Map|Iterable<[string,string]>} meta the rows of the table + * @param {string} file the file's name, for messages + * @param {object} [opts] { writer: true: the builder's check (a key it does not know is an error) } + * @returns {{values: Map, requires: string[], ignored: string[], get: function(string): *, + * compatibility: object}} + */ +function readMeta(meta, file, opts = {}) { + const name = typeof file === 'string' ? file : 'the file'; + const rows = [...meta]; + // the revision first: a file of an earlier revision is named as such, whatever else it holds + const req = rows.find(([k]) => k === 'requires'); + let requires = []; + if (req) { + try { requires = JSON.parse(req[1]); } catch (e) { throw new Error(`${name}: meta requires = ${String(req[1]).slice(0, 200)} is not JSON`); } + if (!KEYS.requires.check(requires)) throw new Error(`${name}: meta requires = ${String(req[1]).slice(0, 200)} is not a value this server knows`); + } + for (const f of requires) { + if (!KNOWN_FEATURES.includes(f)) throw new Error(`${name} requires the feature ${f}, which this server does not know (it knows ${KNOWN_FEATURES.join(', ')})`); + } + if (!requires.includes(REVISION) || !requires.includes('identifier-text')) throw new Error(beforeRevision(name)); + const values = new Map(); + const ignored = []; + for (const [key, raw] of rows) { + if (isProvenance(key)) continue; + if (key.startsWith('behaviour.') || REMOVED_KEYS.includes(key)) { + throw new Error(`${name}: meta ${key} is a key of an earlier revision, which a file that requires fhir-reading must not have`); + } + const spec = specOf(key) || (opts.writer ? (WRITER_KEYS[key] || (WRITER_PATTERNS.find(([t]) => t(key)) || [])[1]) : null); + if (!spec) { + if (opts.writer) throw new Error(`${name}: meta ${key} is not a key this builder knows (a typo?)`); + ignored.push(key); + continue; + } + if (typeof raw !== 'string') throw new Error(`${name}: meta ${key} is not text`); + let v = raw; + if (spec.json) { + try { v = JSON.parse(raw); } catch (e) { throw new Error(`${name}: meta ${key} = ${raw.slice(0, 200)} is not JSON`); } + } + if (!spec.check(v)) throw new Error(`${name}: meta ${key} = ${raw.slice(0, 200)} is not a value this server knows`); + values.set(key, v); + } + const get = (key) => (values.has(key) ? values.get(key) : KEYS[key].default); + // the template grammar form needs a grammar + if (get('implicitValueSets').some((t) => t.grammar !== undefined) && get('grammar') == null) { + throw new Error(`${name}: meta implicitValueSets has a grammar template, but the file has no grammar`); + } + const compatibility = Object.freeze({ ...COMPATIBILITY_DEFAULTS, ...get('compatibility') }); + return { values, requires, ignored, get, compatibility }; +} + +/** an order member with its default, as a list of words */ +function orderOf(order, member) { + return (order && order[member]) || ORDER_WORDS[member].default; +} + +module.exports = { + readMeta, orderOf, KEYS, WRITER_KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, FILTER_OPERATORS, FILTER_ROW_OPERATORS, STATUS_MEANINGS, ORDER_WORDS, + COMPATIBILITY, COMPATIBILITY_DEFAULTS, REMOVED_KEYS, FORMAT, REVISION, +}; diff --git a/tx/sqlite-v2/orders.js b/tx/sqlite-v2/orders.js index ed3e8b53..b6ea45d6 100644 --- a/tx/sqlite-v2/orders.js +++ b/tx/sqlite-v2/orders.js @@ -16,11 +16,6 @@ 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; } @@ -85,7 +80,7 @@ function fromBlob(b) { * 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) { +function orderOf(store, 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`); } @@ -100,9 +95,8 @@ function orderOf(store, kind, meta, readBytes) { }; 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', + // compatibility.isAListsFocusFirst (set by the factory): an is-a / << filter lists its concept first + selfFirst: false, hasWalk: meta.has('walk'), stored: true, readMs: 0, @@ -118,12 +112,19 @@ function orderOf(store, kind, meta, readBytes) { 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) { +function storedOrder(store) { // 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)); + return orderOf(store, meta, (name) => readArray(store, name)); +} + +/** meta order.expansion ["code"]: rank and ids by code as binary text, computed at load */ +function codeOrder(store) { + const rows = store.db.prepare('SELECT id, code FROM main.concept WHERE cs_id = ?').raw().all(store.csId); + const { rank, ids } = rankBy(store.conceptCount, rows, byText); + return { selfFirst: false, hasWalk: false, stored: false, readMs: 0, rank, ids, walk: null, loadedBytes() { return rank.byteLength + ids.byteLength; } }; } /** @@ -231,5 +232,5 @@ function hierarchyArrays(n, xs, others, isChild) { return { start, entries }; } -module.exports = { orderKind, rankBy, byText, byNumber, walkFrom, fromBlob, orderOf, storedOrder, hierarchyOrder, computeOrder, snomedWalk, +module.exports = { codeOrder, 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 index 730d8e21..39b35c62 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1,7 +1,7 @@ '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). +// Generic CodeSystemProvider over one sqlite-v2 file: every answer from the file's FHIR reading +// (tx/sqlite-v2/README.md); snomed.js adds the SNOMED CT grammar (expressions, ECL, editions). // // 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 @@ -14,23 +14,46 @@ const { TxParameters } = require('../params'); 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/i18n/languages'); const { openStore, KIND } = require('./store'); const { Engine } = require('./engine/engine'); -const { Compiler, FilterError } = require('./engine/compile'); -const { dialectFor, LOINC, RXNORM } = require('./dialects'); +const { Compiler, FilterError, notUnderstood, isEnumerableLayer, pidsOf } = require('./engine/compile'); +const { cmpCodeNumber } = require('./text-index'); +const { DesignationUse } = require('../library/designations'); +const { VersionUtilities } = require('../../library/fhir/version-utilities'); const { SupplementLayers } = require('./layers'); -const { HIER_CHILD } = require('./orders'); const { RoaringBitmap32 } = require('roaring-js'); -const { sctTextSearchG, sctTextLanguages, rxTextSearchG, loincTextSearchG, genericTextSearchG, rxSearchable } = require('./text-index'); +const { searchG, textLanguages, searchCandidates } = 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 primary = (l) => String(l || '').toLowerCase().split('-')[0]; +/** a stored use (item_use) as a Coding: system and display only when the file has them */ +const useCoding = (u) => { + const c = {}; + if (u.system != null) c.system = u.system; + c.code = u.code; + if (u.display != null) c.display = u.display; + return c; +}; const PAGE_ROWS = 2000; // a processSelection page's rows read per statement, with a pause between +/** two sort keys (_linkKey, _literalKey) compared element by element */ +const cmpKeys = (a, b) => { + for (let i = 0; i < Math.max(a.length, b.length); i++) { + const x = a[i], y = b[i]; + if (x === y) continue; + if (typeof x === 'number' && typeof y === 'number') return x - y; + if (x === undefined) return -1; + if (y === undefined) return 1; + const r = typeof x === 'object' ? x.cmp(y) : cmpText(String(x), String(y)); + if (r) return r; + } + return 0; +}; + /** a concept handle: id (concept_id), code; row/designations filled lazily or by a page batch */ class V2Concept { constructor(id, code, row = null) { @@ -39,7 +62,7 @@ class V2Concept { 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) + this.status = undefined; // the status literal (role status), when read with the row (undefined = not read) } } @@ -55,8 +78,12 @@ class V2FilterSet { this.bufStart = 0; this.current = null; this.expressionsFalse = !!opts.expressionsFalse; + // codes in their own right read through an identifier scheme (README.md "Alternate codes"), + // listed after the concepts: [{id, code, scheme}] + this.extra = opts.extra || []; } - get size() { return this.ids ? this.ids.length : (this.bm ? this.bm.size : 0); } + get baseSize() { return this.ids ? this.ids.length : (this.bm ? this.bm.size : 0); } + get size() { return this.baseSize + this.extra.length; } } class V2Prep { @@ -81,7 +108,8 @@ class SqliteV2Provider extends BaseCSServices { this.f = factory; this.store = factory.store; this.engine = factory.engine; - this.dialect = factory.dialect; + // the file grammar's filter rules (snomed.js), or none + this.grammarRules = factory.grammarRules || {}; 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 || []); @@ -96,24 +124,139 @@ class SqliteV2Provider extends BaseCSServices { version() { return this.store.version; } name() { return this.f.name(); } description() { return this.f.description(); } - lookupName() { return this.f.lookupName(); } + lookupName(langs) { return this.f.lookupName(langs); } defLang() { return this.f.defLang(); } totalCount() { return this.f.totalCount(); } /** - * expand.js asks this for count=0 of a whole code system: the codes iteratorAll walks (for RxNorm, - * the live ones - not the archived), but the inactive ones when excludeInactive, as main's - * providers count them (A9) + * expand.js asks this for count=0 of a whole code system: the listed codes (not the unlisted + * ones: README.md "Concept status"), the inactive ones left out when excludeInactive */ async countAllCodes(excludeInactive) { if (!excludeInactive) return this.totalCount(); - const walked = this.dialect.name === 'rxnorm' ? this._rxLive() : this.store.all(); + const walked = this.store.listed(this._stats()) || this.store.all(); return walked.andCardinality(this.store.active()); } - hasParents() { return !!this.store.hierarchy || this.dialect.name === 'rxnorm'; } + /** + * whether an expansion may nest a row under its parent: the file has a hierarchy and does not say + * compatibility.expansionNeverNests (README.md "compatibility"); expand.js then lists the rows flat + */ + hasParents() { return !!this.store.hierarchy && !this.store.compat.expansionNeverNests; } isNotClosed() { return !!this.store.notClosed; } + /** code_system.hierarchy_meaning (CodeSystem.hierarchyMeaning); null: not said, which is is-a ($subsumes refuses any other) */ + hierarchyMeaning() { return this.store.cs.hierarchy_meaning || null; } contentMode() { return this.store.cs.content || 'complete'; } versionAlgorithm() { return this.f.versionAlgorithm(); } + /** + * Whether a requested version (criteria) matches the file's (meta version.match): exact, or with + * prefix any non-empty start of it + */ + versionMatches(criteria, version = this.version()) { + if (criteria === version) return true; + return this.store.versionRule.match === 'prefix' && !!criteria && String(version).startsWith(criteria); + } + /** + * A requested version is less detailed than the file's only where meta version.partial says so: + * the file's version starts with it followed by the separator + */ + versionIsMoreDetailed(check, actual) { + const sep = this.store.versionRule.partial; + return !!sep && !!check && !!actual && !String(check).includes(sep) && String(actual).startsWith(check + sep); + } isCaseSensitive() { return this.store.caseSensitive; } + /** the most codes of this system an expansion lists or walks (meta expansionLimits.maxCodes; 0: no limit) */ + expandLimitation() { return this.store.expansionLimits.maxCodes || 0; } + /** the properties every expansion row reports (property.expansion 'always'), by their reported names */ + mandatoryExpansionProperties() { return [...this.store.catalog.values()].filter((d) => d.expansion === 'always').map((d) => d.name); } + + /** + * Whether a request's property list reports a catalog row (README.md "Which rows are reported"): + * never an internal, record or language row; $lookup: with no list the rows with lookup default, + * else the rows named (fhir_code, code or an also_asked_as name, ASCII case-insensitive), and + * with * every row with lookup default or named; expansions (forExpansion): the rows named or * + * with expansion asked or always, and every always row + */ + _reportsDef(d, props, forExpansion = false) { + if (d.internal || d.shape === 'record' || d.role === 'language') return false; + if (forExpansion) { + if (d.expansion === 'never') return false; + if (d.expansion === 'always') return true; + if (!props || !props.length) return false; + return props.some((p) => p === '*' || this._names(d).includes(String(p).toLowerCase())); + } + if (d.lookup === 'never') return false; + if (!props || props.length === 0) return d.lookup === 'default'; + return props.some((p) => { + if (p === '*') return true; + const low = String(p).toLowerCase(); + return this._names(d).includes(low) + || (d.shape === 'mapping' && low.endsWith('.details') && this._names(d).includes(low.slice(0, -8))); + }); + } + + /** the names a row is asked for by, lower case */ + _names(d) { + if (!d._names) d._names = [...new Set([d.name, ...d.alsoAskedAs].map((n) => n.toLowerCase()))]; + return d._names; + } + + /** + * a property's value as reported: a boolean where the catalog says (true_value), else the value in + * the form and with the parts property.presentation names; without one, a link's target code and a + * literal's value in the form its fhir_type gives (_literalValue) + */ + _addReported(params, d, value, display) { + const pr = d.presentation; + if (d.trueValue != null) { + params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueBoolean: String(value) === d.trueValue }] }); + return; + } + const node = d.kind === 'concept' || d.shape === 'link' || d.shape === 'both'; + const form = pr && pr.value ? pr.value : null; + const v = form === 'display' ? { valueString: display || String(value) } : form === 'string' ? { valueString: String(value) } + : form === 'coding' ? { valueCoding: { system: this.system(), code: String(value), ...(display ? { display } : {}) } } + : form === 'code' || node ? { valueCode: String(value) } : this._literalValue(d, value); + const parts = [{ name: 'code', valueCode: d.name }, { name: 'value', ...v }]; + for (const p of (pr && pr.parts) || []) { + if (p === 'description' && display) parts.push({ name: 'description', valueString: display }); + else if (p === 'code-display') parts.push({ name: 'code-display', valueString: this._propertyDisplay(d) }); + else if (p === 'partCode') parts.push({ name: 'partCode', valueCode: String(value) }); + } + params.push({ name: 'property', part: parts }); + } + + /** + * A literal value in the form of its property's fhir_type: code, string, integer, decimal, + * boolean, dateTime (an 8-digit date written YYYY-MM-DD); date as dateTime (a concept property + * has no date value: OMOP's valid-start-date, as cs-omop.js reports it) + */ + _literalValue(d, value) { + switch (d.type) { + case 'code': return { valueCode: String(value) }; + case 'integer': return { valueInteger: Math.round(Number(value)) }; + case 'decimal': return { valueDecimal: Number(value) }; + case 'boolean': return { valueBoolean: value === 1 || value === true || value === '1' || value === 'true' }; + case 'date': + case 'dateTime': { + const t = String(value); + return { valueDateTime: /^\d{8}$/.test(t) ? t.substring(0, 4) + '-' + t.substring(4, 6) + '-' + t.substring(6, 8) : t }; + } + default: return { valueString: String(value) }; + } + } + + /** + * What a property is called (the code-display part): property.display, else the display of the + * concept of the file whose code is the property's code (a SNOMED CT attribute), else its code + */ + _propertyDisplay(d) { + if (d.display) return d.display; + if (d._conceptDisplay === undefined) { + const id = d.conceptId != null ? d.conceptId : this.store.idOf(d.code); + const row = id != null ? this.store.conceptRows([id]).get(id) : null; + d._conceptDisplay = row && row.display ? row.display : null; + } + return d._conceptDisplay || d.code; + } sourcePackage() { return null; } /** @@ -143,7 +286,7 @@ class SqliteV2Provider extends BaseCSServices { /** _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; + if (!codes.length) 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()); @@ -155,9 +298,8 @@ class SqliteV2Provider extends BaseCSServices { return out; } - /** the code's own display in the file (cs-api _rootDisplay): SNOMED CT's preferred term, LOINC's display */ + /** the code's own display in the file (cs-api _rootDisplay: concept.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); @@ -197,8 +339,8 @@ class SqliteV2Provider extends BaseCSServices { 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; + // the status literal (catalog role 'status') with the rows: getStatus() is asked for every code of an expansion + const sp = this.store.statusProp; if (sp) { const ns = concepts.filter((c) => c.status === undefined && c.row).map((c) => c.id); if (ns.length) { @@ -209,10 +351,10 @@ class SqliteV2Provider extends BaseCSServices { 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; } + // the items of a use whose items are a property's values (item_use.as_property) are not designations + const skip = this.store.propertyUseIds; + const d = this.store.designationRows(nd, st, skip.length ? { skipUses: skip } : {}); + for (const c of concepts) if (!c.desigs) c.desigs = d.get(c.id) || []; } } } @@ -254,16 +396,6 @@ class SqliteV2Provider extends BaseCSServices { 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) { @@ -303,13 +435,30 @@ class SqliteV2Provider extends BaseCSServices { this.byCode.set(n, c); } } - if (!c) return { context: null, message: undefined }; + // compatibility.unknownCodeMessage: the reason for a code the system does not have + if (!c) return { context: null, message: this._message(this.store.compat.unknownCodeMessage, code) }; if (!c.row) this._loadRows([c], false); return { context: c, message: null }; } normaliseCode(code) { return String(code); } + /** + * expansionLimits.wholeSystem refuse (README.md "expansionLimits"): 500, exception, the text of + * compatibility.wholeSystemRefusalMessage ({system} filled in) or the plain one, repeated as the + * issue's diagnostics (as the server reports a provider's thrown error) + */ + _wholeSystemRefusal() { + const msg = (this.store.compat.wholeSystemRefusalMessage || 'The code system {system} cannot be expanded as a whole').split('{system}').join(this.system()); + return new Issue('error', 'exception', null, null, msg, 'invalid-data', 500).withDiagnostics(msg); + } + + /** the text of a compatibility message with {code} filled in, or undefined */ + _message(template, code) { + return template ? template.split('{code}').join(String(code)) : undefined; + } + + /** * 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 @@ -320,10 +469,77 @@ class SqliteV2Provider extends BaseCSServices { 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 this._aliasConcept(c.id, n, this.store.propsById.get(hit.scheme_id), hit); + } + + /** + * A code in its own right read through an identifier of a scheme (resolves 2): the concept's row + * and designations under the code as written; alias.scheme says which scheme (its alias_literals + * are the values it reports), alias.conceptCode the concept's own code + */ + _aliasConcept(id, code, scheme, row = null) { + const c = this._concept(id, row); + if (!c.row) this._loadRows([c], false); + const own = new V2Concept(id, code, { ...c.row, code }); + own.alias = { scheme, conceptCode: c.code }; return own; } + // ---- an alias form reported beside the code (README.md "Alternate codes": alias_parameter, alias_extension) ---- + + /** + * The concept's alias form: its identifier (resolves 1) of the scheme with alias_parameter, the + * least value; null without such a scheme or identifier. $validate-code reports it as the output + * parameter alias_parameter names (classificationCode: store.js checks the name) + */ + async classificationCode(context) { + const d = this.store.aliasParameterScheme; + if (!d) return null; + const c = await this._ensure(context); + if (!(c instanceof V2Concept) || c.alias) return null; + return this.store.aliasValuesOf(d, c.id)[0] || null; + } + + /** the alias form is reported for a code written canonically (the concept's own code) only */ + async reportedClassificationCode(context, code) { + const c = await this._ensure(context); + if (!(c instanceof V2Concept) || c.alias || code !== c.code) return null; + return this.classificationCode(c); + } + + /** an expansion lists a code a value set enumerated as the file answers it (an alias, resolves 1, as its concept's code) */ + async expansionCode(context, requested) { + if (!this.store.hasCodeIdentifiers) return requested; + return (await this.code(context)) || requested; + } + + /** + * The Coding extension of the scheme's alias_extension restates the code's alias form, and must be + * right: only defined where a scheme has alias_parameter (_SYSTEM), beside the canonical code + * (_NOT_ID), of a code that has an alias form (_NONE), and equal to it (_WRONG) + */ + async checkCodingExtensions(coding, context) { + const d = this.store.aliasExtensionScheme; + if (!d) return []; + const out = []; + const exts = coding.extension || []; + for (let index = 0; index < exts.length; index++) { + const ext = exts[index]; + if (!ext || ext.url !== d.aliasExtension) continue; + const value = ext.valueCode ?? ''; + if (!this.store.aliasParameterScheme) { + out.push({ index, msgId: 'ICD11_CLASSIFICATION_CODE_SYSTEM', params: [this.system()] }); + continue; + } + const id = await this.code(context); + const expected = await this.classificationCode(context); + if (coding.code !== id) out.push({ index, msgId: 'ICD11_CLASSIFICATION_CODE_NOT_ID', params: [coding.code, id] }); + else if (!expected) out.push({ index, msgId: 'ICD11_CLASSIFICATION_CODE_NONE', params: [value, coding.code] }); + else if (value !== expected) out.push({ index, msgId: 'ICD11_CLASSIFICATION_CODE_WRONG', params: [value, coding.code, expected] }); + } + return out; + } + /** 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; } @@ -336,7 +552,7 @@ class SqliteV2Provider extends BaseCSServices { 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.desigs) c.desigs = got.desigs; if (!c.desigs && got.displayOnly) c.displayOnly = true; if (c.status === undefined) c.status = got.status; } @@ -372,7 +588,8 @@ class SqliteV2Provider extends BaseCSServices { 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); + // (a code that is no concept code may be an identifier accepted as a code: locate() reads it) + if (r || !this.store.hasCodeIdentifiers) 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); @@ -393,68 +610,121 @@ class SqliteV2Provider extends BaseCSServices { async display(context) { const c = await this._ensure(context); if (!c) return null; + return this._displayOf(c).term; + } + + /** + * A concept's display and the language its text is in: a supplement's display (language not + * known: null); else the display in a requested language (README.md "Display in a requested + * language"), where a use of the file has language_display_rank and a requested language is not + * the stored display's; else concept.display, in the display designation's language + * (_displayLanguageOf) + * @returns {{term: string, language: string|null}} + */ + _displayOf(c) { const s = this._displayFromSupplements(c.code); - if (s) return s; + if (s) return { term: s, language: null }; + const uses = this.store.languageDisplayUses; const displayLangs = this.displayLanguages(); - if (this.dialect.name === 'loinc' && displayLangs && !displayLangs.isEnglishOrNothing()) { + const langs = ((displayLangs && displayLangs.languages) || []).filter((l) => l && l.code !== '*'); + if (uses.length && langs.length) { 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 = displayLangs.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; + const own = primary(this._displayLanguageOf(c)); + if (langs.some((l) => primary(l.language || l.code) !== own)) { + const rank = new Map(uses.map((u, i) => [u.id, i])); + const cands = [{ language: this._displayLanguageOf(c), term: c.row.display }] + .concat(this._ordered(c.desigs).filter((d) => d.use && rank.has(d.use.id)).sort((a, b) => rank.get(a.use.id) - rank.get(b.use.id))); + // exact tag matches first, then by primary subtag + const tag = (l) => String(l.code || l.language || '').toLowerCase(); + for (const exact of [true, false]) { + for (const l of langs) { + for (const d of cands) { + if (d.language && (exact ? String(d.language).toLowerCase() === tag(l) : primary(d.language) === primary(tag(l)))) return { term: d.term, language: d.language }; + } + } + } } } - return (c.row && c.row.display) || ''; + return { term: (c.row && c.row.display) || '', language: this._displayLanguageOf(c) }; } async definition(context) { + // compatibility.lookupOmitsTextDefinitions: no definition + if (this.store.compat.lookupOmitsTextDefinitions) return null; const c = await this._ensure(context); return c && c.row ? c.row.definition || null : null; } - async isAbstract() { return false; } + /** notSelectable (README.md "Concept status"): the concept's `abstract` */ + async isAbstract(context) { + const set = this.store.statusSet('notSelectable', this._stats()); + if (!set) return false; + const c = await this._ensure(context); + return !!c && set.has(c.id); + } async isInactive(context) { const c = await this._ensure(context); return c ? !c.row.active : false; } + /** deprecated (README.md "Concept status"): the reading, of an active concept */ async isDeprecated(context) { + const set = this.store.statusSet('deprecated', this._stats()); + if (!set) return false; 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(); + return !!c && set.has(c.id); } - /** RxNorm: inactive because archived (RXNATOMARCHIVE only), not obsolete (SUPPRESS = O) */ - _rxArchived(c) { return !c.row.active && !this._rxLive().has(c.id); } - + /** + * The status text (README.md "Concept status"): the concept's status literal (role status) as + * stored when it has one; else `inactive` for an inactive concept; else none. Where an operation + * reports it is the operation's rule (expand.js leaves out `active` in any case; validate.js reports + * it for an inactive concept unless it is `inactive`) + */ 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; + const p = this.store.statusProp; + if (p) { + let v = c.status; + if (v === undefined) { + v = this.store.literalValues([c.id], p.id, this._stats()).get(c.id); + c.status = v === undefined ? null : v; + v = c.status; + } + if (v != null) return String(v); } - if (this.dialect.name === 'rxnorm') return c.row.active ? null : (this._rxArchived(c) ? 'archived' : 'obsolete'); - return c.row.active ? 'active' : 'inactive'; + return c.row.active ? null : 'inactive'; } - async parent() { return null; } + /** + * The concept's first parent (an expansion nests its row under it): the first target of its active + * hierarchy links in the order of order.links; null without a hierarchy or for what is not a + * concept of the file + */ + async parent(context) { + const S = this.store; + if (!S.hierarchy) return null; + const c = await this._ensure(context); + if (!(c instanceof V2Concept) || c.id == null) return null; + const links = S.linksFrom([c.id], new Set([S.hierarchy.id]), true, this._stats()); + if (!links.length) return null; + const targets = S.conceptRows([...new Set(links.map((l) => l.t))], this._stats()); + let best = null; + for (const l of links) { + const t = targets.get(l.t); + if (!t) continue; + const key = this._linkKey(S.hierarchy, { ...l, other: l.t }, t.code); + if (!best || cmpKeys(key, best.key) < 0) best = { key, code: t.code }; + } + return best ? best.code : null; + } + /** a designation whose text is accepted as a display: its use's role (item_use.role display, fsn or synonym) */ isDisplay(d) { - if (this.dialect.name === 'loinc') return !!(d.use && ['SHORTNAME', 'LONG_COMMON_NAME', 'LinguisticVariantDisplayName'].includes(d.use.code)); - return false; + const role = this.store.useRoleOf(d && d.use); + return role === 'display' || role === 'fsn' || role === 'synonym'; } async designations(context, displays, significantOnly) { @@ -464,6 +734,16 @@ class SqliteV2Provider extends BaseCSServices { return this._trace.spanAsync('designations', 'rows', this.system(), () => this._designations(context, displays, significantOnly)); } + /** items in the designation order: item rank (NULL last), then item id */ + _ordered(desigs) { + return [...desigs].sort((x, y) => ((x.rank ?? Infinity) - (y.rank ?? Infinity)) || (x.id - y.id)); + } + + /** + * The designation list (README.md "Designations"): the items in rank, then id order, each with its + * use (compatibility.designationUse) or preferredForLanguage for a preferred item, inactive ones + * marked; the display designation first (compatibility.displayDesignation once / always) + */ async _designations(context, displays) { const c = await this._ensure(context); if (!c) return; @@ -473,41 +753,50 @@ class SqliteV2Provider extends BaseCSServices { 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); + const mode = this.store.compat.displayDesignation; + const display = (c.row.display || '').trim(); + const seen = new Set(); + if (mode !== 'none') { + displays.addDesignation(true, 'active', this._displayLanguageOf(c), null, display); + seen.add(display); + } + for (const d of this._ordered(c.desigs)) { + const term = d.term.trim(); + if (mode === 'once') { + if (seen.has(term)) continue; + seen.add(term); } + displays.addDesignation(false, d.active ? 'active' : 'inactive', d.language, this._useOf(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); + /** + * A designation's use as it is reported (map: the stored use -> the reported one): the item's use + * (compatibility.designationUse source); for a preferred item without one (or whose use is not + * reported), preferredForLanguage; else none + */ + _useOf(d, map = useCoding) { + if (d.use && this.store.compat.designationUse === 'source') return map(d.use); + return d.preferred ? { ...DesignationUse.DISPLAY } : null; } + /** + * The language of the display designation (README.md "The display designation"): + * code_system.default_language, else en. No item is consulted (an item with the display's text may + * be a translation: LOINC LP7786-9 "CHEM") + */ + _displayLanguageOf(c) { + void c; + return this.store.defaultLanguage || this.defLang(); + } + /** the display as the one designation, plus supplement designations */ + _displayOnly(c, displays) { + const d = ((c.row && c.row.display) || '').trim(); + if (d) displays.addDesignation(true, 'active', this._displayLanguageOf(c), null, d); + this._listSupplementDesignations(c.code, displays); + } // ---- iteration -------------------------------------------------------------------------- @@ -526,27 +815,41 @@ class SqliteV2Provider extends BaseCSServices { return { ids, pos: 0, total: context == null ? this.totalCount() : ids.length }; } + /** + * The usual path's whole-system walk (expand.js includeCodeAndDescendants from each root): a + * hierarchy given as explicit closure pairs (LOINC) has no tree to walk, so every concept; a file + * without a hierarchy, its listed concepts in the expansion order; otherwise the concepts without + * a parent, the active ones with compatibility.wholeSystemIncludeActiveOnly + */ _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(); + const S = this.store; + if (S.expansionLimits.wholeSystem === 'refuse') throw this._wholeSystemRefusal(); + if (S.hierarchy && S.closure != null) { + const ord = this.engine._order; + if (ord && ord.hasWalk) return ord.walk; + return ord ? this.engine._ordered(S.all()) : S.all().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(); + if (!S.hierarchy) { + const b = S.listed(this._stats()) || S.all(); + return this.engine._order ? this.engine._ordered(b) : b.toArray(); + } + const hasParent = S.getSet(KIND.hasProp, S.hierarchy.id, 0); + const base = S.compat.wholeSystemIncludeActiveOnly ? S.active() : S.all(); + let roots = RoaringBitmap32.andNot(base, hasParent); + const listed = S.listed(this._stats()); + if (listed) roots = RoaringBitmap32.and(roots, listed); + return roots.toArray(); } async iteratorAll() { - const ids = (this.dialect.name === 'rxnorm' ? this._rxLive() : this.store.all()).toArray(); + const ids = (this.store.listed(this._stats()) || 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)); + const batch = Array.from(iter.ids.slice(iter.pos, iter.pos + CHUNK), (id) => this._concept(id)); this._loadChunk(batch); iter.loaded = iter.pos + batch.length; } @@ -563,7 +866,8 @@ class SqliteV2Provider extends BaseCSServices { async _subsumesTest(codeA, codeB) { const a = await this._ensure(codeA); const b = await this._ensure(codeB); - if (this.dialect.name === 'rxnorm') return 'not-subsumed'; + // a file with no hierarchy property: nothing subsumes anything + if (!this.store.hierarchy) 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'; @@ -594,7 +898,7 @@ class SqliteV2Provider extends BaseCSServices { 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(); + if (!this.store.hierarchy) 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; @@ -619,168 +923,242 @@ class SqliteV2Provider extends BaseCSServices { // ---- $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)); + if (!this._trace) await this._extendLookup(context, props, params); + else await this._trace.spanAsync('lookup properties', 'rows', this.system(), () => this._extendLookup(context, props, params)); } + /** + * $lookup's properties (README.md "Properties"): the upstream-copy steps of compatibility first + * (the copyright, typed designations), then every reported value in the one order of the + * comparator (_propertyValues) + */ 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); + // compatibility.lookupListsCopyright: the code system's copyright notice as a property + if (this.store.copyright != null) this._addStringProperty(params, 'property', 'copyright', this.store.copyright); + // compatibility.typedDesignationsInLookup: each item with a use again, as a designation with its use's code + if (this.store.compat.typedDesignationsInLookup) this._typedDesignations(c, props, params); + for (const v of this._propertyValues(c, props, false)) v.emit(params); + this._appendNotSelectable(c, props, params); } - _targetDisplays(ids) { - return this.store.conceptRows(ids, this._stats()); + /** + * notSelectable where the file reads it (conceptStatus) without a reading-shape row to place it: + * after the properties, when the concept is notSelectable or * or notSelectable is asked for + */ + _appendNotSelectable(c, props, params) { + const S = this.store; + const set = S.statusSet('notSelectable', this._stats()); + if (!set || [...S.catalog.values()].some((d) => d.shape === 'reading' && d.code === 'notSelectable')) return; + const asked = (props || []).some((p) => p === '*' || String(p).toLowerCase() === 'notselectable'); + if (set.has(c.id) || asked) params.push({ name: 'property', part: [{ name: 'code', valueCode: 'notSelectable' }, { name: 'value', valueBoolean: set.has(c.id) }] }); } - _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 + /** + * Every value a $lookup (or an expansion row: forExpansion) reports for a concept, in the order + * of README.md "$lookup order": property.lookup_rank (compatibility.lookupRankWhenConceptHas may + * change it), then links, literals, identifiers, mappings, item-use values, readings, then meta + * order.links / order.literals (identifiers by name then value, mappings by system then code, + * item-use values by item rank then id), then the reported name and the value as binary text. + * (The spec, 5.4.2, puts the last four in one kind; ordering them by shape keeps each shape's + * own key meaningful.) + * @returns {Array<{d, rank, kind, key: Array, name, text, emit: function(params)}>} + */ + _propertyValues(c, props, forExpansion) { 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 = [...S.catalog.values()].filter((d) => this._reportsDef(d, props, forExpansion)); + if (!rows.length) return []; + const out = []; + const rankOf = this._ranks(c, rows); + // a code read through a scheme's identifier reports the scheme's alias_literals instead of the + // concept's stored values of those properties (README.md "Alternate codes") + const aliasLits = (c.alias && c.alias.scheme && c.alias.scheme.aliasLiterals) || null; + const overridden = (d) => !!aliasLits && Object.prototype.hasOwnProperty.call(aliasLits, d.name); + const add = (d, kind, key, text, emit) => { if (!overridden(d)) out.push({ d, rank: rankOf(d), kind, key, name: d.name, text: String(text), emit }); }; + if (aliasLits) { + for (const d of rows.filter(overridden)) { + const v = aliasLits[d.name].split('{code}').join(c.alias.conceptCode); + out.push({ d, rank: rankOf(d), kind: 1, key: this._literalKey(d, { v, g: 0 }), name: d.name, text: v, emit: (params) => this._addReported(params, d, v, null) }); } } - 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; + // links (link, both, union rows) and inverse links, with their targets' rows + const linkRows = rows.filter((d) => ['link', 'both', 'union'].includes(d.shape) && !d.reverses); + const byPid = new Map(); + for (const d of linkRows) for (const pid of pidsOf(d)) { if (!byPid.has(pid)) byPid.set(pid, []); byPid.get(pid).push(d); } + const links = byPid.size ? S.linksFrom([c.id], new Set(byPid.keys()), true, st).map((l) => ({ ...l, other: l.t })) : []; + const inverseRows = rows.filter((d) => d.reverses); + const inverse = []; + for (const d of inverseRows) for (const l of S.linksToOf(c.id, d.reverses.map((r) => r.id), st)) inverse.push({ d, l: { ...l, other: l.s } }); + const targets = S.conceptRows([...new Set([...links.map((l) => l.other), ...inverse.map((x) => x.l.other)])], st); + const linkEntries = []; + const pushLink = (d, l) => { + const t = targets.get(l.other); + if (!t) return; + linkEntries.push({ d, t, rank: rankOf(d), key: this._linkKey(d, l, t.code) }); }; - 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); + for (const l of links) for (const d of byPid.get(l.p) || []) pushLink(d, l); + for (const { d, l } of inverse) pushLink(d, l); + linkEntries.sort((a, b) => (a.rank - b.rank) || cmpKeys(a.key, b.key) || cmpText(a.d.name, b.d.name) || cmpText(a.t.code, b.t.code)); + const seen = new Set(); + for (const { d, t, key } of linkEntries) { + // a property lists a target once, keeping the earliest link in `order.links` + const k = d.id + '|' + t.code; + if (seen.has(k)) continue; + seen.add(k); + add(d, 0, key, t.code, (params) => this._addReported(params, d, t.code, t.display)); + } + // literals (literal and both rows) + const litRows = new Map(rows.filter((d) => d.shape === 'literal' || d.shape === 'both').map((d) => [d.id, d])); + if (litRows.size) { + for (const r of S.literalsOf([c.id], true, st)) { + const d = litRows.get(r.p); + if (!d) continue; + const labels = S.valueLabels(d); + const label = labels ? labels[r.v] : undefined; + add(d, 1, this._literalKey(d, r), r.v, (params) => this._addReported(params, d, r.v, label)); } } - 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)); + // identifiers of the concept (identifier rows) + const idRows = rows.filter((d) => d.shape === 'identifier'); + if (idRows.length) { + for (const r of S.identifiersOf(c.id, idRows)) { + const d = S.propsById.get(r.p); + add(d, 2, [d.name, r.v], r.v, (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, + { name: 'value', ...(d.valueSystem ? { valueCoding: { system: d.valueSystem, code: r.v } } : { valueCode: 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); + // mappings (mapping rows: README.md "The three shapes without rows of their own") + const mapRows = rows.filter((d) => d.shape === 'mapping'); + if (mapRows.length) { + for (const m of S.mappingsOf(c.id, mapRows.map((d) => d.id))) { + const d = S.propsById.get(m.property_id); + // presentation parts: version (the Coding carries the row's version), equivalence (the subproperty) + const parts = (d.presentation && d.presentation.parts) || []; + const coding = { system: m.system }; + if (m.version && parts.includes('version')) coding.version = m.version; + coding.code = m.code; + if (m.display) coding.display = m.display; + const sub = parts.includes('equivalence') ? [{ name: 'subproperty', part: [{ name: 'code', valueCode: 'equivalence' }, { name: 'value', valueCode: m.equivalence }] }] : []; + add(d, 3, [m.system, m.code], m.code, (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueCoding: coding }, ...sub] })); + } + } + // item-use values: the active items of the use that names the row + for (const d of rows.filter((x) => x.shape === 'item-use')) { + const items = S.designationRows([c.id], st, { onlyUse: d.use.id }).get(c.id) || []; + for (const it of items) { + if (!it.active) continue; + add(d, 4, [it.rank ?? Infinity, it.id], it.term, (params) => this._addStringProperty(params, 'property', d.name, it.term, it.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 }] }] }); + // readings (README.md "Concept status"): true when the concept has the meaning, no value otherwise + for (const d of rows.filter((x) => x.shape === 'reading')) { + const has = d.code === 'inactive' ? !c.row.active : !!(S.statusSet(d.code, st) || { has: () => false }).has(c.id); + if (has) add(d, 5, [], 'true', (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueBoolean: true }] })); } + out.sort((a, b) => (a.rank - b.rank) || (a.kind - b.kind) || cmpKeys(a.key, b.key) || cmpText(a.name, b.name) || cmpText(a.text, b.text)); + return out; + } + + /** property row -> its lookup rank for this concept (unranked rows after every ranked one) */ + _ranks(c, rows) { + const over = new Map(); + for (const e of this.store.compat.lookupRankWhenConceptHas) { + const when = this.store.catalog.get(e.when); + if (when && this.store.literalsOf([c.id], true).some((r) => r.p === when.id)) over.set(e.property, e.rank); + } + void rows; + return (d) => (over.has(d.code) ? over.get(d.code) : d.lookupRank != null ? d.lookupRank : Infinity); } /** - * 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). + * a link's sort key by meta order.links, ending with property id, group, target code, target id + * (for an inverse link the other end, l.other, is the subject of the link it reverses) */ - _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 }); + _linkKey(d, l, code) { + const key = []; + for (const w of this.store.orderWords('links')) { + switch (w) { + case 'property-id': key.push(d.id); break; + case 'property': key.push(d.name); break; + case 'group': key.push(l.g || 0); break; + // an inverse link takes the seq of the link it reverses; inverse links of one seq keep the + // stored order of the links by target (ix_in: seq, then subject), as they are read + case 'stored': key.push(l.q ?? 0); if (d.reverses) key.push(l.other); break; + case 'code': key.push(code); break; + case 'code-number': key.push({ v: code, cmp(o) { return cmpCodeNumber(this.v, o.v); } }); break; + default: break; + } + } + key.push(d.id, l.g || 0, code, l.other); + return key; + } + + /** a literal's sort key by meta order.literals, ending with property id, group, value */ + _literalKey(d, r) { + const val = typeof r.v === 'number' ? r.v : String(r.v); + const key = []; + for (const w of this.store.orderWords('literals')) { + switch (w) { + case 'property-id': key.push(d.id); break; + case 'property': key.push(d.name); break; + case 'group': key.push(r.g || 0); break; + case 'stored': key.push(r.q ?? 0); break; + case 'value': key.push(val); break; + default: break; + } } - 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); + key.push(d.id, r.g || 0, val); + return key; } /** - * 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. + * compatibility.typedDesignationsInLookup: when $lookup lists designations, each item that has a + * use once more as a designation with parts code (the use's code), value, language (else en), in + * item id order + */ + _typedDesignations(c, props, params) { + if (!this._hasProp(props, 'designation', true)) return; + const items = this.store.designationRows([c.id], this._stats()).get(c.id) || []; + for (const d of items) { + if (!d.use) continue; + params.push({ name: 'designation', part: [{ name: 'code', valueCode: d.use.code }, { name: 'value', valueString: d.term }, + { name: 'language', valueCode: d.language || 'en' }] }); + } + } + + /** + * The properties this system reports ({code, uri, type}), for expansion.property: each row that + * has a uri and can be reported (none where compatibility.expansionDeclaresProperties is false) */ 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). + * Properties of a concept for an expansion (ValueSet contains.property): the values $lookup + * reports, for the rows the request names (in its order) or * (expansion_rank first), and every + * row with expansion 'always'; 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 always = [...this.store.catalog.values()].some((d) => d.expansion === 'always'); + if (!wanted && !always) return []; const c = await this._ensure(context); if (!c) return []; + let vals = this._propertyValues(c, wanted || [], true); + const star = (wanted || []).includes('*'); + const pos = (v) => { + if (star) return v.d.expansionRank != null ? v.d.expansionRank : Infinity; + const names = this._names(v.d); + const i = (wanted || []).findIndex((n) => names.includes(String(n).toLowerCase())); + return i < 0 ? Infinity : i; + }; + vals = vals.map((v, i) => ({ v, i, p: pos(v) })).sort((a, b) => (a.p - b.p) || (a.i - b.i)).map((x) => x.v); const params = []; - await this._extendLookup(c, wanted, params); + for (const v of vals) v.emit(params); const out = []; for (const p of params) { const code = p.part.find((x) => x.name === 'code'); @@ -792,45 +1170,52 @@ class SqliteV2Provider extends BaseCSServices { return out; } - async getTranslations(map, coding, target) { + /** + * $translate over an implicit map: a map of meta implicitMaps.maps (the mapping rows of its + * system, both ways, or from this system only with implicitMaps.forwardOnly; each target with the + * display of the concept translated with compatibility.translationDisplayIsSourceDisplay), or an + * association (implicitMaps.associations: the active record rows of the relation, subject -> + * target, forward only). With implicitMaps.used, the map a translation reports as used is + * `{base}{used}{key}|{version}`. + */ + async getTranslations(map, coding, target, reverse) { + const S = this.store; + const targetSystem = target ? target.split('|')[0] : null; + const assoc = map && map.jsonObj && map.jsonObj.association; + if (assoc) { + if (reverse || (targetSystem && targetSystem !== this.system())) return []; + const rel = S.relations.get(S.idOf(assoc.relation)); + const src = S.idOf(this.normaliseCode(coding.code)); + if (!rel || src == null) return []; + const ids = S.recordTargets(rel.id, src); + const rows = S.conceptRows(ids); + return ids.filter((id) => rows.get(id)).map((id) => ({ map: map.vurl, code: rows.get(id).code, system: this.system(), version: this.version(), + display: rows.get(id).display, relationship: assoc.relationship })); + } const lm = map && map.jsonObj && map.jsonObj.loincMap; if (!lm) return []; - const targetSystem = target ? target.split('|')[0] : null; - const S = this.store; const out = []; + const usedMap = S.implicitMapsSpec.used !== undefined ? `${S.implicitMapsSpec.base}${S.implicitMapsSpec.used}${lm.key}|${this.version()}` : map.vurl; if (coding.system === this.system() && (!targetSystem || targetSystem === lm.system)) { const id = S.idOf(coding.code); if (id == null) return []; + const sourceDisplay = S.compat.translationDisplayIsSourceDisplay ? ((S.conceptRows([id]).get(id) || {}).display || null) : null; 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) }; + const t = { map: usedMap, 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; + const display = S.compat.translationDisplayIsSourceDisplay ? sourceDisplay : r.display; + if (display) t.display = display; out.push(t); } - } else if (coding.system === lm.system && (!targetSystem || targetSystem === this.system())) { + } else if (!S.implicitMapsSpec.forwardOnly && 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) }); + const display = S.compat.translationDisplayIsSourceDisplay ? r.source_display : r.display; + out.push({ map: usedMap, system: this.system(), version: this.version(), code: r.code, 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 -------------------------------------------------------------------------------- /** @@ -851,46 +1236,48 @@ class SqliteV2Provider extends BaseCSServices { _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, + // lang: the language of a filter that reads designations (README.md "What a row reads": the + // text-search language), chosen when one asks for it, so that another filter or ECL does not + // list the file's languages + const term = { store: this.store, grammar: this.grammarRules, layers: this.layers, get lang() { return lang === undefined ? (lang = provider._regexLanguage()) : lang; } }; return new Compiler(term, { stats: stats || this._stats() }); } + /** the language a filter that reads designations searches: the text-search language (_searchLanguage) */ + _regexLanguage() { + return this._searchLanguage(null).language.toLowerCase().split('-')[0]; + } + /** - * 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. + * The language a text filter searches (README.md "Text search language"): with + * search.supplementsChooseLanguage (the default), CodeSystemProvider.searchLanguage over what the + * request asked for (the file's and the supplements' languages); without, the first language the + * filter context names that the file has names in (_fileSearchLanguage) + * @returns {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)); + _searchLanguage(prep) { + const sp = this.store.search || {}; + if (sp.supplementsChooseLanguage === false) { + const languages = prep ? prep.languages : this._requestedLangs; + const named = ((languages && languages.languages) || []).filter((l) => l && l.language); + const code = this._fileSearchLanguage(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); } - 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'; + return this.searchLanguage((prep && prep.languages) || this._requestLangs || this.opContext.langs || null); } /** - * 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. + * The first language named (each as tx/sct/languages.js languageBytesFor has it: Norwegian under + * either "no" or "nb"/"nn") that the file has names in; else the file's default language + * (code_system default_language), if it has names in it, or has none at all; else the file'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); + _fileSearchLanguage(named) { + const present = textLanguages(this.store); for (const l of named || []) { for (const b of languageBytesFor(l)) { const code = languageCode(b); @@ -923,13 +1310,12 @@ class SqliteV2Provider extends BaseCSServices { /** * 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). + * (displayLanguage, else Accept-Language). Kept for the request's later filters too: a filter + * that reads designations 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) + // what the request named, or null (the filter context's languages: _searchLanguage) this._requestedLangs = languages || null; return new V2Prep(iterate, languages); } @@ -943,56 +1329,190 @@ class SqliteV2Provider extends BaseCSServices { } if (node.t === 'all' && node.expressionsFalse) prep.expressionsFalse = true; prep.nodes.push(node); - prep.specs.push({ prop, op, value }); + prep.specs.push({ prop, op, value, node }); return null; } - /** errors as the upstream provider reports them; dialects may wrap them (SNOMED ECL) */ + // ---- codes in their own right read through an identifier scheme (README.md "Alternate codes") --- + + /** + * The alias schemes whose alias_literals name a property a filter reads: [{scheme, template, row}] + * (a filter row that understands prop and op) + */ + _aliasReads(prop, op) { + const S = this.store; + if (!S.aliasSchemes.length) return []; + const out = []; + for (const hit of S.filterRows(prop, op)) { + for (const x of hit.row.reads) { + const d = S.catalog.get(x === '{1}' ? hit.capture : x); + if (!d) continue; + for (const s of S.aliasSchemes) { + if (s.aliasLiterals && Object.prototype.hasOwnProperty.call(s.aliasLiterals, d.name)) out.push({ scheme: s, template: s.aliasLiterals[d.name], row: hit.row }); + } + } + } + return out; + } + + /** + * Whether a filter holds for a code read through the scheme's identifier, whose property values + * are the scheme's alias_literals ({code}: the concept's own code): true or false; null when the + * filter reads no property the scheme's alias_literals names (then the concept's own values decide) + */ + _aliasHolds(spec, scheme, conceptCode) { + const r = this._aliasReads(spec.prop, spec.op).find((x) => x.scheme === scheme); + if (!r) return null; + const v = r.template.split('{code}').join(conceptCode == null ? '' : conceptCode); + const row = r.row; + const value = String(spec.value == null ? '' : spec.value); + if (spec.op === 'exists') return value === 'true'; + let vals = spec.op === 'in' || spec.op === 'not-in' ? value.split(',').map((x) => x.trim()).filter(Boolean) : [value]; + if (row.prefix != null) vals = vals.map((x) => (x.startsWith(row.prefix) ? x.substring(row.prefix.length) : null)).filter((x) => x != null); + const eq = (x) => (row.exactCase ? x === v : x.toLowerCase() === v.toLowerCase()); + switch (spec.op) { + case '=': return vals.length === 1 && eq(vals[0]); + case 'in': return vals.some(eq); + case 'not-in': return !vals.some(eq); + case 'regex': try { return new RegExp('^(?:' + value + ')$').test(v); } catch (e) { return false; } + default: return false; + } + } + + /** + * The schemes whose codes in their own right a filter lists: a filter `=` (or `in`) on a property + * the scheme's alias_literals names, with the template's value (one without {code}) + */ + _aliasListingSchemes(specs) { + const out = []; + for (const sp of specs) { + if (sp.op !== '=' && sp.op !== 'in') continue; + for (const r of this._aliasReads(sp.prop, sp.op)) { + if (!r.template.includes('{code}') && this._aliasHolds(sp, r.scheme, null) && !out.includes(r.scheme)) out.push(r.scheme); + } + } + return out; + } + + /** + * The codes in their own right a set of filters lists (README.md "Alternate codes"): the + * identifiers with resolves 2 of each scheme a filter lists by its template value, for which every + * filter holds (on a property the alias_literals name: the template's value; else the concept's + * own), in the order of their concepts, then value. [{id, code, scheme}] + */ + async _aliasEntries(specs) { + const schemes = this._aliasListingSchemes(specs); + if (!schemes.length) return []; + const S = this.store; + const st = this._stats(); + const listed = S.listed(st); + const sets = new Map(); + const setOf = async (sp) => { + if (!sets.has(sp)) sets.set(sp, await this.engine.evaluateAsync(sp.node, this._trace, this._pause())); + return sets.get(sp); + }; + const out = []; + for (const scheme of schemes) { + let rows = S.codeIdentifiersOf(scheme, st); + if (listed) rows = rows.filter(([id]) => listed.has(id)); + // the concepts' own codes, where a template of a filter names {code} + let codes = null; + for (const sp of specs) { + const r = this._aliasReads(sp.prop, sp.op).find((x) => x.scheme === scheme); + if (r && r.template.includes('{code}') && !codes) { + const ids = [...new Set(rows.map(([id]) => id))]; + const cr = S.conceptRows(ids, st); + codes = new Map(ids.map((id) => [id, (cr.get(id) || {}).code])); + } + } + for (const sp of specs) { + const r = this._aliasReads(sp.prop, sp.op).find((x) => x.scheme === scheme); + if (!r) { + const bm = await setOf(sp); + rows = rows.filter(([id]) => bm.has(id)); + } else if (!r.template.includes('{code}')) { + if (!this._aliasHolds(sp, scheme, null)) rows = []; + } else rows = rows.filter(([id]) => this._aliasHolds(sp, scheme, codes.get(id))); + } + // in the order of their concepts (the expansion order), then value + const ids = [...new Set(rows.map(([id]) => id))]; + const order = this.engine._order ? this.engine._ordered(new RoaringBitmap32(ids)) : ids.sort((a, b) => a - b); + const pos = new Map(order.map((id, i) => [id, i])); + rows.sort((a, b) => (pos.get(a[0]) - pos.get(b[0])) || cmpText(a[1], b[1])); + for (const [id, code] of rows) out.push({ id, code, scheme }); + } + return out; + } + + /** whether a code read through a scheme's identifier is in a filter set: every filter holds for it */ + _aliasMember(set, c) { + const listed = this.store.listed(this._stats()); + if (listed && !listed.has(c.id)) return false; + for (const sp of set.specs || []) { + const h = this._aliasHolds(sp, c.alias.scheme, c.alias.conceptCode); + if (h === false) return false; + if (h === null && !this.engine.contains(sp.node, c.id, this._trace)) return false; + } + return true; + } + + /** whether a compose names codes in their own right of a scheme: in a filter that lists them, or a listed code that is no concept code */ + _composeHasAliasCodes(includes, excludes) { + const S = this.store; + if (!S.hasCodeIdentifiers) return false; + const listed = []; + for (const cset of [...includes, ...excludes]) { + if (cset.filter && this._aliasListingSchemes(cset.filter.map((f) => ({ prop: f.property, op: f.op, value: f.value }))).length) return true; + for (const cc of cset.concept || []) listed.push(this.normaliseCode(cc.code)); + } + if (!listed.length) return false; + const ids = S.resolveCodes(listed, this._stats()); + return listed.some((n) => ids.get(n) == null && !!S.identifierAsCode(n, this._stats())); + } + + /** errors as the upstream provider reports them; a grammar 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 + // a filter no filter row understands: 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); } + // a filter that cannot be evaluated for its value (a reference set of descriptions in concept in): a 400 + if (e.invalid) return new Issue('error', 'invalid', null, null, e.message, 'vs-invalid').handleAsOO(400); 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 + * A text filter (README.md "Text search"): refused, TEXT_SEARCH_NOT_SUPPORTED, for a file without + * meta search; otherwise one language (_searchLanguage), the file's names in it (Store.searchText, + * text-index.js), and the codes a supplement in use gives a matching name in that language that + * the file's own search does not find (_supplementSearchCodes), among the search's candidates. A * supplement that adds codes is noted on the filter context (prep.usedSupplements), for * used-supplement. */ - async searchFilter(prep, filter) { + async searchFilter(prep, filter, sort) { + if (!this.store.search) return super.searchFilter(prep, filter, sort); 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); + const node = { t: 'search', text }; + const searchLang = this._searchLanguage(prep); 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') { + if (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 base = codes.size ? ((await this._pausing(this.store.searchTextG(text, this._stats(), node.lang))) || new RoaringBitmap32()) : null; const ids = []; - const active = this.dialect.searchMode === 'designation' ? this.store.active(this._stats()) : null; + const cands = searchCandidates(this.store, this._stats()); 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; + if (id == null || base.has(id) || (cands && !cands.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) + // codes only a supplement's text matches: after the file's matches, in the supplement's order prep.searchExtras = ids; n = { t: 'or', items: [{ t: 'ids', ids: base.toArray() }, { t: 'ids', ids }] }; } @@ -1003,17 +1523,6 @@ class SqliteV2Provider extends BaseCSServices { 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(); @@ -1023,25 +1532,11 @@ class SqliteV2Provider extends BaseCSServices { return Promise.resolve(r.value); } - /** the order the built-in provider lists text-search results in (text-index.js) */ + /** the order of text-search results (text-index.js search), then a supplement's codes */ 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); - } + const out = []; + for (const id of (await this._pausing(searchG(this.store, text, lang || 'en', this._stats()))).ids) if (bm.has(id)) out.push(id); + if (extras && extras.length) for (const id of extras) if (bm.has(id)) out.push(id); return out; } @@ -1052,8 +1547,13 @@ class SqliteV2Provider extends BaseCSServices { 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) + if (prep.forIterate && prep.specs.length > 0 && prep.specs.every((sp) => sp.node.t === 'layer') + && !prep.specs.some((sp) => isEnumerableLayer(sp.node))) { + const sp = prep.specs[0]; + throw this.filterError(notUnderstood(sp.prop, sp.op, sp.value)); + } + // within the listed concepts, as processSelection's includes are (compile.js domain: an + // unlisted concept is never selected by a filter) const node = this._compiler().domain(prep.nodes.length === 1 ? prep.nodes[0] : { t: 'and', items: prep.nodes }); if (prep.forIterate) { if (prep.searchText != null) { @@ -1075,6 +1575,8 @@ class SqliteV2Provider extends BaseCSServices { prep.filters = [new V2FilterSet(null, { node, expressionsFalse: prep.expressionsFalse })]; } for (const f of prep.filters) f.specs = prep.specs; + // codes in their own right of an identifier scheme a filter lists by its alias value + if (prep.forIterate && this.store.aliasSchemes.length) prep.filters[0].extra = await this._aliasEntries(prep.specs); return prep.filters; } @@ -1095,6 +1597,11 @@ class SqliteV2Provider extends BaseCSServices { 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; + if (set.pos >= set.baseSize) { + const e = set.extra[set.pos - set.baseSize]; + set.current = this._aliasConcept(e.id, e.code, e.scheme); + return true; + } 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)); @@ -1115,13 +1622,17 @@ class SqliteV2Provider extends BaseCSServices { 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; + const compat = this.store.compat; + // compatibility.filterUnknownCodeMessage: the reason for a code a value-set filter check cannot locate + if (!r.context) return compat.filterUnknownCodeMessage ? this._message(compat.filterUnknownCodeMessage, code) : r.message; + if (r.context.alias ? this._aliasMember(set, r.context) : this._member(set, r.context.id)) return r.context; + // compatibility.filterRejectMessage: the reason for a located code the clause does not select + return compat.filterRejectMessage ? this._message(compat.filterRejectMessage, code) : null; } async filterCheck(prep, set, concept) { const c = await this._ensure(concept); - return this._member(set, c.id); + return c.alias ? this._aliasMember(set, c) : this._member(set, c.id); } _member(set, id) { @@ -1134,7 +1645,9 @@ class SqliteV2Provider extends BaseCSServices { // ---- processSelection (whole single-system composes) ---------------------------------------- - handlesSelecting() { return true; } + // not for a system with an expansion limit (expansionLimits.maxCodes): expand.js's usual path + // counts the codes against it + handlesSelecting() { return !(this.expandLimitation() > 0); } /** * cs-api processSelection (expand.js processCodes): the page of the whole compose, with the @@ -1170,6 +1683,8 @@ class SqliteV2Provider extends BaseCSServices { // 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; + // codes in their own right read through an identifier scheme: the usual path lists and checks them + if (this._composeHasAliasCodes(includes, excludes)) 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]) { @@ -1186,6 +1701,16 @@ class SqliteV2Provider extends BaseCSServices { } catch (e) { if (trace) trace.span('fallback: ' + e.message, 'set', this.system(), () => null); if (e.unsupported) return null; + // expansionLimits.wholeSystem refuse: the whole system is not listed (count=0 of the one + // include is counted: the usual path asks countAllCodes) + if (e.wholeSystemRefused) { + if (count === 0 && includes.length === 1 && !excludes.length) return null; + throw this._wholeSystemRefusal(); + } + if (e.supplementNotEnumerable) { + throw new Issue('error', 'not-supported', e.filterPath || null, 'FILTER_NOT_UNDERSTOOD', + this.opContext.i18n.translate('FILTER_NOT_UNDERSTOOD', (params && params.HTTPLanguages) || this.opContext.langs, e.notUnderstood), 'vs-invalid', 422); + } if (e.filterError) return null; // expand.js reports it through filter() throw e; } @@ -1227,7 +1752,7 @@ class SqliteV2Provider extends BaseCSServices { // active ones when the compose or activeOnly leaves the inactive ones out (A9). Not with // excludeNotForUI, which expand.js doesn't count this way either (no provider counts abstract codes) // (RxNorm: its whole system is the RXNCONSO concepts, a set, not the walk) - const whole = result.wholeSystem || (this.dialect.name === 'rxnorm' && includes.length === 1 && !excludes.length + const whole = result.wholeSystem || (this.store.readingValues('unlisted').length > 0 && includes.length === 1 && !excludes.length && ['filter', 'concept', 'valueSet'].every((k) => !(includes[0][k] || []).length)); const total = count === 0 && whole && !(params && params.excludeNotForUI) ? await this.countAllCodes(excludeInactive || !!(params && params.activeOnly)) : result.total; @@ -1245,6 +1770,7 @@ class SqliteV2Provider extends BaseCSServices { const open = async (cset) => { const filters = cset.filter || []; const prep = { + specs: filters.map((f) => ({ prop: f.property, op: f.op, value: f.value })), expressionsFalse: filters.some((f) => f.property === 'expressions' && String(f.value) === 'false'), supplementOnly: filters.length > 0 && filters.every((f) => this._isSupplementFilter(f)) }; @@ -1277,68 +1803,68 @@ class SqliteV2Provider extends BaseCSServices { } -/** 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' }; +/** binary text order (SQLite BINARY for BMP text; code points beyond) */ +function cmpText(x, y) { + if (x === y) return 0; + if (!/[\uD800-\uDFFF]/.test(x) && !/[\uD800-\uDFFF]/.test(y)) return x < y ? -1 : 1; + return Buffer.compare(Buffer.from(x, 'utf8'), Buffer.from(y, 'utf8')); +} + +/** + * The property definitions a file declares in expansions (data built at load): each reportable row + * with a uri; none where compatibility.expansionDeclaresProperties is false + */ +function propertyDefinitionsFor(store) { + if (!store.compat.expansionDeclaresProperties) return null; 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'); + for (const d of store.catalog.values()) { + if (d.internal || d.shape === 'record' || d.role === 'language' || !d.uri || seen.has(d.name)) continue; + if (d.lookup === 'never' && d.expansion === 'never') continue; + seen.add(d.name); + defs.push({ code: d.name, uri: d.uri, type: d.shape === 'link' || d.shape === 'union' ? 'code' : d.type }); + } 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; - }); +/** + * The file's implicit ConceptMaps over mapping rows (meta implicitMaps base and maps): [{system, + * key, url}], each map `{base}{key}` translating to the target system + */ +function implicitMaps(store) { + const im = store.implicitMapsSpec; + return im.maps ? im.maps.map(([system, key]) => ({ system, key, url: im.base + key })) : []; } -// 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) { +/** R4 equivalence from the file's side -> R5 relationship from the translated code's side */ +function mapRelationship(equivalence, fromFile) { 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'; + case 'narrower': return fromFile ? 'source-is-broader-than-target' : 'source-is-narrower-than-target'; + case 'wider': return fromFile ? 'source-is-narrower-than-target' : 'source-is-broader-than-target'; default: return 'related-to'; } } +/** substitute {v}, {v_} ({v} with each - written _), {display}, {version} in every string of a JSON value */ +function substitute(x, vars) { + if (typeof x === 'string') return x.replace(/\{(v_|v|display|version)\}/g, (m, k) => (vars[k] != null ? vars[k] : m)); + if (Array.isArray(x)) return x.map((y) => substitute(y, vars)); + if (x && typeof x === 'object') return Object.fromEntries(Object.entries(x).map(([k, y]) => [k, substitute(y, vars)])); + return x; +} + // ---- factory ------------------------------------------------------------------------------- +/** + * The grammars this reader implements (meta grammar): name -> the factory class that serves files + * with it (index.js registers snomed.js). A file without a grammar has plain codes. + */ class SqliteV2Factory extends CodeSystemFactoryProvider { + /** the code grammar this factory implements (meta grammar; null: plain codes) */ + static grammar = null; + constructor(i18n, file, opts = {}) { super(i18n); this.file = file; @@ -1347,26 +1873,43 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { 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; + // a file whose codes have a grammar this factory does not implement (index.js GRAMMARS) + if (this.store.grammar !== this.constructor.grammar) { + const g = this.store.grammar; + this.store.close(); + throw new Error(`${this.file}: ${g == null ? 'its codes are plain codes, not' : `its codes are in the grammar ${g}, not`} ${this.constructor.grammar == null ? 'plain codes' : 'the grammar ' + this.constructor.grammar} (meta grammar), which this provider serves`); + } + // the grammar's filter rules (snomed.js), or none + this.grammarRules = this.constructor.grammarRules || {}; + // implicit value set templates: the grammar form only where the grammar answers it + for (const t of this.store.implicitValueSets) { + if (t.grammar !== undefined && !(this.constructor.implicitValueSetGrammars || []).includes(t.grammar)) { + this.store.close(); + throw new Error(`${this.file}: meta implicitValueSets names the grammar form ${t.grammar}, which this server does not implement`); + } + } + // meta order.expansion: concept ids, the stored order (ix_order), or the code + const words = this.store.orderWords('expansion'); + if (words.length !== 1) { + this.store.close(); + throw new Error(`${this.file}: meta order.expansion ${JSON.stringify(words)}: this server orders expansions by one word`); + } + const order = words[0] === 'stored' ? this._systemOrder() + : words[0] === 'code' ? require('./orders').codeOrder(this.store) : null; + if (order) order.selfFirst = !!this.store.compat.isAListsFocusFirst; 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]; + // text-search ties by the stored order read the same arrays + if (order && words[0] === 'stored') this.store.ordinal = (id) => order.rank[id]; this.layers = new SupplementLayers(this.store); - this.propDefs = propertyDefinitionsFor(this.store, this.dialect); + this.propDefs = propertyDefinitionsFor(this.store); // 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) { + /** the stored answer order (orders.js): arrays stored in the file (ix_order), read lazily, array by array */ + _systemOrder() { const t0 = Date.now(); - const order = this.store.systemOrder(kind); + const order = this.store.systemOrder(); this.orderBuildMs = Date.now() - t0; return order; } @@ -1374,40 +1917,73 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { 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(); } + /** the catalog name: the stored CodeSystem resource's name, else code_system.name, else the system */ + name() { + const r = this._resource(); + return (r && typeof r.name === 'string' && r.name) || this.store.cs.name || this.store.system; + } + _resource() { + if (this._res === undefined) { + try { this._res = this.store.cs.resource ? JSON.parse(this.store.cs.resource) : null; } catch (e) { this._res = null; } + } + return this._res; + } + // compatibility.lookupNameIsTitle: code_system.name or the title (a title of the requested + // language from meta titles first; no title: the name; no name: the system) + _csName() { return this.store.cs.name || this.store.system; } + _csTitle(langs = null) { + const titles = this.store.meta.has('titles') ? JSON.parse(this.store.meta.get('titles')) : null; + if (titles && langs) { + for (const l of (langs.languages || [])) { + const want = primary(l && (l.code || l.language)); + const k = Object.keys(titles).find((t) => primary(t) === want); + if (want && k) return titles[k]; + } + } + return this.store.cs.title || this._csName(); + } + // (CodeSystemProvider.description: no answer reads it) code_system.description, else the title + description() { return this.store.cs.description || this._csTitle(); } + lookupName(langs = null) { return this.store.compat.lookupNameIsTitle ? this._csTitle(langs) : this._csName(); } 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 - */ + /** the listed concepts (README.md "Concept status": not the unlisted ones) */ 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; + const l = this.store.listed(); + return l ? l.size : this.store.conceptCount; + } + /** what the stored CodeSystem resource declares (versionAlgorithmString / versionAlgorithmCoding), else null */ + versionAlgorithm() { + if (this._resourceAlgorithm === undefined) { + const r = this._resource(); + this._resourceAlgorithm = r ? VersionUtilities.versionAlgorithmOf(r) : null; } - return this._liveCount; + return this._resourceAlgorithm; } - 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. + * The factory id: read.js and search.js serve the system as CodeSystem/x-, so that the + * CodeSystem id is the stored resource's id as it is (`x-loinc2.82`); none without one */ 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(); + const r = this._resource(); + const id = r && typeof r.id === 'string' ? r.id : null; + return id && id.startsWith('x-') ? id.substring(2) : id; } + /** + * The partial version a request may name for this file (library.js registers the factory under + * it too): with meta version.partial, the version before the separator + */ + getPartialVersion() { + const v = this.version(); + const sep = this.store.versionRule.partial; + return sep && v.includes(sep) ? v.substring(0, v.indexOf(sep)) : null; + } + describeVersion(v) { - if (this.store.system === RXNORM) { + // meta version.describe release-date: this file's version is described by its release date (DD-Mon YYYY) + const rd = this.store.cs.release_date; + if (this.store.versionRule.describe === 'release-date' && v === this.version() && /^\d{4}-\d{2}-\d{2}/.test(rd || '')) { const { formatDateMMDDYYYY } = require('../../library/utils/utilities'); - return formatDateMMDDYYYY(v); + return formatDateMMDDYYYY(rd.substring(5, 7) + rd.substring(8, 10) + rd.substring(0, 4)); } return super.describeVersion(v); } @@ -1416,22 +1992,15 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { languages() { return this._langs; } /** - * The link a page gives a code, as main's providers gave it (org.hl7.fhir.core's LoincLinker and - * DataRenderer.getLinkForCode): LOINC codes, parts, answers and groups to their page at - * loinc.org; RxNorm concepts to RxNav. Other systems have none. SNOMED CT is SnomedV2Factory's. + * The link a page gives a code (meta codeLink, README.md "Code links"): the template with the + * code, URI-encoded; none without one. The `snomed` grammar gives SNOMED CT's (snomed.js). */ codeLink(context) { - if (!context || !context.code) { + const template = this.store.codeLink; + if (!template || !context || !context.code) { return undefined; } - const code = encodeURIComponent(context.code); - if (this.store.system === LOINC) { - return `https://loinc.org/${code}/`; - } - if (this.store.system === RXNORM) { - return `https://mor.nlm.nih.gov/RxNav/search?searchBy=RXCUI&searchTerm=${code}`; - } - return undefined; + return template.split('{code}').join(encodeURIComponent(context.code)); } async build(opContext, supplements) { @@ -1439,70 +2008,130 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { return new SqliteV2Provider(opContext, supplements, this); } + /** + * The file's implicit value sets (meta implicitValueSets, README.md "implicitValueSets"): the first + * template whose url (with {v}) and v match the URL; a grammar template is the grammar's + */ async buildKnownValueSet(url, version) { - if (version && version !== this.version()) return null; - if (this.store.system === LOINC) return this._loincKnownValueSet(url); + for (const t of this.store.implicitValueSets) { + if (t.grammar !== undefined) { + const vs = await this.grammarValueSet(t.grammar, url, version); + if (vs) return vs; + continue; + } + if (version && version !== this.version()) continue; + const vs = this._templateValueSet(t, url); + if (vs !== undefined) return vs; + } 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 }] } }; + /** a grammar's implicit value sets (snomed.js); none here */ + async grammarValueSet() { return null; } + + /** the value set a template makes of url; undefined: the template does not match */ + _templateValueSet(t, url) { + const i = t.url.indexOf('{v}'); + let v = ''; + if (i < 0) { + if (url !== t.url) return undefined; + } else { + const head = t.url.substring(0, i), tail = t.url.substring(i + 3); + if (!(url.startsWith(head) && url.endsWith(tail) && url.length >= head.length + tail.length)) return undefined; + v = url.substring(head.length, url.length - tail.length); } - 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 })) }] } }; + if (t.v !== undefined && !new RegExp(t.v).test(v)) return undefined; + let row = null; + if (t.mustBeCode || t.enumerate || /\{display\}/.test(JSON.stringify(t))) { + const id = this.store.idOf(v); + if (id == null) { + if (t.mustBeCode) return undefined; + } else row = this.store.conceptRows([id]).get(id); } - return null; + const vars = { v, v_: v.replace(/-/g, '_'), display: row ? row.display : null, version: this.version() }; + const vs = { resourceType: 'ValueSet', url, version: this.version(), status: 'active' }; + for (const k of ['name', 'title', 'description']) if (t[k] !== undefined) vs[k] = substitute(t[k], vars); + vs.date = new Date().toISOString(); + vs.experimental = false; + let include; + if (t.enumerate) { + // the concepts one filter selects, in the filter's order, listed + const f = substitute(t.enumerate, vars); + const c = new Compiler({ store: this.store, grammar: this.grammarRules }, { listOrder: true }); + const node = c.filter(f.property, f.op, f.value); + const ids = this.engine.ordered(node); + const rows = this.store.conceptRows(ids); + include = { system: this.system(), concept: ids.map((id) => ({ code: rows.get(id).code })) }; + } else { + include = { system: this.system(), ...substitute(t.include, vars) }; + } + vs.compose = { include: [include] }; + return vs; } - // LOINC's implicit concept maps (http://loinc.org/cm/) + /** + * The file's implicit concept maps over mapping rows (meta implicitMaps: {base}{key}), offered for + * a translation between this system and the map's: from this system when the code has a row of + * it; into this system (not with implicitMaps.forwardOnly) when some row maps the code. With + * implicitMaps.used a map is offered both ways whether or not it translates the code (its + * translations are getTranslations': forwardOnly still finds nothing into this system). + */ async findImplicitConceptMaps(conceptMaps, source, sourceVersion, dest, code = null) { - if (this.store.system !== LOINC || !dest) return; + const maps = implicitMaps(this.store); + if (!maps.length || !dest) return; + const me = this.system(); 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 spec = this.store.implicitMapsSpec; + const always = spec.used !== undefined; + const other = source === me ? destSystem : destSystem === me && (always || !spec.forwardOnly) ? source : null; + const lm = maps.find((m) => m.system === other); + if (!lm || conceptMaps.some((m) => m.url === lm.url)) return; + if (code && !always) { const id = this.store.idOf(code); if (!this.store.hasMap(id, lm.system, code)) return; } - conceptMaps.push(this._loincMap(lm)); + conceptMaps.push(this._implicitMap(lm)); } + /** an implicit map by URL: one of implicitMaps.maps, or an association (`?fhir_cm=`) */ async findImplicitConceptMap(url, version) { - if (this.store.system !== LOINC || !url || !url.startsWith(LOINC_MAP_BASE)) return null; + if (!url) 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; + const lm = implicitMaps(this.store).find((m) => m.url === url); + if (lm) return this._implicitMap(lm); + const prefix = this.system() + '?fhir_cm='; + if (url.startsWith(prefix)) { + const a = (this.store.implicitMapsSpec.associations || []).find((x) => x.relation === url.substring(prefix.length)); + if (a) return this._associationMap(a); + } + return null; } - _loincMap(lm) { + _implicitMap(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`, + const me = this.system(); + const groups = [{ source: me, target: lm.system }]; + if (lm.system !== me && !this.store.implicitMapsSpec.forwardOnly) groups.push({ source: lm.system, target: me }); + return new ConceptMap({ resourceType: 'ConceptMap', internalSource: this, loincMap: lm, url: lm.url, + name: `${this.name()} ${lm.key} Concept Map`, description: `The mappings between ${this.name()} ${this.version()} and ${lm.system}, as published by ${this.name()}`, status: 'active', group: groups }); } + /** the map of an association relation (implicitMaps.associations), named by the relation's concept */ + _associationMap(a) { + const { ConceptMap } = require('../library/conceptmap'); + const id = this.store.idOf(a.relation); + const row = id != null ? this.store.conceptRows([id]).get(id) : null; + const what = row && row.display ? row.display : a.relation; + const r = this._resource(); + return new ConceptMap({ + resourceType: 'ConceptMap', internalSource: this, association: a, id: a.relation, url: `${this.system()}?fhir_cm=${a.relation}`, version: this.version(), + name: `${this.name()} ${what} Concept Map`, description: `The concept map implicitly defined by ${what}`, + ...(r && r.copyright ? { copyright: r.copyright } : {}), + status: 'active', group: [{ source: this.system(), target: this.system() }] + }); + } + async close() { this.store.close(); } } diff --git a/tx/sqlite-v2/sct-main-ecl.js b/tx/sqlite-v2/sct-main-ecl.js index 0a37243e..b5e01f11 100644 --- a/tx/sqlite-v2/sct-main-ecl.js +++ b/tx/sqlite-v2/sct-main-ecl.js @@ -71,6 +71,10 @@ class Handles { class V2View { constructor(store) { this.store = store; + if (store._mainEclOrder === undefined) { + store._mainEclOrder = store.db.prepare("SELECT 1 FROM main.ix_order WHERE name = 'rank' LIMIT 1").get() ? store.systemOrder() : null; + } + this.order = store._mainEclOrder; this.h = new Handles(); this.rows = new Map(); // concept_id -> row (+ facts) this.idByCode = new Map(); @@ -99,8 +103,11 @@ class V2View { 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; } + idx(id) { return (this.order ? this.order.rank[id] : id - 1) * CONCEPT_SIZE; } + idOf(index) { + const r = index / CONCEPT_SIZE; + return this.order ? this.order.ids[r] : r + 1; + } conceptId(code) { const c = String(code); @@ -188,7 +195,22 @@ function strings(v) { 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) + getLength: (h) => (h === 0 || h === NO || h == null ? 0 : (v.h.get(h) || []).length), + hasSortedReference: (h, value) => { + if (h === 0 || h === NO || h == null) return false; + const list = v.h.get(h); + if (!list || !list.length) return false; + let lo = 0; + let hi = list.length - 1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + const x = list[mid]; + if (x === value) return true; + if (x < value) lo = mid + 1; + else hi = mid - 1; + } + return false; + } }; } @@ -201,7 +223,7 @@ function concepts(v) { }, 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; }, + conceptExists(index) { return index >= 0 && index % CONCEPT_SIZE === 0 && index / CONCEPT_SIZE < S.conceptCount; }, getConcept(index) { const id = v.idOf(index); const f = v.facts(id); @@ -242,7 +264,10 @@ function concepts(v) { 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)) : []; + if (!bm || !bm.size) return []; + const out = bm.toArray().map((d) => v.idx(d)); + if (v.order) out.sort((a, b) => a - b); + return out; }); }, getDepth(index) { @@ -343,23 +368,40 @@ function refSetIndexAndMembers(v) { } return list; }; + const strHandles = new Map(); + const strHandle = (s) => { + let h = strHandles.get(s); + if (h === undefined) { + h = v.h.value(s); + strHandles.set(s, h); + } + return h; + }; 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 rel = S.relations.get(rid); + let rows = S.refsetMemberRows(rid, null, { raw: true, conceptsOnly: true }); + if (!rows.length && !(rel && rel.subjectKind === 'item')) { const bm = S.loadSets(KIND.refset, 0, [rid]).get(rid); - rows = bm ? bm.toArray().map((c) => ({ concept_id: c, fields: '[]' })) : []; + rows = bm ? bm.toArray().map((c) => ({ concept_id: c, f: [] })) : []; } const out = []; for (const r of rows) { - const fields = JSON.parse(r.fields || '[]'); + const fields = r.f || []; const vals = []; - fields.forEach((x, i) => { + for (let i = 0; i < fields.length; i++) { + const x = fields[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); - }); + if (t === 'c') { + const c = typeof x === 'number' ? (x <= S.hi ? x : null) : (x ? v.conceptId(x) : null); + vals.push(c ? v.idx(c) : 0, 1); + } else if (t === 'i') { + vals.push(Number(x), 4); + } else { + const s = typeof x === 'number' ? (S.codesOfNodes([x]).get(x) ?? '') : String(x); + vals.push(strHandle(s), 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 }); } @@ -374,7 +416,30 @@ function refSetIndexAndMembers(v) { }; 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) + getMember: (h, pos) => { + if (h === NO || h === 0 || h == null) return null; + const ms = v.h.get(h); + return ms && pos >= 0 && pos < ms.length ? ms[pos] : null; + }, + getMemberCount: (h) => (h === NO || h === 0 || h == null ? 0 : (v.h.get(h) || []).length), + getMemberRefs: (h) => { + if (h === NO || h === 0 || h == null) return new Uint32Array(0); + const ms = v.h.get(h) || []; + const out = new Uint32Array(ms.length); + for (let i = 0; i < ms.length; i++) out[i] = ms[i].ref; + return out; + }, + getMemberKindsAndValues: (h) => { + if (h === NO || h === 0 || h == null) return { kinds: new Uint8Array(0), values: new Uint32Array(0) }; + const ms = v.h.get(h) || []; + const kinds = new Uint8Array(ms.length); + const values = new Uint32Array(ms.length); + for (let i = 0; i < ms.length; i++) { + kinds[i] = ms[i].kind; + values[i] = ms[i].values; + } + return { kinds, values }; + } }; return { index, mem }; } @@ -435,7 +500,12 @@ function servicesFor(factory) { 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._eclEnumerateAllConcepts = () => { + const out = store.all().toArray().map((id) => v.idx(id)); + if (v.order) out.sort((a, b) => a - b); + return out; + }; + sv._v2 = v; sv.activeConceptCount = () => store.active().size; // read when first used lazyField(sv, ['identifiersByConcept', 'conceptsByIdentifier', 'identifierModules'], () => loadIdentifiers(sv, v)); @@ -511,13 +581,34 @@ function noTextIndexes() { return NO_TEXT_INDEXES || (NO_TEXT_INDEXES = new SnomedTextIndexes([], new Map()).serialize()); } -async function evaluateEcl(store, text, opContext) { +/** description moduleId / effectiveTime are not stored in the file (description() has 0 for both) */ +function assertSupportedByFile(node) { + if (!node || typeof node !== 'object') return; + if (Array.isArray(node)) { for (const x of node) assertSupportedByFile(x); return; } + if (node.kind === 'D' && Array.isArray(node.filters)) { + for (const f of node.filters) { + const field = f && f.field ? String(f.field).toLowerCase() : ''; + if (field === 'moduleid' || field === 'effectivetime') { + throw new Error(`Unsupported ECL description filter ${f.field}: the edition files hold no description ${field === 'moduleid' ? 'modules' : 'effective times'}`); + } + } + } + for (const v of Object.values(node)) assertSupportedByFile(v); +} + +async function evaluateEclOrdered(store, text, opContext) { const { ECLLexer, ECLParser } = require('../sct/ecl'); const sv = servicesFor({ store }); const ast = new ECLParser(new ECLLexer(text).tokenize()).parse(); + assertSupportedByFile(ast); 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)); + if (ctx.eclWildcard && !(ctx.descendants && ctx.descendants.length)) return { bm: store.all(), order: null }; + const order = sv._eclToIndexArray(ctx).map((i) => sv._v2.idOf(i)); + return { bm: new RoaringBitmap32(order), order }; +} + +async function evaluateEcl(store, text, opContext) { + return (await evaluateEclOrdered(store, text, opContext)).bm; } // ---- results kept per file, for the synchronous compiler ------------------------------------ @@ -544,7 +635,7 @@ async function resolveMainEcl(store, text) { if (kept.has(text)) return; let entry; try { - entry = { bm: await evaluateEcl(store, text, null) }; + entry = await evaluateEclOrdered(store, text, null); } catch (err) { entry = { err }; } diff --git a/tx/sqlite-v2/sct-native.js b/tx/sqlite-v2/sct-native.js index aeced27d..b45b499a 100644 --- a/tx/sqlite-v2/sct-native.js +++ b/tx/sqlite-v2/sct-native.js @@ -318,8 +318,14 @@ class NativeExpressionServices extends E.SnomedExpressionServices { 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; + if (t == null || t === NO_REFERENCE) return null; + const cv = this.concreteValueOf(ref.value); + if (cv) { + const concrete = cv.string !== null ? { kind: 'string', value: cv.string } : { kind: 'number', value: cv.number }; + return { active: true, relType: t, target: -1, group: g, concrete }; + } 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 }; + return v == null || 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; @@ -340,8 +346,14 @@ class NativeExpressionServices extends E.SnomedExpressionServices { 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); + if (node.operator) { + if (node.operator === ECLTokenType.DESCENDANT_OR_SELF_OF || node.operator === ECLTokenType.DESCENDANT_OF) { + return this.exprBelowNode(expr, f, node.operator); + } + return false; + } + if (f.type === ECLNodeType.MEMBER_OF || f.type === ECLNodeType.ALT_IDENTIFIER) return false; // an expression is not a refset member return this.exprNode(expr, rels, f); } case ECLNodeType.COMPOUND_EXPRESSION_CONSTRAINT: { @@ -354,17 +366,43 @@ class NativeExpressionServices extends E.SnomedExpressionServices { } case ECLNodeType.REFINED_EXPRESSION_CONSTRAINT: return this.exprNode(expr, rels, node.base) && this.refinementMatches(rels, node.refinement); + case ECLNodeType.DOTTED_EXPRESSION_CONSTRAINT: { + // A dotted constraint (S).A evaluates to a set of pre-coordinated target concepts. + // A complex/refined expression is strictly below its focus, so it cannot equal any + // target concept (matching exprConcept without < / << and Rust ecl.rs); a simple + // equivalent expression matches iff its focus concept is in that target set. + if (!expr.isSimple() || expr.status === E.SnomedExpressionStatus.SubsumedBy) return false; + const ref = expr.concepts && expr.concepts[0] && expr.concepts[0].reference; + if (ref == null || ref === NO_REFERENCE) return false; + return this.evalNode(node).has(ref); + } case ECLNodeType.CONCEPT_REFERENCE: return this.exprConcept(expr, node.conceptId, null); case ECLNodeType.WILDCARD: return true; case ECLNodeType.MEMBER_OF: + case ECLNodeType.ALT_IDENTIFIER: return false; default: throw new Error(`Unsupported ECL node type for expression membership: ${node.type}`); } } + /** whether every focus concept of expr is below focusNode (<< for refined/subsumed expressions) */ + exprBelowNode(expr, focusNode, operator) { + const focus = (expr.concepts || []).map((c) => c.reference).filter((r) => r != null && r !== NO_REFERENCE); + if (!focus.length) return false; + const op = (expr.isSimple() && expr.status !== E.SnomedExpressionStatus.SubsumedBy) + ? operator + : ECLTokenType.DESCENDANT_OR_SELF_OF; + const below = this.evalNode({ + type: ECLNodeType.SUB_EXPRESSION_CONSTRAINT, + operator: op, + focus: focusNode, + }); + return focus.every((f) => below.has(f)); + } + /** a refined expression is strictly below its focus: only < and << can hold */ exprConcept(expr, conceptId, operator) { const target = this.id(conceptId); diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 482f5427..9627831c 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -1,29 +1,33 @@ '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. +// The grammar `snomed` (meta grammar; README.md "grammar"): SNOMED CT expressions and ECL, the +// filters that read the grammar (constraint, expressions) and its value checks, editions and their +// versions, the display ranking from displayContexts (language reference sets and dialects), the +// MRCM typing of concrete values, and the implicit value sets of `?fhir_vs` and the implicit maps an +// edition's content defines (edition translations, alternate identifiers). Everything else (the +// properties $lookup lists, filters, status, orders, the association maps of meta implicitMaps) is +// the generic reader's, from the file. Semantics follow tx/cs/cs-snomed.js. const { SqliteV2Provider, SqliteV2Factory } = require('./provider'); +const { FilterError, Unsupported } = require('./engine/compile'); const { KIND } = require('./store'); const { Issue } = require('../library/operation-outcome'); const { ECLLexer, ECLParser } = require('../sct/ecl'); const { ConceptMap } = require('../library/conceptmap'); -const { editionName, editionCode, snomedCodeLink, noteLoadedRelease, heldReleaseVersion } = require('../sct/editions'); +const { editionName, snomedCodeLink, noteLoadedRelease, heldReleaseVersion } = require('../sct/editions'); const { formatDateMMDDYYYY } = require('../../library/utils/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' } }; +/** + * An identifier scheme whose values are codes of another system (catalog value_system): {system, + * property (its reported name)}, or null + */ +function schemeOf(store, code) { + const d = store.catalog.get(String(code)); + return d && d.shape === 'identifier' && d.valueSystem ? { system: d.valueSystem, property: d.name } : null; +} // 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 @@ -61,17 +65,9 @@ class NativeExprContext { 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; @@ -105,10 +101,6 @@ class SnomedV2Provider extends SqliteV2Provider { 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 @@ -149,7 +141,7 @@ class SnomedV2Provider extends SqliteV2Provider { // 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); + const use = (d) => this._useOf(d, (u) => ({ system: SCT, code: u.code, display: u.display })); // 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); @@ -243,126 +235,23 @@ class SnomedV2Provider extends SqliteV2Provider { 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; } - + /** the generic properties, then the normal forms where asked for by name */ 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 } }] }); - } - } + await super._extendLookup(c, props, params); if (!noNormalForm) this._addNormalForms(c.id, null, props, params); } + /** + * A concrete value of an attribute: an integer where the attribute's MRCM range (reference set + * 723562003) is int(...), else as its fhir_type + */ + _literalValue(d, value) { + if (d.attribute && d.type === 'decimal' && this._concreteIsInteger(d.code)) return { valueInteger: Math.round(Number(value)) }; + return super._literalValue(d, value); + } + /** * 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) @@ -379,6 +268,14 @@ class SnomedV2Provider extends SqliteV2Provider { /** whether a concrete attribute's MRCM range (refset 723562003) is an integer: int(...) */ _concreteIsInteger(attrCode) { + if (!this._intRanges) this._intRanges = new Map(); + if (this._intRanges.has(attrCode)) return this._intRanges.get(attrCode); + const r = this._mrcmIsInteger(attrCode); + this._intRanges.set(attrCode, r); + return r; + } + + _mrcmIsInteger(attrCode) { const S = this.store; const rs = S.idOf('723562003'); const a = S.idOf(attrCode); @@ -472,10 +369,33 @@ class SnomedV2Provider extends SqliteV2Provider { // asked for; triage B9) const add = async (refinement) => { if (!this._hasProp(props, refinement.name.code, true)) return; + const cv = svc.concreteValueOf(refinement.value); + if (cv) { + let val; + if (cv.string !== null) { + val = { valueString: cv.string }; + } else { + const dec = refinement.value.concepts[0].decimal; + const constraint = svc.mrcmAttributeRanges().get(refinement.name.reference); + const range = constraint ? svc.parseConcreteRange(constraint) : null; + const type = range && (range.type === 'dec' || range.type === 'int') ? range.type : (dec.includes('.') ? 'dec' : 'int'); + val = type === 'int' && Number.isInteger(cv.number) ? { valueInteger: cv.number } : { valueDecimal: cv.number }; + } + params.push({ + name: 'property', + part: [ + { name: 'code', valueCode: refinement.name.code }, + { name: 'value', ...val }, + { name: 'code-display', valueString: svc.getDisplayName(refinement.name.code) } + ] + }); + return; + } 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); + const c0 = refinement.value.concepts[0]; + const code = value.isComplex() ? svc.renderExpression(refinement.value, E.SnomedServicesRenderOption.Minimal) : c0.code; + const description = value.isComplex() ? svc.renderExpression(refinement.value, E.SnomedServicesRenderOption.FillMissing) : (c0.reference !== E.NO_REFERENCE ? svc.getDisplayName(c0.reference) : null); + const p = this._addCodeProperty(params, 'property', refinement.name.code, code, null, description || null); p.part.push({ name: 'code-display', valueString: svc.getDisplayName(refinement.name.code) }); }; for (const r of ctxt.expression.refinements) await add(r); @@ -492,14 +412,14 @@ class SnomedV2Provider extends SqliteV2Provider { 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]; + const scheme = schemeOf(this.store, 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]; + const scheme = schemeOf(this.store, schemeId); if (!scheme || scheme.system !== coding.system) continue; const sid = S.idOf(schemeId); if (sid == null) continue; @@ -638,6 +558,13 @@ class SnomedV2Provider extends SqliteV2Provider { return super._subsumesTest(a.context, b.context); } + async doesFilter(prop, op, value) { + // constraint = is always a supported SNOMED filter (cs-snomed.js doesFilter); + // syntax/unknown-concept errors are reported as 400 INVALID_ECL when filter() runs. + if (prop === 'constraint' && op === '=') return true; + return super.doesFilter(prop, op, value); + } + /** 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)) { @@ -653,47 +580,79 @@ class SnomedV2Provider extends SqliteV2Provider { 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; + return super.getTranslations(map, coding, target, reverse); } } -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(); + +/** a SNOMED CT concept id as a filter value: 6-18 digits */ +function sctId(v) { + return /^\s*\d{6,18}\s*$/.test(String(v)); } -const LOADED = new Set(); +/** + * The grammar's filter rules (README.md "grammar"), used by the compiler (engine/compile.js + * term.grammar): the filters that read `grammar` (constraint: ECL; expressions), the value check + * (a concept or attribute value is 6-18 digits: Invalid concept ID otherwise), an unknown concept + * on a concept row is an error, and ECL the engine does not evaluate is handed to main's ECL + */ +const SNOMED_RULES = Object.freeze({ + /** + * the name a not-understood filter is reported under: a name whose filter rows read only the + * concept is reported as `concept` (cs-snomed.js #filterProperty: code is concept) + */ + filterName(c, name) { + const rows = c.store.filters.filter((f) => f.code === name); + return rows.length && rows.every((f) => f.reads.length === 1 && f.reads[0] === 'concept') ? 'concept' : name; + }, + checkValues(c, row, op, vals) { + if (op === 'in' || op === 'not-in' || op === 'regex' || op === 'exists') return; + const nodeValued = row.reads.some((x) => x === 'concept' || x === '{1}' || (c.store.catalog.get(x) || {}).kind === 'concept'); + if (!nodeValued) return; + for (const v of vals) if (!sctId(v)) throw new FilterError(`Invalid concept ID: ${v}`); + }, + unknownConcept(c, op, value) { + throw new FilterError(`The SNOMED CT Concept ${value} is not known`, { unknownConcept: value }); + }, + filter(c, prop, op, value) { + if (prop === 'constraint' && op === '=') return c.ecl(value); + // expressions = true: expressions are allowed as well (an expansion still lists only concepts; an + // expression's membership is decided natively over this file, see _nativeMember) + if (prop === 'expressions' && op === '=') return value === 'true' ? { t: 'all', expressionsTrue: true } : { t: 'all', expressionsFalse: true }; + return null; + }, + /** ECL the engine refuses: evaluated by main's ECL (cs-snomed.js) over this file, as ids */ + eclFallback(c, text) { + const M = require('./sct-main-ecl'); + const kept = M.mainEclResult(c.store, text); + if (kept === undefined) throw new M.NeedsMainEcl(c.store, text); + 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); + } + const node = { t: 'ids', ids: kept.bm.toArray(), label: 'ECL (main) ' + text.slice(0, 60) }; + if (kept.order) node.order = kept.order; + return node; + }, +}); class SnomedV2Factory extends SqliteV2Factory { + static grammar = 'snomed'; + static grammarRules = SNOMED_RULES; + static implicitValueSetGrammars = ['fhir_vs']; + 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; - } /** - * The links cs-snomed.js gives (editions.js snomedCodeLink): a concept to snomed.info, in its - * edition when snomed.info knows it; an expression that is more than one concept to the - * browser's home page. A context is a concept (V2Concept) or an expression (NativeExprContext). + * The `snomed` grammar's code links, as cs-snomed.js gives them (editions.js snomedCodeLink): a + * concept to snomed.info, in its edition when snomed.info knows it; an expression that is more + * than one concept to the browser's home page. A context is a concept (V2Concept) or an + * expression (NativeExprContext). */ codeLink(context) { if (!context) { @@ -705,23 +664,6 @@ class SnomedV2Factory extends SqliteV2Factory { return context.code ? snomedCodeLink(String(context.code), this.version()) : undefined; } - /** - * 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; @@ -762,7 +704,7 @@ class SnomedV2Factory extends SqliteV2Factory { noteLoadedRelease(this.version()); // 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']) + this._displayRefsets = [].concat(this.store.displayRefsets || []) .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); @@ -803,7 +745,9 @@ class SnomedV2Factory extends SqliteV2Factory { return null; } - async buildKnownValueSet(url, version) { + /** the grammar's implicit value sets: meta implicitValueSets {"grammar": "fhir_vs"} */ + async grammarValueSet(name, url, version) { + if (name !== 'fhir_vs') return null; if (!url.startsWith('http://snomed.info/')) return null; if (version != null && !this.version().startsWith(version)) return null; const form = this.implicitValueSetForm(url); @@ -825,7 +769,13 @@ class SnomedV2Factory extends SqliteV2Factory { 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(); + const ids = new Set(this.store.refsetIds()); + for (const cid of this.store.languageRefsetIds()) ids.add(cid); + if ((this.store.moduleDependencies || []).length) { + const md = this.store.idOf('900000000000534007'); + if (md != null) ids.add(md); + } + const codes = this.store.codesOf([...ids]).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/')) { @@ -843,7 +793,13 @@ class SnomedV2Factory extends SqliteV2Factory { 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)); + let ecl = id.substring(13); + try { + ecl = decodeURIComponent(ecl); + } catch (e) { + // not encoded (or not validly): use it as it stands (as cs-snomed.js) + } + if (!ecl.trim()) return null; 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; @@ -918,9 +874,9 @@ class SnomedV2Factory extends SqliteV2Factory { } _identifierMap(moduleId, mods) { - const schemes = [...((mods || this._identifierModules()).get(moduleId) || [])].filter((x) => IDENTIFIER_SCHEMES[x]); + const schemes = [...((mods || this._identifierModules()).get(moduleId) || [])].filter((x) => schemeOf(this.store, x)); if (!schemes.length) return null; - const systems = schemes.map((x) => IDENTIFIER_SCHEMES[x].system); + const systems = schemes.map((x) => schemeOf(this.store, x).system); const mid = this.store.idOf(moduleId); const moduleName = mid != null ? (this.store.conceptRows([mid]).get(mid).display || moduleId) : moduleId; return new ConceptMap({ @@ -942,7 +898,7 @@ class SnomedV2Factory extends SqliteV2Factory { 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)) { + if ([...schemes].some((x) => schemeOf(this.store, x) && schemeOf(this.store, x).system === ident)) { const cm = this._identifierMap(moduleId, mods); if (cm && !conceptMaps.some((m) => m.url === cm.url)) conceptMaps.push(cm); } @@ -968,32 +924,42 @@ class SnomedV2Factory extends SqliteV2Factory { } 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 }] - }); + return super.findImplicitConceptMap(url, version); } webSource() { return this.version(); } } -// an expression context is answered natively +// An expression context is answered natively. A single concept written <<< X (the only simple +// expression _nativeLocate keeps as an expression, triage B8) is the concept X for everything but +// its code (cs-snomed.js answers it as a concept that is not complex): its display, designations, +// status and properties are X's. Its code and $lookup (which adds the normal forms) stay native, +// and an expression has no classificationCode (cs-api.js, as cs-snomed.js). +const NATIVE_ALWAYS = new Set(['code', 'extendLookup', 'expansionCode', 'classificationCode', 'reportedClassificationCode']); for (const m of ['code', 'display', 'definition', 'isAbstract', 'isInactive', 'isDeprecated', 'getStatus', 'itemWeight', - 'parent', 'designations', 'extensions', 'properties', 'incompleteValidationMessage', 'extendLookup', 'expansionCode']) { + 'parent', 'designations', 'extensions', 'properties', 'incompleteValidationMessage', 'extendLookup', 'expansionCode', + 'classificationCode', 'reportedClassificationCode']) { const own = SnomedV2Provider.prototype[m]; + const answer = async function (ctxt, rest) { + if (NATIVE_ALWAYS.has(m) || ctxt.isComplex() || ctxt.expression.concepts[0].literal) return this._nativeAnswer(m, ctxt, rest); + if (m === 'display') { + const sup = this._displayFromSupplements(ctxt.source); + if (sup) return sup; + } + if (!ctxt.concept) { + const r = await SqliteV2Provider.prototype._locate.call(this, ctxt.expression.concepts[0].code); + if (!r.context) throw new Error(r.message || `Unknown code ${ctxt.expression.concepts[0].code}`); + ctxt.concept = r.context; + } + return own.call(this, ctxt.concept, ...rest); + }; SnomedV2Provider.prototype[m] = async function (context, ...rest) { - if (context instanceof NativeExprContext) return this._nativeAnswer(m, context, rest); + if (context instanceof NativeExprContext) return answer.call(this, 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); + if (r.context instanceof NativeExprContext) return answer.call(this, r.context, rest); return own.call(this, r.context, ...rest); } return own.call(this, context, ...rest); diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 29d1efb9..d00eb0c7 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -4,22 +4,27 @@ // 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); +// - its access path: shape (link / literal / both / union / record / identifier, and the three +// shapes without rows of their own: item-use, mapping, reading), 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; 'status': the status text), by_target (which links ix_in holds), by_subject +// (which identifier rows ix_by_subject holds); +// - how it is reported: fhir_code, also_asked_as, lookup, expansion, the ranks, true_value, +// presentation, internal; // - 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 FHIR reading is the rest of the file: item_use (designation kinds), filter (the filters the +// system understands) and the meta keys of meta.js (conceptStatus, order, search, version, ..., +// compatibility). Each has one meaning and a default; a malformed value is an error at open, and so +// is a value this server does not implement. // // 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('../../library/sql/better-sqlite3'); const { RoaringBitmap32 } = require('roaring-js'); +const { readMeta, orderOf, FILTER_ROW_OPERATORS } = require('./meta'); const FORMAT = 'tx-terminology/1'; const USER_VERSION = 1; @@ -60,8 +65,8 @@ function holdReadLock(db) { } /** - * 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 + * A source id (item.external_id) 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); @@ -74,80 +79,26 @@ function setKey(kind, pid, value, vk = 0) { } +const FILTER_OPS = new Set(FILTER_ROW_OPERATORS); +const SHAPES = new Set(['link', 'literal', 'both', 'identifier', 'record', 'union', 'item-use', 'mapping', 'reading']); +const LOOKUP = new Set(['default', 'named', 'never']); +const EXPANSION = new Set(['asked', 'always', 'never']); +const READINGS = new Set(['inactive', 'deprecated', 'notSelectable']); +// catalog columns of earlier revisions: a file that has one is a writer's mistake (README.md "property") +const REMOVED_COLUMNS = ['filterable', 'filter_ops', 'report', 'reported_as', 'named_links', 'name_any_case', 'value_any_case', + 'default_value', 'match_display', 'selects_members', 'n_rows', 'target_kind']; +// what a filter row may read besides a property code (README.md "filter") +const FILTER_READS = new Set(['concept', 'inactive', 'display', 'designations', 'grammar', '{1}']); + /** - * 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. + * property.presentation: {value?: code|string|display|coding, parts?: [description|code-display|partCode|equivalence|version]}; + * equivalence and version only on a mapping row */ -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); +function isPresentation(v, shape) { + const parts = ['description', 'code-display', 'partCode'].concat(shape === 'mapping' ? ['equivalence', 'version'] : []); + return v !== null && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).every((k) => k === 'value' || k === 'parts') + && (v.value === undefined || ['code', 'string', 'display', 'coding'].includes(v.value)) + && (v.parts === undefined || (Array.isArray(v.parts) && v.parts.every((x) => parts.includes(x)))); } const NODE_SHAPES = new Set(['link', 'union']); @@ -201,7 +152,7 @@ class Store { this.uid = ++ownerSeq; try { checkFormat(this.db, file); - this._loadMeta(); + this._loadMeta(!opts.db); } catch (e) { if (!opts.db) this.db.close(); throw e; @@ -331,17 +282,12 @@ class Store { // ---- 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`. + * Text filter ($expand filter): the concepts a text filter matches (text-index.js search, with + * the parameters of meta search). `lang` (a primary language subtag) is the one language a text + * filter searches (the provider chooses it). */ - searchText(text, stats, mode, lang = null, defLang = 'en') { - const g = this.searchTextG(text, stats, mode, lang, defLang); + searchText(text, stats, lang = null) { + const g = this.searchTextG(text, stats, lang); let r = g.next(); while (!r.done) r = g.next(); return r.value; @@ -351,28 +297,27 @@ class Store { * 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') { + * searchTextG(text, stats, lang = null) { 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; + return (yield* ti.searchG(this, t, lang || primaryLang(this.defaultLanguage), stats)).bm; } // ---- metadata and catalog ----------------------------------------------------------------- - _loadMeta() { + _loadMeta(checkIds = true) { 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'); + // the meta keys (meta.js): a file of an earlier revision, a malformed value, an unknown feature: refused + const m = readMeta(this.meta, this.file); + this.requires = m.requires; 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, + this.cs = { id: cs.cs_id, uri: cs.uri, version: cs.version, name: cs.name, title: cs.title, description: cs.description, resource: cs.resource ?? null, 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; @@ -381,7 +326,32 @@ class Store { this.activeCount = cs.active_count; this.lo = 1; this.hi = cs.concept_count; - this.behaviour = readBehaviour(this.meta, this.file); + // the id ranges every read relies on (an id <= concept_count is a concept, above it an item): + // concept ids 1..N and item ids above N; three probes of the rowid b-trees (min and max apart: + // SQLite reads one end of the b-tree for a lone min() or max()) + // (not for a store over a connection a caller holds: a supplement layer, a file mid-build) + if (checkIds) this._checkIdRanges(cs.concept_count); + // the FHIR reading (README.md "Meta keys"), every key with its default + this.compat = m.compatibility; + this.conceptStatus = m.get('conceptStatus'); + this.expansionLimits = m.get('expansionLimits'); + this.order = m.get('order'); + this.search = m.get('search'); + this.versionRule = m.get('version'); + this.implicitValueSets = m.get('implicitValueSets'); + this.implicitMapsSpec = m.get('implicitMaps'); + this.grammar = m.get('grammar'); + this.codeLink = m.get('codeLink'); + // (compatibility.expansionKeepsRepeatedDesignations: the server's expansion code lists every + // designation a provider gives, repeats included, so a file that sets it is served as it says) + // compatibility.lookupListsCopyright: the notice $lookup lists (code_system.resource.copyright) + this.copyright = null; + if (this.compat.lookupListsCopyright) { + let r = null; + try { r = cs.resource ? JSON.parse(cs.resource) : null; } catch (e) { r = null; } + if (!r || typeof r.copyright !== 'string' || !r.copyright) throw new Error(`${this.file}: compatibility.lookupListsCopyright without code_system.resource.copyright`); + this.copyright = r.copyright; + } // a compositional system's expansions are never closed (post-coordinated expressions are codes) this.notClosed = cs.compositional === 1; this.defaultLanguage = cs.default_language || null; @@ -391,8 +361,10 @@ class Store { 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._loadUses(); + this._loadFilters(); + this._loadStatus(); + this._checkReading(); this.hasFts = true; this.hasAcceptability = this.langRelations.size > 0; this.hasRank = true; @@ -404,28 +376,304 @@ class Store { this.hasLinkOrder = !!(this.hierarchy && this.hierarchy.byTarget); } + /** an order member of meta order with its default (meta.js ORDER_WORDS) */ + orderWords(member) { return orderOf(this.order, member); } + + /** + * item_use: the kinds of designation (README.md "item_use"): role fsn / synonym / display, a use + * whose items are the values of an item-use property (as_property), the uses that give a display + * in a requested language (language_display_rank) + */ + _loadUses() { + const db = this.db; + const cols = new Set(db.prepare('PRAGMA main.table_info(item_use)').all().map((c) => c.name)); + if (cols.has('reported_as')) throw new Error(`${this.file}: item_use has the column reported_as of an earlier revision`); + const missing = ['role', 'as_property', 'language_display_rank'].filter((c) => !cols.has(c)); + if (missing.length) throw new Error(`${this.file}: item_use lacks the columns ${missing.join(', ')}`); + this.uses = new Map(); + const asProperty = new Map(); + for (const u of db.prepare('SELECT use_id, system, code, display, role, as_property, language_display_rank FROM main.item_use').all()) { + if (u.role != null && !['fsn', 'synonym', 'display'].includes(u.role)) throw new Error(`${this.file}: item use ${u.code} has role ${u.role} (fsn, synonym, display or NULL)`); + if (u.language_display_rank != null && !(Number.isSafeInteger(u.language_display_rank) && u.language_display_rank >= 0)) { + throw new Error(`${this.file}: item use ${u.code} has language_display_rank ${u.language_display_rank}`); + } + const use = { id: u.use_id, system: u.system, code: u.code, display: u.display, role: u.role ?? null, asProperty: u.as_property ?? null, languageDisplayRank: u.language_display_rank ?? null }; + if (use.asProperty != null) { + const d = this.catalog.get(use.asProperty); + if (!d || d.shape !== 'item-use') throw new Error(`${this.file}: item use ${u.code} names as_property ${use.asProperty}, which is no item-use property`); + if (asProperty.has(use.asProperty)) throw new Error(`${this.file}: two item uses name as_property ${use.asProperty}`); + asProperty.set(use.asProperty, use); + d.use = use; + } + this.uses.set(u.use_id, use); + } + for (const d of this.catalog.values()) { + if (d.shape === 'item-use' && !d.use) throw new Error(`${this.file}: property ${d.code} has shape item-use, and no item use names it`); + } + // item_use.role by the use's coding (a designation reports its use as a coding) + this.useRoles = new Map(); + for (const u of this.uses.values()) if (u.role) this.useRoles.set(`${u.system || ''}|${u.code}`, u.role); + // the uses whose items are not designations (as_property) + this.propertyUseIds = [...this.uses.values()].filter((u) => u.asProperty != null).map((u) => u.id); + // the uses that give the display in a requested language, in their order + this.languageDisplayUses = [...this.uses.values()].filter((u) => u.languageDisplayRank != null) + .sort((a, b) => a.languageDisplayRank - b.languageDisplayRank || a.id - b.id); + } + + /** the filter table (README.md "filter"): every filter the system understands, checked at open */ + _loadFilters() { + const db = this.db; + if (!db.prepare("SELECT 1 FROM main.sqlite_master WHERE type = 'table' AND name = 'filter'").get()) throw new Error(`${this.file}: no filter table`); + const bad = (r, why) => new Error(`${this.file}: filter ${r.id} (${r.code ?? r.code_pattern}): ${why}`); + const parse = (r, col) => { try { return JSON.parse(r[col]); } catch (e) { throw bad(r, `${col} is not JSON`); } }; + this.filters = []; + for (const r of db.prepare('SELECT * FROM main.filter ORDER BY id').all()) { + if ((r.code == null) === (r.code_pattern == null)) throw bad(r, 'exactly one of code and code_pattern must be set'); + let pattern = null; + if (r.code_pattern != null) { + try { pattern = new RegExp('^(?:' + r.code_pattern + ')$'); } catch (e) { throw bad(r, 'code_pattern is not a regular expression'); } + } + const ops = parse(r, 'operators'); + if (!(Array.isArray(ops) && ops.length && new Set(ops).size === ops.length && ops.every((o) => FILTER_OPS.has(o)))) throw bad(r, `operators ${r.operators}`); + let reads = parse(r, 'reads'); + if (typeof reads === 'string') reads = [reads]; + if (!(Array.isArray(reads) && reads.length && reads.every((x) => typeof x === 'string' && x))) throw bad(r, `reads ${r.reads}`); + for (const x of reads) { + if (FILTER_READS.has(x)) { + if (x === 'grammar' && this.grammar == null) throw bad(r, 'reads grammar, and the file has no grammar'); + if (x === '{1}' && !(pattern && /\((?!\?)/.test(r.code_pattern))) throw bad(r, 'reads {1} without a capture group'); + continue; + } + // (an internal row may be read: it is never a filter's name, reported or declared) + if (!this.catalog.get(x)) throw bad(r, `reads ${x}, which is no property of the catalog`); + } + if (r.code != null && (this.catalog.get(r.code) || {}).internal) throw bad(r, `named by the internal property ${r.code}`); + const allowed = r.allowed_values == null ? null : parse(r, 'allowed_values'); + if (!(allowed === null || allowed === 'codes' || (Array.isArray(allowed) && allowed.every((x) => typeof x === 'string')))) throw bad(r, `allowed_values ${r.allowed_values}`); + if (!['any', 'exact'].includes(r.value_case)) throw bad(r, `value_case ${r.value_case}`); + const where = r.where_literal == null ? null : parse(r, 'where_literal'); + if (where !== null) { + if (!(where && typeof where === 'object' && !Array.isArray(where))) throw bad(r, `where_literal ${r.where_literal}`); + for (const [k, v] of Object.entries(where)) { + const d = this.catalog.get(k); + if (!d || d.shape !== 'literal' || typeof v !== 'string') throw bad(r, `where_literal names ${k}, which is no literal property`); + } + } + let then = null; + if (r.then_link != null) { + then = this.catalog.get(r.then_link); + if (!then || !['link', 'both', 'union'].includes(then.shape)) throw bad(r, `then_link ${r.then_link} is no link property`); + } + this.filters.push({ id: r.id, code: r.code, pattern, anyCase: !!r.code_any_case, description: r.description ?? null, operators: ops, reads, + allowed, prefix: r.value_prefix ?? null, exactCase: r.value_case === 'exact', asDisplay: !!r.value_as_display, where, then }); + } + // two rows of one name have disjoint operators, or value prefixes that no value has both of + // (then not exists, which takes no prefix): a value is read by one row + for (let i = 0; i < this.filters.length; i++) { + for (let j = i + 1; j < this.filters.length; j++) { + const a = this.filters[i], b = this.filters[j]; + if (a.code == null || a.code !== b.code) continue; + const shared = a.operators.filter((o) => b.operators.includes(o)); + if (!shared.length) continue; + const apart = a.prefix != null && b.prefix != null && !a.prefix.startsWith(b.prefix) && !b.prefix.startsWith(a.prefix) && !shared.includes('exists'); + if (!apart) throw bad(b, `shares an operator with filter ${a.id} of the same code, and values could be read by both`); + } + } + } + + /** + * The filter rows that understand a filter's name and operator (README.md "filter"), each with the + * capture of a code_pattern row: [{row, capture}], empty when none does. Several rows only when they + * are told apart by value_prefix: each value is read by the row whose prefix it has + */ + filterRows(name, op) { + // `of` offers VCL `of` and set-valued `in` on a row; a filter with the operator `of` is no row's + if (op === 'of') return []; + const n = String(name); + const named = (f) => f.code === n || (f.anyCase && f.code.toLowerCase() === n.toLowerCase()); + for (const f of this.filters) { + if (!f.operators.includes(op)) continue; + if (f.code != null) { + if (named(f)) return this.filters.filter((g) => g.code === f.code && g.operators.includes(op)).map((g) => ({ row: g, capture: null })); + } else { + const m = f.pattern.exec(n); + if (m) return [{ row: f, capture: m[1] ?? null }]; + } + } + return []; + } + + /** + * conceptStatus (README.md "conceptStatus"): for each entry, the property and the meanings of each + * value, without the readings compatibility.statusReadingsIgnored removes + */ + _loadStatus() { + const ignored = new Map(this.compat.statusReadingsIgnored.map((e) => [e.property, e.values])); + this.statusReadings = []; + for (const e of this.conceptStatus) { + const d = this.catalog.get(e.property); + if (!d || d.shape !== 'literal') throw new Error(`${this.file}: conceptStatus names ${e.property}, which is no literal property`); + const ign = ignored.get(e.property) || {}; + const values = new Map(); + for (const [v, ms] of Object.entries(e.values)) { + const left = ms.filter((x) => !(ign[v] || []).includes(x)); + if (left.length) values.set(v, new Set(left)); + } + this.statusReadings.push({ property: d, values }); + } + for (const e of this.compat.statusReadingsIgnored) { + if (!this.conceptStatus.some((x) => x.property === e.property)) throw new Error(`${this.file}: compatibility.statusReadingsIgnored names ${e.property}, which conceptStatus does not`); + } + this._statusSets = new Map(); + } + + /** the values (per property) that give a concept the meaning: [{property, values: [...]}] */ + readingValues(meaning) { + const out = []; + for (const r of this.statusReadings) { + const vs = [...r.values].filter(([, ms]) => ms.has(meaning)).map(([v]) => v); + if (vs.length) out.push({ property: r.property, values: vs }); + } + return out; + } + + /** + * The concepts with a reading (README.md "Concept status": deprecated, notSelectable, unlisted), + * as the union of the property's stored sets of the values with that meaning; deprecated only + * for active concepts. null: no value has that meaning in this file + */ + statusSet(meaning, stats) { + if (this._statusSets.has(meaning)) return this._statusSets.get(meaning); + const parts = []; + for (const { property, values } of this.readingValues(meaning)) { + for (const b of this.loadSets(KIND.prop, property.id, values, stats).values()) if (b.size) parts.push(b); + } + let bm = this.readingValues(meaning).length ? RoaringBitmap32.orMany(parts) : null; + if (bm && meaning === 'deprecated') bm = RoaringBitmap32.and(bm, this.active(stats)); + this._statusSets.set(meaning, bm); + return bm; + } + + /** the readings of one concept (README.md "Concept status"), from its status literals: a Set */ + readingsOf(id, stats) { + const out = new Set(); + for (const { property, values } of this.statusReadings) { + for (const r of this.literalsOf([id], false, stats)) { + if (r.p !== property.id) continue; + for (const x of values.get(String(r.v)) || []) out.add(x); + } + } + return out; + } + + /** + * Checks of the reading at open: the rows conceptStatus names have the stored sets a reading is + * read from, and every column this reader obeys has a value it implements + */ + _checkReading() { + // the alias columns (README.md "Alternate codes"): identifier rows only. alias_literals is + // {fhir code: template} (a string each; {code} is the concept's own code) + this.aliasSchemes = []; + for (const d of this.catalog.values()) { + d.aliasLiterals = null; + d.aliasParameter = null; + d.aliasExtension = null; + const has = ['alias_parameter', 'alias_extension', 'alias_literals'].filter((c) => d[c] != null); + if (!has.length) continue; + if (d.shape !== 'identifier') throw new Error(`${this.file}: property ${d.code} has ${has.join(', ')}, which only an identifier row may have`); + if (d.alias_literals != null) { + let v; + try { v = JSON.parse(d.alias_literals); } catch (e) { v = null; } + if (!(v && typeof v === 'object' && !Array.isArray(v) && Object.values(v).every((x) => typeof x === 'string'))) { + throw new Error(`${this.file}: property ${d.code}: alias_literals ${d.alias_literals} is not {fhir code: template}`); + } + d.aliasLiterals = v; + } + for (const [c, k] of [['alias_parameter', 'aliasParameter'], ['alias_extension', 'aliasExtension']]) { + if (d[c] == null) continue; + if (typeof d[c] !== 'string' || d[c] === '') throw new Error(`${this.file}: property ${d.code}: ${c} ${d[c]} is not a name`); + d[k] = d[c]; + } + this.aliasSchemes.push(d); + } + // the output parameter $validate-code reports the alias under: the server's one such parameter + for (const d of this.aliasSchemes) { + if (d.aliasParameter != null && d.aliasParameter !== 'classificationCode') { + throw new Error(`${this.file}: property ${d.code} has alias_parameter ${d.aliasParameter}; this server reports an alias as the parameter classificationCode only`); + } + } + if (this.aliasSchemes.filter((d) => d.aliasParameter != null).length > 1 || this.aliasSchemes.filter((d) => d.aliasExtension != null).length > 1) { + throw new Error(`${this.file}: more than one property has alias_parameter or alias_extension`); + } + this.aliasParameterScheme = this.aliasSchemes.find((d) => d.aliasParameter != null) || null; + this.aliasExtensionScheme = this.aliasSchemes.find((d) => d.aliasExtension != null) || null; + } + + /** + * The identifiers of a scheme that are codes in their own right (resolves = 2), as + * [[concept id, value]] in concept id, then value order; within the listed concepts (subject <= hi) + */ + codeIdentifiersOf(d, stats) { + const q = this.stmt('SELECT subject_id, value FROM main.identifier WHERE property_id = ? AND resolves = 2 AND subject_id <= ? ORDER BY subject_id, value').raw(); + const rows = q.all(d.id, this.hi).map(([s, v]) => [s, String(v)]); + if (stats) count(stats, this, q, rows.length); + return rows; + } + + /** a concept's identifiers of a scheme that resolve as an alias (resolves = 1), in value order */ + aliasValuesOf(d, id) { + return this.stmt('SELECT value FROM main.identifier WHERE property_id = ? AND subject_id = ? AND resolves = 1 ORDER BY value').pluck().all(d.id, id).map(String); + } + + _checkIdRanges(n) { + const one = (sql) => this.db.prepare(sql).pluck().get(); + const lo = one('SELECT min(id) FROM main.concept'), hi = one('SELECT max(id) FROM main.concept'); + if (n > 0 ? (lo !== 1 || hi !== n) : lo != null) throw new Error(`${this.file}: concept ids are not 1..${n} (concept_count): min ${lo}, max ${hi}; the file is damaged`); + const ilo = one('SELECT min(id) FROM main.item'); + if (ilo != null && ilo <= n) throw new Error(`${this.file}: item id ${ilo} is not above every concept id (1..${n}); the file is damaged`); + } + _loadCatalog() { + // the catalog columns of this revision (README.md "property"): a file without them, or with a + // column of an earlier revision, is refused + const cols = new Set(this.db.prepare('PRAGMA main.table_info(property)').all().map((c) => c.name)); + const old = REMOVED_COLUMNS.filter((c) => cols.has(c)); + if (old.length) throw new Error(`${this.file}: property has the columns ${old.join(', ')} of an earlier revision`); + const missing = ['fhir_code', 'also_asked_as', 'lookup', 'expansion', 'lookup_rank', 'expansion_rank', 'true_value', 'presentation', 'value_system', + 'internal', 'alias_parameter', 'alias_extension', 'alias_literals'].filter((c) => !cols.has(c)); + if (missing.length) throw new Error(`${this.file}: property lacks the columns ${missing.join(', ')}`); 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 + const bad = (r, why) => new Error(`${this.file}: property ${r.code}: ${why}`); 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, + subjectKind: r.subject_kind, conceptId: r.concept_id, + isHierarchy: !!r.subsumption, closureFrom: r.closure_from, 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, + // how it is reported (README.md "property"): under fhir_code (else code), also asked for by + // also_asked_as; lookup / expansion; ranks; a boolean where true_value is set + fhirCode: r.fhir_code ?? null, alsoAskedAs: r.also_asked_as ? JSON.parse(r.also_asked_as) : [], trueValue: r.true_value ?? null, + lookup: r.lookup, expansion: r.expansion, lookupRank: r.lookup_rank ?? null, expansionRank: r.expansion_rank ?? null, + internal: !!r.internal, valueSystem: r.value_system ?? null, presentation: r.presentation ? JSON.parse(r.presentation) : null, + alias_parameter: r.alias_parameter ?? null, alias_extension: r.alias_extension ?? null, alias_literals: r.alias_literals ?? 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)`); + def.name = def.fhirCode || def.code; + if (!SHAPES.has(def.shape)) throw bad(r, `shape ${def.shape}`); + if (!LOOKUP.has(def.lookup)) throw bad(r, `lookup ${def.lookup} (default, named or never)`); + if (!EXPANSION.has(def.expansion)) throw bad(r, `expansion ${def.expansion} (asked, always or never)`); + for (const k of ['lookupRank', 'expansionRank']) if (def[k] != null && !(Number.isSafeInteger(def[k]) && def[k] >= 0)) throw bad(r, `${k} ${def[k]}`); + if (def.role != null && !['language', 'status'].includes(def.role)) throw bad(r, `role ${def.role}`); + if (def.internal && (def.lookup !== 'never' || def.expansion !== 'never')) throw bad(r, 'internal, and reported'); + if (def.shape === 'reading' && !(READINGS.has(def.code) && def.type === 'boolean')) throw bad(r, 'a reading row is inactive, deprecated or notSelectable, of type boolean'); + if (!(Array.isArray(def.alsoAskedAs) && def.alsoAskedAs.every((x) => typeof x === 'string' && x))) throw bad(r, `also_asked_as ${r.also_asked_as}, not a list of names`); + if (def.presentation !== null && !isPresentation(def.presentation, def.shape)) throw bad(r, `presentation ${r.presentation}`); this.catalog.set(def.code, def); this.propsById.set(def.id, def); } @@ -436,22 +684,28 @@ class Store { 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)); + // a union of identifier rows is read as they are, by value (RxNorm AUI:); a union + // with no members has no statements + if (d.shape === 'union') { + const all = d.members ? stored(d) : []; + if (all.length && all.every((m) => m.shape === 'identifier')) d.kind = 'identifier'; + else if (all.some((m) => m.shape === 'identifier')) throw new Error(`${this.file}: property ${d.code}: a union of identifier and other rows`); + } } 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) + // the statement-valued properties by code (ECL attributes and supplement-layer filters read + // them): link, literal, both and union rows; 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; + if (!FILTER_SHAPES.has(d.shape) || d.kind === 'identifier' || d.reverses || closureSources.has(d.id)) 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); + // descendants sets) + this.hiddenLinks = [...closureSources]; // 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 @@ -464,8 +718,11 @@ class Store { // 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:')); + // the literal that holds the concept's status text (role 'status') + const status = [...this.catalog.values()].filter((d) => d.role === 'status'); + if (status.length > 1) throw new Error(`${this.file}: more than one property with role status`); + if (status.length && status[0].shape !== 'literal') throw new Error(`${this.file}: the status property ${status[0].code} is not a literal`); + this.statusProp = status[0] || null; // 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; } @@ -473,12 +730,6 @@ class Store { /** 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) { @@ -491,11 +742,46 @@ class Store { return this._labels.get(p.id) || null; } + /** + * The concepts answers list (README.md "Concept status": every concept but the unlisted ones), + * or null: every concept + */ + listed(stats) { + if (this._listed === undefined) { + const u = this.statusSet('unlisted', stats); + this._listed = u ? RoaringBitmap32.andNot(this.all(stats), u) : null; + } + return this._listed; + } + + /** the role (item_use.role) of a designation's use coding, or null */ + useRoleOf(use) { + return use ? this.useRoles.get(`${use.system || ''}|${use.code}`) || null : null; + } + /** the languages of the served system's items (meta, a release fact) */ languages() { return JSON.parse(this.meta.get('languages') || '[]'); } + /** + * concept id -> its place in the stored system order (ix_order rank), for the order word + * `stored`; by concept id where the file stores no rank + */ + rankOrdinal() { + if (this._rankOrdinal === undefined) { + if (this.ordinal) this._rankOrdinal = this.ordinal; + else if (this.db.prepare("SELECT 1 FROM main.ix_order WHERE name = 'rank' LIMIT 1").get()) { + const order = this.systemOrder(); + this._rankOrdinal = (id) => order.rank[id]; + } else this._rankOrdinal = (id) => id; + } + return this._rankOrdinal; + } + + /** an identifier value to probe with: text (identifier-text) */ + _idProbe(v) { return String(v); } + /** the built-in answer order (ix_order rank / ids / walk), read array by array */ - systemOrder(kind) { return require('./orders').storedOrder(this, kind); } + systemOrder() { return require('./orders').storedOrder(this); } hierarchyOrderOf(id) { if (this._hierOrder === undefined) this._hierOrder = require('./orders').hierarchyOrder(this); @@ -597,9 +883,20 @@ class Store { return ids.sort((a, b) => a - b); } + /** language reference sets (role 'language') with at least one record row, by concept id */ + languageRefsetIds() { + const ids = []; + if (!this.langRelations.size) return ids; + const q = this.stmt('SELECT EXISTS(SELECT 1 FROM main.record WHERE relation_id = ?)').pluck(); + for (const [relId, cid] of this.langRelations) { + if (cid != null && q.get(relId)) ids.push(cid); + } + return ids.sort((a, b) => a - b); + } + // ---- codes ------------------------------------------------------------------------------ - resolveCodes(codes, stats) { + resolveCodes(codes, stats, opts = {}) { const out = new Map(); const want = [...new Set(codes.filter((c) => c != null).map(String))]; if (!want.length) return out; @@ -608,8 +905,17 @@ class Store { : 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); + // (opts.identifiers: a code that is no concept code may be an identifier accepted as a code, + // README.md "Alternate codes": its concept) + if (opts.identifiers && this.hasCodeIdentifiers) { + for (const c of want) { + if (out.has(c)) continue; + const hit = this.identifierAsCode(c, stats); + if (hit) out.set(c, hit.concept_id); + } + } + for (const c of want) if (!out.has(c)) out.set(c, null); return out; } @@ -650,9 +956,9 @@ class Store { * 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} + const q = this.stmt(`SELECT ${this._rowCols}, i.resolves, i.property_id AS scheme_id 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; + const r = q.get(this._idProbe(value)) || null; if (stats) count(stats, this, q, r ? 1 : 0); return r; } @@ -666,6 +972,11 @@ class Store { return this.stmt('SELECT id, code FROM main.concept WHERE cs_id = +? AND code >= ? AND code < ?').raw().all(this.csId, low, high); } + /** identifiers accepted as codes (resolves > 0) with a value in [low, high): [[concept id, value]] */ + identifierCodesInRange(low, high) { + return this.stmt('SELECT subject_id, value FROM main.identifier WHERE resolves > 0 AND value >= ? AND value < ? AND subject_id <= ?').raw().all(low, high, this.hi); + } + codesUpToLength(n) { return this.stmt('SELECT id, code FROM main.concept WHERE cs_id = +? AND length(code) <= ?').raw().all(this.csId, n); } @@ -743,28 +1054,26 @@ class Store { /** * 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, + * [{id, language, use, term, active, preferred, rank, acc}]). opts: skipUses (use ids), * 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 skip = (opts.skipUses || []).map(Number); + const useCond = opts.onlyUse != null ? `AND use_id = ${Number(opts.onlyUse)}` : skip.length ? `AND (use_id IS NULL OR use_id NOT IN (${skip.join(',')}))` : ''; 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; + let l = null, lid = 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] } : {}) }); } @@ -828,7 +1137,7 @@ class Store { } /** - * Node-valued facts about concepts (one statement): rows {s, p, g, t, active}; pids (a Set) the + * Node-valued facts about concepts (one statement): rows {s, p, g, t, active, q (link.seq)}; 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) */ @@ -839,11 +1148,11 @@ class Store { 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 + q = this.stmt(`SELECT subject_id AS s, property_id AS p, group_id AS g, target_id AS t, active, seq AS q 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 + q = this.stmt(`SELECT subject_id AS s, property_id AS p, group_id AS g, target_id AS t, active, seq AS q 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); } @@ -851,14 +1160,75 @@ class Store { return rows; } + /** + * The active links of some properties to a concept (an inverse row's values): rows {s, p, g, q + * (link.seq)}; from ix_in for a by-target property, else the property's stored sets (kind 5: + * its subjects) and their link rows + */ + linksToOf(id, pids, stats) { + const out = []; + for (const pid of pids) { + const d = this.propsById.get(pid); + if (!d) continue; + if (d.byTarget) { + const q = this.stmt('SELECT subject_id AS s, property_id AS p, group_id AS g, seq AS q FROM main.ix_in WHERE target_id = +? AND property_id = +? AND active = 1'); + const rows = q.all(id, pid); + if (stats) count(stats, this, q, rows.length); + out.push(...rows); + continue; + } + const subjects = this.getSet(KIND.prop, pid, id, stats).toArray(); + if (!subjects.length) continue; + const q = this.stmt(`SELECT subject_id AS s, property_id AS p, group_id AS g, seq AS q FROM main.link + WHERE subject_id IN (SELECT value FROM json_each(?)) AND property_id = +? AND target_id = +? AND active = 1`); + const rows = q.all(json(subjects), pid, id); + if (stats) count(stats, this, q, rows.length); + out.push(...rows); + } + return out.filter((r) => r.s <= this.hi); + } + + /** a concept's identifiers of some identifier rows: [{p, v}] (ix_by_subject for the by_subject ones) */ + identifiersOf(id, rows) { + const out = []; + const by = rows.filter((d) => d.bySubject).map((d) => d.id); + if (by.length) for (const [p, v] of this.stmt('SELECT property_id, value FROM main.ix_by_subject WHERE subject_id = ? AND property_id IN (SELECT value FROM json_each(?))').raw().all(id, json(by))) out.push({ p, v: String(v) }); + for (const d of rows.filter((x) => !x.bySubject)) { + for (const v of this.stmt('SELECT value FROM main.identifier WHERE property_id = ? AND subject_id = ?').pluck().all(d.id, id)) out.push({ p: d.id, v: String(v) }); + } + return out; + } + + /** a concept's mapping rows of some mapping-shape properties */ + mappingsOf(id, pids) { + return this.stmt('SELECT property_id, system, version, code, display, relationship AS equivalence FROM main.mapping WHERE concept_id = ? AND property_id IN (SELECT value FROM json_each(?)) ORDER BY system, code') + .all(id, json(pids)); + } + + /** a subject's active rows of a record relation, in seq order: [{seq, target, fields}] (fields: the JSON array, parsed) */ + recordRowsOf(relationId, subjectId) { + return this.stmt('SELECT seq, target_id, fields FROM main.record WHERE relation_id = ? AND subject_id = ? AND active = 1 ORDER BY seq').raw().all(relationId, subjectId) + .map(([seq, target, fields]) => ({ seq, target, fields: fields ? JSON.parse(fields) : [] })); + } + + /** the targets of a concept's active rows of a record relation, in seq order */ + recordTargets(relationId, subjectId) { + return this.stmt('SELECT target_id FROM main.record WHERE relation_id = ? AND subject_id = ? AND active = 1 AND target_id IS NOT NULL ORDER BY seq').pluck().all(relationId, subjectId); + } + /** 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); } + /** + * literal rows {c, p, g, v, active, q (literal.seq, read only when order.literals names stored: a + * file written before the column has none)} + */ 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 + const seq = this.orderWords('literals').includes('stored') ? ', seq AS q' : ''; + const q = this.stmt(`SELECT subject_id AS c, property_id AS p, group_id AS g, value AS v, active${seq} 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); @@ -873,6 +1243,12 @@ class Store { return r; } + /** the concept's parents in the release's row order (link seq), else as stored */ + parentsInOrder(id) { + if (!this.hierarchy) return []; + return this.stmt('SELECT target_id FROM main.link WHERE subject_id = +? AND property_id = +? AND active = 1 ORDER BY seq').pluck().all(id, this.hierarchy.id); + } + /** 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)]; @@ -920,13 +1296,16 @@ class Store { * 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) + * opts.targetIn: only the rows whose target column is one of these node ids (in SQL). + * opts.conceptsOnly: only rows whose subject is a concept (subject_id <= hi), not item rows + * projected onto their owning concept (e.g. ECL history supplements skip description refsets). */ refsetMemberRows(refsetId, subjectId = null, opts = {}) { const rel = this.relations.get(refsetId); if (!rel) return []; + if (opts.conceptsOnly && rel.subjectKind === 'item') 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'); + const onItems = !opts.conceptsOnly && 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); @@ -1028,8 +1407,8 @@ class Store { /** 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))); + // values as stored: text (identifier-text) + const vals = values.map((v) => String(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)); @@ -1046,7 +1425,12 @@ class Store { 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)); + 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, this._idProbe(value)); + } + + /** the concepts with an identifier of a scheme (an identifier property row), sorted */ + subjectsOfScheme(d) { + return this.stmt('SELECT DISTINCT subject_id FROM main.identifier WHERE property_id = ? ORDER BY 1').pluck().all(d.id); } conceptsWithScheme(schemeId) { @@ -1082,7 +1466,7 @@ class Store { } 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); + return this.stmt('SELECT c.code, c.display, m.display AS source_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) { @@ -1101,29 +1485,20 @@ class Store { } /** - * 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 + * fn(id, lang, term) for every name the file's text search reads, in concept order (meta + * ix.ix_word.names, text-index.js searchNamesSelection) */ - eachSearchName(dialect, fn) { - require('./text-index').eachSearchName(this, dialect, fn); + eachSearchName(fn) { + require('./text-index').eachSearchName(this, fn); } - searchNames(dialect, ids, fn) { - return require('./text-index').searchNamesOf(this, dialect, ids, fn); + searchNames(ids, fn) { + return require('./text-index').searchNamesOf(this, 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) */ @@ -1131,4 +1506,4 @@ 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 }; +module.exports = { Store, openStore, checkFormat, 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 index e1aa1e68..5a698dd8 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -1,138 +1,185 @@ '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: +// $expand filter= (a text filter): one procedure for every file, with the parameters of meta +// `search` (README.md "search"), over the rules of tx/library/text-match.js (TextQuery): // -// 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). +// 1. the query's words (TextQuery.tokens) in the search language (the provider chooses it); +// 2. the names: the texts meta search.names selects (the display, and the items it names); +// 3. the candidates: the listed concepts (not unlisted), the active ones with candidates.active, +// those with a literal of candidates.hasLiteral.property whose value is not in its `except`; +// 4. a name scores TextQuery.nameRank of the name as stored (nameScore as-written) or of its +// distinct words (distinct-words, as a database text index holds them); a concept its best +// name's; with shortlist n, a one-word query scores only the candidates with the fewest +// distinct words (the n-th smallest count and below; at least 10), the others follow with 0; +// 5. codes: the query as a code prefix (codeMatch text-prefix: TextQuery.codeRanges and +// codeRank) or as a number prefix (number-prefix: the codes of digits whose value starts with +// the query's digits); codeHits merged (by score with the names) or first (before them); +// 6. hits by score, then meta order.searchTies. // // 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. +// ranking a broad filter's names takes seconds (most of it stemming, in TextQuery.nameRank). // -// 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. +// 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 where search.shortlist is set the row with word '', the distinct words of each +// concept (unsigned 16-bit little-endian 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. // // 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. +// naming the rules it was made by (FORMAT) and 'ix.ix_word.stemmers' the stemmer of each language. A +// file without one made by these rules has it built in memory on the first search; so does each +// language whose stemmer is not this server's (usableLanguages). const { RoaringBitmap32 } = require('roaring-js'); -const { TextQuery, words: textWords, stem: stemOf, languageOf } = require('../library/text-match'); +const { TextQuery, words: textWords, stem: stemOf, languageOf, stemmerName } = 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) +// and comparisons per sort step 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'); } +// ---- order of hits with equal score ------------------------------------------------------------ + +const ROOT_COLLATOR = new Intl.Collator('und'); + +/** a code as an unsigned integer (README.md "order", code-number): its leading digits without leading zeros */ +function codeNumberKey(code) { + const m = /^[0-9]*/.exec(String(code))[0].replace(/^0+/, ''); + return m || '0'; +} + +/** code-number order: shorter canonical digit strings first, then binary text */ +function cmpCodeNumber(x, y) { + const a = codeNumberKey(x), b = codeNumberKey(y); + return (a.length - b.length) || cmpBinary(a, b); +} + +/** + * The order of text-search hits of equal score (meta order.searchTies, README.md "order"), as an + * ordinal over the hits: the words compared left to right, then the concept id + */ +function tieOrdinal(store, ids, stats) { + const words = store.orderWords('searchTies'); + if (words.length === 1 && words[0] === 'id') return (id) => id; + if (words.length === 1 && words[0] === 'stored') return store.rankOrdinal(); + const needRows = words.some((w) => w === 'code' || w === 'code-number' || w === 'display'); + const rows = needRows ? store.conceptRows(Array.from(ids), stats) : null; + const rank = words.includes('stored') ? store.rankOrdinal() : null; + const col = (id, c) => String((rows.get(id) || {})[c] ?? ''); + const cmps = words.map((w) => { + switch (w) { + case 'id': return (a, b) => a - b; + case 'stored': return (a, b) => rank(a) - rank(b); + case 'code': return (a, b) => cmpBinary(col(a, 'code'), col(b, 'code')); + case 'code-number': return (a, b) => cmpCodeNumber(col(a, 'code'), col(b, 'code')); + case 'display': return (a, b) => ROOT_COLLATOR.compare(col(a, 'display'), col(b, 'display')); + default: throw new Error(`order.searchTies word ${w}`); + } + }); + const cmp = (a, b) => { for (const c of cmps) { const r = c(a, b); if (r) return r; } return a - b; }; + const pos = new Map([...ids].sort(cmp).map((id, i) => [id, i])); + return (id) => pos.get(id) ?? Infinity; +} + // ---- 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; +/** + * The names a file's text search reads (meta search.names, README.md "search"), or null: a file + * without search has no text search + */ +function searchNamesSelection(store) { + return store.search ? (store.search.names || {}) : null; +} + +/** + * The selection as SQL over item and concept: { display: [lang] | null, items: {where, params, + * lang} | null } + */ +function selectionPlan(store, names) { + if (store._namesPlan && store._namesPlan.names === names) return store._namesPlan; + const plan = { names, display: null, items: null }; + if (names && names.display) plan.display = primaryLanguage(names.display, 'en'); + const it = names && names.items; + if (it) { + const where = ['cs_id = ' + Number(store.csId)]; + if (it.active) where.push('active = 1'); + if (it.designations) where.push('(kind = 0 OR use_id IS NOT NULL)'); + const excluded = []; + for (const code of it.excludeUses || []) for (const [id, u] of store.uses) if (u.code === code) excluded.push(id); + if (excluded.length) where.push(`(use_id IS NULL OR use_id NOT IN (${excluded.map(Number).join(',')}))`); + if (it.includeUses) { + // only the items with one of these uses (null: an item without a use) + const included = []; + for (const code of it.includeUses) if (code != null) for (const [id, u] of store.uses) if (u.code === code) included.push(id); + const any = []; + if (included.length) any.push(`use_id IN (${included.map(Number).join(',')})`); + if (it.includeUses.includes(null)) any.push('use_id IS NULL'); + where.push(any.length ? `(${any.join(' OR ')})` : '0'); + } + plan.items = { where: where.join(' AND '), lang: it.language ? primaryLanguage(it.language, 'en') : null }; } - return store._relatedUse; + store._namesPlan = plan; + return plan; } -/** 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; +/** + * fn(id, lang, term) for every name the file's text search reads (the selection), in concept order; + * langs: only names in these languages (a Set), or all + */ +function eachSearchName(store, fn, langs = null) { + const plan = selectionPlan(store, searchNamesSelection(store)); 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); + const want = (l) => !langs || langs.has(l); + const parts = []; + if (plan.display && want(plan.display)) parts.push("SELECT id, 0 AS k, NULL AS language, display FROM main.concept WHERE display IS NOT NULL AND display <> ''"); + if (plan.items && (!langs || !plan.items.lang || want(plan.items.lang))) parts.push(`SELECT concept_id, 1, language, text FROM main.item WHERE ${plan.items.where}`); + if (!parts.length) return; + const q = store.db.prepare(parts.join(' UNION ALL ') + ' ORDER BY 1, 2').raw(); + for (const [id, k, language, term] of q.iterate()) { + let lang; + if (k === 0) lang = plan.display; + else { + lang = plan.items.lang || primaryLanguage(language, defLang); } - } 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); + if (want(lang)) fn(id, lang, 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'; +/** fn(id, lang, term) for the names of some concepts the file's text search reads; the rows read */ +function searchNamesOf(store, ids, fn) { + const plan = selectionPlan(store, searchNamesSelection(store)); + const defLang = 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') { + if (plan.display) { 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); + fn(id, plan.display, 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)) { + } + if (plan.items) { + 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 ${plan.items.where} ORDER BY id`).raw().iterate(j)) { rows++; - fn(id, 'en', term); + fn(id, plan.items.lang || primaryLanguage(language, defLang), 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. + * The index of a list of names: each(fn) calls fn(id, lang, term) in id order; counting: keep the + * per-concept distinct-word counts. * @returns {Map, counts: Uint16Array|null}>} by language */ -function computeTextIndexFrom(each, dialect, n) { +function computeTextIndexFrom(each, counting, n) { const byLang = new Map(); - const counting = dialect === 'snomed'; const of = (lang) => { let x = byLang.get(lang); if (!x) { @@ -155,6 +202,20 @@ function computeTextIndexFrom(each, dialect, n) { return byLang; } +/** the per-concept counts row (unsigned 16-bit, little-endian on every host) as a Uint16Array */ +function countsFromLE(b) { + const c = new Uint16Array(b.length >>> 1); + for (let i = 0; i < c.length; i++) c[i] = b.readUInt16LE(i * 2); + return c; +} + +/** a Uint16Array of counts as the counts row stores it: little-endian */ +function countsToLE(c) { + const b = Buffer.alloc(c.length * 2); + for (let i = 0; i < c.length; i++) b.writeUInt16LE(c[i], i * 2); + return b; +} + // ---- reading the index ------------------------------------------------------------------------ /** the word index the index builder stored (ix_word) */ @@ -169,7 +230,7 @@ class WordIndex { 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); + c = b ? countsFromLE(b) : new Uint16Array(0); this._counts.set(lang, c); } return c; @@ -251,16 +312,52 @@ class MemoryTextIndex { close() {} } -/** the file's index: stored in the file, else built in memory now */ -function textIndexOf(store, dialect) { +/** + * The languages of a stored word index whose stems this server reproduces: meta ix.ix_word.stemmers + * names, for each language, the stemmer that made its stem column; a language whose stemmer is not + * this server's (text-match.js stemmerName), or not named, is searched without the stored index + */ +function usableLanguages(store, stored) { + const raw = store.meta.get('ix.ix_word.stemmers'); + if (raw == null || !store.search) return new Set(); + const named = JSON.parse(raw); + return new Set([...stored.langs].filter((l) => named[l] === stemmerName(l))); +} + +/** + * A stored index for the languages whose stemmer this server reproduces, and one built in memory + * (from the same selection) for the others + */ +class SplitTextIndex { + constructor(stored, memory, memLangs) { + this.stored = stored; + this.memory = memory; + this.memLangs = memLangs; + this.langs = new Set([...stored.langs, ...memory.langs]); + } + _of(lang) { return this.memLangs.has(lang) ? this.memory : this.stored; } + counts(lang) { return this._of(lang).counts(lang); } + languages() { return this.stored.languages(); } + conceptsFor(lang, token, stats) { return this._of(lang).conceptsFor(lang, token, stats); } + bytes() { return this.stored.bytes() + this.memory.bytes(); } + close() {} +} + +/** the file's index: stored in the file (per language, where this server reproduces its stems), else built in memory now */ +function textIndexOf(store) { + if (store._textIndexOf) return store._textIndexOf; + const counting = !!(store.search && store.search.shortlist); + const build = (langs) => new MemoryTextIndex(store.withoutMmap(() => computeTextIndexFrom((fn) => eachSearchName(store, fn, langs), counting, store.conceptCount))); 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)))); + let index; + if (!stored) index = build(null); + else { + const usable = usableLanguages(store, stored); + const others = new Set([...stored.langs].filter((l) => !usable.has(l))); + index = others.size ? new SplitTextIndex(stored, build(others), others) : stored; } - return built.get(dialect); + store._textIndexOf = index; + return index; } /** the concepts with a word for each token (before checking that they are in one name) */ @@ -275,9 +372,9 @@ function* candidates(index, lang, tokens, stats) { } /** 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) { +function namesOf(store, ids, stats, fn) { if (!ids.length) return; - const rows = store.searchNames(dialect, ids, fn); + const rows = searchNamesOf(store, ids, fn); if (stats) { stats.statements++; stats.rows += rows; } } @@ -286,22 +383,13 @@ function namesOf(store, dialect, ids, stats, fn) { * 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) { +function* namesOfG(store, 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); + namesOf(store, 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(); @@ -381,17 +469,16 @@ function indexedName(term) { return [...new Set(textWords(term))].join(' '); } -// ---- SNOMED CT -------------------------------------------------------------------------------- +// ---- the search ------------------------------------------------------------------------------- /** - * 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) + * Codes of digits whose value starts with the query's digits (codeMatch number-prefix): for each + * length L from the query's length to 18, the codes in [p * 10^(L - n), (p + 1) * 10^(L - n)) for the + * query's value p: for digits without a leading zero, the codes 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 code of at most 18 - n digits). The concept itself first, then by code-number. */ -function sctCodeMatches(store, q, active, stats) { +function numberPrefixCodes(store, q, cands, stats) { if (!/^[0-9]{1,18}$/.test(q.code)) return []; const n = q.code.length; const p = BigInt(q.code); @@ -399,273 +486,162 @@ function sctCodeMatches(store, q, active, stats) { 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)); + const found = rows.filter(([id, code]) => (!cands || cands.has(id)) && code.length <= maxLen && /^[1-9][0-9]*$/.test(code)); + found.sort((a, b) => (a[1] === q.code ? 0 : 1) - (b[1] === q.code ? 0 : 1) || a[1].length - b[1].length || cmpBinary(a[1], b[1])); 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 + * The concepts that may be hits (README.md "search", candidates): the listed concepts, the active + * ones with candidates.active, those with a literal of hasLiteral.property whose value is not in + * `except`; null: every concept */ -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) { +function searchCandidates(store, stats) { + if (store._searchCands !== undefined) return store._searchCands; + const c = (store.search && store.search.candidates) || {}; + let bm = store.listed(stats); + const and = (x) => { bm = bm ? RoaringBitmap32.and(bm, x) : x.clone(); }; + if (c.active) and(store.active(stats)); + if (c.hasLiteral) { 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); + const d = store.catalog.get(c.hasLiteral.property); + const has = new RoaringBitmap32(); + if (d) { + const except = new Set(c.hasLiteral.except || []); + for (const r of store.propValues(d.id, stats)) if (!except.has(String(r.value))) has.orInPlace(store.getSet(KIND.prop, d.id, r.value, stats)); } - store._rxSearchable = bm; + and(has); } - return store._rxSearchable; + store._searchCands = bm; + return bm; } -// ---- LOINC ------------------------------------------------------------------------------------ - /** - * The concepts a LOINC text filter matches, in the built-in provider's order (see the top). + * The concepts a text filter matches, best first (README.md "search"). * @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* () { +function* searchG(store, text, lang, stats = null) { + const sp = store.search; + if (!sp) throw new Error(`${store.file}: no text search`); + return yield* cached(store, 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 cands = searchCandidates(store, stats); const tokens = q.tokens(lang); + // name scores; the shortlist's tail (score 0, after the scored names) + const named = new Map(); + let tail = []; if (tokens.length) { - const index = textIndexOf(store, 'loinc'); + const index = textIndexOf(store); 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); - }); + if (cands) bm.andInPlace(cands); + const asWritten = sp.nameScore === 'as-written'; + const rate = function* (ids) { + const best = new Map(); + yield* namesOfG(store, ids, stats, (id, l, term) => { + if (l !== lang) return; + const r = q.nameRank(asWritten ? term : indexedName(term), lang); + if (r > (best.get(id) ?? 0)) best.set(id, r); + }); + return best; + }; + const ids = Array.from(bm.toUint32Array()); + yield; + if (sp.shortlist && tokens.length === 1) { + // the candidates with the fewest distinct words: the n-th smallest count and below + const counts = index.counts(lang); + const wc = (id) => counts[id] || 1; + const byCount = new Map(); + for (const id of ids) { 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 >= sp.shortlist) { cutoff = c; break; } + } + const head = []; + for (const id of ids) (wc(id) <= cutoff ? head : tail).push(id); + const best = yield* rate(head); + for (const id of head) named.set(id, Math.max(best.get(id) ?? 0, 10)); + } else { + for (const [id, r] of yield* rate(ids)) if (r > 0) named.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); - }); + // codes + let codes; // [id, score] in their order + if (sp.codeMatch === 'number-prefix') { + codes = numberPrefixCodes(store, q, cands, stats).map((id) => [id, null]); + } else { + const ids = codesInRanges(store, q.codeRanges(text), stats).filter((id) => !cands || cands.has(id)); + const rows = store.conceptRows(ids, stats); + codes = ids.map((id) => [id, q.codeRank(rows.get(id).code)]); + for (const [id, v] of identifierCodes(store, q, text, stats)) if (!cands || cands.has(id)) codes.push([id, q.codeRank(v)]); } - 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) }; + let out; + if (sp.codeHits === 'first') { + // code hits first: exact first, then by code-number; then the names + if (sp.codeMatch !== 'number-prefix') { + const crow = store.conceptRows(codes.map(([id]) => id), stats); + const c = (id) => (crow.get(id) || {}).code ?? ''; + codes.sort((a, b) => ((b[1] === 100) - (a[1] === 100)) || cmpCodeNumber(c(a[0]), c(b[0])) || cmpBinary(c(a[0]), c(b[0]))); + } + const have = new Set(codes.map(([id]) => id)); + const head = [...named.keys()].filter((id) => !have.has(id)); + const ord = tieOrdinal(store, [...head, ...tail.filter((id) => !have.has(id))], stats); + const sorted = yield* sortG(head, (a, b) => (named.get(b) - named.get(a)) || ord(a) - ord(b)); + const rest = tail.filter((id) => !have.has(id)).sort((a, b) => ord(a) - ord(b)); + out = [...new Set(codes.map(([id]) => id))].concat(sorted, rest); + } else { + // code hits scored with the names (the better of the two) + const score = new Map(named); + for (const [id, r] of codes) if (r != null && r > (score.get(id) ?? 0)) score.set(id, r); + for (const id of tail) if (!score.has(id)) score.set(id, 0); + const keys = [...score.keys()]; + const ord = tieOrdinal(store, keys, stats); + out = yield* sortG(keys, (a, b) => (score.get(b) - score.get(a)) || ord(a) - ord(b)); + } + return { bm: new RoaringBitmap32(out), ids: Uint32Array.from(out) }; }); } -// ---- other code systems (cs-cs.js) ------------------------------------------------------------ +/** identifiers accepted as codes (resolves > 0) that start with the query (codeMatch text-prefix): [[concept id, value]] */ +function identifierCodes(store, q, text, stats) { + if (!store.hasCodeIdentifiers) return []; + const out = []; + const seen = new Set(); + for (const [low, high] of q.codeRanges(text)) { + for (const [id, v] of store.identifierCodesInRange(low, high)) if (!seen.has(id)) { seen.add(id); out.push([id, v]); } + } + if (stats) stats.statements++; + return out; +} /** - * 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 + * The languages the file has names in (primary subtags), once per file: from the stored index's + * counts rows where it keeps them (one for every language of the names), else from the active items */ -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)); - } +function textLanguages(store) { + if (!store._textLangs) { + const idx = store.textIndex(); + const stored = idx && store.search && store.search.shortlist ? 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))); } - 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); + return store._textLangs; } -// 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)); +// the sync API (runSync): the same search straight through +const search = (...a) => runSync(searchG(...a)); module.exports = { - FORMAT, WordIndex, blockConcepts, indexed, eachSearchName, searchNamesOf, rxSearchable, - computeTextIndexFrom, textIndexOf, primaryLanguage, - sctTextSearch, sctTextLanguages, loincTextSearch, rxTextSearch, genericTextSearch, rateConcepts, - sctTextSearchG, loincTextSearchG, rxTextSearchG, genericTextSearchG + FORMAT, WordIndex, SplitTextIndex, eachSearchName, searchNamesOf, searchNamesSelection, searchCandidates, + computeTextIndexFrom, textIndexOf, primaryLanguage, countsFromLE, countsToLE, usableLanguages, + search, searchG, textLanguages, tieOrdinal, cmpCodeNumber, }; diff --git a/tx/syndication/syndication-store.js b/tx/syndication/syndication-store.js index f017a964..aa1ebd06 100644 --- a/tx/syndication/syndication-store.js +++ b/tx/syndication/syndication-store.js @@ -47,11 +47,17 @@ const BINARY_TERMS = { cpt: 'CPT_DB', // one format for every terminology (tx/sqlite-v2, tx-terminology/1): the entry's identifier // says which code system a file holds + 'sqlite-v2': 'TX_TERMINOLOGY_DB', 'snomed-v2': 'TX_TERMINOLOGY_DB', 'loinc-v2': 'TX_TERMINOLOGY_DB', - 'rxnorm-v2': 'TX_TERMINOLOGY_DB' + 'rxnorm-v2': 'TX_TERMINOLOGY_DB', + 'ndc-v2': 'TX_TERMINOLOGY_DB', + 'unii-v2': 'TX_TERMINOLOGY_DB', + 'cpt-v2': 'TX_TERMINOLOGY_DB' }; const SNOMED_TYPES = new Set(['snomed', 'snomed-v2']); +const SNOMED_SYSTEM = 'http://snomed.info/sct'; +const CPT_SYSTEM = 'http://www.ama-assn.org/go/cpt'; const RESOURCE_TYPES = ['CodeSystem', 'ValueSet', 'ConceptMap']; @@ -356,7 +362,8 @@ class SyndicationStore { } // the full CPT database is licensed content, and is never distributed; the public // fragment is - if (bin.sourceType === 'cpt' && !fileName.toLowerCase().includes('fragment')) { + if ((bin.sourceType === 'cpt' || bin.sourceType === 'cpt-v2' || bin.system === CPT_SYSTEM) + && !fileName.toLowerCase().includes('fragment')) { return this.queue; } const key = `binary:${fileName}`; @@ -378,8 +385,9 @@ class SyndicationStore { const sha256 = await hashFile(bin.filePath); let identifier = bin.system; let version = bin.version ? `${bin.system}|${bin.version}` : bin.system; + const isSnomed = SNOMED_TYPES.has(bin.sourceType) || bin.system === SNOMED_SYSTEM; const sct = /^(.*)\/version\/[^/]+$/.exec(bin.version || ''); - if (SNOMED_TYPES.has(bin.sourceType) && sct) { + if (isSnomed && sct) { // SNOMED editions are identified by their module uri, and versioned by the version uri identifier = sct[1]; version = bin.version; @@ -393,7 +401,7 @@ class SyndicationStore { version, title: `${name}${bin.version && !name.includes(bin.version) ? ' ' + bin.version : ''} (${fileName})`, summary: `FHIRsmith ${term} file ${fileName}`, - rights: SNOMED_TYPES.has(bin.sourceType) ? SNOMED_RIGHTS : OTHER_RIGHTS, + rights: isSnomed ? SNOMED_RIGHTS : OTHER_RIGHTS, link: { href, type: 'application/octet-stream', length: stat.size, sha256 } }); }); diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 9cff0b2e..fb1de05c 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -1315,7 +1315,14 @@ class ValueSetExpander { vsInfo.csDoOffset = true; this.paging = false; this.providerPaged = true; - this.canBeHierarchy = false; + // rows nest under their parent as on the usual path (includeCodes, excludeCodes): a code system + // with parents, each include and exclude with at most one filter (a whole-system include is + // walked there, not nested by parent: flat here) + const nests = cs.hasParents() && [...includes, ...excludes].every(cset => !cset.valueSet && (cset.filter || []).length === 1); + if (!nests) { + this.canBeHierarchy = false; + } + const parentOf = async (c) => (this.canBeHierarchy && !this.noDetails ? this.map.get(this.keyS(cs.system(), cs.version(), await cs.parent(c))) || null : null); const cds = new Designations(this.worker.i18n.languageDefinitions); for (const set of selection.sets || []) { while (await cs.filterMore(null, set)) { @@ -1326,11 +1333,11 @@ class ValueSetExpander { await this.includeCode(cs, null, cs.system(), cs.version(), await cs.code(c), await cs.isAbstract(c), await cs.isInactive(c), null, null, cds, null, null, expansion, null, null, null, null, null, excludeInactive, vsSrc.url); } else if (this.#defers(cs, await cs.code(c))) { - await this.includeCode(cs, null, cs.system(), cs.version(), await cs.code(c), await cs.isAbstract(c), await cs.isInactive(c), + await this.includeCode(cs, await parentOf(c), cs.system(), cs.version(), await cs.code(c), await cs.isAbstract(c), await cs.isInactive(c), null, null, cds, null, null, expansion, null, null, null, null, null, excludeInactive, vsSrc.url, () => this.#readDetails(cs, c)); } else { await this.listDisplaysFromProvider(cds, cs, c); - await this.includeCode(cs, null, cs.system(), cs.version(), await cs.code(c), await cs.isAbstract(c), await cs.isInactive(c), + await this.includeCode(cs, await parentOf(c), cs.system(), cs.version(), await cs.code(c), await cs.isAbstract(c), await cs.isInactive(c), await cs.isDeprecated(c), await cs.getStatus(c), cds, await cs.definition(c), await cs.itemWeight(c), expansion, null, await cs.extensions(c), null, await this.#conceptProperties(cs, c), null, excludeInactive, vsSrc.url); } @@ -2124,6 +2131,10 @@ class ValueSetExpander { const iter = await cs.iterator(context); if (iter) { let c = await cs.nextContext(iter); + if (c && !cs.hasParents()) { + // a code system without parents for an expansion (as the filter path above): the rows are flat + this.canBeHierarchy = false; + } while (c) { await this.worker.checkAndYield('processCodeAndDescendants#3'); result += await this.includeCodeAndDescendants(cs, c, expansion, imports, n, excludeInactive, srcUrl, visited); diff --git a/tx/workers/lookup.js b/tx/workers/lookup.js index f6d4baf9..014fc7a5 100644 --- a/tx/workers/lookup.js +++ b/tx/workers/lookup.js @@ -438,6 +438,58 @@ class LookupWorker extends TerminologyWorker { } checkAddedParameters(responseParams, providerParamsFrom, providerName); + // `.details`: for a Coding property emitted without embedded details (such as a + // sqlite-v2 mapping property like ICD-11 `source`), enrich it with the target concept's + // definition, parent subproperties, and designations (matching cs-icd11.js `#sourcePart`). + const detailProps = new Set((params.properties || []) + .filter(p => typeof p === 'string' && p.toLowerCase().endsWith('.details')) + .map(p => p.slice(0, -8).toLowerCase())); + if (detailProps.size > 0) { + for (let i = providerParamsFrom; i < responseParams.length; i++) { + const entry = responseParams[i]; + if (entry.name !== 'property' || !Array.isArray(entry.part)) continue; + const codePart = entry.part.find(x => x.name === 'code'); + const valPart = entry.part.find(x => x.name === 'value' && x.valueCoding); + if (!codePart || !valPart || !detailProps.has(String(codePart.valueCode || '').toLowerCase())) continue; + if (entry.part.some(x => x.name === 'subproperty' || x.name === 'designation')) continue; + const coding = valPart.valueCoding; + if (!coding.system || !coding.code) continue; + let targetProvider = null; + try { + targetProvider = await this.findCodeSystem(coding.system, coding.version || '', params, ['complete', 'fragment'], null, true); + } catch { + targetProvider = null; + } + if (!targetProvider) continue; + const tLoc = await targetProvider.locate(coding.code); + if (!tLoc || !tLoc.context) continue; + const tDef = await targetProvider.definition(tLoc.context); + if (tDef) { + entry.part.push({ name: 'subproperty', part: [{ name: 'code', valueCode: 'definition' }, { name: 'value', valueString: tDef }] }); + } + const parentParams = []; + await targetProvider.extendLookup(tLoc.context, ['parent'], parentParams, params); + for (const pp of parentParams) { + if (pp.name !== 'property' || !Array.isArray(pp.part)) continue; + const pc = pp.part.find(x => x.name === 'code'); + const pv = pp.part.find(x => x.name === 'value' && x.valueCode); + if (pc && pc.valueCode === 'parent' && pv) { + entry.part.push({ name: 'subproperty', part: [{ name: 'code', valueCode: 'parent' }, { name: 'value', valueCode: pv.valueCode }] }); + } + } + const tDesigs = new Designations(this.languages); + await targetProvider.designations(tLoc.context, tDesigs); + for (const d of tDesigs.designations || []) { + const dp = []; + if (d.language) dp.push({ name: 'language', valueCode: d.language.code }); + if (d.use) dp.push({ name: 'use', valueCoding: d.use }); + if (d.status && d.status !== 'active') dp.push({ name: 'status', valueCode: d.status }); + dp.push({ name: 'value', valueString: d.value }); + entry.part.push({ name: 'designation', part: dp }); + } + } + } + // the properties the supplements in use give the code, whatever the provider (A12): each one // asked for by its code, or by 'property' (or '*', or nothing asked for), as cs-cs.js reports // a code system's own diff --git a/tx/workers/worker.js b/tx/workers/worker.js index 50353a7e..a92864bd 100644 --- a/tx/workers/worker.js +++ b/tx/workers/worker.js @@ -226,7 +226,8 @@ class TerminologyWorker { } } if (provider && checkVer) { - this.checkVersion(url, provider.version(), params, provider.versionAlgorithm(), op); + this.checkVersion(url, provider.version(), params, provider.versionAlgorithm(), op, + typeof provider.versionMatches === 'function' ? (criteria, v) => provider.versionMatches(criteria, v) : null); } return provider; @@ -1294,12 +1295,16 @@ class TerminologyWorker { return result; } - checkVersion(url, version, params, versionAlgorithm, op) { + /** + * @param {Function} [matches] (criteria, version) -> whether a requested version matches: the + * provider's own rule where it has one (versionMatches), else versionMatchesByAlgorithm + */ + checkVersion(url, version, params, versionAlgorithm, op, matches = null) { if (params) { let list = params.rulesForSystem(url); for (let t of list) { if (t.mode === 'check' && !t.vs) { - if (!VersionUtilities.versionMatchesByAlgorithm(t.version, version, versionAlgorithm)) { + if (!(matches ? matches(t.version, version) : VersionUtilities.versionMatchesByAlgorithm(t.version, version, versionAlgorithm))) { let issue = new Issue("error", "exception", null, 'VALUESET_VERSION_CHECK', this.i18n.translate('VALUESET_VERSION_CHECK', params.FHTTPLanguages, [url, version, t.version]), 'version-error', 400); if (op) { op.addIssue(issue);