From c54a2b2b92a4d68a34ae1cd2969a3c7cff64b7fc Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:21:50 -0600 Subject: [PATCH 01/90] sqlite-v2 meta: requires, known keys checked, unknown keys ignored A file's meta follows one rule: requires names the features a reader must understand (an unknown one refuses the file); a known key with a malformed value is refused; any other key is ignored. The builder checks every key it writes against its own list, so a misspelt key fails the build instead of being ignored by readers. The checks live in one place (tx/sqlite-v2/meta.js), used by the reader and the builder. Co-Authored-By: Claude --- tests/tx/sqlite-v2-builder.test.js | 5 +- tests/tx/sqlite-v2-format-round2.test.js | 112 ++++++++++++++++++ tx/importers/sqlite-v2/builder.js | 43 +++++-- tx/importers/sqlite-v2/schema.sql | 6 +- tx/sqlite-v2/README.md | 37 +++++- tx/sqlite-v2/meta.js | 137 +++++++++++++++++++++++ tx/sqlite-v2/store.js | 75 +++---------- 7 files changed, 340 insertions(+), 75 deletions(-) create mode 100644 tests/tx/sqlite-v2-format-round2.test.js create mode 100644 tx/sqlite-v2/meta.js diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js index ac1ed66af..e2e218246 100644 --- a/tests/tx/sqlite-v2-builder.test.js +++ b/tests/tx/sqlite-v2-builder.test.js @@ -352,7 +352,7 @@ 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('behaviour settings: defaults, the ones a file sets, a malformed value 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 }); @@ -365,7 +365,6 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check w.close(); expect(() => openStore(f)).toThrow(msg); }; - bad('behaviour.colour', '"red"', /unknown behaviour setting behaviour.colour/); bad('behaviour.designationUses', '"sometimes"', /behaviour.designationUses = "sometimes" is not a value this server knows/); bad('behaviour.grammar', 'snomed', /is not JSON/); bad('behaviour.preferredForLanguage', '"yes"', /behaviour.preferredForLanguage = "yes" is not a value/); @@ -375,6 +374,7 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check 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.colour', '"red"'); 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', @@ -383,6 +383,7 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check const G = openStore(good, { unregistered: true }); try { expect(G.behaviour.preferredForLanguage).toBe(true); + expect(G.behaviour.colour).toBeUndefined(); expect(G.behaviour.aliasLiterals).toEqual({ 'code-type': '11-digit', synonym: '{code}' }); expect(G.behaviour.filters.map((f) => f.code)).toEqual(['inactive', 'category']); } finally { G.close(); } diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js new file mode 100644 index 000000000..ad490e88f --- /dev/null +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -0,0 +1,112 @@ +'use strict'; + +// The terminology file format (tx/sqlite-v2/README.md): the meta rule (requires, known keys checked, +// unknown keys ignored, the builder's own list), on a small generic fixture. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { TerminologyBuilder } = require('../../tx/importers/sqlite-v2/builder'); +const { openStore } = require('../../tx/sqlite-v2/store'); +const { readMeta } = require('../../tx/sqlite-v2/meta'); + +let dir; +beforeAll(() => { dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-r2-')); }); +afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + +let seq = 0; +/** a small file: a hierarchy, a literal, designations, identifiers; build(b, c) adds to it */ +function fixture(build = null, { uri = 'http://example.org/cs' } = {}) { + 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' }); + 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.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, v); + } + w.close(); + return f; +} + +function withStore(file, fn) { + const S = openStore(file, { unregistered: true }); + try { return fn(S); } finally { S.close(); } +} + +describe('P1. meta: requires, known keys checked, unknown keys ignored', () => { + let base; + beforeAll(() => { base = fixture(); }); + + test('a required feature this reader does not know refuses the file, naming it', () => { + expect(() => openStore(withMeta(base, { requires: '["identifier-text", "time-travel"]' }))).toThrow(/requires the feature time-travel, which this server does not know/); + }); + + test('requires must be a list of distinct strings', () => { + expect(() => openStore(withMeta(base, { requires: '"identifier-text"' }))).toThrow(/meta requires = "identifier-text" is not a value/); + expect(() => openStore(withMeta(base, { requires: '["a", "a"]' }))).toThrow(/meta requires = .* is not a value/); + }); + + test('an unknown meta key is ignored (a behaviour.* key too)', () => { + const f = withMeta(base, { 'colour.of.the.day': 'blue', 'behaviour.colour': 'not even JSON', 'ix.ix_word.someday': '{' }); + withStore(f, (S) => { + expect(S.system).toBe('http://example.org/cs'); + expect(S.behaviour.colour).toBeUndefined(); + }); + const m = readMeta(new Database(f, { readonly: true }).prepare('SELECT key, value FROM meta').raw().all(), f); + expect(m.ignored.sort()).toEqual(['behaviour.colour', 'colour.of.the.day', 'ix.ix_word.someday']); + }); + + test('a known key with a malformed value is refused, naming key and value', () => { + expect(() => openStore(withMeta(base, { 'behaviour.expansionOrder': '"sideways"' }))).toThrow(/meta behaviour.expansionOrder = "sideways" is not a value this server knows/); + expect(() => openStore(withMeta(base, { 'behaviour.distinctDesignationTexts': 'yes' }))).toThrow(/meta behaviour.distinctDesignationTexts = yes 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/); + }); + + test('the builder refuses to finish a file with a key it does not know', () => { + 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, 'never2.db'), { overwrite: true, importer: 'test' }); + b2.codeSystem({ uri: 'http://example.org/x', version: '1' }); + b2.concept('a'); + b2.setBehaviour('expansionOrdre', 'stored'); + expect(() => b2.finish()).toThrow(/meta behaviour.expansionOrdre is not a key this builder knows/); + }); + + test('provenance.* is free-form', () => { + const b = new TerminologyBuilder(path.join(dir, 'prov.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/x', version: '1' }); + b.concept('a'); + b.setMeta('provenance.anything', 'goes'); + b.finish(); + withStore(path.join(dir, 'prov.db'), (S) => expect(S.conceptCount).toBe(1)); + }); +}); + diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 514f7e22a..998416d9f 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -14,8 +14,10 @@ // link row with members and no rows of its own) from the rows, by_target (hierarchy or // refinable) and by_subject (every identifier row) unless the importer set them; // 4. builds the ix_* tables (indexes.js, which reads fact tables only); -// 5. writes meta (format, provenance), ANALYZE (sqlite_stat1 only: analyze()) and VACUUM (unless -// the importer still writes derived-by-importer rows: then it calls vacuumFile() after them). +// 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 +27,7 @@ const crypto = require('crypto'); const Database = require('better-sqlite3'); const { numberConcepts } = require('../sqlite-v2/numbering'); const { buildIndexes } = require('./indexes'); +const { readMeta } = require('../../sqlite-v2/meta'); const SCHEMA_PATH = path.join(__dirname, 'schema.sql'); const FORMAT = 'tx-terminology/1'; @@ -140,7 +143,7 @@ class TerminologyBuilder { return this.systems.length; } - /** a behaviour setting (meta behaviour., a JSON value; tx/sqlite-v2/store.js BEHAVIOUR) */ + /** a behaviour setting (meta behaviour., a JSON value; tx/sqlite-v2/meta.js KEYS) */ setBehaviour(key, value) { this.meta.set(`behaviour.${key}`, JSON.stringify(value)); } @@ -499,9 +502,9 @@ 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) + 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 +524,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']) { @@ -594,10 +600,27 @@ 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: 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) { + readMeta(db.prepare('SELECT key, value FROM main.meta').raw().all(), file, { writer: true }); } -module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, analyze, externalIdValue }; +module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, finishFile, analyze, externalIdValue }; diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 1941df724..2a0e6ae6b 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -29,8 +29,10 @@ CREATE TABLE code_system ( -- 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. +-- values and defaults in tx/sqlite-v2/README.md "Meta"). `requires` (JSON list) names the features the +-- content uses that a reader must understand: a reader refuses a file that requires one it does not +-- know. 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 ( diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 994b4d44c..735ef229f 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -78,10 +78,43 @@ Index tables (rebuildable): | `ix_word` | the text-filter word index per language: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (Uint16 by concept id) | | `ix_text_display`, `ix_text_item` | FTS5 trigram indexes over displays and item texts (regex prefilter) | +## Meta + +`meta` is key -> text. One rule for every key: + +- `requires` (JSON list of distinct strings; absent: `[]`) names 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, and says which. A writer that adds something every reader must understand names a feature + here; nothing else makes an older reader refuse a file. +- A reader ignores a key it does not know. A key it knows with a malformed value is refused, with + the key and the value in the message, in every file. +- Each key has one meaning and a default (absent means the default). A reader obeys the file's + value; it has no rule of its own for a system that overrides the file or fills in for an absent key. + An importer writes the values its system needs. +- A builder checks every key it writes against its own list and refuses to finish a file with a key + it does not know (a typo is caught where it is made). `provenance.*` is free-form and never read. + +| key | value | default | meaning | +|---|---|---|---| +| `format` | `tx-terminology/1` | (required) | the format | +| `requires` | JSON list of feature names | `[]` | above | +| `languages` | JSON list of language tags | `[]` | the languages of the served system's items, in order of first appearance | +| `displayContexts` | JSON `{relations, preferred, use}` | none | the language relations that rank displays (SNOMED CT) | +| `moduleDependencies` | JSON list of `[module, target module, effective time, target effective time]` | `[]` | SNOMED CT module dependencies | +| `edition` | text | none | the SNOMED CT edition (module id) | +| `titles` | JSON object, language -> title | `{}` | the system's title per language (ICD-11) | +| `derived-by-importer` | JSON list of `{table, name}` | `[]` | index rows the importer writes (below) | +| `ix.ix_word.format` | text | none | the word index's rules (`text-match/1`); absent: no word index | +| `ix.ix_order..reached` | decimal integer | none | how many concepts a stored walk reaches | +| `behaviour.*` | JSON | per key | below | + +Informational keys a builder writes that no reader reads: `ix.ix_key.normalForm.stats` (SNOMED CT +normal forms written, failed, seconds). + ## Behaviour settings -`meta` keys `behaviour.`, JSON values. A key that is absent has its default. A reader refuses a -file with a key or value it does not know (the importers check the same at build). +`meta` keys `behaviour.`, JSON values. A key that is absent has its default; a malformed value is +refused (the builders check the same at build). | key | values | default | written by | |---|---|---|---| diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js new file mode 100644 index 000000000..45219d379 --- /dev/null +++ b/tx/sqlite-v2/meta.js @@ -0,0 +1,137 @@ +'use strict'; +// The meta table of a terminology file (tx-terminology/1; 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. +// - 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. +// - 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 "requires") */ +const KNOWN_FEATURES = Object.freeze(['identifier-text']); + +/** the features every file this builder writes requires */ +const WRITTEN_FEATURES = Object.freeze(['identifier-text']); + +/** the FHIR filter operators (behaviour.filters, property.filter_ops) */ +const FILTER_OPERATORS = Object.freeze(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'exists']); + +const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); +const isString = (v) => typeof v === 'string'; +const isStrings = (a) => Array.isArray(a) && a.every(isString); +const onlyKeys = (o, keys) => Object.keys(o).every((k) => keys.includes(k)); +const isBool = (v) => v === true || v === false; +const DECIMAL = /^(0|[1-9][0-9]*)$/; + +/** one entry of behaviour.filters: {code, operator: [FHIR filter operators, at least one], values?: [strings]} */ +const isFilterSpec = (f) => isPlainObject(f) && onlyKeys(f, ['code', 'operator', 'values']) && isString(f.code) + && isStrings(f.operator) && f.operator.length > 0 && f.operator.every((o) => FILTER_OPERATORS.includes(o)) + && (f.values === undefined || isStrings(f.values)); + +/** 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. + * The behaviour.* keys are README.md "Behaviour settings". + */ +const KEYS = Object.freeze({ + format: text((v) => v === FORMAT), + requires: json((v) => isStrings(v) && new Set(v).size === v.length, []), + // 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)), []), + // facts about indexes + 'ix.ix_word.format': text((v) => v !== '', null), + // behaviour settings + 'behaviour.grammar': json((v) => [null, 'snomed', 'icd11'].includes(v), null), + 'behaviour.filters': json((v) => v === null || (Array.isArray(v) && v.every(isFilterSpec)), null), + 'behaviour.expansionOrder': json((v) => ['ids', 'stored', 'stored-self-first'].includes(v), 'ids'), + 'behaviour.lookupName': json((v) => v === 'name' || v === 'title', 'name'), + 'behaviour.description': json((v) => v === 'name' || v === 'title', 'title'), + 'behaviour.versionAlgorithm': json((v) => v === null || isString(v), null), + 'behaviour.designationUses': json((v) => v === 'keep' || v === 'drop', 'keep'), + 'behaviour.distinctDesignationTexts': json(isBool, false), + 'behaviour.lookupSkipsMixedLinks': json(isBool, false), + 'behaviour.aliasProperty': json((v) => v === null || isString(v), null), + 'behaviour.aliasExtension': json((v) => v === null || isString(v), null), + 'behaviour.preferredForLanguage': json(isBool, false), + 'behaviour.aliasLiterals': json((v) => isPlainObject(v) && Object.values(v).every(isString), {}), +}); + +/** 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)], +]); + +/** keys a builder of this repository writes that no reader reads (informational) */ +const WRITER_KEYS = Object.freeze({ + // SNOMED CT normal forms written by the importer (sct-v2-common.js) + 'ix.ix_key.normalForm.stats': json(isPlainObject, null), +}); + +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; +} + +/** + * Check a file's meta and return the values of the keys this reader knows (defaults filled in for + * the behaviour and requires keys). Throws, naming key and value, on a malformed value of a + * known key, and on a required feature this reader does not know. + * @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[], behaviour: object, ignored: string[]}} + */ +function readMeta(meta, file, opts = {}) { + const name = typeof file === 'string' ? file : 'the file'; + const values = new Map(); + const ignored = []; + for (const [key, raw] of meta) { + if (isProvenance(key)) continue; + const spec = specOf(key) || (opts.writer ? WRITER_KEYS[key] : 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 requires = values.get('requires') || []; + 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(', ')})`); + } + const get = (key) => (values.has(key) ? values.get(key) : KEYS[key].default); + const behaviour = {}; + for (const key of Object.keys(KEYS)) if (key.startsWith('behaviour.')) behaviour[key.substring('behaviour.'.length)] = get(key); + return { + values, requires, ignored, + behaviour: Object.freeze(behaviour), + }; +} + +module.exports = { readMeta, KEYS, WRITER_KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, FILTER_OPERATORS, FORMAT }; diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 3e93d87f0..afd5dfa96 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -11,15 +11,17 @@ // identifier rows ix_by_subject holds); // - release facts from code_system and meta (default language, compositional, display contexts, // module dependencies, languages). -// How a server presents the system (where both servers that read these files would do the same) -// is in the file too: meta behaviour.* keys (BEHAVIOUR below; an unknown key or value is an error -// at open) and the catalog columns filter_ops and report. +// How a server presents the system (where every server that reads these files would do the same) +// is in the file too: meta behaviour.* keys (meta.js; each has one meaning and a default, and a +// malformed value is an error at open; an unknown meta key is ignored) and the catalog columns +// filter_ops and report. // // The stored sets (ix_set) are read in batches through loadSets, with the evaluation's working // set and counters; text search is text-index.js over the file's word index. const Database = require('better-sqlite3'); const { RoaringBitmap32 } = require('roaring'); +const { readMeta, FILTER_OPERATORS } = require('./meta'); const FORMAT = 'tx-terminology/1'; const USER_VERSION = 1; @@ -75,62 +77,15 @@ function setKey(kind, pid, value, vk = 0) { /** - * 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. + * A file's meta checked (meta.js readMeta: a malformed value of a known key, or a required feature + * this server does not know, is an error; an unknown key is ignored), and its behaviour settings + * (meta 'behaviour.', every key with its default filled in; README.md "Behaviour settings") */ -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'); +function readBehaviour(meta, file) { + return readMeta(meta, file).behaviour; } -const FILTER_OPS = new Set(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'exists']); + +const FILTER_OPS = new Set(FILTER_OPERATORS); const REPORT = new Set([null, 'named', 'always']); /** meta behaviour.* -> settings object (every key, defaults filled); throws on an unknown key or value */ @@ -381,7 +336,9 @@ class Store { this.activeCount = cs.active_count; this.lo = 1; this.hi = cs.concept_count; - this.behaviour = readBehaviour(this.meta, this.file); + const m = readMeta(this.meta, this.file); + this.requires = m.requires; + this.behaviour = m.behaviour; // a compositional system's expansions are never closed (post-coordinated expressions are codes) this.notClosed = cs.compositional === 1; this.defaultLanguage = cs.default_language || null; @@ -1131,4 +1088,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, readBehaviour, FORMAT, KIND, EMPTY, VK, setKey, registry, count, holdReadLock, primaryLang }; From 9f9cfbe9e20fc72365c07985cd9f56ea73027963 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:24:48 -0600 Subject: [PATCH 02/90] sqlite-v2: identifier.value declared TEXT; files require identifier-text With the column declared TEXT, SQLite stores every identifier value as text whatever the writer binds. The builder writes requires ["identifier-text"]; in such a file the reader binds identifier probes as text, lists passed through json_each included (an integer there does not match a text value). A file without the feature keeps the older typing. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-cases.test.js | 4 +-- tests/tx/sqlite-v2-format-round2.test.js | 41 ++++++++++++++++++++++++ tx/importers/sqlite-v2/builder.js | 4 ++- tx/importers/sqlite-v2/schema.sql | 6 ++-- tx/sqlite-v2/README.md | 6 +++- tx/sqlite-v2/store.js | 20 ++++++++---- 6 files changed, 69 insertions(+), 12 deletions(-) diff --git a/tests/tx/sqlite-v2-format-cases.test.js b/tests/tx/sqlite-v2-format-cases.test.js index 50f26af5d..a3153abe4 100644 --- a/tests/tx/sqlite-v2-format-cases.test.js +++ b/tests/tx/sqlite-v2-format-cases.test.js @@ -217,8 +217,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:'], diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index ad490e88f..f5247d9ec 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -110,3 +110,44 @@ describe('P1. meta: requires, known keys checked, unknown keys ignored', () => { }); }); + +describe('P2. identifier values are TEXT (requires identifier-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('the builder writes requires identifier-text; every stored value is text', () => { + const db = new Database(file, { readonly: true }); + try { + expect(JSON.parse(db.prepare("SELECT value FROM meta WHERE key = 'requires'").pluck().get())).toEqual(['identifier-text']); + 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.identifierText).toBe(true); + 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')]); + }); + }); + + test('without identifier-text a reader keeps the older typing (and an integer through json_each misses a text value)', () => { + const old = withMeta(file, { requires: null }); + withStore(old, (S) => { + expect(S.identifierText).toBe(false); + expect(S.subjectsOfIdentifiers(S.catalog.get('alias'), ['456'])).toEqual([]); + expect(S.subjectsOfIdentifiers(S.catalog.get('alias'), ['00123'])).toEqual([S.idOf('A')]); + }); + }); +}); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 998416d9f..fc3b86b4f 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -27,7 +27,7 @@ const crypto = require('crypto'); const Database = require('better-sqlite3'); const { numberConcepts } = require('../sqlite-v2/numbering'); const { buildIndexes } = require('./indexes'); -const { readMeta } = require('../../sqlite-v2/meta'); +const { readMeta, WRITTEN_FEATURES } = require('../../sqlite-v2/meta'); const SCHEMA_PATH = path.join(__dirname, 'schema.sql'); const FORMAT = 'tx-terminology/1'; @@ -504,6 +504,8 @@ class TerminologyBuilder { // 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); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 2a0e6ae6b..e2c713764 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -105,7 +105,9 @@ CREATE TABLE literal ( 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 @@ -177,7 +179,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), diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 735ef229f..1d3bcf88d 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -59,7 +59,7 @@ Fact tables: | `property`, `property_member` | the catalog; a union property's members | | `link` | subject, property, role group, target, active, seq (source order) | | `literal` | subject, property, role group, value, active | -| `identifier` | property (the scheme), value (INTEGER when a canonical decimal integer, else TEXT; compared as text), subject, `resolves`: 0 not a code; 1 an alias, accepted as a code and answered with the subject's own code (ICD-11 short codes); 2 a code in its own right, answered as written (NDC 11-digit forms). A concept code always wins over an identifier with the same value. A probe for codes that are identifiers says `resolves > 0` as well as `value = ?`: only then does SQLite use the partial index `identifier_code` (the readers' probes do); without it the probe scans every identifier row. The catalog's `by_subject` says which properties' rows are also read by subject (`ix_by_subject`) | +| `identifier` | property (the scheme), value (declared `TEXT`: every value is stored as text, whatever a writer binds; see `identifier-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 | @@ -86,6 +86,10 @@ Index tables (rebuildable): uses that a reader must understand. A reader refuses a file that requires a feature it does not know, and says which. A writer that adds something every reader must understand names a feature here; nothing else makes an older reader refuse a file. + + | feature | meaning | + |---|---| + | `identifier-text` | every `identifier.value` (and `ix_by_subject.value`) is text: the column is declared `TEXT`. A reader binds identifier probe values as text, lists passed through `json_each` included (an integer there does not match a text value). In a file without it, a canonical decimal integer may be stored as INTEGER and a reader probes with an INTEGER for such a value. Every file the builder writes requires it. | - A reader ignores a key it does not know. A key it knows with a malformed value is refused, with the key and the value in the message, in every file. - Each key has one meaning and a default (absent means the default). A reader obeys the file's diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index afd5dfa96..8dadf84fc 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -62,8 +62,9 @@ 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), or an identifier value of a file that does not require + * identifier-text, 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); @@ -338,6 +339,9 @@ class Store { this.hi = cs.concept_count; const m = readMeta(this.meta, this.file); this.requires = m.requires; + // identifier values are all text (identifier-text): probes bind text, lists through json_each + // included (an integer there would not match a text value); else the older typing + this.identifierText = m.requires.includes('identifier-text'); this.behaviour = m.behaviour; // a compositional system's expansions are never closed (post-coordinated expressions are codes) this.notClosed = cs.compositional === 1; @@ -451,6 +455,9 @@ class Store { /** the languages of the served system's items (meta, a release fact) */ languages() { return JSON.parse(this.meta.get('languages') || '[]'); } + /** an identifier value to probe with, typed as the file stores it */ + _idProbe(v) { return this.identifierText ? String(v) : idValue(v); } + /** the built-in answer order (ix_order rank / ids / walk), read array by array */ systemOrder(kind) { return require('./orders').storedOrder(this, kind); } @@ -609,7 +616,7 @@ class Store { identifierAsCode(value, stats) { const q = this.stmt(`SELECT ${this._rowCols}, i.resolves FROM main.identifier i JOIN main.concept c ON c.id = i.subject_id AND c.cs_id = ${this.csId} WHERE i.value = ? AND i.resolves > 0 ORDER BY i.resolves, i.property_id, i.subject_id LIMIT 1`); - const r = q.get(idValue(value)) || null; + const r = q.get(this._idProbe(value)) || null; if (stats) count(stats, this, q, r ? 1 : 0); return r; } @@ -985,8 +992,9 @@ 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); else a canonical integer is an INTEGER (json_each + // gives it as one), text otherwise + const vals = values.map((v) => (this.identifierText || idValue(v) === String(v) ? String(v) : Number(v))); const q = this.stmt(`SELECT DISTINCT subject_id FROM main.identifier WHERE property_id IN (SELECT value FROM json_each(?)) AND value IN (SELECT value FROM json_each(?)) ORDER BY 1`).pluck(); const r = q.all(JSON.stringify(pids), JSON.stringify(vals)); @@ -1003,7 +1011,7 @@ 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)); } conceptsWithScheme(schemeId) { From 65e37bededcece8046220926df74a82db3a6dad1 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:33:39 -0600 Subject: [PATCH 03/90] sqlite-v2 word index: the names selection as data, stemmers per language, little-endian counts meta ix.ix_word.names says which names the word index holds, and so which names text search reads: concept displays under a language, and items filtered by active, designation, excluded uses, concepts with a property, and an optional language. The importers state it (SNOMED CT, LOINC, RxNorm); the index builder builds from it and the reader's search names (stored or in-memory index, ranking reads) run from it, with no switch on the system. A file without the key uses the selection the format had for its system, from one table (LEGACY_NAMES); on the installed SNOMED CT, LOINC and RxNorm files it selects exactly the rows the earlier code did. meta ix.ix_word.stemmers names each language's stemmer (natural: or none). A language whose stemmer this reader does not have is searched with an index built in memory; the other languages keep the stored one. The counts row is written and read little-endian. Co-Authored-By: Claude --- tests/tx/sqlite-v2-engine.test.js | 29 ++- tests/tx/sqlite-v2-format-round2.test.js | 107 +++++++++ tx/importers/import-loinc-v2.module.js | 2 + tx/importers/import-rxnorm-v2.module.js | 2 + tx/importers/sct-v2-common.js | 3 + tx/importers/sqlite-v2/indexes.js | 38 +++- tx/importers/sqlite-v2/schema.sql | 9 +- tx/library/text-match.js | 51 +++-- tx/sqlite-v2/README.md | 51 ++++- tx/sqlite-v2/meta.js | 17 ++ tx/sqlite-v2/store.js | 13 +- tx/sqlite-v2/text-index.js | 266 ++++++++++++++++------- 12 files changed, 455 insertions(+), 133 deletions(-) diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index 44a260144..0107d0f60 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -633,10 +633,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 ix.ix_word.names): the display mode reads LOINC's, the + // designation mode SNOMED CT's + 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.setMeta('ix.ix_word.names', 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,18 +647,22 @@ 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', { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); + ts = build('text-desig.db', { items: { active: true, designations: true }, counts: true }); }); - 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']); + expect(ids(td.searchText('volumen', null, 'display', 'en'), td)).toEqual([]); + expect(ids(td.searchText('volumen', null, 'display', 'de'), td)).toEqual(['G']); + expect(ids(td.searchText('glucose', null, 'display', '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, 'display', 'en'), td)).toEqual(['H']); + expect(ids(td.searchText('blut', null, 'display', 'de'), td)).toEqual([]); }); test('designation mode: only designations in the language', () => { diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index f5247d9ec..64e391ecc 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -151,3 +151,110 @@ describe('P2. identifier values are TEXT (requires identifier-text)', () => { }); }); }); + +describe('P3. word index: the names selection as data, 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; B: two 'banana tree' syns, flagged; C: nothing + const rich = (names) => fixture((b, c) => { + b.setMeta('ix.ix_word.names', names); + const flag = b.property({ code: 'FLAG', shape: 'literal', fhirType: 'string' }); + b.literal(c.B, flag, 'N'); + 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' }); + }); + 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({ 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 of the served system in its own language (none: the default language, then en)', () => { + const got = names(rich({ 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'); + }); + + test('items.active, items.designations, items.excludeUses', () => { + expect(names(rich({ items: { active: true } })).map((r) => r[2])).not.toContain('withered tree'); + expect(names(rich({ items: { designations: true } })).map((r) => r[2])).not.toContain('a definition without use'); + const ex = names(rich({ items: { excludeUses: ['RELATED', 'not-a-use'] } })).map((r) => r[2]); + expect(ex).not.toContain('related wording'); + expect(ex).toContain('apple tree'); + }); + + test('items.conceptsWith: only the items of concepts with a row of that property; items.language: every item under it', () => { + expect(names(rich({ items: { conceptsWith: 'FLAG', language: 'en' } }))).toEqual([['B', 'en', 'banana tree'], ['B', 'en', 'banana tree']]); + expect(names(rich({ items: { conceptsWith: 'NO-SUCH-PROPERTY' } }))).toEqual([]); + expect(new Set(names(rich({ items: { language: 'fr' } })).map((r) => r[1]))).toEqual(new Set(['fr'])); + }); + + test('a file without ix.ix_word.names: none for a system the format had no selection for; the legacy one for SNOMED CT, LOINC, RxNorm', () => { + expect(names(withMeta(rich({ items: {} }), { 'ix.ix_word.names': null }))).toEqual([]); + expect(ti.LEGACY_NAMES['http://loinc.org']).toEqual({ display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); + const sct = fixture((b) => b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }), { uri: 'http://snomed.info/sct' }); + const legacy = withMeta(sct, { 'ix.ix_word.names': null }); + expect(names(legacy)).toEqual(names(sct)); + }); + + test('the index builder writes the selection, the stemmer of each language, and the counts row little-endian (2 * (N + 1) bytes)', () => { + const f = rich({ items: { active: true, designations: true }, counts: true }); + 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.names'))).toEqual({ items: { active: true, designations: true }, counts: true }); + expect(JSON.parse(meta('ix.ix_word.stemmers'))).toEqual({ de: stemmerName('de'), en: stemmerName('en') }); + expect(stemmerName('en')).toBe('natural:PorterStemmer'); + expect(stemmerName('xx')).toBe('none'); + 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 (the inactive syn and the definition are not names) + expect(Array.from(ti.countsFromLE(ti.countsToLE(Uint16Array.from([1, 258, 65535]))))).toEqual([1, 258, 65535]); + expect([...ti.countsToLE(Uint16Array.from([258]))]).toEqual([2, 1]); + } finally { db.close(); } + // without counts: no counts row + const g = rich({ 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({ items: { active: true, designations: true }, counts: true }); + // de named with a stemmer this server does not have; the stored de rows emptied to show they are not read + const g = withMeta(f, { 'ix.ix_word.stemmers': JSON.stringify({ de: 'snowball:german', en: stemmerName('en') }) }); + const w = new Database(g); + w.prepare("UPDATE ix_word SET ids = ? WHERE lang = 'de' AND word <> ''").run(Buffer.from(new (require('roaring').RoaringBitmap32)().serialize('portable'))); + w.prepare("UPDATE ix_word SET ids = ? WHERE lang = 'en' AND word = 'banana'").run(Buffer.from(new (require('roaring').RoaringBitmap32)().serialize('portable'))); + w.close(); + withStore(g, (S) => { + const index = ti.textIndexOf(S); + expect(index.memLangs).toEqual(new Set(['de'])); + const codes = (bm) => bm.toArray().map((id) => S.conceptRows([id]).get(id).code); + expect(codes(S.searchText('apfelbaum', null, 'designation', 'de'))).toEqual(['A']); + // en is read from the stored index (where banana was emptied above) + expect(codes(S.searchText('apple', null, 'designation', 'en'))).toEqual(['A']); + expect(codes(S.searchText('banana', null, 'designation', 'en'))).toEqual([]); + }); + // the file's own stemmers: the stored index for every language + withStore(f, (S) => expect(ti.textIndexOf(S)).toBeInstanceOf(ti.WordIndex)); + }); + + test('a malformed selection is refused', () => { + const f = rich({ items: {} }); + expect(() => openStore(withMeta(f, { 'ix.ix_word.names': '{"items": {"active": "yes"}}' }))).toThrow(/meta ix.ix_word.names = .* is not a value/); + expect(() => openStore(withMeta(f, { 'ix.ix_word.names': '{"scope": "snomed"}' }))).toThrow(/meta ix.ix_word.names = .* is not a value/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 653739bb6..7aca4ed11 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -181,6 +181,8 @@ function loincCodeSystem(b, version, description) { b.setBehaviour('lookupName', 'title'); b.setBehaviour('description', 'name'); b.setBehaviour('versionAlgorithm', 'natural'); + // text search reads the display (English) and every name but RELATEDNAMES2 + b.setMeta('ix.ix_word.names', { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); } /** @param {object} cfg { source, dest, version, overwrite, log, hierarchyArrays: 'auto' | 'always' | 'never' } */ diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 88cdcf8b4..f9578ab08 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -66,6 +66,8 @@ async function importRxNormV2(cfg) { b.setBehaviour('distinctDesignationTexts', true); b.setBehaviour('designationUses', 'drop'); b.setBehaviour('versionAlgorithm', 'date'); + // text search reads the atoms of the concepts in RXNCONSO (those with a SUPPRESS literal), as English + b.setMeta('ix.ix_word.names', { items: { conceptsWith: 'SUPPRESS', language: 'en' } }); // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships const EQ_IN = ['=', 'in']; diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 64ce70ca8..c5d77bcb6 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -178,6 +178,9 @@ class SnomedSink { b.setBehaviour('grammar', 'snomed'); b.setBehaviour('expansionOrder', 'stored-self-first'); b.setBehaviour('lookupSkipsMixedLinks', true); + // text search reads the active descriptions (and text definitions) in their own language, and + // ranks one-word filters by each concept's distinct-word count + b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }); b.setMeta('derived-by-importer', DERIVED); this.stats = { languageRows: 0, languageRowsSkipped: 0, descriptions: 0, relationships: 0, relationshipsSkipped: 0, concreteTypeLinks: 0, concreteValues: 0, identifiers: 0, refsetRows: 0, refsetRowsOnDescriptions: 0, diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index a51195987..97495beee 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -18,8 +18,12 @@ // 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_word the word index (tx/sqlite-v2/text-index.js rules) over the names meta +// ix.ix_word.names selects (the importer states it; it is kept across a +// rebuild), 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. +// A file without ix.ix_word.names gets no word index, unless it had one before +// the key existed: then the selection of tx/sqlite-v2/text-index.js LEGACY_NAMES // ix_key nothing generic (SNOMED normal forms are derived-by-importer) const Database = require('better-sqlite3'); @@ -64,6 +68,8 @@ function dropIndexes(db) { } const keepKeys = derived.map((d) => `ix.${d.table}.${d.name}.`); for (const k of db.prepare("SELECT key FROM meta WHERE key LIKE 'ix.%'").pluck().all()) { + // ix.ix_word.names is the importer's statement of what the word index holds: kept + if (k === 'ix.ix_word.names') continue; if (!keepKeys.some((p) => k.startsWith(p))) db.prepare('DELETE FROM meta WHERE key = ?').run(k); } } @@ -74,6 +80,14 @@ function dropIndexes(db) { */ function buildIndexes(db, opts = {}) { const time = opts.time || ((name, fn) => fn()); + // the names the word index holds: the importer's statement, else (a file built before the key + // existed that has a word index) the selection the format had for its system + const metaOf = (k) => db.prepare('SELECT value FROM main.meta WHERE key = ?').pluck().get(k); + let names = metaOf('ix.ix_word.names'); + if (names == null && metaOf('ix.ix_word.format') != null) { + const legacy = require('../../sqlite-v2/text-index').LEGACY_NAMES[db.prepare('SELECT uri FROM main.code_system WHERE served = 1').pluck().get()]; + if (legacy) names = JSON.stringify(legacy); + } 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(); @@ -94,18 +108,23 @@ function buildIndexes(db, opts = {}) { 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)) { + if (names != null) { + const setMeta = db.prepare('INSERT OR REPLACE INTO main.meta VALUES (?, ?)'); + setMeta.run('ix.ix_word.names', names); 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); + const byLang = computeTextIndexFrom((fn) => eachSearchName(store, fn), !!JSON.parse(names).counts, 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 @@ -290,8 +309,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 +320,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; } diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index e2c713764..2aa019aa3 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -188,10 +188,11 @@ 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 it holds +-- in 'ix.ix_word.names', each language's stemmer in 'ix.ix_word.stemmers'; README.md "Word index"): 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), where the names selection says counts. 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/library/text-match.js b/tx/library/text-match.js index 08a043a63..a8321313c 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/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 1d3bcf88d..309b5fcfd 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -75,7 +75,7 @@ Index tables (rebuildable): | `ix_by_subject` | identifier rows by subject (subject, property, value), for the properties with `by_subject = 1`: SNOMED CT alternate identifiers, aliases. The builder sets `by_subject = 1` on every identifier property unless the importer says otherwise; RxNorm's atom relationships (`AUI:*`, read only by value) are `by_subject = 0`. Every other identifier read goes by the primary key (property, value, subject) or `identifier_code` | | `ix_order` | per-concept arrays in 1,024-entry blocks: `rank`, `ids` (the system order), `walk` (the whole system in the built-in walk order; `ix.ix_order.walk.reached` in meta), `active` (walk restricted to active concepts, stored only where they are not a prefix of walk: LOINC), `hier_start` / `hier` (LOINC parent and child entries in main's order, where the parent links' seq does not give it) | | `ix_key` | text keys of nodes (SNOMED CT normal forms) | -| `ix_word` | the text-filter word index per language: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (Uint16 by concept id) | +| `ix_word` | the text-filter word index per language over the names `ix.ix_word.names` selects: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (below) | | `ix_text_display`, `ix_text_item` | FTS5 trigram indexes over displays and item texts (regex prefilter) | ## Meta @@ -109,6 +109,8 @@ Index tables (rebuildable): | `titles` | JSON object, language -> title | `{}` | the system's title per language (ICD-11) | | `derived-by-importer` | JSON list of `{table, name}` | `[]` | index rows the importer writes (below) | | `ix.ix_word.format` | text | none | the word index's rules (`text-match/1`); absent: no word index | +| `ix.ix_word.names` | JSON object | below | which names the word index holds, and so which names text search reads | +| `ix.ix_word.stemmers` | JSON object, language -> stemmer name | below | the stemmer that made each language's `stem` column | | `ix.ix_order..reached` | decimal integer | none | how many concepts a stored walk reaches | | `behaviour.*` | JSON | per key | below | @@ -146,6 +148,53 @@ and the relationships: `=`, `in`) and `report` (`named`: $lookup returns it only set `named` on `child`, `browserUrl` and `residual`, and `always` on `classificationCode` in MMS and ICF; NDC files `named` on `kind`). +## Word index + +`ix.ix_word.names` says which names the word index holds, and so which names a reader's text search +reads (the stored index or, where a reader does without it, its own built from the same names): + +```json +{"display": "en", "items": {"active": true, "designations": true, "excludeUses": ["RELATEDNAMES2"], "language": "en", "conceptsWith": "SUPPRESS"}, "counts": true} +``` + +- `display` (a language tag, optional): each concept's non-empty `concept.display`, under this + language. Absent: displays are not names. +- `items` (object, optional; absent: items are not names): the items of the served system + (`item.cs_id` = the served `cs_id`), filtered by `active` (bool, default false: only `active = 1`), + `designations` (bool, default false: only designations, `kind = 0 OR use_id IS NOT NULL`), + `excludeUses` (list of `item_use.code`, default `[]`: not the items with one of these uses), + `conceptsWith` (a property code, optional: only the items of concepts with a row of that property, + active or not, in the table its catalog shape says; a code not in the catalog selects nothing) and + `language` (a tag, optional: every item under it; absent: the item's own language, NULL -> + `code_system.default_language`, then `en`). +- `counts` (bool, default false): the row with word `''` holds per-concept distinct-word counts. + +Languages are compared by primary subtag. A value with any other field is malformed. The importers +write: + +| system | `ix.ix_word.names` | +|---|---| +| SNOMED CT | `{"items": {"active": true, "designations": true}, "counts": true}` | +| LOINC | `{"display": "en", "items": {"excludeUses": ["RELATEDNAMES2"]}}` | +| RxNorm | `{"items": {"conceptsWith": "SUPPRESS", "language": "en"}}` | + +A file without the key was written before it existed: a reader uses the selection above for the +file's system (SNOMED CT, LOINC, RxNorm; `LEGACY_NAMES` in `text-index.js`, the one table of systems +for this), and no names for any other. The index builder keeps the key across a rebuild, and writes +it from that table when it rebuilds such a file. + +`ix.ix_word.stemmers`: for each language of the word index, the stemmer that made its `stem` column, +an open string: `none` (a word is its own stem), `natural:` (a stemmer class of the `natural` +package: `natural:PorterStemmer` for en, `natural:PorterStemmerDe`, `...Es`, `...Fa`, `...Fr`, +`natural:StemmerId`, `...It`, `...No` for nb / nn / no, `...Nl`, `...Pt`, `...Ru`, `...Sv`, `...Uk`), +`snowball:` (a Snowball algorithm: `snowball:german`, ...). A reader that cannot +reproduce a language's stemmer searches that language without the stored index (the JS reader +builds the names of that language in memory on the first search); other languages keep using it. A +file without the key was written with the stemmers of `tx/library/text-match.js`. + +The counts row: for each concept id 0..N an unsigned 16-bit count, little-endian, `2 * (N + 1)` +bytes, written and read little-endian on every host. + ## How each terminology maps | source | becomes | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 45219d379..9ede54d86 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -35,6 +35,21 @@ const isFilterSpec = (f) => isPlainObject(f) && onlyKeys(f, ['code', 'operator', && isStrings(f.operator) && f.operator.length > 0 && f.operator.every((o) => FILTER_OPERATORS.includes(o)) && (f.values === undefined || isStrings(f.values)); +/** + * ix.ix_word.names: which names the word index holds, and so which names text search reads + * (README.md "Word index"): {display?: tag, items?: {active?, designations?, excludeUses?, + * conceptsWith?, language?}, counts?} + */ +const isNames = (v) => isPlainObject(v) && onlyKeys(v, ['display', 'items', 'counts']) + && (v.display === undefined || (isString(v.display) && v.display !== '')) + && (v.counts === undefined || isBool(v.counts)) + && (v.items === undefined || (isPlainObject(v.items) && onlyKeys(v.items, ['active', 'designations', 'excludeUses', 'conceptsWith', 'language']) + && (v.items.active === undefined || isBool(v.items.active)) + && (v.items.designations === undefined || isBool(v.items.designations)) + && (v.items.excludeUses === undefined || isStrings(v.items.excludeUses)) + && (v.items.conceptsWith === undefined || (isString(v.items.conceptsWith) && v.items.conceptsWith !== '')) + && (v.items.language === undefined || (isString(v.items.language) && v.items.language !== '')))); + /** 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 }); @@ -56,6 +71,8 @@ const KEYS = Object.freeze({ 'derived-by-importer': json((v) => Array.isArray(v) && v.every((d) => isPlainObject(d) && isString(d.table) && isString(d.name)), []), // 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), + 'ix.ix_word.names': json(isNames, null), // behaviour settings 'behaviour.grammar': json((v) => [null, 'snomed', 'icd11'].includes(v), null), 'behaviour.filters': json((v) => v === null || (Array.isArray(v) && v.every(isFilterSpec)), null), diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 8dadf84fc..5eefecfd2 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -1066,16 +1066,15 @@ 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() { diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js index 146ed8bf3..ae484678f 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -27,20 +27,23 @@ // in the built-in providers, which let other work run while they rank (bestRanks). // anything else (cs-cs.js searchFilter): see contentTextSearch. // -// Which concepts have a name with a word is a word index, one per language (primary subtag) of -// the names: ix_word(lang, word, stem, ids), every word (text-match words: folded letters, marks -// and digits) with its stem in that language and the concepts that have it (portable Roaring -// bitmap of concept ids), and for SNOMED CT the row with word '', the distinct words of each -// concept (Uint16 by concept id). A filter word matches the words it is the start of and those +// Which names a search reads is file data: meta ix.ix_word.names (searchNamesSelection; README.md +// "Word index"), the same selection for the stored index and one built in memory. 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 the selection says counts 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; a filter of several words is then checked // name by name (TextQuery.nameMatches), as every word has to be in one name. // // The index builder writes it (tx/importers/sqlite-v2/indexes.js), with meta 'ix.ix_word.format' -// naming the rules it was made by (FORMAT); a file without one made by these rules has it built in -// memory on the first search, as the built-in providers do. +// 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, as the built-in +// providers do; so does each language whose stemmer is not this server's (usableLanguages). const { RoaringBitmap32 } = require('roaring'); -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; @@ -61,78 +64,125 @@ function primaryLanguage(code, defLang) { // ---- 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 selection a file's word index holds, and so the names its text search reads, for a file whose + * meta has no ix.ix_word.names (every file written before the key): the selection the format had for + * that file's system. The one table of systems for this; a file that states its names never reads it. + * SNOMED CT active designations of the served system, in their own language, with the counts row + * LOINC the displays (as en) and every item of the served system but RELATEDNAMES2 + * RxNorm the items of the concepts with a SUPPRESS literal (the concepts in RXNCONSO), as en + */ +const LEGACY_NAMES = Object.freeze({ + 'http://snomed.info/sct': Object.freeze({ items: { active: true, designations: true }, counts: true }), + 'http://loinc.org': Object.freeze({ display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }), + 'http://www.nlm.nih.gov/research/umls/rxnorm': Object.freeze({ items: { conceptsWith: 'SUPPRESS', language: 'en' } }), +}); + +/** + * The names a file's text search reads (meta ix.ix_word.names, README.md "Word index"), or null for + * none: the file's own statement, else LEGACY_NAMES for its system + */ +function searchNamesSelection(store) { + if (store._names === undefined) { + const own = store.meta.get('ix.ix_word.names'); + store._names = own != null ? JSON.parse(own) : (LEGACY_NAMES[store.system] || null); + } + return store._names; +} + +/** + * The selection as SQL over item and concept: { display: [lang] | null, items: {where, params, + * lang} | null, conceptsWith: a bitmap of the concepts selected | null } + */ +function selectionPlan(store, names) { + if (store._namesPlan && store._namesPlan.names === names) return store._namesPlan; + const plan = { names, display: null, items: null, concepts: 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(',')}))`); + plan.items = { where: where.join(' AND '), lang: it.language ? primaryLanguage(it.language, 'en') : null }; + if (it.conceptsWith) plan.concepts = conceptsWithProperty(store, it.conceptsWith); } - 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; +/** the concepts with a row (active or not) of a property, as its catalog shape says; none if it is not in the catalog */ +function conceptsWithProperty(store, code) { + const bm = new RoaringBitmap32(); + const d = store.catalog.get(code); + if (!d) return bm; + const stored = (x) => (x.members ? x.members.flatMap(stored) : [x]); + for (const p of stored(d)) { + const tables = p.shape === 'link' ? ['link'] : p.shape === 'literal' ? ['literal'] : p.shape === 'both' ? ['link', 'literal'] + : p.shape === 'identifier' ? ['identifier'] : p.shape === 'record' ? ['record'] : []; + for (const t of tables) { + const col = t === 'record' ? 'relation_id' : 'property_id'; + bm.addMany(store.db.prepare(`SELECT DISTINCT subject_id FROM main.${t} WHERE ${col} = ? AND subject_id <= ?`).pluck().all(p.id, store.hi)); + } + } + return bm; +} + +/** + * 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 { + if (plan.concepts && !plan.concepts.has(id)) continue; + 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) { + const some = plan.concepts ? JSON.stringify(ids.filter((id) => plan.concepts.has(id))) : j; + 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(some)) { 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 +205,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 +233,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 +315,54 @@ 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) is searched without the stored index. A file without + * the key was written by this builder before it existed, with this server's stemmers. + */ +function usableLanguages(store, stored) { + const raw = store.meta.get('ix.ix_word.stemmers'); + if (raw == null) return new Set(stored.langs); + 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 names = searchNamesSelection(store); + const counting = !!(names && names.counts); + 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 +377,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,17 +388,17 @@ 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) { +function* inOneName(store, bm, q, lang, stats) { const ok = new RoaringBitmap32(); - yield* namesOfG(store, dialect, bm.toArray(), stats, (id, l, term) => { + yield* namesOfG(store, bm.toArray(), stats, (id, l, term) => { if (l === lang && !ok.has(id) && q.nameMatches(term, lang)) ok.add(id); }); return ok; @@ -420,7 +522,7 @@ function* sctTextSearchG(store, text, lang, ordinal, stats = null) { const active = store.active(stats); let ranked = []; if (tokens.length) { - const index = textIndexOf(store, 'snomed'); + const index = textIndexOf(store); const bm = (yield* candidates(index, lang, tokens, stats)).andInPlace(active); const kept = Array.from(bm.toUint32Array()).sort((a, b) => ordinal(a) - ordinal(b)); yield; @@ -437,7 +539,7 @@ 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) => { + yield* namesOfG(store, ids, stats, (id, l, term) => { if (l !== lang) return; const r = q.nameRank(term, lang); if (r > best.get(id)) best.set(id, r); @@ -476,7 +578,7 @@ function* rankSct(store, kept, ordinal, counts, q, lang, several, stats) { function sctTextLanguages(store) { if (!store._textLangs) { const idx = store.textIndex(); - const stored = idx ? idx.languages() : null; + const stored = idx && searchNamesSelection(store) && searchNamesSelection(store).counts ? idx.languages() : null; if (stored) store._textLangs = new Set(stored); else { const defLang = store.defaultLanguage || 'en'; @@ -522,13 +624,13 @@ function* loincTextSearchG(store, text, lang, ordinal, stats = null) { for (const id of codes) rank.set(id, q.codeRank(codeRows.get(id).code)); const tokens = q.tokens(lang); if (tokens.length) { - const index = textIndexOf(store, 'loinc'); + 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) => { + yield* namesOfG(store, 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); @@ -557,12 +659,12 @@ function* rxTextSearchG(store, text, eligible, stats = null) { 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); + bm = (yield* candidates(textIndexOf(store), 'en', tokens, stats)).andInPlace(eligible); + if (tokens.length > 1 && bm.size) bm = yield* inOneName(store, 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) => { + yield* namesOfG(store, bm.toArray(), stats, (id, l, term) => { const r = q.nameRank(indexedName(term), 'en'); if (r > (best.get(id) ?? 0)) best.set(id, r); }); @@ -664,8 +766,8 @@ const rxTextSearch = (...a) => runSync(rxTextSearchG(...a)); const genericTextSearch = (...a) => runSync(genericTextSearchG(...a)); module.exports = { - FORMAT, WordIndex, blockConcepts, indexed, eachSearchName, searchNamesOf, rxSearchable, - computeTextIndexFrom, textIndexOf, primaryLanguage, + FORMAT, WordIndex, blockConcepts, eachSearchName, searchNamesOf, searchNamesSelection, LEGACY_NAMES, rxSearchable, + computeTextIndexFrom, textIndexOf, primaryLanguage, countsFromLE, countsToLE, usableLanguages, sctTextSearch, sctTextLanguages, loincTextSearch, rxTextSearch, genericTextSearch, rateConcepts, sctTextSearchG, loincTextSearchG, rxTextSearchG, genericTextSearchG }; From c3623d94c694bd11dc2b8daaa4d152bc4b938e2a Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:39:04 -0600 Subject: [PATCH 04/90] sqlite-v2: behaviour and order keys are obeyed from the file Each key has one meaning and a default, and the reader obeys the file's value with no rule of its own for a system on top: - designationUses and preferredForLanguage apply to every designation path (SNOMED CT, LOINC, RxNorm and the generic one), not only RxNorm's. - lookupName and description choose code_system.name or .title (a title of the requested language from meta titles first) for every file; the SNOMED CT provider no longer overrides them, nor versionAlgorithm, which the SNOMED CT importer now writes ("url"). - meta linkOrder orders a concept's links in the generic $lookup (property, seq, property-seq, target-int); meta searchTieBreak "rank" orders text-search ties by the stored rank. Both are checked strictly. - aliasProperty, aliasExtension and aliasLiterals (identifier-aliased codes) are not implemented by this reader: a file that sets one is refused rather than answered wrongly. Co-Authored-By: Claude --- tests/tx/sqlite-v2-builder.test.js | 6 +- tests/tx/sqlite-v2-format-round2.test.js | 119 +++++++++++++++++++++++ tx/importers/sct-v2-common.js | 2 + tx/sqlite-v2/README.md | 23 ++++- tx/sqlite-v2/meta.js | 8 +- tx/sqlite-v2/provider.js | 67 ++++++++++--- tx/sqlite-v2/snomed.js | 8 +- tx/sqlite-v2/store.js | 31 +++++- tx/sqlite-v2/text-index.js | 16 ++- 9 files changed, 248 insertions(+), 32 deletions(-) diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js index e2e218246..69a79e6d8 100644 --- a/tests/tx/sqlite-v2-builder.test.js +++ b/tests/tx/sqlite-v2-builder.test.js @@ -371,12 +371,14 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check 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/); + // identifier-aliased codes: this reader does not implement them, and refuses a file that sets them + bad('behaviour.aliasLiterals', '{"code-type": "11-digit", "synonym": "{code}"}', /behaviour.aliasLiterals is set .* which this server does not implement/); + bad('behaviour.aliasProperty', '"classificationCode"', /behaviour.aliasProperty is set/); 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.colour', '"red"'); 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(); @@ -384,7 +386,7 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check try { expect(G.behaviour.preferredForLanguage).toBe(true); expect(G.behaviour.colour).toBeUndefined(); - expect(G.behaviour.aliasLiterals).toEqual({ 'code-type': '11-digit', synonym: '{code}' }); + expect(G.behaviour.aliasLiterals).toEqual({}); expect(G.behaviour.filters.map((f) => f.code)).toEqual(['inactive', 'category']); } finally { G.close(); } const b = new TerminologyBuilder(path.join(dir, 'never.db'), { overwrite: true, importer: 'test' }); diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 64e391ecc..b7cc32952 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -258,3 +258,122 @@ describe('P3. word index: the names selection as data, stemmers per language, li expect(() => openStore(withMeta(f, { 'ix.ix_word.names': '{"scope": "snomed"}' }))).toThrow(/meta ix.ix_word.names = .* is not a value/); }); }); + +describe('P4. behaviour and order keys: the file\'s value obeyed, absent = the default', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { Designations } = require('../../tx/library/designations'); + const { writeOrderArray } = require('../../tx/importers/sqlite-v2/indexes'); + let op, base; + const factories = []; + beforeAll(async () => { + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + base = fixture((b, c) => { + const site = b.property({ code: 'site', shape: 'link' }); + const area = b.property({ code: 'area', shape: 'link' }); + // 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.item(c.C, { language: 'en', text: 'cherry preferred', preferred: true }); + }); + }); + afterAll(() => { for (const f of factories) f.store.close(); }); + const provider = async (file) => { + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + factories.push(f); + return { f, p: await f.build(op, []) }; + }; + const designations = async (p, code) => { + const ds = new Designations(op.i18n.languageDefinitions); + await p.designations((await p.locate(code)).context, ds); + return ds.designations.filter((d) => !d.isDisplay && d.value !== `display ${code}`).map((d) => [d.value, d.use ? d.use.code : null]); + }; + const lookup = async (p, code) => { + const params = []; + await p.extendLookup((await p.locate(code)).context, [], params); + return params.map((x) => x.part.find((y) => y.name === 'code').valueCode + '=' + (x.part.find((y) => y.name === 'value').valueCode || x.part.find((y) => y.name === 'value').valueString)); + }; + + test('defaults: description the title, lookupName the name, versionAlgorithm none, every use kept, every text', async () => { + const { f, p } = await provider(base); + expect(f.description()).toBe('The Example System'); + expect(p.lookupName()).toBe('Example'); + expect(p.versionAlgorithm()).toBeNull(); + expect(await designations(p, 'B')).toEqual([['banana tree', 'syn'], ['banana tree', 'syn']]); + expect(await designations(p, 'C')).toEqual([['cherry preferred', null]]); + expect(f.engine._order).toBeFalsy(); + }); + + test('lookupName, description, versionAlgorithm', async () => { + const { f, p } = await provider(withMeta(base, { 'behaviour.lookupName': '"title"', 'behaviour.description': '"name"', 'behaviour.versionAlgorithm': '"semver"' })); + expect(f.description()).toBe('Example'); + expect(p.lookupName()).toBe('The Example System'); + expect(p.versionAlgorithm()).toBe('semver'); + // with meta titles: the title of the first requested language that has one + const t = await provider(withMeta(base, { 'behaviour.lookupName': '"title"', titles: '{"de": "Das Beispiel"}' })); + expect(t.p.lookupName({ languages: [{ code: 'fr' }, { code: 'de-AT' }] })).toBe('Das Beispiel'); + expect(t.p.lookupName({ languages: [{ code: 'fr' }] })).toBe('The Example System'); + }); + + test('designationUses drop, distinctDesignationTexts, preferredForLanguage', async () => { + expect(await designations((await provider(withMeta(base, { 'behaviour.designationUses': '"drop"' }))).p, 'B')).toEqual([['banana tree', null], ['banana tree', null]]); + expect(await designations((await provider(withMeta(base, { 'behaviour.distinctDesignationTexts': 'true' }))).p, 'B')).toEqual([['banana tree', 'syn']]); + expect(await designations((await provider(withMeta(base, { 'behaviour.preferredForLanguage': 'true' }))).p, 'C')).toEqual([['cherry preferred', 'preferredForLanguage']]); + }); + + test('expansionOrder: stored lists in ix_order rank; ids (the default) in concept id order', async () => { + const stored = withMeta(base, { 'behaviour.expansionOrder': '"stored"' }); + const w = new Database(stored); + const codes = w.prepare('SELECT id, code FROM concept ORDER BY code DESC').raw().all(); + const n = codes.length; + const ids = new Uint32Array(n + 1), rank = new Uint32Array(n + 1); + codes.forEach(([id], i) => { ids[i] = id; rank[id] = i; }); + ids[n] = 0; rank[0] = n; + writeOrderArray(w, 'rank', rank); + writeOrderArray(w, 'ids', ids); + w.close(); + const { f } = await provider(stored); + expect(f.engine._order).toBeTruthy(); + const listed = f.engine.ordered({ t: 'all' }).map((id) => f.store.conceptRows([id]).get(id).code); + expect(listed).toEqual(['root', 'X', 'C', 'B', 'A']); + }); + + test('linkOrder: property (default), seq, property-seq, target-int; a value it does not know is refused', async () => { + const order = async (v) => (await lookup((await provider(v ? withMeta(base, { linkOrder: v }) : base)).p, 'A')).filter((x) => !x.startsWith('colour') && !x.startsWith('parent')); + // property ids: parent 1, colour 2, site 3, area 4 + expect(await order(null)).toEqual(['site=B', 'site=C', 'site=root', 'area=B']); + expect(await order('property')).toEqual(['site=B', 'site=C', 'site=root', 'area=B']); + expect(await order('seq')).toEqual(['site=C', 'area=B', 'site=root', 'site=B']); + expect(await order('property-seq')).toEqual(['site=C', 'site=root', 'site=B', 'area=B']); + expect(await order('target-int')).toEqual(['site=C', 'area=B', 'site=root', 'site=B']); + expect(() => openStore(withMeta(base, { linkOrder: 'random' }))).toThrow(/meta linkOrder = random is not a value/); + }); + + test('searchTieBreak rank: hits of equal score in the stored rank order', async () => { + const f = withMeta(base, { searchTieBreak: 'rank' }); + const w = new Database(f); + // rank: B before A (both match "tree" equally) + const id = (c) => w.prepare('SELECT id FROM concept WHERE code = ?').pluck().get(c); + const n = w.prepare('SELECT count(*) FROM concept').pluck().get(); + const order = ['B', 'A', 'C', 'X', 'root'].map(id); + const ids = new Uint32Array(n + 1), rank = new Uint32Array(n + 1); + order.forEach((x, i) => { ids[i] = x; rank[x] = i; }); + writeOrderArray(w, 'rank', rank); + writeOrderArray(w, 'ids', ids); + w.close(); + const codes = (S, ids2) => Array.from(ids2).map((x) => S.conceptRows([x]).get(x).code); + const gen = require('../../tx/sqlite-v2/text-index').genericTextSearch; + withStore(base, (S) => expect(codes(S, gen(S, 'tree', 'en', 'en').ids)).toEqual(['A', 'B'])); + withStore(f, (S) => expect(codes(S, gen(S, 'tree', 'en', 'en').ids)).toEqual(['B', 'A'])); + }); + + test('aliasProperty, aliasExtension, aliasLiterals: this reader does not implement them and refuses a file that sets one', () => { + expect(() => openStore(withMeta(base, { 'behaviour.aliasExtension': '"http://example.org/ext"' }))).toThrow(/behaviour.aliasExtension is set .* does not implement/); + expect(() => openStore(withMeta(base, { 'behaviour.aliasLiterals': '{"kind": "{code}"}' }))).toThrow(/behaviour.aliasLiterals is set/); + withStore(withMeta(base, { 'behaviour.aliasLiterals': '{}', 'behaviour.aliasProperty': 'null' }), (S) => expect(S.behaviour.aliasLiterals).toEqual({})); + }); +}); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index c5d77bcb6..8ec04bc27 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -178,6 +178,8 @@ class SnomedSink { b.setBehaviour('grammar', 'snomed'); b.setBehaviour('expansionOrder', 'stored-self-first'); b.setBehaviour('lookupSkipsMixedLinks', true); + // versions are URIs (http://snomed.info/sct//version/) + b.setBehaviour('versionAlgorithm', 'url'); // text search reads the active descriptions (and text definitions) in their own language, and // ranks one-word filters by each concept's distinct-word count b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 309b5fcfd..1ba4116b4 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -126,13 +126,13 @@ refused (the builders check the same at build). |---|---|---|---| | `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"` | +| `lookupName` | `"name"`, `"title"` | `"name"` | the name `$lookup` reports: `code_system.name` (no name: the system URI), or the title (below; no title: the name). LOINC `"title"` | +| `description` | `"name"`, `"title"` | `"title"` | the description a server gives the code system (its catalog entry): `code_system.title` (no title: the name), or `code_system.name`. LOINC `"name"` | +| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm, used to match a requested version. SNOMED CT `"url"`, LOINC `"natural"`, RxNorm `"date"` | +| `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | | `lookupSkipsMixedLinks` | `true`, `false` | `false` | SNOMED CT `true`: a `both` attribute's links are not read where no property is named (main keeps one value kind per attribute) | -| `aliasProperty` | a property code, `null` | `null` | ICD-11 MMS and ICF files `"classificationCode"`: $validate-code of a code written in its canonical form also returns its alias (an identifier with `resolves = 1`) as an output parameter of this name | +| `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. The JS reader does not implement identifier aliases and refuses a file that sets this, `aliasExtension` or `aliasLiterals` | | `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 | @@ -142,6 +142,19 @@ Release facts in `meta` that a reader also presents: `titles` (JSON object, lang 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`. +## Order + +Two plain-text meta keys say how a reader orders what no rule of its own lists: + +| key | values | default | meaning | +|---|---|---|---| +| `linkOrder` | `property`, `seq`, `property-seq`, `target-int` | `property` | the order of a concept's links in `$lookup`: `property` by property id, role group, target code; `seq` by `link.seq` (none: 0), then property, group, target code; `property-seq` by property, `link.seq`, target code; `target-int` by the target code as a number, `link.seq`, property, target code. Codes compare as binary text. ICD-11 files `property-seq`, OMOP `target-int`, LOINC `seq` | +| `searchTieBreak` | `rank` | none | `rank`: text-search hits of equal score in the stored order (`ix_order` `rank`; by concept id where there is none); absent: the reader's own order for ties. ICD-11 files `rank` | + +The JS reader obeys `linkOrder` in the `$lookup` of a system with no adapter of its own; its LOINC +and RxNorm adapters list `$lookup` properties in the order of the providers they follow (their +property lists, `dialects.js` / `provider.js`), which no value of the key describes. + 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 diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 9ede54d86..cff5c6fad 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -73,6 +73,9 @@ const KEYS = Object.freeze({ '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), 'ix.ix_word.names': json(isNames, null), + // order (README.md "Order"): plain text values + linkOrder: text((v) => ['property', 'seq', 'property-seq', 'target-int'].includes(v), 'property'), + searchTieBreak: text((v) => v === 'rank', null), // behaviour settings 'behaviour.grammar': json((v) => [null, 'snomed', 'icd11'].includes(v), null), 'behaviour.filters': json((v) => v === null || (Array.isArray(v) && v.every(isFilterSpec)), null), @@ -116,7 +119,8 @@ function specOf(key) { * @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[], behaviour: object, ignored: string[]}} + * @returns {{values: Map, requires: string[], behaviour: object, linkOrder: string, + * searchTieBreak: string|null, ignored: string[]}} */ function readMeta(meta, file, opts = {}) { const name = typeof file === 'string' ? file : 'the file'; @@ -148,6 +152,8 @@ function readMeta(meta, file, opts = {}) { return { values, requires, ignored, behaviour: Object.freeze(behaviour), + linkOrder: get('linkOrder'), + searchTieBreak: get('searchTieBreak'), }; } diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 0b4e03183..ced6c5e9f 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -20,6 +20,7 @@ const { openStore, KIND } = require('./store'); const { Engine } = require('./engine/engine'); const { Compiler, FilterError } = require('./engine/compile'); const { dialectFor, LOINC, RXNORM } = require('./dialects'); +const { DesignationUse } = require('../library/designations'); const { SupplementLayers } = require('./layers'); const { HIER_CHILD } = require('./orders'); const { RoaringBitmap32 } = require('roaring'); @@ -96,7 +97,7 @@ 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(); } /** @@ -477,27 +478,37 @@ class SqliteV2Provider extends BaseCSServices { 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()); + displays.addDesignation(false, 'active', d.language, this._useOf(d), 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 }); + // upstream: the display is the first non-SY atom; every other atom is a designation 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); + displays.addDesignation(false, 'active', 'en-US', this._useOf(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); + displays.addDesignation(false, d.active ? 'active' : 'inactive', d.language, this._useOf(d), d.term); } } this._listSupplementDesignations(c.code, displays); } + /** + * A designation's use as it is reported (map: the stored use -> the reported one): none where + * the file says so (behaviour.designationUses 'drop'); for a preferred item with no use, + * preferredForLanguage where the file says so (behaviour.preferredForLanguage) + */ + _useOf(d, map = (u) => ({ system: u.system, code: u.code, display: u.display })) { + const b = this.store.behaviour; + if (b.designationUses === 'drop') return null; + if (d.use) return map(d.use); + return b.preferredForLanguage && d.preferred ? { ...DesignationUse.DISPLAY } : null; + } + /** the display as the one designation, as each dialect adds it, plus supplement designations */ _displayOnly(c, displays) { const d = (c.row && c.row.display) || ''; @@ -819,6 +830,7 @@ class SqliteV2Provider extends BaseCSServices { const S = this.store; const links = S.linksFrom([c.id], null, true, this._stats()); const rows = this._targetDisplays(links.map((l) => l.t)); + sortLinks(links, S.linkOrder, (id) => (rows.get(id) || {}).code); for (const l of links) { const p = S.propsById.get(l.p); const t = rows.get(l.t); @@ -1280,6 +1292,26 @@ class SqliteV2Provider extends BaseCSServices { /** the property definitions a file reports (data built at load) */ const NO_PROPERTY_DEFINITIONS = new Set(['snomed', 'loinc', 'rxnorm']); +/** + * A concept's links in the order meta linkOrder names (README.md "Order"): 'property' (by property, + * group, target code), 'seq' (link.seq, then property, group, target code), 'property-seq' (by + * property, link.seq, target code), 'target-int' (target code as a number, link.seq, property, + * target code). A link with no seq counts as 0; codes compare as binary text. + */ +function sortLinks(links, kind, codeOf) { + const txt = (a, b) => { const x = String(codeOf(a.t) ?? ''), y = String(codeOf(b.t) ?? ''); return x < y ? -1 : x > y ? 1 : 0; }; + const seq = (a, b) => (a.q ?? 0) - (b.q ?? 0); + const prop = (a, b) => a.p - b.p || a.g - b.g; + const int = (a, b) => { const x = Number.parseInt(codeOf(a.t), 10), y = Number.parseInt(codeOf(b.t), 10); return (Number.isNaN(x) ? 0 : x) - (Number.isNaN(y) ? 0 : y); }; + const cmp = { + property: (a, b) => prop(a, b) || txt(a, b), + seq: (a, b) => seq(a, b) || prop(a, b) || txt(a, b), + 'property-seq': (a, b) => a.p - b.p || seq(a, b) || txt(a, b), + 'target-int': (a, b) => int(a, b) || seq(a, b) || a.p - b.p || txt(a, b), + }[kind]; + return links.sort(cmp); +} + 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; @@ -1375,10 +1407,23 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { 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(); } + // behaviour.description / lookupName: code_system.name or code_system.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) { + const primary = (l) => String(l || '').toLowerCase().split('-')[0]; + 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(); + } + description() { return this.store.behaviour.description === 'name' ? this._csName() : this._csTitle(); } + lookupName(langs = null) { return this.store.behaviour.lookupName === 'title' ? this._csTitle(langs) : this._csName(); } defLang() { return 'en'; } /** * RxNorm: the concepts in RXNCONSO, as cs-rxnorm.js counts them (its totalCodeCount), not those diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 652ccfdaf..38989a79c 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -61,9 +61,6 @@ 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; } @@ -149,7 +146,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); @@ -676,9 +673,6 @@ class SnomedV2Factory extends SqliteV2Factory { 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(); diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 5eefecfd2..c7280d965 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -343,6 +343,16 @@ class Store { // included (an integer there would not match a text value); else the older typing this.identifierText = m.requires.includes('identifier-text'); this.behaviour = m.behaviour; + // the order of a concept's links where no rule of the system's adapter lists them ($lookup), and + // how text-search hits of equal score are ordered (null: each search's own order) + this.linkOrder = m.linkOrder; + this.searchTieBreak = m.searchTieBreak; + // identifier-aliased codes (behaviour.aliasProperty, aliasExtension, aliasLiterals): this server + // does not implement them, and would answer such a file's codes wrongly + for (const k of ['aliasProperty', 'aliasExtension']) { + if (m.behaviour[k] !== null) throw new Error(`${this.file}: behaviour.${k} is set (identifier-aliased codes), which this server does not implement`); + } + if (Object.keys(m.behaviour.aliasLiterals).length) throw new Error(`${this.file}: behaviour.aliasLiterals is set (identifier-aliased codes), which this server does not implement`); // a compositional system's expansions are never closed (post-coordinated expressions are codes) this.notClosed = cs.compositional === 1; this.defaultLanguage = cs.default_language || null; @@ -455,6 +465,21 @@ class Store { /** 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 meta searchTieBreak + * 'rank'; 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('stored'); + this._rankOrdinal = (id) => order.rank[id]; + } else this._rankOrdinal = (id) => id; + } + return this._rankOrdinal; + } + /** an identifier value to probe with, typed as the file stores it */ _idProbe(v) { return this.identifierText ? String(v) : idValue(v); } @@ -792,7 +817,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) */ @@ -803,11 +828,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); } diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js index ae484678f..ab752d972 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -516,6 +516,8 @@ function sctCodeMatches(store, q, active, stats) { * @returns {{bm: RoaringBitmap32, ids: Uint32Array}} active matches; ids best first */ function* sctTextSearchG(store, text, lang, ordinal, stats = null) { + // meta searchTieBreak 'rank': ties in the stored rank order + if (store.searchTieBreak === 'rank') ordinal = store.rankOrdinal(); return yield* cached(store, 'sct\u0000' + lang + '\u0000' + text, function* () { const q = new TextQuery(text); const tokens = q.tokens(lang); @@ -616,6 +618,8 @@ function rxSearchable(store, stats) { * @returns {{bm: RoaringBitmap32, ids: Uint32Array}} */ function* loincTextSearchG(store, text, lang, ordinal, stats = null) { + // meta searchTieBreak 'rank': ties in the stored rank order + if (store.searchTieBreak === 'rank') ordinal = store.rankOrdinal(); return yield* cached(store, 'loinc\u0000' + lang + '\u0000' + text, function* () { const q = new TextQuery(text); const rank = new Map(); // concept -> rank (cs-loinc.js: codeRank, then a better nameRank) @@ -641,7 +645,9 @@ function* loincTextSearchG(store, text, lang, ordinal, stats = null) { 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)); + // (meta searchTieBreak 'rank': ties in the stored rank order instead) + const tie = store.searchTieBreak === 'rank' ? null : (a, b) => disp(a).localeCompare(disp(b)); + const ids = yield* sortG([...rank.keys()], (a, b) => (rank.get(b) - rank.get(a)) || (tie ? tie(a, b) : 0) || ordinal(a) - ordinal(b)); return { bm: new RoaringBitmap32(ids), ids: Uint32Array.from(ids) }; }); } @@ -675,7 +681,9 @@ function* rxTextSearchG(store, text, eligible, stats = null) { 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))); + // (meta searchTieBreak 'rank': ties in the stored rank order instead) + const ord = store.searchTieBreak === 'rank' ? store.rankOrdinal() : null; + const ids = yield* sortG(bm.toArray(), (a, b) => (rank.get(b) - rank.get(a)) || (ord ? ord(a) - ord(b) : cmpBinary(code(a), code(b)))); return { bm, ids: Uint32Array.from(ids) }; }); } @@ -752,7 +760,9 @@ function* blockConcepts(store, csLang, stats) { /** 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); + let hits = yield* rateConceptsG(blockConcepts(store, csLang, stats), new TextQuery(text), lang, supplementCodes); + // meta searchTieBreak 'rank': ties in the stored rank order (else in concept id order) + if (store.searchTieBreak === 'rank') { const ord = store.rankOrdinal(); hits = yield* sortG(hits, (a, b) => b.rating - a.rating || ord(a.id) - ord(b.id)); } const ids = hits.map((h) => h.id); return { bm: new RoaringBitmap32(ids), ids: Uint32Array.from(ids) }; }; From 928f49a46b58ae53f47a97c2afcb2dc46c555887 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:41:04 -0600 Subject: [PATCH 05/90] sqlite-v2: grammar is an open name with a registry; behaviour.filters applied behaviour.grammar is any name (or null). The reader holds the grammars it implements by name (snomed: the SNOMED CT provider) and refuses a file whose grammar it does not implement, with no fallback by system URI; a provider loaded directly refuses a file of another grammar too. behaviour.filters is applied: where a file lists the only filters the system understands, a filter, operator or value (each item of an in list) not in the list is FILTER_NOT_UNDERSTOOD. The file itself is served. A listed inactive filter is FHIR's concept status. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 50 ++++++++++++++++++++++++ tx/sqlite-v2/README.md | 4 +- tx/sqlite-v2/engine/compile.js | 32 +++++++++++++++ tx/sqlite-v2/index.js | 23 +++++++++-- tx/sqlite-v2/meta.js | 3 +- tx/sqlite-v2/provider.js | 9 +++++ tx/sqlite-v2/snomed.js | 2 + 7 files changed, 117 insertions(+), 6 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index b7cc32952..cd09f2668 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -377,3 +377,53 @@ describe('P4. behaviour and order keys: the file\'s value obeyed, absent = the d withStore(withMeta(base, { 'behaviour.aliasLiterals': '{}', 'behaviour.aliasProperty': 'null' }), (S) => expect(S.behaviour.aliasLiterals).toEqual({})); }); }); + +describe('P5. grammar: an open string, implemented by name; behaviour.filters applied', () => { + const { loadSqliteV2Factory, factoryForGrammar } = require('../../tx/sqlite-v2/index'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { SnomedV2Factory } = require('../../tx/sqlite-v2/snomed'); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + const { Engine } = require('../../tx/sqlite-v2/engine/engine'); + let base, i18n; + beforeAll(async () => { + base = fixture(); + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + i18n = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())).i18n; + }); + + test('the registry: plain codes and snomed served; any other grammar refused, whatever the system', async () => { + expect(factoryForGrammar(null, 'f')).toBe(SqliteV2Factory); + expect(factoryForGrammar('snomed', 'f')).toBe(SnomedV2Factory); + for (const g of ['icd11', 'some-grammar']) { + const f = withMeta(base, { 'behaviour.grammar': JSON.stringify(g) }); + withStore(f, (S) => expect(S.behaviour.grammar).toBe(g)); + await expect(loadSqliteV2Factory(i18n, f)).rejects.toThrow(new RegExp(`its codes are in the grammar ${g} \\(behaviour.grammar\\), which this server does not implement`)); + // nor does the plain-code provider serve it when loaded directly + await expect(new SqliteV2Factory(i18n, f).load()).rejects.toThrow(/its codes are in the grammar/); + } + expect(() => openStore(withMeta(base, { 'behaviour.grammar': '""' }))).toThrow(/behaviour.grammar = "" is not a value/); + }); + + test('a filter, operator or value not in behaviour.filters is FILTER_NOT_UNDERSTOOD; a listed one is answered; the file is served', () => { + const f = withMeta(base, { 'behaviour.filters': JSON.stringify([{ code: 'colour', operator: ['=', 'in'], values: ['red', 'blue'] }, { code: 'inactive', operator: ['='] }]) }); + withStore(f, (S) => { + const c = new Compiler({ store: S, dialect: {} }); + const e = new Engine(S); + const codes = (node) => e.evaluate(node).toArray().map((id) => S.conceptRows([id]).get(id).code).sort(); + expect(codes(c.filter('colour', '=', 'red'))).toEqual(['A']); + expect(codes(c.filter('colour', 'in', 'red,blue'))).toEqual(['A', 'B']); + expect(codes(c.filter('inactive', '=', 'true'))).toEqual(['X']); + for (const [p, o, v] of [['colour', 'regex', 'r.*'], ['colour', '=', 'green'], ['colour', 'in', 'red,green'], ['parent', '=', 'A'], ['concept', 'is-a', 'A']]) { + let err = null; + try { c.filter(p, o, v); } catch (x) { err = x; } + expect(err && err.notUnderstood).toEqual([p, o, v]); + } + }); + // without the list: every filter the catalog allows + withStore(base, (S) => { + const c = new Compiler({ store: S, dialect: {} }); + expect(new Engine(S).evaluate(c.filter('concept', 'is-a', 'A')).size).toBe(2); + }); + }); +}); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 1ba4116b4..8eb6a53d8 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -124,7 +124,7 @@ refused (the builders check the same at build). | key | values | default | written by | |---|---|---|---| -| `grammar` | `"snomed"`, `"icd11"`, `null` | `null` (plain codes) | SNOMED CT: `"snomed"` (expressions, ECL; the SNOMED CT provider). ICD-11 MMS and ICF files: `"icd11"` (postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records) | +| `grammar` | a grammar name (an open string), `null` | `null` (plain codes) | the grammar of the system's codes. A reader holds its implementations by name and refuses a file whose grammar it does not implement ("its codes are in the grammar X, which this server does not implement"); there is no fallback by system URI. Names in use: `"snomed"` (SNOMED CT expressions and ECL; the JS reader's SNOMED CT provider, `index.js` `GRAMMARS`), `"icd11"` (ICD-11 MMS and ICF files: postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records), and a code system whose codes carry modifiers. The JS reader implements `snomed` only | | `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"` | the name `$lookup` reports: `code_system.name` (no name: the system URI), or the title (below; no title: the name). LOINC `"title"` | | `description` | `"name"`, `"title"` | `"title"` | the description a server gives the code system (its catalog entry): `code_system.title` (no title: the name), or `code_system.name`. LOINC `"name"` | @@ -136,7 +136,7 @@ refused (the builders check the same at build). | `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) | +| `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | 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 diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index c81fe669b..ce483e141 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -156,12 +156,44 @@ class Compiler { // ---- filters ------------------------------------------------------------------------------- + /** + * A filter as a request names it. Where the file lists the only filters the system understands + * (meta behaviour.filters), a filter, operator or value not in the list is FILTER_NOT_UNDERSTOOD; + * the list is checked once, for the filter as requested (not the filters a rule rewrites it into) + */ filter(prop, op, value) { + if (this._inFilter) return this._filter(prop, op, value); + this._inFilter = true; + try { + this.checkListedFilter(prop, op, value); + return this._filter(prop, op, value); + } finally { + this._inFilter = false; + } + } + + /** meta behaviour.filters: [{code, operator: [...], values?: [...]}] or null (every filter the catalog allows) */ + checkListedFilter(prop, op, value) { + const listed = this.store.behaviour.filters; + if (!listed) return; + const f = listed.find((x) => x.code === prop); + const values = op === 'in' || op === 'not-in' ? splitList(value) : [String(value)]; + if (!f || !f.operator.includes(op) || (f.values && !values.every((v) => f.values.includes(v)))) { + throw new FilterError(`The filter "${prop} ${op} ${value}" is not understood or supported`, { notUnderstood: [prop, op, value] }); + } + } + + _filter(prop, op, value) { if (this.dialect.filter) { const n = this.dialect.filter(this, prop, op, value); if (n) return n; } if (prop === 'display' && !this.store.filterProp('display')) return this.displayFilter(op, value); + // FHIR's concept status, where the file lists it as a filter (behaviour.filters code 'inactive') + if (prop === 'inactive' && !this.store.filterProp('inactive') && op === '=' && (this.store.behaviour.filters || []).some((x) => x.code === 'inactive')) { + if (value !== 'true' && value !== 'false') throw new FilterError(`Invalid filter value: ${value}`); + return value === 'true' ? { t: 'inactive' } : { t: 'active' }; + } 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}"` }; diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js index 3502f22a9..a01f3635d 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -9,6 +9,23 @@ const { SqliteV2Factory } = require('./provider'); const { SnomedV2Factory } = require('./snomed'); const { checkFormat } = require('./store'); +/** + * The code grammars this server implements, by name (meta behaviour.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, +}); + +/** 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} (behaviour.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 = {}) { const db = new Database(file, { readonly: true, fileMustExist: true }); @@ -19,10 +36,10 @@ async function loadSqliteV2Factory(i18n, file, opts = {}) { } 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/meta.js b/tx/sqlite-v2/meta.js index cff5c6fad..1044e0e5b 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -77,7 +77,8 @@ const KEYS = Object.freeze({ linkOrder: text((v) => ['property', 'seq', 'property-seq', 'target-int'].includes(v), 'property'), searchTieBreak: text((v) => v === 'rank', null), // behaviour settings - 'behaviour.grammar': json((v) => [null, 'snomed', 'icd11'].includes(v), null), + // an open string: a reader refuses a grammar it does not implement (index.js) + 'behaviour.grammar': json((v) => v === null || (isString(v) && v !== ''), null), 'behaviour.filters': json((v) => v === null || (Array.isArray(v) && v.every(isFilterSpec)), null), 'behaviour.expansionOrder': json((v) => ['ids', 'stored', 'stored-self-first'].includes(v), 'ids'), 'behaviour.lookupName': json((v) => v === 'name' || v === 'title', 'name'), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index ced6c5e9f..62756fd59 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1371,6 +1371,9 @@ function mapRelationship(equivalence, fromLoinc) { // ---- factory ------------------------------------------------------------------------------- class SqliteV2Factory extends CodeSystemFactoryProvider { + /** the code grammar this factory implements (meta behaviour.grammar; null: plain codes) */ + static grammar = null; + constructor(i18n, file, opts = {}) { super(i18n); this.file = file; @@ -1379,6 +1382,12 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { async load() { this.store = openStore(this.file, this.opts); + // a file whose codes have a grammar this factory does not implement (index.js GRAMMARS) + if (this.store.behaviour.grammar !== this.constructor.grammar) { + const g = this.store.behaviour.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} (behaviour.grammar), which this provider serves`); + } this.dialect = dialectFor(this.store.system); // behaviour.expansionOrder: concept ids, or the stored order (ix_order) const kind = this.store.behaviour.expansionOrder; diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 38989a79c..3e34d48be 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -667,6 +667,8 @@ function fmtDate(v) { const LOADED = new Set(); class SnomedV2Factory extends SqliteV2Factory { + static grammar = 'snomed'; + edition() { return this.store.cs.edition; } name() { From 6ed4d2067681e3360d820e0a93289bc57ff246a9 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:45:10 -0600 Subject: [PATCH 06/90] sqlite-v2: contracts written down and checked by the builder; drop n_rows and target_kind The format document lists the contracts every file keeps (id ranges, the hierarchy and list properties, index key conventions, ix_in and ix_by_subject contents, ix_order block layout, counts rows, a stemmer for every word-index language, a stored order where expansionOrder needs one, the schema's indexes, statistics). The builder checks them before it finishes a file, and so does indexes.js after a rebuild. property.n_rows and property.target_kind are dropped: derived and read by nothing. code_system.case_sensitive, hierarchy_meaning and release_date stay (CodeSystem facts; isCaseSensitive reads case_sensitive). The reader checks the id ranges it relies on at open (three rowid probes). Co-Authored-By: Claude --- tests/tx/sqlite-v2-builder.test.js | 10 +- tests/tx/sqlite-v2-format-round2.test.js | 66 +++++++++++ tests/tx/sqlite-v2-loinc.test.js | 6 +- tests/tx/sqlite-v2-rxnorm-filters.test.js | 2 +- tx/importers/import-rxnorm-v2.module.js | 2 +- tx/importers/sqlite-v2/builder.js | 129 ++++++++++++++++++---- tx/importers/sqlite-v2/diff.js | 4 +- tx/importers/sqlite-v2/indexes.js | 8 +- tx/importers/sqlite-v2/schema.sql | 13 ++- tx/sqlite-v2/README.md | 32 ++++++ tx/sqlite-v2/layers.js | 6 +- tx/sqlite-v2/store.js | 19 +++- 12 files changed, 254 insertions(+), 43 deletions(-) diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js index 69a79e6d8..849531be7 100644 --- a/tests/tx/sqlite-v2-builder.test.js +++ b/tests/tx/sqlite-v2-builder.test.js @@ -127,11 +127,11 @@ 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', () => { + const row = (code) => db.prepare('SELECT shape, subject_kind, by_target, filterable FROM property WHERE code = ?').get(code); + expect(row('isa')).toEqual({ shape: 'link', subject_kind: 'concept', by_target: 1, filterable: 1 }); + expect(row('colour')).toEqual({ shape: 'literal', subject_kind: 'concept', by_target: 0, filterable: 1 }); + expect(row('S1')).toEqual({ shape: 'record', subject_kind: 'concept', by_target: 0, filterable: 1 }); }); test('descendant sets equal the closure recomputed with a recursive CTE', () => { diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index cd09f2668..af523ae33 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -427,3 +427,69 @@ describe('P5. grammar: an open string, implemented by name; behaviour.filters ap }); }); }); + +describe('P6. contracts checked by the builder; the CodeSystem columns kept; cheap id checks at open', () => { + const { checkContracts } = require('../../tx/importers/sqlite-v2/builder'); + let base; + beforeAll(() => { base = fixture((b, c) => b.setMeta('ix.ix_word.names', { items: {}, counts: true })); }); + /** a writable copy changed by sql, its contracts checked */ + const broken = (sql, ...args) => { + 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.prepare(sql).run(...args); + 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 item SET id = id + 100 WHERE id = (SELECT max(id) FROM item)')).toThrow(/contract: item ids are not exactly/); + expect(broken('UPDATE property SET subsumption = 1')).toThrow(/contract: more than one property with subsumption = 1/); + expect(broken("UPDATE ix_set SET value_kind = 2 WHERE kind = 1")).toThrow(/ix_set rows break the key conventions/); + expect(broken('DELETE FROM ix_in WHERE subject_id = (SELECT max(subject_id) FROM ix_in)')).toThrow(/contract: ix_in does not hold exactly/); + 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("INSERT OR REPLACE INTO meta VALUES ('behaviour.expansionOrder', '\"stored\"')")).toThrow(/contract: behaviour.expansionOrder "stored" without ix_order rank and ids/); + expect(broken('DROP INDEX item_concept')).toThrow(/contract: the index item_concept is missing/); + expect(broken('ANALYZE')).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'); + 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; n_rows and target_kind are gone', async () => { + const db = new Database(base, { readonly: true }); + try { + const cols = db.prepare('PRAGMA table_info(code_system)').all().map((c) => c.name); + expect(cols).toEqual(expect.arrayContaining(['case_sensitive', 'hierarchy_meaning', 'release_date'])); + const pcols = db.prepare('PRAGMA table_info(property)').all().map((c) => c.name); + expect(pcols).not.toContain('n_rows'); + expect(pcols).not.toContain('target_kind'); + } finally { db.close(); } + 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', () => { + const f = path.join(dir, `ids${++seq}.db`); + fs.copyFileSync(base, f); + const w = new Database(f); + w.prepare('UPDATE code_system SET concept_count = concept_count + 1 WHERE served = 1').run(); + w.close(); + expect(() => openStore(f)).toThrow(/concept ids are not 1\.\.6 \(concept_count\)/); + }); +}); diff --git a/tests/tx/sqlite-v2-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js index 55879f3be..c9097682f 100644 --- a/tests/tx/sqlite-v2-loinc.test.js +++ b/tests/tx/sqlite-v2-loinc.test.js @@ -220,9 +220,9 @@ describe('LOINC v2 importer over the test fixture', () => { 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, p.filterable, 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', filterable: 1, ordered: 0 }); + expect(row('AnswerList')).toEqual({ code: 'AnswerList', inverse_of: 'Answer|answers-for', filterable: 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'); diff --git a/tests/tx/sqlite-v2-rxnorm-filters.test.js b/tests/tx/sqlite-v2-rxnorm-filters.test.js index f8a6f48fd..3b1ec4dbb 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/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index f9578ab08..1bedd7535 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -14,7 +14,7 @@ // 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 diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index fc3b86b4f..8893665f9 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -10,9 +10,9 @@ // 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; // 4. builds the ix_* tables (indexes.js, which reads fact tables only); // 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 @@ -476,12 +476,12 @@ class TerminologyBuilder { const nodeId = (h) => (h == null ? null : h >= 0 ? idOf[h] : db.prepare('SELECT new FROM st.s_node WHERE old = ?').pluck().get(h)); const computed = this._time('catalog computed fields', () => catalogStats(db, n)); const insProp = db.prepare(`INSERT INTO property (id, cs_id, code, uri, display, concept_id, shape, role, fhir_type, subject_kind, - target_kind, n_rows, subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, filter_ops, report, fields) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, filter_ops, report, fields) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); const parents = new Set(this.members.map(([a]) => a)); for (const p of this.properties) { // subject_kind NULL for a catalog row with no rows - const c = computed.get(p.id) || { subjectKind: null, targetKind: null, n: 0 }; + const c = computed.get(p.id) || { subjectKind: null, n: 0 }; // shape 'union': a link row whose only rows are its members' let shape = p.shape; if (parents.has(p.id)) { @@ -492,7 +492,6 @@ class TerminologyBuilder { const byTarget = p.byTarget != null ? p.byTarget : ((shape === 'link' || shape === 'both') && (p.subsumption || p.refinable) ? 1 : 0); insProp.run(p.id, p.cs, p.code, p.uri, p.display, nodeId(p.concept), shape, p.role, p.fhirType, c.subjectKind, - (shape === 'link' || shape === 'both' || shape === 'record') ? c.targetKind : null, c.n, p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.filterOps, p.report, p.fields); } const insMember = db.prepare('INSERT OR IGNORE INTO property_member VALUES (?, ?)'); @@ -544,25 +543,24 @@ class TerminologyBuilder { } } -/** per property: n_rows, subject_kind, target_kind from the fact rows (ids <= n are concepts) */ +/** + * 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; } @@ -616,13 +614,104 @@ function vacuumFile(file) { } /** - * The step that finishes a file, after every other table, meta row and ANALYZE: 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 + * The step that finishes a file, after every other table, meta row and ANALYZE: the contracts of the + * format hold (checkContracts), 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); readMeta(db.prepare('SELECT key, value FROM main.meta').raw().all(), file, { writer: true }); } -module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, finishFile, analyze, externalIdValue }; +/** 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'); + 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`); + } + // a stored expansion order (behaviour.expansionOrder 'stored' / 'stored-self-first') has its arrays + const eo = one("SELECT value FROM main.meta WHERE key = 'behaviour.expansionOrder'"); + if (eo != null && JSON.parse(eo) !== 'ids' && !(arrays.has('rank') && arrays.has('ids'))) fail(`behaviour.expansionOrder ${eo} without ix_order rank and ids`); + // 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, finishFile, checkContracts, analyze, externalIdValue }; diff --git a/tx/importers/sqlite-v2/diff.js b/tx/importers/sqlite-v2/diff.js index 398d89a1e..e4a0f5287 100644 --- a/tx/importers/sqlite-v2/diff.js +++ b/tx/importers/sqlite-v2/diff.js @@ -44,9 +44,9 @@ function keyed(db) { 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, + view('property', `SELECT code, uri, display, concept_id, shape, role, fhir_type, subject_kind, 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; }); + (r) => { r[3] = key(r[3]); r[9] = r[9] == null ? null : pcode.get(r[9]); r[13] = r[13] == null ? null : pcode.get(r[13]); return r; }); view('property_member', 'SELECT parent_id, child_id FROM property_member', ([a, b]) => [pcode.get(a), pcode.get(b)]); view('link', 'SELECT subject_id, property_id, group_id, target_id, active FROM link', ([s, p, g, t, a]) => [key(s), pcode.get(p), g, key(t), a]); view('literal', 'SELECT subject_id, property_id, group_id, CAST(value AS TEXT), active FROM literal', ([s, p, g, v, a]) => [key(s), pcode.get(p), g, v, a]); diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index 97495beee..268d0caf9 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -333,7 +333,8 @@ function intPairs(stmt) { module.exports = { buildIndexes, dropIndexes, ixTables, derivedByImporter, writeOrderArray, writeActiveOrder, KIND, VK }; -// node indexes.js [--drop-only]: rebuild (or only drop) the ix_* tables of a built file +// 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); @@ -342,7 +343,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 2aa019aa3..2bde6ce9b 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 ( @@ -62,9 +70,8 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat -- ('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) + 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 diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 8eb6a53d8..fd106ee56 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -78,6 +78,38 @@ Index tables (rebuildable): | `ix_word` | the text-filter word index per language over the names `ix.ix_word.names` selects: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (below) | | `ix_text_display`, `ix_text_item` | FTS5 trigram indexes over displays and item texts (regex prefilter) | +## Contracts + +What every file keeps, and every reader may rely on. The builder checks those marked before it +finishes a file (`builder.js` `checkContracts`, run by `finishFile`; `node indexes.js ` runs it +after a rebuild); `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, one id space with the concepts | yes | +| at most one property with `subsumption = 1` (the hierarchy), at most one `ordered = 1` link property (the list property) | yes | +| codes are unique per system and matched exactly (binary): the unique index `concept_code` | yes | +| `identifier.value` is text | by the schema (`TEXT`; `identifier-text`) | +| `ix_set` keys: kinds 1, 2, 3 have property 0, value 0, value kind 0; kinds 6 and 7 value 0, value kind 0; kind 4 value kind 1 | yes | +| a kind 4 set (the descendants of the concept `value`) does not hold `value`; the all and active sets have N and A members; sets hold concept ids only | yes (kinds 1, 2, 4 decoded) | +| `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 (row counts) | +| `ix_order` arrays: little-endian u32 in 1,024-entry blocks 0..k, all full but the last; `rank` and `ids` N+1 entries, `walk` and `active` at most N; `ix.ix_order.walk.reached` at most the walk's length | yes | +| `behaviour.expansionOrder` other than `ids`: `ix_order` has `rank` and `ids` | yes | +| the `ix_word` counts rows are `2 * (N + 1)` bytes; every `ix_word` 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 | +| meta follows "Meta" (every key one the builder knows, every value well-formed) | yes | +| record `fields` is a JSON array in the order of the relation's non-target fields | stated (a check would parse every record row) | + +The JS reader checks the id ranges it relies on at open (an id up to N is a concept, above N an +item): `min(concept.id) = 1`, `max(concept.id) = N`, `min(item.id) > N`, three probes of the rowid +b-trees. It checks nothing else of the list at open. + +Columns: `code_system.case_sensitive`, `hierarchy_meaning` and `release_date` are the FHIR +CodeSystem facts (the JS provider's `isCaseSensitive()` reads `case_sensitive`; NULL: true). +`property.n_rows` and `property.target_kind` are gone: derived, and read by no reader (a file built +before still has them; readers ignore them). + ## Meta `meta` is key -> text. One rule for every key: diff --git a/tx/sqlite-v2/layers.js b/tx/sqlite-v2/layers.js index 07083f8b8..620abe8fd 100644 --- a/tx/sqlite-v2/layers.js +++ b/tx/sqlite-v2/layers.js @@ -117,9 +117,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)); }; diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index c7280d965..086b8d46e 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -157,7 +157,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; @@ -321,7 +321,7 @@ class Store { // ---- 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?)`); @@ -337,6 +337,11 @@ class Store { this.activeCount = cs.active_count; this.lo = 1; this.hi = cs.concept_count; + // 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); const m = readMeta(this.meta, this.file); this.requires = m.requires; // identifier values are all text (identifier-text): probes bind text, lists through json_each @@ -375,6 +380,14 @@ class Store { this.hasLinkOrder = !!(this.hierarchy && this.hierarchy.byTarget); } + _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() { 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) @@ -385,7 +398,7 @@ class Store { // 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, + subjectKind: r.subject_kind, conceptId: r.concept_id, isHierarchy: !!r.subsumption, closureFrom: r.closure_from, filterable: !!r.filterable, refinable: !!r.refinable, wildcard: !!r.wildcard, byTarget: !!r.by_target, bySubject: !!r.by_subject, ordered: !!r.ordered, role: r.role, attribute: !!r.refinable, // (the SNOMED CT adapters' "attribute": a row ECL refines by) From d40acfea0f9b03e98aeabcfba903809f53da82b7 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:49:22 -0600 Subject: [PATCH 07/90] sqlite-v2: optional integrity facts and verify.js The builder writes meta integrity when it finishes a file: the item count and SHA-256 digests of the schema and of the catalog tables (defined in the format document). Readers do not check them. node tx/importers/sqlite-v2/verify.js checks a file on request, read-only: the format, the meta values, every contract the builder checks (id ranges included) and the integrity facts where the file has them (file length, both digests, the item count). It prints each check and exits 1 on a failure, 2 when the file cannot be read. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 58 +++++++++++++++++ tx/importers/sqlite-v2/builder.js | 6 +- tx/importers/sqlite-v2/indexes.js | 2 + tx/importers/sqlite-v2/verify.js | 72 ++++++++++++++++++++ tx/sqlite-v2/README.md | 24 +++++++ tx/sqlite-v2/integrity.js | 83 ++++++++++++++++++++++++ tx/sqlite-v2/meta.js | 4 ++ 7 files changed, 248 insertions(+), 1 deletion(-) create mode 100644 tx/importers/sqlite-v2/verify.js create mode 100644 tx/sqlite-v2/integrity.js diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index af523ae33..efa5d6f6d 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -493,3 +493,61 @@ describe('P6. contracts checked by the builder; the CodeSystem columns kept; che expect(() => openStore(f)).toThrow(/concept ids are not 1\.\.6 \(concept_count\)/); }); }); + +describe('P7. 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((b) => b.setMeta('ix.ix_word.names', { items: {} })); }); + const copy = (change) => { + const f = path.join(dir, `v${++seq}.db`); + fs.copyFileSync(base, f); + change(f); + return f; + }; + + test('the builder writes meta integrity: items, schema and catalog digests', () => { + 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()); + expect(v.schema).toBe(require('../../tx/sqlite-v2/integrity').schemaDigest(db)); + } finally { db.close(); } + }); + + test('a finished file passes, and lists what was checked', () => { + const r = run(base); + expect(r.stdout).toMatch(/^ok {3}format/m); + expect(r.stdout).toMatch(/^ok {3}contracts/m); + expect(r.stdout).toMatch(/^ok {3}integrity: catalog digest/m); + expect(r.status).toBe(0); + }); + + test('a file without integrity facts is checked for the rest (they are optional)', () => { + const f = copy((p) => { const w = new Database(p); w.exec("DELETE FROM meta WHERE key = 'integrity'"); w.close(); }); + const r = run(f); + expect(r.stdout).toMatch(/integrity: the file states no integrity facts/); + expect(r.status).toBe(0); + // a reader opens it as any file + withStore(f, (S) => expect(S.conceptCount).toBe(5)); + }); + + test('corrupted copies fail with a non-zero exit, naming the check', () => { + const appended = copy((p) => fs.appendFileSync(p, Buffer.alloc(100))); + expect(run(appended).status).toBe(1); + expect(run(appended).stdout).toMatch(/^FAIL integrity: file length/m); + const catalog = copy((p) => { const w = new Database(p); w.exec("UPDATE property SET filterable = 0 WHERE code = 'colour'"); w.close(); }); + expect(run(catalog).stdout).toMatch(/^FAIL integrity: catalog digest/m); + expect(run(catalog).status).toBe(1); + const index = copy((p) => { const w = new Database(p); w.exec('DROP INDEX item_concept'); w.close(); }); + const r = run(index); + expect(r.stdout).toMatch(/^FAIL contracts: contract: the index item_concept is missing/m); + expect(r.stdout).toMatch(/^FAIL integrity: schema digest/m); + expect(r.status).toBe(1); + const meta = copy((p) => { const w = new Database(p); w.exec("UPDATE meta SET value = '\"sideways\"' WHERE key = 'behaviour.expansionOrder'; INSERT OR REPLACE INTO meta VALUES ('behaviour.expansionOrder', '\"sideways\"')"); w.close(); }); + expect(run(meta).stdout).toMatch(/^FAIL meta: .*behaviour.expansionOrder = "sideways"/m); + expect(run(path.join(dir, 'no-such.db')).status).toBe(2); + }); +}); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 8893665f9..d17178d50 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -28,6 +28,7 @@ const Database = require('better-sqlite3'); const { numberConcepts } = require('../sqlite-v2/numbering'); const { buildIndexes } = require('./indexes'); const { readMeta, WRITTEN_FEATURES } = require('../../sqlite-v2/meta'); +const { computeIntegrity, integrityValue } = require('../../sqlite-v2/integrity'); const SCHEMA_PATH = path.join(__dirname, 'schema.sql'); const FORMAT = 'tx-terminology/1'; @@ -615,13 +616,16 @@ function vacuumFile(file) { /** * The step that finishes a file, after every other table, meta row and ANALYZE: the contracts of the - * format hold (checkContracts), 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 + * 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 }); } diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index 268d0caf9..d11bcc6b3 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -72,6 +72,8 @@ function dropIndexes(db) { if (k === 'ix.ix_word.names') continue; 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(); } /** diff --git a/tx/importers/sqlite-v2/verify.js b/tx/importers/sqlite-v2/verify.js new file mode 100644 index 000000000..98f1a3cd5 --- /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, 2 when the file cannot be read. +// Readers make none of these checks but the cheap id ranges (tx/sqlite-v2/store.js). + +const fs = require('fs'); +const Database = require('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(2); + } + let results; + try { + results = verifyFile(file); + } catch (e) { + console.error(e.message); + process.exit(2); + } + 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/sqlite-v2/README.md b/tx/sqlite-v2/README.md index fd106ee56..e356b3507 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -110,6 +110,29 @@ CodeSystem facts (the JS provider's `isCaseSensitive()` reads `case_sensitive`; `property.n_rows` and `property.target_kind` are gone: derived, and read by no reader (a file built before still has them; readers ignore them). +## 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), `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 (2 when the file cannot be read). Readers do not check digests. + ## Meta `meta` is key -> text. One rule for every key: @@ -134,6 +157,7 @@ before still has them; readers ignore them). |---|---|---|---| | `format` | `tx-terminology/1` | (required) | the format | | `requires` | JSON list of feature names | `[]` | above | +| `integrity` | JSON `{items, schema, catalog}` | none | facts a tool checks on request (below); readers do not | | `languages` | JSON list of language tags | `[]` | the languages of the served system's items, in order of first appearance | | `displayContexts` | JSON `{relations, preferred, use}` | none | the language relations that rank displays (SNOMED CT) | | `moduleDependencies` | JSON list of `[module, target module, effective time, target effective time]` | `[]` | SNOMED CT module dependencies | diff --git a/tx/sqlite-v2/integrity.js b/tx/sqlite-v2/integrity.js new file mode 100644 index 000000000..9f91a7002 --- /dev/null +++ b/tx/sqlite-v2/integrity.js @@ -0,0 +1,83 @@ +'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'], + ['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/meta.js b/tx/sqlite-v2/meta.js index 1044e0e5b..bee63b86f 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -28,6 +28,8 @@ const isString = (v) => typeof v === 'string'; const isStrings = (a) => Array.isArray(a) && a.every(isString); 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 DECIMAL = /^(0|[1-9][0-9]*)$/; /** one entry of behaviour.filters: {code, operator: [FHIR filter operators, at least one], values?: [strings]} */ @@ -61,6 +63,8 @@ const text = (check, dflt) => ({ json: false, check, default: dflt }); const KEYS = Object.freeze({ format: text((v) => v === FORMAT), requires: json((v) => isStrings(v) && new Set(v).size === v.length, []), + // 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) From 24d7be293c71c3e3881c606c4d1642a8a271b7f6 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 16:52:23 -0600 Subject: [PATCH 08/90] sqlite-v2: property.report never, behaviour.expansionLimit Catalog property.report gains 'never': the property is not reported by $lookup (asked for or not), nor on expansions, nor declared; with filterable = 1 it is a filter only. The reader now obeys report in every $lookup path (named: only when the request names it; always: on every expansion row, mandatoryExpansionProperties), where before it checked the value and ignored it. The builder refuses a report value it does not know. behaviour.expansionLimit (an integer, default 0: no limit) is the most codes of the system an expansion lists or walks: the provider's expandLimitation(). A file that sets it is expanded through expand.js's usual path, which counts codes against the limit. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 73 ++++++++++++++++++++++++ tx/importers/sqlite-v2/builder.js | 3 +- tx/importers/sqlite-v2/schema.sql | 5 +- tx/sqlite-v2/README.md | 13 +++-- tx/sqlite-v2/meta.js | 1 + tx/sqlite-v2/provider.js | 35 +++++++++--- tx/sqlite-v2/snomed.js | 4 +- tx/sqlite-v2/store.js | 4 +- 8 files changed, 119 insertions(+), 19 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index efa5d6f6d..1cf9cd8d3 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -551,3 +551,76 @@ describe('P7. integrity facts written by the builder; verify.js checks a file on expect(run(path.join(dir, 'no-such.db')).status).toBe(2); }); }); + +describe('P8. property.report never / named / always; behaviour.expansionLimit', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + let op, f, p; + beforeAll(async () => { + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const file = fixture((b, c) => { + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'code', report: 'never' }); + const note = b.property({ code: 'note', shape: 'literal', fhirType: 'string', report: 'named' }); + const cls = b.property({ code: 'class', shape: 'literal', fhirType: 'code', report: 'always' }); + b.literal(c.A, kind, 'product'); + b.literal(c.A, note, 'a note'); + b.literal(c.A, cls, 'K1'); + b.setBehaviour('expansionLimit', 2); + }); + f = new SqliteV2Factory(op.i18n, file); + await f.load(); + p = await f.build(op, []); + }); + afterAll(() => f.store.close()); + const lookup = async (props) => { + const params = []; + await p.extendLookup((await p.locate('A')).context, props, params); + return params.map((x) => x.part.find((y) => y.name === 'code').valueCode); + }; + + test('never: not in $lookup (asked for or not), not on expansions, not a declared property; still a filter', async () => { + expect(await lookup([])).not.toContain('kind'); + expect(await lookup(['kind'])).not.toContain('kind'); + expect(await lookup(['*'])).not.toContain('kind'); + expect((p.propertyDefinitions() || []).map((d) => d.code)).not.toContain('kind'); + expect(await p.properties((await p.locate('A')).context, ['kind'])).toEqual([]); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + expect(f.engine.evaluate(new Compiler({ store: f.store, dialect: {} }).filter('kind', '=', 'product')).size).toBe(1); + }); + + test('named: only when the request names it; always: by default and on every expansion', async () => { + expect(await lookup([])).not.toContain('note'); + expect(await lookup(['*'])).not.toContain('note'); + expect(await lookup(['note'])).toContain('note'); + expect(await lookup([])).toContain('class'); + expect(p.mandatoryExpansionProperties()).toEqual(['class']); + }); + + test('a report value the builder does not know is refused', () => { + const b = new TerminologyBuilder(path.join(dir, 'never3.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/x', version: '1' }); + expect(() => b.property({ code: 'x', shape: 'literal', fhirType: 'string', report: 'sometimes' })).toThrow(/bad report sometimes/); + }); + + test('expansionLimit: the provider\'s expandLimitation; absent: 0 (no limit); malformed: refused', () => { + expect(p.expandLimitation()).toBe(2); + withStore(fixture(), (S) => expect(S.behaviour.expansionLimit).toBe(0)); + expect(() => openStore(withMeta(fixture(), { 'behaviour.expansionLimit': '-1' }))).toThrow(/behaviour.expansionLimit = -1 is not a value/); + expect(() => openStore(withMeta(fixture(), { 'behaviour.expansionLimit': '1.5' }))).toThrow(/behaviour.expansionLimit = 1.5 is not a value/); + }); +}); + +describe('P8b. an expansion of a system with expansionLimit takes the path that counts against it', () => { + test('handlesSelecting is off where the file sets a limit', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + for (const [meta, want] of [[{}, true], [{ 'behaviour.expansionLimit': '3' }, false]]) { + const f = new SqliteV2Factory(op.i18n, withMeta(fixture(), meta)); + await f.load(); + try { expect((await f.build(op, [])).handlesSelecting()).toBe(want); } finally { f.store.close(); } + } + }); +}); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index d17178d50..f9a59a30a 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -171,7 +171,7 @@ class TerminologyBuilder { * (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) } + * report ('named' | 'always' | 'never': when $lookup and expansions report it) } */ property(spec) { const cs = spec.cs || 1; @@ -186,6 +186,7 @@ class TerminologyBuilder { 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.report != null && !['named', 'always', 'never'].includes(spec.report)) throw new Error(`property ${spec.code}: bad report ${spec.report}`); 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}`); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 2bde6ce9b..fc0e8ae10 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -85,8 +85,9 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat 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 + report TEXT, -- when $lookup and expansions report it: 'never' (not at all: a filter + -- only), 'named' (only when asked for by name), 'always' (also on every + -- expansion row); NULL: by default and when asked for 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` diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index e356b3507..2f1d1b1b0 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -192,6 +192,7 @@ refused (the builders check the same at build). | `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 | +| `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | Release facts in `meta` that a reader also presents: `titles` (JSON object, language -> the system's @@ -212,10 +213,14 @@ and RxNorm adapters list `$lookup` properties in the order of the providers they property lists, `dialects.js` / `provider.js`), which no value of the key describes. 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`). +and the relationships: `=`, `in`) and `report`, when `$lookup` and expansions report it: `never` (not +by `$lookup`, asked for or not, nor on expansions, nor among the declared properties: a filter only +where `filterable = 1`, hidden altogether where not), `named` (`$lookup` returns it only when the +request names it; `*` does not), `always` (also on every expansion row), NULL (the default: `$lookup` +reports it by default and when asked for). None of SNOMED CT, LOINC, RxNorm 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`. A filter-only property is `never` with `filterable = 1`: one value, as +filterability is the separate `filterable` column. ## Word index diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index bee63b86f..e4e7d2b8a 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -95,6 +95,7 @@ const KEYS = Object.freeze({ 'behaviour.aliasExtension': json((v) => v === null || isString(v), null), 'behaviour.preferredForLanguage': json(isBool, false), 'behaviour.aliasLiterals': json((v) => isPlainObject(v) && Object.values(v).every(isString), {}), + 'behaviour.expansionLimit': json(isCount, 0), }); /** key patterns this reader knows (one entry per family): [test, spec] */ diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 62756fd59..9d4596f38 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -115,6 +115,23 @@ class SqliteV2Provider extends BaseCSServices { contentMode() { return this.store.cs.content || 'complete'; } versionAlgorithm() { return this.f.versionAlgorithm(); } isCaseSensitive() { return this.store.caseSensitive; } + /** the most codes of this system an expansion lists or walks (behaviour.expansionLimit; 0: no limit) */ + expandLimitation() { return this.store.behaviour.expansionLimit; } + /** the properties every expansion row reports (catalog report 'always') */ + mandatoryExpansionProperties() { return [...this.store.catalog.values()].filter((d) => d.report === 'always').map((d) => d.code); } + + /** + * Whether a lookup (or an expansion's properties) reports a catalog property (report: 'never' not + * at all, 'named' only when the request names it, else as the request's list says; dflt: whether + * an empty list reports it) + */ + _reports(code, props, dflt = true) { + const d = this.store.catalog.get(code); + const report = d ? d.report : null; + if (report === 'never') return false; + if (report === 'named') return !!(props && props.some((p) => String(p).toLowerCase() === String(code).toLowerCase())); + return this._hasProp(props, code, dflt); + } sourcePackage() { return null; } /** @@ -684,7 +701,7 @@ class SqliteV2Provider extends BaseCSServices { }; 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; + if (!this._reports(l.code, props, true)) continue; const t = rows.get(l.t); if (l.code === 'CLASS') { const pr = this._addStringProperty(params, 'property', 'CLASS', t.display || t.code); @@ -696,7 +713,7 @@ class SqliteV2Provider extends BaseCSServices { } 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 === 'STATUS' || !this._reports(r.code, props, true)) continue; if (r.code === 'CLASSTYPE') { const map = S.valueLabels(S.props.get('CLASSTYPE')) || {}; const pr = this._addStringProperty(params, 'property', 'CLASSTYPE', String(r.v)); @@ -742,7 +759,7 @@ class SqliteV2Provider extends BaseCSServices { } 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; + if (!this._reports(name, props, true)) continue; for (const v of [...(lits.get(name) || [])].sort(asText)) this._addCodeProperty(params, 'property', name, v); } if (!(props && props.length > 0)) return; @@ -755,7 +772,7 @@ class SqliteV2Provider extends BaseCSServices { 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; + if (!t || seen.has(name + '|' + t.code) || !this._reports(name, props, false)) continue; seen.add(name + '|' + t.code); named.push({ name, code: t.code }); } @@ -834,12 +851,12 @@ class SqliteV2Provider extends BaseCSServices { 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; + if (!p || !t || !this._reports(p.code, props, 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)); + if (p && this._reports(p.code, props, true)) this._addStringProperty(params, 'property', p.code, String(r.v)); } } @@ -1146,7 +1163,9 @@ class SqliteV2Provider extends BaseCSServices { // ---- processSelection (whole single-system composes) ---------------------------------------- - handlesSelecting() { return true; } + // not for a system with an expansion limit (behaviour.expansionLimit): expand.js's usual path + // counts the codes against it + handlesSelecting() { return !(this.store.behaviour.expansionLimit > 0); } /** * cs-api processSelection (expand.js processCodes): the page of the whole compose, with the @@ -1320,7 +1339,7 @@ function propertyDefinitionsFor(store, dialect) { 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 p of store.props.values()) if (!p.code.includes('@') && p.report !== 'never') add(p.isHierarchy ? 'parent' : p.code, p.uri, p.type); for (const c of ['parent', 'child', 'inactive']) add(c, null, 'code'); return defs; } diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 3e34d48be..6faf94b1c 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -328,7 +328,7 @@ class SnomedV2Provider extends SqliteV2Provider { 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; + if (!p || !p.attribute || p.code === IS_A || !this._reports(p.code, props, true)) continue; const k = p.code + ':' + code(l.t); if (seen.has(k)) continue; seen.add(k); @@ -338,7 +338,7 @@ class SnomedV2Provider extends SqliteV2Provider { } // 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); }) + const concreteLits = lits.filter((l) => { const p = S.propsById.get(l.p); return p && p.attribute && this._reports(p.code, props, 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); diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 086b8d46e..0e3be6587 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -87,7 +87,7 @@ function readBehaviour(meta, file) { } const FILTER_OPS = new Set(FILTER_OPERATORS); -const REPORT = new Set([null, 'named', 'always']); +const REPORT = new Set([null, 'named', 'always', 'never']); /** meta behaviour.* -> settings object (every key, defaults filled); throws on an unknown key or value */ function readBehaviour(meta, file) { @@ -409,7 +409,7 @@ class Store { 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)`); + if (!REPORT.has(def.report)) throw new Error(`${this.file}: property ${def.code} has report ${def.report} (named, always, never or NULL)`); this.catalog.set(def.code, def); this.propsById.set(def.id, def); } From 22e30f6b8f115dfc77ac1b5e6d72bad9089f649b Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 17:00:47 -0600 Subject: [PATCH 09/90] sqlite-v2: remove the dead readBehaviour body; lint The old readBehaviour body was left below the new one and, being declared later, replaced it: the exported function referred to a table that no longer exists. A test now calls the export. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 10 +++++++++- tx/sqlite-v2/store.js | 17 ----------------- 2 files changed, 9 insertions(+), 18 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 1cf9cd8d3..a1bb35325 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -100,6 +100,14 @@ describe('P1. meta: requires, known keys checked, unknown keys ignored', () => { expect(() => b2.finish()).toThrow(/meta behaviour.expansionOrdre is not a key this builder knows/); }); + test('readBehaviour (exported): every behaviour key with its default, the file\'s values, a malformed one refused', () => { + const { readBehaviour } = require('../../tx/sqlite-v2/store'); + const b = readBehaviour([['behaviour.expansionOrder', '"stored"'], ['behaviour.unknown', 'x']], 'f'); + expect(b).toMatchObject({ expansionOrder: 'stored', lookupName: 'name', grammar: null, expansionLimit: 0 }); + expect(b.unknown).toBeUndefined(); + expect(() => readBehaviour([['behaviour.lookupName', '"nick"']], 'f')).toThrow(/behaviour.lookupName = "nick" is not a value/); + }); + test('provenance.* is free-form', () => { const b = new TerminologyBuilder(path.join(dir, 'prov.db'), { overwrite: true, importer: 'test' }); b.codeSystem({ uri: 'http://example.org/x', version: '1' }); @@ -431,7 +439,7 @@ describe('P5. grammar: an open string, implemented by name; behaviour.filters ap describe('P6. contracts checked by the builder; the CodeSystem columns kept; cheap id checks at open', () => { const { checkContracts } = require('../../tx/importers/sqlite-v2/builder'); let base; - beforeAll(() => { base = fixture((b, c) => b.setMeta('ix.ix_word.names', { items: {}, counts: true })); }); + beforeAll(() => { base = fixture((b) => b.setMeta('ix.ix_word.names', { items: {}, counts: true })); }); /** a writable copy changed by sql, its contracts checked */ const broken = (sql, ...args) => { const f = path.join(dir, `c${++seq}.db`); diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 0e3be6587..12d8e1805 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -89,23 +89,6 @@ function readBehaviour(meta, file) { const FILTER_OPS = new Set(FILTER_OPERATORS); const REPORT = new Set([null, 'named', 'always', 'never']); -/** meta behaviour.* -> settings object (every key, defaults filled); throws on an unknown key or value */ -function readBehaviour(meta, file) { - const out = {}; - for (const [k, d] of Object.entries(BEHAVIOUR)) out[k] = d.default; - for (const [key, raw] of meta) { - if (!key.startsWith('behaviour.')) continue; - const k = key.substring('behaviour.'.length); - const d = BEHAVIOUR[k]; - if (!d) throw new Error(`${file}: unknown behaviour setting ${key} (this server knows ${Object.keys(BEHAVIOUR).join(', ')})`); - let v; - try { v = JSON.parse(raw); } catch (e) { throw new Error(`${file}: ${key} is not JSON: ${raw}`); } - if (d.values ? !d.values.includes(v) : !d.check(v)) throw new Error(`${file}: ${key} = ${raw} is not a value this server knows`); - out[k] = v; - } - return Object.freeze(out); -} - const NODE_SHAPES = new Set(['link', 'union']); const FILTER_SHAPES = new Set(['link', 'literal', 'both', 'union']); const VK = { none: 0, node: 1, literal: 2 }; From 3f5467fd62e586caf00ae65c944564dd2930c2bd Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 17:01:28 -0600 Subject: [PATCH 10/90] sqlite-v2: $expand of a file with behaviour.expansionLimit Through the real $expand: the codes up to the cap, the total all of the system's codes, and the expansion-issue VALUESET_EXPANSION_CODESYSTEM_LIMITED when the page asked for was cut short, as expand.js does for any provider whose expandLimitation() is set. Co-Authored-By: Claude --- tests/tx/sqlite-v2-expansion-limit.test.js | 77 ++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 tests/tx/sqlite-v2-expansion-limit.test.js 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 000000000..55dcaa6d6 --- /dev/null +++ b/tests/tx/sqlite-v2-expansion-limit.test.js @@ -0,0 +1,77 @@ +'use strict'; + +// behaviour.expansionLimit 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.setBehaviour('expansionLimit', 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']); +}); From 7a9e1f588d1ca569273f0e164035fce4d2a77f88 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 17:04:43 -0600 Subject: [PATCH 11/90] sqlite-v2 RxNorm: which properties $lookup reports is catalog data The RxNorm importer writes property.report: never on SUPPRESS and on the storage codes (@REL, RELA@REL), named on the relationships. The RxNorm adapter reads the catalog; the code rule it replaces applies only to a file whose catalog has no report value there (built before), and gives the same answers (tested on one fixture both ways). report 'named' now means: by name or *, not by default, which is what the RxNorm relationships and SNOMED CT's named-only properties need. The format document states the absent ix.ix_word.names rule as a compatibility rule for files built before the key; a test checks that node indexes.js on such a file writes the key from the legacy table. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 88 +++++++++++++++++++++++- tx/importers/import-rxnorm-v2.module.js | 16 +++-- tx/sqlite-v2/README.md | 15 ++-- tx/sqlite-v2/provider.js | 26 ++++--- 4 files changed, 122 insertions(+), 23 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index a1bb35325..dfcbd623e 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -214,6 +214,21 @@ describe('P3. word index: the names selection as data, stemmers per language, li expect(names(legacy)).toEqual(names(sct)); }); + test('rebuilding the indexes of a file built before ix.ix_word.names (node indexes.js) writes the key from the legacy table', () => { + const { spawnSync } = require('child_process'); + const sct = fixture((b) => b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }), { uri: 'http://snomed.info/sct' }); + const old = withMeta(sct, { 'ix.ix_word.names': null, 'ix.ix_word.stemmers': null }); + const before = names(old); + const r = spawnSync(process.execPath, [path.join(__dirname, '../../tx/importers/sqlite-v2/indexes.js'), old], { encoding: 'utf8' }); + expect(r.status).toBe(0); + const db = new Database(old, { readonly: true }); + try { + expect(JSON.parse(db.prepare("SELECT value FROM meta WHERE key = 'ix.ix_word.names'").pluck().get())).toEqual(ti.LEGACY_NAMES['http://snomed.info/sct']); + expect(db.prepare("SELECT value FROM meta WHERE key = 'ix.ix_word.stemmers'").pluck().get()).not.toBeNull(); + } finally { db.close(); } + expect(names(old)).toEqual(before); + }); + test('the index builder writes the selection, the stemmer of each language, and the counts row little-endian (2 * (N + 1) bytes)', () => { const f = rich({ items: { active: true, designations: true }, counts: true }); const db = new Database(f, { readonly: true }); @@ -597,10 +612,11 @@ describe('P8. property.report never / named / always; behaviour.expansionLimit', expect(f.engine.evaluate(new Compiler({ store: f.store, dialect: {} }).filter('kind', '=', 'product')).size).toBe(1); }); - test('named: only when the request names it; always: by default and on every expansion', async () => { + test('named: only when the request names it or asks for *, not by default; always: by default and on every expansion', async () => { expect(await lookup([])).not.toContain('note'); - expect(await lookup(['*'])).not.toContain('note'); + expect(await lookup(['*'])).toContain('note'); expect(await lookup(['note'])).toContain('note'); + expect(await lookup(['class'])).not.toContain('note'); expect(await lookup([])).toContain('class'); expect(p.mandatoryExpansionProperties()).toEqual(['class']); }); @@ -632,3 +648,71 @@ describe('P8b. an expansion of a system with expansionLimit takes the path that } }); }); + +describe('P8. RxNorm: which properties $lookup reports is catalog data (report), with the same answers as the rule it replaces', () => { + const { importRxNormV2 } = require('../../tx/importers/import-rxnorm-v2.module'); + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const conso = (cui, aui, sab, tty, str, sup = 'N') => [cui, 'ENG', '', '', '', '', '', aui, '', '', '', sab, tty, cui, str, '', sup, ''].join('|') + '|'; + const cuiRel = (cui1, rel, cui2, rela) => [cui1, '', 'CUI', rel, cui2, '', 'CUI', rela, '', '', 'RXNORM', '', '', '', 'N', ''].join('|') + '|'; + let op, file, legacy; + beforeAll(async () => { + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const rrf = path.join(dir, 'rrf'); + fs.mkdirSync(rrf, { recursive: true }); + fs.writeFileSync(path.join(rrf, 'RXNCONSO.RRF'), [conso('100', '1001', 'RXNORM', 'SCD', 'drug a 10 MG Oral Tablet'), conso('100', '1004', 'RXNORM', 'SY', 'drug a tablet'), + conso('200', '2001', 'RXNORM', 'IN', 'ingredient b'), conso('300', '3001', 'RXNORM', 'SBD', 'brand c 10 MG Oral Tablet')].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNREL.RRF'), [cuiRel('200', 'RO', '100', 'has_ingredient'), cuiRel('100', 'RB', '300', 'tradename_of'), + cuiRel('300', 'RN', '100', ''), cuiRel('100', 'RO', '200', 'ingredient_of'), cuiRel('100', 'RB', '200', 'ingredient_of')].join('\n') + '\n'); + fs.writeFileSync(path.join(rrf, 'RXNSTY.RRF'), ['100|T200|||A|', '200|T121|||A|', '300|T200|||A|'].join('\n') + '\n'); + file = path.join(dir, 'rx.db'); + await importRxNormV2({ source: rrf, dest: file, version: '01012026', overwrite: true, log: () => {} }); + // the same file as built before the importer wrote report + legacy = path.join(dir, 'rx-legacy.db'); + fs.copyFileSync(file, legacy); + const w = new Database(legacy); + w.exec('UPDATE property SET report = NULL'); + w.close(); + }); + const lookups = async (f) => { + const fac = new SqliteV2Factory(op.i18n, f); + await fac.load(); + try { + const p = await fac.build(op, []); + const out = {}; + for (const code of ['100', '200', '300']) { + for (const props of [[], ['*'], ['TTY'], ['SUPPRESS'], ['ingredient_of'], ['RB', 'tradename_of'], ['ingredient_of@RO']]) { + const params = []; + await p.extendLookup((await p.locate(code)).context, props, params); + out[code + ' ' + props.join(',')] = params.map((x) => x.part.map((y) => y.valueCode || y.valueString).join('=')); + } + } + return out; + } finally { fac.store.close(); } + }; + + test('the importer writes never on SUPPRESS and the @ codes, named on the relationships', () => { + const db = new Database(file, { readonly: true }); + try { + const r = Object.fromEntries(db.prepare('SELECT code, report FROM property').raw().all()); + expect(r.SUPPRESS).toBe('never'); + expect(r.TTY).toBeNull(); + expect(r.has_ingredient).toBe('named'); + expect(r.RO).toBe('named'); + expect(Object.entries(r).filter(([c]) => c.includes('@')).every(([, v]) => v === 'never')).toBe(true); + expect(Object.keys(r).some((c) => c.includes('@'))).toBe(true); + } finally { db.close(); } + }); + + test('$lookup answers from the catalog equal the answers of the code rule on a file without report values', async () => { + const a = await lookups(file); + expect(a).toEqual(await lookups(legacy)); + expect(a['100 ']).toEqual(['TTY=SCD', 'TTY=SY', 'STY=T200', 'SAB=RXNORM']); + expect(a['200 *']).toEqual(['TTY=IN', 'STY=T121', 'SAB=RXNORM', 'ingredient_of=100']); + expect(a['200 ']).toEqual(['TTY=IN', 'STY=T121', 'SAB=RXNORM']); + expect(a['100 SUPPRESS']).toEqual([]); + expect(a['200 ingredient_of@RO']).toEqual([]); + expect(a['300 RB,tradename_of']).toEqual(['tradename_of=100']); + }); +}); diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 1bedd7535..3cfcd12fa 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -73,8 +73,9 @@ async function importRxNormV2(cfg) { 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 }), + // RXNCONSO concepts (the live domain), and it has no property = value sets; $lookup never reports + // it (report 'never': cs-rxnorm.js has no such property) + const TTY = lit('TTY', 'Term Type'), SAB = lit('SAB', 'Source'), SUPPRESS = lit('SUPPRESS', 'Suppress flag', { filterable: false, filterOps: null, report: 'never' }), 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; }; @@ -159,15 +160,18 @@ 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 }); + // $lookup reports a relationship only when the request asks for properties (report 'named', as + // cs-rxnorm.js: by name or *, never by default) + const relProp = (rel) => b.property({ code: rel, uri: `${RXNORM}/${rel}`, shape: 'link', display: rel, wildcard: false, filterOps: EQ_IN, report: 'named' }); + const relaProp = (rela) => b.property({ code: rela, uri: `${RXNORM}/${rela}`, shape: 'link', display: rela, wildcard: true, filterOps: EQ_IN, report: 'named' }); // 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, filterable: false, report: 'never' }); b.propertyMember(relProp(rel), p); noRelaOf.set(rel, p); } @@ -244,7 +248,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, filterable: false, report: 'never' }); qualified.set(code, q); } b.link(relRows[k], q, relRows[k + 1]); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 2f1d1b1b0..e4008f3e5 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -216,8 +216,9 @@ Per property: `filter_ops` (JSON list of the operators a filter on it accepts; R and the relationships: `=`, `in`) and `report`, when `$lookup` and expansions report it: `never` (not by `$lookup`, asked for or not, nor on expansions, nor among the declared properties: a filter only where `filterable = 1`, hidden altogether where not), `named` (`$lookup` returns it only when the -request names it; `*` does not), `always` (also on every expansion row), NULL (the default: `$lookup` -reports it by default and when asked for). None of SNOMED CT, LOINC, RxNorm sets it; ICD-11 files set +request names it or asks for `*`, not by default), `always` (also on every expansion row), NULL (the default: `$lookup` +reports it by default and when asked for). RxNorm files set `never` on SUPPRESS and the `@` storage codes and `named` on the relationships (a file built +before has none there; the JS reader's RxNorm adapter then applies the rule they state); ICD-11 files set `named` on `child`, `browserUrl` and `residual`, and `always` on `classificationCode` in MMS and ICF; NDC files `named` on `kind`. A filter-only property is `never` with `filterable = 1`: one value, as filterability is the separate `filterable` column. @@ -252,10 +253,12 @@ write: | LOINC | `{"display": "en", "items": {"excludeUses": ["RELATEDNAMES2"]}}` | | RxNorm | `{"items": {"conceptsWith": "SUPPRESS", "language": "en"}}` | -A file without the key was written before it existed: a reader uses the selection above for the -file's system (SNOMED CT, LOINC, RxNorm; `LEGACY_NAMES` in `text-index.js`, the one table of systems -for this), and no names for any other. The index builder keeps the key across a rebuild, and writes -it from that table when it rebuilds such a file. +Compatibility rule for files built before `ix.ix_word.names` existed (and only for them; every file +the builder writes now has the key): a reader treats a file without the key as holding the selection +above for its system (SNOMED CT, LOINC, RxNorm: `LEGACY_NAMES` in `text-index.js`, the one table of +systems for this), and no names for any other system. Rebuilding such a file's indexes (`node +indexes.js `) writes the key from that table, so the rebuilt file states its names and the +table is not consulted for it again. The index builder keeps the key across later rebuilds. `ix.ix_word.stemmers`: for each language of the word index, the stemmer that made its `stem` column, an open string: `none` (a word is its own stem), `natural:` (a stemmer class of the `natural` diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 9d4596f38..be1ec8074 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -122,14 +122,14 @@ class SqliteV2Provider extends BaseCSServices { /** * Whether a lookup (or an expansion's properties) reports a catalog property (report: 'never' not - * at all, 'named' only when the request names it, else as the request's list says; dflt: whether - * an empty list reports it) + * at all, 'named' only when the request names it or asks for *, not by default; else as the + * request's list says; dflt: whether an empty list reports it) */ _reports(code, props, dflt = true) { const d = this.store.catalog.get(code); const report = d ? d.report : null; if (report === 'never') return false; - if (report === 'named') return !!(props && props.some((p) => String(p).toLowerCase() === String(code).toLowerCase())); + if (report === 'named') return this._hasProp(props, code, false); return this._hasProp(props, code, dflt); } sourcePackage() { return null; } @@ -752,18 +752,26 @@ class SqliteV2Provider extends BaseCSServices { _rxnormLookup(c, props, params) { const S = this.store; const st = this._stats(); + // which properties are reported is catalog data (property.report: SUPPRESS and the `@` storage + // codes 'never', the relationships 'named'); a file built before the importer wrote report has + // none there, and gets the same answer from the rule it stood for + const legacy = S.catalog.has('SUPPRESS') && S.catalog.get('SUPPRESS').report == null; + const hidden = (code) => (legacy ? code === 'SUPPRESS' || code.includes('@') : (S.catalog.get(code) || {}).report === 'never'); 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)); + if (p && !hidden(p.code)) (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']) { + // cs-rxnorm.js's order: TTY, STY, SAB, then any other + const ORDER = ['TTY', 'STY', 'SAB']; + const pos = (n) => { const i = ORDER.indexOf(n); return i < 0 ? ORDER.length : i; }; + for (const name of [...lits.keys()].sort((a, b) => pos(a) - pos(b) || asText(a, b))) { if (!this._reports(name, props, true)) continue; - for (const v of [...(lits.get(name) || [])].sort(asText)) this._addCodeProperty(params, 'property', name, v); + 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('@'); }); + if (legacy && !(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 && !hidden(p.code); }); 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); @@ -772,7 +780,7 @@ class SqliteV2Provider extends BaseCSServices { 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._reports(name, props, false)) continue; + if (!t || seen.has(name + '|' + t.code) || !this._reports(name, props, !legacy)) continue; seen.add(name + '|' + t.code); named.push({ name, code: t.code }); } From f2b6703518c864d11a9786b561bc672aa8b05e8f Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 18:14:21 -0600 Subject: [PATCH 12/90] sqlite-v2: remove behaviour.description No answer reads a provider's description(): the key chose a value nothing consumed. It leaves the reader's list of keys, the LOINC importer and the format document; a file that still carries it has an unknown key, ignored. description() returns code_system.description, else the title. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 15 ++++++++++----- tx/importers/import-loinc-v2.module.js | 1 - tx/sqlite-v2/README.md | 1 - tx/sqlite-v2/meta.js | 1 - tx/sqlite-v2/provider.js | 5 +++-- 5 files changed, 13 insertions(+), 10 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index dfcbd623e..fd2b56c02 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -321,9 +321,8 @@ describe('P4. behaviour and order keys: the file\'s value obeyed, absent = the d return params.map((x) => x.part.find((y) => y.name === 'code').valueCode + '=' + (x.part.find((y) => y.name === 'value').valueCode || x.part.find((y) => y.name === 'value').valueString)); }; - test('defaults: description the title, lookupName the name, versionAlgorithm none, every use kept, every text', async () => { + test('defaults: lookupName the name, versionAlgorithm none, every use kept, every text', async () => { const { f, p } = await provider(base); - expect(f.description()).toBe('The Example System'); expect(p.lookupName()).toBe('Example'); expect(p.versionAlgorithm()).toBeNull(); expect(await designations(p, 'B')).toEqual([['banana tree', 'syn'], ['banana tree', 'syn']]); @@ -331,9 +330,15 @@ describe('P4. behaviour and order keys: the file\'s value obeyed, absent = the d expect(f.engine._order).toBeFalsy(); }); - test('lookupName, description, versionAlgorithm', async () => { - const { f, p } = await provider(withMeta(base, { 'behaviour.lookupName': '"title"', 'behaviour.description': '"name"', 'behaviour.versionAlgorithm': '"semver"' })); - expect(f.description()).toBe('Example'); + test('behaviour.description is not a key (no answer reads it): a file carrying it is served, the key ignored', () => { + const f = withMeta(base, { 'behaviour.description': '"name"' }); + withStore(f, (S) => expect(S.behaviour.description).toBeUndefined()); + const db = new Database(f, { readonly: true }); + try { expect(readMeta(db.prepare('SELECT key, value FROM meta').raw().all(), f).ignored).toEqual(['behaviour.description']); } finally { db.close(); } + }); + + test('lookupName, versionAlgorithm', async () => { + const { p } = await provider(withMeta(base, { 'behaviour.lookupName': '"title"', 'behaviour.versionAlgorithm': '"semver"' })); expect(p.lookupName()).toBe('The Example System'); expect(p.versionAlgorithm()).toBe('semver'); // with meta titles: the title of the first requested language that has one diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 7aca4ed11..30e44ab28 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -179,7 +179,6 @@ function loincCodeSystem(b, version, description) { // title, the description the name, versions compared naturally b.setBehaviour('expansionOrder', 'stored'); b.setBehaviour('lookupName', 'title'); - b.setBehaviour('description', 'name'); b.setBehaviour('versionAlgorithm', 'natural'); // text search reads the display (English) and every name but RELATEDNAMES2 b.setMeta('ix.ix_word.names', { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index e4008f3e5..1f0dad654 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -183,7 +183,6 @@ refused (the builders check the same at build). | `grammar` | a grammar name (an open string), `null` | `null` (plain codes) | the grammar of the system's codes. A reader holds its implementations by name and refuses a file whose grammar it does not implement ("its codes are in the grammar X, which this server does not implement"); there is no fallback by system URI. Names in use: `"snomed"` (SNOMED CT expressions and ECL; the JS reader's SNOMED CT provider, `index.js` `GRAMMARS`), `"icd11"` (ICD-11 MMS and ICF files: postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records), and a code system whose codes carry modifiers. The JS reader implements `snomed` only | | `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"` | the name `$lookup` reports: `code_system.name` (no name: the system URI), or the title (below; no title: the name). LOINC `"title"` | -| `description` | `"name"`, `"title"` | `"title"` | the description a server gives the code system (its catalog entry): `code_system.title` (no title: the name), or `code_system.name`. LOINC `"name"` | | `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm, used to match a requested version. SNOMED CT `"url"`, LOINC `"natural"`, RxNorm `"date"` | | `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index e4e7d2b8a..2bc9763c4 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -86,7 +86,6 @@ const KEYS = Object.freeze({ 'behaviour.filters': json((v) => v === null || (Array.isArray(v) && v.every(isFilterSpec)), null), 'behaviour.expansionOrder': json((v) => ['ids', 'stored', 'stored-self-first'].includes(v), 'ids'), 'behaviour.lookupName': json((v) => v === 'name' || v === 'title', 'name'), - 'behaviour.description': json((v) => v === 'name' || v === 'title', 'title'), 'behaviour.versionAlgorithm': json((v) => v === null || isString(v), null), 'behaviour.designationUses': json((v) => v === 'keep' || v === 'drop', 'keep'), 'behaviour.distinctDesignationTexts': json(isBool, false), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index be1ec8074..9a85cb652 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1443,7 +1443,7 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { version() { return this.store.version; } defaultVersion() { return this.store.version; } name() { return this.store.cs.name || this.store.system; } - // behaviour.description / lookupName: code_system.name or code_system.title (a title of the + // behaviour.lookupName: code_system.name or code_system.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) { @@ -1458,7 +1458,8 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { } return this.store.cs.title || this._csName(); } - description() { return this.store.behaviour.description === 'name' ? this._csName() : this._csTitle(); } + // (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.behaviour.lookupName === 'title' ? this._csTitle(langs) : this._csName(); } defLang() { return 'en'; } /** From 6238914bc3d20dfcba1705a1d6a99836491b191e Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 18:15:55 -0600 Subject: [PATCH 13/90] sqlite-v2: behaviour.lookupDesignationCode A property code (default null): $lookup lists each designation that has a literal of that item property again, coded by the literal's value, with its text and language. A few lines in the generic $lookup. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 37 ++++++++++++++++++++++++ tx/sqlite-v2/README.md | 1 + tx/sqlite-v2/meta.js | 1 + tx/sqlite-v2/provider.js | 22 ++++++++++++++ 4 files changed, 61 insertions(+) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index fd2b56c02..3a5229465 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -721,3 +721,40 @@ describe('P8. RxNorm: which properties $lookup reports is catalog data (report), expect(a['300 RB,tradename_of']).toEqual(['tradename_of=100']); }); }); + +describe('behaviour.lookupDesignationCode: each designation again, coded by an item literal', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + let op; + beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); + const build = (set) => fixture((b, c) => { + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'code', filterable: false, report: 'never' }); + b.literal(b.item(c.C, { language: 'en', use: { system: 'u', code: 'short' }, text: 'cherry' }), kind, 'short'); + b.literal(b.item(c.C, { language: 'en', use: { system: 'u', code: 'long' }, text: 'a cherry tree' }), kind, 'long'); + b.item(c.C, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'no kind' }); + if (set) b.setBehaviour('lookupDesignationCode', 'kind'); + }); + const lookup = async (file, props) => { + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + const p = await f.build(op, []); + const params = []; + await p.extendLookup((await p.locate('C')).context, props, params); + return params.filter((x) => x.name === 'designation').map((x) => x.part.map((y) => y.valueCode || y.valueString).join('|')); + } finally { f.store.close(); } + }; + + test('set: the designations with the literal, coded by its value, by default and when designation is asked for', async () => { + const f = build(true); + expect(await lookup(f, [])).toEqual(['short|cherry|en', 'long|a cherry tree|en']); + expect(await lookup(f, ['designation'])).toEqual(['short|cherry|en', 'long|a cherry tree|en']); + expect(await lookup(f, ['parent'])).toEqual([]); + }); + + test('absent (default null): none', async () => { + expect(await lookup(build(false), [])).toEqual([]); + expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '3' }))).toThrow(/lookupDesignationCode = 3 is not a value/); + }); +}); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 1f0dad654..333f6d81d 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -192,6 +192,7 @@ refused (the builders check the same at build). | `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 | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | +| `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A property not in the catalog lists nothing | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | Release facts in `meta` that a reader also presents: `titles` (JSON object, language -> the system's diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 2bc9763c4..90c2483d8 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -95,6 +95,7 @@ const KEYS = Object.freeze({ 'behaviour.preferredForLanguage': json(isBool, false), 'behaviour.aliasLiterals': json((v) => isPlainObject(v) && Object.values(v).every(isString), {}), 'behaviour.expansionLimit': json(isCount, 0), + 'behaviour.lookupDesignationCode': json((v) => v === null || (isString(v) && v !== ''), null), }); /** key patterns this reader knows (one entry per family): [test, spec] */ diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 9a85cb652..46fe4b122 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -866,6 +866,28 @@ class SqliteV2Provider extends BaseCSServices { const p = S.propsById.get(r.p); if (p && this._reports(p.code, props, true)) this._addStringProperty(params, 'property', p.code, String(r.v)); } + this._designationCodes(c, props, params); + } + + /** + * behaviour.lookupDesignationCode (a property of items): $lookup lists each designation that has + * a literal of that property again, as a designation whose code is the literal's value (with its + * text and language), when the request lists designations (by default, or 'designation' named) + */ + _designationCodes(c, props, params) { + const S = this.store; + const code = S.behaviour.lookupDesignationCode; + const p = code != null ? S.catalog.get(code) : null; + if (!p || !this._hasProp(props, 'designation', true)) return; + const st = this._stats(); + const items = S.designationRows([c.id], st).get(c.id) || []; + const value = new Map(); + for (const r of S.literalsOf(items.map((d) => d.id), true, st)) if (r.p === p.id && !value.has(r.c)) value.set(r.c, String(r.v)); + for (const d of items) { + if (!value.has(d.id)) continue; + params.push({ name: 'designation', part: [{ name: 'code', valueCode: value.get(d.id) }, { name: 'value', valueString: d.term }, + { name: 'language', valueCode: d.language || this.defLang() }] }); + } } // ---- filters -------------------------------------------------------------------------------- From 33515576f6851520a2d3093f2ac1aa760b7a80cb Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 18:18:23 -0600 Subject: [PATCH 14/90] sqlite-v2: lookupCopyright; contracts for requires and the word-index names behaviour.lookupCopyright (default false): $lookup lists code_system.resource.copyright as a copyright property; a file that sets it without a copyright is refused. The builder's contracts now also require meta requires (not for node indexes.js on a file built before it) and ix.ix_word.names wherever there is a word index. A builder accepts ix.ix_key..stats for any index name. These bring the JS side in line with the other reader of the format. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 23 +++++++++++++++++++++++ tx/importers/sqlite-v2/builder.js | 9 ++++++--- tx/importers/sqlite-v2/indexes.js | 5 +++-- tx/sqlite-v2/README.md | 3 ++- tx/sqlite-v2/meta.js | 10 +++++----- tx/sqlite-v2/provider.js | 8 +++++--- tx/sqlite-v2/store.js | 8 ++++++++ 7 files changed, 52 insertions(+), 14 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 3a5229465..0756b9422 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -485,6 +485,8 @@ describe('P6. contracts checked by the builder; the CodeSystem columns kept; che 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("INSERT OR REPLACE INTO meta VALUES ('behaviour.expansionOrder', '\"stored\"')")).toThrow(/contract: behaviour.expansionOrder "stored" without ix_order rank and ids/); expect(broken('DROP INDEX item_concept')).toThrow(/contract: the index item_concept is missing/); + expect(broken("DELETE FROM meta WHERE key = 'requires'")).toThrow(/contract: meta requires is missing/); + expect(broken("DELETE FROM meta WHERE key = 'ix.ix_word.names'")).toThrow(/contract: the word index has no meta ix.ix_word.names/); expect(broken('ANALYZE')).toThrow(/contract: sqlite_stat4 is present/); }); @@ -758,3 +760,24 @@ describe('behaviour.lookupDesignationCode: each designation again, coded by an i expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '3' }))).toThrow(/lookupDesignationCode = 3 is not a value/); }); }); + +describe('behaviour.lookupCopyright', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + test('$lookup lists the resource\'s copyright as a property; set without one, the file is refused; absent, none', async () => { + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const withCopyright = fixture((b) => { b.systems[0].resource = { resourceType: 'CodeSystem', copyright: 'A synthetic notice' }; b.setBehaviour('lookupCopyright', true); }); + const f = new SqliteV2Factory(op.i18n, withCopyright); + await f.load(); + try { + const p = await f.build(op, []); + const params = []; + await p.extendLookup((await p.locate('A')).context, [], params); + const cr = params.filter((x) => x.part[0].valueCode === 'copyright').map((x) => x.part[1].valueString); + expect(cr).toEqual(['A synthetic notice']); + } finally { f.store.close(); } + expect(() => openStore(withMeta(fixture(), { 'behaviour.lookupCopyright': 'true' }))).toThrow(/lookupCopyright without code_system.resource.copyright/); + withStore(fixture(), (S) => expect(S.copyright).toBeNull()); + }); +}); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index f9a59a30a..afd884453 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -622,9 +622,9 @@ function vacuumFile(file) { * 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) { +function finishFile(db, file = db.name, opts = {}) { db.exec('DROP TABLE IF EXISTS sqlite_stat4'); - checkContracts(db); + checkContracts(db, opts); // 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 }); @@ -642,7 +642,7 @@ function schemaIndexes() { * 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) { +function checkContracts(db, opts = {}) { 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(); @@ -707,6 +707,9 @@ function checkContracts(db) { // a stored expansion order (behaviour.expansionOrder 'stored' / 'stored-self-first') has its arrays const eo = one("SELECT value FROM main.meta WHERE key = 'behaviour.expansionOrder'"); if (eo != null && JSON.parse(eo) !== 'ids' && !(arrays.has('rank') && arrays.has('ids'))) fail(`behaviour.expansionOrder ${eo} without ix_order rank and ids`); + // meta requires is stated; a word index states its names + if (!opts.olderFile && one("SELECT count(*) FROM main.meta WHERE key = 'requires'") !== 1) fail('meta requires is missing'); + if (langs.length && one("SELECT count(*) FROM main.meta WHERE key = 'ix.ix_word.names'") !== 1) fail('the word index has no meta ix.ix_word.names'); // 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); diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index d11bcc6b3..8567306b8 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -347,8 +347,9 @@ if (require.main === module) { 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; } }); const { analyze, finishFile } = require('./builder'); analyze(db); - // the contracts and the meta keys, as the builder checks a file it finishes - finishFile(db, file); + // the contracts and the meta keys, as the builder checks a file it finishes (a file built before + // meta requires existed keeps its identifier typing and has no requires: olderFile) + finishFile(db, file, { olderFile: !db.prepare("SELECT 1 FROM main.meta WHERE key = 'requires'").get() }); console.log(JSON.stringify({ seconds: (Date.now() - t0) / 1000, ...s })); } db.close(); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 333f6d81d..ad1e7cc1b 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -98,7 +98,7 @@ after a rebuild); `verify.js` checks them on request. | `behaviour.expansionOrder` other than `ids`: `ix_order` has `rank` and `ids` | yes | | the `ix_word` counts rows are `2 * (N + 1)` bytes; every `ix_word` 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 | -| meta follows "Meta" (every key one the builder knows, every value well-formed) | yes | +| meta follows "Meta" (every key one the builder knows, every value well-formed); `requires` is stated; a word index has its `ix.ix_word.names` | yes (`node indexes.js` on a file built before `requires` existed skips the `requires` check) | | record `fields` is a JSON array in the order of the relation's non-target fields | stated (a check would parse every record row) | The JS reader checks the id ranges it relies on at open (an id up to N is a concept, above N an @@ -191,6 +191,7 @@ refused (the builders check the same at build). | `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 | +| `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A property not in the catalog lists nothing | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 90c2483d8..6cecc8c05 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -95,6 +95,7 @@ const KEYS = Object.freeze({ 'behaviour.preferredForLanguage': json(isBool, false), 'behaviour.aliasLiterals': json((v) => isPlainObject(v) && Object.values(v).every(isString), {}), 'behaviour.expansionLimit': json(isCount, 0), + 'behaviour.lookupCopyright': json(isBool, false), 'behaviour.lookupDesignationCode': json((v) => v === null || (isString(v) && v !== ''), null), }); @@ -105,10 +106,9 @@ const KEY_PATTERNS = Object.freeze([ ]); /** keys a builder of this repository writes that no reader reads (informational) */ -const WRITER_KEYS = Object.freeze({ - // SNOMED CT normal forms written by the importer (sct-v2-common.js) - 'ix.ix_key.normalForm.stats': json(isPlainObject, null), -}); +const WRITER_KEYS = Object.freeze({}); +/** key patterns of the same kind: statistics of an ix_key index an importer writes (SNOMED CT normal forms) */ +const WRITER_PATTERNS = Object.freeze([[(k) => /^ix\.ix_key\.[^.]+\.stats$/.test(k), json(isPlainObject, null)]]); const isProvenance = (key) => key.startsWith('provenance.'); @@ -134,7 +134,7 @@ function readMeta(meta, file, opts = {}) { const ignored = []; for (const [key, raw] of meta) { if (isProvenance(key)) continue; - const spec = specOf(key) || (opts.writer ? WRITER_KEYS[key] : null); + 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); diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 46fe4b122..c5e36aad6 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -654,9 +654,11 @@ class SqliteV2Provider extends BaseCSServices { 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); + if (this.dialect.name === 'loinc') this._loincLookup(c, props, params); + else if (this.dialect.name === 'rxnorm') this._rxnormLookup(c, props, params); + else this._genericLookup(c, props, params); + // behaviour.lookupCopyright: the code system's copyright notice as a property + if (this.store.copyright != null) this._addStringProperty(params, 'property', 'copyright', this.store.copyright); } _targetDisplays(ids) { diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 12d8e1805..35d436cd0 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -340,6 +340,14 @@ class Store { for (const k of ['aliasProperty', 'aliasExtension']) { if (m.behaviour[k] !== null) throw new Error(`${this.file}: behaviour.${k} is set (identifier-aliased codes), which this server does not implement`); } + // behaviour.lookupCopyright: the notice $lookup lists (code_system.resource.copyright) + this.copyright = null; + if (m.behaviour.lookupCopyright) { + 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}: behaviour.lookupCopyright without code_system.resource.copyright`); + this.copyright = r.copyright; + } if (Object.keys(m.behaviour.aliasLiterals).length) throw new Error(`${this.file}: behaviour.aliasLiterals is set (identifier-aliased codes), which this server does not implement`); // a compositional system's expansions are never closed (post-coordinated expressions are codes) this.notClosed = cs.compositional === 1; From 2217d4e4e715707e52d1b7584466c733f8e561d5 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 18:18:23 -0600 Subject: [PATCH 15/90] sqlite-v2 README: versionAlgorithm's meaning and default null means no algorithm is stated: the version string decides how a requested version matches, with no rule of the reader's own for a system; the SNOMED CT importer writes "url". Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index ad1e7cc1b..d7bce53d2 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -183,7 +183,7 @@ refused (the builders check the same at build). | `grammar` | a grammar name (an open string), `null` | `null` (plain codes) | the grammar of the system's codes. A reader holds its implementations by name and refuses a file whose grammar it does not implement ("its codes are in the grammar X, which this server does not implement"); there is no fallback by system URI. Names in use: `"snomed"` (SNOMED CT expressions and ECL; the JS reader's SNOMED CT provider, `index.js` `GRAMMARS`), `"icd11"` (ICD-11 MMS and ICF files: postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records), and a code system whose codes carry modifiers. The JS reader implements `snomed` only | | `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"` | the name `$lookup` reports: `code_system.name` (no name: the system URI), or the title (below; no title: the name). LOINC `"title"` | -| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm, used to match a requested version. SNOMED CT `"url"`, LOINC `"natural"`, RxNorm `"date"` | +| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm: how a requested version matches the file's version (`semver` with wildcards, `integer` exactly, anything else by prefix). `null`: none stated; a reader guesses the algorithm from the version string (FHIRsmith `guessVersionFormat`), with no rule of its own for a system. SNOMED CT `"url"` (versions are URIs, matched by prefix), LOINC `"natural"`, RxNorm `"date"` | | `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | | `lookupSkipsMixedLinks` | `true`, `false` | `false` | SNOMED CT `true`: a `both` attribute's links are not read where no property is named (main keeps one value kind per attribute) | From 83fdf385be0cbddcc047766bb9d868de5f17835c Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 18:18:33 -0600 Subject: [PATCH 16/90] sqlite-v2 tests: the values both readers agree on searchTieBreak other than rank refused; a file without ix.ix_word.stemmers read with this reader's stemmers (the stored index used). Unknown fields in ix.ix_word.names, linkOrder values and report named (by name or *) were covered already. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 0756b9422..5e2ab409f 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -273,6 +273,8 @@ describe('P3. word index: the names selection as data, stemmers per language, li }); // the file's own stemmers: the stored index for every language withStore(f, (S) => expect(ti.textIndexOf(S)).toBeInstanceOf(ti.WordIndex)); + // no ix.ix_word.stemmers (a file built before the key): this reader's own stemmers, the stored index used + withStore(withMeta(f, { 'ix.ix_word.stemmers': null }), (S) => expect(ti.textIndexOf(S)).toBeInstanceOf(ti.WordIndex)); }); test('a malformed selection is refused', () => { @@ -379,6 +381,7 @@ describe('P4. behaviour and order keys: the file\'s value obeyed, absent = the d expect(await order('property-seq')).toEqual(['site=C', 'site=root', 'site=B', 'area=B']); expect(await order('target-int')).toEqual(['site=C', 'area=B', 'site=root', 'site=B']); expect(() => openStore(withMeta(base, { linkOrder: 'random' }))).toThrow(/meta linkOrder = random is not a value/); + expect(() => openStore(withMeta(base, { searchTieBreak: 'id' }))).toThrow(/meta searchTieBreak = id is not a value/); }); test('searchTieBreak rank: hits of equal score in the stored rank order', async () => { From fa78589789d7cb737cc78942afb98539619666b9 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 18:20:26 -0600 Subject: [PATCH 17/90] sqlite-v2: agree with the other reader on two file facts The LOINC importer writes meta linkOrder seq (a concept's links in source order): the other reader orders a LOINC $lookup by it, so a file built here means the same there. A lookupDesignationCode that is not a literal property of the catalog refuses the file (it listed nothing). Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 2 ++ tx/importers/import-loinc-v2.module.js | 3 +++ tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/store.js | 5 +++++ 4 files changed, 11 insertions(+), 1 deletion(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 5e2ab409f..3398d7319 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -761,6 +761,8 @@ describe('behaviour.lookupDesignationCode: each designation again, coded by an i test('absent (default null): none', async () => { expect(await lookup(build(false), [])).toEqual([]); expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '3' }))).toThrow(/lookupDesignationCode = 3 is not a value/); + expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '"parent"' }))).toThrow(/lookupDesignationCode parent is not a literal property/); + expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '"nothing"' }))).toThrow(/is not a literal property/); }); }); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 30e44ab28..457743467 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -180,6 +180,9 @@ function loincCodeSystem(b, version, description) { b.setBehaviour('expansionOrder', 'stored'); b.setBehaviour('lookupName', 'title'); b.setBehaviour('versionAlgorithm', 'natural'); + // a concept's links in source order (link.seq), as cs-loinc.js reads its Relationships (meta + // linkOrder: this reader's LOINC $lookup lists them in its own fixed groups) + b.setMeta('linkOrder', 'seq'); // text search reads the display (English) and every name but RELATEDNAMES2 b.setMeta('ix.ix_word.names', { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); } diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index d7bce53d2..86dce9e3d 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -193,7 +193,7 @@ refused (the builders check the same at build). | `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 | | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | -| `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A property not in the catalog lists nothing | +| `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | Release facts in `meta` that a reader also presents: `titles` (JSON object, language -> the system's diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 35d436cd0..809eb0555 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -358,6 +358,11 @@ class Store { this.displayRefsets = dc && dc.relations ? dc.relations.map(String) : null; this.moduleDependencies = metaJson('moduleDependencies', []); this._loadCatalog(); + // behaviour.lookupDesignationCode names a literal property of the catalog + const ldc = this.behaviour.lookupDesignationCode; + if (ldc != null && !(this.catalog.has(ldc) && ['literal', 'both'].includes(this.catalog.get(ldc).shape))) { + throw new Error(`${this.file}: behaviour.lookupDesignationCode ${ldc} is not a literal property of the catalog`); + } this.uses = new Map(); for (const u of db.prepare('SELECT use_id, system, code, display FROM main.item_use').all()) this.uses.set(u.use_id, { system: u.system, code: u.code, display: u.display }); this.hasFts = true; From 3ef7683f67bc336132defcfe5e67fa5322efd2cf Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 19:10:56 -0600 Subject: [PATCH 18/90] sqlite-v2: verify.js exits 1 for every failure; report text for ICD-11 and NDC verify.js exits 1 when any check fails, a file it cannot read included. The format document says ICD-11 residual and NDC kind are 'never' (filter-only), as their importers now write, and notes the one difference between readers on a file without versionAlgorithm. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 2 +- tx/importers/sqlite-v2/verify.js | 6 +++--- tx/sqlite-v2/README.md | 12 +++++++++--- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 3398d7319..a588ce54f 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -581,7 +581,7 @@ describe('P7. integrity facts written by the builder; verify.js checks a file on expect(r.status).toBe(1); const meta = copy((p) => { const w = new Database(p); w.exec("UPDATE meta SET value = '\"sideways\"' WHERE key = 'behaviour.expansionOrder'; INSERT OR REPLACE INTO meta VALUES ('behaviour.expansionOrder', '\"sideways\"')"); w.close(); }); expect(run(meta).stdout).toMatch(/^FAIL meta: .*behaviour.expansionOrder = "sideways"/m); - expect(run(path.join(dir, 'no-such.db')).status).toBe(2); + expect(run(path.join(dir, 'no-such.db')).status).toBe(1); }); }); diff --git a/tx/importers/sqlite-v2/verify.js b/tx/importers/sqlite-v2/verify.js index 98f1a3cd5..e6a9e1315 100644 --- a/tx/importers/sqlite-v2/verify.js +++ b/tx/importers/sqlite-v2/verify.js @@ -3,7 +3,7 @@ // 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, 2 when the file cannot be read. +// 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'); @@ -58,14 +58,14 @@ if (require.main === module) { const file = process.argv[2]; if (!file) { console.error('usage: node verify.js '); - process.exit(2); + process.exit(1); } let results; try { results = verifyFile(file); } catch (e) { console.error(e.message); - process.exit(2); + 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/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 86dce9e3d..8293239de 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -131,7 +131,7 @@ it again (the index builder removes it when it drops the indexes). `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 (2 when the file cannot be read). Readers do not check digests. +each check and exits 1 when one fails, the file cannot be read included (non-zero for every failure). Readers do not check digests. ## Meta @@ -196,6 +196,12 @@ refused (the builders check the same at build). | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | +Known difference between readers: for a file without `versionAlgorithm` (every SNOMED CT file +built before the importer wrote `"url"`), the JS reader guesses the algorithm from the version +string, while the other reader keeps an earlier rule (a SNOMED CT edition-URI match, semver +otherwise). For a SNOMED CT version URI both match by prefix; files that state the key mean the same +to both. + 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`. @@ -220,8 +226,8 @@ where `filterable = 1`, hidden altogether where not), `named` (`$lookup` returns request names it or asks for `*`, not by default), `always` (also on every expansion row), NULL (the default: `$lookup` reports it by default and when asked for). RxNorm files set `never` on SUPPRESS and the `@` storage codes and `named` on the relationships (a file built before has none there; the JS reader's RxNorm adapter then applies the rule they state); ICD-11 files set -`named` on `child`, `browserUrl` and `residual`, and `always` on `classificationCode` in MMS and ICF; -NDC files `named` on `kind`. A filter-only property is `never` with `filterable = 1`: one value, as +`named` on `child` and `browserUrl`, `never` on `residual` (a filter only), and `always` on +`classificationCode` in MMS and ICF; NDC files `never` on `kind` (a filter only). A filter-only property is `never` with `filterable = 1`: one value, as filterability is the separate `filterable` column. ## Word index From 495683a495086b5f33a25e608c36acb8d7bb871b Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 19:22:04 -0600 Subject: [PATCH 19/90] sqlite-v2: an absent versionAlgorithm matches exactly A requested version matches by the file's versionAlgorithm, else by what its stored CodeSystem resource declares, else only exactly: no guess from the version string. The worker's version check asks the provider (versionMatches) where it has a rule of its own. Every importer writes the key (SNOMED CT url, LOINC natural, RxNorm date). Co-Authored-By: Claude --- tests/tx/sqlite-v2-version-check.test.js | 70 ++++++++++++++++++++++++ tx/sqlite-v2/README.md | 8 +-- tx/sqlite-v2/provider.js | 25 ++++++++- tx/sqlite-v2/store.js | 2 +- tx/workers/worker.js | 11 +++- 5 files changed, 104 insertions(+), 12 deletions(-) create mode 100644 tests/tx/sqlite-v2-version-check.test.js 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 000000000..e05c31b7d --- /dev/null +++ b/tests/tx/sqlite-v2-version-check.test.js @@ -0,0 +1,70 @@ +'use strict'; + +// behaviour.versionAlgorithm through a real request (check-system-version on $expand): the file's +// algorithm, else what its stored CodeSystem resource declares, else an exact match (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-semver': { algorithm: 'semver' }, + '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.algorithm) b.setBehaviour('versionAlgorithm', o.algorithm); + 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 from the file, or from the stored resource: wildcards match', async () => { + for (const u of ['http://example.org/v-semver', 'http://example.org/v-resource']) { + expect(await status(u, '1.2.3')).toBe(200); + expect(await status(u, '1.2.x')).toBe(200); + expect(await status(u, '1.3.x')).toBe(400); + } +}); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 8293239de..6d90cf671 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -183,7 +183,7 @@ refused (the builders check the same at build). | `grammar` | a grammar name (an open string), `null` | `null` (plain codes) | the grammar of the system's codes. A reader holds its implementations by name and refuses a file whose grammar it does not implement ("its codes are in the grammar X, which this server does not implement"); there is no fallback by system URI. Names in use: `"snomed"` (SNOMED CT expressions and ECL; the JS reader's SNOMED CT provider, `index.js` `GRAMMARS`), `"icd11"` (ICD-11 MMS and ICF files: postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records), and a code system whose codes carry modifiers. The JS reader implements `snomed` only | | `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"` | the name `$lookup` reports: `code_system.name` (no name: the system URI), or the title (below; no title: the name). LOINC `"title"` | -| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm: how a requested version matches the file's version (`semver` with wildcards, `integer` exactly, anything else by prefix). `null`: none stated; a reader guesses the algorithm from the version string (FHIRsmith `guessVersionFormat`), with no rule of its own for a system. SNOMED CT `"url"` (versions are URIs, matched by prefix), LOINC `"natural"`, RxNorm `"date"` | +| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm: how a requested version (check-system-version) matches the file's version (FHIRsmith `versionMatchesByAlgorithm`: `semver` with wildcards, `integer` exactly, any other value by prefix). `null`: what the stored CodeSystem resource declares (`versionAlgorithmString` / `versionAlgorithmCoding`), else only the exact version matches; no guess from the version string and no rule of the reader's own for a system. Every importer writes it: SNOMED CT `"url"` (versions are edition URIs, matched by prefix), LOINC `"natural"`, RxNorm `"date"` | | `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | | `lookupSkipsMixedLinks` | `true`, `false` | `false` | SNOMED CT `true`: a `both` attribute's links are not read where no property is named (main keeps one value kind per attribute) | @@ -196,12 +196,6 @@ refused (the builders check the same at build). | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | -Known difference between readers: for a file without `versionAlgorithm` (every SNOMED CT file -built before the importer wrote `"url"`), the JS reader guesses the algorithm from the version -string, while the other reader keeps an earlier rule (a SNOMED CT edition-URI match, semver -otherwise). For a SNOMED CT version URI both match by prefix; files that state the key mean the same -to both. - 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`. diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index c5e36aad6..f29a3fe18 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -21,6 +21,7 @@ const { Engine } = require('./engine/engine'); const { Compiler, FilterError } = require('./engine/compile'); const { dialectFor, LOINC, RXNORM } = require('./dialects'); 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'); @@ -114,6 +115,16 @@ class SqliteV2Provider extends BaseCSServices { isNotClosed() { return !!this.store.notClosed; } contentMode() { return this.store.cs.content || 'complete'; } versionAlgorithm() { return this.f.versionAlgorithm(); } + /** + * Whether a requested version (criteria) matches the file's: by the file's versionAlgorithm + * (FHIRsmith versionMatchesByAlgorithm); a file that states none matches exactly (no guess from + * the version string) + */ + versionMatches(criteria, version = this.version()) { + const algorithm = this.versionAlgorithm(); + if (algorithm == null) return criteria === version; + return VersionUtilities.versionMatchesByAlgorithm(criteria, version, algorithm); + } isCaseSensitive() { return this.store.caseSensitive; } /** the most codes of this system an expansion lists or walks (behaviour.expansionLimit; 0: no limit) */ expandLimitation() { return this.store.behaviour.expansionLimit; } @@ -1498,7 +1509,19 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { } return this._liveCount; } - versionAlgorithm() { return this.store.behaviour.versionAlgorithm; } + /** + * behaviour.versionAlgorithm, else what the stored CodeSystem resource declares + * (versionAlgorithmString / versionAlgorithmCoding), else null (versions match exactly) + */ + versionAlgorithm() { + if (this.store.behaviour.versionAlgorithm != null) return this.store.behaviour.versionAlgorithm; + if (this._resourceAlgorithm === undefined) { + let r = null; + try { r = this.store.cs.resource ? JSON.parse(this.store.cs.resource) : null; } catch (e) { r = null; } + this._resourceAlgorithm = r ? VersionUtilities.versionAlgorithmOf(r) : null; + } + return this._resourceAlgorithm; + } /** * 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 diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 809eb0555..6396403ae 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -311,7 +311,7 @@ class Store { this.meta = new Map(db.prepare("SELECT key, value FROM main.meta WHERE key NOT LIKE 'provenance.%'").raw().all()); this.format = this.meta.get('format'); this.csId = cs.cs_id; - this.cs = { id: cs.cs_id, uri: cs.uri, version: cs.version, name: cs.name, title: cs.title, description: cs.description, + 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; diff --git a/tx/workers/worker.js b/tx/workers/worker.js index 84c24e2cd..4e8eb1629 100644 --- a/tx/workers/worker.js +++ b/tx/workers/worker.js @@ -223,7 +223,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; @@ -1239,12 +1240,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); From 1241e08332bd7de7a53635d003d380b4e31b42d1 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 19:32:44 -0600 Subject: [PATCH 20/90] sqlite-v2: no reader paths for files built before a key existed The reader keeps no rule whose only purpose is a file written before a key existed: - no legacy word-index selection: a file without ix.ix_word.names has no names to search, and a stored index without ix.ix_word.stemmers is not used; - identifier values are always probed as text; a file that does not require identifier-text (its identifier column may hold INTEGERs) is refused, to be rebuilt or upgraded; - no default display reference set for a SNOMED CT file without displayContexts; - the RxNorm $lookup reads property.report only; - node indexes.js checks every contract, requires included. Supplement layers state requires like any file. Existing tests pass with their expectations unchanged. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 56 ++++++++++-------------- tx/importers/sqlite-v2/builder.js | 8 ++-- tx/importers/sqlite-v2/indexes.js | 18 +++----- tx/sqlite-v2/README.md | 27 +++++++----- tx/sqlite-v2/layers.js | 1 + tx/sqlite-v2/provider.js | 9 ++-- tx/sqlite-v2/snomed.js | 2 +- tx/sqlite-v2/store.js | 21 ++++----- tx/sqlite-v2/text-index.js | 27 +++--------- 9 files changed, 70 insertions(+), 99 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index a588ce54f..575b39d9d 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -141,7 +141,6 @@ describe('P2. identifier values are TEXT (requires identifier-text)', () => { test('probes with integer-looking values match, one by one and as a list through json_each', () => { withStore(file, (S) => { - expect(S.identifierText).toBe(true); expect(S.identifierAsCode('123').code).toBe('B'); expect(S.identifierAsCode('00123').code).toBe('A'); const def = S.catalog.get('alias'); @@ -150,13 +149,9 @@ describe('P2. identifier values are TEXT (requires identifier-text)', () => { }); }); - test('without identifier-text a reader keeps the older typing (and an integer through json_each misses a text value)', () => { - const old = withMeta(file, { requires: null }); - withStore(old, (S) => { - expect(S.identifierText).toBe(false); - expect(S.subjectsOfIdentifiers(S.catalog.get('alias'), ['456'])).toEqual([]); - expect(S.subjectsOfIdentifiers(S.catalog.get('alias'), ['00123'])).toEqual([S.idOf('A')]); - }); + test('a file that does not require identifier-text (built before identifier values were text) is refused', () => { + expect(() => openStore(withMeta(file, { requires: null }))).toThrow(/built before identifier values were text .* rebuild it with the importers, or upgrade it/); + expect(() => openStore(withMeta(file, { requires: '[]' }))).toThrow(/built before identifier values were text/); }); }); @@ -206,27 +201,28 @@ describe('P3. word index: the names selection as data, stemmers per language, li expect(new Set(names(rich({ items: { language: 'fr' } })).map((r) => r[1]))).toEqual(new Set(['fr'])); }); - test('a file without ix.ix_word.names: none for a system the format had no selection for; the legacy one for SNOMED CT, LOINC, RxNorm', () => { + test('a file without ix.ix_word.names has no names to search, whatever its system (no table of systems)', () => { expect(names(withMeta(rich({ items: {} }), { 'ix.ix_word.names': null }))).toEqual([]); - expect(ti.LEGACY_NAMES['http://loinc.org']).toEqual({ display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); const sct = fixture((b) => b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }), { uri: 'http://snomed.info/sct' }); - const legacy = withMeta(sct, { 'ix.ix_word.names': null }); - expect(names(legacy)).toEqual(names(sct)); + expect(names(sct).length).toBeGreaterThan(0); + const without = withMeta(sct, { 'ix.ix_word.names': null }); + expect(names(without)).toEqual([]); + withStore(without, (S) => { + expect(ti.textIndexOf(S)).not.toBeInstanceOf(ti.WordIndex); + expect(S.searchText('apple', null, 'designation', 'en').size).toBe(0); + }); }); - test('rebuilding the indexes of a file built before ix.ix_word.names (node indexes.js) writes the key from the legacy table', () => { + test('rebuilding the indexes of a file without ix.ix_word.names (node indexes.js) writes no word index', () => { const { spawnSync } = require('child_process'); - const sct = fixture((b) => b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }), { uri: 'http://snomed.info/sct' }); - const old = withMeta(sct, { 'ix.ix_word.names': null, 'ix.ix_word.stemmers': null }); - const before = names(old); - const r = spawnSync(process.execPath, [path.join(__dirname, '../../tx/importers/sqlite-v2/indexes.js'), old], { encoding: 'utf8' }); + const f = withMeta(rich({ items: {} }), { 'ix.ix_word.names': null }); + const r = spawnSync(process.execPath, [path.join(__dirname, '../../tx/importers/sqlite-v2/indexes.js'), f], { encoding: 'utf8' }); expect(r.status).toBe(0); - const db = new Database(old, { readonly: true }); + const db = new Database(f, { readonly: true }); try { - expect(JSON.parse(db.prepare("SELECT value FROM meta WHERE key = 'ix.ix_word.names'").pluck().get())).toEqual(ti.LEGACY_NAMES['http://snomed.info/sct']); - expect(db.prepare("SELECT value FROM meta WHERE key = 'ix.ix_word.stemmers'").pluck().get()).not.toBeNull(); + 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(); } - expect(names(old)).toEqual(before); }); test('the index builder writes the selection, the stemmer of each language, and the counts row little-endian (2 * (N + 1) bytes)', () => { @@ -273,8 +269,11 @@ describe('P3. word index: the names selection as data, stemmers per language, li }); // the file's own stemmers: the stored index for every language withStore(f, (S) => expect(ti.textIndexOf(S)).toBeInstanceOf(ti.WordIndex)); - // no ix.ix_word.stemmers (a file built before the key): this reader's own stemmers, the stored index used - withStore(withMeta(f, { 'ix.ix_word.stemmers': null }), (S) => expect(ti.textIndexOf(S)).toBeInstanceOf(ti.WordIndex)); + // no ix.ix_word.stemmers: the stored index is not used (every language from the names, in memory) + withStore(withMeta(f, { 'ix.ix_word.stemmers': null }), (S) => { + expect(ti.textIndexOf(S)).toBeInstanceOf(ti.SplitTextIndex); + expect(ti.textIndexOf(S).memLangs).toEqual(new Set(['de', 'en'])); + }); }); test('a malformed selection is refused', () => { @@ -666,7 +665,7 @@ describe('P8. RxNorm: which properties $lookup reports is catalog data (report), const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); const conso = (cui, aui, sab, tty, str, sup = 'N') => [cui, 'ENG', '', '', '', '', '', aui, '', '', '', sab, tty, cui, str, '', sup, ''].join('|') + '|'; const cuiRel = (cui1, rel, cui2, rela) => [cui1, '', 'CUI', rel, cui2, '', 'CUI', rela, '', '', 'RXNORM', '', '', '', 'N', ''].join('|') + '|'; - let op, file, legacy; + let op, file; beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); const rrf = path.join(dir, 'rrf'); @@ -678,12 +677,6 @@ describe('P8. RxNorm: which properties $lookup reports is catalog data (report), fs.writeFileSync(path.join(rrf, 'RXNSTY.RRF'), ['100|T200|||A|', '200|T121|||A|', '300|T200|||A|'].join('\n') + '\n'); file = path.join(dir, 'rx.db'); await importRxNormV2({ source: rrf, dest: file, version: '01012026', overwrite: true, log: () => {} }); - // the same file as built before the importer wrote report - legacy = path.join(dir, 'rx-legacy.db'); - fs.copyFileSync(file, legacy); - const w = new Database(legacy); - w.exec('UPDATE property SET report = NULL'); - w.close(); }); const lookups = async (f) => { const fac = new SqliteV2Factory(op.i18n, f); @@ -715,9 +708,8 @@ describe('P8. RxNorm: which properties $lookup reports is catalog data (report), } finally { db.close(); } }); - test('$lookup answers from the catalog equal the answers of the code rule on a file without report values', async () => { + test('$lookup answers from the catalog: TTY, STY, SAB by default; relationships by name or *; SUPPRESS and @ codes never', async () => { const a = await lookups(file); - expect(a).toEqual(await lookups(legacy)); expect(a['100 ']).toEqual(['TTY=SCD', 'TTY=SY', 'STY=T200', 'SAB=RXNORM']); expect(a['200 *']).toEqual(['TTY=IN', 'STY=T121', 'SAB=RXNORM', 'ingredient_of=100']); expect(a['200 ']).toEqual(['TTY=IN', 'STY=T121', 'SAB=RXNORM']); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index afd884453..a38c6e082 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -622,9 +622,9 @@ function vacuumFile(file) { * 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, opts = {}) { +function finishFile(db, file = db.name) { db.exec('DROP TABLE IF EXISTS sqlite_stat4'); - checkContracts(db, opts); + 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 }); @@ -642,7 +642,7 @@ function schemaIndexes() { * 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, opts = {}) { +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(); @@ -708,7 +708,7 @@ function checkContracts(db, opts = {}) { const eo = one("SELECT value FROM main.meta WHERE key = 'behaviour.expansionOrder'"); if (eo != null && JSON.parse(eo) !== 'ids' && !(arrays.has('rank') && arrays.has('ids'))) fail(`behaviour.expansionOrder ${eo} without ix_order rank and ids`); // meta requires is stated; a word index states its names - if (!opts.olderFile && one("SELECT count(*) FROM main.meta WHERE key = 'requires'") !== 1) fail('meta requires is missing'); + if (one("SELECT count(*) FROM main.meta WHERE key = 'requires'") !== 1) fail('meta requires is missing'); if (langs.length && one("SELECT count(*) FROM main.meta WHERE key = 'ix.ix_word.names'") !== 1) fail('the word index has no meta ix.ix_word.names'); // the secondary indexes of the schema; sqlite_stat1 and no sqlite_stat4 for (const [name, unique] of schemaIndexes()) { diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index 8567306b8..ed16b58c7 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -22,8 +22,7 @@ // ix.ix_word.names selects (the importer states it; it is kept across a // rebuild), 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. -// A file without ix.ix_word.names gets no word index, unless it had one before -// the key existed: then the selection of tx/sqlite-v2/text-index.js LEGACY_NAMES +// A file without ix.ix_word.names gets no word index // ix_key nothing generic (SNOMED normal forms are derived-by-importer) const Database = require('better-sqlite3'); @@ -82,14 +81,8 @@ function dropIndexes(db) { */ function buildIndexes(db, opts = {}) { const time = opts.time || ((name, fn) => fn()); - // the names the word index holds: the importer's statement, else (a file built before the key - // existed that has a word index) the selection the format had for its system - const metaOf = (k) => db.prepare('SELECT value FROM main.meta WHERE key = ?').pluck().get(k); - let names = metaOf('ix.ix_word.names'); - if (names == null && metaOf('ix.ix_word.format') != null) { - const legacy = require('../../sqlite-v2/text-index').LEGACY_NAMES[db.prepare('SELECT uri FROM main.code_system WHERE served = 1').pluck().get()]; - if (legacy) names = JSON.stringify(legacy); - } + // the names the word index holds: the importer's statement (none: no word index) + const names = db.prepare("SELECT value FROM main.meta WHERE key = 'ix.ix_word.names'").pluck().get(); 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(); @@ -347,9 +340,8 @@ if (require.main === module) { 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; } }); const { analyze, finishFile } = require('./builder'); analyze(db); - // the contracts and the meta keys, as the builder checks a file it finishes (a file built before - // meta requires existed keeps its identifier typing and has no requires: olderFile) - finishFile(db, file, { olderFile: !db.prepare("SELECT 1 FROM main.meta WHERE key = 'requires'").get() }); + // 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/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 6d90cf671..f774d1344 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -98,7 +98,7 @@ after a rebuild); `verify.js` checks them on request. | `behaviour.expansionOrder` other than `ids`: `ix_order` has `rank` and `ids` | yes | | the `ix_word` counts rows are `2 * (N + 1)` bytes; every `ix_word` 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 | -| meta follows "Meta" (every key one the builder knows, every value well-formed); `requires` is stated; a word index has its `ix.ix_word.names` | yes (`node indexes.js` on a file built before `requires` existed skips the `requires` check) | +| meta follows "Meta" (every key one the builder knows, every value well-formed); `requires` is stated; a word index has its `ix.ix_word.names` | yes | | record `fields` is a JSON array in the order of the relation's non-target fields | stated (a check would parse every record row) | The JS reader checks the id ranges it relies on at open (an id up to N is a concept, above N an @@ -133,6 +133,13 @@ meta values, the contracts above (id ranges included), and, where the file state 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. +## Files built before a key existed + +Readers carry no path for a file built before a key existed: such a file is read by the rules above +(an absent key has its default) or refused where that would give wrong answers (no +`identifier-text`). Rebuild it with the importers, or upgrade it (the other implementation's +`tx-import upgrade` writes a file with every key this format now has). + ## Meta `meta` is key -> text. One rule for every key: @@ -144,7 +151,7 @@ each check and exits 1 when one fails, the file cannot be read included (non-zer | feature | meaning | |---|---| - | `identifier-text` | every `identifier.value` (and `ix_by_subject.value`) is text: the column is declared `TEXT`. A reader binds identifier probe values as text, lists passed through `json_each` included (an integer there does not match a text value). In a file without it, a canonical decimal integer may be stored as INTEGER and a reader probes with an INTEGER for such a value. Every file the builder writes requires it. | + | `identifier-text` | every `identifier.value` (and `ix_by_subject.value`) is text: the column is declared `TEXT`. A reader binds identifier probe values as text, lists passed through `json_each` included (an integer there does not match a text value). Every file the builder writes requires it; the JS reader refuses a file that does not (one built before the column was declared `TEXT`, which may hold INTEGER values a text probe misses: rebuild or upgrade it). The name stays in `requires` so that a reader that does not know it, and would bind integers, refuses such a file. | - A reader ignores a key it does not know. A key it knows with a malformed value is refused, with the key and the value in the message, in every file. - Each key has one meaning and a default (absent means the default). A reader obeys the file's @@ -159,7 +166,7 @@ each check and exits 1 when one fails, the file cannot be read included (non-zer | `requires` | JSON list of feature names | `[]` | above | | `integrity` | JSON `{items, schema, catalog}` | none | facts a tool checks on request (below); readers do not | | `languages` | JSON list of language tags | `[]` | the languages of the served system's items, in order of first appearance | -| `displayContexts` | JSON `{relations, preferred, use}` | none | the language relations that rank displays (SNOMED CT) | +| `displayContexts` | JSON `{relations, preferred, use}` | none (no display reference sets) | the language relations that rank displays (SNOMED CT; the importer always writes it) | | `moduleDependencies` | JSON list of `[module, target module, effective time, target effective time]` | `[]` | SNOMED CT module dependencies | | `edition` | text | none | the SNOMED CT edition (module id) | | `titles` | JSON object, language -> title | `{}` | the system's title per language (ICD-11) | @@ -218,8 +225,7 @@ and the relationships: `=`, `in`) and `report`, when `$lookup` and expansions re by `$lookup`, asked for or not, nor on expansions, nor among the declared properties: a filter only where `filterable = 1`, hidden altogether where not), `named` (`$lookup` returns it only when the request names it or asks for `*`, not by default), `always` (also on every expansion row), NULL (the default: `$lookup` -reports it by default and when asked for). RxNorm files set `never` on SUPPRESS and the `@` storage codes and `named` on the relationships (a file built -before has none there; the JS reader's RxNorm adapter then applies the rule they state); ICD-11 files set +reports it by default and when asked for). RxNorm files set `never` on SUPPRESS and the `@` storage codes and `named` on the relationships ; ICD-11 files set `named` on `child` and `browserUrl`, `never` on `residual` (a filter only), and `always` on `classificationCode` in MMS and ICF; NDC files `never` on `kind` (a filter only). A filter-only property is `never` with `filterable = 1`: one value, as filterability is the separate `filterable` column. @@ -254,12 +260,9 @@ write: | LOINC | `{"display": "en", "items": {"excludeUses": ["RELATEDNAMES2"]}}` | | RxNorm | `{"items": {"conceptsWith": "SUPPRESS", "language": "en"}}` | -Compatibility rule for files built before `ix.ix_word.names` existed (and only for them; every file -the builder writes now has the key): a reader treats a file without the key as holding the selection -above for its system (SNOMED CT, LOINC, RxNorm: `LEGACY_NAMES` in `text-index.js`, the one table of -systems for this), and no names for any other system. Rebuilding such a file's indexes (`node -indexes.js `) writes the key from that table, so the rebuilt file states its names and the -table is not consulted for it again. The index builder keeps the key across later rebuilds. +A file without the key has no names to search (text search matches codes only), whatever its +system: no reader holds a table of systems for it. The index builder keeps the key across a +rebuild, and builds no word index for a file without it. `ix.ix_word.stemmers`: for each language of the word index, the stemmer that made its `stem` column, an open string: `none` (a word is its own stem), `natural:` (a stemmer class of the `natural` @@ -268,7 +271,7 @@ package: `natural:PorterStemmer` for en, `natural:PorterStemmerDe`, `...Es`, `.. `snowball:` (a Snowball algorithm: `snowball:german`, ...). A reader that cannot reproduce a language's stemmer searches that language without the stored index (the JS reader builds the names of that language in memory on the first search); other languages keep using it. A -file without the key was written with the stemmers of `tx/library/text-match.js`. +file without the key (or without `ix.ix_word.names`) is searched without its stored index. The counts row: for each concept id 0..N an unsigned 16-bit count, little-endian, `2 * (N + 1)` bytes, written and read little-endian on every host. diff --git a/tx/sqlite-v2/layers.js b/tx/sqlite-v2/layers.js index 620abe8fd..324b929a4 100644 --- a/tx/sqlite-v2/layers.js +++ b/tx/sqlite-v2/layers.js @@ -145,6 +145,7 @@ 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'); diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index f29a3fe18..88c165769 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -766,10 +766,8 @@ class SqliteV2Provider extends BaseCSServices { const S = this.store; const st = this._stats(); // which properties are reported is catalog data (property.report: SUPPRESS and the `@` storage - // codes 'never', the relationships 'named'); a file built before the importer wrote report has - // none there, and gets the same answer from the rule it stood for - const legacy = S.catalog.has('SUPPRESS') && S.catalog.get('SUPPRESS').report == null; - const hidden = (code) => (legacy ? code === 'SUPPRESS' || code.includes('@') : (S.catalog.get(code) || {}).report === 'never'); + // codes 'never', the relationships 'named') + const hidden = (code) => (S.catalog.get(code) || {}).report === 'never'; const lits = new Map(); for (const r of S.literalsOf([c.id], true, st)) { const p = S.propsById.get(r.p); @@ -783,7 +781,6 @@ class SqliteV2Provider extends BaseCSServices { if (!this._reports(name, props, true)) continue; for (const v of [...lits.get(name)].sort(asText)) this._addCodeProperty(params, 'property', name, v); } - if (legacy && !(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 && !hidden(p.code); }); 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 @@ -793,7 +790,7 @@ class SqliteV2Provider extends BaseCSServices { 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._reports(name, props, !legacy)) continue; + if (!t || seen.has(name + '|' + t.code) || !this._reports(name, props, true)) continue; seen.add(name + '|' + t.code); named.push({ name, code: t.code }); } diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 6faf94b1c..11b1f027c 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -737,7 +737,7 @@ class SnomedV2Factory extends SqliteV2Factory { LOADED.add(this); // the SNOMED files this server loaded (load-time data, for edition-only URLs) // data read at load (no caches): the acceptability and display refset ids this._preferredId = this.store.idOf(PREFERRED); - this._displayRefsets = [].concat(this.store.displayRefsets || ['900000000000509007']) + 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); diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 6396403ae..7e515f221 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -62,8 +62,7 @@ function holdReadLock(db) { } /** - * A source id (item.external_id), or an identifier value of a file that does not require - * identifier-text, as the file stores it: a canonical decimal integer as an INTEGER (bound as + * 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) { @@ -327,9 +326,12 @@ class Store { if (checkIds) this._checkIdRanges(cs.concept_count); const m = readMeta(this.meta, this.file); this.requires = m.requires; - // identifier values are all text (identifier-text): probes bind text, lists through json_each - // included (an integer there would not match a text value); else the older typing - this.identifierText = m.requires.includes('identifier-text'); + // identifier values are text (identifier-text): probes bind text, lists through json_each + // included. A file that does not say so was built before identifier.value was declared TEXT + // (it may hold INTEGER values a text probe misses): refused, to be rebuilt or upgraded + if (!m.requires.includes('identifier-text')) { + throw new Error(`${this.file} was built before identifier values were text (meta requires has no identifier-text): rebuild it with the importers, or upgrade it`); + } this.behaviour = m.behaviour; // the order of a concept's links where no rule of the system's adapter lists them ($lookup), and // how text-search hits of equal score are ordered (null: each search's own order) @@ -489,8 +491,8 @@ class Store { return this._rankOrdinal; } - /** an identifier value to probe with, typed as the file stores it */ - _idProbe(v) { return this.identifierText ? String(v) : idValue(v); } + /** 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); } @@ -1026,9 +1028,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: text (identifier-text); else a canonical integer is an INTEGER (json_each - // gives it as one), text otherwise - const vals = values.map((v) => (this.identifierText || 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)); diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js index ab752d972..4d95aa0de 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -65,27 +65,13 @@ function primaryLanguage(code, defLang) { // ---- the names ------------------------------------------------------------------------------ /** - * The selection a file's word index holds, and so the names its text search reads, for a file whose - * meta has no ix.ix_word.names (every file written before the key): the selection the format had for - * that file's system. The one table of systems for this; a file that states its names never reads it. - * SNOMED CT active designations of the served system, in their own language, with the counts row - * LOINC the displays (as en) and every item of the served system but RELATEDNAMES2 - * RxNorm the items of the concepts with a SUPPRESS literal (the concepts in RXNCONSO), as en - */ -const LEGACY_NAMES = Object.freeze({ - 'http://snomed.info/sct': Object.freeze({ items: { active: true, designations: true }, counts: true }), - 'http://loinc.org': Object.freeze({ display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }), - 'http://www.nlm.nih.gov/research/umls/rxnorm': Object.freeze({ items: { conceptsWith: 'SUPPRESS', language: 'en' } }), -}); - -/** - * The names a file's text search reads (meta ix.ix_word.names, README.md "Word index"), or null for - * none: the file's own statement, else LEGACY_NAMES for its system + * The names a file's text search reads (meta ix.ix_word.names, README.md "Word index"), or null: a + * file that states none has no names to search (codes are still matched) */ function searchNamesSelection(store) { if (store._names === undefined) { const own = store.meta.get('ix.ix_word.names'); - store._names = own != null ? JSON.parse(own) : (LEGACY_NAMES[store.system] || null); + store._names = own != null ? JSON.parse(own) : null; } return store._names; } @@ -318,12 +304,11 @@ class MemoryTextIndex { /** * 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) is searched without the stored index. A file without - * the key was written by this builder before it existed, with this server's stemmers. + * 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) return new Set(stored.langs); + if (raw == null || store.meta.get('ix.ix_word.names') == null) return new Set(); const named = JSON.parse(raw); return new Set([...stored.langs].filter((l) => named[l] === stemmerName(l))); } @@ -776,7 +761,7 @@ const rxTextSearch = (...a) => runSync(rxTextSearchG(...a)); const genericTextSearch = (...a) => runSync(genericTextSearchG(...a)); module.exports = { - FORMAT, WordIndex, blockConcepts, eachSearchName, searchNamesOf, searchNamesSelection, LEGACY_NAMES, rxSearchable, + FORMAT, WordIndex, SplitTextIndex, blockConcepts, eachSearchName, searchNamesOf, searchNamesSelection, rxSearchable, computeTextIndexFrom, textIndexOf, primaryLanguage, countsFromLE, countsToLE, usableLanguages, sctTextSearch, sctTextLanguages, loincTextSearch, rxTextSearch, genericTextSearch, rateConcepts, sctTextSearchG, loincTextSearchG, rxTextSearchG, genericTextSearchG From 8d5ecb6dc7b940decdba5fbe529f2193038f6559 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 19:37:00 -0600 Subject: [PATCH 21/90] sqlite-v2: reported names and the status literal are catalog data property gains reported_as (the name it is reported and asked for under), also_asked_as (further names a request may ask by) and true_value (reported as a boolean, true for that value). The SNOMED CT importer writes them for is-a (parent), moduleId (also module) and definitionStatusId (sufficientlyDefined, true for fully defined, named); the SNOMED CT $lookup reads them instead of its own names. property.role 'status' marks the literal that holds a concept's status (at most one, a builder contract); the LOINC importer sets it on STATUS, and the reader finds the status property by role, not by system or code. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 69 ++++++++++++++++++++++++ tx/importers/import-loinc-v2.module.js | 3 +- tx/importers/sct-v2-common.js | 9 ++-- tx/importers/sqlite-v2/builder.js | 21 ++++++-- tx/importers/sqlite-v2/schema.sql | 9 +++- tx/sqlite-v2/README.md | 20 ++++++- tx/sqlite-v2/provider.js | 56 +++++++++++++------ tx/sqlite-v2/snomed.js | 26 ++++----- tx/sqlite-v2/store.js | 10 ++++ 9 files changed, 181 insertions(+), 42 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 575b39d9d..ae3ded1c1 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -778,3 +778,72 @@ describe('behaviour.lookupCopyright', () => { withStore(fixture(), (S) => expect(S.copyright).toBeNull()); }); }); + +describe('P9a/P9b. reported names, extra asked-for names, boolean values; the status literal', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { checkContracts } = require('../../tx/importers/sqlite-v2/builder'); + let op, file, f, p; + beforeAll(async () => { + op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + file = fixture((b, c) => { + const mod = b.property({ code: 'mod', shape: 'link', alsoAskedAs: ['module'] }); + const def = b.property({ code: 'defStatus', shape: 'link', reportedAs: 'fullyDefined', trueValue: 'B', report: 'named' }); + const st = b.property({ code: 'state', shape: 'literal', fhirType: 'string', role: 'status' }); + b.link(c.A, mod, c.root); + b.link(c.A, def, c.B); + b.link(c.C, def, c.X); + b.literal(c.A, st, 'TRIAL'); + }); + f = new SqliteV2Factory(op.i18n, file); + await f.load(); + p = await f.build(op, []); + }); + afterAll(() => f.store.close()); + const lookup = async (code, props) => { + const params = []; + await p.extendLookup((await p.locate(code)).context, props, params); + return params.map((x) => x.part[0].valueCode + '=' + JSON.stringify(x.part[1].valueCode ?? x.part[1].valueString ?? x.part[1].valueBoolean)); + }; + + test('reported_as: reported and asked for under that name; true_value: a boolean; named: by name or *, not by default', async () => { + expect(await lookup('A', [])).not.toContain('fullyDefined=true'); + expect(await lookup('A', ['fullyDefined'])).toEqual(['fullyDefined=true']); + expect(await lookup('C', ['fullyDefined'])).toEqual(['fullyDefined=false']); + expect(await lookup('A', ['*'])).toContain('fullyDefined=true'); + expect(await lookup('A', ['defStatus'])).toEqual([]); + }); + + test('also_asked_as: asked for by the extra name, still reported under its own', async () => { + expect(await lookup('A', ['module'])).toEqual(['mod="root"']); + expect(await lookup('A', ['mod'])).toEqual(['mod="root"']); + expect(await lookup('A', [])).toContain('mod="root"'); + }); + + test('role status: getStatus reads the literal, $lookup lists it by default under its name', async () => { + expect(await p.getStatus((await p.locate('A')).context)).toBe('TRIAL'); + expect(await p.getStatus((await p.locate('B')).context)).toBeNull(); + expect(await lookup('A', [])).toContain('state="TRIAL"'); + expect(f.store.statusProp.code).toBe('state'); + }); + + test('at most one status property (builder contract, reader check); a malformed also_asked_as is refused', () => { + const two = path.join(dir, 'two-status.db'); + fs.copyFileSync(file, two); + const w = new Database(two); + w.exec("UPDATE property SET role = 'status' WHERE code = 'colour'"); + expect(() => checkContracts(w)).toThrow(/more than one property with role status/); + w.close(); + expect(() => openStore(two)).toThrow(/more than one property with role status/); + const bad = path.join(dir, 'bad-asked.db'); + fs.copyFileSync(file, bad); + const w2 = new Database(bad); + w2.exec("UPDATE property SET also_asked_as = '\"module\"' WHERE code = 'mod'"); + w2.close(); + expect(() => openStore(bad)).toThrow(/also_asked_as "module", not a list of names/); + const b = new TerminologyBuilder(path.join(dir, 'never4.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/x', version: '1' }); + expect(() => b.property({ code: 's', shape: 'link', role: 'status' })).toThrow(/status role is for a literal/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 457743467..1fe991eee 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -157,7 +157,8 @@ function loincCatalog(b) { const link = (code, extra = {}) => b.property({ code, uri: `${PROP}/${code}`, shape: 'link', display: code, ...extra }); const parent = link('parent', { subsumption: true }); const partProp = Object.fromEntries([...new Set(Object.values(PART_LINK)), 'CLASS'].map((c) => [c, link(c)])); - const lit = Object.fromEntries(LITERALS.map(([c]) => [c, b.property({ code: c, uri: `${PROP}/${c}`, shape: 'literal', fhirType: 'string', display: c })])); + // 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, ...(c === 'STATUS' ? { role: 'status' } : {}) })])); const answer = link('Answer', { ordered: true }); const answersFor = link('answers-for'); b.property({ code: 'child', uri: `${PROP}/child`, shape: 'link', display: 'child', inverseOf: parent }); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 8ec04bc27..d9605ca5b 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -190,9 +190,12 @@ 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 CT on FHIR): is-a as parent; moduleId also asked for as module; + // the definition status as the boolean sufficientlyDefined (true for fully defined), only when asked for + this.isA = b.property({ code: IS_A, uri: `${SCT}/${IS_A}`, shape: 'link', subsumption: true, refinable: true, wildcard: false, reportedAs: 'parent' }); + this.module = b.property({ code: 'moduleId', shape: 'link', display: 'Module', refinable: false, wildcard: false, alsoAskedAs: ['module'] }); + this.defStatus = b.property({ code: 'definitionStatusId', shape: 'link', display: 'Definition status', refinable: false, wildcard: false, + reportedAs: 'sufficientlyDefined', trueValue: '900000000000073002', report: 'named' }); 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] diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index a38c6e082..f6e7e7ca3 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -37,7 +37,7 @@ const FORMAT = 'tx-terminology/1'; const USER_VERSION = 1; const COMMIT_EVERY = 100000; const SHAPES = new Set(['link', 'literal', 'both', 'identifier', 'record', 'union']); -const ROLES = new Set(['language']); +const ROLES = new Set(['language', 'status']); /** * 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 @@ -171,7 +171,9 @@ class TerminologyBuilder { * (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' | 'never': when $lookup and expansions report it) } + * report ('named' | 'always' | 'never': when $lookup and expansions report it), reportedAs (the + * name it is reported and asked for under), alsoAskedAs ([names] a request may also ask by), + * trueValue (reported as a boolean: true when its value is this) } */ property(spec) { const cs = spec.cs || 1; @@ -187,6 +189,10 @@ class TerminologyBuilder { throw new Error(`property ${spec.code}: a language relation is a record with a target column (the acceptability)`); } if (spec.report != null && !['named', 'always', 'never'].includes(spec.report)) throw new Error(`property ${spec.code}: bad report ${spec.report}`); + if (spec.role === 'status' && spec.shape !== 'literal') throw new Error(`property ${spec.code}: the status role is for a literal property`); + if (spec.alsoAskedAs != null && !(Array.isArray(spec.alsoAskedAs) && spec.alsoAskedAs.every((x) => typeof x === 'string' && x))) { + throw new Error(`property ${spec.code}: alsoAskedAs is a list of names`); + } 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}`); @@ -201,6 +207,8 @@ class TerminologyBuilder { 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, + reportedAs: spec.reportedAs ?? null, alsoAskedAs: spec.alsoAskedAs && spec.alsoAskedAs.length ? JSON.stringify(spec.alsoAskedAs) : null, + trueValue: spec.trueValue == null ? null : String(spec.trueValue), // 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) : [], }; @@ -478,8 +486,9 @@ class TerminologyBuilder { const nodeId = (h) => (h == null ? null : h >= 0 ? idOf[h] : db.prepare('SELECT new FROM st.s_node WHERE old = ?').pluck().get(h)); const computed = this._time('catalog computed fields', () => catalogStats(db, n)); const insProp = db.prepare(`INSERT INTO property (id, cs_id, code, uri, display, concept_id, shape, role, fhir_type, subject_kind, - subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, filter_ops, report, fields) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, filter_ops, report, reported_as, + also_asked_as, true_value, fields) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); const parents = new Set(this.members.map(([a]) => a)); for (const p of this.properties) { // subject_kind NULL for a catalog row with no rows @@ -494,7 +503,8 @@ class TerminologyBuilder { 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, - p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.filterOps, p.report, p.fields); + p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.filterOps, p.report, p.reportedAs, + p.alsoAskedAs, p.trueValue, p.fields); } const insMember = db.prepare('INSERT OR IGNORE INTO property_member VALUES (?, ?)'); for (const [a, b] of this.members) insMember.run(a, b); @@ -707,6 +717,7 @@ function checkContracts(db) { // a stored expansion order (behaviour.expansionOrder 'stored' / 'stored-self-first') has its arrays const eo = one("SELECT value FROM main.meta WHERE key = 'behaviour.expansionOrder'"); if (eo != null && JSON.parse(eo) !== 'ids' && !(arrays.has('rank') && arrays.has('ids'))) fail(`behaviour.expansionOrder ${eo} without ix_order rank and ids`); + if (one("SELECT count(*) FROM main.property WHERE role = 'status'") > 1) fail('more than one property with role status'); // meta requires is stated; a word index states its names if (one("SELECT count(*) FROM main.meta WHERE key = 'requires'") !== 1) fail('meta requires is missing'); if (langs.length && one("SELECT count(*) FROM main.meta WHERE key = 'ix.ix_word.names'") !== 1) fail('the word index has no meta ix.ix_word.names'); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index fc0e8ae10..688d9eb4c 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -68,7 +68,8 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat 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 + role TEXT, -- NULL; 'language': a record relation on items that ranks displays; + -- 'status': the literal that holds the concept's status (at most one) fhir_type TEXT, -- literal type 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) @@ -88,6 +89,12 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat report TEXT, -- when $lookup and expansions report it: 'never' (not at all: a filter -- only), 'named' (only when asked for by name), 'always' (also on every -- expansion row); NULL: by default and when asked for + reported_as TEXT, -- the name the property is reported under ($lookup, expansion rows) and + -- asked for by; NULL: its code + also_asked_as TEXT, -- JSON list of further names a request may ask for it by (still reported + -- under reported_as or code); NULL: none + 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 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` diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index f774d1344..3813acb51 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -88,7 +88,7 @@ after a rebuild); `verify.js` checks them on request. |---|---| | 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, one id space with the concepts | yes | -| at most one property with `subsumption = 1` (the hierarchy), at most one `ordered = 1` link property (the list property) | yes | +| at most one property with `subsumption = 1` (the hierarchy), at most one `ordered = 1` link property (the list property), at most one with `role = 'status'` | yes | | codes are unique per system and matched exactly (binary): the unique index `concept_code` | yes | | `identifier.value` is text | by the schema (`TEXT`; `identifier-text`) | | `ix_set` keys: kinds 1, 2, 3 have property 0, value 0, value kind 0; kinds 6 and 7 value 0, value kind 0; kind 4 value kind 1 | yes | @@ -230,6 +230,24 @@ reports it by default and when asked for). RxNorm files set `never` on SUPPRESS `classificationCode` in MMS and ICF; NDC files `never` on `kind` (a filter only). A filter-only property is `never` with `filterable = 1`: one value, as filterability is the separate `filterable` column. +How a property is reported and asked for (three nullable columns; NULL: absent): + +| column | meaning | default | +|---|---|---| +| `reported_as` | the name it is reported under (`$lookup`, expansion rows) and asked for by | its `code` | +| `also_asked_as` | JSON list of further names a request may ask for it by; it is still listed under `reported_as` (or `code`) | `[]` | +| `true_value` | reported as a boolean: `true` when its value (a link's target code, a literal's value) equals this, else `false` | its own value | + +A request asks for a property by its reported name or a name in `also_asked_as`, or by `*`; `report` +applies under the reported name. SNOMED CT files: `116680003` reported as `parent`; `moduleId` also +asked for as `module`; `definitionStatusId` reported as `sufficientlyDefined`, true for +`900000000000073002`, `report` `named`. No other system sets them. Readers keep no table of names +by system. + +`property.role = 'status'`: the literal that holds the concept's status (at most one per system): +every row reads it (the provider's `getStatus()`), and `$lookup` lists it by default under its name. +LOINC files: `STATUS`. + ## Word index `ix.ix_word.names` says which names the word index holds, and so which names a reader's text search diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 88c165769..2b419afef 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -138,10 +138,33 @@ class SqliteV2Provider extends BaseCSServices { */ _reports(code, props, dflt = true) { const d = this.store.catalog.get(code); - const report = d ? d.report : null; - if (report === 'never') return false; - if (report === 'named') return this._hasProp(props, code, false); - return this._hasProp(props, code, dflt); + return d ? this._reportsDef(d, props, dflt) : this._hasProp(props, code, dflt); + } + + /** the name a catalog property is reported under (property.reported_as, else its code) */ + _reportedName(d) { return d.reportedAs || d.code; } + + /** + * Whether a request's property list reports a catalog property: by its report value, asked for + * by its reported name or a name in also_asked_as, or by * + */ + _reportsDef(d, props, dflt = true) { + if (d.report === 'never') return false; + const byDefault = d.report === 'named' ? false : dflt; + if (!props || props.length === 0) return byDefault; + const names = [this._reportedName(d), ...d.alsoAskedAs].map((n) => n.toLowerCase()); + return props.some((p) => p === '*' || names.includes(String(p).toLowerCase())); + } + + /** a property's value as reported: a boolean where the catalog says (true_value), else the value */ + _addReported(params, d, value, display) { + if (d.trueValue != null) { + params.push({ name: 'property', part: [{ name: 'code', valueCode: this._reportedName(d) }, { name: 'value', valueBoolean: String(value) === d.trueValue }] }); + } else if (d.kind === 'concept' || d.shape === 'link' || d.shape === 'both') { + this._addCodeProperty(params, 'property', this._reportedName(d), value, null, display); + } else { + this._addStringProperty(params, 'property', this._reportedName(d), String(value)); + } } sourcePackage() { return null; } @@ -226,8 +249,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) { @@ -468,10 +491,10 @@ class SqliteV2Provider extends BaseCSServices { async getStatus(context) { const c = await this._ensure(context); if (!c) return null; - if (this.dialect.name === 'loinc') { + // the concept's status literal, where the catalog has one (role 'status') + const p = this.store.statusProp; + if (p) { 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; } @@ -724,9 +747,9 @@ class SqliteV2Provider extends BaseCSServices { this._addCodeProperty(params, 'property', l.code, t.code, null, t.display || null); } } - const lits = S.literalsOf([c.id], true, st).map((r) => ({ ...r, code: (S.propsById.get(r.p) || {}).code })).filter((r) => r.code); + const lits = S.literalsOf([c.id], true, st).map((r) => ({ ...r, code: (S.propsById.get(r.p) || {}).code, role: (S.propsById.get(r.p) || {}).role })).filter((r) => r.code); for (const r of lits) { - if (r.code === 'STATUS' || !this._reports(r.code, props, true)) continue; + if (r.role === 'status' || !this._reports(r.code, props, true)) continue; if (r.code === 'CLASSTYPE') { const map = S.valueLabels(S.props.get('CLASSTYPE')) || {}; const pr = this._addStringProperty(params, 'property', 'CLASSTYPE', String(r.v)); @@ -735,7 +758,8 @@ class SqliteV2Provider extends BaseCSServices { this._addStringProperty(params, 'property', r.code, String(r.v)); } } - for (const r of lits) if (r.code === 'STATUS' && this._hasProp(props, 'STATUS', true)) this._addStringProperty(params, 'property', 'STATUS', String(r.v)); + // the status literal (role 'status') after the other properties + for (const r of lits) if (r.role === 'status' && this._reports(r.code, props, true)) this._addStringProperty(params, 'property', r.code, 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; @@ -869,12 +893,14 @@ class SqliteV2Provider extends BaseCSServices { for (const l of links) { const p = S.propsById.get(l.p); const t = rows.get(l.t); - if (!p || !t || !this._reports(p.code, props, true)) continue; - this._addCodeProperty(params, 'property', p.isHierarchy ? 'parent' : p.code, t.code, null, t.display); + if (!p || !t || !this._reportsDef(p, props, true)) continue; + // (a hierarchy without a reported name is reported as FHIR's parent) + if (p.isHierarchy && !p.reportedAs) this._addCodeProperty(params, 'property', 'parent', t.code, null, t.display); + else this._addReported(params, p, t.code, t.display); } for (const r of S.literalsOf([c.id], true, this._stats())) { const p = S.propsById.get(r.p); - if (p && this._reports(p.code, props, true)) this._addStringProperty(params, 'property', p.code, String(r.v)); + if (p && this._reportsDef(p, props, true)) this._addReported(params, p, r.v); } this._designationCodes(c, props, params); } diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 11b1f027c..d985020c3 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -283,8 +283,9 @@ class SnomedV2Provider extends SqliteV2Provider { 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)); + // the hierarchy under its reported name (property.reported_as) + if (this._reportsDef(S.hierarchy, props, true)) { + for (const l of links) if (l.p === hid) this._addReported(params, S.hierarchy, code(l.t), 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); @@ -298,20 +299,13 @@ class SnomedV2Provider extends SqliteV2Provider { } 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' }] }); - } + // the concept's other links (module, definition status), in catalog order, each under its + // reported name, asked for by it or an also_asked_as name, a boolean where the catalog gives + // true_value, by default unless report says otherwise (catalog data, README "Per property") + for (const d of S.catalog.values()) { + if ((d.shape !== 'link' && d.shape !== 'both') || d.attribute || d.isHierarchy || d.inverseOfId != null || !this._reportsDef(d, props, true)) continue; + const l = links.find((x) => x.p === d.id); + if (l) this._addReported(params, d, code(l.t), disp(l.t)); } if (this._hasProp(props, 'semanticTag', false)) { // the bracketed suffix of the concept's active fully specified name diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 7e515f221..db4664153 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -403,10 +403,16 @@ class Store { 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, + // the name it is reported and asked for under, further names it is asked for by, and the + // value it is true for where it is reported as a boolean (absent columns: none) + reportedAs: r.reported_as ?? null, alsoAskedAs: r.also_asked_as ? JSON.parse(r.also_asked_as) : [], trueValue: r.true_value ?? 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 (!(Array.isArray(def.alsoAskedAs) && def.alsoAskedAs.every((x) => typeof x === 'string' && x))) { + throw new Error(`${this.file}: property ${def.code} has also_asked_as ${r.also_asked_as}, not a list of names`); + } if (!REPORT.has(def.report)) throw new Error(`${this.file}: property ${def.code} has report ${def.report} (named, always, never or NULL)`); this.catalog.set(def.code, def); this.propsById.set(def.id, def); @@ -448,6 +454,10 @@ class Store { 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 (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`); + 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; } From 5e7762b10aaf86ec1ba31170630f29a593427e3d Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 19:43:12 -0600 Subject: [PATCH 22/90] sqlite-v2: the text search and its tie order are named in the file behaviour.textSearch names the text-search algorithm (an open name with a registry, like grammar: snomed, loinc, rxnorm; null the generic one); the provider picks the search from the file, not from the system. Which names a search reads was already ix.ix_word.names. Ties are meta searchTieBreak: rank, display (then rank), code; absent: concept id. The importers write SNOMED CT snomed/rank, LOINC loinc/display, RxNorm rxnorm/code, which give the answers the per-system rules gave (the parity tests against the built-in providers pass unchanged). Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 43 +++++++++++++++ tx/importers/import-loinc-v2.module.js | 3 ++ tx/importers/import-rxnorm-v2.module.js | 3 ++ tx/importers/sct-v2-common.js | 3 ++ tx/sqlite-v2/README.md | 3 +- tx/sqlite-v2/dialects.js | 3 -- tx/sqlite-v2/meta.js | 4 +- tx/sqlite-v2/provider.js | 18 ++++--- tx/sqlite-v2/text-index.js | 66 ++++++++++++++++++------ 9 files changed, 117 insertions(+), 29 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index ae3ded1c1..9513d75a0 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -847,3 +847,46 @@ describe('P9a/P9b. reported names, extra asked-for names, boolean values; the st expect(() => b.property({ code: 's', shape: 'link', role: 'status' })).toThrow(/status role is for a literal/); }); }); + +describe('P9e. the text search and its tie order are file data', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const ti = require('../../tx/sqlite-v2/text-index'); + let i18n; + beforeAll(async () => { i18n = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())).i18n; }); + // three concepts whose displays tie for "tree": codes, displays and ids in different orders + const ties = (meta = {}) => { + const dest = path.join(dir, `t${++seq}.db`); + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/ties', version: '1' }); + b.setMeta('ix.ix_word.names', { display: 'en' }); + for (const [k, v] of Object.entries(meta)) b.setMeta(k, v); + b.concept('m', { display: 'tree z' }); + b.concept('a', { display: 'tree y' }); + b.concept('z', { display: 'tree x' }); + b.finish(); + return dest; + }; + + test('behaviour.textSearch names the search (registry by name); a name this server does not implement refuses the file', async () => { + expect(ti.textSearchMode(null, 'f')).toBeNull(); + expect(ti.textSearchMode('loinc', 'f')).toBe('display'); + expect(ti.textSearchMode('snomed', 'f')).toBe('designation'); + expect(ti.textSearchMode('rxnorm', 'f')).toBe('rxnorm'); + const f = withMeta(fixture(), { 'behaviour.textSearch': '"bm25"' }); + await expect(new SqliteV2Factory(i18n, f).load()).rejects.toThrow(/its text search is bm25 \(behaviour.textSearch\), which this server does not implement/); + const g = new SqliteV2Factory(i18n, withMeta(fixture(), { 'behaviour.textSearch': '"loinc"' })); + await g.load(); + try { expect(g.searchMode).toBe('display'); } finally { g.store.close(); } + }); + + test('searchTieBreak: code, display; absent: concept id', () => { + const order = (meta) => withStore(ties(meta), (S) => Array.from(ti.genericTextSearch(S, 'tree', 'en', 'en').ids).map((id) => S.conceptRows([id]).get(id).code)); + const byId = withStore(ties(), (S) => ['m', 'a', 'z'].sort((x, y) => S.idOf(x) - S.idOf(y))); + expect(order({})).toEqual(byId); + expect(order({ searchTieBreak: 'code' })).toEqual(['a', 'm', 'z']); + expect(order({ searchTieBreak: 'display' })).toEqual(['z', 'a', 'm']); + expect(() => openStore(withMeta(ties(), { searchTieBreak: 'random' }))).toThrow(/meta searchTieBreak = random is not a value/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 1fe991eee..0a999048c 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -184,6 +184,9 @@ function loincCodeSystem(b, version, description) { // a concept's links in source order (link.seq), as cs-loinc.js reads its Relationships (meta // linkOrder: this reader's LOINC $lookup lists them in its own fixed groups) b.setMeta('linkOrder', 'seq'); + // text search: each concept's best name or code; ties by display, then the stored order + b.setBehaviour('textSearch', 'loinc'); + b.setMeta('searchTieBreak', 'display'); // text search reads the display (English) and every name but RELATEDNAMES2 b.setMeta('ix.ix_word.names', { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); } diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 3cfcd12fa..f96eb9d50 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -66,6 +66,9 @@ async function importRxNormV2(cfg) { b.setBehaviour('distinctDesignationTexts', true); b.setBehaviour('designationUses', 'drop'); b.setBehaviour('versionAlgorithm', 'date'); + // text search: the best atom name or code among the concepts with a non-SY atom; ties by code (text) + b.setBehaviour('textSearch', 'rxnorm'); + b.setMeta('searchTieBreak', 'code'); // text search reads the atoms of the concepts in RXNCONSO (those with a SUPPRESS literal), as English b.setMeta('ix.ix_word.names', { items: { conceptsWith: 'SUPPRESS', language: 'en' } }); // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index d9605ca5b..0cb6c6ea3 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -180,6 +180,9 @@ class SnomedSink { b.setBehaviour('lookupSkipsMixedLinks', true); // versions are URIs (http://snomed.info/sct//version/) b.setBehaviour('versionAlgorithm', 'url'); + // text search: the shortlist by distinct-word count over designations; ties in the stored order + b.setBehaviour('textSearch', 'snomed'); + b.setMeta('searchTieBreak', 'rank'); // text search reads the active descriptions (and text definitions) in their own language, and // ranks one-word filters by each concept's distinct-word count b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 3813acb51..85f9eb5bf 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -198,6 +198,7 @@ refused (the builders check the same at build). | `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 | +| `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | @@ -214,7 +215,7 @@ Two plain-text meta keys say how a reader orders what no rule of its own lists: | key | values | default | meaning | |---|---|---|---| | `linkOrder` | `property`, `seq`, `property-seq`, `target-int` | `property` | the order of a concept's links in `$lookup`: `property` by property id, role group, target code; `seq` by `link.seq` (none: 0), then property, group, target code; `property-seq` by property, `link.seq`, target code; `target-int` by the target code as a number, `link.seq`, property, target code. Codes compare as binary text. ICD-11 files `property-seq`, OMOP `target-int`, LOINC `seq` | -| `searchTieBreak` | `rank` | none | `rank`: text-search hits of equal score in the stored order (`ix_order` `rank`; by concept id where there is none); absent: the reader's own order for ties. ICD-11 files `rank` | +| `searchTieBreak` | `rank`, `display`, `code` | none | the order of text-search hits of equal score: `rank` the stored order (`ix_order` `rank`; by concept id where there is none); `display` the display (String.localeCompare), then the stored order; `code` the code as binary text; absent: concept id. SNOMED CT and ICD-11 files `rank`, LOINC `display`, RxNorm `code` | The JS reader obeys `linkOrder` in the `$lookup` of a system with no adapter of its own; its LOINC and RxNorm adapters list `$lookup` properties in the order of the providers they follow (their diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js index 4a06bfdf8..2d1434715 100644 --- a/tx/sqlite-v2/dialects.js +++ b/tx/sqlite-v2/dialects.js @@ -67,7 +67,6 @@ const loinc = { 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); @@ -173,7 +172,6 @@ const loinc = { 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. @@ -242,7 +240,6 @@ function sctId(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) { diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 6cecc8c05..e94cbd29d 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -79,7 +79,7 @@ const KEYS = Object.freeze({ 'ix.ix_word.names': json(isNames, null), // order (README.md "Order"): plain text values linkOrder: text((v) => ['property', 'seq', 'property-seq', 'target-int'].includes(v), 'property'), - searchTieBreak: text((v) => v === 'rank', null), + searchTieBreak: text((v) => ['rank', 'display', 'code'].includes(v), null), // behaviour settings // an open string: a reader refuses a grammar it does not implement (index.js) 'behaviour.grammar': json((v) => v === null || (isString(v) && v !== ''), null), @@ -95,6 +95,8 @@ const KEYS = Object.freeze({ 'behaviour.preferredForLanguage': json(isBool, false), 'behaviour.aliasLiterals': json((v) => isPlainObject(v) && Object.values(v).every(isString), {}), 'behaviour.expansionLimit': json(isCount, 0), + // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one + 'behaviour.textSearch': json((v) => v === null || (isString(v) && v !== ''), null), 'behaviour.lookupCopyright': json(isBool, false), 'behaviour.lookupDesignationCode': json((v) => v === null || (isString(v) && v !== ''), null), }); diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 2b419afef..4e90d8934 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -25,7 +25,7 @@ const { VersionUtilities } = require('../../library/fhir/version-utilities'); const { SupplementLayers } = require('./layers'); const { HIER_CHILD } = require('./orders'); const { RoaringBitmap32 } = require('roaring'); -const { sctTextSearchG, sctTextLanguages, rxTextSearchG, loincTextSearchG, genericTextSearchG, rxSearchable } = require('./text-index'); +const { sctTextSearchG, sctTextLanguages, rxTextSearchG, loincTextSearchG, genericTextSearchG, rxSearchable, textSearchMode } = require('./text-index'); const { runAsync: runPausing } = require('./engine/evaluate'); const { SupplementTextIndex } = require('../library/supplement-text-index'); const { languageByte, languageCode, languageBytesFor } = require('../sct/languages'); @@ -84,6 +84,7 @@ class SqliteV2Provider extends BaseCSServices { this.store = factory.store; this.engine = factory.engine; this.dialect = factory.dialect; + this.searchMode = factory.searchMode; 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 || []); @@ -960,7 +961,7 @@ class SqliteV2Provider extends BaseCSServices { */ _regexLanguage() { const primary = (c) => String(c || '').toLowerCase().split('-')[0]; - if (this.dialect.searchMode === 'designation') { + if (this.searchMode === 'designation') { const requested = (this._requestedLangs && this._requestedLangs.languages) || []; return this._sctFilterLanguage(requested.map((l) => l && l.language)); } @@ -1065,19 +1066,19 @@ class SqliteV2Provider extends BaseCSServices { */ async searchFilter(prep, filter) { const text = typeof filter === 'string' ? filter : (filter && filter.filter) || ''; - const node = { t: 'search', text, mode: this.dialect.searchMode }; + const node = { t: 'search', text, mode: this.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 searchLang = this.searchMode === 'designation' ? this._sctSearchLanguage(prep ? prep.languages : this._requestedLangs) : this.searchLanguage(requested); node.lang = (searchLang.language || this.defLang() || 'en').toLowerCase(); node.defLang = this.defLang(); let n = node; - if (this.dialect.searchMode !== 'rxnorm' && this.supplements && this.supplements.length && filter && typeof filter.passes === 'function') { + if (this.searchMode !== 'rxnorm' && this.supplements && this.supplements.length && filter && typeof filter.passes === 'function') { const sources = new Map(); const codes = await this._supplementSearchCodes(filter, searchLang, sources); const base = codes.size ? ((await this._pausing(this.store.searchTextG(text, this._stats(), node.mode, node.lang, node.defLang))) || new RoaringBitmap32()) : null; const ids = []; - const active = this.dialect.searchMode === 'designation' ? this.store.active(this._stats()) : null; + const active = this.searchMode === 'designation' ? this.store.active(this._stats()) : null; const idsOf = this.store.resolveCodes([...codes].map((c) => this.normaliseCode(c)), this._stats()); for (const code of codes) { const id = idsOf.get(this.normaliseCode(code)); @@ -1121,7 +1122,7 @@ class SqliteV2Provider extends BaseCSServices { /** the order the built-in provider lists text-search results in (text-index.js) */ async _searchOrder(bm, text, extras = null, lang = null) { const keep = (ids) => { const out = []; for (const id of ids) if (bm.has(id)) out.push(id); return out; }; - const mode = this.dialect.searchMode; + const mode = this.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 @@ -1474,6 +1475,9 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { 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} (behaviour.grammar), which this provider serves`); } this.dialect = dialectFor(this.store.system); + // the text search the file names (behaviour.textSearch; text-index.js TEXT_SEARCHES), or the + // generic one (null) + this.searchMode = textSearchMode(this.store.behaviour.textSearch, this.file); // behaviour.expansionOrder: concept ids, or the stored order (ix_order) const kind = this.store.behaviour.expansionOrder; const order = kind !== 'ids' ? this._systemOrder(kind) : null; diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js index 4d95aa0de..a99116e2d 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -62,6 +62,43 @@ function primaryLanguage(code, defLang) { return languageOf(code || null, defLang || 'en'); } +// ---- the text searches a file may name ------------------------------------------------------ + +/** + * The text searches, by the name a file gives them (meta behaviour.textSearch), each the ranking of + * a FHIRsmith provider (see the top of this file): name -> the search mode store.searchText runs. + * null: the generic search (cs-cs.js rules). A name not here refuses the file. + */ +const TEXT_SEARCHES = Object.freeze({ + snomed: 'designation', // shortlist by distinct-word count, best designation; active concepts + loinc: 'display', // best name (or code range) per concept + rxnorm: 'rxnorm', // best atom name or code, among concepts with a non-SY RXNCONSO atom +}); + +/** + * The order of text-search hits of equal score (meta searchTieBreak; README.md "Order"), as an + * ordinal over the hits: 'rank' the stored rank; 'display' the display (String.localeCompare), then + * the stored rank; 'code' the code as binary text; absent: concept id + */ +function tieOrdinal(store, ids, stats) { + const kind = store.searchTieBreak; + if (kind === 'rank') return store.rankOrdinal(); + if (kind !== 'display' && kind !== 'code') return (id) => id; + const rows = store.conceptRows(Array.from(ids), stats); + const rank = store.rankOrdinal(); + const key = (id) => String((rows.get(id) || {})[kind] ?? ''); + const cmp = kind === 'display' ? (a, b) => key(a).localeCompare(key(b)) || rank(a) - rank(b) : (a, b) => cmpBinary(key(a), key(b)) || a - b; + const pos = new Map([...ids].sort(cmp).map((id, i) => [id, i])); + return (id) => pos.get(id) ?? Infinity; +} + +/** the search mode for behaviour.textSearch (null: generic); throws for a name this server does not implement */ +function textSearchMode(name, file) { + if (name == null) return null; + if (Object.prototype.hasOwnProperty.call(TEXT_SEARCHES, name)) return TEXT_SEARCHES[name]; + throw new Error(`${file}: its text search is ${name} (behaviour.textSearch), which this server does not implement`); +} + // ---- the names ------------------------------------------------------------------------------ /** @@ -501,8 +538,6 @@ function sctCodeMatches(store, q, active, stats) { * @returns {{bm: RoaringBitmap32, ids: Uint32Array}} active matches; ids best first */ function* sctTextSearchG(store, text, lang, ordinal, stats = null) { - // meta searchTieBreak 'rank': ties in the stored rank order - if (store.searchTieBreak === 'rank') ordinal = store.rankOrdinal(); return yield* cached(store, 'sct\u0000' + lang + '\u0000' + text, function* () { const q = new TextQuery(text); const tokens = q.tokens(lang); @@ -511,6 +546,8 @@ function* sctTextSearchG(store, text, lang, ordinal, stats = null) { if (tokens.length) { const index = textIndexOf(store); const bm = (yield* candidates(index, lang, tokens, stats)).andInPlace(active); + // ties (and the shortlist's concept order) by meta searchTieBreak + ordinal = tieOrdinal(store, bm.toArray(), stats); 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); @@ -603,8 +640,6 @@ function rxSearchable(store, stats) { * @returns {{bm: RoaringBitmap32, ids: Uint32Array}} */ function* loincTextSearchG(store, text, lang, ordinal, stats = null) { - // meta searchTieBreak 'rank': ties in the stored rank order - if (store.searchTieBreak === 'rank') ordinal = store.rankOrdinal(); return yield* cached(store, 'loinc\u0000' + lang + '\u0000' + text, function* () { const q = new TextQuery(text); const rank = new Map(); // concept -> rank (cs-loinc.js: codeRank, then a better nameRank) @@ -627,12 +662,9 @@ function* loincTextSearchG(store, text, lang, ordinal, stats = null) { } } 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 - // (meta searchTieBreak 'rank': ties in the stored rank order instead) - const tie = store.searchTieBreak === 'rank' ? null : (a, b) => disp(a).localeCompare(disp(b)); - const ids = yield* sortG([...rank.keys()], (a, b) => (rank.get(b) - rank.get(a)) || (tie ? tie(a, b) : 0) || ordinal(a) - ordinal(b)); + // the best first; ties by meta searchTieBreak (LOINC files: display, as cs-loinc.js, then CodeKey) + const ord = tieOrdinal(store, [...rank.keys()], stats); + const ids = yield* sortG([...rank.keys()], (a, b) => (rank.get(b) - rank.get(a)) || ord(a) - ord(b)); return { bm: new RoaringBitmap32(ids), ids: Uint32Array.from(ids) }; }); } @@ -665,10 +697,10 @@ function* rxTextSearchG(store, text, eligible, stats = null) { 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) - // (meta searchTieBreak 'rank': ties in the stored rank order instead) - const ord = store.searchTieBreak === 'rank' ? store.rankOrdinal() : null; - const ids = yield* sortG(bm.toArray(), (a, b) => (rank.get(b) - rank.get(a)) || (ord ? ord(a) - ord(b) : cmpBinary(code(a), code(b)))); + // cs-rxnorm.js #rank: the best first (nameRank or codeRank); ties by meta searchTieBreak (RxNorm + // files: code, RXCUI order as text) + const ord = tieOrdinal(store, bm.toArray(), stats); + const ids = yield* sortG(bm.toArray(), (a, b) => (rank.get(b) - rank.get(a)) || ord(a) - ord(b)); return { bm, ids: Uint32Array.from(ids) }; }); } @@ -746,8 +778,8 @@ function* blockConcepts(store, csLang, stats) { function* genericTextSearchG(store, text, lang, csLang, stats = null, supplementCodes = null) { const run = function* () { let hits = yield* rateConceptsG(blockConcepts(store, csLang, stats), new TextQuery(text), lang, supplementCodes); - // meta searchTieBreak 'rank': ties in the stored rank order (else in concept id order) - if (store.searchTieBreak === 'rank') { const ord = store.rankOrdinal(); hits = yield* sortG(hits, (a, b) => b.rating - a.rating || ord(a.id) - ord(b.id)); } + // ties by meta searchTieBreak (absent: in concept id order, as rated) + if (store.searchTieBreak != null) { const ord = tieOrdinal(store, hits.map((h) => h.id), stats); hits = yield* sortG(hits, (a, b) => b.rating - a.rating || ord(a.id) - ord(b.id)); } const ids = hits.map((h) => h.id); return { bm: new RoaringBitmap32(ids), ids: Uint32Array.from(ids) }; }; @@ -761,7 +793,7 @@ const rxTextSearch = (...a) => runSync(rxTextSearchG(...a)); const genericTextSearch = (...a) => runSync(genericTextSearchG(...a)); module.exports = { - FORMAT, WordIndex, SplitTextIndex, blockConcepts, eachSearchName, searchNamesOf, searchNamesSelection, rxSearchable, + FORMAT, WordIndex, SplitTextIndex, TEXT_SEARCHES, textSearchMode, blockConcepts, eachSearchName, searchNamesOf, searchNamesSelection, rxSearchable, computeTextIndexFrom, textIndexOf, primaryLanguage, countsFromLE, countsToLE, usableLanguages, sctTextSearch, sctTextLanguages, loincTextSearch, rxTextSearch, genericTextSearch, rateConcepts, sctTextSearchG, loincTextSearchG, rxTextSearchG, genericTextSearchG From 37b05ee2dacaf03ce9744ee02407df01785eedca Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 19:49:11 -0600 Subject: [PATCH 23/90] sqlite-v2: behaviour.aliases replaces the three alias keys One key for identifier-aliased codes: behaviour.aliases = null or {parameter?, extension?, literals?} (any other field malformed), each field meaning what aliasProperty, aliasExtension and aliasLiterals meant; those three are removed (now unknown keys, ignored). This reader does not implement identifier aliases and refuses a file that sets it. Co-Authored-By: Claude --- tests/tx/sqlite-v2-builder.test.js | 7 +++---- tests/tx/sqlite-v2-format-round2.test.js | 12 ++++++++---- tx/importers/sqlite-v2/schema.sql | 6 +++--- tx/sqlite-v2/README.md | 4 +--- tx/sqlite-v2/meta.js | 8 +++++--- tx/sqlite-v2/store.js | 9 +++------ 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js index 849531be7..aaf964174 100644 --- a/tests/tx/sqlite-v2-builder.test.js +++ b/tests/tx/sqlite-v2-builder.test.js @@ -368,12 +368,11 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check 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.aliases', '{"literals": {"code-type": 11}}', /behaviour.aliases = .* 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/); // identifier-aliased codes: this reader does not implement them, and refuses a file that sets them - bad('behaviour.aliasLiterals', '{"code-type": "11-digit", "synonym": "{code}"}', /behaviour.aliasLiterals is set .* which this server does not implement/); - bad('behaviour.aliasProperty', '"classificationCode"', /behaviour.aliasProperty is set/); + bad('behaviour.aliases', '{"literals": {"code-type": "11-digit", "synonym": "{code}"}}', /behaviour.aliases is set .* which this server does not implement/); const good = path.join(dir, 'behaviour-ok.db'); fs.copyFileSync(file, good); const w = new Database(good); @@ -386,7 +385,7 @@ describe('sqlite-v2 identifiers accepted as codes; definitions; the format check try { expect(G.behaviour.preferredForLanguage).toBe(true); expect(G.behaviour.colour).toBeUndefined(); - expect(G.behaviour.aliasLiterals).toEqual({}); + expect(G.behaviour.aliases).toBeNull(); expect(G.behaviour.filters.map((f) => f.code)).toEqual(['inactive', 'category']); } finally { G.close(); } const b = new TerminologyBuilder(path.join(dir, 'never.db'), { overwrite: true, importer: 'test' }); diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 9513d75a0..f98b8c046 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -401,10 +401,14 @@ describe('P4. behaviour and order keys: the file\'s value obeyed, absent = the d withStore(f, (S) => expect(codes(S, gen(S, 'tree', 'en', 'en').ids)).toEqual(['B', 'A'])); }); - test('aliasProperty, aliasExtension, aliasLiterals: this reader does not implement them and refuses a file that sets one', () => { - expect(() => openStore(withMeta(base, { 'behaviour.aliasExtension': '"http://example.org/ext"' }))).toThrow(/behaviour.aliasExtension is set .* does not implement/); - expect(() => openStore(withMeta(base, { 'behaviour.aliasLiterals': '{"kind": "{code}"}' }))).toThrow(/behaviour.aliasLiterals is set/); - withStore(withMeta(base, { 'behaviour.aliasLiterals': '{}', 'behaviour.aliasProperty': 'null' }), (S) => expect(S.behaviour.aliasLiterals).toEqual({})); + test('behaviour.aliases (identifier-aliased codes): this reader does not implement them and refuses a file that sets it; the three old keys are unknown', () => { + expect(() => openStore(withMeta(base, { 'behaviour.aliases': '{"extension": "http://example.org/ext"}' }))).toThrow(/behaviour.aliases is set .* does not implement/); + expect(() => openStore(withMeta(base, { 'behaviour.aliases': '{"literals": {"kind": "{code}"}}' }))).toThrow(/behaviour.aliases is set/); + expect(() => openStore(withMeta(base, { 'behaviour.aliases': '{"param": "x"}' }))).toThrow(/behaviour.aliases = .* is not a value/); + withStore(withMeta(base, { 'behaviour.aliases': 'null', 'behaviour.aliasLiterals': '{"kind": "{code}"}', 'behaviour.aliasProperty': '"x"' }), (S) => { + expect(S.behaviour.aliases).toBeNull(); + expect(S.behaviour.aliasLiterals).toBeUndefined(); + }); }); }); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 688d9eb4c..047669ca2 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -34,9 +34,9 @@ CREATE TABLE code_system ( ); -- 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; +-- how the system is presented (grammar, filters, expansionOrder, lookupName, versionAlgorithm, +-- designationUses, distinctDesignationTexts, preferredForLanguage, aliases, expansionLimit, textSearch, +-- lookupCopyright, lookupDesignationCode; -- values and defaults in tx/sqlite-v2/README.md "Meta"). `requires` (JSON list) names the features the -- content uses that a reader must understand: a reader refuses a file that requires one it does not -- know. A reader ignores a key it does not know and refuses a malformed value of one it knows; a diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 85f9eb5bf..c027b1566 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -194,10 +194,8 @@ refused (the builders check the same at build). | `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | | `lookupSkipsMixedLinks` | `true`, `false` | `false` | SNOMED CT `true`: a `both` attribute's links are not read where no property is named (main keeps one value kind per attribute) | -| `aliasProperty` | a property code, `null` | `null` | ICD-11 MMS and ICF files `"classificationCode"`: $validate-code of a code written in its canonical form also returns its alias (an identifier with `resolves = 1`) as an output parameter of this name. The JS reader does not implement identifier aliases and refuses a file that sets this, `aliasExtension` or `aliasLiterals` | -| `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) | +| `aliases` | `null`, or `{"parameter"?, "extension"?, "literals"?}` (any other field: malformed) | `null` | identifier-aliased codes (identifiers with `resolves` 1 or 2). `parameter`: `$validate-code` of a code written in its canonical form also returns its alias (`resolves = 1`) as an output parameter of this name. `extension`: a Coding extension that restates the alias form of its code, which `$validate-code` checks against the code's alias. `literals` (property code -> value): the literal values a concept reports when read through an identifier code instead of its stored values of those properties; `{code}` is the concept's own code. ICD-11 MMS and ICF `{"parameter": "classificationCode", "extension": "http://id.who.int/icd/schema/extension/classificationCode"}`, Foundation `{"extension": ...}`, NDC `{"literals": {"code-type": "11-digit", "synonym": "{code}"}}`. The JS reader does not implement identifier aliases and refuses a file that sets it | | `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 | | `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index e94cbd29d..f986a66a8 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -90,10 +90,12 @@ const KEYS = Object.freeze({ 'behaviour.designationUses': json((v) => v === 'keep' || v === 'drop', 'keep'), 'behaviour.distinctDesignationTexts': json(isBool, false), 'behaviour.lookupSkipsMixedLinks': json(isBool, false), - 'behaviour.aliasProperty': json((v) => v === null || isString(v), null), - 'behaviour.aliasExtension': json((v) => v === null || isString(v), null), 'behaviour.preferredForLanguage': json(isBool, false), - 'behaviour.aliasLiterals': json((v) => isPlainObject(v) && Object.values(v).every(isString), {}), + // identifier-aliased codes: {parameter?, extension?, literals?} (README.md "Behaviour settings") + 'behaviour.aliases': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['parameter', 'extension', 'literals']) + && (v.parameter === undefined || (isString(v.parameter) && v.parameter !== '')) + && (v.extension === undefined || (isString(v.extension) && v.extension !== '')) + && (v.literals === undefined || (isPlainObject(v.literals) && Object.values(v.literals).every(isString)))), null), 'behaviour.expansionLimit': json(isCount, 0), // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one 'behaviour.textSearch': json((v) => v === null || (isString(v) && v !== ''), null), diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index db4664153..f4103abe2 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -337,11 +337,9 @@ class Store { // how text-search hits of equal score are ordered (null: each search's own order) this.linkOrder = m.linkOrder; this.searchTieBreak = m.searchTieBreak; - // identifier-aliased codes (behaviour.aliasProperty, aliasExtension, aliasLiterals): this server - // does not implement them, and would answer such a file's codes wrongly - for (const k of ['aliasProperty', 'aliasExtension']) { - if (m.behaviour[k] !== null) throw new Error(`${this.file}: behaviour.${k} is set (identifier-aliased codes), which this server does not implement`); - } + // identifier-aliased codes (behaviour.aliases): this server does not implement them, and would + // answer such a file's codes wrongly + if (m.behaviour.aliases !== null) throw new Error(`${this.file}: behaviour.aliases is set (identifier-aliased codes), which this server does not implement`); // behaviour.lookupCopyright: the notice $lookup lists (code_system.resource.copyright) this.copyright = null; if (m.behaviour.lookupCopyright) { @@ -350,7 +348,6 @@ class Store { if (!r || typeof r.copyright !== 'string' || !r.copyright) throw new Error(`${this.file}: behaviour.lookupCopyright without code_system.resource.copyright`); this.copyright = r.copyright; } - if (Object.keys(m.behaviour.aliasLiterals).length) throw new Error(`${this.file}: behaviour.aliasLiterals is set (identifier-aliased codes), which this server does not implement`); // a compositional system's expansions are never closed (post-coordinated expressions are codes) this.notClosed = cs.compositional === 1; this.defaultLanguage = cs.default_language || null; From 6afd28397b3b5eb722bd909073323fb0e9bcda4a Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 19:51:41 -0600 Subject: [PATCH 24/90] sqlite-v2: property.named_links replaces behaviour.lookupSkipsMixedLinks A catalog fact per property instead of a file-wide flag: named_links = 1 means the property's links are read only where it is named (a $lookup asking for it, a filter, an ECL refinement); its literals follow report as usual. The SNOMED CT importer sets it on every shape both attribute (what the file key meant). The links left out where no property is named are the closure sources and the named_links properties. The file key is removed. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 31 ++++++++++++++++++++++++ tx/importers/sct-v2-common.js | 7 +++--- tx/importers/sqlite-v2/builder.js | 11 +++++---- tx/importers/sqlite-v2/schema.sql | 2 ++ tx/sqlite-v2/README.md | 7 +++++- tx/sqlite-v2/meta.js | 1 - tx/sqlite-v2/store.js | 6 ++--- 7 files changed, 52 insertions(+), 13 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index f98b8c046..7082e4168 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -894,3 +894,34 @@ describe('P9e. the text search and its tie order are file data', () => { expect(() => openStore(withMeta(ties(), { searchTieBreak: 'random' }))).toThrow(/meta searchTieBreak = random is not a value/); }); }); + +describe('property.named_links: links read only where the property is named', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + test('$lookup leaves the links out unless the property is asked for; its literals as usual; the old file key is unknown', async () => { + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + // (the old file key is unknown to the builder too, so it is added to the built file) + const file = withMeta(fixture((b, c) => { + const size = b.property({ code: 'size', shape: 'both', fhirType: 'string', namedLinks: true }); + b.link(c.A, size, c.B); + b.literal(c.A, size, 'large'); + }), { 'behaviour.lookupSkipsMixedLinks': 'true' }); + const db = new Database(file, { readonly: true }); + try { expect(db.prepare("SELECT named_links FROM property WHERE code = 'size'").pluck().get()).toBe(1); } finally { db.close(); } + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + expect(f.store.behaviour.lookupSkipsMixedLinks).toBeUndefined(); + const p = await f.build(op, []); + const lookup = async (props) => { + const params = []; + await p.extendLookup((await p.locate('A')).context, props, params); + return params.map((x) => x.part[0].valueCode + '=' + (x.part[1].valueCode || x.part[1].valueString)).filter((x) => x.startsWith('size')); + }; + expect(await lookup([])).toEqual(['size=large']); + expect(f.store.linksFrom([f.store.idOf('A')]).some((l) => l.p === f.store.catalog.get('size').id)).toBe(false); + expect(f.store.linksFrom([f.store.idOf('A')], new Set([f.store.catalog.get('size').id])).length).toBe(1); + } finally { f.store.close(); } + }); +}); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 0cb6c6ea3..b6dbea662 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -32,7 +32,7 @@ // refset, one identifier row per scheme // code_system compositional = 1 (post-coordinated expressions are codes too, so an // expansion is never closed) -// behaviour grammar 'snomed', expansionOrder 'stored-self-first', lookupSkipsMixedLinks +// behaviour grammar 'snomed', expansionOrder 'stored-self-first' // 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 @@ -177,7 +177,6 @@ class SnomedSink { // 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); // versions are URIs (http://snomed.info/sct//version/) b.setBehaviour('versionAlgorithm', 'url'); // text search: the shortlist by distinct-word count over designations; ties in the stored order @@ -294,7 +293,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: its links are read only where it is + // named (cs-snomed.js keeps one value kind per attribute: $lookup reads its concrete values) + return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: both ? 'both' : 'literal', fhirType, refinable: true, wildcard: true, namedLinks: both }); } /** an active inferred concrete value row; s: concept handle; raw: the RF2 value (#n, "s", true) */ diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index f6e7e7ca3..6b4c2a027 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -173,7 +173,8 @@ class TerminologyBuilder { * ranks displays, by meta displayContexts), filterOps (the FHIR operators a filter on it accepts), * report ('named' | 'always' | 'never': when $lookup and expansions report it), reportedAs (the * name it is reported and asked for under), alsoAskedAs ([names] a request may also ask by), - * trueValue (reported as a boolean: true when its value is this) } + * trueValue (reported as a boolean: true when its value is this), namedLinks (its links are read + * only where the property is named) } */ property(spec) { const cs = spec.cs || 1; @@ -204,7 +205,7 @@ class TerminologyBuilder { filterable: spec.filterable === false ? 0 : 1, refinable: spec.refinable ? 1 : 0, wildcard: spec.wildcard ? 1 : 0, inverseOf: spec.inverseOf ?? null, byTarget: spec.byTarget == null ? null : (spec.byTarget ? 1 : 0), bySubject: spec.shape === 'identifier' && spec.bySubject !== false ? 1 : 0, - ordered: spec.ordered ? 1 : 0, + ordered: spec.ordered ? 1 : 0, namedLinks: spec.namedLinks ? 1 : 0, filterOps: spec.filterOps ? JSON.stringify(spec.filterOps) : null, report: spec.report ?? null, fields: spec.fields ? JSON.stringify(spec.fields) : null, reportedAs: spec.reportedAs ?? null, alsoAskedAs: spec.alsoAskedAs && spec.alsoAskedAs.length ? JSON.stringify(spec.alsoAskedAs) : null, @@ -486,9 +487,9 @@ class TerminologyBuilder { const nodeId = (h) => (h == null ? null : h >= 0 ? idOf[h] : db.prepare('SELECT new FROM st.s_node WHERE old = ?').pluck().get(h)); const computed = this._time('catalog computed fields', () => catalogStats(db, n)); const insProp = db.prepare(`INSERT INTO property (id, cs_id, code, uri, display, concept_id, shape, role, fhir_type, subject_kind, - subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, filter_ops, report, reported_as, + subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, named_links, filter_ops, report, reported_as, also_asked_as, true_value, fields) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); const parents = new Set(this.members.map(([a]) => a)); for (const p of this.properties) { // subject_kind NULL for a catalog row with no rows @@ -503,7 +504,7 @@ class TerminologyBuilder { 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, - p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.filterOps, p.report, p.reportedAs, + p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.namedLinks, p.filterOps, p.report, p.reportedAs, p.alsoAskedAs, p.trueValue, p.fields); } const insMember = db.prepare('INSERT OR IGNORE INTO property_member VALUES (?, ?)'); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 047669ca2..5a5fb0304 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -83,6 +83,8 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat by_subject INTEGER NOT NULL DEFAULT 0, -- shape 'identifier': its rows are read by subject (ix_by_subject); the -- builder's default for an identifier row is 1, an importer sets 0 for -- rows only ever read by value (RxNorm atom relationships AUI:*) + named_links INTEGER NOT NULL DEFAULT 0, -- 1: its links are read only where the property is named (a $lookup + -- asking for it, a filter, an ECL refinement); left out elsewhere 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) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index c027b1566..f33bc511e 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -193,7 +193,6 @@ refused (the builders check the same at build). | `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm: how a requested version (check-system-version) matches the file's version (FHIRsmith `versionMatchesByAlgorithm`: `semver` with wildcards, `integer` exactly, any other value by prefix). `null`: what the stored CodeSystem resource declares (`versionAlgorithmString` / `versionAlgorithmCoding`), else only the exact version matches; no guess from the version string and no rule of the reader's own for a system. Every importer writes it: SNOMED CT `"url"` (versions are edition URIs, matched by prefix), LOINC `"natural"`, RxNorm `"date"` | | `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | -| `lookupSkipsMixedLinks` | `true`, `false` | `false` | SNOMED CT `true`: a `both` attribute's links are not read where no property is named (main keeps one value kind per attribute) | | `aliases` | `null`, or `{"parameter"?, "extension"?, "literals"?}` (any other field: malformed) | `null` | identifier-aliased codes (identifiers with `resolves` 1 or 2). `parameter`: `$validate-code` of a code written in its canonical form also returns its alias (`resolves = 1`) as an output parameter of this name. `extension`: a Coding extension that restates the alias form of its code, which `$validate-code` checks against the code's alias. `literals` (property code -> value): the literal values a concept reports when read through an identifier code instead of its stored values of those properties; `{code}` is the concept's own code. ICD-11 MMS and ICF `{"parameter": "classificationCode", "extension": "http://id.who.int/icd/schema/extension/classificationCode"}`, Foundation `{"extension": ...}`, NDC `{"literals": {"code-type": "11-digit", "synonym": "{code}"}}`. The JS reader does not implement identifier aliases and refuses a file that sets it | | `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 | | `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | @@ -229,6 +228,12 @@ reports it by default and when asked for). RxNorm files set `never` on SUPPRESS `classificationCode` in MMS and ICF; NDC files `never` on `kind` (a filter only). A filter-only property is `never` with `filterable = 1`: one value, as filterability is the separate `filterable` column. +`property.named_links` (0 or 1, default 0): 1 = the property's links are read only where the property +is named (a `$lookup` asking for it, a filter, an ECL refinement); where no property is named they are +left out (its literals follow `report` as usual). SNOMED CT files set it on every shape `both` +attribute (one with relationship rows and concrete values). The links a reader leaves out where no +property is named are those of the closure sources and the `named_links = 1` properties. + How a property is reported and asked for (three nullable columns; NULL: absent): | column | meaning | default | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index f986a66a8..123ad10b5 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -89,7 +89,6 @@ const KEYS = Object.freeze({ 'behaviour.versionAlgorithm': json((v) => v === null || isString(v), null), 'behaviour.designationUses': json((v) => v === 'keep' || v === 'drop', 'keep'), 'behaviour.distinctDesignationTexts': json(isBool, false), - 'behaviour.lookupSkipsMixedLinks': json(isBool, false), 'behaviour.preferredForLanguage': json(isBool, false), // identifier-aliased codes: {parameter?, extension?, literals?} (README.md "Behaviour settings") 'behaviour.aliases': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['parameter', 'extension', 'literals']) diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index f4103abe2..5ffa7079e 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -396,6 +396,7 @@ class Store { subjectKind: r.subject_kind, conceptId: r.concept_id, isHierarchy: !!r.subsumption, closureFrom: r.closure_from, filterable: !!r.filterable, refinable: !!r.refinable, wildcard: !!r.wildcard, byTarget: !!r.by_target, bySubject: !!r.by_subject, ordered: !!r.ordered, role: r.role, + namedLinks: !!r.named_links, 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 @@ -434,9 +435,8 @@ class Store { 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), and not one whose links are read only where it is named (property.named_links) + this.hiddenLinks = [...this.catalog.values()].filter((d) => d.namedLinks || closureSources.has(d.id)).map((d) => d.id); // the reference sets: record relations by their concept; the language ones rank displays this.relations = new Map(); this.langRelations = new Map(); // relation id -> refset concept id From 11a2ff43c4cf7438e8e6405ab8a07e1614c0b39a Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 21:13:19 -0600 Subject: [PATCH 25/90] sqlite-v2: searchTieBreak code-length; refuse a catalog without the reporting columns searchTieBreak gains code-length: the code's length, then the code as binary text (numeric order for numeric codes). The SNOMED CT importer writes it: it is the order of the stored rank SNOMED CT files carry, so answers are unchanged (the parity tests pass as written), and it does not depend on the expansion order. A file whose property table lacks reported_as, also_asked_as, true_value or named_links was built before them and is refused with a message to rebuild or upgrade it. A text search the reader does not implement (icd11 included) refuses the file, as before; tested. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 25 ++++++++++++++++++++++++ tx/importers/sct-v2-common.js | 5 +++-- tx/sqlite-v2/README.md | 7 ++++--- tx/sqlite-v2/meta.js | 2 +- tx/sqlite-v2/store.js | 5 +++++ tx/sqlite-v2/text-index.js | 11 +++++++---- 6 files changed, 45 insertions(+), 10 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 7082e4168..681e2c907 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -878,6 +878,8 @@ describe('P9e. the text search and its tie order are file data', () => { expect(ti.textSearchMode('loinc', 'f')).toBe('display'); expect(ti.textSearchMode('snomed', 'f')).toBe('designation'); expect(ti.textSearchMode('rxnorm', 'f')).toBe('rxnorm'); + // icd11 is a search another reader implements; this one does not + await expect(new SqliteV2Factory(i18n, withMeta(fixture(), { 'behaviour.textSearch': '"icd11"' })).load()).rejects.toThrow(/its text search is icd11 .* does not implement/); const f = withMeta(fixture(), { 'behaviour.textSearch': '"bm25"' }); await expect(new SqliteV2Factory(i18n, f).load()).rejects.toThrow(/its text search is bm25 \(behaviour.textSearch\), which this server does not implement/); const g = new SqliteV2Factory(i18n, withMeta(fixture(), { 'behaviour.textSearch': '"loinc"' })); @@ -891,6 +893,19 @@ describe('P9e. the text search and its tie order are file data', () => { expect(order({})).toEqual(byId); expect(order({ searchTieBreak: 'code' })).toEqual(['a', 'm', 'z']); expect(order({ searchTieBreak: 'display' })).toEqual(['z', 'a', 'm']); + // code-length: numeric order for numeric codes (binary text would put 100 before 9) + const numeric = (meta) => { + const dest = path.join(dir, `n${++seq}.db`); + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/numeric', version: '1' }); + b.setMeta('ix.ix_word.names', { display: 'en' }); + for (const [k, v] of Object.entries(meta)) b.setMeta(k, v); + for (const [c, d] of [['100', 'tree x'], ['9', 'tree y'], ['20', 'tree z']]) b.concept(c, { display: d }); + b.finish(); + return withStore(dest, (S) => Array.from(ti.genericTextSearch(S, 'tree', 'en', 'en').ids).map((id) => S.conceptRows([id]).get(id).code)); + }; + expect(numeric({ searchTieBreak: 'code-length' })).toEqual(['9', '20', '100']); + expect(numeric({ searchTieBreak: 'code' })).toEqual(['100', '20', '9']); expect(() => openStore(withMeta(ties(), { searchTieBreak: 'random' }))).toThrow(/meta searchTieBreak = random is not a value/); }); }); @@ -925,3 +940,13 @@ describe('property.named_links: links read only where the property is named', () } finally { f.store.close(); } }); }); + +describe('a catalog without the reporting columns is refused', () => { + test('a property table lacking reported_as / also_asked_as / true_value / named_links: upgrade it', () => { + const f = withMeta(fixture(), {}); + const w = new Database(f); + w.exec('ALTER TABLE property DROP COLUMN true_value; ALTER TABLE property DROP COLUMN named_links'); + w.close(); + expect(() => openStore(f)).toThrow(/built before the catalog columns true_value, named_links existed: rebuild it with the importers, or upgrade it/); + }); +}); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index b6dbea662..f233e93b9 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -179,9 +179,10 @@ class SnomedSink { b.setBehaviour('expansionOrder', 'stored-self-first'); // versions are URIs (http://snomed.info/sct//version/) b.setBehaviour('versionAlgorithm', 'url'); - // text search: the shortlist by distinct-word count over designations; ties in the stored order + // text search: the shortlist by distinct-word count over designations; ties in code order as + // numbers (the order of the stored rank, cs-snomed.js's concept order) b.setBehaviour('textSearch', 'snomed'); - b.setMeta('searchTieBreak', 'rank'); + b.setMeta('searchTieBreak', 'code-length'); // text search reads the active descriptions (and text definitions) in their own language, and // ranks one-word filters by each concept's distinct-word count b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index f33bc511e..32d34e63d 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -137,7 +137,8 @@ each check and exits 1 when one fails, the file cannot be read included (non-zer Readers carry no path for a file built before a key existed: such a file is read by the rules above (an absent key has its default) or refused where that would give wrong answers (no -`identifier-text`). Rebuild it with the importers, or upgrade it (the other implementation's +`identifier-text`; a catalog without the columns `reported_as`, `also_asked_as`, `true_value` and +`named_links`). Rebuild it with the importers, or upgrade it (the other implementation's `tx-import upgrade` writes a file with every key this format now has). ## Meta @@ -195,7 +196,7 @@ refused (the builders check the same at build). | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | | `aliases` | `null`, or `{"parameter"?, "extension"?, "literals"?}` (any other field: malformed) | `null` | identifier-aliased codes (identifiers with `resolves` 1 or 2). `parameter`: `$validate-code` of a code written in its canonical form also returns its alias (`resolves = 1`) as an output parameter of this name. `extension`: a Coding extension that restates the alias form of its code, which `$validate-code` checks against the code's alias. `literals` (property code -> value): the literal values a concept reports when read through an identifier code instead of its stored values of those properties; `{code}` is the concept's own code. ICD-11 MMS and ICF `{"parameter": "classificationCode", "extension": "http://id.who.int/icd/schema/extension/classificationCode"}`, Foundation `{"extension": ...}`, NDC `{"literals": {"code-type": "11-digit", "synonym": "{code}"}}`. The JS reader does not implement identifier aliases and refuses a file that sets it | | `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 | -| `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | +| `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. ICD-11 files name `icd11`, which the JS reader does not implement (such a file is refused). SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | @@ -212,7 +213,7 @@ Two plain-text meta keys say how a reader orders what no rule of its own lists: | key | values | default | meaning | |---|---|---|---| | `linkOrder` | `property`, `seq`, `property-seq`, `target-int` | `property` | the order of a concept's links in `$lookup`: `property` by property id, role group, target code; `seq` by `link.seq` (none: 0), then property, group, target code; `property-seq` by property, `link.seq`, target code; `target-int` by the target code as a number, `link.seq`, property, target code. Codes compare as binary text. ICD-11 files `property-seq`, OMOP `target-int`, LOINC `seq` | -| `searchTieBreak` | `rank`, `display`, `code` | none | the order of text-search hits of equal score: `rank` the stored order (`ix_order` `rank`; by concept id where there is none); `display` the display (String.localeCompare), then the stored order; `code` the code as binary text; absent: concept id. SNOMED CT and ICD-11 files `rank`, LOINC `display`, RxNorm `code` | +| `searchTieBreak` | `rank`, `display`, `code`, `code-length` | none | the order of text-search hits of equal score: `rank` the stored order (`ix_order` `rank`; by concept id where there is none); `display` the display (String.localeCompare), then the stored order; `code` the code as binary text; `code-length` the code's length, then the code as binary text (numeric order for numeric codes such as SCTIDs); absent: concept id. SNOMED CT `code-length`, ICD-11 `rank`, LOINC `display`, RxNorm `code` | The JS reader obeys `linkOrder` in the `$lookup` of a system with no adapter of its own; its LOINC and RxNorm adapters list `$lookup` properties in the order of the providers they follow (their diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 123ad10b5..fec729b60 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -79,7 +79,7 @@ const KEYS = Object.freeze({ 'ix.ix_word.names': json(isNames, null), // order (README.md "Order"): plain text values linkOrder: text((v) => ['property', 'seq', 'property-seq', 'target-int'].includes(v), 'property'), - searchTieBreak: text((v) => ['rank', 'display', 'code'].includes(v), null), + searchTieBreak: text((v) => ['rank', 'display', 'code', 'code-length'].includes(v), null), // behaviour settings // an open string: a reader refuses a grammar it does not implement (index.js) 'behaviour.grammar': json((v) => v === null || (isString(v) && v !== ''), null), diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 5ffa7079e..d17e4a1f6 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -384,6 +384,11 @@ class Store { } _loadCatalog() { + // the catalog columns readers rely on (a file built before them is refused: no reader keeps a rule + // for a property that does not say how it is reported) + const cols = new Set(this.db.prepare('PRAGMA main.table_info(property)').all().map((c) => c.name)); + const missing = ['reported_as', 'also_asked_as', 'true_value', 'named_links'].filter((c) => !cols.has(c)); + if (missing.length) throw new Error(`${this.file} was built before the catalog columns ${missing.join(', ')} existed: rebuild it with the importers, or upgrade it`); 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 diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js index a99116e2d..aef044797 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -78,16 +78,19 @@ const TEXT_SEARCHES = Object.freeze({ /** * The order of text-search hits of equal score (meta searchTieBreak; README.md "Order"), as an * ordinal over the hits: 'rank' the stored rank; 'display' the display (String.localeCompare), then - * the stored rank; 'code' the code as binary text; absent: concept id + * the stored rank; 'code' the code as binary text; 'code-length' the code's length, then the code as + * binary text (numeric order for numeric codes); absent: concept id */ function tieOrdinal(store, ids, stats) { const kind = store.searchTieBreak; if (kind === 'rank') return store.rankOrdinal(); - if (kind !== 'display' && kind !== 'code') return (id) => id; + if (kind !== 'display' && kind !== 'code' && kind !== 'code-length') return (id) => id; const rows = store.conceptRows(Array.from(ids), stats); const rank = store.rankOrdinal(); - const key = (id) => String((rows.get(id) || {})[kind] ?? ''); - const cmp = kind === 'display' ? (a, b) => key(a).localeCompare(key(b)) || rank(a) - rank(b) : (a, b) => cmpBinary(key(a), key(b)) || a - b; + const key = (id) => String((rows.get(id) || {})[kind === 'display' ? 'display' : 'code'] ?? ''); + const cmp = kind === 'display' ? (a, b) => key(a).localeCompare(key(b)) || rank(a) - rank(b) + : kind === 'code-length' ? (a, b) => (key(a).length - key(b).length) || cmpBinary(key(a), key(b)) || a - b + : (a, b) => cmpBinary(key(a), key(b)) || a - b; const pos = new Map([...ids].sort(cmp).map((id, i) => [id, i])); return (id) => pos.get(id) ?? Infinity; } From ebf03222234c3aae9e9fbbb8d6f9deaf35b7c958 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 21:38:34 -0600 Subject: [PATCH 26/90] sqlite-v2: behaviour.domain names the concepts answers select A property code (default null: every concept): answers select only the concepts with a row of it; the file's other concepts are kept but never selected by a filter, an expansion, a count or the whole-system walk. The RxNorm importer writes SUPPRESS (the concepts in RXNCONSO), which replaces the RxNorm adapter's live-domain rule and five checks of the system in the provider. The engine test's RxNorm fixture now states its domain (expectations unchanged). Co-Authored-By: Claude --- tests/tx/sqlite-v2-engine.test.js | 4 ++++ tests/tx/sqlite-v2-format-round2.test.js | 28 ++++++++++++++++++++++++ tx/importers/import-rxnorm-v2.module.js | 2 ++ tx/sqlite-v2/README.md | 1 + tx/sqlite-v2/dialects.js | 9 -------- tx/sqlite-v2/engine/compile.js | 8 ++++--- tx/sqlite-v2/meta.js | 2 ++ tx/sqlite-v2/provider.js | 27 ++++++++++------------- tx/sqlite-v2/store.js | 11 ++++++++++ tx/sqlite-v2/text-index.js | 5 +++-- 10 files changed, 67 insertions(+), 30 deletions(-) diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index 0107d0f60..56d440de5 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -62,6 +62,10 @@ function buildRx(dest) { b.literal(c['2'], tty, 'SCD'); b.literal(c['3'], tty, 'SCD'); b.literal(c['5'], tty, 'SCD'); + // the concepts answers select (behaviour.domain): 1-4; 5 is archived (in the file, never selected) + const sup = b.property({ code: 'SUPPRESS', shape: 'literal', fhirType: 'code', filterable: false }); + for (const code of ['1', '2', '3', '4']) b.literal(c[code], sup, 'N'); + b.setBehaviour('domain', 'SUPPRESS'); 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 diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 681e2c907..bc9d26dc9 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -950,3 +950,31 @@ describe('a catalog without the reporting columns is refused', () => { expect(() => openStore(f)).toThrow(/built before the catalog columns true_value, named_links existed: rebuild it with the importers, or upgrade it/); }); }); + +describe('behaviour.domain: the concepts answers select', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + test('a filter, the whole system and the count select only the concepts with the property', async () => { + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const file = fixture((b, c) => { + const live = b.property({ code: 'live', shape: 'literal', fhirType: 'code', filterable: false }); + for (const k of ['root', 'A', 'X']) b.literal(c[k], live, 'Y'); + b.setBehaviour('domain', 'live'); + }); + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + const S = f.store; + const codes = (bm) => bm.toArray().map((id) => S.conceptRows([id]).get(id).code).sort(); + expect(codes(S.domain())).toEqual(['A', 'X', 'root']); + const p = await f.build(op, []); + expect(p.totalCount()).toBe(3); + expect((await p.iteratorAll()).ids.length).toBe(3); + const c = new Compiler({ store: S, dialect: {} }); + expect(codes(f.engine.evaluate(c.domain(c.filter('concept', 'is-a', 'root'))))).toEqual(['A', 'root']); + } finally { f.store.close(); } + withStore(fixture(), (S) => expect(S.domain()).toBeNull()); + }); +}); diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index f96eb9d50..2bae9f9df 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -66,6 +66,8 @@ async function importRxNormV2(cfg) { b.setBehaviour('distinctDesignationTexts', true); b.setBehaviour('designationUses', 'drop'); b.setBehaviour('versionAlgorithm', 'date'); + // answers select the concepts in RXNCONSO (a SUPPRESS literal), never the RXNATOMARCHIVE-only ones + b.setBehaviour('domain', 'SUPPRESS'); // text search: the best atom name or code among the concepts with a non-SY atom; ties by code (text) b.setBehaviour('textSearch', 'rxnorm'); b.setMeta('searchTieBreak', 'code'); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 32d34e63d..f16590b87 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -198,6 +198,7 @@ refused (the builders check the same at build). | `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 | | `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. ICD-11 files name `icd11`, which the JS reader does not implement (such a file is refused). SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | +| `domain` | a property code, `null` | `null` (every concept) | the concepts answers select: those with a row of this property (active or not); the file's other concepts are kept (e.g. for history) but no expansion, filter, count or whole-system walk selects them. RxNorm `"SUPPRESS"` (the concepts in RXNCONSO; RXNATOMARCHIVE-only concepts are never selected) | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js index 2d1434715..276e505ce 100644 --- a/tx/sqlite-v2/dialects.js +++ b/tx/sqlite-v2/dialects.js @@ -171,15 +171,6 @@ const loinc = { const rxnorm = { name: 'rxnorm', - // text filter: cs-rxnorm.js's stem search (text-index.js rxTextSearch) - // 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); }, diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index ce483e141..aaf5b8f77 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -135,10 +135,12 @@ class Compiler { return { parts }; } - /** the concepts a filter can select at all (RxNorm: never archived concepts) */ + /** the concepts a filter can select at all (behaviour.domain: the concepts with that property) */ domain(node) { - if (this.dialect.domain !== 'live') return node; - const live = this.dialect.live(this.store); + const code = this.store.behaviour.domain; + if (code == null) return node; + const d = this.store.catalog.get(code); + const live = d ? { t: 'set', kind: KIND.hasProp, pid: d.id, value: 0 } : { t: 'empty' }; return node.t === 'all' ? live : { t: 'and', items: [node, live] }; } diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index fec729b60..fa467e155 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -95,6 +95,8 @@ const KEYS = Object.freeze({ && (v.parameter === undefined || (isString(v.parameter) && v.parameter !== '')) && (v.extension === undefined || (isString(v.extension) && v.extension !== '')) && (v.literals === undefined || (isPlainObject(v.literals) && Object.values(v.literals).every(isString)))), null), + // the property whose rows mark the concepts answers select (others are in the file, never selected) + 'behaviour.domain': json((v) => v === null || (isString(v) && v !== ''), null), 'behaviour.expansionLimit': json(isCount, 0), // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one 'behaviour.textSearch': json((v) => v === null || (isString(v) && v !== ''), null), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 4e90d8934..aca006ed0 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -109,7 +109,7 @@ class SqliteV2Provider extends BaseCSServices { */ async countAllCodes(excludeInactive) { if (!excludeInactive) return this.totalCount(); - const walked = this.dialect.name === 'rxnorm' ? this._rxLive() : this.store.all(); + const walked = this.store.domain(this._stats()) || this.store.all(); return walked.andCardinality(this.store.active()); } hasParents() { return !!this.store.hierarchy || this.dialect.name === 'rxnorm'; } @@ -482,8 +482,7 @@ class SqliteV2Provider extends BaseCSServices { /** 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 this.store.domain(this._stats()) || this.store.all(); } /** RxNorm: inactive because archived (RXNATOMARCHIVE only), not obsolete (SUPPRESS = O) */ @@ -590,11 +589,11 @@ class SqliteV2Provider extends BaseCSServices { } _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(); - } + if (this.dialect.name === 'loinc') return this.store.all().toArray(); + // a system with a domain (behaviour.domain): its concepts, in the stored order (cs-rxnorm.js + // iterator(null): ORDER BY RXCUI) + const dom = this.store.domain(this._stats()); + if (dom) return this.engine._order ? this.engine._ordered(dom) : dom.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); @@ -602,7 +601,7 @@ class SqliteV2Provider extends BaseCSServices { } async iteratorAll() { - const ids = (this.dialect.name === 'rxnorm' ? this._rxLive() : this.store.all()).toArray(); + const ids = (this.store.domain(this._stats()) || this.store.all()).toArray(); return { ids, pos: 0, total: ids.length }; } @@ -1325,7 +1324,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.behaviour.domain != null && 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; @@ -1529,12 +1528,8 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { * found only in RXNATOMARCHIVE, which the file also holds (archived) but no answer selects */ totalCount() { - if (this.dialect.name !== 'rxnorm') return this.store.conceptCount; - if (this._liveCount == null) { - const p = this.store.props.get('SUPPRESS'); - this._liveCount = p ? this.store.getSet(KIND.hasProp, p.id, 0).size : this.store.active().size; - } - return this._liveCount; + const dom = this.store.domain(); + return dom ? dom.size : this.store.conceptCount; } /** * behaviour.versionAlgorithm, else what the stored CodeSystem resource declares diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index d17e4a1f6..bba3cb697 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -485,6 +485,17 @@ class Store { return this._labels.get(p.id) || null; } + /** + * The concepts answers select (behaviour.domain: those with a row of that property; the file's + * other concepts are never selected, e.g. RxNorm's RXNATOMARCHIVE-only ones), or null: every concept + */ + domain(stats) { + const code = this.behaviour.domain; + if (code == null) return null; + const d = this.catalog.get(code); + return d ? this.getSet(KIND.hasProp, d.id, 0, stats) : EMPTY; + } + /** the languages of the served system's items (meta, a release fact) */ languages() { return JSON.parse(this.meta.get('languages') || '[]'); } diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js index aef044797..648c91712 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -622,8 +622,9 @@ function sctTextLanguages(store) { function rxSearchable(store, stats) { if (!store._rxSearchable) { const { KIND } = require('./store'); - const sup = store.props.get('SUPPRESS'), tty = store.props.get('TTY'); - const bm = sup ? store.getSet(KIND.hasProp, sup.id, 0, stats).clone() : store.active(stats).clone(); + // the system's domain (behaviour.domain: RxNorm's RXNCONSO concepts), else the active concepts + const tty = store.props.get('TTY'); + const bm = (store.domain(stats) || 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)); From b2fe0964d575a8f72277137dc1ca0606da032712 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 21:47:35 -0600 Subject: [PATCH 27/90] sqlite-v2: the catalog id is the stored resource's id A server serves a file's system as CodeSystem/x-. The id is now code_system.resource.id, which each importer writes as the built-in provider for its system forms it (SNOMED CT SCT--, LOINC loinc, RxNorm RxNorm-), instead of three rules by system in the reader. The id tests compare the importers' functions with the built-in providers' ids over the same table of versions (the ids are unchanged). Co-Authored-By: Claude --- tests/tx/sqlite-v2-cs-ids.test.js | 23 +++++++++++++++-------- tx/importers/import-loinc-v2.module.js | 9 +++++++-- tx/importers/import-rxnorm-v2.module.js | 9 +++++++-- tx/importers/sct-v2-common.js | 19 +++++++++++++++++-- tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/provider.js | 12 ++++++------ tx/sqlite-v2/snomed.js | 17 ----------------- 7 files changed, 53 insertions(+), 38 deletions(-) diff --git a/tests/tx/sqlite-v2-cs-ids.test.js b/tests/tx/sqlite-v2-cs-ids.test.js index 3b46af61a..4b02ab602 100644 --- a/tests/tx/sqlite-v2-cs-ids.test.js +++ b/tests/tx/sqlite-v2-cs-ids.test.js @@ -97,17 +97,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) => Object.assign(Object.create(RxNormServicesFactory.prototype), { isNCI: false, _sharedData: { version: v } }); const mainSct = (v, edition) => Object.assign(Object.create(SnomedServicesFactory.prototype), { _sharedData: { versionUri: v, edition } }); + // 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 } = require('../../tx/importers/sct-v2-common'); + const resource = (id) => JSON.stringify({ resourceType: 'CodeSystem', ...(id ? { id } : {}) }); 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([ @@ -121,15 +126,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)) }); 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/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 0a999048c..7f05b46a9 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -172,10 +172,15 @@ function loincCatalog(b) { return { link, parent, partProp, lit, answer, answersFor, ancestor }; } +/** 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' }); + 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: loincCatalogId(version) } }); // 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'); @@ -542,4 +547,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 }; diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 2bae9f9df..811ff1a06 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -49,6 +49,9 @@ async function* rrf(file) { } /** @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,7 +62,9 @@ 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' }); + caseSensitive: true, defaultLanguage: 'en-US', + // the catalog id, as cs-rxnorm.js forms it (CodeSystem/x-RxNorm-) + resource: { resourceType: 'CodeSystem', id: rxnormCatalogId(v) } }); // 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'); @@ -316,4 +321,4 @@ class RxNormV2Module extends BaseTerminologyModule { } } -module.exports = { RxNormV2Module, importRxNormV2 }; +module.exports = { RxNormV2Module, importRxNormV2, rxnormCatalogId }; diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index f233e93b9..1de33a1e4 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -161,6 +161,17 @@ function concrete(raw) { const DERIVED = [{ table: 'ix_key', name: 'normalForm' }, { table: 'ix_order', name: 'walk' }]; +/** 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 { /** * @param {object} cfg { dest, overwrite, log, importer, codeSystem: {uri, version, name, title, @@ -171,7 +182,11 @@ 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 (code_system.resource id): as cs-snomed.js forms it, SCT-- + // (xSCT- for an xsct edition); none for an undated version + const catalogId = sctCatalogId(cfg.codeSystem && cfg.codeSystem.version); + b.codeSystem({ caseSensitive: true, hierarchyMeaning: 'is-a', compositional: true, + resource: { resourceType: 'CodeSystem', ...(catalogId ? { id: catalogId } : {}) }, ...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 @@ -476,4 +491,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 }; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index f16590b87..d7377b98a 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -51,7 +51,7 @@ 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) | +| `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). The catalog id a server serves the system under (`CodeSystem/x-`) is `resource.id`; the importers write the id main's provider for the system forms (SNOMED CT `SCT--`, LOINC `loinc`, RxNorm `RxNorm-`); a resource without an id: none; no resource: name and version | | `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 | diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index aca006ed0..0e8709080 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1545,14 +1545,14 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { return this._resourceAlgorithm; } /** - * 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 it as CodeSystem/x-): the stored CodeSystem + * resource's id (the importers write the id main's provider for the system forms; a resource + * without one: none), else, with no resource, the name and version */ id() { - if (this.store.system === LOINC) return 'loinc' + this.version(); - if (this.store.system === RXNORM) return this.name() + '-' + this.version(); + let r = null; + try { r = this.store.cs.resource ? JSON.parse(this.store.cs.resource) : null; } catch (e) { r = null; } + if (r) return typeof r.id === 'string' && r.id ? r.id : null; return (this.name().replace(/\W/g, '') + '-' + this.version()).toLowerCase(); } describeVersion(v) { diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index d985020c3..b29d25a99 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -675,23 +675,6 @@ class SnomedV2Factory extends SqliteV2Factory { return v.includes('/version') ? v.substring(0, v.indexOf('/version')) : null; } - /** - * As cs-snomed.js id(), byte for byte: 'SCT--', or null without a dated version. - * Main's test-edition branch (snomed.info/xsct) prefixes 'x' to the match array, which makes it - * a string, so its [1] and [2] are the characters 'h' and 't': every xsct edition has the id - * 'SCT-h-t'. Kept so CodeSystem/x- reads and search ids are the same on both engines. - */ - /** as cs-snomed.js SnomedServicesFactory.id(): SCT--, or xSCT-- for an xsct edition */ - id() { - let prefix = ''; - let match = this.version().match(/^http:\/\/snomed\.info\/sct\/(\d+)(?:\/version\/(\d{8}))?$/); - if (!match) { - match = this.version().match(/^http:\/\/snomed\.info\/xsct\/(\d+)(?:\/version\/(\d{8}))?$/); - if (match) prefix = 'x'; - } - return match && match[1] && match[2] ? prefix + 'SCT-' + match[1] + '-' + match[2] : null; - } - describeVersion(version) { const m = String(version).match(/^http:\/\/snomed\.info\/sct\/(\d+)(?:\/version\/(\d{8}))?$/); if (!m) return version; From 373e440c70188eba1c05da4c55acbcf7f3cd940e Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 21:53:24 -0600 Subject: [PATCH 28/90] sqlite-v2: names selection includeUses; LOINC and RxNorm selections state designations ix.ix_word.names.items.includeUses lists the item uses whose items are names (null: an item without a use); absent: every use; combined with the other item fields. The LOINC and RxNorm importers now state designations: true, the rule their searches already applied (the answers on the fixtures are unchanged). Text search reads the names from the selection only, as before. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 7 +++++++ tx/importers/import-loinc-v2.module.js | 2 +- tx/importers/import-rxnorm-v2.module.js | 2 +- tx/sqlite-v2/README.md | 8 ++++++-- tx/sqlite-v2/meta.js | 3 ++- tx/sqlite-v2/text-index.js | 9 +++++++++ 6 files changed, 26 insertions(+), 5 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index bc9d26dc9..0ceba86ee 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -195,6 +195,13 @@ describe('P3. word index: the names selection as data, stemmers per language, li expect(ex).toContain('apple tree'); }); + test('items.includeUses: only the items with a listed use (null: no use), combined with the other fields', () => { + expect(names(rich({ items: { includeUses: ['RELATED', null] } })).map((r) => r[2]).sort()).toEqual(['a definition without use', 'related wording']); + expect(names(rich({ items: { includeUses: ['RELATED', null], designations: true } })).map((r) => r[2])).toEqual(['related wording']); + expect(names(rich({ items: { includeUses: ['not-a-use'] } }))).toEqual([]); + expect(() => openStore(withMeta(rich({ items: {} }), { 'ix.ix_word.names': '{"items": {"includeUses": "syn"}}' }))).toThrow(/is not a value/); + }); + test('items.conceptsWith: only the items of concepts with a row of that property; items.language: every item under it', () => { expect(names(rich({ items: { conceptsWith: 'FLAG', language: 'en' } }))).toEqual([['B', 'en', 'banana tree'], ['B', 'en', 'banana tree']]); expect(names(rich({ items: { conceptsWith: 'NO-SUCH-PROPERTY' } }))).toEqual([]); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 7f05b46a9..07dd0a917 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -193,7 +193,7 @@ function loincCodeSystem(b, version, description) { b.setBehaviour('textSearch', 'loinc'); b.setMeta('searchTieBreak', 'display'); // text search reads the display (English) and every name but RELATEDNAMES2 - b.setMeta('ix.ix_word.names', { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); + b.setMeta('ix.ix_word.names', { display: 'en', items: { designations: true, excludeUses: ['RELATEDNAMES2'] } }); } /** @param {object} cfg { source, dest, version, overwrite, log, hierarchyArrays: 'auto' | 'always' | 'never' } */ diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 811ff1a06..0b9624a70 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -77,7 +77,7 @@ async function importRxNormV2(cfg) { b.setBehaviour('textSearch', 'rxnorm'); b.setMeta('searchTieBreak', 'code'); // text search reads the atoms of the concepts in RXNCONSO (those with a SUPPRESS literal), as English - b.setMeta('ix.ix_word.names', { items: { conceptsWith: 'SUPPRESS', language: 'en' } }); + b.setMeta('ix.ix_word.names', { items: { designations: true, conceptsWith: 'SUPPRESS', language: 'en' } }); // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships const EQ_IN = ['=', 'in']; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index d7377b98a..b893b0273 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -269,6 +269,8 @@ reads (the stored index or, where a reader does without it, its own built from t (`item.cs_id` = the served `cs_id`), filtered by `active` (bool, default false: only `active = 1`), `designations` (bool, default false: only designations, `kind = 0 OR use_id IS NOT NULL`), `excludeUses` (list of `item_use.code`, default `[]`: not the items with one of these uses), + `includeUses` (list of `item_use.code` and/or `null`, optional: only the items with one of these + uses, `null` meaning an item without a use; absent: every use; combines with the others), `conceptsWith` (a property code, optional: only the items of concepts with a row of that property, active or not, in the table its catalog shape says; a code not in the catalog selects nothing) and `language` (a tag, optional: every item under it; absent: the item's own language, NULL -> @@ -281,8 +283,10 @@ write: | system | `ix.ix_word.names` | |---|---| | SNOMED CT | `{"items": {"active": true, "designations": true}, "counts": true}` | -| LOINC | `{"display": "en", "items": {"excludeUses": ["RELATEDNAMES2"]}}` | -| RxNorm | `{"items": {"conceptsWith": "SUPPRESS", "language": "en"}}` | +| LOINC | `{"display": "en", "items": {"designations": true, "excludeUses": ["RELATEDNAMES2"]}}` | +| RxNorm | `{"items": {"designations": true, "conceptsWith": "SUPPRESS", "language": "en"}}` | +| ICD-11 | `{"items": {"designations": true, "includeUses": [null, "indexTerm", "inclusion", "fullySpecifiedName"]}}` | +| NDC, OMOP, UNII, CPT | `{"items": {"designations": true}}` | A file without the key has no names to search (text search matches codes only), whatever its system: no reader holds a table of systems for it. The index builder keeps the key across a diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index fa467e155..925910936 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -45,10 +45,11 @@ const isFilterSpec = (f) => isPlainObject(f) && onlyKeys(f, ['code', 'operator', const isNames = (v) => isPlainObject(v) && onlyKeys(v, ['display', 'items', 'counts']) && (v.display === undefined || (isString(v.display) && v.display !== '')) && (v.counts === undefined || isBool(v.counts)) - && (v.items === undefined || (isPlainObject(v.items) && onlyKeys(v.items, ['active', 'designations', 'excludeUses', 'conceptsWith', 'language']) + && (v.items === undefined || (isPlainObject(v.items) && onlyKeys(v.items, ['active', 'designations', 'excludeUses', 'includeUses', 'conceptsWith', 'language']) && (v.items.active === undefined || isBool(v.items.active)) && (v.items.designations === undefined || isBool(v.items.designations)) && (v.items.excludeUses === undefined || isStrings(v.items.excludeUses)) + && (v.items.includeUses === undefined || (Array.isArray(v.items.includeUses) && v.items.includeUses.every((u) => u === null || (isString(u) && u !== '')))) && (v.items.conceptsWith === undefined || (isString(v.items.conceptsWith) && v.items.conceptsWith !== '')) && (v.items.language === undefined || (isString(v.items.language) && v.items.language !== '')))); diff --git a/tx/sqlite-v2/text-index.js b/tx/sqlite-v2/text-index.js index 648c91712..4c3df9037 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -132,6 +132,15 @@ function selectionPlan(store, names) { 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 }; if (it.conceptsWith) plan.concepts = conceptsWithProperty(store, it.conceptsWith); } From fddf7ba1e36ddcbb0eeba0dd86da642e41e540e7 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 21:59:18 -0600 Subject: [PATCH 29/90] sqlite-v2: item_use.reported_as, an item use reported as a property The items of a use with reported_as are not designations: $lookup lists the active ones as values of a property of that name (with their language). At most one such use per file (builder contract, reader check); a file without the column is refused. The LOINC importer sets it on RELATEDNAMES2, which replaces the LOINC rules by code in the designation reads and the LOINC $lookup. Listed by default, by name or *, as the built-in LOINC provider lists RELATEDNAMES2 (cs-loinc.js). Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 43 ++++++++++++++++++++++++ tx/importers/import-loinc-v2.module.js | 2 ++ tx/importers/sqlite-v2/builder.js | 13 +++++-- tx/importers/sqlite-v2/schema.sql | 4 ++- tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/layers.js | 2 +- tx/sqlite-v2/provider.js | 31 ++++++++++------- tx/sqlite-v2/store.js | 11 +++++- 8 files changed, 89 insertions(+), 19 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 0ceba86ee..22e7ca456 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -985,3 +985,46 @@ describe('behaviour.domain: the concepts answers select', () => { withStore(fixture(), (S) => expect(S.domain()).toBeNull()); }); }); + +describe('R3-3. item_use.reported_as: an item use reported as a property', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { Designations } = require('../../tx/library/designations'); + test('its active items are a $lookup property (by default, by name, *), not designations; at most one; the column is required', async () => { + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const file = fixture((b, c) => { + b.item(c.A, { language: 'en', use: { system: 'u', code: 'REL' }, text: 'fruit; orchard' }); + b.item(c.A, { language: 'en', use: { system: 'u', code: 'REL' }, text: 'withdrawn words', active: false }); + b.reportUseAs('REL', 'relatedNames'); + }); + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + const p = await f.build(op, []); + const ctx = (await p.locate('A')).context; + const ds = new Designations(op.i18n.languageDefinitions); + await p.designations(ctx, ds); + expect(ds.designations.map((d) => d.value)).not.toContain('fruit; orchard'); + const lookup = async (props) => { + const params = []; + await p.extendLookup((await p.locate('A')).context, props, params); + return params.filter((x) => x.part[0].valueCode === 'relatedNames').map((x) => x.part[1].valueString); + }; + expect(await lookup([])).toEqual(['fruit; orchard']); + expect(await lookup(['relatedNames'])).toEqual(['fruit; orchard']); + expect(await lookup(['*'])).toEqual(['fruit; orchard']); + expect(await lookup(['colour'])).toEqual([]); + } finally { f.store.close(); } + const two = withMeta(file, {}); + const w = new Database(two); + w.exec("UPDATE item_use SET reported_as = 'x' WHERE reported_as IS NULL"); + w.close(); + expect(() => openStore(two)).toThrow(/more than one item use with reported_as/); + const old = withMeta(file, {}); + const w2 = new Database(old); + w2.exec('ALTER TABLE item_use DROP COLUMN reported_as'); + w2.close(); + expect(() => openStore(old)).toThrow(/built before the item_use column reported_as existed/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 07dd0a917..9119a00f8 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -189,6 +189,8 @@ function loincCodeSystem(b, version, description) { // a concept's links in source order (link.seq), as cs-loinc.js reads its Relationships (meta // linkOrder: this reader's LOINC $lookup lists them in its own fixed groups) b.setMeta('linkOrder', 'seq'); + // RELATEDNAMES2 items are a $lookup property, not designations + b.reportUseAs('RELATEDNAMES2', 'RELATEDNAMES2'); // text search: each concept's best name or code; ties by display, then the stored order b.setBehaviour('textSearch', 'loinc'); b.setMeta('searchTieBreak', 'display'); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 6b4c2a027..1c39e52d9 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -248,6 +248,14 @@ class TerminologyBuilder { setDisplay(i, display) { this.display[i] = display; } setSortKey(i, key) { this.sortKey[i] = key; } + /** + * The items of the uses with this code are reported as values of a property of this name, not as + * designations (item_use.reported_as) + */ + reportUseAs(code, name) { + (this.reportedUses || (this.reportedUses = new Map())).set(code, name); + } + /** an item_use coding; returns its use_id */ use({ system = null, code, display = null }) { const k = `${system || ''}|${code}`; @@ -459,8 +467,8 @@ 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); + 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, (this.reportedUses && this.reportedUses.get(u.code)) ?? null); const insConcept = db.prepare('INSERT INTO concept VALUES (?,?,?,?,?)'); this._time('rewrite concept', () => { @@ -718,6 +726,7 @@ function checkContracts(db) { // a stored expansion order (behaviour.expansionOrder 'stored' / 'stored-self-first') has its arrays const eo = one("SELECT value FROM main.meta WHERE key = 'behaviour.expansionOrder'"); if (eo != null && JSON.parse(eo) !== 'ids' && !(arrays.has('rank') && arrays.has('ids'))) fail(`behaviour.expansionOrder ${eo} without ix_order rank and ids`); + if (one('SELECT count(*) FROM main.item_use WHERE reported_as IS NOT NULL') > 1) fail('more than one item use with reported_as'); if (one("SELECT count(*) FROM main.property WHERE role = 'status'") > 1) fail('more than one property with role status'); // meta requires is stated; a word index states its names if (one("SELECT count(*) FROM main.meta WHERE key = 'requires'") !== 1) fail('meta requires is missing'); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 5a5fb0304..94c8042d1 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -61,7 +61,9 @@ 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, + reported_as TEXT); -- the items of this use are reported as values of a property of this + -- name ($lookup), not as designations; NULL: designations (at most one per file) 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, diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index b893b0273..f6f992d89 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -55,7 +55,7 @@ Fact tables: | `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) | +| `item_use` | the uses (SNOMED CT description types, LOINC name kinds, RxNorm TTYs); `reported_as` (NULL default; at most one per file): the active items of this use are reported as values of a property of this name (`$lookup`: the item's text, with its language), not as designations; listed by default, by name or `*` (LOINC `RELATEDNAMES2`) | | `property`, `property_member` | the catalog; a union property's members | | `link` | subject, property, role group, target, active, seq (source order) | | `literal` | subject, property, role group, value, active | diff --git a/tx/sqlite-v2/layers.js b/tx/sqlite-v2/layers.js index 324b929a4..bebeb704f 100644 --- a/tx/sqlite-v2/layers.js +++ b/tx/sqlite-v2/layers.js @@ -71,7 +71,7 @@ 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 = []; diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 0e8709080..a8279cd20 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -262,7 +262,7 @@ 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 + // the items of a use reported as a property (item_use.reported_as) are not designations: 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; } @@ -307,14 +307,21 @@ class SqliteV2Provider extends BaseCSServices { return () => oc.checkAndYield('sqlite-v2'); } - /** LOINC's RELATEDNAMES2 use_id when designation reads leave it out (else null) */ + /** the use_id of the item use reported as a property (item_use.reported_as), which designation reads leave out, or 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; + return this.store.reportedUse ? this.store.reportedUse.id : null; + } + + /** + * The active items of the use reported as a property (item_use.reported_as), as values of that + * property (with their language), when the request lists it (by default, by name or *) + */ + _reportedUseProperty(c, props, params) { + const r = this.store.reportedUse; + if (!r || !this._hasProp(props, r.name, true)) return; + this._needDesigs(c); + const rows = c.desigsNoRelated ? (this.store.designationRows([c.id], this._stats(), { onlyUse: r.id }).get(c.id) || []) : c.desigs; + for (const d of rows) if (d.active && d.use && d.use.reportedAs) this._addStringProperty(params, 'property', r.name, d.term, d.language); } async _ensure(context) { @@ -528,7 +535,7 @@ class SqliteV2Provider extends BaseCSServices { 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; + if (d.use && d.use.reportedAs) continue; displays.addDesignation(false, 'active', d.language, this._useOf(d), d.term.trim()); } } else if (this.dialect.name === 'rxnorm') { @@ -761,10 +768,7 @@ class SqliteV2Provider extends BaseCSServices { // the status literal (role 'status') after the other properties for (const r of lits) if (r.role === 'status' && this._reports(r.code, props, true)) this._addStringProperty(params, 'property', r.code, 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); - } + this._reportedUseProperty(c, props, params); const maps = S.externalMaps(c.id); for (const m of maps) { const key = loincMapKey(m.system); @@ -902,6 +906,7 @@ class SqliteV2Provider extends BaseCSServices { const p = S.propsById.get(r.p); if (p && this._reportsDef(p, props, true)) this._addReported(params, p, r.v); } + this._reportedUseProperty(c, props, params); this._designationCodes(c, props, params); } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index bba3cb697..5fc4e2857 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -363,7 +363,16 @@ class Store { throw new Error(`${this.file}: behaviour.lookupDesignationCode ${ldc} is not a literal property of the catalog`); } 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 }); + if (!db.prepare('PRAGMA main.table_info(item_use)').all().some((c) => c.name === 'reported_as')) { + throw new Error(`${this.file} was built before the item_use column reported_as existed: rebuild it with the importers, or upgrade it`); + } + for (const u of db.prepare('SELECT use_id, system, code, display, reported_as FROM main.item_use').all()) { + this.uses.set(u.use_id, { system: u.system, code: u.code, display: u.display, ...(u.reported_as != null ? { reportedAs: u.reported_as } : {}) }); + } + // the item use whose items are reported as a property, not as designations (item_use.reported_as) + const reported = [...this.uses].filter(([, u]) => u.reportedAs); + if (reported.length > 1) throw new Error(`${this.file}: more than one item use with reported_as`); + this.reportedUse = reported.length ? { id: reported[0][0], name: reported[0][1].reportedAs } : null; this.hasFts = true; this.hasAcceptability = this.langRelations.size > 0; this.hasRank = true; From ab4f85410e8ed18685b6db32a52e3e04366b77ab Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:02:27 -0600 Subject: [PATCH 30/90] sqlite-v2: SNOMED CT semanticTag stored as a literal The SNOMED CT importer stores each concept's semantic tag as a literal semanticTag (named, not filterable), computed once from the final rows (builder deriveFacts): among the active FSN items in rank then id order, the first whose text ends with ')' and contains '(', the text between the last '(' and that ')'. The SNOMED CT $lookup lists it like any literal; the reader derives nothing. On the test fixtures the answers are unchanged; on concepts with nested brackets or trailing spaces the stored rule differs from the earlier regular expression. Co-Authored-By: Claude --- tx/importers/sct-v2-common.js | 27 +++++++++++++++++++++++++++ tx/importers/sqlite-v2/builder.js | 10 ++++++++++ tx/sqlite-v2/README.md | 6 ++++++ tx/sqlite-v2/snomed.js | 16 +++++----------- 4 files changed, 48 insertions(+), 11 deletions(-) diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 1de33a1e4..9a6029842 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -161,6 +161,30 @@ function concrete(raw) { const DERIVED = [{ table: 'ix_key', name: 'normalForm' }, { 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 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 id of a SNOMED CT version URI, as cs-snomed.js forms it, or null without a dated version */ function sctCatalogId(version) { let prefix = ''; @@ -198,6 +222,9 @@ class SnomedSink { // numbers (the order of the stored rank, cs-snomed.js's concept order) b.setBehaviour('textSearch', 'snomed'); b.setMeta('searchTieBreak', 'code-length'); + // semanticTag: stored, one value per concept that has one (semanticTags below) + const tagProp = b.property({ code: 'semanticTag', shape: 'literal', fhirType: 'string', filterable: false, refinable: false, wildcard: false, report: 'named' }); + b.deriveFacts((db) => semanticTags(db, tagProp)); // text search reads the active descriptions (and text definitions) in their own language, and // ranks one-word filters by each concept's distinct-word count b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 1c39e52d9..24183f177 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -256,6 +256,14 @@ class TerminologyBuilder { (this.reportedUses || (this.reportedUses = new Map())).set(code, name); } + /** + * 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}`; @@ -493,6 +501,8 @@ class TerminologyBuilder { // 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, subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, named_links, filter_ops, report, reported_as, diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index f6f992d89..7673e611f 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -250,6 +250,12 @@ asked for as `module`; `definitionStatusId` reported as `sufficientlyDefined`, t `900000000000073002`, `report` `named`. No other system sets them. Readers keep no table of names by system. +SNOMED CT files store each concept's semantic tag as a literal `semanticTag` (string, `filterable = +0`, `report = 'named'`, one value per concept that has one): 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 `)`. Readers report it like +any property and derive nothing. + `property.role = 'status'`: the literal that holds the concept's status (at most one per system): every row reads it (the provider's `getStatus()`), and `$lookup` lists it by default under its name. LOINC files: `STATUS`. diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index b29d25a99..80ab1d9af 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -307,17 +307,11 @@ class SnomedV2Provider extends SqliteV2Provider { const l = links.find((x) => x.p === d.id); if (l) this._addReported(params, d, code(l.t), disp(l.t)); } - 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; - } - } + // the concept's other literals (not attributes; not effectiveTime, above): semanticTag (stored by + // the importer, report named), each under its reported name + for (const d of S.catalog.values()) { + if (d.shape !== 'literal' || d.attribute || d.code === 'effectiveTime' || d.role || !this._reportsDef(d, props, true)) continue; + for (const l of lits) if (l.p === d.id) this._addReported(params, d, l.v); } const seen = new Set(); for (const l of links) { From 8a70daeeafa93629f02a6451b0fbebee67bbc402 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:09:25 -0600 Subject: [PATCH 31/90] sqlite-v2: behaviour.lookupOrder orders $lookup's properties {ranks: {name: int}, concept?: int, other: int, byCode?: bool}: each property sorts by its rank (by name; else concept for a code-valued property where given; else other); ties keep the order listed, or with byCode sort by name then value code. Absent: no reordering. The SNOMED CT, LOINC and RxNorm importers write their providers' orders; LOINC's also ranks each implicit map's key last (13), where cs-loinc.js lists the mappings. The parity tests against the built-in providers pass. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 35 ++++++++++++++++++++++++ tx/importers/import-loinc-v2.module.js | 13 +++++++++ tx/importers/import-rxnorm-v2.module.js | 1 + tx/importers/sct-v2-common.js | 1 + tx/sqlite-v2/README.md | 1 + tx/sqlite-v2/meta.js | 4 +++ tx/sqlite-v2/provider.js | 32 ++++++++++++++++++++-- 7 files changed, 85 insertions(+), 2 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 22e7ca456..6f9adfc9c 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1028,3 +1028,38 @@ describe('R3-3. item_use.reported_as: an item use reported as a property', () => expect(() => openStore(old)).toThrow(/built before the item_use column reported_as existed/); }); }); + +describe('R3-5a. behaviour.lookupOrder', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const names = async (meta) => { + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const file = withMeta(fixture((b, c) => { + const site = b.property({ code: 'site', shape: 'link' }); + const size = b.property({ code: 'size', shape: 'literal', fhirType: 'string' }); + b.link(c.A, site, c.C); + b.link(c.A, site, c.B); + b.literal(c.A, size, 'big'); + }), meta); + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + const p = await f.build(op, []); + const params = []; + await p.extendLookup((await p.locate('A')).context, [], params); + return params.map((x) => x.part[0].valueCode + '=' + (x.part[1].valueCode || x.part[1].valueString)); + } finally { f.store.close(); } + }; + test('ranks by name, concept-valued, other; ties as listed or byCode; absent: as listed', async () => { + const plain = await names({}); + expect(plain).toEqual(['parent=root', 'site=B', 'site=C', 'colour=red', 'size=big']); + expect(await names({ 'behaviour.lookupOrder': JSON.stringify({ ranks: { size: 0, colour: 1 }, other: 2 }) })) + .toEqual(['size=big', 'colour=red', 'parent=root', 'site=B', 'site=C']); + expect(await names({ 'behaviour.lookupOrder': JSON.stringify({ ranks: { parent: 3 }, concept: 0, other: 1 }) })) + .toEqual(['site=B', 'site=C', 'colour=red', 'size=big', 'parent=root']); + expect(await names({ 'behaviour.lookupOrder': JSON.stringify({ ranks: {}, other: 0, byCode: true }) })) + .toEqual(['colour=red', 'parent=root', 'site=B', 'site=C', 'size=big']); + expect(() => openStore(withMeta(fixture(), { 'behaviour.lookupOrder': '{"ranks": {}}' }))).toThrow(/lookupOrder = .* is not a value/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 9119a00f8..b3e3d6f15 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -172,6 +172,15 @@ function loincCatalog(b) { return { link, parent, partProp, lit, answer, answersFor, ancestor }; } +/** 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 catalog id of a LOINC version, as cs-loinc.js forms it */ const loincCatalogId = (version) => `loinc${version}`; @@ -194,6 +203,10 @@ function loincCodeSystem(b, version, description) { // text search: each concept's best name or code; ties by display, then the stored order b.setBehaviour('textSearch', 'loinc'); b.setMeta('searchTieBreak', 'display'); + // $lookup's property order (cs-loinc.js extendLookup): the axes, the other links, parent and child, + // the other properties, STATUS, RELATEDNAMES2, then the mappings (each map's key, last) + b.setBehaviour('lookupOrder', { ranks: { CLASS: 0, COMPONENT: 1, PROPERTY: 2, TIME_ASPCT: 3, SYSTEM: 4, SCALE_TYP: 5, METHOD_TYP: 6, AnswerList: 8, + parent: 9, child: 9, STATUS: 11, RELATEDNAMES2: 12, ...Object.fromEntries(LOINC_MAPS.map(([, key]) => [key, 13])) }, concept: 8, other: 10 }); // text search reads the display (English) and every name but RELATEDNAMES2 b.setMeta('ix.ix_word.names', { display: 'en', items: { designations: true, excludeUses: ['RELATEDNAMES2'] } }); } diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 0b9624a70..663c109ec 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -76,6 +76,7 @@ async function importRxNormV2(cfg) { // text search: the best atom name or code among the concepts with a non-SY atom; ties by code (text) b.setBehaviour('textSearch', 'rxnorm'); b.setMeta('searchTieBreak', 'code'); + b.setBehaviour('lookupOrder', { ranks: { TTY: 0, STY: 1, SAB: 2 }, other: 3, byCode: true }); // text search reads the atoms of the concepts in RXNCONSO (those with a SUPPRESS literal), as English b.setMeta('ix.ix_word.names', { items: { designations: true, conceptsWith: 'SUPPRESS', language: 'en' } }); // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 9a6029842..46ed0043c 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -222,6 +222,7 @@ class SnomedSink { // numbers (the order of the stored rank, cs-snomed.js's concept order) b.setBehaviour('textSearch', 'snomed'); b.setMeta('searchTieBreak', 'code-length'); + b.setBehaviour('lookupOrder', { ranks: { effectiveTime: 0, parent: 1, child: 2, moduleId: 3, sufficientlyDefined: 4, semanticTag: 5 }, other: 6 }); // semanticTag: stored, one value per concept that has one (semanticTags below) const tagProp = b.property({ code: 'semanticTag', shape: 'literal', fhirType: 'string', filterable: false, refinable: false, wildcard: false, report: 'named' }); b.deriveFacts((db) => semanticTags(db, tagProp)); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 7673e611f..a920031ff 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -199,6 +199,7 @@ refused (the builders check the same at build). | `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. ICD-11 files name `icd11`, which the JS reader does not implement (such a file is refused). SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | | `domain` | a property code, `null` | `null` (every concept) | the concepts answers select: those with a row of this property (active or not); the file's other concepts are kept (e.g. for history) but no expansion, filter, count or whole-system walk selects them. RxNorm `"SUPPRESS"` (the concepts in RXNCONSO; RXNATOMARCHIVE-only concepts are never selected) | +| `lookupOrder` | `null`, or `{"ranks": {name: int}, "concept"?: int, "other": int, "byCode"?: bool}` | `null` (no reordering) | the order of the properties `$lookup` lists: by rank, `ranks[name]` (the reported name), else `concept` for a code-valued property where given, else `other`; ties in the order the reader lists them, or with `byCode` by name, then value code. SNOMED CT `{"ranks": {"effectiveTime": 0, "parent": 1, "child": 2, "moduleId": 3, "sufficientlyDefined": 4, "semanticTag": 5}, "other": 6}`; RxNorm `{"ranks": {"TTY": 0, "STY": 1, "SAB": 2}, "other": 3, "byCode": true}`; LOINC the axes 0-6, `AnswerList` 8, `parent`/`child` 9, `STATUS` 11, `RELATEDNAMES2` 12, each implicit map's key 13, `concept` 8, `other` 10 | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 925910936..a63b187e5 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -98,6 +98,10 @@ const KEYS = Object.freeze({ && (v.literals === undefined || (isPlainObject(v.literals) && Object.values(v.literals).every(isString)))), null), // the property whose rows mark the concepts answers select (others are in the file, never selected) 'behaviour.domain': json((v) => v === null || (isString(v) && v !== ''), null), + // the order of $lookup's properties: {ranks: {name: int}, concept?: int, other: int, byCode?: bool} + 'behaviour.lookupOrder': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['ranks', 'concept', 'other', 'byCode']) + && isPlainObject(v.ranks) && Object.values(v.ranks).every(Number.isSafeInteger) && Number.isSafeInteger(v.other) + && (v.concept === undefined || Number.isSafeInteger(v.concept)) && (v.byCode === undefined || isBool(v.byCode))), null), 'behaviour.expansionLimit': json(isCount, 0), // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one 'behaviour.textSearch': json((v) => v === null || (isString(v) && v !== ''), null), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index a8279cd20..bba9424e3 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -688,8 +688,10 @@ 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)); + const from = params.length; + if (!this._trace) await this._extendLookup(context, props, params); + else await this._trace.spanAsync('lookup properties', 'rows', this.system(), () => this._extendLookup(context, props, params)); + sortLookupProperties(params, from, this.store.behaviour.lookupOrder); } async _extendLookup(context, props, params) { @@ -1382,6 +1384,32 @@ class SqliteV2Provider extends BaseCSServices { /** the property definitions a file reports (data built at load) */ const NO_PROPERTY_DEFINITIONS = new Set(['snomed', 'loinc', 'rxnorm']); +/** + * The property parameters $lookup added (params from `from` on) in the order behaviour.lookupOrder + * gives (README.md "Behaviour settings"): by rank, ranks[name], else `concept` for a code-valued + * property where given, else `other`; ties in the order listed, or with byCode by name, then value + * code. Other parameters (designations) keep their places. Absent: no reordering. + */ +function sortLookupProperties(params, from, order) { + if (!order) return; + const slots = []; + for (let i = from; i < params.length; i++) if (params[i].name === 'property') slots.push(i); + if (slots.length < 2) return; + const part = (p, n) => (p.part || []).find((x) => x.name === n) || {}; + const nameOf = (p) => String(part(p, 'code').valueCode ?? ''); + const valueOf = (p) => { const v = part(p, 'value'); const k = Object.keys(v).find((x) => x.startsWith('value')); return k ? String(typeof v[k] === 'object' ? JSON.stringify(v[k]) : v[k]) : ''; }; + const rank = (p) => { + const n = nameOf(p); + if (Object.prototype.hasOwnProperty.call(order.ranks || {}, n)) return order.ranks[n]; + if (order.concept != null && part(p, 'value').valueCode !== undefined) return order.concept; + return order.other; + }; + const txt = (a, b) => (a < b ? -1 : a > b ? 1 : 0); + const items = slots.map((i, k) => ({ p: params[i], k, r: rank(params[i]) })); + items.sort((a, b) => (a.r - b.r) || (order.byCode ? txt(nameOf(a.p), nameOf(b.p)) || txt(valueOf(a.p), valueOf(b.p)) : 0) || a.k - b.k); + slots.forEach((i, k) => { params[i] = items[k].p; }); +} + /** * A concept's links in the order meta linkOrder names (README.md "Order"): 'property' (by property, * group, target code), 'seq' (link.seq, then property, group, target code), 'property-seq' (by From e9454badcbf96be24bc88ff060849027fdaaa139 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:13:08 -0600 Subject: [PATCH 32/90] sqlite-v2: behaviour.implicitMaps, the implicit ConceptMaps over mapping rows {base, maps: [[target system, key]], used?}: map {base}{key} translates to and from the target system over the file's mapping rows, and $lookup lists a concept's mappings to it under the key. The LOINC importer writes cs-loinc.js's twelve maps under http://loinc.org/cm/; the reader's LOINC map table and its checks of the system go. used (OMOP's reporting) is not implemented here: a file that sets it is refused. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 31 ++++++++++ tx/importers/import-loinc-v2.module.js | 2 + tx/sqlite-v2/README.md | 1 + tx/sqlite-v2/meta.js | 4 ++ tx/sqlite-v2/provider.js | 72 ++++++++++++------------ tx/sqlite-v2/store.js | 4 ++ 6 files changed, 79 insertions(+), 35 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 6f9adfc9c..94b0cebaf 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1063,3 +1063,34 @@ describe('R3-5a. behaviour.lookupOrder', () => { expect(() => openStore(withMeta(fixture(), { 'behaviour.lookupOrder': '{"ranks": {}}' }))).toThrow(/lookupOrder = .* is not a value/); }); }); + +describe('R3-5b. behaviour.implicitMaps', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + test('maps {base}{key} over the mapping rows: found, offered for a code that has a row, listed by $lookup under the key; used refused', async () => { + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const file = fixture((b, c) => { + b.mapping(c.A, { system: 'http://example.org/other', code: 'O-1', display: 'other one', relationship: 'equivalent' }); + b.setBehaviour('implicitMaps', { base: 'http://example.org/cm/', maps: [['http://example.org/other', 'other']] }); + }); + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + const cm = await f.findImplicitConceptMap('http://example.org/cm/other'); + expect(cm.jsonObj.url).toBe('http://example.org/cm/other'); + expect(await f.findImplicitConceptMap('http://example.org/cm/none')).toBeNull(); + const found = []; + await f.findImplicitConceptMaps(found, 'http://example.org/cs', '1', 'http://example.org/other', 'A'); + expect(found.map((m) => m.jsonObj.url)).toEqual(['http://example.org/cm/other']); + const none = []; + await f.findImplicitConceptMaps(none, 'http://example.org/cs', '1', 'http://example.org/other', 'B'); + expect(none).toEqual([]); + const p = await f.build(op, []); + const params = []; + await p.extendLookup((await p.locate('A')).context, [], params); + expect(params.filter((x) => x.part[0].valueCode === 'other').map((x) => x.part[1].valueCoding.code)).toEqual(['O-1']); + } finally { f.store.close(); } + expect(() => openStore(withMeta(fixture(), { 'behaviour.implicitMaps': '{"base": "u/", "maps": [], "used": "to-"}' }))).toThrow(/implicitMaps.used is set/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index b3e3d6f15..b2b843f51 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -205,6 +205,8 @@ function loincCodeSystem(b, version, description) { b.setMeta('searchTieBreak', 'display'); // $lookup's property order (cs-loinc.js extendLookup): the axes, the other links, parent and child, // the other properties, STATUS, RELATEDNAMES2, then the mappings (each map's key, last) + // the implicit concept maps http://loinc.org/cm/ over the mapping rows + b.setBehaviour('implicitMaps', { base: 'http://loinc.org/cm/', maps: LOINC_MAPS }); b.setBehaviour('lookupOrder', { ranks: { CLASS: 0, COMPONENT: 1, PROPERTY: 2, TIME_ASPCT: 3, SYSTEM: 4, SCALE_TYP: 5, METHOD_TYP: 6, AnswerList: 8, parent: 9, child: 9, STATUS: 11, RELATEDNAMES2: 12, ...Object.fromEntries(LOINC_MAPS.map(([, key]) => [key, 13])) }, concept: 8, other: 10 }); // text search reads the display (English) and every name but RELATEDNAMES2 diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index a920031ff..bef10060d 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -200,6 +200,7 @@ refused (the builders check the same at build). | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | | `domain` | a property code, `null` | `null` (every concept) | the concepts answers select: those with a row of this property (active or not); the file's other concepts are kept (e.g. for history) but no expansion, filter, count or whole-system walk selects them. RxNorm `"SUPPRESS"` (the concepts in RXNCONSO; RXNATOMARCHIVE-only concepts are never selected) | | `lookupOrder` | `null`, or `{"ranks": {name: int}, "concept"?: int, "other": int, "byCode"?: bool}` | `null` (no reordering) | the order of the properties `$lookup` lists: by rank, `ranks[name]` (the reported name), else `concept` for a code-valued property where given, else `other`; ties in the order the reader lists them, or with `byCode` by name, then value code. SNOMED CT `{"ranks": {"effectiveTime": 0, "parent": 1, "child": 2, "moduleId": 3, "sufficientlyDefined": 4, "semanticTag": 5}, "other": 6}`; RxNorm `{"ranks": {"TTY": 0, "STY": 1, "SAB": 2}, "other": 3, "byCode": true}`; LOINC the axes 0-6, `AnswerList` 8, `parent`/`child` 9, `STATUS` 11, `RELATEDNAMES2` 12, each implicit map's key 13, `concept` 8, `other` 10 | +| `implicitMaps` | `null`, or `{"base": url prefix, "maps": [[target system, key], ...], "used"?: infix}` | `null` | the file's implicit ConceptMaps over its `mapping` rows: map `{base}{key}` translates to (and from) the target system, and `$lookup` lists a concept's mappings to it as a property named `key`. With `used`, a map is reported as used as `{base}{used}{key}|{version}` and offered whether or not it translates the code (OMOP); the JS reader does not implement `used` and refuses such a file. LOINC `{"base": "http://loinc.org/cm/", "maps": [...cs-loinc.js's twelve]}` | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index a63b187e5..049e01719 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -102,6 +102,10 @@ const KEYS = Object.freeze({ 'behaviour.lookupOrder': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['ranks', 'concept', 'other', 'byCode']) && isPlainObject(v.ranks) && Object.values(v.ranks).every(Number.isSafeInteger) && Number.isSafeInteger(v.other) && (v.concept === undefined || Number.isSafeInteger(v.concept)) && (v.byCode === undefined || isBool(v.byCode))), null), + // implicit ConceptMaps over mapping rows: {base, maps: [[target system, key]], used?} + 'behaviour.implicitMaps': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['base', 'maps', 'used']) && isString(v.base) && v.base !== '' + && Array.isArray(v.maps) && v.maps.every((m) => Array.isArray(m) && m.length === 2 && isString(m[0]) && isString(m[1]) && m[1] !== '') + && (v.used === undefined || (isString(v.used) && v.used !== ''))), null), 'behaviour.expansionLimit': json(isCount, 0), // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one 'behaviour.textSearch': json((v) => v === null || (isString(v) && v !== ''), null), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index bba9424e3..ffb3d25e5 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -771,9 +771,16 @@ class SqliteV2Provider extends BaseCSServices { for (const r of lits) if (r.role === 'status' && this._reports(r.code, props, true)) this._addStringProperty(params, 'property', r.code, String(r.v)); this._needDesigs(c); this._reportedUseProperty(c, props, params); - const maps = S.externalMaps(c.id); - for (const m of maps) { - const key = loincMapKey(m.system); + this._mapProperties(c, props, params); + } + + /** a concept's mappings of the file's implicit maps (behaviour.implicitMaps), as properties named by each map's key */ + _mapProperties(c, props, params) { + const maps = implicitMaps(this.store); + if (!maps.length) return; + for (const m of this.store.externalMaps(c.id)) { + const im = maps.find((x) => x.system === m.system); + const key = im ? im.key : null; if (!key || !this._hasProp(props, key, true)) continue; // main's key order: system, version, code, display const coding = { system: m.system }; @@ -909,6 +916,7 @@ class SqliteV2Provider extends BaseCSServices { if (p && this._reportsDef(p, props, true)) this._addReported(params, p, r.v); } this._reportedUseProperty(c, props, params); + this._mapProperties(c, props, params); this._designationCodes(c, props, params); } @@ -1457,24 +1465,15 @@ function sortLoinc(desigs) { }); } -// 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; } +/** + * The file's implicit ConceptMaps (behaviour.implicitMaps): [{system, key, url}], each map + * `{base}{key}` translating to the target system; $lookup lists a concept's mappings to it as a + * property named key + */ +function implicitMaps(store) { + const im = store.behaviour.implicitMaps; + return im ? im.maps.map(([system, key]) => ({ system, key, url: im.base + key })) : []; +} /** R4 equivalence from the LOINC side -> R5 relationship from the translated code's side */ function mapRelationship(equivalence, fromLoinc) { @@ -1638,33 +1637,36 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { return null; } - // LOINC's implicit concept maps (http://loinc.org/cm/) + // the file's implicit concept maps (behaviour.implicitMaps: {base}{key}, over its mapping rows) 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; + const other = source === me ? destSystem : destSystem === me ? source : null; + const lm = maps.find((m) => m.system === other); + if (!lm || conceptMaps.some((m) => m.url === lm.url)) return; if (code) { 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)); } 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); + return lm ? this._implicitMap(lm) : 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) 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 }); } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 5fc4e2857..73eb33018 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -340,6 +340,10 @@ class Store { // identifier-aliased codes (behaviour.aliases): this server does not implement them, and would // answer such a file's codes wrongly if (m.behaviour.aliases !== null) throw new Error(`${this.file}: behaviour.aliases is set (identifier-aliased codes), which this server does not implement`); + // behaviour.implicitMaps.used (maps reported as used whether or not they translate): not implemented here + if (m.behaviour.implicitMaps && m.behaviour.implicitMaps.used !== undefined) { + throw new Error(`${this.file}: behaviour.implicitMaps.used is set, which this server does not implement`); + } // behaviour.lookupCopyright: the notice $lookup lists (code_system.resource.copyright) this.copyright = null; if (m.behaviour.lookupCopyright) { From 6c87a660adfa00f8de314499a5846c4474162987 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:16:59 -0600 Subject: [PATCH 33/90] sqlite-v2: partial versions resolved by versionAlgorithm A file's partial version (the library registers the factory under it) follows its versionAlgorithm, not its grammar: with url, the version before /version/ (an edition URI without its date); any other algorithm, none (exact versions only). The SNOMED CT provider's own rule goes; SNOMED CT files state url, so their partial versions are unchanged. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 24 ++++++++++++++++++++++++ tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/provider.js | 10 ++++++++++ tx/sqlite-v2/snomed.js | 5 ----- 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 94b0cebaf..83ab01d20 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1094,3 +1094,27 @@ describe('R3-5b. behaviour.implicitMaps', () => { expect(() => openStore(withMeta(fixture(), { 'behaviour.implicitMaps': '{"base": "u/", "maps": [], "used": "to-"}' }))).toThrow(/implicitMaps.used is set/); }); }); + +describe('R3-5c. partial versions by versionAlgorithm', () => { + test('url: the edition URI before /version/; any other algorithm: none', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const partial = async (version, algorithm) => { + const dest = path.join(dir, `pv${++seq}.db`); + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/pv', version }); + b.concept('a'); + if (algorithm) b.setBehaviour('versionAlgorithm', algorithm); + b.finish(); + const f = new SqliteV2Factory(op.i18n, dest); + await f.load(); + try { return f.getPartialVersion(); } finally { f.store.close(); } + }; + expect(await partial('http://example.org/pv/1/version/20260101', 'url')).toBe('http://example.org/pv/1'); + expect(await partial('http://example.org/pv/1', 'url')).toBeNull(); + expect(await partial('http://example.org/pv/1/version/20260101', null)).toBeNull(); + expect(await partial('1.2.3', 'semver')).toBeNull(); + }); +}); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index bef10060d..e961a8090 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -191,7 +191,7 @@ refused (the builders check the same at build). | `grammar` | a grammar name (an open string), `null` | `null` (plain codes) | the grammar of the system's codes. A reader holds its implementations by name and refuses a file whose grammar it does not implement ("its codes are in the grammar X, which this server does not implement"); there is no fallback by system URI. Names in use: `"snomed"` (SNOMED CT expressions and ECL; the JS reader's SNOMED CT provider, `index.js` `GRAMMARS`), `"icd11"` (ICD-11 MMS and ICF files: postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records), and a code system whose codes carry modifiers. The JS reader implements `snomed` only | | `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"` | the name `$lookup` reports: `code_system.name` (no name: the system URI), or the title (below; no title: the name). LOINC `"title"` | -| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm: how a requested version (check-system-version) matches the file's version (FHIRsmith `versionMatchesByAlgorithm`: `semver` with wildcards, `integer` exactly, any other value by prefix). `null`: what the stored CodeSystem resource declares (`versionAlgorithmString` / `versionAlgorithmCoding`), else only the exact version matches; no guess from the version string and no rule of the reader's own for a system. Every importer writes it: SNOMED CT `"url"` (versions are edition URIs, matched by prefix), LOINC `"natural"`, RxNorm `"date"` | +| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm: how a requested version (check-system-version) matches the file's version (FHIRsmith `versionMatchesByAlgorithm`: `semver` with wildcards, `integer` exactly, any other value by prefix). `null`: what the stored CodeSystem resource declares (`versionAlgorithmString` / `versionAlgorithmCoding`), else only the exact version matches; no guess from the version string and no rule of the reader's own for a system. Every importer writes it: SNOMED CT `"url"` (versions are edition URIs, matched by prefix), LOINC `"natural"`, RxNorm `"date"`. A request naming a partial version resolves by it too: with `url`, the version before `/version/` (an edition URI without its date) names the file; any other algorithm resolves exact versions only (which of several files with the same partial version is the library's rule: the JS library takes the one it loaded last) | | `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | | `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | | `aliases` | `null`, or `{"parameter"?, "extension"?, "literals"?}` (any other field: malformed) | `null` | identifier-aliased codes (identifiers with `resolves` 1 or 2). `parameter`: `$validate-code` of a code written in its canonical form also returns its alias (`resolves = 1`) as an output parameter of this name. `extension`: a Coding extension that restates the alias form of its code, which `$validate-code` checks against the code's alias. `literals` (property code -> value): the literal values a concept reports when read through an identifier code instead of its stored values of those properties; `{code}` is the concept's own code. ICD-11 MMS and ICF `{"parameter": "classificationCode", "extension": "http://id.who.int/icd/schema/extension/classificationCode"}`, Foundation `{"extension": ...}`, NDC `{"literals": {"code-type": "11-digit", "synonym": "{code}"}}`. The JS reader does not implement identifier aliases and refuses a file that sets it | diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index ffb3d25e5..1c057a745 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1587,6 +1587,16 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { if (r) return typeof r.id === 'string' && r.id ? r.id : null; return (this.name().replace(/\W/g, '') + '-' + this.version()).toLowerCase(); } + /** + * The partial version a request may name for this file (library.js registers the factory under + * it too): with versionAlgorithm url, the version before '/version/' (an edition URI without its + * date); any other algorithm: none (exact versions only) + */ + getPartialVersion() { + const v = this.version(); + return this.versionAlgorithm() === 'url' && v.includes('/version/') ? v.substring(0, v.indexOf('/version/')) : null; + } + describeVersion(v) { if (this.store.system === RXNORM) { const { formatDateMMDDYYYY } = require('../../library/utils/utilities'); diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 80ab1d9af..031883f75 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -664,11 +664,6 @@ class SnomedV2Factory extends SqliteV2Factory { } nameBase() { return 'SCT'; } - getPartialVersion() { - const v = this.version(); - return v.includes('/version') ? v.substring(0, v.indexOf('/version')) : null; - } - describeVersion(version) { const m = String(version).match(/^http:\/\/snomed\.info\/sct\/(\d+)(?:\/version\/(\d{8}))?$/); if (!m) return version; From 9a52d8150e368e58aec2744870566ca28db2a33b Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:33:28 -0600 Subject: [PATCH 34/90] sqlite-v2: the stored resource id is the CodeSystem id as it is; the catalog name from the resource The importers store code_system.resource.id with its x- prefix, as the files of other systems already do (SNOMED CT x-SCT--, or x-xSCT-..., none for an undated version; LOINC x-loinc; RxNorm x-RxNorm-), and the reader serves it as it is; a file without a resource id has no catalog id. The catalog name is resource.name (SNOMED CT: SCT , or SNOMED CT Test Set), else code_system.name; the SNOMED CT factory's name rule goes. The format document lists the semanticTag answer change on installed SNOMED CT files. Co-Authored-By: Claude --- tests/tx/sqlite-v2-cs-ids.test.js | 6 +++--- tests/tx/sqlite-v2-format-round2.test.js | 18 ++++++++++++++++++ tx/importers/import-loinc-v2.module.js | 2 +- tx/importers/import-rxnorm-v2.module.js | 2 +- tx/importers/sct-v2-common.js | 18 +++++++++++++----- tx/sqlite-v2/README.md | 7 +++++-- tx/sqlite-v2/provider.js | 24 ++++++++++++++++-------- tx/sqlite-v2/snomed.js | 5 +---- 8 files changed, 58 insertions(+), 24 deletions(-) diff --git a/tests/tx/sqlite-v2-cs-ids.test.js b/tests/tx/sqlite-v2-cs-ids.test.js index 4b02ab602..e748302e4 100644 --- a/tests/tx/sqlite-v2-cs-ids.test.js +++ b/tests/tx/sqlite-v2-cs-ids.test.js @@ -101,8 +101,8 @@ describe('main\'s id() and the engine\'s, over a table of versions', () => { // 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 } = require('../../tx/importers/sct-v2-common'); - const resource = (id) => JSON.stringify({ resourceType: 'CodeSystem', ...(id ? { id } : {}) }); + 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) => { @@ -127,7 +127,7 @@ describe('main\'s id() and the engine\'s, over a table of versions', () => { ['31000003106', 'http://snomed.info/xsct/31000003106'] // undated test edition: no id, as for sct ])('SNOMED CT %s %s', (edition, v) => { expect(sctCatalogId(v)).toBe(mainSct(v, edition).id()); - const engine = v2(SnomedV2Factory, SCT, v, { edition, resource: resource(sctCatalogId(v)) }); + 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()); diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 83ab01d20..0cdcdada0 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1118,3 +1118,21 @@ describe('R3-5c. partial versions by versionAlgorithm', () => { expect(await partial('1.2.3', 'semver')).toBeNull(); }); }); + +describe('catalog id and name from code_system.resource', () => { + test('the stored id as it is is the CodeSystem id (x-...); its name the catalog name; none without an id', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const load = async (file) => { const f = new SqliteV2Factory(op.i18n, file); await f.load(); return f; }; + const a = await load(fixture((b) => { b.systems[0].resource = { resourceType: 'CodeSystem', id: 'x-example-1', name: 'EX 1' }; })); + const n = await load(fixture()); + try { + expect('x-' + a.id()).toBe('x-example-1'); + expect(a.name()).toBe('EX 1'); + expect(n.id()).toBeNull(); + expect(n.name()).toBe('Example'); + } finally { a.store.close(); n.store.close(); } + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index b2b843f51..91155286d 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -189,7 +189,7 @@ 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', // the catalog id, as cs-loinc.js forms it (CodeSystem/x-loinc) - resource: { resourceType: 'CodeSystem', id: loincCatalogId(version) } }); + resource: { resourceType: 'CodeSystem', id: 'x-' + loincCatalogId(version) } }); // 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'); diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 663c109ec..b4a115ab3 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -64,7 +64,7 @@ async function importRxNormV2(cfg) { description: 'RxNorm normalized drug nomenclature (U.S. National Library of Medicine)', caseSensitive: true, defaultLanguage: 'en-US', // the catalog id, as cs-rxnorm.js forms it (CodeSystem/x-RxNorm-) - resource: { resourceType: 'CodeSystem', id: rxnormCatalogId(v) } }); + resource: { resourceType: 'CodeSystem', id: 'x-' + rxnormCatalogId(v) } }); // 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'); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 46ed0043c..aa6079e0c 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -185,6 +185,12 @@ function semanticTags(db, propertyId) { 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 = ''; @@ -206,11 +212,13 @@ 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 }); - // the catalog id (code_system.resource id): as cs-snomed.js forms it, SCT-- - // (xSCT- for an xsct edition); none for an undated version - const catalogId = sctCatalogId(cfg.codeSystem && cfg.codeSystem.version); + // 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: catalogId } : {}) }, ...cfg.codeSystem }); + 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 @@ -519,4 +527,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, sctCatalogId }; + DISPLAY_REFSETS, EDITION_NAMES, EDITION_LANGUAGES, MODULE_DEPENDENCY, SCT, IS_A, PREFERRED, US_ENGLISH, INFERRED, sctCatalogId, sctCatalogName }; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index e961a8090..d17c66bcf 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -51,7 +51,7 @@ 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). The catalog id a server serves the system under (`CodeSystem/x-`) is `resource.id`; the importers write the id main's provider for the system forms (SNOMED CT `SCT--`, LOINC `loinc`, RxNorm `RxNorm-`); a resource without an id: none; no resource: name and version | +| `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). The CodeSystem id a server serves the system under is `resource.id` as it is (`x-` included), and its catalog name `resource.name` (else `name`); the importers write what main's provider for the system forms: SNOMED CT `x-SCT--` (`x-xSCT-...` for an xsct edition; no id for an undated version) named `SCT ` (`SNOMED CT Test Set` for xsct), LOINC `x-loinc`, RxNorm `x-RxNorm-`; a file without a resource id has no catalog id | | `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 | @@ -256,7 +256,10 @@ SNOMED CT files store each concept's semantic tag as a literal `semanticTag` (st 0`, `report = 'named'`, one value per concept that has one): 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 `)`. Readers report it like -any property and derive nothing. +any property and derive nothing. Answer change: on installed SNOMED CT files this rule differs from the earlier JS provider's +regular expression `/\(([^()]+)\)\s*$/` on 3 concepts per edition (nested brackets) and 94 in the UK +editions (nested brackets and trailing spaces), as counted by the other implementation; for those +concepts `$lookup`'s `semanticTag` changes (to the stored value). `property.role = 'status'`: the literal that holds the concept's status (at most one per system): every row reads it (the provider's `getStatus()`), and `$lookup` lists it by default under its name. diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 1c057a745..7d0210ae3 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1535,7 +1535,17 @@ 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; } + /** 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; + } // behaviour.lookupName: code_system.name or code_system.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; } @@ -1577,15 +1587,13 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { return this._resourceAlgorithm; } /** - * The factory id (read.js and search.js serve it as CodeSystem/x-): the stored CodeSystem - * resource's id (the importers write the id main's provider for the system forms; a resource - * without one: none), else, with no resource, the name and version + * 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() { - let r = null; - try { r = this.store.cs.resource ? JSON.parse(this.store.cs.resource) : null; } catch (e) { r = null; } - if (r) return typeof r.id === 'string' && r.id ? r.id : null; - 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 diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 031883f75..966f8c576 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -9,7 +9,7 @@ const { KIND } = require('./store'); const { Issue } = require('../library/operation-outcome'); const { ECLLexer, ECLParser } = require('../sct/ecl'); const { ConceptMap } = require('../library/conceptmap'); -const { editionName, editionCode } = require('../sct/editions'); +const { editionName } = require('../sct/editions'); const { formatDateMMDDYYYY } = require('../../library/utils/utilities'); const SCT = 'http://snomed.info/sct'; @@ -659,9 +659,6 @@ class SnomedV2Factory extends SqliteV2Factory { edition() { return this.store.cs.edition; } - name() { - return this.version().includes('xsct') ? 'SNOMED CT Test Set' : `SCT ${editionCode(this.edition()) || 'Unknown Edition'}`; - } nameBase() { return 'SCT'; } describeVersion(version) { From e9742eda43435ac5d95534b199fc723ba8f47dce Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:42:26 -0600 Subject: [PATCH 35/90] sqlite-v2: behaviour.domain naming no catalog property refuses the file As the format text states it: a domain code that is not a property of the catalog refuses the file (it selected nothing before). Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 1 + tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/engine/compile.js | 3 +-- tx/sqlite-v2/store.js | 7 +++++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 0cdcdada0..2c1c5239b 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -983,6 +983,7 @@ describe('behaviour.domain: the concepts answers select', () => { expect(codes(f.engine.evaluate(c.domain(c.filter('concept', 'is-a', 'root'))))).toEqual(['A', 'root']); } finally { f.store.close(); } withStore(fixture(), (S) => expect(S.domain()).toBeNull()); + expect(() => openStore(withMeta(fixture(), { 'behaviour.domain': '"nothing"' }))).toThrow(/behaviour.domain nothing is not a property of the catalog/); }); }); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index d17c66bcf..c01859b29 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -198,7 +198,7 @@ refused (the builders check the same at build). | `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 | | `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. ICD-11 files name `icd11`, which the JS reader does not implement (such a file is refused). SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | | `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | -| `domain` | a property code, `null` | `null` (every concept) | the concepts answers select: those with a row of this property (active or not); the file's other concepts are kept (e.g. for history) but no expansion, filter, count or whole-system walk selects them. RxNorm `"SUPPRESS"` (the concepts in RXNCONSO; RXNATOMARCHIVE-only concepts are never selected) | +| `domain` | a property code, `null` | `null` (every concept) | the concepts answers select: those with a row of this property (active or not); the file's other concepts are kept (e.g. for history) but no expansion, filter, count, text-search base set or whole-system walk selects them. A code naming no catalog property refuses the file. RxNorm `"SUPPRESS"` (the concepts in RXNCONSO; RXNATOMARCHIVE-only concepts are never selected) | | `lookupOrder` | `null`, or `{"ranks": {name: int}, "concept"?: int, "other": int, "byCode"?: bool}` | `null` (no reordering) | the order of the properties `$lookup` lists: by rank, `ranks[name]` (the reported name), else `concept` for a code-valued property where given, else `other`; ties in the order the reader lists them, or with `byCode` by name, then value code. SNOMED CT `{"ranks": {"effectiveTime": 0, "parent": 1, "child": 2, "moduleId": 3, "sufficientlyDefined": 4, "semanticTag": 5}, "other": 6}`; RxNorm `{"ranks": {"TTY": 0, "STY": 1, "SAB": 2}, "other": 3, "byCode": true}`; LOINC the axes 0-6, `AnswerList` 8, `parent`/`child` 9, `STATUS` 11, `RELATEDNAMES2` 12, each implicit map's key 13, `concept` 8, `other` 10 | | `implicitMaps` | `null`, or `{"base": url prefix, "maps": [[target system, key], ...], "used"?: infix}` | `null` | the file's implicit ConceptMaps over its `mapping` rows: map `{base}{key}` translates to (and from) the target system, and `$lookup` lists a concept's mappings to it as a property named `key`. With `used`, a map is reported as used as `{base}{used}{key}|{version}` and offered whether or not it translates the code (OMOP); the JS reader does not implement `used` and refuses such a file. LOINC `{"base": "http://loinc.org/cm/", "maps": [...cs-loinc.js's twelve]}` | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index aaf5b8f77..3ce9fa35e 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -139,8 +139,7 @@ class Compiler { domain(node) { const code = this.store.behaviour.domain; if (code == null) return node; - const d = this.store.catalog.get(code); - const live = d ? { t: 'set', kind: KIND.hasProp, pid: d.id, value: 0 } : { t: 'empty' }; + const live = { t: 'set', kind: KIND.hasProp, pid: this.store.catalog.get(code).id, value: 0 }; return node.t === 'all' ? live : { t: 'and', items: [node, live] }; } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 73eb33018..bda921d58 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -455,6 +455,10 @@ class Store { // link properties linksFrom reads when none is named: not a closure source (its pairs are the // descendants sets), and not one whose links are read only where it is named (property.named_links) this.hiddenLinks = [...this.catalog.values()].filter((d) => d.namedLinks || closureSources.has(d.id)).map((d) => d.id); + // behaviour.domain names a catalog property + if (this.behaviour.domain != null && !this.catalog.has(this.behaviour.domain)) { + throw new Error(`${this.file}: behaviour.domain ${this.behaviour.domain} is not a property of the catalog`); + } // 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 @@ -505,8 +509,7 @@ class Store { domain(stats) { const code = this.behaviour.domain; if (code == null) return null; - const d = this.catalog.get(code); - return d ? this.getSet(KIND.hasProp, d.id, 0, stats) : EMPTY; + return this.getSet(KIND.hasProp, this.catalog.get(code).id, 0, stats); } /** the languages of the served system's items (meta, a release fact) */ From e96e47aefd1cea6c93c72bd7891c83b4d1c8d337 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:48:13 -0600 Subject: [PATCH 36/90] sqlite-v2: item_use.role (fsn, synonym, name) item_use.role says what a use is: fsn and synonym (the SNOMED CT description types) and name (a use whose text is accepted as a display: LOINC LONG_COMMON_NAME, SHORTNAME, LinguisticVariantDisplayName). The importers write them; isDisplay finds display uses by role, never by code or system. A file without the column is refused. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 30 +++++++++++++++++++++++- tx/importers/import-loinc-v2.module.js | 2 ++ tx/importers/sct-v2-common.js | 3 +++ tx/importers/sqlite-v2/builder.js | 12 ++++++++-- tx/importers/sqlite-v2/schema.sql | 4 +++- tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/provider.js | 4 ++-- tx/sqlite-v2/snomed.js | 4 +++- tx/sqlite-v2/store.js | 19 +++++++++++---- 9 files changed, 67 insertions(+), 13 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 2c1c5239b..eb9998aee 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1026,7 +1026,7 @@ describe('R3-3. item_use.reported_as: an item use reported as a property', () => const w2 = new Database(old); w2.exec('ALTER TABLE item_use DROP COLUMN reported_as'); w2.close(); - expect(() => openStore(old)).toThrow(/built before the item_use column reported_as existed/); + expect(() => openStore(old)).toThrow(/built before the item_use columns reported_as existed/); }); }); @@ -1137,3 +1137,31 @@ describe('catalog id and name from code_system.resource', () => { } finally { a.store.close(); n.store.close(); } }); }); + +describe('R3-10. item_use.role', () => { + test('a use with role name is a display use; an unknown role or a file without the column is refused', async () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + const file = fixture((b) => b.setUseRole('syn', 'name')); + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { + const p = await f.build(op, []); + expect(p.isDisplay({ use: { system: 'http://example.org/use', code: 'syn' } })).toBe(true); + expect(p.isDisplay({ use: { system: 'http://example.org/use', code: 'other' } })).toBe(false); + expect(p.isDisplay({})).toBe(false); + } finally { f.store.close(); } + const bad = withMeta(file, {}); + const w = new Database(bad); + w.exec("UPDATE item_use SET role = 'preferred'"); + w.close(); + expect(() => openStore(bad)).toThrow(/has role preferred/); + const old = withMeta(file, {}); + const w2 = new Database(old); + w2.exec('ALTER TABLE item_use DROP COLUMN role'); + w2.close(); + expect(() => openStore(old)).toThrow(/built before the item_use columns role existed/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 91155286d..e879daf69 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -200,6 +200,8 @@ function loincCodeSystem(b, version, description) { b.setMeta('linkOrder', 'seq'); // RELATEDNAMES2 items are a $lookup property, not designations b.reportUseAs('RELATEDNAMES2', 'RELATEDNAMES2'); + // the uses whose text is accepted as a display + for (const code of ['LONG_COMMON_NAME', 'SHORTNAME', 'LinguisticVariantDisplayName']) b.setUseRole(code, 'name'); // text search: each concept's best name or code; ties by display, then the stored order b.setBehaviour('textSearch', 'loinc'); b.setMeta('searchTieBreak', 'display'); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index aa6079e0c..7b81b9364 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -230,6 +230,9 @@ class SnomedSink { // numbers (the order of the stored rank, cs-snomed.js's concept order) b.setBehaviour('textSearch', 'snomed'); b.setMeta('searchTieBreak', 'code-length'); + // the description types by role (item_use.role) + b.setUseRole(FSN, 'fsn'); + b.setUseRole(SYNONYM, 'synonym'); b.setBehaviour('lookupOrder', { ranks: { effectiveTime: 0, parent: 1, child: 2, moduleId: 3, sufficientlyDefined: 4, semanticTag: 5 }, other: 6 }); // semanticTag: stored, one value per concept that has one (semanticTags below) const tagProp = b.property({ code: 'semanticTag', shape: 'literal', fhirType: 'string', filterable: false, refinable: false, wildcard: false, report: 'named' }); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 24183f177..04ddb1a5c 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -264,6 +264,12 @@ class TerminologyBuilder { (this.derivers || (this.derivers = [])).push(fn); } + /** the uses with this code have this role (item_use.role: fsn, synonym or name) */ + setUseRole(code, role) { + if (!['fsn', 'synonym', 'name'].includes(role)) throw new Error(`item use ${code}: bad role ${role}`); + (this.useRoles || (this.useRoles = new Map())).set(code, role); + } + /** an item_use coding; returns its use_id */ use({ system = null, code, display = null }) { const k = `${system || ''}|${code}`; @@ -475,8 +481,10 @@ 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, (this.reportedUses && this.reportedUses.get(u.code)) ?? null); + 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, (this.reportedUses && this.reportedUses.get(u.code)) ?? null, (this.useRoles && this.useRoles.get(u.code)) ?? null); + } const insConcept = db.prepare('INSERT INTO concept VALUES (?,?,?,?,?)'); this._time('rewrite concept', () => { diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 94c8042d1..7dc68a69d 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -62,8 +62,10 @@ CREATE TABLE item ( 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, - reported_as TEXT); -- the items of this use are reported as values of a property of this + reported_as TEXT, -- the items of this use are reported as values of a property of this -- name ($lookup), not as designations; NULL: designations (at most one per file) + role TEXT); -- NULL; 'fsn', 'synonym' (SNOMED CT description types); 'name': a use whose + -- text is accepted as a display (LOINC) 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, diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index c01859b29..5f215fd59 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -55,7 +55,7 @@ Fact tables: | `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); `reported_as` (NULL default; at most one per file): the active items of this use are reported as values of a property of this name (`$lookup`: the item's text, with its language), not as designations; listed by default, by name or `*` (LOINC `RELATEDNAMES2`) | +| `item_use` | the uses (SNOMED CT description types, LOINC name kinds, RxNorm TTYs); `reported_as` (NULL default; at most one per file): the active items of this use are reported as values of a property of this name (`$lookup`: the item's text, with its language), not as designations; listed by default, by name or `*` (LOINC `RELATEDNAMES2`); `role` (NULL default): `fsn`, `synonym` (SNOMED CT description types), `name` (a use whose text is accepted as a display: LOINC `LONG_COMMON_NAME`, `SHORTNAME`, `LinguisticVariantDisplayName`); readers find these uses by role, never by code | | `property`, `property_member` | the catalog; a union property's members | | `link` | subject, property, role group, target, active, seq (source order) | | `literal` | subject, property, role group, value, active | diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 7d0210ae3..272a25c15 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -511,9 +511,9 @@ class SqliteV2Provider extends BaseCSServices { async parent() { return null; } + /** a designation whose use's text is accepted as a display (item_use.role 'name') */ isDisplay(d) { - if (this.dialect.name === 'loinc') return !!(d.use && ['SHORTNAME', 'LONG_COMMON_NAME', 'LinguisticVariantDisplayName'].includes(d.use.code)); - return false; + return this.store.useRoleOf(d.use) === 'name'; } async designations(context, displays, significantOnly) { diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 966f8c576..82c6ab813 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -103,7 +103,9 @@ class SnomedV2Provider extends SqliteV2Provider { } isDisplay(d) { - return !!(d && d.use && d.use.system === SCT && (d.use.code === SYNONYM || d.use.code === FSN)); + // the FSN and synonym description types (item_use.role) + const role = d ? this.store.useRoleOf(d.use) : null; + return role === 'synonym' || role === 'fsn'; } /** diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index bda921d58..7b5326863 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -367,12 +367,16 @@ class Store { throw new Error(`${this.file}: behaviour.lookupDesignationCode ${ldc} is not a literal property of the catalog`); } this.uses = new Map(); - if (!db.prepare('PRAGMA main.table_info(item_use)').all().some((c) => c.name === 'reported_as')) { - throw new Error(`${this.file} was built before the item_use column reported_as existed: rebuild it with the importers, or upgrade it`); - } - for (const u of db.prepare('SELECT use_id, system, code, display, reported_as FROM main.item_use').all()) { - this.uses.set(u.use_id, { system: u.system, code: u.code, display: u.display, ...(u.reported_as != null ? { reportedAs: u.reported_as } : {}) }); + const useCols = new Set(db.prepare('PRAGMA main.table_info(item_use)').all().map((c) => c.name)); + const missingUse = ['reported_as', 'role'].filter((c) => !useCols.has(c)); + if (missingUse.length) throw new Error(`${this.file} was built before the item_use columns ${missingUse.join(', ')} existed: rebuild it with the importers, or upgrade it`); + for (const u of db.prepare('SELECT use_id, system, code, display, reported_as, role FROM main.item_use').all()) { + if (u.role != null && !['fsn', 'synonym', 'name'].includes(u.role)) throw new Error(`${this.file}: item use ${u.code} has role ${u.role} (fsn, synonym, name or NULL)`); + this.uses.set(u.use_id, { system: u.system, code: u.code, display: u.display, ...(u.reported_as != null ? { reportedAs: u.reported_as } : {}), ...(u.role != null ? { role: u.role } : {}) }); } + // 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 item use whose items are reported as a property, not as designations (item_use.reported_as) const reported = [...this.uses].filter(([, u]) => u.reportedAs); if (reported.length > 1) throw new Error(`${this.file}: more than one item use with reported_as`); @@ -512,6 +516,11 @@ class Store { return this.getSet(KIND.hasProp, this.catalog.get(code).id, 0, stats); } + /** 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') || '[]'); } From 139319fba32197660641ce637d1128b1a3bbe81c Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 22:58:40 -0600 Subject: [PATCH 37/90] sqlite-v2: plain answer facts as behaviour keys displayRegex, generalizesExcludesSelf, wholeActiveOnly, lookupDefinition, plainDesignationIsDisplay, wholeSystem, locateMessage, versionFormat, inactiveDesignations, displayDesignation and displayLanguage replace the reader's checks of the system: the SNOMED CT dialect's display regex and generalizes rule, the designation lists per system (LOINC order now item.rank written by its importer), the display-only language, the LOINC locate message, the RxNorm version description. The importers write their systems' values. keepDuplicateDesignations is refused (the server's expansion code deduplicates); unknownCodeVersion is checked but the message is chosen by the shared worker code. The SNOMED CT provider no longer reports text definitions (lookupDefinition false, as cs-snomed.js). Two generic test fixtures state their designation facts (expectations unchanged). Co-Authored-By: Claude --- tests/tx/sqlite-v2-engine.test.js | 3 + tests/tx/sqlite-v2-format-round2.test.js | 84 +++++++++++++++++++ tests/tx/sqlite-v2-mixed-providers.test.js | 3 + .../import-loinc-v2-classic.module.js | 4 +- tx/importers/import-loinc-v2.module.js | 20 ++++- tx/importers/import-rxnorm-v2.module.js | 6 ++ tx/importers/sct-v2-common.js | 10 +++ tx/sqlite-v2/README.md | 16 ++++ tx/sqlite-v2/dialects.js | 15 +--- tx/sqlite-v2/engine/compile.js | 19 ++++- tx/sqlite-v2/meta.js | 14 ++++ tx/sqlite-v2/provider.js | 78 ++++++++--------- tx/sqlite-v2/snomed.js | 6 -- tx/sqlite-v2/store.js | 3 + 14 files changed, 213 insertions(+), 68 deletions(-) diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index 56d440de5..b6d92b1b3 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -29,6 +29,9 @@ let rx; function buildFixture(dest) { const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); + // (the display listed as the first designation, inactive items with their status) + b.setBehaviour('displayDesignation', 'distinct'); + b.setBehaviour('inactiveDesignations', 'status'); 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 diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index eb9998aee..b1c63bfd7 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1165,3 +1165,87 @@ describe('R3-10. item_use.role', () => { expect(() => openStore(old)).toThrow(/built before the item_use columns role existed/); }); }); + +describe('R3-8. answer facts as behaviour keys', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { Designations } = require('../../tx/library/designations'); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + let op; + beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); + const base = (extra) => fixture((b, c) => { + b.item(c.A, { language: 'en', text: 'display A' }); // no use, equal to the display + b.item(c.A, { kind: 1, text: 'a text definition', preferred: true }); + b.setUseRole('syn', 'synonym'); + if (extra) extra(b, c); + }); + const withF = async (file, fn) => { + const f = new SqliteV2Factory(op.i18n, file); + await f.load(); + try { return await fn(f, await f.build(op, [])); } finally { f.store.close(); } + }; + const desigs = async (p, code) => { + const ds = new Designations(op.i18n.languageDefinitions); + await p.designations((await p.locate(code)).context, ds); + return ds.designations.map((d) => d.value); + }; + const codes = (f, node) => f.engine.evaluate(node).toArray().map((id) => f.store.conceptRows([id]).get(id).code).sort(); + + test('defaults: no display designation, inactive items left out, generalizes keeps the concept, definitions reported, whole system listed', async () => { + const file = base((b, c) => b.item(c.B, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'old banana', active: false })); + await withF(file, async (f, p) => { + expect(await desigs(p, 'A')).toEqual(['apple tree', 'Apfelbaum', 'display A']); + expect(await desigs(p, 'B')).not.toContain('old banana'); + expect(await p.definition((await p.locate('A')).context)).toBe('a text definition'); + const c = new Compiler({ store: f.store, dialect: {} }); + expect(codes(f, c.filter('concept', 'generalizes', 'A'))).toEqual(['A', 'root']); + expect(codes(f, c.include({ system: f.store.system }).parts[0].node)).toEqual(['A', 'B', 'C', 'X', 'root']); + expect(codes(f, c.filter('display', 'regex', 'display .*'))).toEqual(['A', 'B', 'C', 'X', 'root']); + }); + }); + + test('displayDesignation, inactiveDesignations, plainDesignationIsDisplay', async () => { + const extra = (b, c) => b.item(c.B, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'old banana', active: false }); + await withF(withMeta(base(extra), { 'behaviour.displayDesignation': '"distinct"', 'behaviour.inactiveDesignations': '"status"' }), async (f, p) => { + expect(await desigs(p, 'A')).toEqual(['display A', 'apple tree', 'Apfelbaum', 'display A']); + expect(await desigs(p, 'B')).toContain('old banana'); + }); + await withF(withMeta(base(extra), { 'behaviour.displayDesignation': '"first"', 'behaviour.inactiveDesignations': '"plain"' }), async (f, p) => { + expect(await desigs(p, 'A')).toEqual(['display A', 'apple tree', 'Apfelbaum']); + }); + await withF(withMeta(base(), { 'behaviour.plainDesignationIsDisplay': 'true' }), async (f, p) => { + expect(await desigs(p, 'A')).toEqual(['apple tree', 'Apfelbaum']); + }); + }); + + test('generalizesExcludesSelf, wholeActiveOnly, wholeSystem, lookupDefinition, displayRegex', async () => { + await withF(withMeta(base(), { 'behaviour.generalizesExcludesSelf': 'true', 'behaviour.wholeActiveOnly': 'true', 'behaviour.lookupDefinition': 'false', + 'behaviour.displayRegex': '"designations"' }), async (f, p) => { + const c = new Compiler({ store: f.store, dialect: {}, lang: 'en' }); + expect(codes(f, c.filter('concept', 'generalizes', 'A'))).toEqual(['root']); + expect(codes(f, c.include({ system: f.store.system }).parts[0].node)).toEqual(['A', 'B', 'C', 'root']); + expect(await p.definition((await p.locate('A')).context)).toBeNull(); + // display regex over the designations of synonym / fsn uses, not the display + expect(codes(f, c.filter('display', 'regex', 'apple.*'))).toEqual(['A']); + expect(codes(f, c.filter('display', 'regex', 'display A'))).toEqual([]); + }); + await withF(withMeta(base(), { 'behaviour.wholeSystem': '"empty"' }), async (f) => { + expect(codes(f, new Compiler({ store: f.store, dialect: {} }).include({ system: f.store.system }).parts[0].node)).toEqual([]); + }); + await withF(withMeta(base(), { 'behaviour.wholeSystem': '"refuse"' }), async (f) => { + expect(() => new Compiler({ store: f.store, dialect: {} }).include({ system: f.store.system })).toThrow(/cannot be expanded as a whole/); + }); + }); + + test('locateMessage, versionFormat; keepDuplicateDesignations refused; malformed values refused', async () => { + await withF(withMeta(base(), { 'behaviour.locateMessage': '"No code {code} here"', 'behaviour.versionFormat': '"MMDDYYYY"' }), async (f, p) => { + expect(await p._filterLocate(null, null, 'ZZ')).toBe('No code ZZ here'); + expect(f.describeVersion('03022026')).toBe(require('../../library/utils/utilities').formatDateMMDDYYYY('03022026')); + }); + expect(() => openStore(withMeta(base(), { 'behaviour.keepDuplicateDesignations': 'true' }))).toThrow(/keepDuplicateDesignations is set/); + for (const [k, v] of [['locateMessage', '"no placeholder"'], ['versionFormat', '"YYYY"'], ['wholeSystem', '"some"'], ['displayDesignation', '"all"']]) { + expect(() => openStore(withMeta(base(), { ['behaviour.' + k]: v }))).toThrow(/is not a value/); + } + }); +}); diff --git a/tests/tx/sqlite-v2-mixed-providers.test.js b/tests/tx/sqlite-v2-mixed-providers.test.js index 37062c134..519d3e0e6 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 display listed as the first designation, inactive items with their status) + b.setBehaviour('displayDesignation', 'distinct'); + b.setBehaviour('inactiveDesignations', 'status'); const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); const c = {}; for (const code of ['root', 'A', 'A1', 'A2', 'A3', 'B', 'B1']) { diff --git a/tx/importers/import-loinc-v2-classic.module.js b/tx/importers/import-loinc-v2-classic.module.js index 379b11e00..ca93c56c3 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('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 e879daf69..8cdaca676 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -172,6 +172,17 @@ function loincCatalog(b) { 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); +} + /** 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'], @@ -208,6 +219,11 @@ function loincCodeSystem(b, version, description) { // $lookup's property order (cs-loinc.js extendLookup): the axes, the other links, parent and child, // the other properties, STATUS, RELATEDNAMES2, then the mappings (each map's key, last) // the implicit concept maps http://loinc.org/cm/ over the mapping rows + // designations: the display first, then every designation (equal texts too), in item rank; the + // display's language en-US; a code it cannot locate: cs-loinc.js's message + b.setBehaviour('displayDesignation', 'distinct'); + b.setBehaviour('displayLanguage', 'en-US'); + b.setBehaviour('locateMessage', 'Not a valid code: {code}'); b.setBehaviour('implicitMaps', { base: 'http://loinc.org/cm/', maps: LOINC_MAPS }); b.setBehaviour('lookupOrder', { ranks: { CLASS: 0, COMPONENT: 1, PROPERTY: 2, TIME_ASPCT: 3, SYSTEM: 4, SCALE_TYP: 5, METHOD_TYP: 6, AnswerList: 8, parent: 9, child: 9, STATUS: 11, RELATEDNAMES2: 12, ...Object.fromEntries(LOINC_MAPS.map(([, key]) => [key, 13])) }, concept: 8, other: 10 }); @@ -229,7 +245,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 @@ -566,4 +582,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, loincCatalogId }; + KIND, LOINC, ORDER_TYPE, ORDER_STAGE, ORDER, LITERALS, PART_LINK, loincCatalogId, loincItemRank }; diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index b4a115ab3..bb2d23506 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -73,6 +73,12 @@ async function importRxNormV2(cfg) { b.setBehaviour('versionAlgorithm', 'date'); // answers select the concepts in RXNCONSO (a SUPPRESS literal), never the RXNATOMARCHIVE-only ones b.setBehaviour('domain', 'SUPPRESS'); + // designations: the display first, the atom equal to it not repeated; archived atoms listed like + // active ones; versions are dates MMDDYYYY; the display's language en-US + b.setBehaviour('displayDesignation', 'first'); + b.setBehaviour('inactiveDesignations', 'plain'); + b.setBehaviour('versionFormat', 'MMDDYYYY'); + b.setBehaviour('displayLanguage', 'en-US'); // text search: the best atom name or code among the concepts with a non-SY atom; ties by code (text) b.setBehaviour('textSearch', 'rxnorm'); b.setMeta('searchTieBreak', 'code'); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 7b81b9364..24ba67655 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -230,6 +230,16 @@ class SnomedSink { // numbers (the order of the stored rank, cs-snomed.js's concept order) b.setBehaviour('textSearch', 'snomed'); b.setMeta('searchTieBreak', 'code-length'); + // display regex over the FSNs and synonyms; generalizes leaves out the concept; whole-system + // selections active only; no text definition reported (as cs-snomed.js); inactive descriptions + // listed with their status; the unknown-code message names the edition; the display en-US + b.setBehaviour('displayRegex', 'designations'); + b.setBehaviour('generalizesExcludesSelf', true); + b.setBehaviour('wholeActiveOnly', true); + b.setBehaviour('lookupDefinition', false); + b.setBehaviour('inactiveDesignations', 'status'); + b.setBehaviour('unknownCodeVersion', true); + b.setBehaviour('displayLanguage', 'en-US'); // the description types by role (item_use.role) b.setUseRole(FSN, 'fsn'); b.setUseRole(SYNONYM, 'synonym'); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 5f215fd59..19d6f8b2e 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -201,6 +201,19 @@ refused (the builders check the same at build). | `domain` | a property code, `null` | `null` (every concept) | the concepts answers select: those with a row of this property (active or not); the file's other concepts are kept (e.g. for history) but no expansion, filter, count, text-search base set or whole-system walk selects them. A code naming no catalog property refuses the file. RxNorm `"SUPPRESS"` (the concepts in RXNCONSO; RXNATOMARCHIVE-only concepts are never selected) | | `lookupOrder` | `null`, or `{"ranks": {name: int}, "concept"?: int, "other": int, "byCode"?: bool}` | `null` (no reordering) | the order of the properties `$lookup` lists: by rank, `ranks[name]` (the reported name), else `concept` for a code-valued property where given, else `other`; ties in the order the reader lists them, or with `byCode` by name, then value code. SNOMED CT `{"ranks": {"effectiveTime": 0, "parent": 1, "child": 2, "moduleId": 3, "sufficientlyDefined": 4, "semanticTag": 5}, "other": 6}`; RxNorm `{"ranks": {"TTY": 0, "STY": 1, "SAB": 2}, "other": 3, "byCode": true}`; LOINC the axes 0-6, `AnswerList` 8, `parent`/`child` 9, `STATUS` 11, `RELATEDNAMES2` 12, each implicit map's key 13, `concept` 8, `other` 10 | | `implicitMaps` | `null`, or `{"base": url prefix, "maps": [[target system, key], ...], "used"?: infix}` | `null` | the file's implicit ConceptMaps over its `mapping` rows: map `{base}{key}` translates to (and from) the target system, and `$lookup` lists a concept's mappings to it as a property named `key`. With `used`, a map is reported as used as `{base}{used}{key}|{version}` and offered whether or not it translates the code (OMOP); the JS reader does not implement `used` and refuses such a file. LOINC `{"base": "http://loinc.org/cm/", "maps": [...cs-loinc.js's twelve]}` | +| `displayRegex` | `"display"`, `"designations"` | `"display"` | what a `display regex` filter matches: the concept's display, or (`designations`) any active designation of a use with role `fsn` or `synonym` in the request's text-search language. SNOMED CT `"designations"` | +| `generalizesExcludesSelf` | boolean | `false` | `generalizes` leaves out the concept itself. SNOMED CT `true` | +| `wholeActiveOnly` | boolean | `false` | a whole-system selection, and the roots of a walk, hold active concepts only. SNOMED CT `true` | +| `lookupDefinition` | boolean | `true` | text definitions are reported (`$lookup` `definition`, expansion rows). SNOMED CT `false` | +| `keepDuplicateDesignations` | boolean | `false` | expansion rows keep a designation that repeats another. The JS reader does not implement it (the server's expansion code deduplicates) and refuses `true` | +| `plainDesignationIsDisplay` | boolean | `false` | a designation with no use whose text equals the display is the display (not listed again) | +| `wholeSystem` | `"list"`, `"empty"`, `"refuse"` | `"list"` | what an include of the whole system does | +| `unknownCodeVersion` | boolean | `false` | the unknown-code message names the version and edition (meta `edition`). SNOMED CT `true`. The JS server chooses that message in its shared worker code by the system URI, for every provider; the JS reader validates the key but cannot set the message | +| `locateMessage` | a string with `{code}`, `null` | `null` | the provider's reason for a code it cannot locate. LOINC `"Not a valid code: {code}"` | +| `versionFormat` | `"MMDDYYYY"`, `null` | `null` | versions are dates written MMDDYYYY (described as such; the JS reader's `describeVersion`). RxNorm `"MMDDYYYY"` | +| `inactiveDesignations` | `"omit"`, `"status"`, `"plain"` | `"omit"` | inactive items as designations: left out; listed with status inactive; listed like active ones. SNOMED CT `"status"`, RxNorm `"plain"` | +| `displayDesignation` | `"none"`, `"first"`, `"distinct"` | `"none"` | the display listed as the first designation: `first` also drops the first designation whose text equals it, `distinct` keeps every designation. LOINC `"distinct"`, RxNorm `"first"` | +| `displayLanguage` | a language tag, `null` | `null` (`code_system.default_language`) | the language of the stored display (the display designation's language). SNOMED CT, LOINC, RxNorm `"en-US"` | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | @@ -252,6 +265,9 @@ asked for as `module`; `definitionStatusId` reported as `sufficientlyDefined`, t `900000000000073002`, `report` `named`. No other system sets them. Readers keep no table of names by system. +Designations are listed in `item.rank` order (unranked last), then item order; the LOINC importer +writes ranks in cs-loinc.js's order (by use, en-US first). + SNOMED CT files store each concept's semantic tag as a literal `semanticTag` (string, `filterable = 0`, `report = 'named'`, one value per concept that has one): 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 diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js index 276e505ce..4cf8a576b 100644 --- a/tx/sqlite-v2/dialects.js +++ b/tx/sqlite-v2/dialects.js @@ -4,11 +4,8 @@ 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, @@ -231,7 +228,6 @@ function sctId(v) { const snomed = { name: 'snomed', - 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); @@ -319,15 +315,8 @@ const snomed = { 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); + // display: regex only (behaviour.displayRegex: compile.js), as cs-snomed.js + if (prop === 'display' && op !== 'regex') throw notUnderstood(prop, op, value); if (sctId(prop)) { if (op !== '=') throw notUnderstood(prop, op, value); const p = S.filterProp(String(prop).trim()); diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 3ce9fa35e..d5f562b2b 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -116,7 +116,14 @@ class Compiler { 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 }); + // behaviour.wholeSystem: list it, list nothing, or refuse; wholeActiveOnly: its active concepts + const whole = this.store.behaviour.wholeSystem; + if (whole === 'refuse') throw new FilterError(`The code system ${this.store.system} cannot be expanded as a whole`); + if (whole === 'empty') parts.push({ node: { t: 'empty' }, order: null }); + else { + const all = this.domain({ t: 'all', whole: true }); + parts.push({ node: this.store.behaviour.wholeActiveOnly ? { t: 'and', items: [all, { t: 'active' }], whole: true } : all, order: null }); + } return { parts }; } if (inc.concept && inc.concept.length) { @@ -189,6 +196,14 @@ class Compiler { const n = this.dialect.filter(this, prop, op, value); if (n) return n; } + if (prop === 'display' && op === 'regex' && this.store.behaviour.displayRegex === 'designations' && !this.store.filterProp('display')) { + // behaviour.displayRegex 'designations': any active designation of a display use (item_use.role + // fsn or synonym) in the one language the request chooses (term.lang) matches the whole term + const lits = this.store.hasFts ? requiredLiterals(value) : []; + const lang = (this.term && this.term.lang) || 'en'; + const uses = [...this.store.uses.values()].filter((u) => u.role === 'fsn' || u.role === 'synonym').map((u) => u.code); + return { t: 'desigRegex', re: String(value), lang, uses, ...(lits.length ? { lits } : {}), label: `display (${lang}) ~ /${value}/` }; + } if (prop === 'display' && !this.store.filterProp('display')) return this.displayFilter(op, value); // FHIR's concept status, where the file lists it as a filter (behaviour.filters code 'inactive') if (prop === 'inactive' && !this.store.filterProp('inactive') && op === '=' && (this.store.behaviour.filters || []).some((x) => x.code === 'inactive')) { @@ -259,7 +274,7 @@ 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: !this.store.behaviour.generalizesExcludesSelf }; case 'child-of': return S.hierarchy ? { t: 'set', kind: KIND.prop, pid: S.hierarchy.id, value: id } : { t: 'empty' }; case 'descendent-leaf': return { t: 'and', items: [desc, { t: 'leaf' }] }; default: throw this.notSupported(prop, op, value); diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 049e01719..1be4b3dab 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -106,6 +106,20 @@ const KEYS = Object.freeze({ 'behaviour.implicitMaps': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['base', 'maps', 'used']) && isString(v.base) && v.base !== '' && Array.isArray(v.maps) && v.maps.every((m) => Array.isArray(m) && m.length === 2 && isString(m[0]) && isString(m[1]) && m[1] !== '') && (v.used === undefined || (isString(v.used) && v.used !== ''))), null), + // plain answer facts (README.md "Behaviour settings") + 'behaviour.displayRegex': json((v) => v === 'display' || v === 'designations', 'display'), + 'behaviour.generalizesExcludesSelf': json(isBool, false), + 'behaviour.wholeActiveOnly': json(isBool, false), + 'behaviour.lookupDefinition': json(isBool, true), + 'behaviour.keepDuplicateDesignations': json(isBool, false), + 'behaviour.plainDesignationIsDisplay': json(isBool, false), + 'behaviour.wholeSystem': json((v) => ['list', 'empty', 'refuse'].includes(v), 'list'), + 'behaviour.unknownCodeVersion': json(isBool, false), + 'behaviour.locateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), + 'behaviour.versionFormat': json((v) => v === null || v === 'MMDDYYYY', null), + 'behaviour.inactiveDesignations': json((v) => ['omit', 'status', 'plain'].includes(v), 'omit'), + 'behaviour.displayDesignation': json((v) => ['none', 'first', 'distinct'].includes(v), 'none'), + 'behaviour.displayLanguage': json((v) => v === null || (isString(v) && v !== ''), null), 'behaviour.expansionLimit': json(isCount, 0), // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one 'behaviour.textSearch': json((v) => v === null || (isString(v) && v !== ''), null), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 272a25c15..0225e9265 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -14,12 +14,11 @@ 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 { dialectFor, LOINC } = require('./dialects'); const { DesignationUse } = require('../library/designations'); const { VersionUtilities } = require('../../library/fhir/version-utilities'); const { SupplementLayers } = require('./layers'); @@ -470,6 +469,8 @@ class SqliteV2Provider extends BaseCSServices { } async definition(context) { + // behaviour.lookupDefinition: whether text definitions are reported + if (!this.store.behaviour.lookupDefinition) return null; const c = await this._ensure(context); return c && c.row ? c.row.definition || null : null; } @@ -532,25 +533,23 @@ 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.reportedAs) continue; - displays.addDesignation(false, 'active', d.language, this._useOf(d), d.term.trim()); - } - } else if (this.dialect.name === 'rxnorm') { - // upstream: the display is the first non-SY atom; every other atom is a designation - 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', this._useOf(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, this._useOf(d), d.term); - } + // the file's facts (README.md "Behaviour settings"): whether the display is listed as the first + // designation (displayDesignation), how inactive items are listed (inactiveDesignations), whether + // a designation with no use equal to the display is the display (plainDesignationIsDisplay); + // designations in item rank, then item order + const b = this.store.behaviour; + const display = (c.row.display || '').trim(); + if (b.displayDesignation !== 'none') displays.addDesignation(true, 'active', this._displayLanguage(), null, display); + let skipped = b.displayDesignation !== 'first'; + const rows = [...c.desigs].sort((x, y) => ((x.rank ?? Infinity) - (y.rank ?? Infinity)) || (x.id - y.id)); + for (const d of rows) { + if (d.use && d.use.reportedAs) continue; + if (!d.active && b.inactiveDesignations === 'omit') continue; + const term = d.term.trim(); + if (!skipped && term === display) { skipped = true; continue; } + if (b.plainDesignationIsDisplay && !d.use && term === display) continue; + const status = d.active || b.inactiveDesignations === 'plain' ? 'active' : 'inactive'; + displays.addDesignation(false, status, d.language, this._useOf(d), term); } this._listSupplementDesignations(c.code, displays); } @@ -567,12 +566,15 @@ class SqliteV2Provider extends BaseCSServices { return b.preferredForLanguage && d.preferred ? { ...DesignationUse.DISPLAY } : null; } - /** the display as the one designation, as each dialect adds it, plus supplement designations */ + /** the language of the stored display (behaviour.displayLanguage, else code_system.default_language, else en) */ + _displayLanguage() { + return this.store.behaviour.displayLanguage || this.store.defaultLanguage || this.defLang(); + } + + /** the display as the one designation, 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); + const d = ((c.row && c.row.display) || '').trim(); + if (d) displays.addDesignation(true, 'active', this._displayLanguage(), null, d); this._listSupplementDesignations(c.code, displays); } @@ -601,10 +603,11 @@ class SqliteV2Provider extends BaseCSServices { // iterator(null): ORDER BY RXCUI) const dom = this.store.domain(this._stats()); if (dom) return this.engine._order ? this.engine._ordered(dom) : dom.toArray(); - // concepts without an active parent + // concepts without an active parent: the active ones where the file says so (behaviour.wholeActiveOnly) 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(); + const base = this.store.behaviour.wholeActiveOnly ? this.store.active() : this.store.all(); + return RoaringBitmap32.andNot(base, hasParent).toArray(); } async iteratorAll() { @@ -1225,7 +1228,8 @@ 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; + // behaviour.locateMessage: the provider's reason for a code it cannot locate + if (!r.context) return this.store.behaviour.locateMessage ? this.store.behaviour.locateMessage.split('{code}').join(code) : r.message; return this._member(set, r.context.id) ? r.context : null; } @@ -1451,19 +1455,6 @@ function propertyDefinitionsFor(store, dialect) { 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 (behaviour.implicitMaps): [{system, key, url}], each map @@ -1606,7 +1597,8 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { } describeVersion(v) { - if (this.store.system === RXNORM) { + // behaviour.versionFormat MMDDYYYY: versions are dates written MMDDYYYY + if (this.store.behaviour.versionFormat === 'MMDDYYYY') { const { formatDateMMDDYYYY } = require('../../library/utils/utilities'); return formatDateMMDDYYYY(v); } diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 82c6ab813..366dfc6c1 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -242,12 +242,6 @@ 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'; diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 7b5326863..20caf94a4 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -339,6 +339,9 @@ class Store { this.searchTieBreak = m.searchTieBreak; // identifier-aliased codes (behaviour.aliases): this server does not implement them, and would // answer such a file's codes wrongly + // behaviour.keepDuplicateDesignations: expansion rows' designations are deduplicated by the + // server's expansion code, which this reader does not control + if (m.behaviour.keepDuplicateDesignations) throw new Error(`${this.file}: behaviour.keepDuplicateDesignations is set, which this server does not implement`); if (m.behaviour.aliases !== null) throw new Error(`${this.file}: behaviour.aliases is set (identifier-aliased codes), which this server does not implement`); // behaviour.implicitMaps.used (maps reported as used whether or not they translate): not implemented here if (m.behaviour.implicitMaps && m.behaviour.implicitMaps.used !== undefined) { From 03cbd8fd4bc065310ae815fb8b202a835250be8e Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 23:04:07 -0600 Subject: [PATCH 38/90] sqlite-v2: the sweep's remaining facts as data (status, deprecation, display language, value sets, properties, orders) - RxNorm stores the status of an inactive concept as a status literal (obsolete / archived, role status, never reported); behaviour. deprecatedStatus lists the values that mean deprecated (RxNorm archived, LOINC DEPRECATED). The RxNorm status and deprecation rules go. - behaviour.declaresProperties (default true; SNOMED CT, LOINC, RxNorm false) replaces the reader's list of systems without definitions. - behaviour.implicitValueSets names the implicit value-set URL grammar (snomed, loinc); another name refuses the file. - hasParents and _rootDisplay no longer test the system. - The index builder computes no system order: SNOMED CT and RxNorm importers write ix_order rank and ids (derived-by-importer), as LOINC already did. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 40 +++++++++++++++++++++ tx/importers/import-loinc-v2.module.js | 3 ++ tx/importers/import-rxnorm-v2.module.js | 30 ++++++++++++++-- tx/importers/sct-v2-common.js | 12 +++++-- tx/importers/sqlite-v2/indexes.js | 23 ++----------- tx/sqlite-v2/README.md | 5 ++- tx/sqlite-v2/meta.js | 3 ++ tx/sqlite-v2/provider.js | 44 +++++++++++------------- tx/sqlite-v2/snomed.js | 2 ++ 9 files changed, 113 insertions(+), 49 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index b1c63bfd7..c588d9b24 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1249,3 +1249,43 @@ describe('R3-8. answer facts as behaviour keys', () => { } }); }); + +describe('R3-9. deprecatedStatus, declaresProperties, implicitValueSets; the system order written by the importer', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + let op; + beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); + const load = async (file) => { const f = new SqliteV2Factory(op.i18n, file); await f.load(); return f; }; + test('deprecated: a status listed in deprecatedStatus; declaresProperties false: no property definitions', async () => { + const file = fixture((b, c) => { + const st = b.property({ code: 'status', shape: 'literal', fhirType: 'code', role: 'status', report: 'never', filterable: false }); + b.literal(c.X, st, 'retired'); + b.literal(c.A, st, 'trial'); + b.setBehaviour('deprecatedStatus', ['retired']); + b.setBehaviour('declaresProperties', false); + }); + const f = await load(file); + try { + const p = await f.build(op, []); + expect(await p.isDeprecated((await p.locate('X')).context)).toBe(true); + expect(await p.isDeprecated((await p.locate('A')).context)).toBe(false); + expect(p.propertyDefinitions()).toBeNull(); + } finally { f.store.close(); } + const g = await load(fixture()); + try { expect((await g.build(op, [])).propertyDefinitions().length).toBeGreaterThan(0); } finally { g.store.close(); } + }); + test('implicitValueSets: a URL grammar this reader does not implement refuses the file', async () => { + await expect(load(withMeta(fixture(), { 'behaviour.implicitValueSets': '"omop"' }))).rejects.toThrow(/implicit value sets are omop .* does not implement/); + await expect(load(withMeta(fixture(), { 'behaviour.implicitValueSets': '"snomed"' }))).rejects.toThrow(/implicit value sets are snomed/); + const f = await load(withMeta(fixture(), { 'behaviour.implicitValueSets': '"loinc"' })); + f.store.close(); + }); + test('the index builder computes no order: a file stating a stored expansion order without one breaks a contract', () => { + const b = new TerminologyBuilder(path.join(dir, 'noorder.db'), { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://www.nlm.nih.gov/research/umls/rxnorm', version: '1' }); + b.concept('1'); + b.setBehaviour('expansionOrder', 'stored'); + expect(() => b.finish()).toThrow(/contract: behaviour.expansionOrder "stored" without ix_order rank and ids/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 8cdaca676..337f278c1 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -224,6 +224,9 @@ function loincCodeSystem(b, version, description) { b.setBehaviour('displayDesignation', 'distinct'); b.setBehaviour('displayLanguage', 'en-US'); b.setBehaviour('locateMessage', 'Not a valid code: {code}'); + b.setBehaviour('deprecatedStatus', ['DEPRECATED']); + b.setBehaviour('declaresProperties', false); + b.setBehaviour('implicitValueSets', 'loinc'); b.setBehaviour('implicitMaps', { base: 'http://loinc.org/cm/', maps: LOINC_MAPS }); b.setBehaviour('lookupOrder', { ranks: { CLASS: 0, COMPONENT: 1, PROPERTY: 2, TIME_ASPCT: 3, SYSTEM: 4, SCALE_TYP: 5, METHOD_TYP: 6, AnswerList: 8, parent: 9, child: 9, STATUS: 11, RELATEDNAMES2: 12, ...Object.fromEntries(LOINC_MAPS.map(([, key]) => [key, 13])) }, concept: 8, other: 10 }); diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index bb2d23506..f5caa6f53 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -34,7 +34,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('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'; @@ -79,6 +80,7 @@ async function importRxNormV2(cfg) { b.setBehaviour('inactiveDesignations', 'plain'); b.setBehaviour('versionFormat', 'MMDDYYYY'); b.setBehaviour('displayLanguage', 'en-US'); + b.setBehaviour('declaresProperties', false); // text search: the best atom name or code among the concepts with a non-SY atom; ties by code (text) b.setBehaviour('textSearch', 'rxnorm'); b.setMeta('searchTieBreak', 'code'); @@ -94,6 +96,14 @@ async function importRxNormV2(cfg) { // it (report 'never': cs-rxnorm.js has no such property) const TTY = lit('TTY', 'Term Type'), SAB = lit('SAB', 'Source'), SUPPRESS = lit('SUPPRESS', 'Suppress flag', { filterable: false, filterOps: null, report: 'never' }), STY = lit('STY', 'Semantic Type (TUI)'); + // the status of an inactive concept (role 'status', never reported): obsolete (still in RXNCONSO, + // a SUPPRESS literal) or archived (RXNATOMARCHIVE only); archived ones are deprecated + const STATUS = b.property({ code: 'status', uri: `${RXNORM}/status`, shape: 'literal', fhirType: 'code', display: 'Status', + role: 'status', report: 'never', filterable: false }); + b.setBehaviour('deprecatedStatus', ['archived']); + b.deriveFacts((db) => db.prepare(`INSERT INTO literal SELECT c.id, ?, 0, + CASE WHEN EXISTS (SELECT 1 FROM literal l WHERE l.subject_id = c.id AND l.property_id = ?) THEN 'obsolete' ELSE 'archived' END, 1 + FROM concept c WHERE c.active = 0`).run(STATUS, SUPPRESS).changes); 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(); @@ -304,7 +314,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 { diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 24ba67655..16c2e98c1 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -159,7 +159,7 @@ 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 @@ -240,6 +240,8 @@ class SnomedSink { b.setBehaviour('inactiveDesignations', 'status'); b.setBehaviour('unknownCodeVersion', true); b.setBehaviour('displayLanguage', 'en-US'); + b.setBehaviour('declaresProperties', false); + b.setBehaviour('implicitValueSets', 'snomed'); // the description types by role (item_use.role) b.setUseRole(FSN, 'fsn'); b.setUseRole(SYNONYM, 'synonym'); @@ -512,9 +514,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'); diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index ed16b58c7..4b588242e 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -17,7 +17,7 @@ // 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_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 // ix.ix_word.names selects (the importer states it; it is kept across a // rebuild), with meta ix.ix_word.format and ix.ix_word.stemmers (each language's @@ -28,7 +28,6 @@ const Database = require('better-sqlite3'); const { serialize, rangeSet, descendantsFromEdges, descendantsFromPairs } = require('../sqlite-v2/sets'); const sets = require('../sqlite-v2/sets'); -const dialectOf = (uri) => require('../../sqlite-v2/dialects').dialectFor(uri).name; const KIND = { all: 1, active: 2, leaf: 3, descendants: 4, prop: 5, hasProp: 6, record: 7 }; const VK = { none: 0, node: 1, literal: 2 }; @@ -100,17 +99,12 @@ 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, 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)); - } + // 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 (names != null) { const setMeta = db.prepare('INSERT OR REPLACE INTO main.meta VALUES (?, ?)'); setMeta.run('ix.ix_word.names', names); @@ -256,17 +250,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++) { diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 19d6f8b2e..c6c74a340 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -73,7 +73,7 @@ Index tables (rebuildable): | `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_order` | (written by the importer, listed in `derived-by-importer`; the index builder computes none) per-concept arrays in 1,024-entry blocks: `rank`, `ids` (the system order), `walk` (the whole system in the built-in walk order; `ix.ix_order.walk.reached` in meta), `active` (walk restricted to active concepts, stored only where they are not a prefix of walk: LOINC), `hier_start` / `hier` (LOINC parent and child entries in main's order, where the parent links' seq does not give it) | | `ix_key` | text keys of nodes (SNOMED CT normal forms) | | `ix_word` | the text-filter word index per language over the names `ix.ix_word.names` selects: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (below) | | `ix_text_display`, `ix_text_item` | FTS5 trigram indexes over displays and item texts (regex prefilter) | @@ -214,6 +214,9 @@ refused (the builders check the same at build). | `inactiveDesignations` | `"omit"`, `"status"`, `"plain"` | `"omit"` | inactive items as designations: left out; listed with status inactive; listed like active ones. SNOMED CT `"status"`, RxNorm `"plain"` | | `displayDesignation` | `"none"`, `"first"`, `"distinct"` | `"none"` | the display listed as the first designation: `first` also drops the first designation whose text equals it, `distinct` keeps every designation. LOINC `"distinct"`, RxNorm `"first"` | | `displayLanguage` | a language tag, `null` | `null` (`code_system.default_language`) | the language of the stored display (the display designation's language). SNOMED CT, LOINC, RxNorm `"en-US"` | +| `deprecatedStatus` | a list of status values | `[]` | the values of the status literal (`role = 'status'`) that mean deprecated. RxNorm `["archived"]` (RxNorm files store the status of an inactive concept: `obsolete`, still in RXNCONSO, or `archived`, RXNATOMARCHIVE only); LOINC `["DEPRECATED"]` | +| `declaresProperties` | boolean | `true` | the server declares the file's properties (expansion property definitions). SNOMED CT, LOINC, RxNorm `false` | +| `implicitValueSets` | a URL-grammar name, `null` | `null` (none) | the implicit value sets, by a named URL grammar (like `grammar`); a name the reader does not implement refuses the file. SNOMED CT `snomed` (`?fhir_vs=...`), LOINC `loinc` (`/vs`, `/vs/LP...`, `/vs/LL...`), OMOP `omop` (not in the JS reader) | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | | `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 1be4b3dab..bcf8e75b6 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -119,6 +119,9 @@ const KEYS = Object.freeze({ 'behaviour.versionFormat': json((v) => v === null || v === 'MMDDYYYY', null), 'behaviour.inactiveDesignations': json((v) => ['omit', 'status', 'plain'].includes(v), 'omit'), 'behaviour.displayDesignation': json((v) => ['none', 'first', 'distinct'].includes(v), 'none'), + 'behaviour.deprecatedStatus': json(isStrings, []), + 'behaviour.declaresProperties': json(isBool, true), + 'behaviour.implicitValueSets': json((v) => v === null || (isString(v) && v !== ''), null), 'behaviour.displayLanguage': json((v) => v === null || (isString(v) && v !== ''), null), 'behaviour.expansionLimit': json(isCount, 0), // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 0225e9265..d804692b0 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -111,7 +111,7 @@ class SqliteV2Provider extends BaseCSServices { const walked = this.store.domain(this._stats()) || this.store.all(); return walked.andCardinality(this.store.active()); } - hasParents() { return !!this.store.hierarchy || this.dialect.name === 'rxnorm'; } + hasParents() { return !!this.store.hierarchy; } isNotClosed() { return !!this.store.notClosed; } contentMode() { return this.store.cs.content || 'complete'; } versionAlgorithm() { return this.f.versionAlgorithm(); } @@ -195,7 +195,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()); @@ -207,9 +207,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); @@ -482,20 +481,14 @@ class SqliteV2Provider extends BaseCSServices { return c ? !c.row.active : false; } + /** deprecated: its status (the role 'status' literal) is one behaviour.deprecatedStatus lists */ async isDeprecated(context) { - const c = await this._ensure(context); - if (this.dialect.name === 'rxnorm') return this._rxArchived(c); - return false; - } - - /** RxNorm: the concepts in RXNCONSO (active or obsolete), not the archived ones */ - _rxLive() { - return this.store.domain(this._stats()) || this.store.all(); + const list = this.store.behaviour.deprecatedStatus; + if (!list.length || !this.store.statusProp) return false; + const s = await this.getStatus(context); + return s != null && list.includes(s); } - /** RxNorm: inactive because archived (RXNATOMARCHIVE only), not obsolete (SUPPRESS = O) */ - _rxArchived(c) { return !c.row.active && !this._rxLive().has(c.id); } - async getStatus(context) { const c = await this._ensure(context); if (!c) return null; @@ -506,7 +499,6 @@ class SqliteV2Provider extends BaseCSServices { const v = this.store.literalValues([c.id], p.id, this._stats()).get(c.id); return v === undefined ? null : v; } - if (this.dialect.name === 'rxnorm') return c.row.active ? null : (this._rxArchived(c) ? 'archived' : 'obsolete'); return c.row.active ? 'active' : 'inactive'; } @@ -1393,8 +1385,6 @@ class SqliteV2Provider extends BaseCSServices { } -/** the property definitions a file reports (data built at load) */ -const NO_PROPERTY_DEFINITIONS = new Set(['snomed', 'loinc', 'rxnorm']); /** * The property parameters $lookup added (params from `from` on) in the order behaviour.lookupOrder @@ -1442,9 +1432,9 @@ function sortLinks(links, kind, codeOf) { return links.sort(cmp); } -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; +/** the property definitions a file reports (data built at load; none where behaviour.declaresProperties is false) */ +function propertyDefinitionsFor(store) { + if (!store.behaviour.declaresProperties) return null; const std = { parent: 'http://hl7.org/fhir/concept-properties#parent', child: 'http://hl7.org/fhir/concept-properties#child', inactive: 'http://hl7.org/fhir/concept-properties#inactive', status: 'http://hl7.org/fhir/concept-properties#status' }; const defs = []; @@ -1500,6 +1490,13 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { // the text search the file names (behaviour.textSearch; text-index.js TEXT_SEARCHES), or the // generic one (null) this.searchMode = textSearchMode(this.store.behaviour.textSearch, this.file); + // the implicit value sets' URL grammar (behaviour.implicitValueSets): loinc here, snomed in the + // SNOMED CT provider; another name refuses the file + const ivs = this.store.behaviour.implicitValueSets; + if (ivs != null && !(ivs === 'loinc' || (ivs === 'snomed' && this.constructor.grammar === 'snomed'))) { + this.store.close(); + throw new Error(`${this.file}: its implicit value sets are ${ivs} (behaviour.implicitValueSets), which this server does not implement`); + } // behaviour.expansionOrder: concept ids, or the stored order (ix_order) const kind = this.store.behaviour.expansionOrder; const order = kind !== 'ids' ? this._systemOrder(kind) : null; @@ -1507,7 +1504,7 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { // SNOMED CT text search ranks ties by the built-in concept order (text-index.js) if (order) this.store.ordinal = (id) => order.rank[id]; this.layers = new SupplementLayers(this.store); - this.propDefs = propertyDefinitionsFor(this.store, this.dialect); + this.propDefs = propertyDefinitionsFor(this.store); // data, not cache: read once when the file loads this._langs = this.store.languages(); } @@ -1613,9 +1610,10 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { return new SqliteV2Provider(opContext, supplements, this); } + /** the file's implicit value sets, by the URL grammar it names (behaviour.implicitValueSets) */ async buildKnownValueSet(url, version) { if (version && version !== this.version()) return null; - if (this.store.system === LOINC) return this._loincKnownValueSet(url); + if (this.store.behaviour.implicitValueSets === 'loinc') return this._loincKnownValueSet(url); return null; } diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 366dfc6c1..6579d01b1 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -738,6 +738,8 @@ class SnomedV2Factory extends SqliteV2Factory { } async buildKnownValueSet(url, version) { + // the snomed URL grammar for implicit value sets (behaviour.implicitValueSets) + if (this.store.behaviour.implicitValueSets !== 'snomed') return null; if (!url.startsWith('http://snomed.info/')) return null; if (version != null && !this.version().startsWith(version)) return null; const form = this.implicitValueSetForm(url); From 3b66c7f812bdb88318e2d0c7784b41f3d41deb89 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 23:13:22 -0600 Subject: [PATCH 39/90] sqlite-v2: property filter and presentation facts; LOINC catalog rows New catalog columns: selects_members, name_any_case, value_any_case, default_value, match_display, value_system, presentation (a file without them is refused). The reader: - resolves a filter's property name by code, in any case where name_any_case says so (the RxNorm TTY/STY/SAB rule goes), or by an also_asked_as name (LOINC Answer as answer-list: its rule goes); - applies default_value to = filters (LOINC STATUS NotStated: its rule goes) and match_display to link filter values (LOINC part names: the dialect hook goes); - finds identifier schemes coded in another system by value_system (the SNOMED CT scheme table goes); - forms values in the generic $lookup by presentation. The LOINC importer writes a row for every relationship type cs-loinc.js knows (the reader's list of unused types goes) and a copyright literal (LOINC / 3rdParty, never reported; the copyright rule goes). Importers write the columns as the format document lists them. Answers on the test fixtures are unchanged. Co-Authored-By: Claude --- tests/tx/sqlite-v2-engine.test.js | 2 +- tests/tx/sqlite-v2-format-round2.test.js | 51 ++++++++++++++++++++++++ tx/importers/import-loinc-v2.module.js | 31 +++++++++++--- tx/importers/import-rxnorm-v2.module.js | 4 +- tx/importers/sct-v2-common.js | 15 +++++-- tx/importers/sqlite-v2/builder.js | 9 +++-- tx/importers/sqlite-v2/schema.sql | 7 ++++ tx/sqlite-v2/README.md | 20 ++++++++++ tx/sqlite-v2/dialects.js | 45 +++++---------------- tx/sqlite-v2/engine/compile.js | 19 +++++---- tx/sqlite-v2/provider.js | 20 +++++++++- tx/sqlite-v2/snomed.js | 21 ++++++---- tx/sqlite-v2/store.js | 27 ++++++++++++- 13 files changed, 204 insertions(+), 67 deletions(-) diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index b6d92b1b3..95b48d9c1 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -387,7 +387,7 @@ describe('sqlite-v2 SNOMED concept in / code in', () => { 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), filterProp: (code) => store.props.get(code), resolveFilterName: (n) => n, propValues: store.propValues.bind(store), props: store.props, resolveCodes: store.resolveCodes.bind(store), idOf: store.idOf.bind(store), hierarchy: store.hierarchy, system: store.system }, dialect: {} }; const c = new C(fake); const n = c.filter('colour', '=', 'clinical CLASS'); expect(new Engine(store).evaluate(n).size).toBe(2); // 'red' (F) and 'Red' (G): literal values match without case, as upstream diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index c588d9b24..f65f64cee 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1289,3 +1289,54 @@ describe('R3-9. deprecatedStatus, declaresProperties, implicitValueSets; the sys expect(() => b.finish()).toThrow(/contract: behaviour.expansionOrder "stored" without ix_order rank and ids/); }); }); + +describe('R3-10. property filter and presentation facts', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + let op; + beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); + const file = () => fixture((b, c) => { + const tty = b.property({ code: 'TTY', shape: 'literal', fhirType: 'code', nameAnyCase: true }); + const st = b.property({ code: 'state', shape: 'literal', fhirType: 'string', defaultValue: 'none' }); + const site = b.property({ code: 'site', shape: 'link', matchDisplay: true, alsoAskedAs: ['place'], presentation: { value: 'display', parts: ['partCode'] } }); + const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'string', presentation: { value: 'string', parts: ['code-display'] }, display: 'Kind' }); + b.literal(c.A, tty, 'SCD'); + b.literal(c.B, st, 'done'); + b.link(c.A, site, c.C); + b.literal(c.A, kind, 'k1'); + }); + test('name_any_case and also_asked_as name a property; default_value; match_display', async () => { + const f = new SqliteV2Factory(op.i18n, file()); + await f.load(); + try { + const c = new Compiler({ store: f.store, dialect: {} }); + const codes = (n) => f.engine.evaluate(n).toArray().map((id) => f.store.conceptRows([id]).get(id).code).sort(); + expect(codes(c.filter('tty', '=', 'SCD'))).toEqual(['A']); + expect(codes(c.filter('place', '=', 'C'))).toEqual(['A']); + expect(codes(c.filter('site', '=', 'display C'))).toEqual(['A']); + expect(codes(c.filter('state', '=', 'none'))).toEqual(['A', 'C', 'X', 'root']); + expect(codes(c.filter('state', '=', 'done'))).toEqual(['B']); + const p = await f.build(op, []); + const params = []; + await p.extendLookup((await p.locate('A')).context, ['site', 'kind'], params); + expect(params.map((x) => x.part)).toEqual([ + [{ name: 'code', valueCode: 'site' }, { name: 'value', valueString: 'display C' }, { name: 'partCode', valueCode: 'C' }], + [{ name: 'code', valueCode: 'kind' }, { name: 'value', valueString: 'k1' }, { name: 'code-display', valueString: 'Kind' }]]); + } finally { f.store.close(); } + }); + test('a malformed presentation, or a catalog without the columns, is refused', () => { + const f = file(); + const bad = withMeta(f, {}); + const w = new Database(bad); + w.exec(`UPDATE property SET presentation = '{"value": "upper"}' WHERE code = 'kind'`); + w.close(); + expect(() => openStore(bad)).toThrow(/property kind has presentation/); + const old = withMeta(f, {}); + const w2 = new Database(old); + w2.exec('ALTER TABLE property DROP COLUMN presentation'); + w2.close(); + expect(() => openStore(old)).toThrow(/built before the catalog columns presentation existed/); + }); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 337f278c1..014d03307 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -154,18 +154,33 @@ const CLASSTYPE = { 1: 'Laboratory class', 2: 'Clinical class', 3: 'Claims attac * hierarchy's descendants come from (closure_from); the CLASSTYPE value labels. */ function loincCatalog(b) { - const link = (code, extra = {}) => b.property({ code, uri: `${PROP}/${code}`, shape: 'link', display: code, ...extra }); + // every link: a filter value may be the target's code or its display (cs-loinc.js matches + // relationships by Codes.Description), reported with the target's display as its description + const link = (code, extra = {}) => b.property({ code, uri: `${PROP}/${code}`, shape: 'link', display: code, matchDisplay: true, + 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)])); // 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, ...(c === 'STATUS' ? { role: 'status' } : {}) })])); - const answer = link('Answer', { ordered: true }); - const answersFor = link('answers-for'); - b.property({ code: 'child', uri: `${PROP}/child`, shape: 'link', display: 'child', inverseOf: parent }); + // the literals: values in any case; STATUS NotStated where a concept has none + const lit = Object.fromEntries(LITERALS.map(([c]) => [c, b.property({ code: c, uri: `${PROP}/${c}`, shape: 'literal', fhirType: 'string', display: c, + valueAnyCase: true, presentation: c === 'CLASSTYPE' ? { value: 'string', parts: ['description'] } : { value: 'string' }, + ...(c === 'STATUS' ? { role: 'status', defaultValue: 'NotStated' } : {}) })])); + // Answer is also asked for as answer-list; answers-for selects the members of the lists + const answer = link('Answer', { ordered: true, alsoAskedAs: ['answer-list'] }); + const answersFor = link('answers-for', { selectsMembers: true }); + // 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', + filterOps: ['='], report: 'never' }); + b.deriveFacts((db) => db.prepare(`INSERT INTO literal 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.property({ code: 'child', uri: `${PROP}/child`, shape: 'link', display: 'child', inverseOf: parent, matchDisplay: true, presentation: { parts: ['description'] } }); const listLinks = b.property({ code: 'Answer|answers-for', shape: 'union', display: 'Answer and answers-for', filterable: false }); b.propertyMember(listLinks, answer); b.propertyMember(listLinks, answersFor); - b.property({ code: 'AnswerList', uri: `${PROP}/AnswerList`, shape: 'link', display: 'AnswerList', inverseOf: listLinks }); + b.property({ code: 'AnswerList', uri: `${PROP}/AnswerList`, shape: 'link', display: 'AnswerList', inverseOf: listLinks, matchDisplay: true, presentation: { parts: ['description'] } }); const ancestor = b.property({ code: 'ancestor', uri: `${PROP}/ancestor`, shape: 'link', display: 'ancestor (PATH_TO_ROOT)' }); b.setClosureFrom(parent, ancestor); for (const [v, d] of Object.entries(CLASSTYPE)) b.valueLabel(lit.CLASSTYPE, String(v), d); @@ -183,6 +198,10 @@ function loincItemRank(useCode, language) { 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'], diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index f5caa6f53..1b3ba72e0 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -90,7 +90,9 @@ async function importRxNormV2(cfg) { // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships const EQ_IN = ['=', 'in']; - const lit = (code, display, extra = {}) => b.property({ code, uri: `${RXNORM}/${code}`, shape: 'literal', fhirType: 'code', display, filterOps: EQ_IN, ...extra }); + // (named in any case and matched in any case, as cs-rxnorm.js) + const lit = (code, display, extra = {}) => b.property({ code, uri: `${RXNORM}/${code}`, shape: 'literal', fhirType: 'code', display, filterOps: EQ_IN, + nameAnyCase: true, valueAnyCase: true, ...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; $lookup never reports // it (report 'never': cs-rxnorm.js has no such property) diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 16c2e98c1..0a2bf6491 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -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 -> {system, name it is reported as} */ +const SCHEME_SYSTEMS = { '30051010000102': { system: 'http://loinc.org', name: 'loinc' } }; const SYNONYM = '900000000000013009'; const DEFINITION = '900000000000550004'; const PREFERRED = '900000000000548007'; @@ -261,7 +263,8 @@ class SnomedSink { // as ECL's concept filters ({{ C moduleId = ... }}) and the FHIR filter moduleId name them // how $lookup reports them (SNOMED CT on FHIR): is-a as parent; moduleId also asked for as module; // the definition status as the boolean sufficientlyDefined (true for fully defined), only when asked for - this.isA = b.property({ code: IS_A, uri: `${SCT}/${IS_A}`, shape: 'link', subsumption: true, refinable: true, wildcard: false, reportedAs: 'parent' }); + this.isA = b.property({ code: IS_A, uri: `${SCT}/${IS_A}`, shape: 'link', subsumption: true, refinable: true, wildcard: false, reportedAs: 'parent', + presentation: { parts: ['description'] } }); this.module = b.property({ code: 'moduleId', shape: 'link', display: 'Module', refinable: false, wildcard: false, alsoAskedAs: ['module'] }); this.defStatus = b.property({ code: 'definitionStatusId', shape: 'link', display: 'Definition status', refinable: false, wildcard: false, reportedAs: 'sufficientlyDefined', trueValue: '900000000000073002', report: 'named' }); @@ -343,7 +346,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 */ @@ -362,7 +365,8 @@ class SnomedSink { const both = this.deferredTypes.has(type); // an attribute with relationship rows and concrete values: its links are read only where it is // named (cs-snomed.js keeps one value kind per attribute: $lookup reads its concrete values) - return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: both ? 'both' : 'literal', fhirType, refinable: true, wildcard: true, namedLinks: both }); + return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: both ? 'both' : 'literal', fhirType, refinable: true, wildcard: true, namedLinks: both, + valueAnyCase: true, presentation: { parts: ['code-display'] } }); } /** an active inferred concrete value row; s: concept handle; raw: the RF2 value (#n, "s", true) */ @@ -412,7 +416,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 + 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.system, reportedAs: valueOf.name } : {}) }); this.schemes.set(schemeCode, p); } this.b.identifier(p, value, c); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 04ddb1a5c..54a559433 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -208,6 +208,9 @@ class TerminologyBuilder { ordered: spec.ordered ? 1 : 0, namedLinks: spec.namedLinks ? 1 : 0, filterOps: spec.filterOps ? JSON.stringify(spec.filterOps) : null, report: spec.report ?? null, fields: spec.fields ? JSON.stringify(spec.fields) : null, + selectsMembers: spec.selectsMembers ? 1 : null, nameAnyCase: spec.nameAnyCase ? 1 : null, valueAnyCase: spec.valueAnyCase ? 1 : null, + defaultValue: spec.defaultValue ?? null, matchDisplay: spec.matchDisplay ? 1 : null, valueSystem: spec.valueSystem ?? null, + presentation: spec.presentation ? JSON.stringify(spec.presentation) : null, reportedAs: spec.reportedAs ?? null, alsoAskedAs: spec.alsoAskedAs && spec.alsoAskedAs.length ? JSON.stringify(spec.alsoAskedAs) : null, trueValue: spec.trueValue == null ? null : String(spec.trueValue), // record shape: positions in record.fields (the non-target columns) that hold node handles @@ -514,8 +517,8 @@ class TerminologyBuilder { 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, subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, named_links, filter_ops, report, reported_as, - also_asked_as, true_value, fields) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + also_asked_as, true_value, selects_members, name_any_case, value_any_case, default_value, match_display, value_system, presentation, fields) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); const parents = new Set(this.members.map(([a]) => a)); for (const p of this.properties) { // subject_kind NULL for a catalog row with no rows @@ -531,7 +534,7 @@ class TerminologyBuilder { : ((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, p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.namedLinks, p.filterOps, p.report, p.reportedAs, - p.alsoAskedAs, p.trueValue, p.fields); + p.alsoAskedAs, p.trueValue, p.selectsMembers, p.nameAnyCase, p.valueAnyCase, p.defaultValue, p.matchDisplay, p.valueSystem, p.presentation, p.fields); } const insMember = db.prepare('INSERT OR IGNORE INTO property_member VALUES (?, ?)'); for (const [a, b] of this.members) insMember.run(a, b); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 7dc68a69d..07cafc1af 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -101,6 +101,13 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat -- under reported_as or code); NULL: none 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 + selects_members INTEGER, -- = / in on it select the members of the lists it links to (in: the union of =) + name_any_case INTEGER, -- a filter may name it in any case + value_any_case INTEGER, -- filter values match its stored values in any case + default_value TEXT, -- the value of a concept with no row of it (a filter = on it selects those too) + match_display INTEGER, -- a link filter value may be the target's display (case-folded) + value_system TEXT, -- an identifier property's values are codes of this system + presentation TEXT, -- JSON {value?: code|string|display|coding, parts?: [description|code-display|partCode]} 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` diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index c6c74a340..e19abb286 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -280,6 +280,26 @@ regular expression `/\(([^()]+)\)\s*$/` on 3 concepts per edition (nested bracke editions (nested brackets and trailing spaces), as counted by the other implementation; for those concepts `$lookup`'s `semanticTag` changes (to the stored value). +Filter and presentation facts (nullable columns; NULL or 0: absent): + +| column | meaning | written by | +|---|---|---| +| `selects_members` | `=` / `in` on it select the members of the lists it links to (`in`: the union of `=`) | LOINC `answers-for` | +| `name_any_case` | a filter may name the property in any case | RxNorm `TTY`, `SAB`, `STY` | +| `value_any_case` | filter values match its stored values in any case | LOINC, RxNorm, SNOMED CT literals | +| `default_value` | the value of a concept with no row of it (a filter `=` on it selects those too) | LOINC `STATUS` `NotStated` | +| `match_display` | a link filter value may be the target's display (case-folded) | LOINC links | +| `value_system` | an identifier property's values are codes of this system | SNOMED CT scheme 30051010000102 `http://loinc.org` (reported as `loinc`) | +| `presentation` | JSON `{"value"?: "code"\|"string"\|"display"\|"coding", "parts"?: ["description"\|"code-display"\|"partCode"]}`: how a value is reported | SNOMED CT links `{"parts": ["description", "code-display"]}` (is-a `["description"]`), concrete literals `{"parts": ["code-display"]}`; LOINC `CLASS` `{"value": "display", "parts": ["partCode"]}`, literals `{"value": "string"}`, `CLASSTYPE` `{"value": "string", "parts": ["description"]}`, relationships `{"parts": ["description"]}` | + +A filter names a property by its code, by its code in any case (`name_any_case`), or by a name in +`also_asked_as` (LOINC `Answer` as `answer-list`). LOINC files have a catalog row for every +relationship type cs-loinc.js knows (a type without rows selects nothing) and a literal `copyright` +(`LOINC` or `3rdParty`, `report = 'never'`). The JS reader applies `presentation` in the generic +`$lookup`; its SNOMED CT and LOINC `$lookup` adapters still form those values in code. It matches +literal values without case for every property (`value_any_case` is written but changes nothing in +the JS reader), and its LOINC filter grammar still selects answer-list members (`selects_members`). + `property.role = 'status'`: the literal that holds the concept's status (at most one per system): every row reads it (the provider's `getStatus()`), and `$lookup` lists it by default under its name. LOINC files: `STATUS`. diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js index 4cf8a576b..a9d890df0 100644 --- a/tx/sqlite-v2/dialects.js +++ b/tx/sqlite-v2/dialects.js @@ -32,8 +32,6 @@ const LOINC_RELATIONSHIPS = new Set(['N/A', 'adjustment', 'challenge', 'CLASS', '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', @@ -60,10 +58,6 @@ const 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); - }, filter(c, prop, op, value) { const S = c.store; if (!loincKnows(c, prop, op, value)) throw loinc.notSupported(prop, op, value); @@ -75,15 +69,8 @@ const loinc = { 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)] }; - } + // (relationship types without rows, STATUS NotStated, copyright and answer-list: catalog facts, + // compile.js: property rows without rows, default_value, a stored literal, also_asked_as) 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 } }; @@ -127,20 +114,6 @@ const loinc = { // 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 @@ -182,23 +155,23 @@ const rxnorm = { */ filter(c, prop, op, value) { const S = c.store; - const up = String(prop).toUpperCase(); + // the catalog name the filter means (name_any_case: TTY, STY, SAB in any case) + const name = S.resolveFilterName(prop); 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); + // the operators the catalog row takes (filter_ops); concept / code and the rest: = and in + const row = S.catalog.get(name); 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 + if (row && row.shape === 'literal' && row.filterable) { + // a literal (TTY, STY, SAB): the generic rule matches it const v = op === '=' ? vals[0] : value; - if (prop !== up || !S.props.has(up) || v !== value) return c.filter(up, op, v); + if (prop !== name || v !== value) return c.filter(name, op, v); return null; } if (prop === 'concept' || prop === 'code') return null; // the generic rule: the codes listed diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index d5f562b2b..91e5b1a2c 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -60,11 +60,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 property says so (match_display) */ + valueIds(v, p = null) { const id = this.id(v); if (id != null) return [id]; - return this.dialect.valuesByName ? this.dialect.valuesByName(this, v) : []; + return p && p.matchDisplay ? this.store.displayIdsNoCase(v) : []; } // ---- compose ------------------------------------------------------------------------------- @@ -219,8 +219,9 @@ class Compiler { if (prop === 'concept' || prop === 'code' || (this.store.hierarchy && prop === this.store.hierarchy.code && op !== '=' && op !== 'in' && op !== 'exists')) { return this.conceptFilter(op, value, prop); } - // the property's catalog entry is its access path (store filterProp) - const p = this.store.filterProp(prop); + // the property's catalog entry is its access path (store filterProp), by its name in any case + // or another name it is asked for by, where the catalog says so + const p = this.store.filterProp(this.store.resolveFilterName(prop)); if (!p) { const n = this.term.layers ? this.term.layers.filterNode(this, prop, op, value) : null; if (n) return n; @@ -301,7 +302,7 @@ 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, p)))); } 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))) { @@ -309,6 +310,10 @@ class Compiler { 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)); + // property.default_value: a concept with no row of the property has that value + if (p.defaultValue != null && vals.includes(p.defaultValue)) { + 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; } @@ -378,7 +383,7 @@ 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, p))) }); return op === 'not-in' ? { t: 'minus', a: { t: 'all' }, b: node } : node; } case 'exists': { diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index d804692b0..54104e420 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -156,8 +156,26 @@ class SqliteV2Provider extends BaseCSServices { return props.some((p) => p === '*' || names.includes(String(p).toLowerCase())); } - /** a property's value as reported: a boolean where the catalog says (true_value), else the value */ + /** + * 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 (none: a code with its description, or + * a string) + */ _addReported(params, d, value, display) { + const pr = d.presentation; + if (pr && d.trueValue == null) { + const form = pr.value || ((d.kind === 'concept' || d.shape === 'link' || d.shape === 'both') ? 'code' : 'string'); + const v = form === 'display' ? { valueString: display || String(value) } : form === 'string' ? { valueString: String(value) } + : form === 'coding' ? { valueCoding: { system: this.system(), code: String(value), ...(display ? { display } : {}) } } : { valueCode: String(value) }; + const parts = [{ name: 'code', valueCode: this._reportedName(d) }, { name: 'value', ...v }]; + for (const p of pr.parts || []) { + if (p === 'description' && display) parts.push({ name: 'description', valueString: display }); + else if (p === 'code-display') parts.push({ name: 'code-display', valueString: d.display || d.code }); + else if (p === 'partCode') parts.push({ name: 'partCode', valueCode: String(value) }); + } + params.push({ name: 'property', part: parts }); + return; + } if (d.trueValue != null) { params.push({ name: 'property', part: [{ name: 'code', valueCode: this._reportedName(d) }, { name: 'value', valueBoolean: String(value) === d.trueValue }] }); } else if (d.kind === 'concept' || d.shape === 'link' || d.shape === 'both') { diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 6579d01b1..1c77ef887 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -23,7 +23,14 @@ const ASSOCIATIONS = { '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.reportedAs || d.code } : 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 @@ -336,7 +343,7 @@ class SnomedV2Provider extends SqliteV2Provider { } const ids = S.alternateIdsOf(c.id); for (const r of ids) { - const scheme = IDENTIFIER_SCHEMES[r.scheme]; + const scheme = schemeOf(this.store, 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 } }] }); } @@ -469,14 +476,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; @@ -853,9 +860,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({ @@ -877,7 +884,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); } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 20caf94a4..763540532 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -88,6 +88,13 @@ function readBehaviour(meta, file) { const FILTER_OPS = new Set(FILTER_OPERATORS); const REPORT = new Set([null, 'named', 'always', 'never']); +/** property.presentation: {value?: code|string|display|coding, parts?: [description|code-display|partCode]} */ +function isPresentation(v) { + 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) => ['description', 'code-display', 'partCode'].includes(x)))); +} + const NODE_SHAPES = new Set(['link', 'union']); const FILTER_SHAPES = new Set(['link', 'literal', 'both', 'union']); const VK = { none: 0, node: 1, literal: 2 }; @@ -407,7 +414,8 @@ class Store { // the catalog columns readers rely on (a file built before them is refused: no reader keeps a rule // for a property that does not say how it is reported) const cols = new Set(this.db.prepare('PRAGMA main.table_info(property)').all().map((c) => c.name)); - const missing = ['reported_as', 'also_asked_as', 'true_value', 'named_links'].filter((c) => !cols.has(c)); + const missing = ['reported_as', 'also_asked_as', 'true_value', 'named_links', 'selects_members', 'name_any_case', 'value_any_case', + 'default_value', 'match_display', 'value_system', 'presentation'].filter((c) => !cols.has(c)); if (missing.length) throw new Error(`${this.file} was built before the catalog columns ${missing.join(', ')} existed: rebuild it with the importers, or upgrade it`); 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) @@ -429,6 +437,9 @@ class Store { // the name it is reported and asked for under, further names it is asked for by, and the // value it is true for where it is reported as a boolean (absent columns: none) reportedAs: r.reported_as ?? null, alsoAskedAs: r.also_asked_as ? JSON.parse(r.also_asked_as) : [], trueValue: r.true_value ?? null, + // filter facts (README.md "Per property") + selectsMembers: !!r.selects_members, nameAnyCase: !!r.name_any_case, valueAnyCase: !!r.value_any_case, defaultValue: r.default_value ?? null, + matchDisplay: !!r.match_display, valueSystem: r.value_system ?? null, presentation: r.presentation ? JSON.parse(r.presentation) : 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`); @@ -436,6 +447,7 @@ class Store { if (!(Array.isArray(def.alsoAskedAs) && def.alsoAskedAs.every((x) => typeof x === 'string' && x))) { throw new Error(`${this.file}: property ${def.code} has also_asked_as ${r.also_asked_as}, not a list of names`); } + if (def.presentation !== null && !isPresentation(def.presentation)) throw new Error(`${this.file}: property ${def.code} has presentation ${r.presentation}`); if (!REPORT.has(def.report)) throw new Error(`${this.file}: property ${def.code} has report ${def.report} (named, always, never or NULL)`); this.catalog.set(def.code, def); this.propsById.set(def.id, def); @@ -491,6 +503,19 @@ class Store { /** the inverse rows: [{code, reverses (the stored properties reversed)}] */ inverses() { return [...this.catalog.values()].filter((d) => d.reverses); } + /** + * The catalog code a filter's property name means: the code itself, else a property that may be + * named in any case (name_any_case), else one asked for by that name (also_asked_as) + */ + resolveFilterName(name) { + const n = String(name); + if (this.catalog.has(n)) return n; + const low = n.toLowerCase(); + for (const d of this.catalog.values()) if (d.nameAnyCase && d.code.toLowerCase() === low) return d.code; + for (const d of this.catalog.values()) if (d.alsoAskedAs.includes(n)) return d.code; + return n; + } + /** the catalog row a FHIR filter may name (filterable, statement-valued), or undefined */ filterProp(code) { const d = this.catalog.get(code); From aa2ae519688d5f33af3928998f15674932a003a1 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 23:18:41 -0600 Subject: [PATCH 40/90] sqlite-v2: listed filters over stored properties; concept in a relation; no hierarchy behaviour.filters entries may name the stored literal property a filter reads and where conditions that must also hold. concept in X selects the members of the record relation X defines for every file (the SNOMED CT dialect hook goes). A file with no hierarchy property answers $subsumes not-subsumed and has no ancestors (the RxNorm checks go). Answers on the test fixtures are unchanged. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 43 ++++++++++++++++++++++++ tx/sqlite-v2/README.md | 6 +++- tx/sqlite-v2/dialects.js | 16 --------- tx/sqlite-v2/engine/compile.js | 41 ++++++++++++++++++++-- tx/sqlite-v2/meta.js | 6 ++-- tx/sqlite-v2/provider.js | 5 +-- 6 files changed, 94 insertions(+), 23 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index f65f64cee..7941305f6 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1340,3 +1340,46 @@ describe('R3-10. property filter and presentation facts', () => { expect(() => openStore(old)).toThrow(/built before the catalog columns presentation existed/); }); }); + +describe('R3-11. listed filters over a stored property; concept in a relation; no hierarchy', () => { + const { OperationContext } = require('../../tx/operation-context'); + const { TestUtilities } = require('../test-utilities'); + const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); + const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); + test('behaviour.filters property and where; concept in X: the members of the relation X defines', () => { + const file = fixture((b, c) => { + const std = b.property({ code: 'standard', shape: 'literal', fhirType: 'code' }); + b.literal(c.A, std, 'S'); + b.literal(c.B, std, 'S'); + const set = b.property({ code: 'C', shape: 'record', concept: c.C, fields: [] }); + b.record(set, c.A, { fields: [] }); + b.record(set, c.X, { fields: [] }); + b.setBehaviour('filters', [{ code: 'tint', operator: ['=', 'in'], property: 'colour', where: { standard: 'S' } }, { code: 'concept', operator: ['in'] }]); + }); + withStore(file, (S) => { + const c = new Compiler({ store: S, dialect: {} }); + const { Engine } = require('../../tx/sqlite-v2/engine/engine'); + const codes = (n) => new Engine(S).evaluate(n).toArray().map((id) => S.conceptRows([id]).get(id).code).sort(); + expect(codes(c.filter('tint', '=', 'red'))).toEqual(['A']); + expect(codes(c.filter('tint', 'in', 'red,blue'))).toEqual(['A', 'B']); + expect(codes(c.filter('concept', 'in', 'C,B'))).toEqual(['A', 'B', 'X']); + }); + }); + test('a file with no hierarchy property: not-subsumed, even for the same code; no ancestors', async () => { + const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); + 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 f = new SqliteV2Factory(op.i18n, dest); + await f.load(); + try { + const p = await f.build(op, []); + expect(await p.subsumesTest('a', 'a')).toBe('not-subsumed'); + expect(await p.subsumesTest('a', 'b')).toBe('not-subsumed'); + expect([...(await p.ancestorsOf('a'))]).toEqual([]); + } finally { f.store.close(); } + }); +}); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index e19abb286..078028900 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -219,7 +219,7 @@ refused (the builders check the same at build). | `implicitValueSets` | a URL-grammar name, `null` | `null` (none) | the implicit value sets, by a named URL grammar (like `grammar`); a name the reader does not implement refuses the file. SNOMED CT `snomed` (`?fhir_vs=...`), LOINC `loinc` (`/vs`, `/vs/LP...`, `/vs/LL...`), OMOP `omop` (not in the JS reader) | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | | `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | -| `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one | +| `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one. An entry may also name `property` (the stored literal property the filter reads: `=` / `in` select the concepts whose value is the filter value) and `where` (`{property code: value}` that must also hold) | 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 @@ -292,6 +292,10 @@ Filter and presentation facts (nullable columns; NULL or 0: absent): | `value_system` | an identifier property's values are codes of this system | SNOMED CT scheme 30051010000102 `http://loinc.org` (reported as `loinc`) | | `presentation` | JSON `{"value"?: "code"\|"string"\|"display"\|"coding", "parts"?: ["description"\|"code-display"\|"partCode"]}`: how a value is reported | SNOMED CT links `{"parts": ["description", "code-display"]}` (is-a `["description"]`), concrete literals `{"parts": ["code-display"]}`; LOINC `CLASS` `{"value": "display", "parts": ["partCode"]}`, literals `{"value": "string"}`, `CLASSTYPE` `{"value": "string", "parts": ["description"]}`, relationships `{"parts": ["description"]}` | +`concept in X, Y`: a concept that defines a record relation with members (a reference set) +contributes its members, any other concept itself. A file with no hierarchy property answers +`$subsumes` not-subsumed (the same code too) and has no ancestors (`$closure`). + A filter names a property by its code, by its code in any case (`name_any_case`), or by a name in `also_asked_as` (LOINC `Answer` as `answer-list`). LOINC files have a catalog row for every relationship type cs-loinc.js knows (a type without rows selects nothing) and a literal `copyright` diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js index a9d890df0..97882dc17 100644 --- a/tx/sqlite-v2/dialects.js +++ b/tx/sqlite-v2/dialects.js @@ -227,22 +227,6 @@ const snomed = { 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 diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 91e5b1a2c..3cb70cb01 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -180,7 +180,23 @@ class Compiler { } } - /** meta behaviour.filters: [{code, operator: [...], values?: [...]}] or null (every filter the catalog allows) */ + /** + * A listed filter over a stored literal property: = (or in) selects the concepts whose value of + * `property` is the filter value, and every `where` property: value also holds + */ + listedFilter(f, op, value) { + const lit = (code, v) => { + const p = this.store.catalog.get(code); + if (!p) throw new FilterError(`The filter "${f.code}" reads the property ${code}, which the catalog does not have`); + return this.propertyFilter(p, '=', v); + }; + const vals = op === 'in' ? splitList(value) : [String(value)]; + const sel = vals.length === 1 ? lit(f.property, vals[0]) : { t: 'or', items: vals.map((v) => lit(f.property, v)) }; + const where = Object.entries(f.where || {}).map(([k, v]) => lit(k, v)); + return where.length ? { t: 'and', items: [sel, ...where] } : sel; + } + + /** meta behaviour.filters: [{code, operator: [...], values?: [...], property?, where?}] or null (every filter the catalog allows) */ checkListedFilter(prop, op, value) { const listed = this.store.behaviour.filters; if (!listed) return; @@ -192,6 +208,9 @@ class Compiler { } _filter(prop, op, value) { + // a listed filter that reads a stored literal property (behaviour.filters property / where) + const listed = this.store.behaviour.filters ? this.store.behaviour.filters.find((x) => x.code === prop && x.property) : null; + if (listed) return this.listedFilter(listed, op, value); if (this.dialect.filter) { const n = this.dialect.filter(this, prop, op, value); if (n) return n; @@ -250,6 +269,24 @@ class Compiler { 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 with members (catalog relations: a + * reference set) contributes its members, any other concept itself + */ + conceptIn(ids) { + const S = this.store; + const rel = ids.filter((id) => S.relations && S.relations.has(id)); + const sets = rel.length ? S.loadSets(KIND.refset, 0, rel, this.stats) : new Map(); + 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] : items.length ? { t: 'or', items } : { t: 'ids', ids: [] }; + } + conceptFilter(op, value, prop = 'concept') { const S = this.store; if (op === 'in' || op === 'not-in') { @@ -259,7 +296,7 @@ class Compiler { // 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 }; + const n = this.conceptIn(ids); return op === 'in' ? n : { t: 'minus', a: { t: 'all' }, b: n }; } if (op === 'regex') return { t: 'text', field: 'code', re: value }; diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index bcf8e75b6..2a79cdb36 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -33,9 +33,11 @@ const isCount = (v) => Number.isSafeInteger(v) && v >= 0; const DECIMAL = /^(0|[1-9][0-9]*)$/; /** one entry of behaviour.filters: {code, operator: [FHIR filter operators, at least one], values?: [strings]} */ -const isFilterSpec = (f) => isPlainObject(f) && onlyKeys(f, ['code', 'operator', 'values']) && isString(f.code) +const isFilterSpec = (f) => isPlainObject(f) && onlyKeys(f, ['code', 'operator', 'values', 'property', 'where']) && isString(f.code) && isStrings(f.operator) && f.operator.length > 0 && f.operator.every((o) => FILTER_OPERATORS.includes(o)) - && (f.values === undefined || isStrings(f.values)); + && (f.values === undefined || isStrings(f.values)) + && (f.property === undefined || (isString(f.property) && f.property !== '')) + && (f.where === undefined || (isPlainObject(f.where) && Object.values(f.where).every(isString))); /** * ix.ix_word.names: which names the word index holds, and so which names text search reads diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 54104e420..51fccd7c4 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -645,7 +645,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'; @@ -676,7 +677,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; From e77818d9466be1f6a50987a6d76496f03c23c73c Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 01:08:18 -0600 Subject: [PATCH 41/90] sqlite-v2: displayDesignation defaults to first As agreed for the format: the display listed as the first designation, an item equal to it not repeated, is what every system but SNOMED CT and LOINC gets. The SNOMED CT importer writes none; the generic test fixtures need no value (their expectations are unchanged). Co-Authored-By: Claude --- tests/tx/sqlite-v2-engine.test.js | 3 +-- tests/tx/sqlite-v2-format-round2.test.js | 9 ++++++--- tests/tx/sqlite-v2-mixed-providers.test.js | 3 +-- tx/importers/sct-v2-common.js | 2 ++ tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/meta.js | 2 +- 6 files changed, 12 insertions(+), 9 deletions(-) diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index 95b48d9c1..68ef7bb55 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -29,8 +29,7 @@ let rx; function buildFixture(dest) { const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); - // (the display listed as the first designation, inactive items with their status) - b.setBehaviour('displayDesignation', 'distinct'); + // (inactive items listed with their status) b.setBehaviour('inactiveDesignations', 'status'); const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); const colour = b.property({ code: 'colour', shape: 'literal', fhirType: 'string' }); diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 7941305f6..422f0357c 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1192,10 +1192,10 @@ describe('R3-8. answer facts as behaviour keys', () => { }; const codes = (f, node) => f.engine.evaluate(node).toArray().map((id) => f.store.conceptRows([id]).get(id).code).sort(); - test('defaults: no display designation, inactive items left out, generalizes keeps the concept, definitions reported, whole system listed', async () => { + test('defaults: the display first (an item equal to it not repeated), inactive items left out, generalizes keeps the concept, definitions reported, whole system listed', async () => { const file = base((b, c) => b.item(c.B, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'old banana', active: false })); await withF(file, async (f, p) => { - expect(await desigs(p, 'A')).toEqual(['apple tree', 'Apfelbaum', 'display A']); + expect(await desigs(p, 'A')).toEqual(['display A', 'apple tree', 'Apfelbaum']); expect(await desigs(p, 'B')).not.toContain('old banana'); expect(await p.definition((await p.locate('A')).context)).toBe('a text definition'); const c = new Compiler({ store: f.store, dialect: {} }); @@ -1214,9 +1214,12 @@ describe('R3-8. answer facts as behaviour keys', () => { await withF(withMeta(base(extra), { 'behaviour.displayDesignation': '"first"', 'behaviour.inactiveDesignations': '"plain"' }), async (f, p) => { expect(await desigs(p, 'A')).toEqual(['display A', 'apple tree', 'Apfelbaum']); }); - await withF(withMeta(base(), { 'behaviour.plainDesignationIsDisplay': 'true' }), async (f, p) => { + await withF(withMeta(base(), { 'behaviour.plainDesignationIsDisplay': 'true', 'behaviour.displayDesignation': '"none"' }), async (f, p) => { expect(await desigs(p, 'A')).toEqual(['apple tree', 'Apfelbaum']); }); + await withF(withMeta(base(), { 'behaviour.displayDesignation': '"none"' }), async (f, p) => { + expect(await desigs(p, 'A')).toEqual(['apple tree', 'Apfelbaum', 'display A']); + }); }); test('generalizesExcludesSelf, wholeActiveOnly, wholeSystem, lookupDefinition, displayRegex', async () => { diff --git a/tests/tx/sqlite-v2-mixed-providers.test.js b/tests/tx/sqlite-v2-mixed-providers.test.js index 519d3e0e6..6158f2123 100644 --- a/tests/tx/sqlite-v2-mixed-providers.test.js +++ b/tests/tx/sqlite-v2-mixed-providers.test.js @@ -33,8 +33,7 @@ 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 display listed as the first designation, inactive items with their status) - b.setBehaviour('displayDesignation', 'distinct'); + // (inactive items listed with their status) b.setBehaviour('inactiveDesignations', 'status'); const isa = b.property({ code: 'parent', shape: 'link', subsumption: true }); const c = {}; diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 0a2bf6491..1c192cea7 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -242,6 +242,8 @@ class SnomedSink { b.setBehaviour('inactiveDesignations', 'status'); b.setBehaviour('unknownCodeVersion', true); b.setBehaviour('displayLanguage', 'en-US'); + // the display is not listed again as a designation (the SNOMED CT provider lists its descriptions) + b.setBehaviour('displayDesignation', 'none'); b.setBehaviour('declaresProperties', false); b.setBehaviour('implicitValueSets', 'snomed'); // the description types by role (item_use.role) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 078028900..ce7755894 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -212,7 +212,7 @@ refused (the builders check the same at build). | `locateMessage` | a string with `{code}`, `null` | `null` | the provider's reason for a code it cannot locate. LOINC `"Not a valid code: {code}"` | | `versionFormat` | `"MMDDYYYY"`, `null` | `null` | versions are dates written MMDDYYYY (described as such; the JS reader's `describeVersion`). RxNorm `"MMDDYYYY"` | | `inactiveDesignations` | `"omit"`, `"status"`, `"plain"` | `"omit"` | inactive items as designations: left out; listed with status inactive; listed like active ones. SNOMED CT `"status"`, RxNorm `"plain"` | -| `displayDesignation` | `"none"`, `"first"`, `"distinct"` | `"none"` | the display listed as the first designation: `first` also drops the first designation whose text equals it, `distinct` keeps every designation. LOINC `"distinct"`, RxNorm `"first"` | +| `displayDesignation` | `"none"`, `"first"`, `"distinct"` | `"first"` | the display listed as the first designation: `first` (the default) also drops the first designation whose text equals it; `distinct` keeps every designation (equal texts too); `none` lists no display designation. SNOMED CT `"none"`, LOINC `"distinct"`, RxNorm `"first"` | | `displayLanguage` | a language tag, `null` | `null` (`code_system.default_language`) | the language of the stored display (the display designation's language). SNOMED CT, LOINC, RxNorm `"en-US"` | | `deprecatedStatus` | a list of status values | `[]` | the values of the status literal (`role = 'status'`) that mean deprecated. RxNorm `["archived"]` (RxNorm files store the status of an inactive concept: `obsolete`, still in RXNCONSO, or `archived`, RXNATOMARCHIVE only); LOINC `["DEPRECATED"]` | | `declaresProperties` | boolean | `true` | the server declares the file's properties (expansion property definitions). SNOMED CT, LOINC, RxNorm `false` | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 2a79cdb36..fb65140d7 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -120,7 +120,7 @@ const KEYS = Object.freeze({ 'behaviour.locateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), 'behaviour.versionFormat': json((v) => v === null || v === 'MMDDYYYY', null), 'behaviour.inactiveDesignations': json((v) => ['omit', 'status', 'plain'].includes(v), 'omit'), - 'behaviour.displayDesignation': json((v) => ['none', 'first', 'distinct'].includes(v), 'none'), + 'behaviour.displayDesignation': json((v) => ['none', 'first', 'distinct'].includes(v), 'first'), 'behaviour.deprecatedStatus': json(isStrings, []), 'behaviour.declaresProperties': json(isBool, true), 'behaviour.implicitValueSets': json((v) => v === null || (isString(v) && v !== ''), null), From efbee678a9d263455ac05e8e7083fed746ff5fa0 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 01:10:20 -0600 Subject: [PATCH 42/90] sqlite-v2: three unknown-code messages (locate, filter locate, filter check) locateMessage is the reason for a code the system does not have; filterLocateMessage for a code a value-set filter check cannot locate; filterCheckMessage for a found code a filter clause does not select. LOINC writes filterLocateMessage (its earlier answer, now under the key that means it). Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 5 ++++- tx/importers/import-loinc-v2.module.js | 2 +- tx/sqlite-v2/README.md | 4 +++- tx/sqlite-v2/meta.js | 2 ++ tx/sqlite-v2/provider.js | 13 +++++++++---- 5 files changed, 19 insertions(+), 7 deletions(-) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 422f0357c..6e5547737 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -1242,8 +1242,11 @@ describe('R3-8. answer facts as behaviour keys', () => { }); test('locateMessage, versionFormat; keepDuplicateDesignations refused; malformed values refused', async () => { - await withF(withMeta(base(), { 'behaviour.locateMessage': '"No code {code} here"', 'behaviour.versionFormat': '"MMDDYYYY"' }), async (f, p) => { + await withF(withMeta(base(), { 'behaviour.locateMessage': '"No code {code}"', 'behaviour.filterLocateMessage': '"No code {code} here"', + 'behaviour.filterCheckMessage': '"{code} is not selected"', 'behaviour.versionFormat': '"MMDDYYYY"' }), async (f, p) => { + expect((await p.locate('ZZ')).message).toBe('No code ZZ'); expect(await p._filterLocate(null, null, 'ZZ')).toBe('No code ZZ here'); + expect(await p._filterLocate(null, { ids: [] }, 'A')).toBe('A is not selected'); expect(f.describeVersion('03022026')).toBe(require('../../library/utils/utilities').formatDateMMDDYYYY('03022026')); }); expect(() => openStore(withMeta(base(), { 'behaviour.keepDuplicateDesignations': 'true' }))).toThrow(/keepDuplicateDesignations is set/); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 014d03307..1e87778b1 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -242,7 +242,7 @@ function loincCodeSystem(b, version, description) { // display's language en-US; a code it cannot locate: cs-loinc.js's message b.setBehaviour('displayDesignation', 'distinct'); b.setBehaviour('displayLanguage', 'en-US'); - b.setBehaviour('locateMessage', 'Not a valid code: {code}'); + b.setBehaviour('filterLocateMessage', 'Not a valid code: {code}'); b.setBehaviour('deprecatedStatus', ['DEPRECATED']); b.setBehaviour('declaresProperties', false); b.setBehaviour('implicitValueSets', 'loinc'); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index ce7755894..124fe94ba 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -209,7 +209,9 @@ refused (the builders check the same at build). | `plainDesignationIsDisplay` | boolean | `false` | a designation with no use whose text equals the display is the display (not listed again) | | `wholeSystem` | `"list"`, `"empty"`, `"refuse"` | `"list"` | what an include of the whole system does | | `unknownCodeVersion` | boolean | `false` | the unknown-code message names the version and edition (meta `edition`). SNOMED CT `true`. The JS server chooses that message in its shared worker code by the system URI, for every provider; the JS reader validates the key but cannot set the message | -| `locateMessage` | a string with `{code}`, `null` | `null` | the provider's reason for a code it cannot locate. LOINC `"Not a valid code: {code}"` | +| `locateMessage` | a string with `{code}`, `null` | `null` | the reason for a code the system does not have (`locate`). UNII | +| `filterLocateMessage` | a string with `{code}`, `null` | `null` | the reason for a code a value-set filter check cannot locate. LOINC `"Not a valid code: {code}"`, OMOP | +| `filterCheckMessage` | a string with `{code}`, `null` | `null` | the reason for a found code a filter clause does not select. OMOP | | `versionFormat` | `"MMDDYYYY"`, `null` | `null` | versions are dates written MMDDYYYY (described as such; the JS reader's `describeVersion`). RxNorm `"MMDDYYYY"` | | `inactiveDesignations` | `"omit"`, `"status"`, `"plain"` | `"omit"` | inactive items as designations: left out; listed with status inactive; listed like active ones. SNOMED CT `"status"`, RxNorm `"plain"` | | `displayDesignation` | `"none"`, `"first"`, `"distinct"` | `"first"` | the display listed as the first designation: `first` (the default) also drops the first designation whose text equals it; `distinct` keeps every designation (equal texts too); `none` lists no display designation. SNOMED CT `"none"`, LOINC `"distinct"`, RxNorm `"first"` | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index fb65140d7..35e5aee11 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -118,6 +118,8 @@ const KEYS = Object.freeze({ 'behaviour.wholeSystem': json((v) => ['list', 'empty', 'refuse'].includes(v), 'list'), 'behaviour.unknownCodeVersion': json(isBool, false), 'behaviour.locateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), + 'behaviour.filterLocateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), + 'behaviour.filterCheckMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), 'behaviour.versionFormat': json((v) => v === null || v === 'MMDDYYYY', null), 'behaviour.inactiveDesignations': json((v) => ['omit', 'status', 'plain'].includes(v), 'omit'), 'behaviour.displayDesignation': json((v) => ['none', 'first', 'distinct'].includes(v), 'first'), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 51fccd7c4..d48f95a37 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -379,7 +379,8 @@ class SqliteV2Provider extends BaseCSServices { this.byCode.set(n, c); } } - if (!c) return { context: null, message: undefined }; + // behaviour.locateMessage: the reason for a code the system does not have + if (!c) return { context: null, message: this.store.behaviour.locateMessage ? this.store.behaviour.locateMessage.split('{code}').join(String(code)) : undefined }; if (!c.row) this._loadRows([c], false); return { context: c, message: null }; } @@ -1239,9 +1240,13 @@ class SqliteV2Provider extends BaseCSServices { async _filterLocate(prep, set, code) { const r = await this.locate(code); - // behaviour.locateMessage: the provider's reason for a code it cannot locate - if (!r.context) return this.store.behaviour.locateMessage ? this.store.behaviour.locateMessage.split('{code}').join(code) : r.message; - return this._member(set, r.context.id) ? r.context : null; + const fill = (t) => t.split('{code}').join(code); + const b = this.store.behaviour; + // behaviour.filterLocateMessage: the reason for a code a value-set filter check cannot locate + if (!r.context) return b.filterLocateMessage ? fill(b.filterLocateMessage) : r.message; + if (this._member(set, r.context.id)) return r.context; + // behaviour.filterCheckMessage: the reason for a found code the clause does not select + return b.filterCheckMessage ? fill(b.filterCheckMessage) : null; } async filterCheck(prep, set, concept) { From 51c10acbf5138a3f2e796ee0fdb7bf486397ed0b Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 01:10:20 -0600 Subject: [PATCH 43/90] sqlite-v2: LOINC states no deprecated status Neither main reader reports a LOINC code as deprecated (cs-loinc.js isDeprecated is false): the LOINC importer no longer writes deprecatedStatus. RxNorm keeps ["archived"]. Co-Authored-By: Claude --- tx/importers/import-loinc-v2.module.js | 1 - tx/sqlite-v2/README.md | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 1e87778b1..0950dedcf 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -243,7 +243,6 @@ function loincCodeSystem(b, version, description) { b.setBehaviour('displayDesignation', 'distinct'); b.setBehaviour('displayLanguage', 'en-US'); b.setBehaviour('filterLocateMessage', 'Not a valid code: {code}'); - b.setBehaviour('deprecatedStatus', ['DEPRECATED']); b.setBehaviour('declaresProperties', false); b.setBehaviour('implicitValueSets', 'loinc'); b.setBehaviour('implicitMaps', { base: 'http://loinc.org/cm/', maps: LOINC_MAPS }); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 124fe94ba..9a6eec2a2 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -216,7 +216,7 @@ refused (the builders check the same at build). | `inactiveDesignations` | `"omit"`, `"status"`, `"plain"` | `"omit"` | inactive items as designations: left out; listed with status inactive; listed like active ones. SNOMED CT `"status"`, RxNorm `"plain"` | | `displayDesignation` | `"none"`, `"first"`, `"distinct"` | `"first"` | the display listed as the first designation: `first` (the default) also drops the first designation whose text equals it; `distinct` keeps every designation (equal texts too); `none` lists no display designation. SNOMED CT `"none"`, LOINC `"distinct"`, RxNorm `"first"` | | `displayLanguage` | a language tag, `null` | `null` (`code_system.default_language`) | the language of the stored display (the display designation's language). SNOMED CT, LOINC, RxNorm `"en-US"` | -| `deprecatedStatus` | a list of status values | `[]` | the values of the status literal (`role = 'status'`) that mean deprecated. RxNorm `["archived"]` (RxNorm files store the status of an inactive concept: `obsolete`, still in RXNCONSO, or `archived`, RXNATOMARCHIVE only); LOINC `["DEPRECATED"]` | +| `deprecatedStatus` | a list of status values | `[]` | the values of the status literal (`role = 'status'`) that mean deprecated. RxNorm `["archived"]` (RxNorm files store the status of an inactive concept: `obsolete`, still in RXNCONSO, or `archived`, RXNATOMARCHIVE only) | | `declaresProperties` | boolean | `true` | the server declares the file's properties (expansion property definitions). SNOMED CT, LOINC, RxNorm `false` | | `implicitValueSets` | a URL-grammar name, `null` | `null` (none) | the implicit value sets, by a named URL grammar (like `grammar`); a name the reader does not implement refuses the file. SNOMED CT `snomed` (`?fhir_vs=...`), LOINC `loinc` (`/vs`, `/vs/LP...`, `/vs/LL...`), OMOP `omop` (not in the JS reader) | | `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | From 2734c3c7f08fa5fa660379ba9828ed7ba9e19948 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 01:11:32 -0600 Subject: [PATCH 44/90] sqlite-v2: unknownCodeVersion dropped from the format The SNOMED CT importer no longer writes it and the reader no longer knows it (a file that still carries it has an unknown key, ignored). Co-Authored-By: Claude --- tx/importers/sct-v2-common.js | 3 +-- tx/sqlite-v2/README.md | 1 - tx/sqlite-v2/meta.js | 1 - 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 1c192cea7..7e2ef13d2 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -234,13 +234,12 @@ class SnomedSink { b.setMeta('searchTieBreak', 'code-length'); // display regex over the FSNs and synonyms; generalizes leaves out the concept; whole-system // selections active only; no text definition reported (as cs-snomed.js); inactive descriptions - // listed with their status; the unknown-code message names the edition; the display en-US + // listed with their status; the display en-US b.setBehaviour('displayRegex', 'designations'); b.setBehaviour('generalizesExcludesSelf', true); b.setBehaviour('wholeActiveOnly', true); b.setBehaviour('lookupDefinition', false); b.setBehaviour('inactiveDesignations', 'status'); - b.setBehaviour('unknownCodeVersion', true); b.setBehaviour('displayLanguage', 'en-US'); // the display is not listed again as a designation (the SNOMED CT provider lists its descriptions) b.setBehaviour('displayDesignation', 'none'); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 9a6eec2a2..6291d67ae 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -208,7 +208,6 @@ refused (the builders check the same at build). | `keepDuplicateDesignations` | boolean | `false` | expansion rows keep a designation that repeats another. The JS reader does not implement it (the server's expansion code deduplicates) and refuses `true` | | `plainDesignationIsDisplay` | boolean | `false` | a designation with no use whose text equals the display is the display (not listed again) | | `wholeSystem` | `"list"`, `"empty"`, `"refuse"` | `"list"` | what an include of the whole system does | -| `unknownCodeVersion` | boolean | `false` | the unknown-code message names the version and edition (meta `edition`). SNOMED CT `true`. The JS server chooses that message in its shared worker code by the system URI, for every provider; the JS reader validates the key but cannot set the message | | `locateMessage` | a string with `{code}`, `null` | `null` | the reason for a code the system does not have (`locate`). UNII | | `filterLocateMessage` | a string with `{code}`, `null` | `null` | the reason for a code a value-set filter check cannot locate. LOINC `"Not a valid code: {code}"`, OMOP | | `filterCheckMessage` | a string with `{code}`, `null` | `null` | the reason for a found code a filter clause does not select. OMOP | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 35e5aee11..ed6b7964e 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -116,7 +116,6 @@ const KEYS = Object.freeze({ 'behaviour.keepDuplicateDesignations': json(isBool, false), 'behaviour.plainDesignationIsDisplay': json(isBool, false), 'behaviour.wholeSystem': json((v) => ['list', 'empty', 'refuse'].includes(v), 'list'), - 'behaviour.unknownCodeVersion': json(isBool, false), 'behaviour.locateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), 'behaviour.filterLocateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), 'behaviour.filterCheckMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), From 8db6b865c34e750e6c8422074e9992abd6196f1e Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 01:11:48 -0600 Subject: [PATCH 45/90] sqlite-v2: meta propertyUris is a known key [[name, uri], ...]: the only properties an expansion of all properties lists, in order, with their URIs (written for ICD-11 files). This reader serves no ICD-11 file and checks the value only. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-round2.test.js | 2 ++ tx/sqlite-v2/README.md | 1 + tx/sqlite-v2/meta.js | 2 ++ 3 files changed, 5 insertions(+) diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js index 6e5547737..181062c86 100644 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ b/tests/tx/sqlite-v2-format-round2.test.js @@ -85,6 +85,8 @@ describe('P1. meta: requires, known keys checked, unknown keys ignored', () => { expect(() => openStore(withMeta(base, { 'behaviour.distinctDesignationTexts': 'yes' }))).toThrow(/meta behaviour.distinctDesignationTexts = yes 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, { propertyUris: '[["code"]]' }))).toThrow(/meta propertyUris = .* is not a value/); + withStore(withMeta(base, { propertyUris: '[["code", "http://example.org/p#code"]]' }), (S) => expect(S.conceptCount).toBe(5)); }); test('the builder refuses to finish a file with a key it does not know', () => { diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 6291d67ae..ccec59686 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -171,6 +171,7 @@ Readers carry no path for a file built before a key existed: such a file is read | `moduleDependencies` | JSON list of `[module, target module, effective time, target effective time]` | `[]` | SNOMED CT module dependencies | | `edition` | text | none | the SNOMED CT edition (module id) | | `titles` | JSON object, language -> title | `{}` | the system's title per language (ICD-11) | +| `propertyUris` | JSON list of `[name, uri]` | none | the only properties an expansion of all properties lists, in that order, with their URIs (ICD-11: code, classKind, classificationCode, notSelectable). The JS reader serves no ICD-11 file and checks the value only | | `derived-by-importer` | JSON list of `{table, name}` | `[]` | index rows the importer writes (below) | | `ix.ix_word.format` | text | none | the word index's rules (`text-match/1`); absent: no word index | | `ix.ix_word.names` | JSON object | below | which names the word index holds, and so which names text search reads | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index ed6b7964e..3b45b2dd3 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -75,6 +75,8 @@ const KEYS = Object.freeze({ 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), {}), + // the only properties an expansion of all properties lists, in order, with their URIs (ICD-11 files) + propertyUris: json((v) => Array.isArray(v) && v.every((x) => Array.isArray(x) && x.length === 2 && isString(x[0]) && x[0] !== '' && isString(x[1]) && x[1] !== ''), null), 'derived-by-importer': json((v) => Array.isArray(v) && v.every((d) => isPlainObject(d) && isString(d.table) && isString(d.name)), []), // facts about indexes 'ix.ix_word.format': text((v) => v !== '', null), From be5ca218d6dd87e2f1e835a716f137a646393c07 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 01:19:49 -0600 Subject: [PATCH 46/90] sqlite-v2 README: the plain selection row names no further systems Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index ccec59686..4c5025d1f 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -342,7 +342,7 @@ write: | LOINC | `{"display": "en", "items": {"designations": true, "excludeUses": ["RELATEDNAMES2"]}}` | | RxNorm | `{"items": {"designations": true, "conceptsWith": "SUPPRESS", "language": "en"}}` | | ICD-11 | `{"items": {"designations": true, "includeUses": [null, "indexTerm", "inclusion", "fullySpecifiedName"]}}` | -| NDC, OMOP, UNII, CPT | `{"items": {"designations": true}}` | +| other systems (NDC, OMOP, UNII, ...) | `{"items": {"designations": true}}` | A file without the key has no names to search (text search matches codes only), whatever its system: no reader holds a table of systems for it. The index builder keeps the key across a From 5dff8215db2e010a660969f15a74c05244bc1c42 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 08:12:25 -0600 Subject: [PATCH 47/90] sqlite-v2: proposal for the next format revision Source material in the tables, a small FHIR reading in metadata (conceptStatus, property, item_use, filter), derived data labelled, procedures named. Accounts for every existing behaviour key. Nothing here is implemented. Co-Authored-By: Claude --- tx/sqlite-v2/PROPOSAL-fhir-reading.md | 416 ++++++++++++++++++++++++++ 1 file changed, 416 insertions(+) create mode 100644 tx/sqlite-v2/PROPOSAL-fhir-reading.md diff --git a/tx/sqlite-v2/PROPOSAL-fhir-reading.md b/tx/sqlite-v2/PROPOSAL-fhir-reading.md new file mode 100644 index 000000000..b8c512378 --- /dev/null +++ b/tx/sqlite-v2/PROPOSAL-fhir-reading.md @@ -0,0 +1,416 @@ +# sqlite-v2 files: proposed next revision + +Status: a proposal. Nothing here is implemented; `README.md` describes the format as the code +reads it today. Counts come from queries on built files unless a line says "reported" (found by a +reviewer, not re-run) or "not checked". + +## The idea + +A file has four layers, and each fact belongs to exactly one. + +1. **Source material.** `concept`, `item`, `link`, `literal`, `identifier`, `record` and `mapping` + hold what the release says, under the release's own names and values. No row is there to make + a server behave some way. +2. **The FHIR reading.** A small amount of metadata says what the source material means in FHIR's + terms. It is always a mapping from something the source has to a FHIR notion, and there is one + place per notion, the same for every terminology: + + | FHIR notion | Where the file maps it | Maps from | + |---|---|---| + | concept status: `inactive`, `deprecated`, `notSelectable` | meta `conceptStatus` | values of a source property | + | `CodeSystem.property` | `property` rows | source properties | + | `designation.use` | `item_use` rows | the source's kinds of name | + | `CodeSystem.filter` | `filter` rows | source properties | + | version matching, order, text search, expansion limits | one meta key each | | + +3. **Derived data.** `concept.active`, `concept.display`, `item.rank` and the `ix_*` tables are + computed from layer 1 by the rules of layer 2. They are labelled derived, a tool can rebuild + them, and `verify` checks them against the rules. +4. **Named procedures.** What needs an algorithm (an expression grammar, a stemmer) is named in the + file. A name stands for code only; it hides no data. + +A reader has general rules only: no table, fallback or branch by code system. A reader obeys +every key it accepts or refuses the file. + +Today the format has 33 `behaviour.*` keys, 18 of them set by one terminology each, and several +work by proxy (RxNorm's `domain = "SUPPRESS"` means "in the current release"). Most are an old +provider's `if` statement renamed as a key. This revision replaces them with the mappings above. +Section 12 accounts for every existing key. + +## 1. Concept status + +**Source material.** Whatever the release says about a concept's standing, stored as an ordinary +property with the release's values. + +**Mapping.** Meta `conceptStatus`: a list of properties, and for each value what it means. The +meanings are FHIR's three plus one of the format's: + +- `inactive`, `deprecated`, `notSelectable`: as FHIR defines the concept properties. +- `unlisted`: the code is known (`$lookup` and `$validate-code` find it) but no expansion, filter + or text search returns it. + +```json +// LOINC +[{"property": "STATUS", + "values": {"DISCOURAGED": ["inactive"], "DEPRECATED": ["deprecated"]}}] + +// RxNorm +[{"property": "status", + "values": {"obsolete": ["inactive"], + "archived": ["inactive", "deprecated", "unlisted"]}}] + +// ICD-11 MMS +[{"property": "classKind", + "values": {"block": ["notSelectable"], "chapter": ["notSelectable"], "window": ["notSelectable"]}}] + +// NDC +[{"property": "active", "values": {"false": ["inactive"]}}] +``` + +A value that is not named means nothing special. A file with no `conceptStatus` has no deprecated, +not-selectable or unlisted concepts. + +| System | Source property | Concepts | Reading | +|---|---|---|---| +| LOINC 2.83 | `STATUS` | ACTIVE 173,664; TRIAL 5,436; DEPRECATED 6,018; DISCOURAGED 2,224 | DISCOURAGED inactive; DEPRECATED deprecated | +| RxNorm | `status` | obsolete 99,140; archived 108,388 | obsolete inactive; archived inactive, deprecated, unlisted | +| ICD-11 MMS | `classKind` | block 1,360; chapter 28; window 159; category 35,664 | the first three not selectable | +| NDC | `active` | false 653,541; true 396,156 | false inactive | +| OMOP (fixture) | `invalid-reason` | D 14; U 9 | none today: the upstream provider reports them active. FHIR's reading would be inactive | +| SNOMED CT | the RF2 concept row's `active` | | copied to `concept.active`; no mapping needed | +| UNII, CPT | none | | | + +`concept.active` becomes a derived column, like `concept.display`: where `conceptStatus` names +inactive values, it is computed from them, and `verify` checks that it agrees. Concept ids still +run active first. Readers get the other three meanings as bitmaps from the stored property-value +sets. + +Which property is reported as the concept's `status` stays a catalog fact (`property.role = +'status'`). + +**Two things the importers change.** + +- RxNorm's `status` is not yet source material. The importer computes `obsolete` and `archived` + and writes them only on inactive concepts. It should write one value on every concept and say + in the mapping table how it is formed: `active`; `obsolete` (in RXNCONSO, and the atom that + gives its display has SUPPRESS = O); `archived` (only in RXNATOMARCHIVE). Folding atom-level + flags into one concept-level value is normalisation and stays in the importer. +- ICD-11 stops writing the `notSelectable` literal, which repeats `classKind` exactly (checked on + MMS: 1,547 concepts; ICF and Foundation not checked). + +**Replaces:** `domain`, `ix.ix_word.names.conceptsWith`, `deprecatedStatus`, the ICD-11 +`notSelectable` literal that readers match by name, the importer's unstated LOINC rule, and one +reader's check of the LOINC URL to report DEPRECATED. + +**Choices this makes visible.** LOINC DEPRECATED is active (as upstream) and OMOP's invalid +concepts are active (as upstream). Each is now one word in one file. + +## 2. Expansion limits + +Meta `expansionLimits`, an object; absent means none. + +```json +{"maxCodes": 1000} // CPT: a licence term +{"wholeSystem": "refuse"} // OMOP: an include of the whole system is refused as too costly +``` + +**Replaces:** `expansionLimit`, `wholeSystem`. UNII's `wholeSystem = "empty"` (a 154,561-concept +system answers that it has no codes) and SNOMED CT's `wholeActiveOnly` copy upstream providers; +see section 11. + +## 3. Names and designations + +**Source material.** `item` rows: text, language, the source's kind of name (`use_id`), the +source's own active flag and preferred flag. + +**Mapping.** `item_use`, one row per kind of name the source has: + +| column | meaning | default | +|---|---|---| +| `system`, `code`, `display` | the source's kind, as a Coding | | +| `role` | what the kind is: `fsn`, `synonym`, `definition`, `display` (its text is accepted as a display) | none | +| `as_property` | its items are reported as values of a property of this name, not as designations | none | +| `display_rank` | the kinds that can supply `concept.display`, in order | none | + +| System | Kinds (rows) | Roles | +|---|---|---| +| SNOMED CT | Synonym, Fully specified name, Definition | `synonym`, `fsn`, `definition` | +| LOINC | LONG_COMMON_NAME, SHORTNAME, DisplayName, ConsumerName, LinguisticVariantDisplayName, PartName, RELATEDNAMES2 | `display` on three; RELATEDNAMES2 `as_property` | +| RxNorm | the 23 term types (PSN, SCD, SBD, IN, SY, ...) | | +| ICD-11 | fullySpecifiedName, indexTerm, inclusion, longDefinition, codingNote, diagnosticCriteria | `fsn`, `definition` (both missing today) | +| CPT | its six designation types | today these are an item literal, not rows | +| NDC, OMOP, UNII | none (one plain name per concept) | | + +**General rules, the same for every file.** + +- A designation is reported with its kind as the use. +- An item with no kind and the source's preferred flag is reported with FHIR's use + `preferredForLanguage`. (ICD-11 titles; the single names of NDC and OMOP. Reported: applying + this to every file changes nothing for SNOMED CT, LOINC and RxNorm.) +- An inactive item is listed and marked inactive. Only SNOMED CT (306,090 items, the release's own + flag) and RxNorm (177,997) have any. RxNorm's are the atoms of RXNATOMARCHIVE, which has no + active flag: the importer invented `active = 0` and a key then told readers to ignore it. The + importer should store them active. +- The display's language is the language of the item it came from, else + `code_system.default_language`. + +**Replaces:** `preferredForLanguage` (which in one reader also switches off an unrelated step), +`inactiveDesignations`, `lookupDesignationCode`, `item_use.reported_as`, `plainDesignationIsDisplay` +(UNII: the importer stops storing the display a second time as a plain item), a hard-coded list +of LOINC kinds in the JS reader. + +How the display row and repeated texts are listed differs between three upstream providers and is +no fact about a terminology; see section 11. + +## 4. Properties + +**Source material.** `link`, `literal`, `identifier`, `record` rows under the source's property +names. + +**Mapping.** `property`, one row per source property: + +| column | meaning | default | +|---|---|---| +| `code` | the source's name | | +| `fhir_code` | the name it is reported under and asked for by | `code` | +| `also_asked_as` | further names a request may use | none | +| `uri`, `fhir_type` | as `CodeSystem.property` | | +| `lookup` | `default`, `named` (only when asked for by name or `*`), `never` | `default` | +| `expansion` | `asked`, `always`, `never` | `asked` | +| `lookup_rank` | position among the properties `$lookup` lists; unranked ones follow, by code | none | +| `true_value` | reported as a boolean, true when the value equals this | none | +| `presentation` | how a value is shown (unchanged) | | +| `internal` | a row the importer needs for storage: never reported, filtered or declared | 0 | + +| System | Row | Mapping | +|---|---|---| +| SNOMED CT | `116680003` | `fhir_code` `parent`, rank 1 | +| SNOMED CT | `definitionStatusId` | `fhir_code` `sufficientlyDefined`, `true_value` `900000000000073002`, `lookup` `named` | +| RxNorm | `TTY`, `STY`, `SAB` | ranks 0, 1, 2 | +| RxNorm | the relationships | `lookup` `named` | +| RxNorm | `RN@RB` and the other storage rows | `internal` | +| ICD-11 MMS | `classificationCode` | `expansion` `always` | +| ICD-11 | `code`, `classKind`, `classificationCode` | `expansion` `asked`; every other row `never` | +| ICD-11 | `child`, `browserUrl` | `lookup` `named` | + +**Replaces:** `report` (one column with four values covering two contexts), `reported_as`, +`lookupOrder`, `propertyUris`, and a JS rule that hides codes containing `@`. + +`lookupOrder` is also where the format is wrong today: the CPT, NDC, UNII and three ICD-11 files +carry LOINC's order (`CLASS`, `COMPONENT`, ...), and the order ICD-11 and NDC really use is in one +reader's code. With a rank on each row there is nothing to copy. + +Not settled: NDC lists a package's properties before its product's, which needs one more fact per +row. SNOMED CT's `named_links` (a property with both links and concrete values) is the same idea +as `lookup = named` for half a property and should fold into it; not designed. + +## 5. Filters + +**Mapping.** A `filter` table shaped like `CodeSystem.filter`, complete in every file. A filter +that is not a row is not understood, for every terminology. + +| column | meaning | +|---|---| +| `code` | the filter's name | +| `operators` | JSON list of FHIR filter operators | +| `reads` | a property code; or `concept` (the hierarchy), `inactive`, `display`, `designations`; or `grammar` (the file's grammar defines it) | +| `values` | JSON list of the only values accepted; absent: any | +| `where` | JSON `{property: value}` that must also hold | +| `then` | a property to follow from the concepts found (LOINC `answers-for` -> `Answer`) | +| `code_any_case` | the name may be written in any case | +| `value_as_display` | a value may be the target's display | + +| System | Filter rows | +|---|---| +| RxNorm | 59, each `=`, `in`; `TTY`, `STY`, `SAB` with `code_any_case` | +| NDC | `inactive`, `kind`, `category`, `code-type` | +| OMOP | `domain` `=`: reads `domain-id`, where `standard-concept` = `S` | +| ICD-11 | `concept` `is-a`, `descendent-of` | +| CPT | `kind`, `modifier`, `modified`, each `=` | +| UNII | none | +| SNOMED CT | `concept`, every attribute, `display` (reads `designations`), and `constraint`, `expressions` (read `grammar`) | +| LOINC | every relationship and axis, `STATUS`, `copyright`, `answers-for` (then `Answer`), `LIST`, `ancestor`, ... | + +One general rule: a filter value matches a stored literal value in any case. (The JS reader does +this for every file today and ignores the `value_any_case` column; the other reader obeys the +column, so the two differ on NDC, OMOP and ICD-11.) + +**Replaces:** `property.filterable`, `filter_ops`, `name_any_case`, `value_any_case`, +`match_display`, `selects_members`, `behaviour.filters`, `displayRegex`, and the filter names +still in code. Today three sources disagree: ICD-11 marks 9 properties filterable while its +`filters` list allows one filter, and a file with no `filters` list gets LOINC's filter names in +one reader. The CodeSystem resource's `filter` list is generated from the table. + +## 6. Order + +Meta `order`, an object. Every member takes words from one list. + +| word | meaning | +|---|---| +| `id` | concept id | +| `stored` | the order the importer stored (`ix_order` for concepts, `seq` for links) | +| `code` | the code as text | +| `code-number` | the code as a number | +| `display` | the display | +| `property` | by property, then target code | + +| member | default | SNOMED CT | LOINC | RxNorm | ICD-11 | NDC | OMOP | +|---|---|---|---|---|---|---|---| +| `expansion` | `id` | `stored` | `stored` | `stored` | | `stored` | | +| `searchTies` | `id` | `code-number` | `display` | `code` | `stored` | `code` | `code` | +| `links` | `property` | | `stored` | | `property`, then `stored` | | `code-number` | + +```json +{"expansion": "stored", "searchTies": "display", "links": "stored"} // LOINC +``` + +**Replaces:** `expansionOrder`, `searchTieBreak`, `linkOrder`: three keys in two namespaces whose +values say "the stored order" as `stored`, `rank` and `seq`, and "the code as a number" as +`code-length` and `target-int`. + +Reported: ICD-11 asks for search ties in stored order but stores no concept order, so it gets +concept id. The importer should store the order or say `id`. + +## 7. Text search + +Meta `search`, an object. `names` (which texts are searched) is today's `ix.ix_word.names` +without `conceptsWith`: an unlisted concept is never a search candidate, by the general rule of +section 1. + +The four named algorithms (`snomed`, `loinc`, `rxnorm`, `icd11`) differ in rules that are data. +Reported from a reading of both readers; no run yet shows the parameters reproduce the rankings: + +| parameter | SNOMED CT | LOINC | RxNorm | other files | +|---|---|---|---|---| +| `candidates` | `active` | `all` | `all`, and the concept has a name of a kind other than `SY` | `all` | +| `codeMatch` | `number-prefix` | `text-prefix` | `text-prefix` | `text-prefix` | +| `codeHits` | `first` | `merged` | `merged` | `merged` | +| `allWordsInOneName` | true | false | true | false | +| `shortlist` | by distinct-word count | | | | + +What stays code is the scoring of one name against the query, named `text-match/1` as now. +`icd11` adds no rule in one reader and makes the other refuse the file; it goes. + +Plan: move `candidates` and `names` to data first (certain), then replace each algorithm name +with parameters only where a run shows identical answers. + +## 8. Versions + +Meta `version`: + +```json +{"match": "prefix", "algorithm": "date"} +``` + +- `match`: how a requested version names this file: `exact` or `prefix`. +- `algorithm`: FHIR's `versionAlgorithm` code, used only to order versions. + +| System | Version | Today | Proposed | +|---|---|---|---| +| SNOMED CT | `http://snomed.info/sct//version/` | `url` | `prefix` (the edition URI without its date is a prefix) | +| LOINC | `2.83` | `natural` | `prefix`, `natural` | +| RxNorm | `03022026` | `date`, `versionFormat` `MMDDYYYY` | `prefix`; order and description from `code_system.release_date` | +| the others | dates or years | `date` | `prefix`, `date` | + +**Replaces:** `versionAlgorithm`, whose three values in use all behave as a prefix match (`url` is +not a FHIR code, and `date` on `03022026` compares no dates), and `versionFormat`, which restates +`release_date`. + +## 9. Alternate forms of a code + +**Source material.** `identifier` rows; `resolves` says whether a value is accepted as a code. + +**Mapping.** On the identifier scheme's own `property` row: `alias_parameter` (the output +parameter that returns the alias: ICD-11 `classificationCode`), `alias_extension` (the Coding +extension that restates it), `alias_literals` (the property values a concept reports when read +through the alias: NDC's 11-digit form). + +**Replaces:** `behaviour.aliases`, one system-wide key holding three facts about one scheme. +`alias_literals` is the least clean piece here: it is a small template (`{"synonym": "{code}"}`). +The alternative is to store NDC's 11-digit forms as concepts. + +## 10. Implicit value sets and concept maps + +URL templates in the file, in place of a grammar name per system: + +```json +[{"url": "http://loinc.org/vs", "include": {}}, + {"url": "http://loinc.org/vs/{code}", "when": {"code": "^LP"}, + "include": {"filter": [{"property": "ancestor", "op": "=", "value": "{code}"}]}}] +``` + +SNOMED CT's `?fhir_vs=ecl/...` hands the rest of the URL to the grammar. Implicit concept maps +keep today's `implicitMaps` shape; a map's `$lookup` property becomes a `property` row that the +`mapping` rows point at, as ICD-11 and OMOP already do, and SNOMED CT's association maps, today +only in code, are declared the same way. Reported feasible; not designed in detail. + +## 11. What copies an upstream provider + +Some settings state no fact about a terminology. Each reproduces the answer of one existing +provider where it differs from FHIR or from the other providers. + +| Setting | System | What it copies | +|---|---|---| +| `generalizes` leaves out the concept itself | SNOMED CT | against FHIR's definition of the operator | +| a whole-system include holds active concepts only | SNOMED CT | FHIR includes inactive ones unless `activeOnly` | +| an is-a selection lists its focus concept first | SNOMED CT | | +| text definitions are not reported | SNOMED CT | | +| a whole-system include is empty | UNII | | +| the display is listed as a designation: never / once / with every repeat | SNOMED CT / RxNorm / LOINC, ICD-11 | four keys today | +| designations carry no use | RxNorm | the term type is dropped | +| a designation is listed again with its type as a code | CPT | | +| `$lookup` reports the title, not the name | LOINC, ICD-11, OMOP | | +| `$lookup` lists the copyright | CPT | | +| property definitions are not declared on expansions | SNOMED CT, LOINC, RxNorm | | +| the wording of three not-found messages | UNII, LOINC, OMOP | | +| a concept with no `STATUS` filters as `NotStated` | LOINC | | +| every display is tagged `en-US` | all | five systems' own items are tagged `en` | + +Two ways to handle them: + +- **(a)** One behaviour for every system, FHIR's where FHIR defines it. These settings disappear, + and answers differ from upstream's providers in the listed ways. +- **(b)** Keep upstream's answers in one meta key, `compatibility`, with a member per row above. + Nobody then mistakes them for facts, and each can be deleted on its own later. + +Recommendation: (b) now, because (a) changes answers that are compared against upstream; then +delete rows one at a time as each difference is accepted. + +## 12. Every existing key + +| Today | Becomes | +|---|---| +| `domain`, `deprecatedStatus`, `ix.ix_word.names.conceptsWith` | `conceptStatus` (1) | +| `expansionLimit`, `wholeSystem` | `expansionLimits` (2) | +| `preferredForLanguage`, `inactiveDesignations` | general rules (3) | +| `lookupDesignationCode`, `plainDesignationIsDisplay` | `item_use` rows; importer content (3) | +| `lookupOrder`, `propertyUris`, `property.report`, `reported_as` | `property` columns (4) | +| `filters`, `displayRegex`, `filterable`, `filter_ops`, the four case and display columns | `filter` table (5) | +| `expansionOrder`, `searchTieBreak`, `linkOrder` | `order` (6) | +| `textSearch`, `ix.ix_word.names` | `search` (7) | +| `versionAlgorithm`, `versionFormat` | `version` (8) | +| `aliases` | identifier scheme row (9) | +| `implicitValueSets`, `implicitMaps` | templates (10) | +| `grammar` | unchanged: a named procedure | +| `generalizesExcludesSelf`, `wholeActiveOnly`, `lookupDefinition`, `displayDesignation`, `distinctDesignationTexts`, `keepDuplicateDesignations`, `designationUses`, `lookupName`, `lookupCopyright`, `declaresProperties`, `locateMessage`, `filterLocateMessage`, `filterCheckMessage`, `displayLanguage`, `property.default_value` | `compatibility`, or gone (11) | + +33 `behaviour.*` keys and 2 order keys become 8 meta keys (`conceptStatus`, `expansionLimits`, +`order`, `search`, `version`, `implicitValueSets`, `implicitMaps`, `grammar`), three mapping tables +(`property`, `item_use`, `filter`) and, under (b), `compatibility`. Every meta value is JSON and no +key has a `behaviour.` prefix. + +Named procedures that remain: the SNOMED CT expression grammar and ECL, ICD-11 postcoordination, +CPT modifiers, the stemmers, the scoring of one name in text search, and SNOMED CT's ranking of +displays by language reference set. + +## 13. Not checked + +- That one parameterised search reproduces the four rankings (7). +- That `display_rank` reproduces each importer's choice of display, RxNorm's in particular (3). +- The answer changes of each row in section 11 if it is removed. +- `classKind` against `notSelectable` on ICD-11 ICF and Foundation (1). +- Whether NDC's source has an active flag of its own or the importer derives the `active` literal + from dates; if derived, the source dates are the material and the rule needs a second form. +- The URL-template form for SNOMED CT and OMOP (10). +- The complete LOINC and SNOMED CT filter lists (5): to be written from what the readers' code + understands today, then compared. From 8687251bd5069d3c9f00d4009d94e2b34aab86c9 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 10:25:32 -0600 Subject: [PATCH 48/90] sqlite-v2 reader: read only the fhir-reading revision The reader takes every behaviour from the file's FHIR reading: property reporting columns, item_use roles and as_property, the filter table, and meta conceptStatus, expansionLimits, order, search, version, implicitValueSets, implicitMaps, grammar and compatibility. A file without the fhir-reading feature, or with a key or column of the earlier revision, is refused. dialects.js (per-system filter rules) and the per-system lookup adapters are gone; text search is one procedure with the parameters of meta search. README.md is the format document for the revision; the proposal it replaces is deleted. Co-Authored-By: Claude --- tx/importers/sqlite-v2/schema.sql | 87 +- tx/sqlite-v2/PROPOSAL-fhir-reading.md | 416 --------- tx/sqlite-v2/README.md | 950 ++++++++++++-------- tx/sqlite-v2/dialects.js | 301 ------- tx/sqlite-v2/engine/compile.js | 337 ++++--- tx/sqlite-v2/engine/evaluate.js | 6 +- tx/sqlite-v2/index.js | 9 +- tx/sqlite-v2/integrity.js | 1 + tx/sqlite-v2/layers.js | 2 +- tx/sqlite-v2/meta.js | 280 +++--- tx/sqlite-v2/orders.js | 25 +- tx/sqlite-v2/provider.js | 1200 +++++++++++++------------ tx/sqlite-v2/snomed.js | 223 ++--- tx/sqlite-v2/store.js | 531 +++++++---- tx/sqlite-v2/text-index.js | 554 ++++-------- 15 files changed, 2343 insertions(+), 2579 deletions(-) delete mode 100644 tx/sqlite-v2/PROPOSAL-fhir-reading.md delete mode 100644 tx/sqlite-v2/dialects.js diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 07cafc1af..b6e6c1b98 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -33,14 +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, filters, expansionOrder, lookupName, versionAlgorithm, --- designationUses, distinctDesignationTexts, preferredForLanguage, aliases, expansionLimit, textSearch, --- lookupCopyright, lookupDesignationCode; --- values and defaults in tx/sqlite-v2/README.md "Meta"). `requires` (JSON list) names the features the --- content uses that a reader must understand: a reader refuses a file that requires one it does not --- know. 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. +-- 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 ( @@ -62,24 +61,29 @@ CREATE TABLE item ( 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, - reported_as TEXT, -- the items of this use are reported as values of a property of this - -- name ($lookup), not as designations; NULL: designations (at most one per file) - role TEXT); -- NULL; 'fsn', 'synonym' (SNOMED CT description types); 'name': a use whose - -- text is accepted as a display (LOINC) + 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) + -- | '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 (at most one) - fhir_type TEXT, -- literal type + -- '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) @@ -87,27 +91,20 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat by_subject INTEGER NOT NULL DEFAULT 0, -- shape 'identifier': its rows are read by subject (ix_by_subject); the -- builder's default for an identifier row is 1, an importer sets 0 for -- rows only ever read by value (RxNorm atom relationships AUI:*) - named_links INTEGER NOT NULL DEFAULT 0, -- 1: its links are read only where the property is named (a $lookup - -- asking for it, a filter, an ECL refinement); left out elsewhere 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 and expansions report it: 'never' (not at all: a filter - -- only), 'named' (only when asked for by name), 'always' (also on every - -- expansion row); NULL: by default and when asked for - reported_as TEXT, -- the name the property is reported under ($lookup, expansion rows) and - -- asked for by; NULL: its code - also_asked_as TEXT, -- JSON list of further names a request may ask for it by (still reported - -- under reported_as or code); NULL: none + 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 - selects_members INTEGER, -- = / in on it select the members of the lists it links to (in: the union of =) - name_any_case INTEGER, -- a filter may name it in any case - value_any_case INTEGER, -- filter values match its stored values in any case - default_value TEXT, -- the value of a concept with no row of it (a filter = on it selects those too) - match_display INTEGER, -- a link filter value may be the target's display (case-folded) - value_system TEXT, -- an identifier property's values are codes of this system 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, filtered or declared + 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` @@ -115,6 +112,21 @@ 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 + 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 @@ -185,6 +197,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 @@ -195,8 +208,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. diff --git a/tx/sqlite-v2/PROPOSAL-fhir-reading.md b/tx/sqlite-v2/PROPOSAL-fhir-reading.md deleted file mode 100644 index b8c512378..000000000 --- a/tx/sqlite-v2/PROPOSAL-fhir-reading.md +++ /dev/null @@ -1,416 +0,0 @@ -# sqlite-v2 files: proposed next revision - -Status: a proposal. Nothing here is implemented; `README.md` describes the format as the code -reads it today. Counts come from queries on built files unless a line says "reported" (found by a -reviewer, not re-run) or "not checked". - -## The idea - -A file has four layers, and each fact belongs to exactly one. - -1. **Source material.** `concept`, `item`, `link`, `literal`, `identifier`, `record` and `mapping` - hold what the release says, under the release's own names and values. No row is there to make - a server behave some way. -2. **The FHIR reading.** A small amount of metadata says what the source material means in FHIR's - terms. It is always a mapping from something the source has to a FHIR notion, and there is one - place per notion, the same for every terminology: - - | FHIR notion | Where the file maps it | Maps from | - |---|---|---| - | concept status: `inactive`, `deprecated`, `notSelectable` | meta `conceptStatus` | values of a source property | - | `CodeSystem.property` | `property` rows | source properties | - | `designation.use` | `item_use` rows | the source's kinds of name | - | `CodeSystem.filter` | `filter` rows | source properties | - | version matching, order, text search, expansion limits | one meta key each | | - -3. **Derived data.** `concept.active`, `concept.display`, `item.rank` and the `ix_*` tables are - computed from layer 1 by the rules of layer 2. They are labelled derived, a tool can rebuild - them, and `verify` checks them against the rules. -4. **Named procedures.** What needs an algorithm (an expression grammar, a stemmer) is named in the - file. A name stands for code only; it hides no data. - -A reader has general rules only: no table, fallback or branch by code system. A reader obeys -every key it accepts or refuses the file. - -Today the format has 33 `behaviour.*` keys, 18 of them set by one terminology each, and several -work by proxy (RxNorm's `domain = "SUPPRESS"` means "in the current release"). Most are an old -provider's `if` statement renamed as a key. This revision replaces them with the mappings above. -Section 12 accounts for every existing key. - -## 1. Concept status - -**Source material.** Whatever the release says about a concept's standing, stored as an ordinary -property with the release's values. - -**Mapping.** Meta `conceptStatus`: a list of properties, and for each value what it means. The -meanings are FHIR's three plus one of the format's: - -- `inactive`, `deprecated`, `notSelectable`: as FHIR defines the concept properties. -- `unlisted`: the code is known (`$lookup` and `$validate-code` find it) but no expansion, filter - or text search returns it. - -```json -// LOINC -[{"property": "STATUS", - "values": {"DISCOURAGED": ["inactive"], "DEPRECATED": ["deprecated"]}}] - -// RxNorm -[{"property": "status", - "values": {"obsolete": ["inactive"], - "archived": ["inactive", "deprecated", "unlisted"]}}] - -// ICD-11 MMS -[{"property": "classKind", - "values": {"block": ["notSelectable"], "chapter": ["notSelectable"], "window": ["notSelectable"]}}] - -// NDC -[{"property": "active", "values": {"false": ["inactive"]}}] -``` - -A value that is not named means nothing special. A file with no `conceptStatus` has no deprecated, -not-selectable or unlisted concepts. - -| System | Source property | Concepts | Reading | -|---|---|---|---| -| LOINC 2.83 | `STATUS` | ACTIVE 173,664; TRIAL 5,436; DEPRECATED 6,018; DISCOURAGED 2,224 | DISCOURAGED inactive; DEPRECATED deprecated | -| RxNorm | `status` | obsolete 99,140; archived 108,388 | obsolete inactive; archived inactive, deprecated, unlisted | -| ICD-11 MMS | `classKind` | block 1,360; chapter 28; window 159; category 35,664 | the first three not selectable | -| NDC | `active` | false 653,541; true 396,156 | false inactive | -| OMOP (fixture) | `invalid-reason` | D 14; U 9 | none today: the upstream provider reports them active. FHIR's reading would be inactive | -| SNOMED CT | the RF2 concept row's `active` | | copied to `concept.active`; no mapping needed | -| UNII, CPT | none | | | - -`concept.active` becomes a derived column, like `concept.display`: where `conceptStatus` names -inactive values, it is computed from them, and `verify` checks that it agrees. Concept ids still -run active first. Readers get the other three meanings as bitmaps from the stored property-value -sets. - -Which property is reported as the concept's `status` stays a catalog fact (`property.role = -'status'`). - -**Two things the importers change.** - -- RxNorm's `status` is not yet source material. The importer computes `obsolete` and `archived` - and writes them only on inactive concepts. It should write one value on every concept and say - in the mapping table how it is formed: `active`; `obsolete` (in RXNCONSO, and the atom that - gives its display has SUPPRESS = O); `archived` (only in RXNATOMARCHIVE). Folding atom-level - flags into one concept-level value is normalisation and stays in the importer. -- ICD-11 stops writing the `notSelectable` literal, which repeats `classKind` exactly (checked on - MMS: 1,547 concepts; ICF and Foundation not checked). - -**Replaces:** `domain`, `ix.ix_word.names.conceptsWith`, `deprecatedStatus`, the ICD-11 -`notSelectable` literal that readers match by name, the importer's unstated LOINC rule, and one -reader's check of the LOINC URL to report DEPRECATED. - -**Choices this makes visible.** LOINC DEPRECATED is active (as upstream) and OMOP's invalid -concepts are active (as upstream). Each is now one word in one file. - -## 2. Expansion limits - -Meta `expansionLimits`, an object; absent means none. - -```json -{"maxCodes": 1000} // CPT: a licence term -{"wholeSystem": "refuse"} // OMOP: an include of the whole system is refused as too costly -``` - -**Replaces:** `expansionLimit`, `wholeSystem`. UNII's `wholeSystem = "empty"` (a 154,561-concept -system answers that it has no codes) and SNOMED CT's `wholeActiveOnly` copy upstream providers; -see section 11. - -## 3. Names and designations - -**Source material.** `item` rows: text, language, the source's kind of name (`use_id`), the -source's own active flag and preferred flag. - -**Mapping.** `item_use`, one row per kind of name the source has: - -| column | meaning | default | -|---|---|---| -| `system`, `code`, `display` | the source's kind, as a Coding | | -| `role` | what the kind is: `fsn`, `synonym`, `definition`, `display` (its text is accepted as a display) | none | -| `as_property` | its items are reported as values of a property of this name, not as designations | none | -| `display_rank` | the kinds that can supply `concept.display`, in order | none | - -| System | Kinds (rows) | Roles | -|---|---|---| -| SNOMED CT | Synonym, Fully specified name, Definition | `synonym`, `fsn`, `definition` | -| LOINC | LONG_COMMON_NAME, SHORTNAME, DisplayName, ConsumerName, LinguisticVariantDisplayName, PartName, RELATEDNAMES2 | `display` on three; RELATEDNAMES2 `as_property` | -| RxNorm | the 23 term types (PSN, SCD, SBD, IN, SY, ...) | | -| ICD-11 | fullySpecifiedName, indexTerm, inclusion, longDefinition, codingNote, diagnosticCriteria | `fsn`, `definition` (both missing today) | -| CPT | its six designation types | today these are an item literal, not rows | -| NDC, OMOP, UNII | none (one plain name per concept) | | - -**General rules, the same for every file.** - -- A designation is reported with its kind as the use. -- An item with no kind and the source's preferred flag is reported with FHIR's use - `preferredForLanguage`. (ICD-11 titles; the single names of NDC and OMOP. Reported: applying - this to every file changes nothing for SNOMED CT, LOINC and RxNorm.) -- An inactive item is listed and marked inactive. Only SNOMED CT (306,090 items, the release's own - flag) and RxNorm (177,997) have any. RxNorm's are the atoms of RXNATOMARCHIVE, which has no - active flag: the importer invented `active = 0` and a key then told readers to ignore it. The - importer should store them active. -- The display's language is the language of the item it came from, else - `code_system.default_language`. - -**Replaces:** `preferredForLanguage` (which in one reader also switches off an unrelated step), -`inactiveDesignations`, `lookupDesignationCode`, `item_use.reported_as`, `plainDesignationIsDisplay` -(UNII: the importer stops storing the display a second time as a plain item), a hard-coded list -of LOINC kinds in the JS reader. - -How the display row and repeated texts are listed differs between three upstream providers and is -no fact about a terminology; see section 11. - -## 4. Properties - -**Source material.** `link`, `literal`, `identifier`, `record` rows under the source's property -names. - -**Mapping.** `property`, one row per source property: - -| column | meaning | default | -|---|---|---| -| `code` | the source's name | | -| `fhir_code` | the name it is reported under and asked for by | `code` | -| `also_asked_as` | further names a request may use | none | -| `uri`, `fhir_type` | as `CodeSystem.property` | | -| `lookup` | `default`, `named` (only when asked for by name or `*`), `never` | `default` | -| `expansion` | `asked`, `always`, `never` | `asked` | -| `lookup_rank` | position among the properties `$lookup` lists; unranked ones follow, by code | none | -| `true_value` | reported as a boolean, true when the value equals this | none | -| `presentation` | how a value is shown (unchanged) | | -| `internal` | a row the importer needs for storage: never reported, filtered or declared | 0 | - -| System | Row | Mapping | -|---|---|---| -| SNOMED CT | `116680003` | `fhir_code` `parent`, rank 1 | -| SNOMED CT | `definitionStatusId` | `fhir_code` `sufficientlyDefined`, `true_value` `900000000000073002`, `lookup` `named` | -| RxNorm | `TTY`, `STY`, `SAB` | ranks 0, 1, 2 | -| RxNorm | the relationships | `lookup` `named` | -| RxNorm | `RN@RB` and the other storage rows | `internal` | -| ICD-11 MMS | `classificationCode` | `expansion` `always` | -| ICD-11 | `code`, `classKind`, `classificationCode` | `expansion` `asked`; every other row `never` | -| ICD-11 | `child`, `browserUrl` | `lookup` `named` | - -**Replaces:** `report` (one column with four values covering two contexts), `reported_as`, -`lookupOrder`, `propertyUris`, and a JS rule that hides codes containing `@`. - -`lookupOrder` is also where the format is wrong today: the CPT, NDC, UNII and three ICD-11 files -carry LOINC's order (`CLASS`, `COMPONENT`, ...), and the order ICD-11 and NDC really use is in one -reader's code. With a rank on each row there is nothing to copy. - -Not settled: NDC lists a package's properties before its product's, which needs one more fact per -row. SNOMED CT's `named_links` (a property with both links and concrete values) is the same idea -as `lookup = named` for half a property and should fold into it; not designed. - -## 5. Filters - -**Mapping.** A `filter` table shaped like `CodeSystem.filter`, complete in every file. A filter -that is not a row is not understood, for every terminology. - -| column | meaning | -|---|---| -| `code` | the filter's name | -| `operators` | JSON list of FHIR filter operators | -| `reads` | a property code; or `concept` (the hierarchy), `inactive`, `display`, `designations`; or `grammar` (the file's grammar defines it) | -| `values` | JSON list of the only values accepted; absent: any | -| `where` | JSON `{property: value}` that must also hold | -| `then` | a property to follow from the concepts found (LOINC `answers-for` -> `Answer`) | -| `code_any_case` | the name may be written in any case | -| `value_as_display` | a value may be the target's display | - -| System | Filter rows | -|---|---| -| RxNorm | 59, each `=`, `in`; `TTY`, `STY`, `SAB` with `code_any_case` | -| NDC | `inactive`, `kind`, `category`, `code-type` | -| OMOP | `domain` `=`: reads `domain-id`, where `standard-concept` = `S` | -| ICD-11 | `concept` `is-a`, `descendent-of` | -| CPT | `kind`, `modifier`, `modified`, each `=` | -| UNII | none | -| SNOMED CT | `concept`, every attribute, `display` (reads `designations`), and `constraint`, `expressions` (read `grammar`) | -| LOINC | every relationship and axis, `STATUS`, `copyright`, `answers-for` (then `Answer`), `LIST`, `ancestor`, ... | - -One general rule: a filter value matches a stored literal value in any case. (The JS reader does -this for every file today and ignores the `value_any_case` column; the other reader obeys the -column, so the two differ on NDC, OMOP and ICD-11.) - -**Replaces:** `property.filterable`, `filter_ops`, `name_any_case`, `value_any_case`, -`match_display`, `selects_members`, `behaviour.filters`, `displayRegex`, and the filter names -still in code. Today three sources disagree: ICD-11 marks 9 properties filterable while its -`filters` list allows one filter, and a file with no `filters` list gets LOINC's filter names in -one reader. The CodeSystem resource's `filter` list is generated from the table. - -## 6. Order - -Meta `order`, an object. Every member takes words from one list. - -| word | meaning | -|---|---| -| `id` | concept id | -| `stored` | the order the importer stored (`ix_order` for concepts, `seq` for links) | -| `code` | the code as text | -| `code-number` | the code as a number | -| `display` | the display | -| `property` | by property, then target code | - -| member | default | SNOMED CT | LOINC | RxNorm | ICD-11 | NDC | OMOP | -|---|---|---|---|---|---|---|---| -| `expansion` | `id` | `stored` | `stored` | `stored` | | `stored` | | -| `searchTies` | `id` | `code-number` | `display` | `code` | `stored` | `code` | `code` | -| `links` | `property` | | `stored` | | `property`, then `stored` | | `code-number` | - -```json -{"expansion": "stored", "searchTies": "display", "links": "stored"} // LOINC -``` - -**Replaces:** `expansionOrder`, `searchTieBreak`, `linkOrder`: three keys in two namespaces whose -values say "the stored order" as `stored`, `rank` and `seq`, and "the code as a number" as -`code-length` and `target-int`. - -Reported: ICD-11 asks for search ties in stored order but stores no concept order, so it gets -concept id. The importer should store the order or say `id`. - -## 7. Text search - -Meta `search`, an object. `names` (which texts are searched) is today's `ix.ix_word.names` -without `conceptsWith`: an unlisted concept is never a search candidate, by the general rule of -section 1. - -The four named algorithms (`snomed`, `loinc`, `rxnorm`, `icd11`) differ in rules that are data. -Reported from a reading of both readers; no run yet shows the parameters reproduce the rankings: - -| parameter | SNOMED CT | LOINC | RxNorm | other files | -|---|---|---|---|---| -| `candidates` | `active` | `all` | `all`, and the concept has a name of a kind other than `SY` | `all` | -| `codeMatch` | `number-prefix` | `text-prefix` | `text-prefix` | `text-prefix` | -| `codeHits` | `first` | `merged` | `merged` | `merged` | -| `allWordsInOneName` | true | false | true | false | -| `shortlist` | by distinct-word count | | | | - -What stays code is the scoring of one name against the query, named `text-match/1` as now. -`icd11` adds no rule in one reader and makes the other refuse the file; it goes. - -Plan: move `candidates` and `names` to data first (certain), then replace each algorithm name -with parameters only where a run shows identical answers. - -## 8. Versions - -Meta `version`: - -```json -{"match": "prefix", "algorithm": "date"} -``` - -- `match`: how a requested version names this file: `exact` or `prefix`. -- `algorithm`: FHIR's `versionAlgorithm` code, used only to order versions. - -| System | Version | Today | Proposed | -|---|---|---|---| -| SNOMED CT | `http://snomed.info/sct//version/` | `url` | `prefix` (the edition URI without its date is a prefix) | -| LOINC | `2.83` | `natural` | `prefix`, `natural` | -| RxNorm | `03022026` | `date`, `versionFormat` `MMDDYYYY` | `prefix`; order and description from `code_system.release_date` | -| the others | dates or years | `date` | `prefix`, `date` | - -**Replaces:** `versionAlgorithm`, whose three values in use all behave as a prefix match (`url` is -not a FHIR code, and `date` on `03022026` compares no dates), and `versionFormat`, which restates -`release_date`. - -## 9. Alternate forms of a code - -**Source material.** `identifier` rows; `resolves` says whether a value is accepted as a code. - -**Mapping.** On the identifier scheme's own `property` row: `alias_parameter` (the output -parameter that returns the alias: ICD-11 `classificationCode`), `alias_extension` (the Coding -extension that restates it), `alias_literals` (the property values a concept reports when read -through the alias: NDC's 11-digit form). - -**Replaces:** `behaviour.aliases`, one system-wide key holding three facts about one scheme. -`alias_literals` is the least clean piece here: it is a small template (`{"synonym": "{code}"}`). -The alternative is to store NDC's 11-digit forms as concepts. - -## 10. Implicit value sets and concept maps - -URL templates in the file, in place of a grammar name per system: - -```json -[{"url": "http://loinc.org/vs", "include": {}}, - {"url": "http://loinc.org/vs/{code}", "when": {"code": "^LP"}, - "include": {"filter": [{"property": "ancestor", "op": "=", "value": "{code}"}]}}] -``` - -SNOMED CT's `?fhir_vs=ecl/...` hands the rest of the URL to the grammar. Implicit concept maps -keep today's `implicitMaps` shape; a map's `$lookup` property becomes a `property` row that the -`mapping` rows point at, as ICD-11 and OMOP already do, and SNOMED CT's association maps, today -only in code, are declared the same way. Reported feasible; not designed in detail. - -## 11. What copies an upstream provider - -Some settings state no fact about a terminology. Each reproduces the answer of one existing -provider where it differs from FHIR or from the other providers. - -| Setting | System | What it copies | -|---|---|---| -| `generalizes` leaves out the concept itself | SNOMED CT | against FHIR's definition of the operator | -| a whole-system include holds active concepts only | SNOMED CT | FHIR includes inactive ones unless `activeOnly` | -| an is-a selection lists its focus concept first | SNOMED CT | | -| text definitions are not reported | SNOMED CT | | -| a whole-system include is empty | UNII | | -| the display is listed as a designation: never / once / with every repeat | SNOMED CT / RxNorm / LOINC, ICD-11 | four keys today | -| designations carry no use | RxNorm | the term type is dropped | -| a designation is listed again with its type as a code | CPT | | -| `$lookup` reports the title, not the name | LOINC, ICD-11, OMOP | | -| `$lookup` lists the copyright | CPT | | -| property definitions are not declared on expansions | SNOMED CT, LOINC, RxNorm | | -| the wording of three not-found messages | UNII, LOINC, OMOP | | -| a concept with no `STATUS` filters as `NotStated` | LOINC | | -| every display is tagged `en-US` | all | five systems' own items are tagged `en` | - -Two ways to handle them: - -- **(a)** One behaviour for every system, FHIR's where FHIR defines it. These settings disappear, - and answers differ from upstream's providers in the listed ways. -- **(b)** Keep upstream's answers in one meta key, `compatibility`, with a member per row above. - Nobody then mistakes them for facts, and each can be deleted on its own later. - -Recommendation: (b) now, because (a) changes answers that are compared against upstream; then -delete rows one at a time as each difference is accepted. - -## 12. Every existing key - -| Today | Becomes | -|---|---| -| `domain`, `deprecatedStatus`, `ix.ix_word.names.conceptsWith` | `conceptStatus` (1) | -| `expansionLimit`, `wholeSystem` | `expansionLimits` (2) | -| `preferredForLanguage`, `inactiveDesignations` | general rules (3) | -| `lookupDesignationCode`, `plainDesignationIsDisplay` | `item_use` rows; importer content (3) | -| `lookupOrder`, `propertyUris`, `property.report`, `reported_as` | `property` columns (4) | -| `filters`, `displayRegex`, `filterable`, `filter_ops`, the four case and display columns | `filter` table (5) | -| `expansionOrder`, `searchTieBreak`, `linkOrder` | `order` (6) | -| `textSearch`, `ix.ix_word.names` | `search` (7) | -| `versionAlgorithm`, `versionFormat` | `version` (8) | -| `aliases` | identifier scheme row (9) | -| `implicitValueSets`, `implicitMaps` | templates (10) | -| `grammar` | unchanged: a named procedure | -| `generalizesExcludesSelf`, `wholeActiveOnly`, `lookupDefinition`, `displayDesignation`, `distinctDesignationTexts`, `keepDuplicateDesignations`, `designationUses`, `lookupName`, `lookupCopyright`, `declaresProperties`, `locateMessage`, `filterLocateMessage`, `filterCheckMessage`, `displayLanguage`, `property.default_value` | `compatibility`, or gone (11) | - -33 `behaviour.*` keys and 2 order keys become 8 meta keys (`conceptStatus`, `expansionLimits`, -`order`, `search`, `version`, `implicitValueSets`, `implicitMaps`, `grammar`), three mapping tables -(`property`, `item_use`, `filter`) and, under (b), `compatibility`. Every meta value is JSON and no -key has a `behaviour.` prefix. - -Named procedures that remain: the SNOMED CT expression grammar and ECL, ICD-11 postcoordination, -CPT modifiers, the stemmers, the scoring of one name in text search, and SNOMED CT's ranking of -displays by language reference set. - -## 13. Not checked - -- That one parameterised search reproduces the four rankings (7). -- That `display_rank` reproduces each importer's choice of display, RxNorm's in particular (3). -- The answer changes of each row in section 11 if it is removed. -- `classKind` against `notSelectable` on ICD-11 ICF and Foundation (1). -- Whether NDC's source has an active flag of its own or the importer derives the `active` literal - from dates; if derived, the source dates are the material and the rule needs a second form. -- The URL-template form for SNOMED CT and OMOP (10). -- The complete LOINC and SNOMED CT filter lists (5): to be written from what the readers' code - understands today, then compared. diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 4c5025d1f..3a48b8bd7 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -1,13 +1,40 @@ -# 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`. -## The model +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"). + +## 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` | 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. -A file holds one code system version as **nodes**, a **catalog** and **statements**. +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 | one meta key each | | +| an upstream provider's answer where it differs from FHIR | meta `compatibility` | | + +## 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 @@ -19,31 +46,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 @@ -51,64 +97,543 @@ 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). The CodeSystem id a server serves the system under is `resource.id` as it is (`x-` included), and its catalog name `resource.name` (else `name`); the importers write what main's provider for the system forms: SNOMED CT `x-SCT--` (`x-xSCT-...` for an xsct edition; no id for an undated version) named `SCT ` (`SNOMED CT Test Set` for xsct), LOINC `x-loinc`, RxNorm `x-RxNorm-`; a file without a resource id has no catalog id | -| `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); `reported_as` (NULL default; at most one per file): the active items of this use are reported as values of a property of this name (`$lookup`: the item's text, with its language), not as designations; listed by default, by name or `*` (LOINC `RELATEDNAMES2`); `role` (NULL default): `fsn`, `synonym` (SNOMED CT description types), `name` (a use whose text is accepted as a display: LOINC `LONG_COMMON_NAME`, `SHORTNAME`, `LinguisticVariantDisplayName`); readers find these uses by role, never by code | -| `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`, `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 (declared `TEXT`: every value is stored as text, whatever a writer binds; see `identifier-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) | +| `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` | (written by the importer, listed in `derived-by-importer`; the index builder computes none) 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, 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 over the names `ix.ix_word.names` selects: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (below) | +| `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) | +## property: the catalog + +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`). + +| column | values | NULL / default | meaning | +|---|---|---|---| +| `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`) | +| `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]}` | 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 | +| `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`); never reported, filtered or declared | +| `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). The JS reader does not implement them and refuses a file that sets one | +| 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 with an + `equivalence` subproperty, ordered by system then code. Example: LOINC `sct` (12 such rows, one per + implicit map key). +- `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 | +|---|---| +| `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 | required | the operators this row takes; two rows with one `code` have disjoint operators (LOINC `answers-for`) | +| `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:`) | +| `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 without the `value_prefix`, is not understood. + +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 | | with / without an identifier of the scheme | | | +| `concept` | the concept x (`in`: a concept that defines a record relation contributes its members) | | 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. + +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. + +## 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 | + +Release facts and facts about indexes: + +| key | value | meaning | +|---|---|---| +| `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 `status` parameter of `$validate-code`, an expansion row's `status`): the + value of the concept's `role = 'status'` literal when it has one and that value is not `active` + (ignoring case); else `inactive` for an inactive concept; else none. + +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: that of the first item (list order) whose text is the display and +that has a language, else `code_system.default_language`. LOINC and RxNorm items are `en-US`, so their +display designation is `en-US`; UNII's file has no item equal to the display and default language +`en`. + +`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) before literals before the rest (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. + +## 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`; `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`, `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) | | +| `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 | + +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, and +`child-of` lists the children in `ix_in` seq order. 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`) | +| `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": {}}, + {"url": "http://loinc.org/vs/{v}", "v": "^LP", "mustBeCode": true, + "include": {"filter": [{"property": "ancestor", "op": "=", "value": "{v}"}]}}, + {"url": "http://loinc.org/vs/{v}", "v": "^LL", "mustBeCode": true, "enumerate": {"property": "LIST", "op": "=", "value": "{v}"}}] +``` + +| 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 and version the file's), `{v}` substituted in every string | +| `enumerate` | instead of `include`: one filter whose concepts, in the filter's order, are listed as `include.concept` | +| `name`, `title`, `description` | the resource's texts, with `{v}`, `{display}` (the display of concept `{v}`), `{version}` | +| `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"], ...]} +{"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, both ways. How a mapping row is reported by `$lookup` is decided by its + `property_id` only. +- `used`: a member the JS reader does not implement (a file with it is refused). +- `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. + +## 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` | implemented (`snomed.js`) | +| `icd11` | ICD-11 MMS, ICF | postcoordinated expressions | refused | +| `cpt` | CPT | codes with modifiers; the `modified` filter | refused | + +## 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 | +| `isAListsFocusFirst` | bool | false | SNOMED CT | with `order.expansion` `stored`: `is-a` lists its focus first; `child-of` in `ix_in` seq order | +| `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 reader does not implement it: its expansion code removes repeats) | +| `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 | +| `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...` | none | none | +| `implicitMaps` | the association relations the file has | the twelve map keys | none | none | +| `grammar` | `snomed` | none | none | none | +| `compatibility` | generalizesLeavesOutFocus, wholeSystemIncludeActiveOnly, isAListsFocusFirst, lookupOmitsTextDefinitions, expansionDeclaresProperties false | statusReadingsIgnored, displayDesignation always, lookupNameIsTitle, expansionDeclaresProperties false, filterUnknownCodeMessage, missingValueFiltersAs | displayDesignation once, designationUse none, expansionDeclaresProperties false | displayDesignation once, wholeSystemIncludeEmpty, unknownCodeMessage | +| `filter` rows | 11 (concept, code, inactive, display, moduleId, definitionStatusId, effectiveTime, constraint, expressions, attribute pattern, `mapped:` pattern) | 61 | 61 (TTY, STY, SAB any case; relationships with `CUI:`; concept, code) | none | +| `item_use` | synonym, fsn roles | display roles, `language_display_rank`, `RELATEDNAMES2` as property | the term types | none | + +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 any file of this revision whose keys it implements, whatever the system: the library loads +SNOMED CT, LOINC and RxNorm files (`snomed-v2:`, `loinc-v2:`, `rxnorm-v2:` source lines), and the +generic provider serves any plain-code file (UNII). It refuses, naming the key: + +| file | refused because | +|---|---| +| ICD-11 MMS, ICF | `grammar` `icd11`; `compatibility.expansionKeepsRepeatedDesignations`; alias columns | +| ICD-11 Foundation | `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_extension`) | +| CPT | `grammar` `cpt` | +| NDC | `alias_literals` on `code11` (11-digit codes as codes in their own right) | +| OMOP | `implicitMaps.used` | + ## Contracts What every file keeps, and every reader may rely on. The builder checks those marked before it -finishes a file (`builder.js` `checkContracts`, run by `finishFile`; `node indexes.js ` runs it -after a rebuild); `verify.js` checks them on request. +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, one id space with the concepts | yes | -| at most one property with `subsumption = 1` (the hierarchy), at most one `ordered = 1` link property (the list property), at most one with `role = 'status'` | yes | -| codes are unique per system and matched exactly (binary): the unique index `concept_code` | yes | -| `identifier.value` is text | by the schema (`TEXT`; `identifier-text`) | -| `ix_set` keys: kinds 1, 2, 3 have property 0, value 0, value kind 0; kinds 6 and 7 value 0, value kind 0; kind 4 value kind 1 | yes | -| a kind 4 set (the descendants of the concept `value`) does not hold `value`; the all and active sets have N and A members; sets hold concept ids only | yes (kinds 1, 2, 4 decoded) | -| `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 (row counts) | -| `ix_order` arrays: little-endian u32 in 1,024-entry blocks 0..k, all full but the last; `rank` and `ids` N+1 entries, `walk` and `active` at most N; `ix.ix_order.walk.reached` at most the walk's length | yes | -| `behaviour.expansionOrder` other than `ids`: `ix_order` has `rank` and `ids` | yes | -| the `ix_word` counts rows are `2 * (N + 1)` bytes; every `ix_word` language has an `ix.ix_word.stemmers` entry | 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; `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; `reads` names catalog properties (none internal) 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 | +| `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 | -| meta follows "Meta" (every key one the builder knows, every value well-formed); `requires` is stated; a word index has its `ix.ix_word.names` | yes | -| record `fields` is a JSON array in the order of the relation's non-target fields | stated (a check would parse every record row) | - -The JS reader checks the id ranges it relies on at open (an id up to N is a concept, above N an -item): `min(concept.id) = 1`, `max(concept.id) = N`, `min(item.id) > N`, three probes of the rowid -b-trees. It checks nothing else of the list at open. -Columns: `code_system.case_sensitive`, `hierarchy_meaning` and `release_date` are the FHIR -CodeSystem facts (the JS provider's `isCaseSensitive()` reads `case_sensitive`; NULL: true). -`property.n_rows` and `property.target_kind` are gone: derived, and read by no reader (a file built -before still has them; readers ignore them). +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 @@ -124,7 +649,8 @@ it again (the index builder removes it when it drops the indexes). - `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), `value_label` (ORDER BY property_id, value). + 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. @@ -133,281 +659,6 @@ meta values, the contracts above (id ranges included), and, where the file state 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. -## Files built before a key existed - -Readers carry no path for a file built before a key existed: such a file is read by the rules above -(an absent key has its default) or refused where that would give wrong answers (no -`identifier-text`; a catalog without the columns `reported_as`, `also_asked_as`, `true_value` and -`named_links`). Rebuild it with the importers, or upgrade it (the other implementation's -`tx-import upgrade` writes a file with every key this format now has). - -## Meta - -`meta` is key -> text. One rule for every key: - -- `requires` (JSON list of distinct strings; absent: `[]`) names 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, and says which. A writer that adds something every reader must understand names a feature - here; nothing else makes an older reader refuse a file. - - | feature | meaning | - |---|---| - | `identifier-text` | every `identifier.value` (and `ix_by_subject.value`) is text: the column is declared `TEXT`. A reader binds identifier probe values as text, lists passed through `json_each` included (an integer there does not match a text value). Every file the builder writes requires it; the JS reader refuses a file that does not (one built before the column was declared `TEXT`, which may hold INTEGER values a text probe misses: rebuild or upgrade it). The name stays in `requires` so that a reader that does not know it, and would bind integers, refuses such a file. | -- A reader ignores a key it does not know. A key it knows with a malformed value is refused, with - the key and the value in the message, in every file. -- Each key has one meaning and a default (absent means the default). A reader obeys the file's - value; it has no rule of its own for a system that overrides the file or fills in for an absent key. - An importer writes the values its system needs. -- A builder checks every key it writes against its own list and refuses to finish a file with a key - it does not know (a typo is caught where it is made). `provenance.*` is free-form and never read. - -| key | value | default | meaning | -|---|---|---|---| -| `format` | `tx-terminology/1` | (required) | the format | -| `requires` | JSON list of feature names | `[]` | above | -| `integrity` | JSON `{items, schema, catalog}` | none | facts a tool checks on request (below); readers do not | -| `languages` | JSON list of language tags | `[]` | the languages of the served system's items, in order of first appearance | -| `displayContexts` | JSON `{relations, preferred, use}` | none (no display reference sets) | the language relations that rank displays (SNOMED CT; the importer always writes it) | -| `moduleDependencies` | JSON list of `[module, target module, effective time, target effective time]` | `[]` | SNOMED CT module dependencies | -| `edition` | text | none | the SNOMED CT edition (module id) | -| `titles` | JSON object, language -> title | `{}` | the system's title per language (ICD-11) | -| `propertyUris` | JSON list of `[name, uri]` | none | the only properties an expansion of all properties lists, in that order, with their URIs (ICD-11: code, classKind, classificationCode, notSelectable). The JS reader serves no ICD-11 file and checks the value only | -| `derived-by-importer` | JSON list of `{table, name}` | `[]` | index rows the importer writes (below) | -| `ix.ix_word.format` | text | none | the word index's rules (`text-match/1`); absent: no word index | -| `ix.ix_word.names` | JSON object | below | which names the word index holds, and so which names text search reads | -| `ix.ix_word.stemmers` | JSON object, language -> stemmer name | below | the stemmer that made each language's `stem` column | -| `ix.ix_order..reached` | decimal integer | none | how many concepts a stored walk reaches | -| `behaviour.*` | JSON | per key | below | - -Informational keys a builder writes that no reader reads: `ix.ix_key.normalForm.stats` (SNOMED CT -normal forms written, failed, seconds). - -## Behaviour settings - -`meta` keys `behaviour.`, JSON values. A key that is absent has its default; a malformed value is -refused (the builders check the same at build). - -| key | values | default | written by | -|---|---|---|---| -| `grammar` | a grammar name (an open string), `null` | `null` (plain codes) | the grammar of the system's codes. A reader holds its implementations by name and refuses a file whose grammar it does not implement ("its codes are in the grammar X, which this server does not implement"); there is no fallback by system URI. Names in use: `"snomed"` (SNOMED CT expressions and ECL; the JS reader's SNOMED CT provider, `index.js` `GRAMMARS`), `"icd11"` (ICD-11 MMS and ICF files: postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records), and a code system whose codes carry modifiers. The JS reader implements `snomed` only | -| `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"` | the name `$lookup` reports: `code_system.name` (no name: the system URI), or the title (below; no title: the name). LOINC `"title"` | -| `versionAlgorithm` | a string, `null` | `null` | CodeSystem.versionAlgorithm: how a requested version (check-system-version) matches the file's version (FHIRsmith `versionMatchesByAlgorithm`: `semver` with wildcards, `integer` exactly, any other value by prefix). `null`: what the stored CodeSystem resource declares (`versionAlgorithmString` / `versionAlgorithmCoding`), else only the exact version matches; no guess from the version string and no rule of the reader's own for a system. Every importer writes it: SNOMED CT `"url"` (versions are edition URIs, matched by prefix), LOINC `"natural"`, RxNorm `"date"`. A request naming a partial version resolves by it too: with `url`, the version before `/version/` (an edition URI without its date) names the file; any other algorithm resolves exact versions only (which of several files with the same partial version is the library's rule: the JS library takes the one it loaded last) | -| `designationUses` | `"keep"`, `"drop"` | `"keep"` | `"drop"`: no designation reports a use. RxNorm `"drop"` | -| `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | -| `aliases` | `null`, or `{"parameter"?, "extension"?, "literals"?}` (any other field: malformed) | `null` | identifier-aliased codes (identifiers with `resolves` 1 or 2). `parameter`: `$validate-code` of a code written in its canonical form also returns its alias (`resolves = 1`) as an output parameter of this name. `extension`: a Coding extension that restates the alias form of its code, which `$validate-code` checks against the code's alias. `literals` (property code -> value): the literal values a concept reports when read through an identifier code instead of its stored values of those properties; `{code}` is the concept's own code. ICD-11 MMS and ICF `{"parameter": "classificationCode", "extension": "http://id.who.int/icd/schema/extension/classificationCode"}`, Foundation `{"extension": ...}`, NDC `{"literals": {"code-type": "11-digit", "synonym": "{code}"}}`. The JS reader does not implement identifier aliases and refuses a file that sets it | -| `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 | -| `textSearch` | a search name (open string), `null` | `null` (the generic search: each concept rated by its best name in the search language, the display above a designation, or a code it starts) | the text-search algorithm, by name; a reader holds its implementations by name and refuses a file whose search it does not implement. Names: `snomed` (SNOMED CT: designations in the request's language, a one-word filter shortlisted by each concept's distinct-word count (`ix.ix_word.names` `counts`), then the best designation; identifier digits first; active concepts), `loinc` (each concept's best name or a code in the filter's code ranges, every concept), `rxnorm` (the best atom name or code, among the concepts with a SUPPRESS literal and a term type other than SY; several words must be in one name). Which names each reads is `ix.ix_word.names`; ties are `searchTieBreak`. ICD-11 files name `icd11`, which the JS reader does not implement (such a file is refused). SNOMED CT `snomed`, LOINC `loinc`, RxNorm `rxnorm` | -| `lookupCopyright` | `true`, `false` | `false` | `$lookup` lists `code_system.resource.copyright` as a `copyright` property; a file that sets it without a copyright is refused | -| `domain` | a property code, `null` | `null` (every concept) | the concepts answers select: those with a row of this property (active or not); the file's other concepts are kept (e.g. for history) but no expansion, filter, count, text-search base set or whole-system walk selects them. A code naming no catalog property refuses the file. RxNorm `"SUPPRESS"` (the concepts in RXNCONSO; RXNATOMARCHIVE-only concepts are never selected) | -| `lookupOrder` | `null`, or `{"ranks": {name: int}, "concept"?: int, "other": int, "byCode"?: bool}` | `null` (no reordering) | the order of the properties `$lookup` lists: by rank, `ranks[name]` (the reported name), else `concept` for a code-valued property where given, else `other`; ties in the order the reader lists them, or with `byCode` by name, then value code. SNOMED CT `{"ranks": {"effectiveTime": 0, "parent": 1, "child": 2, "moduleId": 3, "sufficientlyDefined": 4, "semanticTag": 5}, "other": 6}`; RxNorm `{"ranks": {"TTY": 0, "STY": 1, "SAB": 2}, "other": 3, "byCode": true}`; LOINC the axes 0-6, `AnswerList` 8, `parent`/`child` 9, `STATUS` 11, `RELATEDNAMES2` 12, each implicit map's key 13, `concept` 8, `other` 10 | -| `implicitMaps` | `null`, or `{"base": url prefix, "maps": [[target system, key], ...], "used"?: infix}` | `null` | the file's implicit ConceptMaps over its `mapping` rows: map `{base}{key}` translates to (and from) the target system, and `$lookup` lists a concept's mappings to it as a property named `key`. With `used`, a map is reported as used as `{base}{used}{key}|{version}` and offered whether or not it translates the code (OMOP); the JS reader does not implement `used` and refuses such a file. LOINC `{"base": "http://loinc.org/cm/", "maps": [...cs-loinc.js's twelve]}` | -| `displayRegex` | `"display"`, `"designations"` | `"display"` | what a `display regex` filter matches: the concept's display, or (`designations`) any active designation of a use with role `fsn` or `synonym` in the request's text-search language. SNOMED CT `"designations"` | -| `generalizesExcludesSelf` | boolean | `false` | `generalizes` leaves out the concept itself. SNOMED CT `true` | -| `wholeActiveOnly` | boolean | `false` | a whole-system selection, and the roots of a walk, hold active concepts only. SNOMED CT `true` | -| `lookupDefinition` | boolean | `true` | text definitions are reported (`$lookup` `definition`, expansion rows). SNOMED CT `false` | -| `keepDuplicateDesignations` | boolean | `false` | expansion rows keep a designation that repeats another. The JS reader does not implement it (the server's expansion code deduplicates) and refuses `true` | -| `plainDesignationIsDisplay` | boolean | `false` | a designation with no use whose text equals the display is the display (not listed again) | -| `wholeSystem` | `"list"`, `"empty"`, `"refuse"` | `"list"` | what an include of the whole system does | -| `locateMessage` | a string with `{code}`, `null` | `null` | the reason for a code the system does not have (`locate`). UNII | -| `filterLocateMessage` | a string with `{code}`, `null` | `null` | the reason for a code a value-set filter check cannot locate. LOINC `"Not a valid code: {code}"`, OMOP | -| `filterCheckMessage` | a string with `{code}`, `null` | `null` | the reason for a found code a filter clause does not select. OMOP | -| `versionFormat` | `"MMDDYYYY"`, `null` | `null` | versions are dates written MMDDYYYY (described as such; the JS reader's `describeVersion`). RxNorm `"MMDDYYYY"` | -| `inactiveDesignations` | `"omit"`, `"status"`, `"plain"` | `"omit"` | inactive items as designations: left out; listed with status inactive; listed like active ones. SNOMED CT `"status"`, RxNorm `"plain"` | -| `displayDesignation` | `"none"`, `"first"`, `"distinct"` | `"first"` | the display listed as the first designation: `first` (the default) also drops the first designation whose text equals it; `distinct` keeps every designation (equal texts too); `none` lists no display designation. SNOMED CT `"none"`, LOINC `"distinct"`, RxNorm `"first"` | -| `displayLanguage` | a language tag, `null` | `null` (`code_system.default_language`) | the language of the stored display (the display designation's language). SNOMED CT, LOINC, RxNorm `"en-US"` | -| `deprecatedStatus` | a list of status values | `[]` | the values of the status literal (`role = 'status'`) that mean deprecated. RxNorm `["archived"]` (RxNorm files store the status of an inactive concept: `obsolete`, still in RXNCONSO, or `archived`, RXNATOMARCHIVE only) | -| `declaresProperties` | boolean | `true` | the server declares the file's properties (expansion property definitions). SNOMED CT, LOINC, RxNorm `false` | -| `implicitValueSets` | a URL-grammar name, `null` | `null` (none) | the implicit value sets, by a named URL grammar (like `grammar`); a name the reader does not implement refuses the file. SNOMED CT `snomed` (`?fhir_vs=...`), LOINC `loinc` (`/vs`, `/vs/LP...`, `/vs/LL...`), OMOP `omop` (not in the JS reader) | -| `expansionLimit` | an integer >= 0 | `0` (no limit) | the most codes of this system an expansion lists or walks (the JS provider's `expandLimitation()`; such an expansion takes expand.js's usual path, which counts them) | -| `lookupDesignationCode` | a property code, `null` | `null` | `$lookup` lists each designation that has a literal of this property (a property of items) again, as a `designation` parameter with parts `code` (the literal's value), `value` (the item's text) and `language` (the item's language, else `en`), when designations are listed (by default, or `designation` asked for). A code that is not a literal property of the catalog refuses the file | -| `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). `code` may also name a filter the file's grammar defines. A reader applies the list to every filter a request names (the JS reader in `engine/compile.js` `checkListedFilter`); it never refuses the file for having one. An entry may also name `property` (the stored literal property the filter reads: `=` / `in` select the concepts whose value is the filter value) and `where` (`{property code: value}` that must also hold) | - -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`. - -## Order - -Two plain-text meta keys say how a reader orders what no rule of its own lists: - -| key | values | default | meaning | -|---|---|---|---| -| `linkOrder` | `property`, `seq`, `property-seq`, `target-int` | `property` | the order of a concept's links in `$lookup`: `property` by property id, role group, target code; `seq` by `link.seq` (none: 0), then property, group, target code; `property-seq` by property, `link.seq`, target code; `target-int` by the target code as a number, `link.seq`, property, target code. Codes compare as binary text. ICD-11 files `property-seq`, OMOP `target-int`, LOINC `seq` | -| `searchTieBreak` | `rank`, `display`, `code`, `code-length` | none | the order of text-search hits of equal score: `rank` the stored order (`ix_order` `rank`; by concept id where there is none); `display` the display (String.localeCompare), then the stored order; `code` the code as binary text; `code-length` the code's length, then the code as binary text (numeric order for numeric codes such as SCTIDs); absent: concept id. SNOMED CT `code-length`, ICD-11 `rank`, LOINC `display`, RxNorm `code` | - -The JS reader obeys `linkOrder` in the `$lookup` of a system with no adapter of its own; its LOINC -and RxNorm adapters list `$lookup` properties in the order of the providers they follow (their -property lists, `dialects.js` / `provider.js`), which no value of the key describes. - -Per property: `filter_ops` (JSON list of the operators a filter on it accepts; RxNorm TTY, STY, SAB -and the relationships: `=`, `in`) and `report`, when `$lookup` and expansions report it: `never` (not -by `$lookup`, asked for or not, nor on expansions, nor among the declared properties: a filter only -where `filterable = 1`, hidden altogether where not), `named` (`$lookup` returns it only when the -request names it or asks for `*`, not by default), `always` (also on every expansion row), NULL (the default: `$lookup` -reports it by default and when asked for). RxNorm files set `never` on SUPPRESS and the `@` storage codes and `named` on the relationships ; ICD-11 files set -`named` on `child` and `browserUrl`, `never` on `residual` (a filter only), and `always` on -`classificationCode` in MMS and ICF; NDC files `never` on `kind` (a filter only). A filter-only property is `never` with `filterable = 1`: one value, as -filterability is the separate `filterable` column. - -`property.named_links` (0 or 1, default 0): 1 = the property's links are read only where the property -is named (a `$lookup` asking for it, a filter, an ECL refinement); where no property is named they are -left out (its literals follow `report` as usual). SNOMED CT files set it on every shape `both` -attribute (one with relationship rows and concrete values). The links a reader leaves out where no -property is named are those of the closure sources and the `named_links = 1` properties. - -How a property is reported and asked for (three nullable columns; NULL: absent): - -| column | meaning | default | -|---|---|---| -| `reported_as` | the name it is reported under (`$lookup`, expansion rows) and asked for by | its `code` | -| `also_asked_as` | JSON list of further names a request may ask for it by; it is still listed under `reported_as` (or `code`) | `[]` | -| `true_value` | reported as a boolean: `true` when its value (a link's target code, a literal's value) equals this, else `false` | its own value | - -A request asks for a property by its reported name or a name in `also_asked_as`, or by `*`; `report` -applies under the reported name. SNOMED CT files: `116680003` reported as `parent`; `moduleId` also -asked for as `module`; `definitionStatusId` reported as `sufficientlyDefined`, true for -`900000000000073002`, `report` `named`. No other system sets them. Readers keep no table of names -by system. - -Designations are listed in `item.rank` order (unranked last), then item order; the LOINC importer -writes ranks in cs-loinc.js's order (by use, en-US first). - -SNOMED CT files store each concept's semantic tag as a literal `semanticTag` (string, `filterable = -0`, `report = 'named'`, one value per concept that has one): 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 `)`. Readers report it like -any property and derive nothing. Answer change: on installed SNOMED CT files this rule differs from the earlier JS provider's -regular expression `/\(([^()]+)\)\s*$/` on 3 concepts per edition (nested brackets) and 94 in the UK -editions (nested brackets and trailing spaces), as counted by the other implementation; for those -concepts `$lookup`'s `semanticTag` changes (to the stored value). - -Filter and presentation facts (nullable columns; NULL or 0: absent): - -| column | meaning | written by | -|---|---|---| -| `selects_members` | `=` / `in` on it select the members of the lists it links to (`in`: the union of `=`) | LOINC `answers-for` | -| `name_any_case` | a filter may name the property in any case | RxNorm `TTY`, `SAB`, `STY` | -| `value_any_case` | filter values match its stored values in any case | LOINC, RxNorm, SNOMED CT literals | -| `default_value` | the value of a concept with no row of it (a filter `=` on it selects those too) | LOINC `STATUS` `NotStated` | -| `match_display` | a link filter value may be the target's display (case-folded) | LOINC links | -| `value_system` | an identifier property's values are codes of this system | SNOMED CT scheme 30051010000102 `http://loinc.org` (reported as `loinc`) | -| `presentation` | JSON `{"value"?: "code"\|"string"\|"display"\|"coding", "parts"?: ["description"\|"code-display"\|"partCode"]}`: how a value is reported | SNOMED CT links `{"parts": ["description", "code-display"]}` (is-a `["description"]`), concrete literals `{"parts": ["code-display"]}`; LOINC `CLASS` `{"value": "display", "parts": ["partCode"]}`, literals `{"value": "string"}`, `CLASSTYPE` `{"value": "string", "parts": ["description"]}`, relationships `{"parts": ["description"]}` | - -`concept in X, Y`: a concept that defines a record relation with members (a reference set) -contributes its members, any other concept itself. A file with no hierarchy property answers -`$subsumes` not-subsumed (the same code too) and has no ancestors (`$closure`). - -A filter names a property by its code, by its code in any case (`name_any_case`), or by a name in -`also_asked_as` (LOINC `Answer` as `answer-list`). LOINC files have a catalog row for every -relationship type cs-loinc.js knows (a type without rows selects nothing) and a literal `copyright` -(`LOINC` or `3rdParty`, `report = 'never'`). The JS reader applies `presentation` in the generic -`$lookup`; its SNOMED CT and LOINC `$lookup` adapters still form those values in code. It matches -literal values without case for every property (`value_any_case` is written but changes nothing in -the JS reader), and its LOINC filter grammar still selects answer-list members (`selects_members`). - -`property.role = 'status'`: the literal that holds the concept's status (at most one per system): -every row reads it (the provider's `getStatus()`), and `$lookup` lists it by default under its name. -LOINC files: `STATUS`. - -## Word index - -`ix.ix_word.names` says which names the word index holds, and so which names a reader's text search -reads (the stored index or, where a reader does without it, its own built from the same names): - -```json -{"display": "en", "items": {"active": true, "designations": true, "excludeUses": ["RELATEDNAMES2"], "language": "en", "conceptsWith": "SUPPRESS"}, "counts": true} -``` - -- `display` (a language tag, optional): each concept's non-empty `concept.display`, under this - language. Absent: displays are not names. -- `items` (object, optional; absent: items are not names): the items of the served system - (`item.cs_id` = the served `cs_id`), filtered by `active` (bool, default false: only `active = 1`), - `designations` (bool, default false: only designations, `kind = 0 OR use_id IS NOT NULL`), - `excludeUses` (list of `item_use.code`, default `[]`: not the items with one of these uses), - `includeUses` (list of `item_use.code` and/or `null`, optional: only the items with one of these - uses, `null` meaning an item without a use; absent: every use; combines with the others), - `conceptsWith` (a property code, optional: only the items of concepts with a row of that property, - active or not, in the table its catalog shape says; a code not in the catalog selects nothing) and - `language` (a tag, optional: every item under it; absent: the item's own language, NULL -> - `code_system.default_language`, then `en`). -- `counts` (bool, default false): the row with word `''` holds per-concept distinct-word counts. - -Languages are compared by primary subtag. A value with any other field is malformed. The importers -write: - -| system | `ix.ix_word.names` | -|---|---| -| SNOMED CT | `{"items": {"active": true, "designations": true}, "counts": true}` | -| LOINC | `{"display": "en", "items": {"designations": true, "excludeUses": ["RELATEDNAMES2"]}}` | -| RxNorm | `{"items": {"designations": true, "conceptsWith": "SUPPRESS", "language": "en"}}` | -| ICD-11 | `{"items": {"designations": true, "includeUses": [null, "indexTerm", "inclusion", "fullySpecifiedName"]}}` | -| other systems (NDC, OMOP, UNII, ...) | `{"items": {"designations": true}}` | - -A file without the key has no names to search (text search matches codes only), whatever its -system: no reader holds a table of systems for it. The index builder keeps the key across a -rebuild, and builds no word index for a file without it. - -`ix.ix_word.stemmers`: for each language of the word index, the stemmer that made its `stem` column, -an open string: `none` (a word is its own stem), `natural:` (a stemmer class of the `natural` -package: `natural:PorterStemmer` for en, `natural:PorterStemmerDe`, `...Es`, `...Fa`, `...Fr`, -`natural:StemmerId`, `...It`, `...No` for nb / nn / no, `...Nl`, `...Pt`, `...Ru`, `...Sv`, `...Uk`), -`snowball:` (a Snowball algorithm: `snowball:german`, ...). A reader that cannot -reproduce a language's stemmer searches that language without the stored index (the JS reader -builds the names of that language in memory on the first search); other languages keep using it. A -file without the key (or without `ix.ix_word.names`) is searched without its stored index. - -The counts row: for each concept id 0..N an unsigned 16-bit count, little-endian, `2 * (N + 1)` -bytes, written and read little-endian on every host. - -## How each terminology maps - -| source | becomes | -|---|---| -| SNOMED CT concept | `concept`; module and definition status as links `moduleId` / `definitionStatusId`, effectiveTime as a literal (filterable, not refinable: ECL concept filters and the FHIR `moduleId` filter name them) | -| SNOMED CT description, text definition | `item` (external id = SCTID, use = type); the display from the edition's display refsets, then any preferred synonym, the FSN, the first description | -| SNOMED CT relationship (inferred, active and inactive), concrete value | `link` (group, seq = row order) / `literal`; one property may have both (`both`) | -| SNOMED CT language refset | `record` (role `language`, target = acceptability); `item.rank` derived with `meta` `displayContexts` | -| SNOMED CT other refsets (on concepts or on descriptions) | `record` with the field schema (effectiveTime, moduleId, the refset's own columns); members in `ix_set` kind 7 | -| SNOMED CT alternate identifier | `identifier` (`resolves = 0`) | -| SNOMED CT `child` | catalog row `inverse_of` is-a | -| LOINC terms, parts, answer lists, answers, hierarchy-only nodes | `concept`; designations as items | -| LOINC part links, CLASS, parent, Answer (ordered, seq = SequenceNumber), answers-for | `link` | -| LOINC PATH_TO_ROOT | `link` under `ancestor`, the hierarchy's `closure_from` | -| LOINC `child`, `AnswerList` | catalog rows `inverse_of` parent and of the union of Answer and answers-for | -| LOINC properties, STATUS, CLASSTYPE labels | `literal`, `value_label` | -| LOINC key order and walk | `ix_order` (derived-by-importer) | -| RxNorm RXCUI with an RxNorm atom (and archived ones) | `concept`; its RxNorm atoms as items (external id = RXAUI, use = TTY); an archived concept (only in RXNATOMARCHIVE) is inactive and its archive atoms are items with `active = 0`, still its designations | -| RxNorm TTY, SAB, SUPPRESS, STY | `literal` on the concept | -| RxNorm RXNREL concept rows | `link` under the RELA; a REL is the union of its RELAs (`RELA@REL` where a RELA occurs under two RELs; `@REL` for rows with none) | -| RxNorm RXNREL atom rows (option `atomRelationships`) | `identifier` value RXAUI1 -> the concept of RXAUI2, one per row under its pair `AUI::`; `AUI:` and `AUI:` are unions of the pairs; `by_subject = 0` (read by value only) | -| ICD-11, NDC (files built by other readers of this format) | short codes `identifier resolves = 1`, 11-digit NDC forms `resolves = 2` (a form shared by two packages: `resolves = 0` on the package that loses); post-coordination axes as relation `postcoordinationAxis` (seq = axis order; fields axis, axisCode, required, allowMultiple, valueSet) and their roots as relation `postcoordinationRoot` (target = root; field axisSeq); scale value sets derived from those records, not stored; definitions as kind 1 items without a use; the Foundation entity of an MMS or ICF concept as a `mapping` row | - -## How filters and ECL find their rows - -A filter name resolves to one catalog row (base file, then supplements in order). The row picks the path: - -| catalog field | what the compiler does | read | -|---|---|---| -| `shape = 'link'` | `=` / `in`: the property = value set of each value's concept; `exists`: has property; `regex`: the targets' displays | `ix_set` 5 / 6 | -| `shape = 'literal'` (+ `fhir_type`, `value_label`) | the stored values that match (no case; labels to values; search prefixes on numbers and dates) | `ix_set` 5 keys | -| `shape = 'both'` | a code of the file: the link set; else (and `#n`, quoted) the literal sets | `ix_set` 5 by value kind | -| `shape = 'union'` | the union of the members' sets | `ix_set` per member | -| `inverse_of` | the reversed properties from the value's concepts; `exists` one set | `link` by subject; `ix_set` 6 | -| `closure_from`, `subsumption` | hierarchy filters and ECL `<`, `<<`, `>`, `>>`, `!` | `ix_set` 3-6; `link`; `ix_in` | -| `ordered` | a list's members in seq (LOINC answer lists) | `link` by subject | -| `role = 'language'` | display ranking, `{{ D dialect }}`, acceptability | `record` | -| `shape = 'record'` | `^ R`, `concept in R`; `{{ M field op v }}` over the stored rows (node fields compared as node ids) | `ix_set` 7; `record` | -| `shape = 'identifier'` | `mapped: exists`, alternate identifiers, codes that are identifiers (`resolves > 0`) | `identifier` by property and value; `identifier_code`; `ix_by_subject` (`by_subject`) | -| `refinable`, `wildcard` | ECL attribute names; `*` | the attribute's sets and links | - -What stays in each system's adapter (`dialects.js`, `snomed.js`, `provider.js`) is value grammar and -upstream naming: LOINC's filter names (`answers-for`, `LIST`, `copyright`, `ancestor`, -`STATUS = NotStated`) and its answer-list order; RxNorm's `CUI:` / `AUI:` prefixes and the live -domain (concepts with a SUPPRESS literal); SNOMED CT SCTID grammar, concept filter operators, ECL -description type and dialect aliases, history profiles, the English dialect display rules; each -system's text-search names and ranking; the $lookup property lists and order. - ## Importers ``` @@ -430,23 +681,20 @@ 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 | |---|---|---| | 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) | +| RxNorm `REL` / `RELA = AUI:` | follows RXNREL's atom-level rows of every source | 422 FILTER_NOT_UNDERSTOOD (no filter row takes `AUI:`) | | 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 | +| LOINC `LIST = LL...` in `$expand` | answers in the order they first appear in the release's answer-list file | the list's sequence (`then_link` order) | diff --git a/tx/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js deleted file mode 100644 index 97882dc17..000000000 --- a/tx/sqlite-v2/dialects.js +++ /dev/null @@ -1,301 +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 regexUtilities = require('../../library/utils/regex-utilities'); - - -/** - * 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_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); - }, - 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 }; - } - // (relationship types without rows, STATUS NotStated, copyright and answer-list: catalog facts, - // compile.js: property rows without rows, default_value, a stored literal, also_asked_as) - 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' }; - } - // 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', - 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; - // the catalog name the filter means (name_any_case: TTY, STY, SAB in any case) - const name = S.resolveFilterName(prop); - 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); concept / code and the rest: = and in - const row = S.catalog.get(name); - 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 (row && row.shape === 'literal' && row.filterable) { - // a literal (TTY, STY, SAB): the generic rule matches it - const v = op === '=' ? vals[0] : value; - if (prop !== name || v !== value) return c.filter(name, 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', - 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 }); - }, - 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 }; - } - // display: regex only (behaviour.displayRegex: compile.js), as cs-snomed.js - if (prop === 'display' && op !== 'regex') 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 3cb70cb01..245811783 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,15 @@ 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] }); +} class FilterError extends Error { constructor(message, extra = {}) { @@ -33,13 +43,13 @@ 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; this.codeMap = new Map(); // codes resolved while compiling this request (one statement for all) } @@ -60,11 +70,11 @@ class Compiler { return this.ids([c]).get(c); } - /** concept ids for a filter value: the code, or the targets with that display where the property says so (match_display) */ - valueIds(v, p = null) { + /** 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 p && p.matchDisplay ? this.store.displayIdsNoCase(v) : []; + return asDisplay ? this.store.displayIdsNoCase(v) : []; } // ---- compose ------------------------------------------------------------------------------- @@ -98,7 +108,7 @@ class Compiler { // 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 }); return { parts: parts.parts.map((p) => ({ node: { t: 'xlate', from: other, node: p.node, label: 'from ' + other.version }, order: null })) }; @@ -115,14 +125,18 @@ class Compiler { } 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) - // behaviour.wholeSystem: list it, list nothing, or refuse; wholeActiveOnly: its active concepts - const whole = this.store.behaviour.wholeSystem; - if (whole === 'refuse') throw new FilterError(`The code system ${this.store.system} cannot be expanded as a whole`); - if (whole === 'empty') parts.push({ node: { t: 'empty' }, 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: this.store.behaviour.wholeActiveOnly ? { t: 'and', items: [all, { t: 'active' }], whole: true } : all, order: null }); + parts.push({ node: S.compat.wholeSystemIncludeActiveOnly ? { t: 'and', items: [all, { t: 'active' }], whole: true } : all, order: null }); } return { parts }; } @@ -142,12 +156,12 @@ class Compiler { return { parts }; } - /** the concepts a filter can select at all (behaviour.domain: the concepts with that property) */ + /** the concepts a filter can select at all: the listed ones (not unlisted: README.md "Concept status") */ domain(node) { - const code = this.store.behaviour.domain; - if (code == null) return node; - const live = { t: 'set', kind: KIND.hasProp, pid: this.store.catalog.get(code).id, value: 0 }; - 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 */ @@ -162,111 +176,152 @@ class Compiler { return node; } - // ---- filters ------------------------------------------------------------------------------- + // ---- filters --------------------------------------------------------------------------- /** - * A filter as a request names it. Where the file lists the only filters the system understands - * (meta behaviour.filters), a filter, operator or value not in the list is FILTER_NOT_UNDERSTOOD; - * the list is checked once, for the filter as requested (not the filters a rule rewrites it into) + * 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._inFilter) return this._filter(prop, op, value); - this._inFilter = true; - try { - this.checkListedFilter(prop, op, value); - return this._filter(prop, op, value); - } finally { - this._inFilter = false; + const hit = this.store.filterRow(prop, op); + if (!hit) { + const n = this.term.layers ? this.term.layers.filterNode(this, prop, op, value) : null; + if (n) return n; + throw notUnderstood(prop, op, value); } + return this.rowFilter(hit.row, hit.capture, prop, op, value); } - /** - * A listed filter over a stored literal property: = (or in) selects the concepts whose value of - * `property` is the filter value, and every `where` property: value also holds - */ - listedFilter(f, op, value) { - const lit = (code, v) => { - const p = this.store.catalog.get(code); - if (!p) throw new FilterError(`The filter "${f.code}" reads the property ${code}, which the catalog does not have`); - return this.propertyFilter(p, '=', v); + /** 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(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 (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(); + } + if (row.prefix != null) { + if (!vals.every((v) => v.startsWith(row.prefix))) throw nu(); + vals = vals.map((v) => v.substring(row.prefix.length)); + } + // 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 vals = op === 'in' ? splitList(value) : [String(value)]; - const sel = vals.length === 1 ? lit(f.property, vals[0]) : { t: 'or', items: vals.map((v) => lit(f.property, v)) }; - const where = Object.entries(f.where || {}).map(([k, v]) => lit(k, v)); - return where.length ? { t: 'and', items: [sel, ...where] } : sel; + 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; + node = { t: 'propOf', pids: pidsOf(row.then), sources: of, ...(row.then.ordered ? { order: 'lists', of } : {}) }; + } + return node; + } + + /** 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'; } - /** meta behaviour.filters: [{code, operator: [...], values?: [...], property?, where?}] or null (every filter the catalog allows) */ - checkListedFilter(prop, op, value) { - const listed = this.store.behaviour.filters; - if (!listed) return; - const f = listed.find((x) => x.code === prop); - const values = op === 'in' || op === 'not-in' ? splitList(value) : [String(value)]; - if (!f || !f.operator.includes(op) || (f.values && !values.every((v) => f.values.includes(v)))) { - throw new FilterError(`The filter "${prop} ${op} ${value}" is not understood or supported`, { notUnderstood: [prop, op, value] }); + /** + * 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 { 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); + } } } - _filter(prop, op, value) { - // a listed filter that reads a stored literal property (behaviour.filters property / where) - const listed = this.store.behaviour.filters ? this.store.behaviour.filters.find((x) => x.code === prop && x.property) : null; - if (listed) return this.listedFilter(listed, op, value); - if (this.dialect.filter) { - const n = this.dialect.filter(this, prop, op, value); - if (n) return n; + /** 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.shape === 'identifier') { + if (op !== 'exists') 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 (prop === 'display' && op === 'regex' && this.store.behaviour.displayRegex === 'designations' && !this.store.filterProp('display')) { - // behaviour.displayRegex 'designations': any active designation of a display use (item_use.role - // fsn or synonym) in the one language the request chooses (term.lang) matches the whole term - const lits = this.store.hasFts ? requiredLiterals(value) : []; - const lang = (this.term && this.term.lang) || 'en'; - const uses = [...this.store.uses.values()].filter((u) => u.role === 'fsn' || u.role === 'synonym').map((u) => u.code); - return { t: 'desigRegex', re: String(value), lang, uses, ...(lits.length ? { lits } : {}), label: `display (${lang}) ~ /${value}/` }; - } - if (prop === 'display' && !this.store.filterProp('display')) return this.displayFilter(op, value); - // FHIR's concept status, where the file lists it as a filter (behaviour.filters code 'inactive') - if (prop === 'inactive' && !this.store.filterProp('inactive') && op === '=' && (this.store.behaviour.filters || []).some((x) => x.code === 'inactive')) { - if (value !== 'true' && value !== 'false') throw new FilterError(`Invalid filter value: ${value}`); - return value === 'true' ? { t: 'inactive' } : { t: 'active' }; - } - if (prop === 'designation' && !this.store.filterProp('designation')) { - // R5 CodeSystem 4.8.15 generic filters: designation = / regex; the display counts as one - if (op === '=') return { t: 'desigMatch', eq: String(value), label: `designation = "${value}"` }; - if (op === 'regex') return { t: 'desigMatch', re: String(value), label: `designation regex /${value}/` }; - throw this.notSupported(prop, op, value); - } - if (prop === 'concept' || prop === 'code' || (this.store.hierarchy && prop === this.store.hierarchy.code && op !== '=' && op !== 'in' && op !== 'exists')) { - return this.conceptFilter(op, value, prop); - } - // the property's catalog entry is its access path (store filterProp), by its name in any case - // or another name it is asked for by, where the catalog says so - const p = this.store.filterProp(this.store.resolveFilterName(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); + 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(p, op, value); + return this.propertyFilter(d, op, v, row); } - /** display = / in / regex (the concept's display; FHIR's "display" filter property) */ - displayFilter(op, value) { + /** 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); - } - - 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}`); + throw notUnderstood(prop, op, value); } /** @@ -293,17 +348,17 @@ 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]); + // 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 ids = uniqSorted(vals.map((v) => m.get(v)).filter((x) => x != null)); const n = this.conceptIn(ids); return op === 'in' ? n : { t: 'minus', a: { t: 'all' }, b: n }; } if (op === 'regex') return { t: 'text', field: 'code', re: value }; - if (op === 'exists') throw this.notSupported(prop, op, value); + 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 }; @@ -312,10 +367,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.store.behaviour.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); } } @@ -329,9 +384,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': @@ -339,16 +396,17 @@ 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, p)))); + 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)); - // property.default_value: a concept with no row of the property has that value - if (p.defaultValue != null && vals.includes(p.defaultValue)) { + 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] }; } } @@ -356,19 +414,28 @@ class Compiler { } 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); } } @@ -406,7 +473,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); @@ -420,30 +487,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, p))) }); + 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]; } @@ -463,9 +538,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; } } @@ -596,8 +671,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) }); @@ -951,4 +1026,4 @@ function collectIds(n, out) { } } -module.exports = { Compiler, FilterError, Unsupported, splitList, uniqSorted, litSets, pidsOf }; +module.exports = { Compiler, FilterError, Unsupported, notUnderstood, splitList, uniqSorted, litSets, pidsOf }; diff --git a/tx/sqlite-v2/engine/evaluate.js b/tx/sqlite-v2/engine/evaluate.js index eae1d4482..3565d00f4 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,7 +275,7 @@ 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 'search': return (yield* S.searchTextG(node.text, st, node.lang || null)) || new RoaringBitmap32(); case 'group': return yield* this.filterG(node, yield* this.matG({ t: 'and', items: node.attrs.map(attrNode) })); case 'attrCard': { const has = yield* this.matG(node.base); // at least one occurrence diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js index a01f3635d..0c64f5bc7 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -8,9 +8,10 @@ const Database = require('better-sqlite3'); const { SqliteV2Factory } = require('./provider'); const { SnomedV2Factory } = require('./snomed'); const { checkFormat } = require('./store'); +const { readMeta } = require('./meta'); /** - * The code grammars this server implements, by name (meta behaviour.grammar): the factory that + * 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. */ @@ -23,7 +24,7 @@ const GRAMMARS = Object.freeze({ 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} (behaviour.grammar), which this server does not implement`); + 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 */ @@ -32,7 +33,9 @@ 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(); } diff --git a/tx/sqlite-v2/integrity.js b/tx/sqlite-v2/integrity.js index 9f91a7002..9f5a746e6 100644 --- a/tx/sqlite-v2/integrity.js +++ b/tx/sqlite-v2/integrity.js @@ -20,6 +20,7 @@ const CATALOG = Object.freeze([ ['property', 'id'], ['property_member', 'parent_id, child_id'], ['item_use', 'use_id'], + ['filter', 'id'], ['value_label', 'property_id, value'], ]); diff --git a/tx/sqlite-v2/layers.js b/tx/sqlite-v2/layers.js index bebeb704f..537009455 100644 --- a/tx/sqlite-v2/layers.js +++ b/tx/sqlite-v2/layers.js @@ -284,7 +284,7 @@ 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); + const node = new Compiler({ store: l.store, grammar: {} }, { stats: compiler.stats }).propertyFilter(def, op, value); return { t: 'layer', layer: l, node, label: `supplement ${l.info.url} ${prop} ${op} ${value}` }; } return null; diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 3b45b2dd3..6b39bb3bd 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -1,10 +1,14 @@ 'use strict'; -// The meta table of a terminology file (tx-terminology/1; tx/sqlite-v2/README.md "Meta"): +// 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. +// 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. +// 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. @@ -14,58 +18,138 @@ const FORMAT = 'tx-terminology/1'; -/** the features a file may require (README.md "requires") */ -const KNOWN_FEATURES = Object.freeze(['identifier-text']); +/** 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']); +const WRITTEN_FEATURES = Object.freeze(['identifier-text', 'fhir-reading']); -/** the FHIR filter operators (behaviour.filters, property.filter_ops) */ +/** the marker of this revision */ +const REVISION = 'fhir-reading'; + +/** the FHIR filter operators (filter.operators) */ const FILTER_OPERATORS = Object.freeze(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'exists']); +/** 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', '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]*)$/; -/** one entry of behaviour.filters: {code, operator: [FHIR filter operators, at least one], values?: [strings]} */ -const isFilterSpec = (f) => isPlainObject(f) && onlyKeys(f, ['code', 'operator', 'values', 'property', 'where']) && isString(f.code) - && isStrings(f.operator) && f.operator.length > 0 && f.operator.every((o) => FILTER_OPERATORS.includes(o)) - && (f.values === undefined || isStrings(f.values)) - && (f.property === undefined || (isString(f.property) && f.property !== '')) - && (f.where === undefined || (isPlainObject(f.where) && Object.values(f.where).every(isString))); +/** 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)))); -/** - * ix.ix_word.names: which names the word index holds, and so which names text search reads - * (README.md "Word index"): {display?: tag, items?: {active?, designations?, excludeUses?, - * conceptsWith?, language?}, counts?} - */ -const isNames = (v) => isPlainObject(v) && onlyKeys(v, ['display', 'items', 'counts']) - && (v.display === undefined || (isString(v.display) && v.display !== '')) - && (v.counts === undefined || isBool(v.counts)) - && (v.items === undefined || (isPlainObject(v.items) && onlyKeys(v.items, ['active', 'designations', 'excludeUses', 'includeUses', 'conceptsWith', 'language']) - && (v.items.active === undefined || isBool(v.items.active)) - && (v.items.designations === undefined || isBool(v.items.designations)) - && (v.items.excludeUses === undefined || isStrings(v.items.excludeUses)) - && (v.items.includeUses === undefined || (Array.isArray(v.items.includeUses) && v.items.includeUses.every((u) => u === null || (isString(u) && u !== '')))) - && (v.items.conceptsWith === undefined || (isString(v.items.conceptsWith) && v.items.conceptsWith !== '')) - && (v.items.language === undefined || (isString(v.items.language) && v.items.language !== '')))); +/** 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; } }; +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, isString) && opt(t.title, isString) && opt(t.description, isString))); +const isImplicitValueSets = (v) => Array.isArray(v) && v.every(isTemplate); + +/** implicitMaps: {base?, maps?, used?, associations?} */ +const isImplicitMaps = (v) => isPlainObject(v) && onlyKeys(v, ['base', 'maps', 'used', '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.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, + 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), + 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, unknownCodeMessage: null, + filterUnknownCodeMessage: null, filterRejectMessage: null, missingValueFiltersAs: {}, 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. - * The behaviour.* keys are README.md "Behaviour settings". - */ +/** 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) && new Set(v).size === v.length, []), + 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 @@ -75,76 +159,34 @@ const KEYS = Object.freeze({ 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), {}), - // the only properties an expansion of all properties lists, in order, with their URIs (ICD-11 files) - propertyUris: json((v) => Array.isArray(v) && v.every((x) => Array.isArray(x) && x.length === 2 && isString(x[0]) && x[0] !== '' && isString(x[1]) && x[1] !== ''), null), '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, {}), // 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), - 'ix.ix_word.names': json(isNames, null), - // order (README.md "Order"): plain text values - linkOrder: text((v) => ['property', 'seq', 'property-seq', 'target-int'].includes(v), 'property'), - searchTieBreak: text((v) => ['rank', 'display', 'code', 'code-length'].includes(v), null), - // behaviour settings - // an open string: a reader refuses a grammar it does not implement (index.js) - 'behaviour.grammar': json((v) => v === null || (isString(v) && v !== ''), null), - 'behaviour.filters': json((v) => v === null || (Array.isArray(v) && v.every(isFilterSpec)), null), - 'behaviour.expansionOrder': json((v) => ['ids', 'stored', 'stored-self-first'].includes(v), 'ids'), - 'behaviour.lookupName': json((v) => v === 'name' || v === 'title', 'name'), - 'behaviour.versionAlgorithm': json((v) => v === null || isString(v), null), - 'behaviour.designationUses': json((v) => v === 'keep' || v === 'drop', 'keep'), - 'behaviour.distinctDesignationTexts': json(isBool, false), - 'behaviour.preferredForLanguage': json(isBool, false), - // identifier-aliased codes: {parameter?, extension?, literals?} (README.md "Behaviour settings") - 'behaviour.aliases': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['parameter', 'extension', 'literals']) - && (v.parameter === undefined || (isString(v.parameter) && v.parameter !== '')) - && (v.extension === undefined || (isString(v.extension) && v.extension !== '')) - && (v.literals === undefined || (isPlainObject(v.literals) && Object.values(v.literals).every(isString)))), null), - // the property whose rows mark the concepts answers select (others are in the file, never selected) - 'behaviour.domain': json((v) => v === null || (isString(v) && v !== ''), null), - // the order of $lookup's properties: {ranks: {name: int}, concept?: int, other: int, byCode?: bool} - 'behaviour.lookupOrder': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['ranks', 'concept', 'other', 'byCode']) - && isPlainObject(v.ranks) && Object.values(v.ranks).every(Number.isSafeInteger) && Number.isSafeInteger(v.other) - && (v.concept === undefined || Number.isSafeInteger(v.concept)) && (v.byCode === undefined || isBool(v.byCode))), null), - // implicit ConceptMaps over mapping rows: {base, maps: [[target system, key]], used?} - 'behaviour.implicitMaps': json((v) => v === null || (isPlainObject(v) && onlyKeys(v, ['base', 'maps', 'used']) && isString(v.base) && v.base !== '' - && Array.isArray(v.maps) && v.maps.every((m) => Array.isArray(m) && m.length === 2 && isString(m[0]) && isString(m[1]) && m[1] !== '') - && (v.used === undefined || (isString(v.used) && v.used !== ''))), null), - // plain answer facts (README.md "Behaviour settings") - 'behaviour.displayRegex': json((v) => v === 'display' || v === 'designations', 'display'), - 'behaviour.generalizesExcludesSelf': json(isBool, false), - 'behaviour.wholeActiveOnly': json(isBool, false), - 'behaviour.lookupDefinition': json(isBool, true), - 'behaviour.keepDuplicateDesignations': json(isBool, false), - 'behaviour.plainDesignationIsDisplay': json(isBool, false), - 'behaviour.wholeSystem': json((v) => ['list', 'empty', 'refuse'].includes(v), 'list'), - 'behaviour.locateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), - 'behaviour.filterLocateMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), - 'behaviour.filterCheckMessage': json((v) => v === null || (isString(v) && v.includes('{code}')), null), - 'behaviour.versionFormat': json((v) => v === null || v === 'MMDDYYYY', null), - 'behaviour.inactiveDesignations': json((v) => ['omit', 'status', 'plain'].includes(v), 'omit'), - 'behaviour.displayDesignation': json((v) => ['none', 'first', 'distinct'].includes(v), 'first'), - 'behaviour.deprecatedStatus': json(isStrings, []), - 'behaviour.declaresProperties': json(isBool, true), - 'behaviour.implicitValueSets': json((v) => v === null || (isString(v) && v !== ''), null), - 'behaviour.displayLanguage': json((v) => v === null || (isString(v) && v !== ''), null), - 'behaviour.expansionLimit': json(isCount, 0), - // the text search algorithm (text-index.js TEXT_SEARCHES); an open name, null: the generic one - 'behaviour.textSearch': json((v) => v === null || (isString(v) && v !== ''), null), - 'behaviour.lookupCopyright': json(isBool, false), - 'behaviour.lookupDesignationCode': json((v) => v === null || (isString(v) && v !== ''), 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({}); -/** key patterns of the same kind: statistics of an ix_key index an importer writes (SNOMED CT normal forms) */ -const WRITER_PATTERNS = Object.freeze([[(k) => /^ix\.ix_key\.[^.]+\.stats$/.test(k), json(isPlainObject, null)]]); +const WRITER_PATTERNS = Object.freeze([]); const isProvenance = (key) => key.startsWith('provenance.'); @@ -154,22 +196,42 @@ function specOf(key) { 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 for - * the behaviour and requires keys). Throws, naming key and value, on a malformed value of a - * known key, and on a required feature this reader does not know. + * 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[], behaviour: object, linkOrder: string, - * searchTieBreak: string|null, ignored: string[]}} + * @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 meta) { + 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?)`); @@ -184,19 +246,21 @@ function readMeta(meta, file, opts = {}) { 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 requires = values.get('requires') || []; - 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(', ')})`); - } const get = (key) => (values.has(key) ? values.get(key) : KEYS[key].default); - const behaviour = {}; - for (const key of Object.keys(KEYS)) if (key.startsWith('behaviour.')) behaviour[key.substring('behaviour.'.length)] = get(key); - return { - values, requires, ignored, - behaviour: Object.freeze(behaviour), - linkOrder: get('linkOrder'), - searchTieBreak: get('searchTieBreak'), - }; + // 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, KEYS, WRITER_KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, FILTER_OPERATORS, FORMAT }; +module.exports = { + readMeta, orderOf, KEYS, WRITER_KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, FILTER_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 ed3e8b530..b6ea45d65 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 d48f95a37..4f4c678b4 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 @@ -17,19 +17,19 @@ const { BaseCSServices } = require('../cs/cs-base'); 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 } = require('./dialects'); +const { Compiler, FilterError, 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'); -const { sctTextSearchG, sctTextLanguages, rxTextSearchG, loincTextSearchG, genericTextSearchG, rxSearchable, textSearchMode } = 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]; const PAGE_ROWS = 2000; // a processSelection page's rows read per statement, with a pause between /** a concept handle: id (concept_id), code; row/designations filled lazily or by a page batch */ @@ -40,7 +40,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) } } @@ -82,8 +82,8 @@ class SqliteV2Provider extends BaseCSServices { this.f = factory; this.store = factory.store; this.engine = factory.engine; - this.dialect = factory.dialect; - this.searchMode = factory.searchMode; + // 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 || []); @@ -102,13 +102,12 @@ class SqliteV2Provider extends BaseCSServices { 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.store.domain(this._stats()) || this.store.all(); + const walked = this.store.listed(this._stats()) || this.store.all(); return walked.andCardinality(this.store.active()); } hasParents() { return !!this.store.hierarchy; } @@ -116,73 +115,108 @@ class SqliteV2Provider extends BaseCSServices { contentMode() { return this.store.cs.content || 'complete'; } versionAlgorithm() { return this.f.versionAlgorithm(); } /** - * Whether a requested version (criteria) matches the file's: by the file's versionAlgorithm - * (FHIRsmith versionMatchesByAlgorithm); a file that states none matches exactly (no guess from - * the version string) + * 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()) { - const algorithm = this.versionAlgorithm(); - if (algorithm == null) return criteria === version; - return VersionUtilities.versionMatchesByAlgorithm(criteria, version, algorithm); + if (criteria === version) return true; + return this.store.versionRule.match === 'prefix' && !!criteria && String(version).startsWith(criteria); } - isCaseSensitive() { return this.store.caseSensitive; } - /** the most codes of this system an expansion lists or walks (behaviour.expansionLimit; 0: no limit) */ - expandLimitation() { return this.store.behaviour.expansionLimit; } - /** the properties every expansion row reports (catalog report 'always') */ - mandatoryExpansionProperties() { return [...this.store.catalog.values()].filter((d) => d.report === 'always').map((d) => d.code); } - /** - * Whether a lookup (or an expansion's properties) reports a catalog property (report: 'never' not - * at all, 'named' only when the request names it or asks for *, not by default; else as the - * request's list says; dflt: whether an empty list reports it) + * 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 */ - _reports(code, props, dflt = true) { - const d = this.store.catalog.get(code); - return d ? this._reportsDef(d, props, dflt) : this._hasProp(props, code, dflt); + versionIsMoreDetailed(check, actual) { + const sep = this.store.versionRule.partial; + return !!sep && !!check && !!actual && !String(check).includes(sep) && String(actual).startsWith(check + sep); } - - /** the name a catalog property is reported under (property.reported_as, else its code) */ - _reportedName(d) { return d.reportedAs || d.code; } + 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 property: by its report value, asked for - * by its reported name or a name in also_asked_as, or by * + * 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, dflt = true) { - if (d.report === 'never') return false; - const byDefault = d.report === 'named' ? false : dflt; - if (!props || props.length === 0) return byDefault; - const names = [this._reportedName(d), ...d.alsoAskedAs].map((n) => n.toLowerCase()); - return props.some((p) => p === '*' || names.includes(String(p).toLowerCase())); + _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) => p === '*' || this._names(d).includes(String(p).toLowerCase())); + } + + /** 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 (none: a code with its description, or - * a string) + * 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 (pr && d.trueValue == null) { - const form = pr.value || ((d.kind === 'concept' || d.shape === 'link' || d.shape === 'both') ? 'code' : 'string'); - const v = form === 'display' ? { valueString: display || String(value) } : form === 'string' ? { valueString: String(value) } - : form === 'coding' ? { valueCoding: { system: this.system(), code: String(value), ...(display ? { display } : {}) } } : { valueCode: String(value) }; - const parts = [{ name: 'code', valueCode: this._reportedName(d) }, { name: 'value', ...v }]; - for (const p of pr.parts || []) { - if (p === 'description' && display) parts.push({ name: 'description', valueString: display }); - else if (p === 'code-display') parts.push({ name: 'code-display', valueString: d.display || d.code }); - else if (p === 'partCode') parts.push({ name: 'partCode', valueCode: String(value) }); - } - params.push({ name: 'property', part: parts }); + if (d.trueValue != null) { + params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueBoolean: String(value) === d.trueValue }] }); return; } - if (d.trueValue != null) { - params.push({ name: 'property', part: [{ name: 'code', valueCode: this._reportedName(d) }, { name: 'value', valueBoolean: String(value) === d.trueValue }] }); - } else if (d.kind === 'concept' || d.shape === 'link' || d.shape === 'both') { - this._addCodeProperty(params, 'property', this._reportedName(d), value, null, display); - } else { - this._addStringProperty(params, 'property', this._reportedName(d), String(value)); + 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) + */ + _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 '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; } @@ -275,13 +309,21 @@ class SqliteV2Provider extends BaseCSServices { for (const c of concepts) if (c.status === undefined && c.row) c.status = vals.has(c.id) ? vals.get(c.id) : null; } } + if (!withDesignations) { + // the language of each display (the display designation's), for a page read without its designations + const nl = concepts.filter((c) => c.displayLang === undefined && c.row && !c.desigs).map((c) => c.id); + if (nl.length) { + const langs = this.store.displayItemLanguages(nl, st); + for (const c of concepts) if (c.displayLang === undefined && c.row && !c.desigs) c.displayLang = langs.get(c.id) ?? null; + } + } if (withDesignations) { const nd = concepts.filter((c) => !c.desigs).map((c) => c.id); if (nd.length) { - // the items of a use reported as a property (item_use.reported_as) are not designations: 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) || []; } } } @@ -323,23 +365,6 @@ class SqliteV2Provider extends BaseCSServices { return () => oc.checkAndYield('sqlite-v2'); } - /** the use_id of the item use reported as a property (item_use.reported_as), which designation reads leave out, or null */ - _relatedUse() { - return this.store.reportedUse ? this.store.reportedUse.id : null; - } - - /** - * The active items of the use reported as a property (item_use.reported_as), as values of that - * property (with their language), when the request lists it (by default, by name or *) - */ - _reportedUseProperty(c, props, params) { - const r = this.store.reportedUse; - if (!r || !this._hasProp(props, r.name, true)) return; - this._needDesigs(c); - const rows = c.desigsNoRelated ? (this.store.designationRows([c.id], this._stats(), { onlyUse: r.id }).get(c.id) || []) : c.desigs; - for (const d of rows) if (d.active && d.use && d.use.reportedAs) this._addStringProperty(params, 'property', r.name, d.term, d.language); - } - async _ensure(context) { if (context == null) return null; if (context instanceof V2Concept) { @@ -379,14 +404,29 @@ class SqliteV2Provider extends BaseCSServices { this.byCode.set(n, c); } } - // behaviour.locateMessage: the reason for a code the system does not have - if (!c) return { context: null, message: this.store.behaviour.locateMessage ? this.store.behaviour.locateMessage.split('{code}').join(String(code)) : 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 + */ + _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); + } + + /** 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 @@ -413,7 +453,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; } @@ -472,60 +512,80 @@ class SqliteV2Provider extends BaseCSServices { if (!c) return null; const s = this._displayFromSupplements(c.code); if (s) return s; + // 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 + 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))); + for (const exact of [true, false]) { + for (const l of langs) for (const d of cands) if (d.language && l.matches(d.language, exact)) return d.term; + } } } return (c.row && c.row.display) || ''; } async definition(context) { - // behaviour.lookupDefinition: whether text definitions are reported - if (!this.store.behaviour.lookupDefinition) return null; + // 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: its status (the role 'status' literal) is one behaviour.deprecatedStatus lists */ + /** deprecated (README.md "Concept status"): the reading, of an active concept */ async isDeprecated(context) { - const list = this.store.behaviour.deprecatedStatus; - if (!list.length || !this.store.statusProp) return false; - const s = await this.getStatus(context); - return s != null && list.includes(s); + const set = this.store.statusSet('deprecated', this._stats()); + if (!set) return false; + const c = await this._ensure(context); + return !!c && set.has(c.id); } + /** + * The status text (README.md "Concept status"): the concept's status literal (role status) when it + * has one and it is not `active`; else `inactive` for an inactive concept; else none + */ async getStatus(context) { const c = await this._ensure(context); if (!c) return null; - // the concept's status literal, where the catalog has one (role 'status') const p = this.store.statusProp; if (p) { - if (c.status !== undefined) return c.status; - const v = this.store.literalValues([c.id], p.id, this._stats()).get(c.id); - return v === undefined ? null : v; + 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 && String(v).toLowerCase() !== 'active') return String(v); } - return c.row.active ? 'active' : 'inactive'; + return c.row.active ? null : 'inactive'; } async parent() { return null; } - /** a designation whose use's text is accepted as a display (item_use.role 'name') */ + /** a designation whose text is accepted as a display: its use's role (item_use.role display, fsn or synonym) */ isDisplay(d) { - return this.store.useRoleOf(d.use) === 'name'; + const role = this.store.useRoleOf(d && d.use); + return role === 'display' || role === 'fsn' || role === 'synonym'; } async designations(context, displays, significantOnly) { @@ -535,6 +595,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; @@ -544,53 +614,58 @@ class SqliteV2Provider extends BaseCSServices { return; } this._needDesigs(c); - // the file's facts (README.md "Behaviour settings"): whether the display is listed as the first - // designation (displayDesignation), how inactive items are listed (inactiveDesignations), whether - // a designation with no use equal to the display is the display (plainDesignationIsDisplay); - // designations in item rank, then item order - const b = this.store.behaviour; + const mode = this.store.compat.displayDesignation; const display = (c.row.display || '').trim(); - if (b.displayDesignation !== 'none') displays.addDesignation(true, 'active', this._displayLanguage(), null, display); - let skipped = b.displayDesignation !== 'first'; - const rows = [...c.desigs].sort((x, y) => ((x.rank ?? Infinity) - (y.rank ?? Infinity)) || (x.id - y.id)); - for (const d of rows) { - if (d.use && d.use.reportedAs) continue; - if (!d.active && b.inactiveDesignations === 'omit') continue; + 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 (!skipped && term === display) { skipped = true; continue; } - if (b.plainDesignationIsDisplay && !d.use && term === display) continue; - const status = d.active || b.inactiveDesignations === 'plain' ? 'active' : 'inactive'; - displays.addDesignation(false, status, d.language, this._useOf(d), term); + 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); } /** - * A designation's use as it is reported (map: the stored use -> the reported one): none where - * the file says so (behaviour.designationUses 'drop'); for a preferred item with no use, - * preferredForLanguage where the file says so (behaviour.preferredForLanguage) + * 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 = (u) => ({ system: u.system, code: u.code, display: u.display })) { - const b = this.store.behaviour; - if (b.designationUses === 'drop') return null; - if (d.use) return map(d.use); - return b.preferredForLanguage && d.preferred ? { ...DesignationUse.DISPLAY } : null; + if (d.use && this.store.compat.designationUse === 'source') return map(d.use); + return d.preferred ? { ...DesignationUse.DISPLAY } : null; } - /** the language of the stored display (behaviour.displayLanguage, else code_system.default_language, else en) */ - _displayLanguage() { - return this.store.behaviour.displayLanguage || this.store.defaultLanguage || this.defLang(); + /** + * The language of the display designation (README.md "The display designation"): the language of + * the first item (designation order) whose text is the display and that has a language, else + * code_system.default_language, else en + */ + _displayLanguageOf(c) { + const display = c.row ? c.row.display : null; + if (c.desigs && display != null) { + for (const d of this._ordered(c.desigs)) if (d.language && d.term === display) return d.language; + } else if (display != null) { + // a page read for its displays only: the item that gives the display's language (read with the page's rows) + if (c.displayLang === undefined) c.displayLang = this.store.displayItemLanguages([c.id], this._stats()).get(c.id) ?? null; + if (c.displayLang) return c.displayLang; + } + 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._displayLanguage(), null, d); + if (d) displays.addDesignation(true, 'active', this._displayLanguageOf(c), null, d); this._listSupplementDesignations(c.code, displays); } - - // ---- iteration -------------------------------------------------------------------------- async iterator(context) { @@ -608,21 +683,30 @@ 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') return this.store.all().toArray(); - // a system with a domain (behaviour.domain): its concepts, in the stored order (cs-rxnorm.js - // iterator(null): ORDER BY RXCUI) - const dom = this.store.domain(this._stats()); - if (dom) return this.engine._order ? this.engine._ordered(dom) : dom.toArray(); - // concepts without an active parent: the active ones where the file says so (behaviour.wholeActiveOnly) - const hid = this.store.hierarchy ? this.store.hierarchy.id : -1; - const hasParent = this.store.getSet(KIND.hasProp, hid, 0); - const base = this.store.behaviour.wholeActiveOnly ? this.store.active() : this.store.all(); - return RoaringBitmap32.andNot(base, hasParent).toArray(); + const S = this.store; + if (S.expansionLimits.wholeSystem === 'refuse') throw this._wholeSystemRefusal(); + if (S.hierarchy && S.closure != null) return S.all().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.store.domain(this._stats()) || this.store.all()).toArray(); + const ids = (this.store.listed(this._stats()) || this.store.all()).toArray(); return { ids, pos: 0, total: ids.length }; } @@ -703,182 +787,229 @@ class SqliteV2Provider extends BaseCSServices { // ---- $lookup -------------------------------------------------------------------------------- async extendLookup(context, props, params) { - const from = params.length; if (!this._trace) await this._extendLookup(context, props, params); else await this._trace.spanAsync('lookup properties', 'rows', this.system(), () => this._extendLookup(context, props, params)); - sortLookupProperties(params, from, this.store.behaviour.lookupOrder); } + /** + * $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') this._loincLookup(c, props, params); - else if (this.dialect.name === 'rxnorm') this._rxnormLookup(c, props, params); - else this._genericLookup(c, props, params); - // behaviour.lookupCopyright: the code system's copyright notice as a property + // 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 before literals before the rest, 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. + * @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); + const add = (d, kind, key, text, emit) => out.push({ d, rank: rankOf(d), kind, key, name: d.name, text: String(text), emit }); + // 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 seen = new Set(); + const addLink = (d, l) => { + const t = targets.get(l.other); + if (!t) return; + // a property lists a target once + const k = d.id + '|' + t.code; + if (seen.has(k)) return; + seen.add(k); + add(d, 0, this._linkKey(d, l, t.code), t.code, (params) => this._addReported(params, d, t.code, t.display)); + }; + for (const l of links) for (const d of byPid.get(l.p) || []) addLink(d, l); + for (const { d, l } of inverse) addLink(d, l); + // 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 rows = this._targetDisplays(links.map((l) => l.t)); - const named = links.map((l) => ({ ...l, code: l.name || (S.propsById.get(l.p) || {}).code })).filter((l) => l.code && rows.get(l.t)); - const seq = new Map((S.sequenceOf(c.id) || []).map((id, i) => [id, i])); - // answers-for: LoincAnswerListLink.csv's order, by term code as text - // the other relationships (document and radiology axes, ...): the part links file's order, by part code as text - const textOrder = (a, b) => (rows.get(a.t).code < rows.get(b.t).code ? -1 : rows.get(a.t).code > rows.get(b.t).code ? 1 : 0); - const byCode = (a, b) => ((a.code === 'answers-for' && b.code === 'answers-for') || (pos(a.code) === 50 && pos(b.code) === 50 && !seq.has(a.t) && !seq.has(b.t)) ? textOrder(a, b) : 0); - // parent and child: the built-in importer's Relationships rows' order (hierarchy-file order, a - // part's second parent among its children), when the file has it (orders.js) - const hier = S.hierarchyOrderOf(c.id); - let hierRank = null; - if (hier && hier.length) { - hierRank = new Map(); - for (let i = 0; i < hier.length; i++) hierRank.set(hier[i], i); - } - const hierOf = (l) => { - if (!hierRank || pos(l.code) !== 100) return 0; - const r = hierRank.get(((l.code === 'child' ? HIER_CHILD : 0) | l.t) >>> 0); - return r === undefined ? hier.length : r; - }; - named.sort((a, b) => (pos(a.code) - pos(b.code)) || (hierOf(a) - hierOf(b)) || ((seq.get(a.t) ?? 0) - (seq.get(b.t) ?? 0)) || byCode(a, b)); - for (const l of named) { - if (!this._reports(l.code, props, 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); + // 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 }) }] })); } } - const lits = S.literalsOf([c.id], true, st).map((r) => ({ ...r, code: (S.propsById.get(r.p) || {}).code, role: (S.propsById.get(r.p) || {}).role })).filter((r) => r.code); - for (const r of lits) { - if (r.role === 'status' || !this._reports(r.code, props, 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)); + // 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); + const coding = { system: m.system }; + if (m.version) coding.version = m.version; + coding.code = m.code; + if (m.display) coding.display = m.display; + add(d, 2, [m.system, m.code], m.code, (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueCoding: coding }, + { name: 'subproperty', part: [{ name: 'code', valueCode: 'equivalence' }, { name: 'value', valueCode: m.equivalence }] }] })); } } - // the status literal (role 'status') after the other properties - for (const r of lits) if (r.role === 'status' && this._reports(r.code, props, true)) this._addStringProperty(params, 'property', r.code, String(r.v)); - this._needDesigs(c); - this._reportedUseProperty(c, props, params); - this._mapProperties(c, props, params); + // 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, 2, [it.rank ?? Infinity, it.id], it.term, (params) => this._addStringProperty(params, 'property', d.name, it.term, it.language)); + } + } + // 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, 2, [], 'true', (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueBoolean: true }] })); + } + const cmpKey = (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; + }; + out.sort((a, b) => (a.rank - b.rank) || (a.kind - b.kind) || cmpKey(a.key, b.key) || cmpText(a.name, b.name) || cmpText(a.text, b.text)); + return out; } - /** a concept's mappings of the file's implicit maps (behaviour.implicitMaps), as properties named by each map's key */ - _mapProperties(c, props, params) { - const maps = implicitMaps(this.store); - if (!maps.length) return; - for (const m of this.store.externalMaps(c.id)) { - const im = maps.find((x) => x.system === m.system); - const key = im ? im.key : null; - 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 }] }] }); + /** 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); + } + + /** a link's sort key by meta order.links, ending with property id, group, target code, target id */ + _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; + case 'stored': key.push(l.q ?? 0); 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 'value': key.push(val); break; + default: break; + } } + key.push(d.id, r.g || 0, val); + return key; } /** - * 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). + * 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 */ - _rxnormLookup(c, props, params) { - const S = this.store; - const st = this._stats(); - // which properties are reported is catalog data (property.report: SUPPRESS and the `@` storage - // codes 'never', the relationships 'named') - const hidden = (code) => (S.catalog.get(code) || {}).report === 'never'; - const lits = new Map(); - for (const r of S.literalsOf([c.id], true, st)) { - const p = S.propsById.get(r.p); - if (p && !hidden(p.code)) (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); - // cs-rxnorm.js's order: TTY, STY, SAB, then any other - const ORDER = ['TTY', 'STY', 'SAB']; - const pos = (n) => { const i = ORDER.indexOf(n); return i < 0 ? ORDER.length : i; }; - for (const name of [...lits.keys()].sort((a, b) => pos(a) - pos(b) || asText(a, b))) { - if (!this._reports(name, props, true)) continue; - for (const v of [...lits.get(name)].sort(asText)) this._addCodeProperty(params, 'property', name, v); - } - const links = S.linksFrom([c.id], null, true, st).filter((l) => { const p = S.propsById.get(l.p); return p && !hidden(p.code); }); - 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._reports(name, props, true)) continue; - seen.add(name + '|' + t.code); - named.push({ name, code: t.code }); + _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' }] }); } - named.sort((a, b) => (relOnly(b.name) - relOnly(a.name)) || asText(relOnly(a.name) ? '' : a.name, relOnly(b.name) ? '' : b.name) - || asText(a.name, b.name) || asText(a.code, b.code)); - for (const n of named) this._addCodeProperty(params, 'property', n.name, n.code); } /** - * The properties this system reports ({code, uri, type}), for expansion.property: the file's - * property definitions plus the ones the lookup builds (parent, child, ...). FHIR's standard - * concept-property URIs where they exist. - * - * None for SNOMED CT, LOINC and RxNorm, as main (cs-snomed.js, cs-loinc.js and cs-rxnorm.js - * declare none), so expansion.property carries their codes without a uri. The HL7 tester sorts - * expansion.property by uri (absent first), then code, so a uri here would put the definitions - * in a different order from the expected responses, which have none. + * 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'); @@ -890,11 +1021,27 @@ 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 an association (implicitMaps.associations: the active record rows of the + * relation, subject -> target, forward only) + */ + 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 = []; if (coding.system === this.system() && (!targetSystem || targetSystem === lm.system)) { const id = S.idOf(coding.code); @@ -913,49 +1060,6 @@ class SqliteV2Provider extends BaseCSServices { 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)); - sortLinks(links, S.linkOrder, (id) => (rows.get(id) || {}).code); - for (const l of links) { - const p = S.propsById.get(l.p); - const t = rows.get(l.t); - if (!p || !t || !this._reportsDef(p, props, true)) continue; - // (a hierarchy without a reported name is reported as FHIR's parent) - if (p.isHierarchy && !p.reportedAs) this._addCodeProperty(params, 'property', 'parent', t.code, null, t.display); - else this._addReported(params, p, t.code, t.display); - } - for (const r of S.literalsOf([c.id], true, this._stats())) { - const p = S.propsById.get(r.p); - if (p && this._reportsDef(p, props, true)) this._addReported(params, p, r.v); - } - this._reportedUseProperty(c, props, params); - this._mapProperties(c, props, params); - this._designationCodes(c, props, params); - } - - /** - * behaviour.lookupDesignationCode (a property of items): $lookup lists each designation that has - * a literal of that property again, as a designation whose code is the literal's value (with its - * text and language), when the request lists designations (by default, or 'designation' named) - */ - _designationCodes(c, props, params) { - const S = this.store; - const code = S.behaviour.lookupDesignationCode; - const p = code != null ? S.catalog.get(code) : null; - if (!p || !this._hasProp(props, 'designation', true)) return; - const st = this._stats(); - const items = S.designationRows([c.id], st).get(c.id) || []; - const value = new Map(); - for (const r of S.literalsOf(items.map((d) => d.id), true, st)) if (r.p === p.id && !value.has(r.c)) value.set(r.c, String(r.v)); - for (const d of items) { - if (!value.has(d.id)) continue; - params.push({ name: 'designation', part: [{ name: 'code', valueCode: value.get(d.id) }, { name: 'value', valueString: d.term }, - { name: 'language', valueCode: d.language || this.defLang() }] }); - } - } - // ---- filters -------------------------------------------------------------------------------- /** @@ -976,46 +1080,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.searchMode === 'designation') { - const requested = (this._requestedLangs && this._requestedLangs.languages) || []; - return this._sctFilterLanguage(requested.map((l) => l && l.language)); - } - const named = (this._requestLangs && this._requestLangs.languages) || (this.opContext.langs && this.opContext.langs.languages) || []; - const have = new Set((this.f.languages() || []).map(primary)); - for (const l of named) { - const p = primary(l && (l.code || l.language)); - if (p && p !== '*' && have.has(p)) return p; + _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); } - 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); @@ -1048,13 +1154,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); } @@ -1072,11 +1177,11 @@ class SqliteV2Provider extends BaseCSServices { return null; } - /** errors as the upstream provider reports them; dialects may wrap them (SNOMED ECL) */ + /** 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); } @@ -1084,40 +1189,35 @@ class SqliteV2Provider extends BaseCSServices { } /** - * 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.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.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.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.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 }] }; } @@ -1128,17 +1228,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(); @@ -1148,25 +1237,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.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; } @@ -1177,8 +1252,8 @@ 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) + // 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) { @@ -1240,13 +1315,12 @@ class SqliteV2Provider extends BaseCSServices { async _filterLocate(prep, set, code) { const r = await this.locate(code); - const fill = (t) => t.split('{code}').join(code); - const b = this.store.behaviour; - // behaviour.filterLocateMessage: the reason for a code a value-set filter check cannot locate - if (!r.context) return b.filterLocateMessage ? fill(b.filterLocateMessage) : r.message; + 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 (this._member(set, r.context.id)) return r.context; - // behaviour.filterCheckMessage: the reason for a found code the clause does not select - return b.filterCheckMessage ? fill(b.filterCheckMessage) : null; + // 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) { @@ -1264,9 +1338,9 @@ class SqliteV2Provider extends BaseCSServices { // ---- processSelection (whole single-system composes) ---------------------------------------- - // not for a system with an expansion limit (behaviour.expansionLimit): expand.js's usual path + // not for a system with an expansion limit (expansionLimits.maxCodes): expand.js's usual path // counts the codes against it - handlesSelecting() { return !(this.store.behaviour.expansionLimit > 0); } + handlesSelecting() { return !(this.expandLimitation() > 0); } /** * cs-api processSelection (expand.js processCodes): the page of the whole compose, with the @@ -1318,6 +1392,12 @@ 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.filterError) return null; // expand.js reports it through filter() throw e; } @@ -1359,7 +1439,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.store.behaviour.domain != null && 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; @@ -1410,90 +1490,65 @@ class SqliteV2Provider extends BaseCSServices { } -/** - * The property parameters $lookup added (params from `from` on) in the order behaviour.lookupOrder - * gives (README.md "Behaviour settings"): by rank, ranks[name], else `concept` for a code-valued - * property where given, else `other`; ties in the order listed, or with byCode by name, then value - * code. Other parameters (designations) keep their places. Absent: no reordering. - */ -function sortLookupProperties(params, from, order) { - if (!order) return; - const slots = []; - for (let i = from; i < params.length; i++) if (params[i].name === 'property') slots.push(i); - if (slots.length < 2) return; - const part = (p, n) => (p.part || []).find((x) => x.name === n) || {}; - const nameOf = (p) => String(part(p, 'code').valueCode ?? ''); - const valueOf = (p) => { const v = part(p, 'value'); const k = Object.keys(v).find((x) => x.startsWith('value')); return k ? String(typeof v[k] === 'object' ? JSON.stringify(v[k]) : v[k]) : ''; }; - const rank = (p) => { - const n = nameOf(p); - if (Object.prototype.hasOwnProperty.call(order.ranks || {}, n)) return order.ranks[n]; - if (order.concept != null && part(p, 'value').valueCode !== undefined) return order.concept; - return order.other; - }; - const txt = (a, b) => (a < b ? -1 : a > b ? 1 : 0); - const items = slots.map((i, k) => ({ p: params[i], k, r: rank(params[i]) })); - items.sort((a, b) => (a.r - b.r) || (order.byCode ? txt(nameOf(a.p), nameOf(b.p)) || txt(valueOf(a.p), valueOf(b.p)) : 0) || a.k - b.k); - slots.forEach((i, k) => { params[i] = items[k].p; }); +/** 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')); } /** - * A concept's links in the order meta linkOrder names (README.md "Order"): 'property' (by property, - * group, target code), 'seq' (link.seq, then property, group, target code), 'property-seq' (by - * property, link.seq, target code), 'target-int' (target code as a number, link.seq, property, - * target code). A link with no seq counts as 0; codes compare as binary text. + * 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 sortLinks(links, kind, codeOf) { - const txt = (a, b) => { const x = String(codeOf(a.t) ?? ''), y = String(codeOf(b.t) ?? ''); return x < y ? -1 : x > y ? 1 : 0; }; - const seq = (a, b) => (a.q ?? 0) - (b.q ?? 0); - const prop = (a, b) => a.p - b.p || a.g - b.g; - const int = (a, b) => { const x = Number.parseInt(codeOf(a.t), 10), y = Number.parseInt(codeOf(b.t), 10); return (Number.isNaN(x) ? 0 : x) - (Number.isNaN(y) ? 0 : y); }; - const cmp = { - property: (a, b) => prop(a, b) || txt(a, b), - seq: (a, b) => seq(a, b) || prop(a, b) || txt(a, b), - 'property-seq': (a, b) => a.p - b.p || seq(a, b) || txt(a, b), - 'target-int': (a, b) => int(a, b) || seq(a, b) || a.p - b.p || txt(a, b), - }[kind]; - return links.sort(cmp); -} - -/** the property definitions a file reports (data built at load; none where behaviour.declaresProperties is false) */ function propertyDefinitionsFor(store) { - if (!store.behaviour.declaresProperties) 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' }; + 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('@') && p.report !== 'never') 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; } - /** - * The file's implicit ConceptMaps (behaviour.implicitMaps): [{system, key, url}], each map - * `{base}{key}` translating to the target system; $lookup lists a concept's mappings to it as a - * property named key + * 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.behaviour.implicitMaps; - return im ? im.maps.map(([system, key]) => ({ system, key, url: im.base + key })) : []; + const im = store.implicitMapsSpec; + return im.maps ? im.maps.map(([system, key]) => ({ system, key, url: im.base + key })) : []; } -/** 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} (and the other names) in every string of a JSON value */ +function substitute(x, vars) { + if (typeof x === 'string') return x.replace(/\{(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 behaviour.grammar; null: plain codes) */ + /** the code grammar this factory implements (meta grammar; null: plain codes) */ static grammar = null; constructor(i18n, file, opts = {}) { @@ -1505,41 +1560,42 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { async load() { this.store = openStore(this.file, this.opts); // a file whose codes have a grammar this factory does not implement (index.js GRAMMARS) - if (this.store.behaviour.grammar !== this.constructor.grammar) { - const g = this.store.behaviour.grammar; + 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} (behaviour.grammar), which this provider serves`); - } - this.dialect = dialectFor(this.store.system); - // the text search the file names (behaviour.textSearch; text-index.js TEXT_SEARCHES), or the - // generic one (null) - this.searchMode = textSearchMode(this.store.behaviour.textSearch, this.file); - // the implicit value sets' URL grammar (behaviour.implicitValueSets): loinc here, snomed in the - // SNOMED CT provider; another name refuses the file - const ivs = this.store.behaviour.implicitValueSets; - if (ivs != null && !(ivs === 'loinc' || (ivs === 'snomed' && this.constructor.grammar === 'snomed'))) { + 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}: its implicit value sets are ${ivs} (behaviour.implicitValueSets), which this server does not implement`); + throw new Error(`${this.file}: meta order.expansion ${JSON.stringify(words)}: this server orders expansions by one word`); } - // behaviour.expansionOrder: concept ids, or the stored order (ix_order) - const kind = this.store.behaviour.expansionOrder; - const order = kind !== 'ids' ? this._systemOrder(kind) : null; + 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); // 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; } @@ -1558,13 +1614,12 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { } return this._res; } - // behaviour.lookupName: code_system.name or code_system.title (a title of the - // requested language from meta titles first; no title: the name; no name: the system) + // 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) { - const primary = (l) => String(l || '').toLowerCase().split('-')[0]; for (const l of (langs.languages || [])) { const want = primary(l && (l.code || l.language)); const k = Object.keys(titles).find((t) => primary(t) === want); @@ -1575,25 +1630,17 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { } // (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.behaviour.lookupName === 'title' ? this._csTitle(langs) : this._csName(); } + 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() { - const dom = this.store.domain(); - return dom ? dom.size : this.store.conceptCount; + const l = this.store.listed(); + return l ? l.size : this.store.conceptCount; } - /** - * behaviour.versionAlgorithm, else what the stored CodeSystem resource declares - * (versionAlgorithmString / versionAlgorithmCoding), else null (versions match exactly) - */ + /** what the stored CodeSystem resource declares (versionAlgorithmString / versionAlgorithmCoding), else null */ versionAlgorithm() { - if (this.store.behaviour.versionAlgorithm != null) return this.store.behaviour.versionAlgorithm; if (this._resourceAlgorithm === undefined) { - let r = null; - try { r = this.store.cs.resource ? JSON.parse(this.store.cs.resource) : null; } catch (e) { r = null; } + const r = this._resource(); this._resourceAlgorithm = r ? VersionUtilities.versionAlgorithmOf(r) : null; } return this._resourceAlgorithm; @@ -1609,19 +1656,20 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { } /** * The partial version a request may name for this file (library.js registers the factory under - * it too): with versionAlgorithm url, the version before '/version/' (an edition URI without its - * date); any other algorithm: none (exact versions only) + * it too): with meta version.partial, the version before the separator */ getPartialVersion() { const v = this.version(); - return this.versionAlgorithm() === 'url' && v.includes('/version/') ? v.substring(0, v.indexOf('/version/')) : null; + const sep = this.store.versionRule.partial; + return sep && v.includes(sep) ? v.substring(0, v.indexOf(sep)) : null; } describeVersion(v) { - // behaviour.versionFormat MMDDYYYY: versions are dates written MMDDYYYY - if (this.store.behaviour.versionFormat === 'MMDDYYYY') { + // 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); } @@ -1634,42 +1682,68 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { return new SqliteV2Provider(opContext, supplements, this); } - /** the file's implicit value sets, by the URL grammar it names (behaviour.implicitValueSets) */ + /** + * 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.behaviour.implicitValueSets === '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, 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 }); + 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(), version: this.version(), concept: ids.map((id) => ({ code: rows.get(id).code })) }; + } else { + include = { system: this.system(), version: this.version(), ...substitute(t.include, vars) }; + } + vs.compose = { include: [include] }; + return vs; } - // the file's implicit concept maps (behaviour.implicitMaps: {base}{key}, over its mapping rows) + // the file's implicit concept maps over mapping rows (meta implicitMaps: {base}{key}) async findImplicitConceptMaps(conceptMaps, source, sourceVersion, dest, code = null) { const maps = implicitMaps(this.store); if (!maps.length || !dest) return; @@ -1685,11 +1759,18 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { conceptMaps.push(this._implicitMap(lm)); } + /** an implicit map by URL: one of implicitMaps.maps, or an association (`?fhir_cm=`) */ async findImplicitConceptMap(url, version) { if (!url) return null; if (version && version !== this.version()) return null; const lm = implicitMaps(this.store).find((m) => m.url === url); - return lm ? this._implicitMap(lm) : null; + 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; } _implicitMap(lm) { @@ -1702,6 +1783,21 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { 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/snomed.js b/tx/sqlite-v2/snomed.js index 1c77ef887..a097f04d1 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -1,10 +1,14 @@ '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'); @@ -16,20 +20,13 @@ 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'] -}; /** * 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.reportedAs || d.code } : null; + 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()); @@ -72,10 +69,6 @@ class SnomedV2Provider extends SqliteV2Provider { 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; @@ -109,12 +102,6 @@ class SnomedV2Provider extends SqliteV2Provider { return r; } - isDisplay(d) { - // the FSN and synonym description types (item_use.role) - const role = d ? this.store.useRoleOf(d.use) : null; - return role === 'synonym' || role === '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 @@ -249,108 +236,23 @@ class SnomedV2Provider extends SqliteV2Provider { return !!langs && (langs.languages || []).some((l) => l.code && l.code !== '*' && l.code !== d.split('-')[0]); } - 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))); - } - // the hierarchy under its reported name (property.reported_as) - if (this._reportsDef(S.hierarchy, props, true)) { - for (const l of links) if (l.p === hid) this._addReported(params, S.hierarchy, code(l.t), 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)); - } - // the concept's other links (module, definition status), in catalog order, each under its - // reported name, asked for by it or an also_asked_as name, a boolean where the catalog gives - // true_value, by default unless report says otherwise (catalog data, README "Per property") - for (const d of S.catalog.values()) { - if ((d.shape !== 'link' && d.shape !== 'both') || d.attribute || d.isHierarchy || d.inverseOfId != null || !this._reportsDef(d, props, true)) continue; - const l = links.find((x) => x.p === d.id); - if (l) this._addReported(params, d, code(l.t), disp(l.t)); - } - // the concept's other literals (not attributes; not effectiveTime, above): semanticTag (stored by - // the importer, report named), each under its reported name - for (const d of S.catalog.values()) { - if (d.shape !== 'literal' || d.attribute || d.code === 'effectiveTime' || d.role || !this._reportsDef(d, props, true)) continue; - for (const l of lits) if (l.p === d.id) this._addReported(params, d, l.v); - } - 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._reports(p.code, props, 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._reports(p.code, props, 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 = schemeOf(this.store, 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) @@ -367,6 +269,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); @@ -636,29 +546,59 @@ 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({ + 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); + } + return { t: 'ids', ids: kept.bm.toArray(), label: 'ECL (main) ' + text.slice(0, 60) }; + }, +}); class SnomedV2Factory extends SqliteV2Factory { static grammar = 'snomed'; + static grammarRules = SNOMED_RULES; + static implicitValueSetGrammars = ['fhir_vs']; edition() { return this.store.cs.edition; } @@ -744,9 +684,9 @@ class SnomedV2Factory extends SqliteV2Factory { return null; } - async buildKnownValueSet(url, version) { - // the snomed URL grammar for implicit value sets (behaviour.implicitValueSets) - if (this.store.behaviour.implicitValueSets !== 'snomed') return null; + /** 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); @@ -910,16 +850,7 @@ 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(); } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 763540532..bd471ca0d 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -4,24 +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 every server that reads these files would do the same) -// is in the file too: meta behaviour.* keys (meta.js; each has one meaning and a default, and a -// malformed value is an error at open; an unknown meta key is ignored) 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('better-sqlite3'); const { RoaringBitmap32 } = require('roaring'); -const { readMeta, FILTER_OPERATORS } = require('./meta'); +const { readMeta, orderOf, FILTER_OPERATORS } = require('./meta'); const FORMAT = 'tx-terminology/1'; const USER_VERSION = 1; @@ -76,17 +79,16 @@ function setKey(kind, pid, value, vk = 0) { } -/** - * A file's meta checked (meta.js readMeta: a malformed value of a known key, or a required feature - * this server does not know, is an error; an unknown key is ignored), and its behaviour settings - * (meta 'behaviour.', every key with its default filled in; README.md "Behaviour settings") - */ -function readBehaviour(meta, file) { - return readMeta(meta, file).behaviour; -} - const FILTER_OPS = new Set(FILTER_OPERATORS); -const REPORT = new Set([null, 'named', 'always', 'never']); +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}']); /** property.presentation: {value?: code|string|display|coding, parts?: [description|code-display|partCode]} */ function isPresentation(v) { @@ -276,17 +278,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; @@ -296,15 +293,11 @@ 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; } @@ -316,6 +309,9 @@ class Store { 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, resource: cs.resource ?? null, release_date: cs.release_date, content: cs.content, edition: this.meta.get('edition') ?? null, @@ -331,35 +327,28 @@ class Store { // 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); - const m = readMeta(this.meta, this.file); - this.requires = m.requires; - // identifier values are text (identifier-text): probes bind text, lists through json_each - // included. A file that does not say so was built before identifier.value was declared TEXT - // (it may hold INTEGER values a text probe misses): refused, to be rebuilt or upgraded - if (!m.requires.includes('identifier-text')) { - throw new Error(`${this.file} was built before identifier values were text (meta requires has no identifier-text): rebuild it with the importers, or upgrade it`); + // 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'); + // compatibility members this server does not implement: refused, never ignored + if (this.compat.expansionKeepsRepeatedDesignations) { + throw new Error(`${this.file}: compatibility.expansionKeepsRepeatedDesignations is set (the server's expansion code removes repeated designations, which this reader does not control), which this server does not implement`); } - this.behaviour = m.behaviour; - // the order of a concept's links where no rule of the system's adapter lists them ($lookup), and - // how text-search hits of equal score are ordered (null: each search's own order) - this.linkOrder = m.linkOrder; - this.searchTieBreak = m.searchTieBreak; - // identifier-aliased codes (behaviour.aliases): this server does not implement them, and would - // answer such a file's codes wrongly - // behaviour.keepDuplicateDesignations: expansion rows' designations are deduplicated by the - // server's expansion code, which this reader does not control - if (m.behaviour.keepDuplicateDesignations) throw new Error(`${this.file}: behaviour.keepDuplicateDesignations is set, which this server does not implement`); - if (m.behaviour.aliases !== null) throw new Error(`${this.file}: behaviour.aliases is set (identifier-aliased codes), which this server does not implement`); - // behaviour.implicitMaps.used (maps reported as used whether or not they translate): not implemented here - if (m.behaviour.implicitMaps && m.behaviour.implicitMaps.used !== undefined) { - throw new Error(`${this.file}: behaviour.implicitMaps.used is set, which this server does not implement`); - } - // behaviour.lookupCopyright: the notice $lookup lists (code_system.resource.copyright) + // implicitMaps.used (maps reported as used whether or not they translate): not implemented here + if (this.implicitMapsSpec.used !== undefined) throw new Error(`${this.file}: implicitMaps.used is set, which this server does not implement`); + // compatibility.lookupListsCopyright: the notice $lookup lists (code_system.resource.copyright) this.copyright = null; - if (m.behaviour.lookupCopyright) { + 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}: behaviour.lookupCopyright without code_system.resource.copyright`); + 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) @@ -371,26 +360,10 @@ class Store { this.displayRefsets = dc && dc.relations ? dc.relations.map(String) : null; this.moduleDependencies = metaJson('moduleDependencies', []); this._loadCatalog(); - // behaviour.lookupDesignationCode names a literal property of the catalog - const ldc = this.behaviour.lookupDesignationCode; - if (ldc != null && !(this.catalog.has(ldc) && ['literal', 'both'].includes(this.catalog.get(ldc).shape))) { - throw new Error(`${this.file}: behaviour.lookupDesignationCode ${ldc} is not a literal property of the catalog`); - } - this.uses = new Map(); - const useCols = new Set(db.prepare('PRAGMA main.table_info(item_use)').all().map((c) => c.name)); - const missingUse = ['reported_as', 'role'].filter((c) => !useCols.has(c)); - if (missingUse.length) throw new Error(`${this.file} was built before the item_use columns ${missingUse.join(', ')} existed: rebuild it with the importers, or upgrade it`); - for (const u of db.prepare('SELECT use_id, system, code, display, reported_as, role FROM main.item_use').all()) { - if (u.role != null && !['fsn', 'synonym', 'name'].includes(u.role)) throw new Error(`${this.file}: item use ${u.code} has role ${u.role} (fsn, synonym, name or NULL)`); - this.uses.set(u.use_id, { system: u.system, code: u.code, display: u.display, ...(u.reported_as != null ? { reportedAs: u.reported_as } : {}), ...(u.role != null ? { role: u.role } : {}) }); - } - // 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 item use whose items are reported as a property, not as designations (item_use.reported_as) - const reported = [...this.uses].filter(([, u]) => u.reportedAs); - if (reported.length > 1) throw new Error(`${this.file}: more than one item use with reported_as`); - this.reportedUse = reported.length ? { id: reported[0][0], name: reported[0][1].reportedAs } : null; + this._loadUses(); + this._loadFilters(); + this._loadStatus(); + this._checkReading(); this.hasFts = true; this.hasAcceptability = this.langRelations.size > 0; this.hasRank = true; @@ -402,6 +375,199 @@ 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; + } + const d = this.catalog.get(x); + if (!d) throw bad(r, `reads ${x}, which is no property of the catalog`); + if (d.internal) throw bad(r, `reads ${x}, an internal property`); + } + 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 + 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 && a.operators.some((o) => b.operators.includes(o))) throw bad(b, `shares an operator with filter ${a.id} of the same code`); + } + } + } + + /** + * The filter row that understands a filter's name and operator (README.md "filter"), with the + * capture of a code_pattern row: {row, capture}, or null + */ + filterRow(name, op) { + const n = String(name); + for (const f of this.filters) { + if (!f.operators.includes(op)) continue; + if (f.code != null) { + if (f.code === n || (f.anyCase && f.code.toLowerCase() === n.toLowerCase())) return { row: f, capture: null }; + } else { + const m = f.pattern.exec(n); + if (m) return { row: f, capture: m[1] ?? null }; + } + } + return null; + } + + /** + * 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() { + for (const d of this.catalog.values()) { + for (const c of ['alias_parameter', 'alias_extension', 'alias_literals']) { + if (d[c] != null) throw new Error(`${this.file}: property ${d.code} has ${c} (identifier-aliased codes), which this server does not implement`); + } + } + } + _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'); @@ -411,15 +577,18 @@ class Store { } _loadCatalog() { - // the catalog columns readers rely on (a file built before them is refused: no reader keeps a rule - // for a property that does not say how it is reported) + // 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 missing = ['reported_as', 'also_asked_as', 'true_value', 'named_links', 'selects_members', 'name_any_case', 'value_any_case', - 'default_value', 'match_display', 'value_system', 'presentation'].filter((c) => !cols.has(c)); - if (missing.length) throw new Error(`${this.file} was built before the catalog columns ${missing.join(', ')} existed: rebuild it with the importers, or upgrade it`); + 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, @@ -427,28 +596,27 @@ class Store { // 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, conceptId: r.concept_id, - isHierarchy: !!r.subsumption, closureFrom: r.closure_from, filterable: !!r.filterable, refinable: !!r.refinable, + 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, - namedLinks: !!r.named_links, 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, - // the name it is reported and asked for under, further names it is asked for by, and the - // value it is true for where it is reported as a boolean (absent columns: none) - reportedAs: r.reported_as ?? null, alsoAskedAs: r.also_asked_as ? JSON.parse(r.also_asked_as) : [], trueValue: r.true_value ?? null, - // filter facts (README.md "Per property") - selectsMembers: !!r.selects_members, nameAnyCase: !!r.name_any_case, valueAnyCase: !!r.value_any_case, defaultValue: r.default_value ?? null, - matchDisplay: !!r.match_display, valueSystem: r.value_system ?? null, presentation: r.presentation ? JSON.parse(r.presentation) : 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 (!(Array.isArray(def.alsoAskedAs) && def.alsoAskedAs.every((x) => typeof x === 'string' && x))) { - throw new Error(`${this.file}: property ${def.code} has also_asked_as ${r.also_asked_as}, not a list of names`); - } - if (def.presentation !== null && !isPresentation(def.presentation)) throw new Error(`${this.file}: property ${def.code} has presentation ${r.presentation}`); - if (!REPORT.has(def.report)) throw new Error(`${this.file}: property ${def.code} has report ${def.report} (named, always, never 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)) throw bad(r, `presentation ${r.presentation}`); this.catalog.set(def.code, def); this.propsById.set(def.id, def); } @@ -461,23 +629,19 @@ class Store { if (d.inverseOfId != null) d.reverses = stored(this.propsById.get(d.inverseOfId)); } const closureSources = new Set([...this.catalog.values()].map((d) => d.closureFrom).filter((x) => x != null)); - // the properties a filter or a lookup reads by name: link, literal, both and filterable - // unions; not the inverse rows, nor a closure source (its pairs are the descendants sets) + // 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; 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 one whose links are read only where it is named (property.named_links) - this.hiddenLinks = [...this.catalog.values()].filter((d) => d.namedLinks || closureSources.has(d.id)).map((d) => d.id); - // behaviour.domain names a catalog property - if (this.behaviour.domain != null && !this.catalog.has(this.behaviour.domain)) { - throw new Error(`${this.file}: behaviour.domain ${this.behaviour.domain} is not a property of the catalog`); - } + // 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 @@ -490,11 +654,10 @@ 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 (role 'status') + // 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; @@ -503,25 +666,6 @@ class Store { /** the inverse rows: [{code, reverses (the stored properties reversed)}] */ inverses() { return [...this.catalog.values()].filter((d) => d.reverses); } - /** - * The catalog code a filter's property name means: the code itself, else a property that may be - * named in any case (name_any_case), else one asked for by that name (also_asked_as) - */ - resolveFilterName(name) { - const n = String(name); - if (this.catalog.has(n)) return n; - const low = n.toLowerCase(); - for (const d of this.catalog.values()) if (d.nameAnyCase && d.code.toLowerCase() === low) return d.code; - for (const d of this.catalog.values()) if (d.alsoAskedAs.includes(n)) return d.code; - return n; - } - - /** 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) { @@ -535,13 +679,30 @@ class Store { } /** - * The concepts answers select (behaviour.domain: those with a row of that property; the file's - * other concepts are never selected, e.g. RxNorm's RXNATOMARCHIVE-only ones), or null: every concept + * The concepts answers list (README.md "Concept status": every concept but the unlisted ones), + * or null: every concept */ - domain(stats) { - const code = this.behaviour.domain; - if (code == null) return null; - return this.getSet(KIND.hasProp, this.catalog.get(code).id, 0, stats); + 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; + } + + /** + * concept id -> the language of its first item (designation order: rank, then id) whose text is the + * concept's display and that has a language (README.md "The display designation") + */ + displayItemLanguages(ids, stats) { + const out = new Map(); + if (!ids.length) return out; + const q = this.stmt(`SELECT c.id, (SELECT i.language FROM main.item i WHERE i.concept_id = c.id AND i.cs_id = ${this.csId} AND i.text = c.display + AND i.language IS NOT NULL AND (i.kind = 0 OR i.use_id IS NOT NULL)${this.propertyUseIds.length ? ` AND (i.use_id IS NULL OR i.use_id NOT IN (${this.propertyUseIds.join(',')}))` : ''} ORDER BY i.rank IS NULL, i.rank, i.id LIMIT 1) FROM main.concept c WHERE c.id IN (SELECT value FROM json_each(?))`).raw(); + const rows = q.all(json(ids)); + for (const [id, l] of rows) if (l != null) out.set(id, l); + if (stats) count(stats, this, q, rows.length); + return out; } /** the role (item_use.role) of a designation's use coding, or null */ @@ -553,14 +714,14 @@ class Store { languages() { return JSON.parse(this.meta.get('languages') || '[]'); } /** - * concept id -> its place in the stored system order (ix_order rank), for meta searchTieBreak - * 'rank'; by concept id where the file stores no rank + * 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('stored'); + const order = this.systemOrder(); this._rankOrdinal = (id) => order.rank[id]; } else this._rankOrdinal = (id) => id; } @@ -571,7 +732,7 @@ class Store { _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); @@ -742,6 +903,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); } @@ -819,28 +985,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] } : {}) }); } @@ -927,6 +1091,56 @@ 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)); + } + + /** 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); @@ -1125,6 +1339,11 @@ class Store { 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) { const d = this.schemes.get(schemeId); if (!d) return []; @@ -1191,14 +1410,6 @@ class Store { 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) */ @@ -1206,4 +1417,4 @@ function openStore(file, opts = {}) { return new Store(file, opts); } -module.exports = { Store, openStore, checkFormat, readBehaviour, 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 4c3df9037..810203378 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -1,128 +1,110 @@ '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 names a search reads is file data: meta ix.ix_word.names (searchNamesSelection; README.md -// "Word index"), the same selection for the stored index and one built in memory. 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 the selection says counts 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; 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) 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, as the built-in -// providers do; so does each language whose stemmer is not this server's (usableLanguages). +// 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'); 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'); } -// ---- the text searches a file may name ------------------------------------------------------ +// ---- order of hits with equal score ------------------------------------------------------------ -/** - * The text searches, by the name a file gives them (meta behaviour.textSearch), each the ranking of - * a FHIRsmith provider (see the top of this file): name -> the search mode store.searchText runs. - * null: the generic search (cs-cs.js rules). A name not here refuses the file. - */ -const TEXT_SEARCHES = Object.freeze({ - snomed: 'designation', // shortlist by distinct-word count, best designation; active concepts - loinc: 'display', // best name (or code range) per concept - rxnorm: 'rxnorm', // best atom name or code, among concepts with a non-SY RXNCONSO atom -}); +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 searchTieBreak; README.md "Order"), as an - * ordinal over the hits: 'rank' the stored rank; 'display' the display (String.localeCompare), then - * the stored rank; 'code' the code as binary text; 'code-length' the code's length, then the code as - * binary text (numeric order for numeric codes); absent: concept id + * 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 kind = store.searchTieBreak; - if (kind === 'rank') return store.rankOrdinal(); - if (kind !== 'display' && kind !== 'code' && kind !== 'code-length') return (id) => id; - const rows = store.conceptRows(Array.from(ids), stats); - const rank = store.rankOrdinal(); - const key = (id) => String((rows.get(id) || {})[kind === 'display' ? 'display' : 'code'] ?? ''); - const cmp = kind === 'display' ? (a, b) => key(a).localeCompare(key(b)) || rank(a) - rank(b) - : kind === 'code-length' ? (a, b) => (key(a).length - key(b).length) || cmpBinary(key(a), key(b)) || a - b - : (a, b) => cmpBinary(key(a), key(b)) || a - b; + 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 search mode for behaviour.textSearch (null: generic); throws for a name this server does not implement */ -function textSearchMode(name, file) { - if (name == null) return null; - if (Object.prototype.hasOwnProperty.call(TEXT_SEARCHES, name)) return TEXT_SEARCHES[name]; - throw new Error(`${file}: its text search is ${name} (behaviour.textSearch), which this server does not implement`); -} - // ---- the names ------------------------------------------------------------------------------ /** - * The names a file's text search reads (meta ix.ix_word.names, README.md "Word index"), or null: a - * file that states none has no names to search (codes are still matched) + * 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) { - if (store._names === undefined) { - const own = store.meta.get('ix.ix_word.names'); - store._names = own != null ? JSON.parse(own) : null; - } - return store._names; + return store.search ? (store.search.names || {}) : null; } /** * The selection as SQL over item and concept: { display: [lang] | null, items: {where, params, - * lang} | null, conceptsWith: a bitmap of the concepts selected | null } + * lang} | null } */ function selectionPlan(store, names) { if (store._namesPlan && store._namesPlan.names === names) return store._namesPlan; - const plan = { names, display: null, items: null, concepts: null }; + const plan = { names, display: null, items: null }; if (names && names.display) plan.display = primaryLanguage(names.display, 'en'); const it = names && names.items; if (it) { @@ -142,29 +124,11 @@ function selectionPlan(store, names) { where.push(any.length ? `(${any.join(' OR ')})` : '0'); } plan.items = { where: where.join(' AND '), lang: it.language ? primaryLanguage(it.language, 'en') : null }; - if (it.conceptsWith) plan.concepts = conceptsWithProperty(store, it.conceptsWith); } store._namesPlan = plan; return plan; } -/** the concepts with a row (active or not) of a property, as its catalog shape says; none if it is not in the catalog */ -function conceptsWithProperty(store, code) { - const bm = new RoaringBitmap32(); - const d = store.catalog.get(code); - if (!d) return bm; - const stored = (x) => (x.members ? x.members.flatMap(stored) : [x]); - for (const p of stored(d)) { - const tables = p.shape === 'link' ? ['link'] : p.shape === 'literal' ? ['literal'] : p.shape === 'both' ? ['link', 'literal'] - : p.shape === 'identifier' ? ['identifier'] : p.shape === 'record' ? ['record'] : []; - for (const t of tables) { - const col = t === 'record' ? 'relation_id' : 'property_id'; - bm.addMany(store.db.prepare(`SELECT DISTINCT subject_id FROM main.${t} WHERE ${col} = ? AND subject_id <= ?`).pluck().all(p.id, store.hi)); - } - } - return bm; -} - /** * 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 @@ -182,7 +146,6 @@ function eachSearchName(store, fn, langs = null) { let lang; if (k === 0) lang = plan.display; else { - if (plan.concepts && !plan.concepts.has(id)) continue; lang = plan.items.lang || primaryLanguage(language, defLang); } if (want(lang)) fn(id, lang, term); @@ -202,8 +165,7 @@ function searchNamesOf(store, ids, fn) { } } if (plan.items) { - const some = plan.concepts ? JSON.stringify(ids.filter((id) => plan.concepts.has(id))) : j; - 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(some)) { + 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, plan.items.lang || primaryLanguage(language, defLang), term); } @@ -357,7 +319,7 @@ class MemoryTextIndex { */ function usableLanguages(store, stored) { const raw = store.meta.get('ix.ix_word.stemmers'); - if (raw == null || store.meta.get('ix.ix_word.names') == null) return new Set(); + if (raw == null || !store.search) return new Set(); const named = JSON.parse(raw); return new Set([...stored.langs].filter((l) => named[l] === stemmerName(l))); } @@ -384,8 +346,7 @@ class SplitTextIndex { /** 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 names = searchNamesSelection(store); - const counting = !!(names && names.counts); + 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(); let index; @@ -429,15 +390,6 @@ function* namesOfG(store, ids, stats, fn) { } } -/** the candidates with a name (in lang) that has every word of the filter */ -function* inOneName(store, bm, q, lang, stats) { - const ok = new RoaringBitmap32(); - yield* namesOfG(store, 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(); @@ -517,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); @@ -535,279 +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 - */ -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); - const bm = (yield* candidates(index, lang, tokens, stats)).andInPlace(active); - // ties (and the shortlist's concept order) by meta searchTieBreak - ordinal = tieOrdinal(store, bm.toArray(), stats); - 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, 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 && searchNamesSelection(store) && searchNamesSelection(store).counts ? 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 + * 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 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'); - // the system's domain (behaviour.domain: RxNorm's RXNCONSO concepts), else the active concepts - const tty = store.props.get('TTY'); - const bm = (store.domain(stats) || 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); 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, 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; - // the best first; ties by meta searchTieBreak (LOINC files: display, as cs-loinc.js, then CodeKey) - const ord = tieOrdinal(store, [...rank.keys()], stats); - const ids = yield* sortG([...rank.keys()], (a, b) => (rank.get(b) - rank.get(a)) || ord(a) - ord(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), 'en', tokens, stats)).andInPlace(eligible); - if (tokens.length > 1 && bm.size) bm = yield* inOneName(store, 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, 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); ties by meta searchTieBreak (RxNorm - // files: code, RXCUI order as text) - const ord = tieOrdinal(store, bm.toArray(), stats); - const ids = yield* sortG(bm.toArray(), (a, b) => (rank.get(b) - rank.get(a)) || ord(a) - ord(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* () { - let hits = yield* rateConceptsG(blockConcepts(store, csLang, stats), new TextQuery(text), lang, supplementCodes); - // ties by meta searchTieBreak (absent: in concept id order, as rated) - if (store.searchTieBreak != null) { const ord = tieOrdinal(store, hits.map((h) => h.id), stats); hits = yield* sortG(hits, (a, b) => b.rating - a.rating || ord(a.id) - ord(b.id)); } - 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, SplitTextIndex, TEXT_SEARCHES, textSearchMode, blockConcepts, eachSearchName, searchNamesOf, searchNamesSelection, rxSearchable, + FORMAT, WordIndex, SplitTextIndex, eachSearchName, searchNamesOf, searchNamesSelection, searchCandidates, computeTextIndexFrom, textIndexOf, primaryLanguage, countsFromLE, countsToLE, usableLanguages, - sctTextSearch, sctTextLanguages, loincTextSearch, rxTextSearch, genericTextSearch, rateConcepts, - sctTextSearchG, loincTextSearchG, rxTextSearchG, genericTextSearchG + search, searchG, textLanguages, tieOrdinal, cmpCodeNumber, }; From 3da8483c5addf4aacc9b7afbb787bfb0e0fc85d7 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 10:59:00 -0600 Subject: [PATCH 49/90] sqlite-v2 importers: write the fhir-reading revision The builder takes each system's FHIR reading as data (reading(): meta keys, catalog reading columns by rule, item_use roles, filter rows, the rows only the reading has) and writes it in one path; it derives concept.active from conceptStatus where a value means inactive, writes kind 5 sets only for what filters, refinements and conceptStatus read, the word index from search.names (counts with search.shortlist), and checks the revision's contracts. The LOINC, RxNorm and SNOMED CT importers state their content as data; the importer tests assert the new form. Co-Authored-By: Claude --- tests/tx/sqlite-v2-builder.test.js | 262 ++++++++-- tests/tx/sqlite-v2-expansion-limit.test.js | 4 +- tests/tx/sqlite-v2-loinc.test.js | 43 +- tests/tx/sqlite-v2-mixed-providers.test.js | 5 +- tests/tx/sqlite-v2-rxnorm-status.test.js | 30 +- ...-v2-sct-concrete-type-relationship.test.js | 13 +- tests/tx/sqlite-v2-sct-from-cache.test.js | 4 +- tx/importers/import-loinc-v2.module.js | 155 ++++-- tx/importers/import-rxnorm-v2.module.js | 122 +++-- tx/importers/readme.md | 5 +- tx/importers/sct-v2-common.js | 134 +++-- tx/importers/sqlite-v2/builder.js | 468 +++++++++++++++--- tx/importers/sqlite-v2/diff.js | 12 +- tx/importers/sqlite-v2/indexes.js | 96 +++- tx/importers/sqlite-v2/schema.sql | 11 +- 15 files changed, 1049 insertions(+), 315 deletions(-) diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js index aaf964174..6a150a5a1 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: subject kind, by_target for the hierarchy', () => { - const row = (code) => db.prepare('SELECT shape, subject_kind, by_target, filterable FROM property WHERE code = ?').get(code); - expect(row('isa')).toEqual({ shape: 'link', subject_kind: 'concept', by_target: 1, filterable: 1 }); - expect(row('colour')).toEqual({ shape: 'literal', subject_kind: 'concept', by_target: 0, filterable: 1 }); - expect(row('S1')).toEqual({ shape: 'record', subject_kind: 'concept', 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,46 +364,216 @@ 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, a malformed value refused at open, an unknown key ignored', () => { + 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.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.aliases', '{"literals": {"code-type": 11}}', /behaviour.aliases = .* 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/); - // identifier-aliased codes: this reader does not implement them, and refuses a file that sets them - bad('behaviour.aliases', '{"literals": {"code-type": "11-digit", "synonym": "{code}"}}', /behaviour.aliases is set .* which this server does not implement/); - 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.colour', '"red"'); - w.prepare('INSERT INTO meta VALUES (?, ?)').run('behaviour.preferredForLanguage', 'true'); - 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.colour).toBeUndefined(); - expect(G.behaviour.aliases).toBeNull(); - 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 that reads 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(/reads the internal property secret/); }); }); diff --git a/tests/tx/sqlite-v2-expansion-limit.test.js b/tests/tx/sqlite-v2-expansion-limit.test.js index 55dcaa6d6..b54ed0cde 100644 --- a/tests/tx/sqlite-v2-expansion-limit.test.js +++ b/tests/tx/sqlite-v2-expansion-limit.test.js @@ -1,6 +1,6 @@ 'use strict'; -// behaviour.expansionLimit through the real $expand: a file that caps how many of its codes an +// 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 @@ -25,7 +25,7 @@ beforeAll(async () => { 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.setBehaviour('expansionLimit', CAP); + b.reading({ meta: { expansionLimits: { maxCodes: CAP } } }); b.finish(); app = await getTestApp(); tx = getTxModule(); diff --git a/tests/tx/sqlite-v2-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js index c9097682f..9bded0584 100644 --- a/tests/tx/sqlite-v2-loinc.test.js +++ b/tests/tx/sqlite-v2-loinc.test.js @@ -215,14 +215,49 @@ 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(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 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 }); - expect(row('AnswerList')).toEqual({ code: 'AnswerList', inverse_of: 'Answer|answers-for', filterable: 1, ordered: 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 +325,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')); diff --git a/tests/tx/sqlite-v2-mixed-providers.test.js b/tests/tx/sqlite-v2-mixed-providers.test.js index 6158f2123..ae75dc84e 100644 --- a/tests/tx/sqlite-v2-mixed-providers.test.js +++ b/tests/tx/sqlite-v2-mixed-providers.test.js @@ -33,8 +33,8 @@ 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' }); - // (inactive items listed with their status) - b.setBehaviour('inactiveDesignations', 'status'); + // the hierarchy filter (a filter that is no row of the file is not understood) + 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 ['root', 'A', 'A1', 'A2', 'A3', 'B', 'B1']) { @@ -51,6 +51,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}` }); diff --git a/tests/tx/sqlite-v2-rxnorm-status.test.js b/tests/tx/sqlite-v2-rxnorm-status.test.js index aedbd00a1..6adce9318 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('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(); @@ -78,7 +96,9 @@ describe('sqlite-v2 RxNorm obsolete and archived concepts', () => { expect(await facts('100')).toEqual([false, null, false]); expect(await facts('200')).toEqual([true, 'obsolete', false]); expect(await facts('300')).toEqual([false, null, false]); - expect(await facts('400')).toEqual([true, 'archived', true]); + // (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 3062b4cfb..83bf360cb 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-from-cache.test.js b/tests/tx/sqlite-v2-sct-from-cache.test.js index 5b5cf3280..e94b920c5 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/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 0950dedcf..e1dac24c9 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,39 +152,38 @@ 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) { - // every link: a filter value may be the target's code or its display (cs-loinc.js matches - // relationships by Codes.Description), reported with the target's display as its description - const link = (code, extra = {}) => b.property({ code, uri: `${PROP}/${code}`, shape: 'link', display: code, matchDisplay: true, + // 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)])); // STATUS is the concept's status (role 'status') - // the literals: values in any case; STATUS NotStated where a concept has none const lit = Object.fromEntries(LITERALS.map(([c]) => [c, b.property({ code: c, uri: `${PROP}/${c}`, shape: 'literal', fhirType: 'string', display: c, - valueAnyCase: true, presentation: c === 'CLASSTYPE' ? { value: 'string', parts: ['description'] } : { value: 'string' }, - ...(c === 'STATUS' ? { role: 'status', defaultValue: 'NotStated' } : {}) })])); - // Answer is also asked for as answer-list; answers-for selects the members of the lists + 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', { selectsMembers: true }); + const answersFor = link('answers-for'); + 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, 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', - filterOps: ['='], report: 'never' }); + const copyright = b.property({ code: 'copyright', uri: `${PROP}/copyright`, shape: 'literal', fhirType: 'code', display: 'copyright' }); b.deriveFacts((db) => db.prepare(`INSERT INTO literal 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.property({ code: 'child', uri: `${PROP}/child`, shape: 'link', display: 'child', inverseOf: parent, matchDisplay: true, presentation: { parts: ['description'] } }); - const listLinks = b.property({ code: 'Answer|answers-for', shape: 'union', display: 'Answer and answers-for', filterable: false }); - b.propertyMember(listLinks, answer); - b.propertyMember(listLinks, answersFor); - b.property({ code: 'AnswerList', uri: `${PROP}/AnswerList`, shape: 'link', display: 'AnswerList', inverseOf: listLinks, matchDisplay: true, presentation: { parts: ['description'] } }); - const ancestor = b.property({ code: 'ancestor', uri: `${PROP}/ancestor`, shape: 'link', display: 'ancestor (PATH_TO_ROOT)' }); - b.setClosureFrom(parent, ancestor); + 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 }; } @@ -211,6 +212,88 @@ const LOINC_MAPS = [ ['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' }, + implicitValueSets: [ + { url: 'http://loinc.org/vs', include: {} }, + { url: 'http://loinc.org/vs/{v}', v: '^LP', mustBeCode: true, include: { filter: [{ property: 'ancestor', op: '=', value: '{v}' }] } }, + { url: 'http://loinc.org/vs/{v}', v: '^LL', mustBeCode: true, enumerate: { property: 'LIST', op: '=', value: '{v}' } }, + ], + 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, + 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' }, + ...LOINC_MAPS.map(([, key]) => ({ code: key, shape: 'mapping', fhirType: 'Coding' })), + ], + 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}`; @@ -220,36 +303,6 @@ function loincCodeSystem(b, version, description) { 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) } }); - // 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('versionAlgorithm', 'natural'); - // a concept's links in source order (link.seq), as cs-loinc.js reads its Relationships (meta - // linkOrder: this reader's LOINC $lookup lists them in its own fixed groups) - b.setMeta('linkOrder', 'seq'); - // RELATEDNAMES2 items are a $lookup property, not designations - b.reportUseAs('RELATEDNAMES2', 'RELATEDNAMES2'); - // the uses whose text is accepted as a display - for (const code of ['LONG_COMMON_NAME', 'SHORTNAME', 'LinguisticVariantDisplayName']) b.setUseRole(code, 'name'); - // text search: each concept's best name or code; ties by display, then the stored order - b.setBehaviour('textSearch', 'loinc'); - b.setMeta('searchTieBreak', 'display'); - // $lookup's property order (cs-loinc.js extendLookup): the axes, the other links, parent and child, - // the other properties, STATUS, RELATEDNAMES2, then the mappings (each map's key, last) - // the implicit concept maps http://loinc.org/cm/ over the mapping rows - // designations: the display first, then every designation (equal texts too), in item rank; the - // display's language en-US; a code it cannot locate: cs-loinc.js's message - b.setBehaviour('displayDesignation', 'distinct'); - b.setBehaviour('displayLanguage', 'en-US'); - b.setBehaviour('filterLocateMessage', 'Not a valid code: {code}'); - b.setBehaviour('declaresProperties', false); - b.setBehaviour('implicitValueSets', 'loinc'); - b.setBehaviour('implicitMaps', { base: 'http://loinc.org/cm/', maps: LOINC_MAPS }); - b.setBehaviour('lookupOrder', { ranks: { CLASS: 0, COMPONENT: 1, PROPERTY: 2, TIME_ASPCT: 3, SYSTEM: 4, SCALE_TYP: 5, METHOD_TYP: 6, AnswerList: 8, - parent: 9, child: 9, STATUS: 11, RELATEDNAMES2: 12, ...Object.fromEntries(LOINC_MAPS.map(([, key]) => [key, 13])) }, concept: 8, other: 10 }); - // text search reads the display (English) and every name but RELATEDNAMES2 - b.setMeta('ix.ix_word.names', { display: 'en', items: { designations: true, excludeUses: ['RELATEDNAMES2'] } }); } /** @param {object} cfg { source, dest, version, overwrite, log, hierarchyArrays: 'auto' | 'always' | 'never' } */ diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 1b3ba72e0..179c126ec 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -4,12 +4,16 @@ // 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 @@ -24,8 +28,9 @@ // 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 (internal: no +// filter row reads them in this revision). 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. @@ -49,6 +54,45 @@ 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): 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:). + */ +const RXNORM_READING = { + 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' }, + compatibility: { displayDesignation: 'once', designationUse: 'none', expansionDeclaresProperties: false }, + }, + rows: [ + // the qualified (`@`) storage rows: union members only + { codeContains: '@', internal: true }, + // the atom-level rows (--atom-relationships): storage only in this revision (no filter reads 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:' }, + { code: 'concept', operators: EQ_IN, reads: 'concept' }, + { code: 'code', operators: EQ_IN, reads: 'concept' }, + ], +}; + /** @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}`; @@ -66,46 +110,11 @@ async function importRxNormV2(cfg) { caseSensitive: true, defaultLanguage: 'en-US', // the catalog id, as cs-rxnorm.js forms it (CodeSystem/x-RxNorm-) resource: { resourceType: 'CodeSystem', id: 'x-' + rxnormCatalogId(v) } }); - // 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'); - // answers select the concepts in RXNCONSO (a SUPPRESS literal), never the RXNATOMARCHIVE-only ones - b.setBehaviour('domain', 'SUPPRESS'); - // designations: the display first, the atom equal to it not repeated; archived atoms listed like - // active ones; versions are dates MMDDYYYY; the display's language en-US - b.setBehaviour('displayDesignation', 'first'); - b.setBehaviour('inactiveDesignations', 'plain'); - b.setBehaviour('versionFormat', 'MMDDYYYY'); - b.setBehaviour('displayLanguage', 'en-US'); - b.setBehaviour('declaresProperties', false); - // text search: the best atom name or code among the concepts with a non-SY atom; ties by code (text) - b.setBehaviour('textSearch', 'rxnorm'); - b.setMeta('searchTieBreak', 'code'); - b.setBehaviour('lookupOrder', { ranks: { TTY: 0, STY: 1, SAB: 2 }, other: 3, byCode: true }); - // text search reads the atoms of the concepts in RXNCONSO (those with a SUPPRESS literal), as English - b.setMeta('ix.ix_word.names', { items: { designations: true, conceptsWith: 'SUPPRESS', language: 'en' } }); - // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships - const EQ_IN = ['=', 'in']; + b.reading(RXNORM_READING); - // (named in any case and matched in any case, as cs-rxnorm.js) - const lit = (code, display, extra = {}) => b.property({ code, uri: `${RXNORM}/${code}`, shape: 'literal', fhirType: 'code', display, filterOps: EQ_IN, - nameAnyCase: true, valueAnyCase: true, ...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; $lookup never reports - // it (report 'never': cs-rxnorm.js has no such property) - const TTY = lit('TTY', 'Term Type'), SAB = lit('SAB', 'Source'), SUPPRESS = lit('SUPPRESS', 'Suppress flag', { filterable: false, filterOps: null, report: 'never' }), - STY = lit('STY', 'Semantic Type (TUI)'); - // the status of an inactive concept (role 'status', never reported): obsolete (still in RXNCONSO, - // a SUPPRESS literal) or archived (RXNATOMARCHIVE only); archived ones are deprecated - const STATUS = b.property({ code: 'status', uri: `${RXNORM}/status`, shape: 'literal', fhirType: 'code', display: 'Status', - role: 'status', report: 'never', filterable: false }); - b.setBehaviour('deprecatedStatus', ['archived']); - b.deriveFacts((db) => db.prepare(`INSERT INTO literal SELECT c.id, ?, 0, - CASE WHEN EXISTS (SELECT 1 FROM literal l WHERE l.subject_id = c.id AND l.property_id = ?) THEN 'obsolete' ELSE 'archived' END, 1 - FROM concept c WHERE c.active = 0`).run(STATUS, SUPPRESS).changes); + 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(); @@ -154,9 +163,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'))) { @@ -169,7 +179,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]); @@ -189,10 +200,8 @@ async function importRxNormV2(cfg) { }); // RXNREL: RXCUI1|RXAUI1|STYPE1|REL|RXCUI2|RXAUI2|STYPE2|RELA|RUI|SRUI|SAB|SL|DIR|RG|SUPPRESS|CVF - // $lookup reports a relationship only when the request asks for properties (report 'named', as - // cs-rxnorm.js: by name or *, never by default) - const relProp = (rel) => b.property({ code: rel, uri: `${RXNORM}/${rel}`, shape: 'link', display: rel, wildcard: false, filterOps: EQ_IN, report: 'named' }); - const relaProp = (rela) => b.property({ code: rela, uri: `${RXNORM}/${rela}`, shape: 'link', display: rela, wildcard: true, filterOps: EQ_IN, report: 'named' }); + 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(); @@ -200,7 +209,7 @@ async function importRxNormV2(cfg) { let p = noRelaOf.get(rel); if (p === undefined) { // (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, filterable: false, report: 'never' }); + 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); } @@ -212,7 +221,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; @@ -224,7 +233,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); @@ -277,7 +286,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, report: 'never' }); + 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]); @@ -294,6 +303,11 @@ async function importRxNormV2(cfg) { 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; @@ -346,7 +360,7 @@ class RxNormV2Module extends BaseTerminologyModule { .description('Import an unzipped RxNorm full release (rrf folder) into a terminology file') .requiredOption('-s, --source ', 'the rrf/ folder of the release') .requiredOption('-d, --dest ', 'destination .db') - .option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI: filters (otherwise refused)'), version) + .option('--atom-relationships', 'also store RXNREL\'s atom-level rows (storage only: no filter reads them in this format revision)'), version) .action(importAction(this, async (o) => { const c = await resolveCommonOptions(o, version); const s = await importRxNormV2({ source: o.source, dest: o.dest, version: c.version, diff --git a/tx/importers/readme.md b/tx/importers/readme.md index 706225252..f72986d8d 100644 --- a/tx/importers/readme.md +++ b/tx/importers/readme.md @@ -547,8 +547,9 @@ Importer-specific options: `auto`, which fixes caches built east of UTC); `--force` imports a cache with known defects. `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) +- `rxnorm-v2`: `--atom-relationships` also stores RXNREL's atom-level rows (storage only: the + fhir-reading revision has no filter row for `REL` / `RELA` = `AUI:`, so those filters are + refused either way) 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 7e2ef13d2..37c29ae50 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' +// 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,8 +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 -> {system, name it is reported as} */ -const SCHEME_SYSTEMS = { '30051010000102': { system: 'http://loinc.org', name: 'loinc' } }; +/** 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'; @@ -71,6 +71,66 @@ 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 }, + }, + // (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: ['='], 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: ['='], reads: '{1}' }, + { codePattern: '^mapped:([0-9]{6,18})$', operators: ['exists'], reads: '{1}' }, + ], +}; const displayRefsetsFor = (edition) => DISPLAY_REFSETS[edition] || [US_ENGLISH, GB_ENGLISH]; /** @@ -222,39 +282,7 @@ class SnomedSink { 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'); - // versions are URIs (http://snomed.info/sct//version/) - b.setBehaviour('versionAlgorithm', 'url'); - // text search: the shortlist by distinct-word count over designations; ties in code order as - // numbers (the order of the stored rank, cs-snomed.js's concept order) - b.setBehaviour('textSearch', 'snomed'); - b.setMeta('searchTieBreak', 'code-length'); - // display regex over the FSNs and synonyms; generalizes leaves out the concept; whole-system - // selections active only; no text definition reported (as cs-snomed.js); inactive descriptions - // listed with their status; the display en-US - b.setBehaviour('displayRegex', 'designations'); - b.setBehaviour('generalizesExcludesSelf', true); - b.setBehaviour('wholeActiveOnly', true); - b.setBehaviour('lookupDefinition', false); - b.setBehaviour('inactiveDesignations', 'status'); - b.setBehaviour('displayLanguage', 'en-US'); - // the display is not listed again as a designation (the SNOMED CT provider lists its descriptions) - b.setBehaviour('displayDesignation', 'none'); - b.setBehaviour('declaresProperties', false); - b.setBehaviour('implicitValueSets', 'snomed'); - // the description types by role (item_use.role) - b.setUseRole(FSN, 'fsn'); - b.setUseRole(SYNONYM, 'synonym'); - b.setBehaviour('lookupOrder', { ranks: { effectiveTime: 0, parent: 1, child: 2, moduleId: 3, sufficientlyDefined: 4, semanticTag: 5 }, other: 6 }); - // semanticTag: stored, one value per concept that has one (semanticTags below) - const tagProp = b.property({ code: 'semanticTag', shape: 'literal', fhirType: 'string', filterable: false, refinable: false, wildcard: false, report: 'named' }); - b.deriveFacts((db) => semanticTags(db, tagProp)); - // text search reads the active descriptions (and text definitions) in their own language, and - // ranks one-word filters by each concept's distinct-word count - b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: 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, @@ -262,13 +290,11 @@ 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 - // how $lookup reports them (SNOMED CT on FHIR): is-a as parent; moduleId also asked for as module; - // the definition status as the boolean sufficientlyDefined (true for fully defined), only when asked for - this.isA = b.property({ code: IS_A, uri: `${SCT}/${IS_A}`, shape: 'link', subsumption: true, refinable: true, wildcard: false, reportedAs: 'parent', + // (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, alsoAskedAs: ['module'] }); - this.defStatus = b.property({ code: 'definitionStatusId', shape: 'link', display: 'Definition status', refinable: false, wildcard: false, - reportedAs: 'sufficientlyDefined', trueValue: '900000000000073002', report: 'named' }); + this.module = b.property({ code: 'moduleId', shape: 'link', display: 'Module', refinable: false, wildcard: false }); + this.defStatus = b.property({ code: 'definitionStatusId', shape: 'link', display: 'Definition status', refinable: false, wildcard: false }); this.effTime = b.property({ code: 'effectiveTime', shape: 'literal', fhirType: 'dateTime', display: 'Effective time', refinable: false, wildcard: false }); this.displayRefsets = cfg.displayRefsets; // language members, held until the descriptions: [key, refset handle, acceptability handle] @@ -364,10 +390,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); - // an attribute with relationship rows and concrete values: its links are read only where it is - // named (cs-snomed.js keeps one value kind per attribute: $lookup reads its concrete values) - return this.b.property({ code: type, uri: `${SCT}/${type}`, shape: both ? 'both' : 'literal', fhirType, refinable: true, wildcard: true, namedLinks: both, - valueAnyCase: true, presentation: { parts: ['code-display'] } }); + // 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) */ @@ -387,8 +412,8 @@ 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 }); + // (not a filter name: cs-snomed.js takes no `child` filter) + this.b.property({ code: 'child', shape: 'link', display: 'Child', inverseOf: this.isA, refinable: false, wildcard: false }); // language refset rows, now that the descriptions are items const L = this.lang; for (let k = 0; k < L.key.length; k++) { @@ -417,10 +442,10 @@ class SnomedSink { if (scheme === undefined || c === undefined) return; let p = this.schemes.get(schemeCode); if (p === undefined) { - // the LOINC scheme's values are LOINC codes, reported as the property loinc + // 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.system, reportedAs: valueOf.name } : {}) }); + ...(valueOf ? { valueSystem: valueOf } : {}) }); this.schemes.set(schemeCode, p); } this.b.identifier(p, value, c); @@ -493,6 +518,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); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 54a559433..09ee3ca29 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -5,14 +5,20 @@ // 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; 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; +// (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()), finishes the file // (finishFile: checks every meta key against the list this builder knows) and VACUUMs (unless @@ -27,7 +33,7 @@ const crypto = require('crypto'); const Database = require('better-sqlite3'); const { numberConcepts } = require('../sqlite-v2/numbering'); const { buildIndexes } = require('./indexes'); -const { readMeta, WRITTEN_FEATURES } = require('../../sqlite-v2/meta'); +const { readMeta, WRITTEN_FEATURES, FILTER_OPERATORS } = require('../../sqlite-v2/meta'); const { computeIntegrity, integrityValue } = require('../../sqlite-v2/integrity'); const SCHEMA_PATH = path.join(__dirname, 'schema.sql'); @@ -36,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 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 @@ -144,9 +170,41 @@ class TerminologyBuilder { return this.systems.length; } - /** a behaviour setting (meta behaviour., a JSON value; tx/sqlite-v2/meta.js KEYS) */ - 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}]: 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, 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 and reading that row; + * 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 */ @@ -165,16 +223,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' | 'never': when $lookup and expansions report it), reportedAs (the - * name it is reported and asked for under), alsoAskedAs ([names] a request may also ask by), - * trueValue (reported as a boolean: true when its value is this), namedLinks (its links are read - * only where the property is named) } + * 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; @@ -184,35 +241,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.report != null && !['named', 'always', 'never'].includes(spec.report)) throw new Error(`property ${spec.code}: bad report ${spec.report}`); if (spec.role === 'status' && spec.shape !== 'literal') throw new Error(`property ${spec.code}: the status role is for a literal property`); - if (spec.alsoAskedAs != null && !(Array.isArray(spec.alsoAskedAs) && spec.alsoAskedAs.every((x) => typeof x === 'string' && x))) { - throw new Error(`property ${spec.code}: alsoAskedAs is a list of names`); - } 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, namedLinks: spec.namedLinks ? 1 : 0, - filterOps: spec.filterOps ? JSON.stringify(spec.filterOps) : null, report: spec.report ?? null, + ordered: spec.ordered ? 1 : 0, fields: spec.fields ? JSON.stringify(spec.fields) : null, - selectsMembers: spec.selectsMembers ? 1 : null, nameAnyCase: spec.nameAnyCase ? 1 : null, valueAnyCase: spec.valueAnyCase ? 1 : null, - defaultValue: spec.defaultValue ?? null, matchDisplay: spec.matchDisplay ? 1 : null, valueSystem: spec.valueSystem ?? null, + valueSystem: spec.valueSystem ?? null, presentation: spec.presentation ? JSON.stringify(spec.presentation) : null, - reportedAs: spec.reportedAs ?? null, alsoAskedAs: spec.alsoAskedAs && spec.alsoAskedAs.length ? JSON.stringify(spec.alsoAskedAs) : null, - trueValue: spec.trueValue == null ? null : String(spec.trueValue), + 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) : [], }; @@ -251,14 +307,6 @@ class TerminologyBuilder { setDisplay(i, display) { this.display[i] = display; } setSortKey(i, key) { this.sortKey[i] = key; } - /** - * The items of the uses with this code are reported as values of a property of this name, not as - * designations (item_use.reported_as) - */ - reportUseAs(code, name) { - (this.reportedUses || (this.reportedUses = new Map())).set(code, name); - } - /** * 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 @@ -267,12 +315,6 @@ class TerminologyBuilder { (this.derivers || (this.derivers = [])).push(fn); } - /** the uses with this code have this role (item_use.role: fsn, synonym or name) */ - setUseRole(code, role) { - if (!['fsn', 'synonym', 'name'].includes(role)) throw new Error(`item use ${code}: bad role ${role}`); - (this.useRoles || (this.useRoles = new Map())).set(code, role); - } - /** an item_use coding; returns its use_id */ use({ system = null, code, display = null }) { const k = `${system || ''}|${code}`; @@ -433,6 +475,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 @@ -444,6 +519,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 }); + 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); @@ -484,9 +573,12 @@ 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 (?,?,?,?,?,?)'); + // 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()) { - insUse.run(u.id, u.system, u.code, u.display, (this.reportedUses && this.reportedUses.get(u.code)) ?? null, (this.useRoles && this.useRoles.get(u.code)) ?? null); + 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 (?,?,?,?,?)'); @@ -507,7 +599,20 @@ class TerminologyBuilder { 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 @@ -515,14 +620,16 @@ class TerminologyBuilder { // 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, - subsumption, closure_from, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, named_links, filter_ops, report, reported_as, - also_asked_as, true_value, selects_members, name_any_case, value_any_case, default_value, match_display, value_system, presentation, 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, 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)) { @@ -532,9 +639,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, - p.subsumption, p.closureFrom, p.filterable, p.refinable, p.wildcard, p.inverseOf, byTarget, p.bySubject, p.ordered, p.namedLinks, p.filterOps, p.report, p.reportedAs, - p.alsoAskedAs, p.trueValue, p.selectsMembers, p.nameAnyCase, p.valueAnyCase, p.defaultValue, p.matchDisplay, p.valueSystem, p.presentation, 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); @@ -585,6 +713,108 @@ class TerminologyBuilder { } } +/** 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; + rows.push({ code: p.code, operators: f.operators, reads: p.code, 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) @@ -744,14 +974,126 @@ function checkContracts(db) { 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`); } - // a stored expansion order (behaviour.expansionOrder 'stored' / 'stored-self-first') has its arrays - const eo = one("SELECT value FROM main.meta WHERE key = 'behaviour.expansionOrder'"); - if (eo != null && JSON.parse(eo) !== 'ids' && !(arrays.has('rank') && arrays.has('ids'))) fail(`behaviour.expansionOrder ${eo} without ix_order rank and ids`); - if (one('SELECT count(*) FROM main.item_use WHERE reported_as IS NOT NULL') > 1) fail('more than one item use with reported_as'); - if (one("SELECT count(*) FROM main.property WHERE role = 'status'") > 1) fail('more than one property with role status'); - // meta requires is stated; a word index states its names - if (one("SELECT count(*) FROM main.meta WHERE key = 'requires'") !== 1) fail('meta requires is missing'); - if (langs.length && one("SELECT count(*) FROM main.meta WHERE key = 'ix.ix_word.names'") !== 1) fail('the word index has no meta ix.ix_word.names'); + // 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`); + } + // 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)}`); + } + } + 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`); + 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_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; + } + const d = byCode.get(x); + if (!d) fail(`${what}: reads ${x}, which is no property`); + if (d.internal) fail(`${what}: reads the internal property ${x}`); + } + 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`); + } + for (const g of filters) { + if (g.id < f.id && g.code != null && g.code === f.code && JSON.parse(g.operators).some((o) => ops.includes(o))) fail(`${what}: shares an operator with filter ${g.id}`); + } + } + // 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); @@ -764,4 +1106,4 @@ function checkContracts(db) { } -module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, finishFile, checkContracts, 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 e4a0f5287..68c17e171 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('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('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, filterable, refinable, wildcard, inverse_of, by_target, by_subject, ordered, fields FROM property`, - (r) => { r[3] = key(r[3]); r[9] = r[9] == null ? null : pcode.get(r[9]); r[13] = r[13] == null ? null : pcode.get(r[13]); return r; }); + 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 4b588242e..ae7d7be7e 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) @@ -19,10 +19,10 @@ // ix_text_item item.text, rowid = item id // 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 -// ix.ix_word.names selects (the importer states it; it is kept across a -// rebuild), 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. -// A file without ix.ix_word.names gets no word index +// 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('better-sqlite3'); @@ -66,8 +66,6 @@ function dropIndexes(db) { } const keepKeys = derived.map((d) => `ix.${d.table}.${d.name}.`); for (const k of db.prepare("SELECT key FROM meta WHERE key LIKE 'ix.%'").pluck().all()) { - // ix.ix_word.names is the importer's statement of what the word index holds: kept - if (k === 'ix.ix_word.names') continue; 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 @@ -80,8 +78,9 @@ function dropIndexes(db) { */ function buildIndexes(db, opts = {}) { const time = opts.time || ((name, fn) => fn()); - // the names the word index holds: the importer's statement (none: no word index) - const names = db.prepare("SELECT value FROM main.meta WHERE key = 'ix.ix_word.names'").pluck().get(); + // 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(); @@ -105,11 +104,13 @@ function buildIndexes(db, opts = {}) { db.exec('BEGIN'); // 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 (names != null) { + if (search != null) { const setMeta = db.prepare('INSERT OR REPLACE INTO main.meta VALUES (?, ?)'); - setMeta.run('ix.ix_word.names', names); const store = new Store(db.name, { db, unregistered: true }); - const byLang = computeTextIndexFrom((fn) => eachSearchName(store, fn), !!JSON.parse(names).counts, n); + // 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 @@ -122,6 +123,62 @@ 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); + 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 = {}; @@ -173,14 +230,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} @@ -309,7 +361,7 @@ 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, then // finish it as the builder does (builder.js finishFile) diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index b6e6c1b98..2d071579b 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -231,11 +231,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', the names it holds --- in 'ix.ix_word.names', each language's stemmer in 'ix.ix_word.stemmers'; README.md "Word index"): 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), where the names selection says counts. +-- 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); From f20bbc4a3c7554fbc034c9d5a8b73d673c4650e2 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 11:11:54 -0600 Subject: [PATCH 50/90] sqlite-v2: keep the previous answers at the revision's open points; tests for the revision The reader keeps the previous answers where the revision's text is still being settled, each place marked with the section it waits on: the display designation's language is the default language, the status value 'active' only as written is no status text, a then_link row that reads only the concept (LOINC LIST) lists in the stored order, an inverse row reports no code-display, a file without meta version matches by its resource's versionAlgorithm. A SNOMED CT filter the file does not understand is named as concept where its rows read the concept. The display in a requested language matches tags itself. The index builder also writes the hierarchy's and the search candidates' sets. Tests: the format test is rewritten for the revision (identification, concept status and the statusReadingsIgnored switch, property reporting, filter rows, designations, search, versions, implicit value sets and maps, limits, contracts, integrity); the engine, regex, version-check, format-cases, default-language and mixed-providers tests state their fixtures' reading. AUI: filter values wait on the spec and are skipped. Co-Authored-By: Claude --- tests/tx/sqlite-v2-engine.test.js | 101 +- tests/tx/sqlite-v2-format-cases.test.js | 18 +- tests/tx/sqlite-v2-format-round2.test.js | 1393 ----------------- tests/tx/sqlite-v2-format.test.js | 811 ++++++++++ tests/tx/sqlite-v2-mixed-providers.test.js | 5 +- tests/tx/sqlite-v2-regex.test.js | 8 +- .../tx/sqlite-v2-sct-default-language.test.js | 14 +- tests/tx/sqlite-v2-version-check.test.js | 32 +- tx/importers/sqlite-v2/indexes.js | 8 + tx/sqlite-v2/README.md | 24 +- tx/sqlite-v2/engine/compile.js | 17 +- tx/sqlite-v2/provider.js | 64 +- tx/sqlite-v2/snomed.js | 8 + tx/sqlite-v2/store.js | 15 - 14 files changed, 996 insertions(+), 1522 deletions(-) delete mode 100644 tests/tx/sqlite-v2-format-round2.test.js create mode 100644 tests/tx/sqlite-v2-format.test.js diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index 68ef7bb55..ae986af3a 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,8 +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' }); - // (inactive items listed with their status) - b.setBehaviour('inactiveDesignations', 'status'); + // 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 @@ -57,17 +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 concepts answers select (behaviour.domain): 1-4; 5 is archived (in the file, never selected) - const sup = b.property({ code: 'SUPPRESS', shape: 'literal', fhirType: 'code', filterable: false }); - for (const code of ['1', '2', '3', '4']) b.literal(c[code], sup, 'N'); - b.setBehaviour('domain', 'SUPPRESS'); + // 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 @@ -102,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)) }; } @@ -131,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([]); }); @@ -146,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; } @@ -168,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 @@ -183,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 }); @@ -210,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); @@ -219,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 }); @@ -345,7 +359,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'); }); }); @@ -356,6 +370,8 @@ 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 }); @@ -386,9 +402,10 @@ describe('sqlite-v2 SNOMED concept in / code in', () => { 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), resolveFilterName: (n) => n, 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 }); }); @@ -571,7 +588,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 { @@ -599,7 +616,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 () => { @@ -639,13 +656,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)', () => { - // one file per selection of names (meta ix.ix_word.names): the display mode reads LOINC's, the - // designation mode SNOMED CT's + // 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.setMeta('ix.ix_word.names', names); + 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' }); @@ -656,25 +673,25 @@ describe('text filter in one language (store.searchText)', () => { return openStore(path.join(dir, name)); }; beforeAll(() => { - td = build('text.db', { display: 'en', items: { excludeUses: ['RELATEDNAMES2'] } }); - ts = build('text-desig.db', { items: { active: true, designations: true }, counts: true }); + 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(); 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(td.searchText('volumen', null, 'display', 'en'), td)).toEqual([]); - expect(ids(td.searchText('volumen', null, 'display', 'de'), td)).toEqual(['G']); - expect(ids(td.searchText('glucose', null, 'display', 'en'), td)).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(td.searchText('hgb', null, 'display', 'en'), td)).toEqual(['H']); - expect(ids(td.searchText('blut', null, 'display', 'de'), td)).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-format-cases.test.js b/tests/tx/sqlite-v2-format-cases.test.js index a3153abe4..be0cec948 100644 --- a/tests/tx/sqlite-v2-format-cases.test.js +++ b/tests/tx/sqlite-v2-format-cases.test.js @@ -163,15 +163,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 () => { @@ -207,7 +206,9 @@ 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); } }; - test.each(AUI)('every source\'s atom rows: as main (cs-rxnorm.js) %j', async (...filters) => { + // AUI: values over the atom-level rows have no filter rows in the fhir-reading revision (waits on the + // spec: section 14, RxNorm atom-level relationships); a file built with them refuses AUI: values + test.skip.each(AUI)('every source\'s atom rows: as main (cs-rxnorm.js) %j', async (...filters) => { const want = await run(classic, filters); expect(want.status).toBe(200); expect(await run(rxAtoms, filters)).toEqual(want); @@ -227,7 +228,6 @@ describe('4. RxNorm atom-level relationships (importer option atomRelationships) }); test('the default build has no atom rows: AUI: values are refused (422), CUI: values answered as main', async () => { - expect(rx.store.hasAtomRelationships).toBe(false); const r = await run(rx, AUI[0]); expect(r.status).toBe(422); expect(await run(rx, [['has_ingredient', '=', 'CUI:200']])).toEqual(await run(classic, [['has_ingredient', '=', 'CUI:200']])); diff --git a/tests/tx/sqlite-v2-format-round2.test.js b/tests/tx/sqlite-v2-format-round2.test.js deleted file mode 100644 index 181062c86..000000000 --- a/tests/tx/sqlite-v2-format-round2.test.js +++ /dev/null @@ -1,1393 +0,0 @@ -'use strict'; - -// The terminology file format (tx/sqlite-v2/README.md): the meta rule (requires, known keys checked, -// unknown keys ignored, the builder's own list), on a small generic fixture. - -const fs = require('fs'); -const os = require('os'); -const path = require('path'); -const Database = require('better-sqlite3'); -const { TerminologyBuilder } = require('../../tx/importers/sqlite-v2/builder'); -const { openStore } = require('../../tx/sqlite-v2/store'); -const { readMeta } = require('../../tx/sqlite-v2/meta'); - -let dir; -beforeAll(() => { dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-r2-')); }); -afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }); }); - -let seq = 0; -/** a small file: a hierarchy, a literal, designations, identifiers; build(b, c) adds to it */ -function fixture(build = null, { uri = 'http://example.org/cs' } = {}) { - 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' }); - 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.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, v); - } - w.close(); - return f; -} - -function withStore(file, fn) { - const S = openStore(file, { unregistered: true }); - try { return fn(S); } finally { S.close(); } -} - -describe('P1. meta: requires, known keys checked, unknown keys ignored', () => { - let base; - beforeAll(() => { base = fixture(); }); - - test('a required feature this reader does not know refuses the file, naming it', () => { - expect(() => openStore(withMeta(base, { requires: '["identifier-text", "time-travel"]' }))).toThrow(/requires the feature time-travel, which this server does not know/); - }); - - test('requires must be a list of distinct strings', () => { - expect(() => openStore(withMeta(base, { requires: '"identifier-text"' }))).toThrow(/meta requires = "identifier-text" is not a value/); - expect(() => openStore(withMeta(base, { requires: '["a", "a"]' }))).toThrow(/meta requires = .* is not a value/); - }); - - test('an unknown meta key is ignored (a behaviour.* key too)', () => { - const f = withMeta(base, { 'colour.of.the.day': 'blue', 'behaviour.colour': 'not even JSON', 'ix.ix_word.someday': '{' }); - withStore(f, (S) => { - expect(S.system).toBe('http://example.org/cs'); - expect(S.behaviour.colour).toBeUndefined(); - }); - const m = readMeta(new Database(f, { readonly: true }).prepare('SELECT key, value FROM meta').raw().all(), f); - expect(m.ignored.sort()).toEqual(['behaviour.colour', 'colour.of.the.day', 'ix.ix_word.someday']); - }); - - test('a known key with a malformed value is refused, naming key and value', () => { - expect(() => openStore(withMeta(base, { 'behaviour.expansionOrder': '"sideways"' }))).toThrow(/meta behaviour.expansionOrder = "sideways" is not a value this server knows/); - expect(() => openStore(withMeta(base, { 'behaviour.distinctDesignationTexts': 'yes' }))).toThrow(/meta behaviour.distinctDesignationTexts = yes 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, { propertyUris: '[["code"]]' }))).toThrow(/meta propertyUris = .* is not a value/); - withStore(withMeta(base, { propertyUris: '[["code", "http://example.org/p#code"]]' }), (S) => expect(S.conceptCount).toBe(5)); - }); - - test('the builder refuses to finish a file with a key it does not know', () => { - 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, 'never2.db'), { overwrite: true, importer: 'test' }); - b2.codeSystem({ uri: 'http://example.org/x', version: '1' }); - b2.concept('a'); - b2.setBehaviour('expansionOrdre', 'stored'); - expect(() => b2.finish()).toThrow(/meta behaviour.expansionOrdre is not a key this builder knows/); - }); - - test('readBehaviour (exported): every behaviour key with its default, the file\'s values, a malformed one refused', () => { - const { readBehaviour } = require('../../tx/sqlite-v2/store'); - const b = readBehaviour([['behaviour.expansionOrder', '"stored"'], ['behaviour.unknown', 'x']], 'f'); - expect(b).toMatchObject({ expansionOrder: 'stored', lookupName: 'name', grammar: null, expansionLimit: 0 }); - expect(b.unknown).toBeUndefined(); - expect(() => readBehaviour([['behaviour.lookupName', '"nick"']], 'f')).toThrow(/behaviour.lookupName = "nick" is not a value/); - }); - - test('provenance.* is free-form', () => { - const b = new TerminologyBuilder(path.join(dir, 'prov.db'), { overwrite: true, importer: 'test' }); - b.codeSystem({ uri: 'http://example.org/x', version: '1' }); - b.concept('a'); - b.setMeta('provenance.anything', 'goes'); - b.finish(); - withStore(path.join(dir, 'prov.db'), (S) => expect(S.conceptCount).toBe(1)); - }); -}); - - -describe('P2. identifier values are TEXT (requires identifier-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('the builder writes requires identifier-text; every stored value is text', () => { - const db = new Database(file, { readonly: true }); - try { - expect(JSON.parse(db.prepare("SELECT value FROM meta WHERE key = 'requires'").pluck().get())).toEqual(['identifier-text']); - 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')]); - }); - }); - - test('a file that does not require identifier-text (built before identifier values were text) is refused', () => { - expect(() => openStore(withMeta(file, { requires: null }))).toThrow(/built before identifier values were text .* rebuild it with the importers, or upgrade it/); - expect(() => openStore(withMeta(file, { requires: '[]' }))).toThrow(/built before identifier values were text/); - }); -}); - -describe('P3. word index: the names selection as data, 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; B: two 'banana tree' syns, flagged; C: nothing - const rich = (names) => fixture((b, c) => { - b.setMeta('ix.ix_word.names', names); - const flag = b.property({ code: 'FLAG', shape: 'literal', fhirType: 'string' }); - b.literal(c.B, flag, 'N'); - 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' }); - }); - 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({ 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 of the served system in its own language (none: the default language, then en)', () => { - const got = names(rich({ 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'); - }); - - test('items.active, items.designations, items.excludeUses', () => { - expect(names(rich({ items: { active: true } })).map((r) => r[2])).not.toContain('withered tree'); - expect(names(rich({ items: { designations: true } })).map((r) => r[2])).not.toContain('a definition without use'); - const ex = names(rich({ items: { excludeUses: ['RELATED', 'not-a-use'] } })).map((r) => r[2]); - expect(ex).not.toContain('related wording'); - expect(ex).toContain('apple tree'); - }); - - test('items.includeUses: only the items with a listed use (null: no use), combined with the other fields', () => { - expect(names(rich({ items: { includeUses: ['RELATED', null] } })).map((r) => r[2]).sort()).toEqual(['a definition without use', 'related wording']); - expect(names(rich({ items: { includeUses: ['RELATED', null], designations: true } })).map((r) => r[2])).toEqual(['related wording']); - expect(names(rich({ items: { includeUses: ['not-a-use'] } }))).toEqual([]); - expect(() => openStore(withMeta(rich({ items: {} }), { 'ix.ix_word.names': '{"items": {"includeUses": "syn"}}' }))).toThrow(/is not a value/); - }); - - test('items.conceptsWith: only the items of concepts with a row of that property; items.language: every item under it', () => { - expect(names(rich({ items: { conceptsWith: 'FLAG', language: 'en' } }))).toEqual([['B', 'en', 'banana tree'], ['B', 'en', 'banana tree']]); - expect(names(rich({ items: { conceptsWith: 'NO-SUCH-PROPERTY' } }))).toEqual([]); - expect(new Set(names(rich({ items: { language: 'fr' } })).map((r) => r[1]))).toEqual(new Set(['fr'])); - }); - - test('a file without ix.ix_word.names has no names to search, whatever its system (no table of systems)', () => { - expect(names(withMeta(rich({ items: {} }), { 'ix.ix_word.names': null }))).toEqual([]); - const sct = fixture((b) => b.setMeta('ix.ix_word.names', { items: { active: true, designations: true }, counts: true }), { uri: 'http://snomed.info/sct' }); - expect(names(sct).length).toBeGreaterThan(0); - const without = withMeta(sct, { 'ix.ix_word.names': null }); - expect(names(without)).toEqual([]); - withStore(without, (S) => { - expect(ti.textIndexOf(S)).not.toBeInstanceOf(ti.WordIndex); - expect(S.searchText('apple', null, 'designation', 'en').size).toBe(0); - }); - }); - - test('rebuilding the indexes of a file without ix.ix_word.names (node indexes.js) writes no word index', () => { - const { spawnSync } = require('child_process'); - const f = withMeta(rich({ items: {} }), { 'ix.ix_word.names': null }); - const r = spawnSync(process.execPath, [path.join(__dirname, '../../tx/importers/sqlite-v2/indexes.js'), f], { encoding: 'utf8' }); - expect(r.status).toBe(0); - 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(); } - }); - - test('the index builder writes the selection, the stemmer of each language, and the counts row little-endian (2 * (N + 1) bytes)', () => { - const f = rich({ items: { active: true, designations: true }, counts: true }); - 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.names'))).toEqual({ items: { active: true, designations: true }, counts: true }); - expect(JSON.parse(meta('ix.ix_word.stemmers'))).toEqual({ de: stemmerName('de'), en: stemmerName('en') }); - expect(stemmerName('en')).toBe('natural:PorterStemmer'); - expect(stemmerName('xx')).toBe('none'); - 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 (the inactive syn and the definition are not names) - expect(Array.from(ti.countsFromLE(ti.countsToLE(Uint16Array.from([1, 258, 65535]))))).toEqual([1, 258, 65535]); - expect([...ti.countsToLE(Uint16Array.from([258]))]).toEqual([2, 1]); - } finally { db.close(); } - // without counts: no counts row - const g = rich({ 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({ items: { active: true, designations: true }, counts: true }); - // de named with a stemmer this server does not have; the stored de rows emptied to show they are not read - const g = withMeta(f, { 'ix.ix_word.stemmers': JSON.stringify({ de: 'snowball:german', en: stemmerName('en') }) }); - const w = new Database(g); - w.prepare("UPDATE ix_word SET ids = ? WHERE lang = 'de' AND word <> ''").run(Buffer.from(new (require('roaring').RoaringBitmap32)().serialize('portable'))); - w.prepare("UPDATE ix_word SET ids = ? WHERE lang = 'en' AND word = 'banana'").run(Buffer.from(new (require('roaring').RoaringBitmap32)().serialize('portable'))); - w.close(); - withStore(g, (S) => { - const index = ti.textIndexOf(S); - expect(index.memLangs).toEqual(new Set(['de'])); - const codes = (bm) => bm.toArray().map((id) => S.conceptRows([id]).get(id).code); - expect(codes(S.searchText('apfelbaum', null, 'designation', 'de'))).toEqual(['A']); - // en is read from the stored index (where banana was emptied above) - expect(codes(S.searchText('apple', null, 'designation', 'en'))).toEqual(['A']); - expect(codes(S.searchText('banana', null, 'designation', 'en'))).toEqual([]); - }); - // the file's own stemmers: the stored index for every language - withStore(f, (S) => expect(ti.textIndexOf(S)).toBeInstanceOf(ti.WordIndex)); - // no ix.ix_word.stemmers: the stored index is not used (every language from the names, in memory) - withStore(withMeta(f, { 'ix.ix_word.stemmers': null }), (S) => { - expect(ti.textIndexOf(S)).toBeInstanceOf(ti.SplitTextIndex); - expect(ti.textIndexOf(S).memLangs).toEqual(new Set(['de', 'en'])); - }); - }); - - test('a malformed selection is refused', () => { - const f = rich({ items: {} }); - expect(() => openStore(withMeta(f, { 'ix.ix_word.names': '{"items": {"active": "yes"}}' }))).toThrow(/meta ix.ix_word.names = .* is not a value/); - expect(() => openStore(withMeta(f, { 'ix.ix_word.names': '{"scope": "snomed"}' }))).toThrow(/meta ix.ix_word.names = .* is not a value/); - }); -}); - -describe('P4. behaviour and order keys: the file\'s value obeyed, absent = the default', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { Designations } = require('../../tx/library/designations'); - const { writeOrderArray } = require('../../tx/importers/sqlite-v2/indexes'); - let op, base; - const factories = []; - beforeAll(async () => { - op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - base = fixture((b, c) => { - const site = b.property({ code: 'site', shape: 'link' }); - const area = b.property({ code: 'area', shape: 'link' }); - // 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.item(c.C, { language: 'en', text: 'cherry preferred', preferred: true }); - }); - }); - afterAll(() => { for (const f of factories) f.store.close(); }); - const provider = async (file) => { - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - factories.push(f); - return { f, p: await f.build(op, []) }; - }; - const designations = async (p, code) => { - const ds = new Designations(op.i18n.languageDefinitions); - await p.designations((await p.locate(code)).context, ds); - return ds.designations.filter((d) => !d.isDisplay && d.value !== `display ${code}`).map((d) => [d.value, d.use ? d.use.code : null]); - }; - const lookup = async (p, code) => { - const params = []; - await p.extendLookup((await p.locate(code)).context, [], params); - return params.map((x) => x.part.find((y) => y.name === 'code').valueCode + '=' + (x.part.find((y) => y.name === 'value').valueCode || x.part.find((y) => y.name === 'value').valueString)); - }; - - test('defaults: lookupName the name, versionAlgorithm none, every use kept, every text', async () => { - const { f, p } = await provider(base); - expect(p.lookupName()).toBe('Example'); - expect(p.versionAlgorithm()).toBeNull(); - expect(await designations(p, 'B')).toEqual([['banana tree', 'syn'], ['banana tree', 'syn']]); - expect(await designations(p, 'C')).toEqual([['cherry preferred', null]]); - expect(f.engine._order).toBeFalsy(); - }); - - test('behaviour.description is not a key (no answer reads it): a file carrying it is served, the key ignored', () => { - const f = withMeta(base, { 'behaviour.description': '"name"' }); - withStore(f, (S) => expect(S.behaviour.description).toBeUndefined()); - const db = new Database(f, { readonly: true }); - try { expect(readMeta(db.prepare('SELECT key, value FROM meta').raw().all(), f).ignored).toEqual(['behaviour.description']); } finally { db.close(); } - }); - - test('lookupName, versionAlgorithm', async () => { - const { p } = await provider(withMeta(base, { 'behaviour.lookupName': '"title"', 'behaviour.versionAlgorithm': '"semver"' })); - expect(p.lookupName()).toBe('The Example System'); - expect(p.versionAlgorithm()).toBe('semver'); - // with meta titles: the title of the first requested language that has one - const t = await provider(withMeta(base, { 'behaviour.lookupName': '"title"', titles: '{"de": "Das Beispiel"}' })); - expect(t.p.lookupName({ languages: [{ code: 'fr' }, { code: 'de-AT' }] })).toBe('Das Beispiel'); - expect(t.p.lookupName({ languages: [{ code: 'fr' }] })).toBe('The Example System'); - }); - - test('designationUses drop, distinctDesignationTexts, preferredForLanguage', async () => { - expect(await designations((await provider(withMeta(base, { 'behaviour.designationUses': '"drop"' }))).p, 'B')).toEqual([['banana tree', null], ['banana tree', null]]); - expect(await designations((await provider(withMeta(base, { 'behaviour.distinctDesignationTexts': 'true' }))).p, 'B')).toEqual([['banana tree', 'syn']]); - expect(await designations((await provider(withMeta(base, { 'behaviour.preferredForLanguage': 'true' }))).p, 'C')).toEqual([['cherry preferred', 'preferredForLanguage']]); - }); - - test('expansionOrder: stored lists in ix_order rank; ids (the default) in concept id order', async () => { - const stored = withMeta(base, { 'behaviour.expansionOrder': '"stored"' }); - const w = new Database(stored); - const codes = w.prepare('SELECT id, code FROM concept ORDER BY code DESC').raw().all(); - const n = codes.length; - const ids = new Uint32Array(n + 1), rank = new Uint32Array(n + 1); - codes.forEach(([id], i) => { ids[i] = id; rank[id] = i; }); - ids[n] = 0; rank[0] = n; - writeOrderArray(w, 'rank', rank); - writeOrderArray(w, 'ids', ids); - w.close(); - const { f } = await provider(stored); - expect(f.engine._order).toBeTruthy(); - const listed = f.engine.ordered({ t: 'all' }).map((id) => f.store.conceptRows([id]).get(id).code); - expect(listed).toEqual(['root', 'X', 'C', 'B', 'A']); - }); - - test('linkOrder: property (default), seq, property-seq, target-int; a value it does not know is refused', async () => { - const order = async (v) => (await lookup((await provider(v ? withMeta(base, { linkOrder: v }) : base)).p, 'A')).filter((x) => !x.startsWith('colour') && !x.startsWith('parent')); - // property ids: parent 1, colour 2, site 3, area 4 - expect(await order(null)).toEqual(['site=B', 'site=C', 'site=root', 'area=B']); - expect(await order('property')).toEqual(['site=B', 'site=C', 'site=root', 'area=B']); - expect(await order('seq')).toEqual(['site=C', 'area=B', 'site=root', 'site=B']); - expect(await order('property-seq')).toEqual(['site=C', 'site=root', 'site=B', 'area=B']); - expect(await order('target-int')).toEqual(['site=C', 'area=B', 'site=root', 'site=B']); - expect(() => openStore(withMeta(base, { linkOrder: 'random' }))).toThrow(/meta linkOrder = random is not a value/); - expect(() => openStore(withMeta(base, { searchTieBreak: 'id' }))).toThrow(/meta searchTieBreak = id is not a value/); - }); - - test('searchTieBreak rank: hits of equal score in the stored rank order', async () => { - const f = withMeta(base, { searchTieBreak: 'rank' }); - const w = new Database(f); - // rank: B before A (both match "tree" equally) - const id = (c) => w.prepare('SELECT id FROM concept WHERE code = ?').pluck().get(c); - const n = w.prepare('SELECT count(*) FROM concept').pluck().get(); - const order = ['B', 'A', 'C', 'X', 'root'].map(id); - const ids = new Uint32Array(n + 1), rank = new Uint32Array(n + 1); - order.forEach((x, i) => { ids[i] = x; rank[x] = i; }); - writeOrderArray(w, 'rank', rank); - writeOrderArray(w, 'ids', ids); - w.close(); - const codes = (S, ids2) => Array.from(ids2).map((x) => S.conceptRows([x]).get(x).code); - const gen = require('../../tx/sqlite-v2/text-index').genericTextSearch; - withStore(base, (S) => expect(codes(S, gen(S, 'tree', 'en', 'en').ids)).toEqual(['A', 'B'])); - withStore(f, (S) => expect(codes(S, gen(S, 'tree', 'en', 'en').ids)).toEqual(['B', 'A'])); - }); - - test('behaviour.aliases (identifier-aliased codes): this reader does not implement them and refuses a file that sets it; the three old keys are unknown', () => { - expect(() => openStore(withMeta(base, { 'behaviour.aliases': '{"extension": "http://example.org/ext"}' }))).toThrow(/behaviour.aliases is set .* does not implement/); - expect(() => openStore(withMeta(base, { 'behaviour.aliases': '{"literals": {"kind": "{code}"}}' }))).toThrow(/behaviour.aliases is set/); - expect(() => openStore(withMeta(base, { 'behaviour.aliases': '{"param": "x"}' }))).toThrow(/behaviour.aliases = .* is not a value/); - withStore(withMeta(base, { 'behaviour.aliases': 'null', 'behaviour.aliasLiterals': '{"kind": "{code}"}', 'behaviour.aliasProperty': '"x"' }), (S) => { - expect(S.behaviour.aliases).toBeNull(); - expect(S.behaviour.aliasLiterals).toBeUndefined(); - }); - }); -}); - -describe('P5. grammar: an open string, implemented by name; behaviour.filters applied', () => { - const { loadSqliteV2Factory, factoryForGrammar } = require('../../tx/sqlite-v2/index'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { SnomedV2Factory } = require('../../tx/sqlite-v2/snomed'); - const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); - const { Engine } = require('../../tx/sqlite-v2/engine/engine'); - let base, i18n; - beforeAll(async () => { - base = fixture(); - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - i18n = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())).i18n; - }); - - test('the registry: plain codes and snomed served; any other grammar refused, whatever the system', async () => { - expect(factoryForGrammar(null, 'f')).toBe(SqliteV2Factory); - expect(factoryForGrammar('snomed', 'f')).toBe(SnomedV2Factory); - for (const g of ['icd11', 'some-grammar']) { - const f = withMeta(base, { 'behaviour.grammar': JSON.stringify(g) }); - withStore(f, (S) => expect(S.behaviour.grammar).toBe(g)); - await expect(loadSqliteV2Factory(i18n, f)).rejects.toThrow(new RegExp(`its codes are in the grammar ${g} \\(behaviour.grammar\\), which this server does not implement`)); - // nor does the plain-code provider serve it when loaded directly - await expect(new SqliteV2Factory(i18n, f).load()).rejects.toThrow(/its codes are in the grammar/); - } - expect(() => openStore(withMeta(base, { 'behaviour.grammar': '""' }))).toThrow(/behaviour.grammar = "" is not a value/); - }); - - test('a filter, operator or value not in behaviour.filters is FILTER_NOT_UNDERSTOOD; a listed one is answered; the file is served', () => { - const f = withMeta(base, { 'behaviour.filters': JSON.stringify([{ code: 'colour', operator: ['=', 'in'], values: ['red', 'blue'] }, { code: 'inactive', operator: ['='] }]) }); - withStore(f, (S) => { - const c = new Compiler({ store: S, dialect: {} }); - const e = new Engine(S); - const codes = (node) => e.evaluate(node).toArray().map((id) => S.conceptRows([id]).get(id).code).sort(); - expect(codes(c.filter('colour', '=', 'red'))).toEqual(['A']); - expect(codes(c.filter('colour', 'in', 'red,blue'))).toEqual(['A', 'B']); - expect(codes(c.filter('inactive', '=', 'true'))).toEqual(['X']); - for (const [p, o, v] of [['colour', 'regex', 'r.*'], ['colour', '=', 'green'], ['colour', 'in', 'red,green'], ['parent', '=', 'A'], ['concept', 'is-a', 'A']]) { - let err = null; - try { c.filter(p, o, v); } catch (x) { err = x; } - expect(err && err.notUnderstood).toEqual([p, o, v]); - } - }); - // without the list: every filter the catalog allows - withStore(base, (S) => { - const c = new Compiler({ store: S, dialect: {} }); - expect(new Engine(S).evaluate(c.filter('concept', 'is-a', 'A')).size).toBe(2); - }); - }); -}); - -describe('P6. contracts checked by the builder; the CodeSystem columns kept; cheap id checks at open', () => { - const { checkContracts } = require('../../tx/importers/sqlite-v2/builder'); - let base; - beforeAll(() => { base = fixture((b) => b.setMeta('ix.ix_word.names', { items: {}, counts: true })); }); - /** a writable copy changed by sql, its contracts checked */ - const broken = (sql, ...args) => { - 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.prepare(sql).run(...args); - 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 item SET id = id + 100 WHERE id = (SELECT max(id) FROM item)')).toThrow(/contract: item ids are not exactly/); - expect(broken('UPDATE property SET subsumption = 1')).toThrow(/contract: more than one property with subsumption = 1/); - expect(broken("UPDATE ix_set SET value_kind = 2 WHERE kind = 1")).toThrow(/ix_set rows break the key conventions/); - expect(broken('DELETE FROM ix_in WHERE subject_id = (SELECT max(subject_id) FROM ix_in)')).toThrow(/contract: ix_in does not hold exactly/); - 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("INSERT OR REPLACE INTO meta VALUES ('behaviour.expansionOrder', '\"stored\"')")).toThrow(/contract: behaviour.expansionOrder "stored" without ix_order rank and ids/); - expect(broken('DROP INDEX item_concept')).toThrow(/contract: the index item_concept is missing/); - expect(broken("DELETE FROM meta WHERE key = 'requires'")).toThrow(/contract: meta requires is missing/); - expect(broken("DELETE FROM meta WHERE key = 'ix.ix_word.names'")).toThrow(/contract: the word index has no meta ix.ix_word.names/); - expect(broken('ANALYZE')).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'); - 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; n_rows and target_kind are gone', async () => { - const db = new Database(base, { readonly: true }); - try { - const cols = db.prepare('PRAGMA table_info(code_system)').all().map((c) => c.name); - expect(cols).toEqual(expect.arrayContaining(['case_sensitive', 'hierarchy_meaning', 'release_date'])); - const pcols = db.prepare('PRAGMA table_info(property)').all().map((c) => c.name); - expect(pcols).not.toContain('n_rows'); - expect(pcols).not.toContain('target_kind'); - } finally { db.close(); } - 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', () => { - const f = path.join(dir, `ids${++seq}.db`); - fs.copyFileSync(base, f); - const w = new Database(f); - w.prepare('UPDATE code_system SET concept_count = concept_count + 1 WHERE served = 1').run(); - w.close(); - expect(() => openStore(f)).toThrow(/concept ids are not 1\.\.6 \(concept_count\)/); - }); -}); - -describe('P7. 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((b) => b.setMeta('ix.ix_word.names', { items: {} })); }); - const copy = (change) => { - const f = path.join(dir, `v${++seq}.db`); - fs.copyFileSync(base, f); - change(f); - return f; - }; - - test('the builder writes meta integrity: items, schema and catalog digests', () => { - 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()); - expect(v.schema).toBe(require('../../tx/sqlite-v2/integrity').schemaDigest(db)); - } finally { db.close(); } - }); - - test('a finished file passes, and lists what was checked', () => { - const r = run(base); - expect(r.stdout).toMatch(/^ok {3}format/m); - expect(r.stdout).toMatch(/^ok {3}contracts/m); - expect(r.stdout).toMatch(/^ok {3}integrity: catalog digest/m); - expect(r.status).toBe(0); - }); - - test('a file without integrity facts is checked for the rest (they are optional)', () => { - const f = copy((p) => { const w = new Database(p); w.exec("DELETE FROM meta WHERE key = 'integrity'"); w.close(); }); - const r = run(f); - expect(r.stdout).toMatch(/integrity: the file states no integrity facts/); - expect(r.status).toBe(0); - // a reader opens it as any file - withStore(f, (S) => expect(S.conceptCount).toBe(5)); - }); - - test('corrupted copies fail with a non-zero exit, naming the check', () => { - const appended = copy((p) => fs.appendFileSync(p, Buffer.alloc(100))); - expect(run(appended).status).toBe(1); - expect(run(appended).stdout).toMatch(/^FAIL integrity: file length/m); - const catalog = copy((p) => { const w = new Database(p); w.exec("UPDATE property SET filterable = 0 WHERE code = 'colour'"); w.close(); }); - expect(run(catalog).stdout).toMatch(/^FAIL integrity: catalog digest/m); - expect(run(catalog).status).toBe(1); - const index = copy((p) => { const w = new Database(p); w.exec('DROP INDEX item_concept'); w.close(); }); - const r = run(index); - expect(r.stdout).toMatch(/^FAIL contracts: contract: the index item_concept is missing/m); - expect(r.stdout).toMatch(/^FAIL integrity: schema digest/m); - expect(r.status).toBe(1); - const meta = copy((p) => { const w = new Database(p); w.exec("UPDATE meta SET value = '\"sideways\"' WHERE key = 'behaviour.expansionOrder'; INSERT OR REPLACE INTO meta VALUES ('behaviour.expansionOrder', '\"sideways\"')"); w.close(); }); - expect(run(meta).stdout).toMatch(/^FAIL meta: .*behaviour.expansionOrder = "sideways"/m); - expect(run(path.join(dir, 'no-such.db')).status).toBe(1); - }); -}); - -describe('P8. property.report never / named / always; behaviour.expansionLimit', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - let op, f, p; - beforeAll(async () => { - op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const file = fixture((b, c) => { - const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'code', report: 'never' }); - const note = b.property({ code: 'note', shape: 'literal', fhirType: 'string', report: 'named' }); - const cls = b.property({ code: 'class', shape: 'literal', fhirType: 'code', report: 'always' }); - b.literal(c.A, kind, 'product'); - b.literal(c.A, note, 'a note'); - b.literal(c.A, cls, 'K1'); - b.setBehaviour('expansionLimit', 2); - }); - f = new SqliteV2Factory(op.i18n, file); - await f.load(); - p = await f.build(op, []); - }); - afterAll(() => f.store.close()); - const lookup = async (props) => { - const params = []; - await p.extendLookup((await p.locate('A')).context, props, params); - return params.map((x) => x.part.find((y) => y.name === 'code').valueCode); - }; - - test('never: not in $lookup (asked for or not), not on expansions, not a declared property; still a filter', async () => { - expect(await lookup([])).not.toContain('kind'); - expect(await lookup(['kind'])).not.toContain('kind'); - expect(await lookup(['*'])).not.toContain('kind'); - expect((p.propertyDefinitions() || []).map((d) => d.code)).not.toContain('kind'); - expect(await p.properties((await p.locate('A')).context, ['kind'])).toEqual([]); - const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); - expect(f.engine.evaluate(new Compiler({ store: f.store, dialect: {} }).filter('kind', '=', 'product')).size).toBe(1); - }); - - test('named: only when the request names it or asks for *, not by default; always: by default and on every expansion', async () => { - expect(await lookup([])).not.toContain('note'); - expect(await lookup(['*'])).toContain('note'); - expect(await lookup(['note'])).toContain('note'); - expect(await lookup(['class'])).not.toContain('note'); - expect(await lookup([])).toContain('class'); - expect(p.mandatoryExpansionProperties()).toEqual(['class']); - }); - - test('a report value the builder does not know is refused', () => { - const b = new TerminologyBuilder(path.join(dir, 'never3.db'), { overwrite: true, importer: 'test' }); - b.codeSystem({ uri: 'http://example.org/x', version: '1' }); - expect(() => b.property({ code: 'x', shape: 'literal', fhirType: 'string', report: 'sometimes' })).toThrow(/bad report sometimes/); - }); - - test('expansionLimit: the provider\'s expandLimitation; absent: 0 (no limit); malformed: refused', () => { - expect(p.expandLimitation()).toBe(2); - withStore(fixture(), (S) => expect(S.behaviour.expansionLimit).toBe(0)); - expect(() => openStore(withMeta(fixture(), { 'behaviour.expansionLimit': '-1' }))).toThrow(/behaviour.expansionLimit = -1 is not a value/); - expect(() => openStore(withMeta(fixture(), { 'behaviour.expansionLimit': '1.5' }))).toThrow(/behaviour.expansionLimit = 1.5 is not a value/); - }); -}); - -describe('P8b. an expansion of a system with expansionLimit takes the path that counts against it', () => { - test('handlesSelecting is off where the file sets a limit', async () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - for (const [meta, want] of [[{}, true], [{ 'behaviour.expansionLimit': '3' }, false]]) { - const f = new SqliteV2Factory(op.i18n, withMeta(fixture(), meta)); - await f.load(); - try { expect((await f.build(op, [])).handlesSelecting()).toBe(want); } finally { f.store.close(); } - } - }); -}); - -describe('P8. RxNorm: which properties $lookup reports is catalog data (report), with the same answers as the rule it replaces', () => { - const { importRxNormV2 } = require('../../tx/importers/import-rxnorm-v2.module'); - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const conso = (cui, aui, sab, tty, str, sup = 'N') => [cui, 'ENG', '', '', '', '', '', aui, '', '', '', sab, tty, cui, str, '', sup, ''].join('|') + '|'; - const cuiRel = (cui1, rel, cui2, rela) => [cui1, '', 'CUI', rel, cui2, '', 'CUI', rela, '', '', 'RXNORM', '', '', '', 'N', ''].join('|') + '|'; - let op, file; - beforeAll(async () => { - op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const rrf = path.join(dir, 'rrf'); - fs.mkdirSync(rrf, { recursive: true }); - fs.writeFileSync(path.join(rrf, 'RXNCONSO.RRF'), [conso('100', '1001', 'RXNORM', 'SCD', 'drug a 10 MG Oral Tablet'), conso('100', '1004', 'RXNORM', 'SY', 'drug a tablet'), - conso('200', '2001', 'RXNORM', 'IN', 'ingredient b'), conso('300', '3001', 'RXNORM', 'SBD', 'brand c 10 MG Oral Tablet')].join('\n') + '\n'); - fs.writeFileSync(path.join(rrf, 'RXNREL.RRF'), [cuiRel('200', 'RO', '100', 'has_ingredient'), cuiRel('100', 'RB', '300', 'tradename_of'), - cuiRel('300', 'RN', '100', ''), cuiRel('100', 'RO', '200', 'ingredient_of'), cuiRel('100', 'RB', '200', 'ingredient_of')].join('\n') + '\n'); - fs.writeFileSync(path.join(rrf, 'RXNSTY.RRF'), ['100|T200|||A|', '200|T121|||A|', '300|T200|||A|'].join('\n') + '\n'); - file = path.join(dir, 'rx.db'); - await importRxNormV2({ source: rrf, dest: file, version: '01012026', overwrite: true, log: () => {} }); - }); - const lookups = async (f) => { - const fac = new SqliteV2Factory(op.i18n, f); - await fac.load(); - try { - const p = await fac.build(op, []); - const out = {}; - for (const code of ['100', '200', '300']) { - for (const props of [[], ['*'], ['TTY'], ['SUPPRESS'], ['ingredient_of'], ['RB', 'tradename_of'], ['ingredient_of@RO']]) { - const params = []; - await p.extendLookup((await p.locate(code)).context, props, params); - out[code + ' ' + props.join(',')] = params.map((x) => x.part.map((y) => y.valueCode || y.valueString).join('=')); - } - } - return out; - } finally { fac.store.close(); } - }; - - test('the importer writes never on SUPPRESS and the @ codes, named on the relationships', () => { - const db = new Database(file, { readonly: true }); - try { - const r = Object.fromEntries(db.prepare('SELECT code, report FROM property').raw().all()); - expect(r.SUPPRESS).toBe('never'); - expect(r.TTY).toBeNull(); - expect(r.has_ingredient).toBe('named'); - expect(r.RO).toBe('named'); - expect(Object.entries(r).filter(([c]) => c.includes('@')).every(([, v]) => v === 'never')).toBe(true); - expect(Object.keys(r).some((c) => c.includes('@'))).toBe(true); - } finally { db.close(); } - }); - - test('$lookup answers from the catalog: TTY, STY, SAB by default; relationships by name or *; SUPPRESS and @ codes never', async () => { - const a = await lookups(file); - expect(a['100 ']).toEqual(['TTY=SCD', 'TTY=SY', 'STY=T200', 'SAB=RXNORM']); - expect(a['200 *']).toEqual(['TTY=IN', 'STY=T121', 'SAB=RXNORM', 'ingredient_of=100']); - expect(a['200 ']).toEqual(['TTY=IN', 'STY=T121', 'SAB=RXNORM']); - expect(a['100 SUPPRESS']).toEqual([]); - expect(a['200 ingredient_of@RO']).toEqual([]); - expect(a['300 RB,tradename_of']).toEqual(['tradename_of=100']); - }); -}); - -describe('behaviour.lookupDesignationCode: each designation again, coded by an item literal', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - let op; - beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); - const build = (set) => fixture((b, c) => { - const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'code', filterable: false, report: 'never' }); - b.literal(b.item(c.C, { language: 'en', use: { system: 'u', code: 'short' }, text: 'cherry' }), kind, 'short'); - b.literal(b.item(c.C, { language: 'en', use: { system: 'u', code: 'long' }, text: 'a cherry tree' }), kind, 'long'); - b.item(c.C, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'no kind' }); - if (set) b.setBehaviour('lookupDesignationCode', 'kind'); - }); - const lookup = async (file, props) => { - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { - const p = await f.build(op, []); - const params = []; - await p.extendLookup((await p.locate('C')).context, props, params); - return params.filter((x) => x.name === 'designation').map((x) => x.part.map((y) => y.valueCode || y.valueString).join('|')); - } finally { f.store.close(); } - }; - - test('set: the designations with the literal, coded by its value, by default and when designation is asked for', async () => { - const f = build(true); - expect(await lookup(f, [])).toEqual(['short|cherry|en', 'long|a cherry tree|en']); - expect(await lookup(f, ['designation'])).toEqual(['short|cherry|en', 'long|a cherry tree|en']); - expect(await lookup(f, ['parent'])).toEqual([]); - }); - - test('absent (default null): none', async () => { - expect(await lookup(build(false), [])).toEqual([]); - expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '3' }))).toThrow(/lookupDesignationCode = 3 is not a value/); - expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '"parent"' }))).toThrow(/lookupDesignationCode parent is not a literal property/); - expect(() => openStore(withMeta(build(false), { 'behaviour.lookupDesignationCode': '"nothing"' }))).toThrow(/is not a literal property/); - }); -}); - -describe('behaviour.lookupCopyright', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - test('$lookup lists the resource\'s copyright as a property; set without one, the file is refused; absent, none', async () => { - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const withCopyright = fixture((b) => { b.systems[0].resource = { resourceType: 'CodeSystem', copyright: 'A synthetic notice' }; b.setBehaviour('lookupCopyright', true); }); - const f = new SqliteV2Factory(op.i18n, withCopyright); - await f.load(); - try { - const p = await f.build(op, []); - const params = []; - await p.extendLookup((await p.locate('A')).context, [], params); - const cr = params.filter((x) => x.part[0].valueCode === 'copyright').map((x) => x.part[1].valueString); - expect(cr).toEqual(['A synthetic notice']); - } finally { f.store.close(); } - expect(() => openStore(withMeta(fixture(), { 'behaviour.lookupCopyright': 'true' }))).toThrow(/lookupCopyright without code_system.resource.copyright/); - withStore(fixture(), (S) => expect(S.copyright).toBeNull()); - }); -}); - -describe('P9a/P9b. reported names, extra asked-for names, boolean values; the status literal', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { checkContracts } = require('../../tx/importers/sqlite-v2/builder'); - let op, file, f, p; - beforeAll(async () => { - op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - file = fixture((b, c) => { - const mod = b.property({ code: 'mod', shape: 'link', alsoAskedAs: ['module'] }); - const def = b.property({ code: 'defStatus', shape: 'link', reportedAs: 'fullyDefined', trueValue: 'B', report: 'named' }); - const st = b.property({ code: 'state', shape: 'literal', fhirType: 'string', role: 'status' }); - b.link(c.A, mod, c.root); - b.link(c.A, def, c.B); - b.link(c.C, def, c.X); - b.literal(c.A, st, 'TRIAL'); - }); - f = new SqliteV2Factory(op.i18n, file); - await f.load(); - p = await f.build(op, []); - }); - afterAll(() => f.store.close()); - const lookup = async (code, props) => { - const params = []; - await p.extendLookup((await p.locate(code)).context, props, params); - return params.map((x) => x.part[0].valueCode + '=' + JSON.stringify(x.part[1].valueCode ?? x.part[1].valueString ?? x.part[1].valueBoolean)); - }; - - test('reported_as: reported and asked for under that name; true_value: a boolean; named: by name or *, not by default', async () => { - expect(await lookup('A', [])).not.toContain('fullyDefined=true'); - expect(await lookup('A', ['fullyDefined'])).toEqual(['fullyDefined=true']); - expect(await lookup('C', ['fullyDefined'])).toEqual(['fullyDefined=false']); - expect(await lookup('A', ['*'])).toContain('fullyDefined=true'); - expect(await lookup('A', ['defStatus'])).toEqual([]); - }); - - test('also_asked_as: asked for by the extra name, still reported under its own', async () => { - expect(await lookup('A', ['module'])).toEqual(['mod="root"']); - expect(await lookup('A', ['mod'])).toEqual(['mod="root"']); - expect(await lookup('A', [])).toContain('mod="root"'); - }); - - test('role status: getStatus reads the literal, $lookup lists it by default under its name', async () => { - expect(await p.getStatus((await p.locate('A')).context)).toBe('TRIAL'); - expect(await p.getStatus((await p.locate('B')).context)).toBeNull(); - expect(await lookup('A', [])).toContain('state="TRIAL"'); - expect(f.store.statusProp.code).toBe('state'); - }); - - test('at most one status property (builder contract, reader check); a malformed also_asked_as is refused', () => { - const two = path.join(dir, 'two-status.db'); - fs.copyFileSync(file, two); - const w = new Database(two); - w.exec("UPDATE property SET role = 'status' WHERE code = 'colour'"); - expect(() => checkContracts(w)).toThrow(/more than one property with role status/); - w.close(); - expect(() => openStore(two)).toThrow(/more than one property with role status/); - const bad = path.join(dir, 'bad-asked.db'); - fs.copyFileSync(file, bad); - const w2 = new Database(bad); - w2.exec("UPDATE property SET also_asked_as = '\"module\"' WHERE code = 'mod'"); - w2.close(); - expect(() => openStore(bad)).toThrow(/also_asked_as "module", not a list of names/); - const b = new TerminologyBuilder(path.join(dir, 'never4.db'), { overwrite: true, importer: 'test' }); - b.codeSystem({ uri: 'http://example.org/x', version: '1' }); - expect(() => b.property({ code: 's', shape: 'link', role: 'status' })).toThrow(/status role is for a literal/); - }); -}); - -describe('P9e. the text search and its tie order are file data', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const ti = require('../../tx/sqlite-v2/text-index'); - let i18n; - beforeAll(async () => { i18n = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())).i18n; }); - // three concepts whose displays tie for "tree": codes, displays and ids in different orders - const ties = (meta = {}) => { - const dest = path.join(dir, `t${++seq}.db`); - const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); - b.codeSystem({ uri: 'http://example.org/ties', version: '1' }); - b.setMeta('ix.ix_word.names', { display: 'en' }); - for (const [k, v] of Object.entries(meta)) b.setMeta(k, v); - b.concept('m', { display: 'tree z' }); - b.concept('a', { display: 'tree y' }); - b.concept('z', { display: 'tree x' }); - b.finish(); - return dest; - }; - - test('behaviour.textSearch names the search (registry by name); a name this server does not implement refuses the file', async () => { - expect(ti.textSearchMode(null, 'f')).toBeNull(); - expect(ti.textSearchMode('loinc', 'f')).toBe('display'); - expect(ti.textSearchMode('snomed', 'f')).toBe('designation'); - expect(ti.textSearchMode('rxnorm', 'f')).toBe('rxnorm'); - // icd11 is a search another reader implements; this one does not - await expect(new SqliteV2Factory(i18n, withMeta(fixture(), { 'behaviour.textSearch': '"icd11"' })).load()).rejects.toThrow(/its text search is icd11 .* does not implement/); - const f = withMeta(fixture(), { 'behaviour.textSearch': '"bm25"' }); - await expect(new SqliteV2Factory(i18n, f).load()).rejects.toThrow(/its text search is bm25 \(behaviour.textSearch\), which this server does not implement/); - const g = new SqliteV2Factory(i18n, withMeta(fixture(), { 'behaviour.textSearch': '"loinc"' })); - await g.load(); - try { expect(g.searchMode).toBe('display'); } finally { g.store.close(); } - }); - - test('searchTieBreak: code, display; absent: concept id', () => { - const order = (meta) => withStore(ties(meta), (S) => Array.from(ti.genericTextSearch(S, 'tree', 'en', 'en').ids).map((id) => S.conceptRows([id]).get(id).code)); - const byId = withStore(ties(), (S) => ['m', 'a', 'z'].sort((x, y) => S.idOf(x) - S.idOf(y))); - expect(order({})).toEqual(byId); - expect(order({ searchTieBreak: 'code' })).toEqual(['a', 'm', 'z']); - expect(order({ searchTieBreak: 'display' })).toEqual(['z', 'a', 'm']); - // code-length: numeric order for numeric codes (binary text would put 100 before 9) - const numeric = (meta) => { - const dest = path.join(dir, `n${++seq}.db`); - const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); - b.codeSystem({ uri: 'http://example.org/numeric', version: '1' }); - b.setMeta('ix.ix_word.names', { display: 'en' }); - for (const [k, v] of Object.entries(meta)) b.setMeta(k, v); - for (const [c, d] of [['100', 'tree x'], ['9', 'tree y'], ['20', 'tree z']]) b.concept(c, { display: d }); - b.finish(); - return withStore(dest, (S) => Array.from(ti.genericTextSearch(S, 'tree', 'en', 'en').ids).map((id) => S.conceptRows([id]).get(id).code)); - }; - expect(numeric({ searchTieBreak: 'code-length' })).toEqual(['9', '20', '100']); - expect(numeric({ searchTieBreak: 'code' })).toEqual(['100', '20', '9']); - expect(() => openStore(withMeta(ties(), { searchTieBreak: 'random' }))).toThrow(/meta searchTieBreak = random is not a value/); - }); -}); - -describe('property.named_links: links read only where the property is named', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - test('$lookup leaves the links out unless the property is asked for; its literals as usual; the old file key is unknown', async () => { - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - // (the old file key is unknown to the builder too, so it is added to the built file) - const file = withMeta(fixture((b, c) => { - const size = b.property({ code: 'size', shape: 'both', fhirType: 'string', namedLinks: true }); - b.link(c.A, size, c.B); - b.literal(c.A, size, 'large'); - }), { 'behaviour.lookupSkipsMixedLinks': 'true' }); - const db = new Database(file, { readonly: true }); - try { expect(db.prepare("SELECT named_links FROM property WHERE code = 'size'").pluck().get()).toBe(1); } finally { db.close(); } - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { - expect(f.store.behaviour.lookupSkipsMixedLinks).toBeUndefined(); - const p = await f.build(op, []); - const lookup = async (props) => { - const params = []; - await p.extendLookup((await p.locate('A')).context, props, params); - return params.map((x) => x.part[0].valueCode + '=' + (x.part[1].valueCode || x.part[1].valueString)).filter((x) => x.startsWith('size')); - }; - expect(await lookup([])).toEqual(['size=large']); - expect(f.store.linksFrom([f.store.idOf('A')]).some((l) => l.p === f.store.catalog.get('size').id)).toBe(false); - expect(f.store.linksFrom([f.store.idOf('A')], new Set([f.store.catalog.get('size').id])).length).toBe(1); - } finally { f.store.close(); } - }); -}); - -describe('a catalog without the reporting columns is refused', () => { - test('a property table lacking reported_as / also_asked_as / true_value / named_links: upgrade it', () => { - const f = withMeta(fixture(), {}); - const w = new Database(f); - w.exec('ALTER TABLE property DROP COLUMN true_value; ALTER TABLE property DROP COLUMN named_links'); - w.close(); - expect(() => openStore(f)).toThrow(/built before the catalog columns true_value, named_links existed: rebuild it with the importers, or upgrade it/); - }); -}); - -describe('behaviour.domain: the concepts answers select', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); - test('a filter, the whole system and the count select only the concepts with the property', async () => { - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const file = fixture((b, c) => { - const live = b.property({ code: 'live', shape: 'literal', fhirType: 'code', filterable: false }); - for (const k of ['root', 'A', 'X']) b.literal(c[k], live, 'Y'); - b.setBehaviour('domain', 'live'); - }); - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { - const S = f.store; - const codes = (bm) => bm.toArray().map((id) => S.conceptRows([id]).get(id).code).sort(); - expect(codes(S.domain())).toEqual(['A', 'X', 'root']); - const p = await f.build(op, []); - expect(p.totalCount()).toBe(3); - expect((await p.iteratorAll()).ids.length).toBe(3); - const c = new Compiler({ store: S, dialect: {} }); - expect(codes(f.engine.evaluate(c.domain(c.filter('concept', 'is-a', 'root'))))).toEqual(['A', 'root']); - } finally { f.store.close(); } - withStore(fixture(), (S) => expect(S.domain()).toBeNull()); - expect(() => openStore(withMeta(fixture(), { 'behaviour.domain': '"nothing"' }))).toThrow(/behaviour.domain nothing is not a property of the catalog/); - }); -}); - -describe('R3-3. item_use.reported_as: an item use reported as a property', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { Designations } = require('../../tx/library/designations'); - test('its active items are a $lookup property (by default, by name, *), not designations; at most one; the column is required', async () => { - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const file = fixture((b, c) => { - b.item(c.A, { language: 'en', use: { system: 'u', code: 'REL' }, text: 'fruit; orchard' }); - b.item(c.A, { language: 'en', use: { system: 'u', code: 'REL' }, text: 'withdrawn words', active: false }); - b.reportUseAs('REL', 'relatedNames'); - }); - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { - const p = await f.build(op, []); - const ctx = (await p.locate('A')).context; - const ds = new Designations(op.i18n.languageDefinitions); - await p.designations(ctx, ds); - expect(ds.designations.map((d) => d.value)).not.toContain('fruit; orchard'); - const lookup = async (props) => { - const params = []; - await p.extendLookup((await p.locate('A')).context, props, params); - return params.filter((x) => x.part[0].valueCode === 'relatedNames').map((x) => x.part[1].valueString); - }; - expect(await lookup([])).toEqual(['fruit; orchard']); - expect(await lookup(['relatedNames'])).toEqual(['fruit; orchard']); - expect(await lookup(['*'])).toEqual(['fruit; orchard']); - expect(await lookup(['colour'])).toEqual([]); - } finally { f.store.close(); } - const two = withMeta(file, {}); - const w = new Database(two); - w.exec("UPDATE item_use SET reported_as = 'x' WHERE reported_as IS NULL"); - w.close(); - expect(() => openStore(two)).toThrow(/more than one item use with reported_as/); - const old = withMeta(file, {}); - const w2 = new Database(old); - w2.exec('ALTER TABLE item_use DROP COLUMN reported_as'); - w2.close(); - expect(() => openStore(old)).toThrow(/built before the item_use columns reported_as existed/); - }); -}); - -describe('R3-5a. behaviour.lookupOrder', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const names = async (meta) => { - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const file = withMeta(fixture((b, c) => { - const site = b.property({ code: 'site', shape: 'link' }); - const size = b.property({ code: 'size', shape: 'literal', fhirType: 'string' }); - b.link(c.A, site, c.C); - b.link(c.A, site, c.B); - b.literal(c.A, size, 'big'); - }), meta); - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { - const p = await f.build(op, []); - const params = []; - await p.extendLookup((await p.locate('A')).context, [], params); - return params.map((x) => x.part[0].valueCode + '=' + (x.part[1].valueCode || x.part[1].valueString)); - } finally { f.store.close(); } - }; - test('ranks by name, concept-valued, other; ties as listed or byCode; absent: as listed', async () => { - const plain = await names({}); - expect(plain).toEqual(['parent=root', 'site=B', 'site=C', 'colour=red', 'size=big']); - expect(await names({ 'behaviour.lookupOrder': JSON.stringify({ ranks: { size: 0, colour: 1 }, other: 2 }) })) - .toEqual(['size=big', 'colour=red', 'parent=root', 'site=B', 'site=C']); - expect(await names({ 'behaviour.lookupOrder': JSON.stringify({ ranks: { parent: 3 }, concept: 0, other: 1 }) })) - .toEqual(['site=B', 'site=C', 'colour=red', 'size=big', 'parent=root']); - expect(await names({ 'behaviour.lookupOrder': JSON.stringify({ ranks: {}, other: 0, byCode: true }) })) - .toEqual(['colour=red', 'parent=root', 'site=B', 'site=C', 'size=big']); - expect(() => openStore(withMeta(fixture(), { 'behaviour.lookupOrder': '{"ranks": {}}' }))).toThrow(/lookupOrder = .* is not a value/); - }); -}); - -describe('R3-5b. behaviour.implicitMaps', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - test('maps {base}{key} over the mapping rows: found, offered for a code that has a row, listed by $lookup under the key; used refused', async () => { - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const file = fixture((b, c) => { - b.mapping(c.A, { system: 'http://example.org/other', code: 'O-1', display: 'other one', relationship: 'equivalent' }); - b.setBehaviour('implicitMaps', { base: 'http://example.org/cm/', maps: [['http://example.org/other', 'other']] }); - }); - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { - const cm = await f.findImplicitConceptMap('http://example.org/cm/other'); - expect(cm.jsonObj.url).toBe('http://example.org/cm/other'); - expect(await f.findImplicitConceptMap('http://example.org/cm/none')).toBeNull(); - const found = []; - await f.findImplicitConceptMaps(found, 'http://example.org/cs', '1', 'http://example.org/other', 'A'); - expect(found.map((m) => m.jsonObj.url)).toEqual(['http://example.org/cm/other']); - const none = []; - await f.findImplicitConceptMaps(none, 'http://example.org/cs', '1', 'http://example.org/other', 'B'); - expect(none).toEqual([]); - const p = await f.build(op, []); - const params = []; - await p.extendLookup((await p.locate('A')).context, [], params); - expect(params.filter((x) => x.part[0].valueCode === 'other').map((x) => x.part[1].valueCoding.code)).toEqual(['O-1']); - } finally { f.store.close(); } - expect(() => openStore(withMeta(fixture(), { 'behaviour.implicitMaps': '{"base": "u/", "maps": [], "used": "to-"}' }))).toThrow(/implicitMaps.used is set/); - }); -}); - -describe('R3-5c. partial versions by versionAlgorithm', () => { - test('url: the edition URI before /version/; any other algorithm: none', async () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const partial = async (version, algorithm) => { - const dest = path.join(dir, `pv${++seq}.db`); - const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); - b.codeSystem({ uri: 'http://example.org/pv', version }); - b.concept('a'); - if (algorithm) b.setBehaviour('versionAlgorithm', algorithm); - b.finish(); - const f = new SqliteV2Factory(op.i18n, dest); - await f.load(); - try { return f.getPartialVersion(); } finally { f.store.close(); } - }; - expect(await partial('http://example.org/pv/1/version/20260101', 'url')).toBe('http://example.org/pv/1'); - expect(await partial('http://example.org/pv/1', 'url')).toBeNull(); - expect(await partial('http://example.org/pv/1/version/20260101', null)).toBeNull(); - expect(await partial('1.2.3', 'semver')).toBeNull(); - }); -}); - -describe('catalog id and name from code_system.resource', () => { - test('the stored id as it is is the CodeSystem id (x-...); its name the catalog name; none without an id', async () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const load = async (file) => { const f = new SqliteV2Factory(op.i18n, file); await f.load(); return f; }; - const a = await load(fixture((b) => { b.systems[0].resource = { resourceType: 'CodeSystem', id: 'x-example-1', name: 'EX 1' }; })); - const n = await load(fixture()); - try { - expect('x-' + a.id()).toBe('x-example-1'); - expect(a.name()).toBe('EX 1'); - expect(n.id()).toBeNull(); - expect(n.name()).toBe('Example'); - } finally { a.store.close(); n.store.close(); } - }); -}); - -describe('R3-10. item_use.role', () => { - test('a use with role name is a display use; an unknown role or a file without the column is refused', async () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - const file = fixture((b) => b.setUseRole('syn', 'name')); - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { - const p = await f.build(op, []); - expect(p.isDisplay({ use: { system: 'http://example.org/use', code: 'syn' } })).toBe(true); - expect(p.isDisplay({ use: { system: 'http://example.org/use', code: 'other' } })).toBe(false); - expect(p.isDisplay({})).toBe(false); - } finally { f.store.close(); } - const bad = withMeta(file, {}); - const w = new Database(bad); - w.exec("UPDATE item_use SET role = 'preferred'"); - w.close(); - expect(() => openStore(bad)).toThrow(/has role preferred/); - const old = withMeta(file, {}); - const w2 = new Database(old); - w2.exec('ALTER TABLE item_use DROP COLUMN role'); - w2.close(); - expect(() => openStore(old)).toThrow(/built before the item_use columns role existed/); - }); -}); - -describe('R3-8. answer facts as behaviour keys', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { Designations } = require('../../tx/library/designations'); - const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); - let op; - beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); - const base = (extra) => fixture((b, c) => { - b.item(c.A, { language: 'en', text: 'display A' }); // no use, equal to the display - b.item(c.A, { kind: 1, text: 'a text definition', preferred: true }); - b.setUseRole('syn', 'synonym'); - if (extra) extra(b, c); - }); - const withF = async (file, fn) => { - const f = new SqliteV2Factory(op.i18n, file); - await f.load(); - try { return await fn(f, await f.build(op, [])); } finally { f.store.close(); } - }; - const desigs = async (p, code) => { - const ds = new Designations(op.i18n.languageDefinitions); - await p.designations((await p.locate(code)).context, ds); - return ds.designations.map((d) => d.value); - }; - const codes = (f, node) => f.engine.evaluate(node).toArray().map((id) => f.store.conceptRows([id]).get(id).code).sort(); - - test('defaults: the display first (an item equal to it not repeated), inactive items left out, generalizes keeps the concept, definitions reported, whole system listed', async () => { - const file = base((b, c) => b.item(c.B, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'old banana', active: false })); - await withF(file, async (f, p) => { - expect(await desigs(p, 'A')).toEqual(['display A', 'apple tree', 'Apfelbaum']); - expect(await desigs(p, 'B')).not.toContain('old banana'); - expect(await p.definition((await p.locate('A')).context)).toBe('a text definition'); - const c = new Compiler({ store: f.store, dialect: {} }); - expect(codes(f, c.filter('concept', 'generalizes', 'A'))).toEqual(['A', 'root']); - expect(codes(f, c.include({ system: f.store.system }).parts[0].node)).toEqual(['A', 'B', 'C', 'X', 'root']); - expect(codes(f, c.filter('display', 'regex', 'display .*'))).toEqual(['A', 'B', 'C', 'X', 'root']); - }); - }); - - test('displayDesignation, inactiveDesignations, plainDesignationIsDisplay', async () => { - const extra = (b, c) => b.item(c.B, { language: 'en', use: { system: 'u', code: 'syn' }, text: 'old banana', active: false }); - await withF(withMeta(base(extra), { 'behaviour.displayDesignation': '"distinct"', 'behaviour.inactiveDesignations': '"status"' }), async (f, p) => { - expect(await desigs(p, 'A')).toEqual(['display A', 'apple tree', 'Apfelbaum', 'display A']); - expect(await desigs(p, 'B')).toContain('old banana'); - }); - await withF(withMeta(base(extra), { 'behaviour.displayDesignation': '"first"', 'behaviour.inactiveDesignations': '"plain"' }), async (f, p) => { - expect(await desigs(p, 'A')).toEqual(['display A', 'apple tree', 'Apfelbaum']); - }); - await withF(withMeta(base(), { 'behaviour.plainDesignationIsDisplay': 'true', 'behaviour.displayDesignation': '"none"' }), async (f, p) => { - expect(await desigs(p, 'A')).toEqual(['apple tree', 'Apfelbaum']); - }); - await withF(withMeta(base(), { 'behaviour.displayDesignation': '"none"' }), async (f, p) => { - expect(await desigs(p, 'A')).toEqual(['apple tree', 'Apfelbaum', 'display A']); - }); - }); - - test('generalizesExcludesSelf, wholeActiveOnly, wholeSystem, lookupDefinition, displayRegex', async () => { - await withF(withMeta(base(), { 'behaviour.generalizesExcludesSelf': 'true', 'behaviour.wholeActiveOnly': 'true', 'behaviour.lookupDefinition': 'false', - 'behaviour.displayRegex': '"designations"' }), async (f, p) => { - const c = new Compiler({ store: f.store, dialect: {}, lang: 'en' }); - expect(codes(f, c.filter('concept', 'generalizes', 'A'))).toEqual(['root']); - expect(codes(f, c.include({ system: f.store.system }).parts[0].node)).toEqual(['A', 'B', 'C', 'root']); - expect(await p.definition((await p.locate('A')).context)).toBeNull(); - // display regex over the designations of synonym / fsn uses, not the display - expect(codes(f, c.filter('display', 'regex', 'apple.*'))).toEqual(['A']); - expect(codes(f, c.filter('display', 'regex', 'display A'))).toEqual([]); - }); - await withF(withMeta(base(), { 'behaviour.wholeSystem': '"empty"' }), async (f) => { - expect(codes(f, new Compiler({ store: f.store, dialect: {} }).include({ system: f.store.system }).parts[0].node)).toEqual([]); - }); - await withF(withMeta(base(), { 'behaviour.wholeSystem': '"refuse"' }), async (f) => { - expect(() => new Compiler({ store: f.store, dialect: {} }).include({ system: f.store.system })).toThrow(/cannot be expanded as a whole/); - }); - }); - - test('locateMessage, versionFormat; keepDuplicateDesignations refused; malformed values refused', async () => { - await withF(withMeta(base(), { 'behaviour.locateMessage': '"No code {code}"', 'behaviour.filterLocateMessage': '"No code {code} here"', - 'behaviour.filterCheckMessage': '"{code} is not selected"', 'behaviour.versionFormat': '"MMDDYYYY"' }), async (f, p) => { - expect((await p.locate('ZZ')).message).toBe('No code ZZ'); - expect(await p._filterLocate(null, null, 'ZZ')).toBe('No code ZZ here'); - expect(await p._filterLocate(null, { ids: [] }, 'A')).toBe('A is not selected'); - expect(f.describeVersion('03022026')).toBe(require('../../library/utils/utilities').formatDateMMDDYYYY('03022026')); - }); - expect(() => openStore(withMeta(base(), { 'behaviour.keepDuplicateDesignations': 'true' }))).toThrow(/keepDuplicateDesignations is set/); - for (const [k, v] of [['locateMessage', '"no placeholder"'], ['versionFormat', '"YYYY"'], ['wholeSystem', '"some"'], ['displayDesignation', '"all"']]) { - expect(() => openStore(withMeta(base(), { ['behaviour.' + k]: v }))).toThrow(/is not a value/); - } - }); -}); - -describe('R3-9. deprecatedStatus, declaresProperties, implicitValueSets; the system order written by the importer', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - let op; - beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); - const load = async (file) => { const f = new SqliteV2Factory(op.i18n, file); await f.load(); return f; }; - test('deprecated: a status listed in deprecatedStatus; declaresProperties false: no property definitions', async () => { - const file = fixture((b, c) => { - const st = b.property({ code: 'status', shape: 'literal', fhirType: 'code', role: 'status', report: 'never', filterable: false }); - b.literal(c.X, st, 'retired'); - b.literal(c.A, st, 'trial'); - b.setBehaviour('deprecatedStatus', ['retired']); - b.setBehaviour('declaresProperties', false); - }); - const f = await load(file); - try { - const p = await f.build(op, []); - expect(await p.isDeprecated((await p.locate('X')).context)).toBe(true); - expect(await p.isDeprecated((await p.locate('A')).context)).toBe(false); - expect(p.propertyDefinitions()).toBeNull(); - } finally { f.store.close(); } - const g = await load(fixture()); - try { expect((await g.build(op, [])).propertyDefinitions().length).toBeGreaterThan(0); } finally { g.store.close(); } - }); - test('implicitValueSets: a URL grammar this reader does not implement refuses the file', async () => { - await expect(load(withMeta(fixture(), { 'behaviour.implicitValueSets': '"omop"' }))).rejects.toThrow(/implicit value sets are omop .* does not implement/); - await expect(load(withMeta(fixture(), { 'behaviour.implicitValueSets': '"snomed"' }))).rejects.toThrow(/implicit value sets are snomed/); - const f = await load(withMeta(fixture(), { 'behaviour.implicitValueSets': '"loinc"' })); - f.store.close(); - }); - test('the index builder computes no order: a file stating a stored expansion order without one breaks a contract', () => { - const b = new TerminologyBuilder(path.join(dir, 'noorder.db'), { overwrite: true, importer: 'test' }); - b.codeSystem({ uri: 'http://www.nlm.nih.gov/research/umls/rxnorm', version: '1' }); - b.concept('1'); - b.setBehaviour('expansionOrder', 'stored'); - expect(() => b.finish()).toThrow(/contract: behaviour.expansionOrder "stored" without ix_order rank and ids/); - }); -}); - -describe('R3-10. property filter and presentation facts', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); - let op; - beforeAll(async () => { op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); }); - const file = () => fixture((b, c) => { - const tty = b.property({ code: 'TTY', shape: 'literal', fhirType: 'code', nameAnyCase: true }); - const st = b.property({ code: 'state', shape: 'literal', fhirType: 'string', defaultValue: 'none' }); - const site = b.property({ code: 'site', shape: 'link', matchDisplay: true, alsoAskedAs: ['place'], presentation: { value: 'display', parts: ['partCode'] } }); - const kind = b.property({ code: 'kind', shape: 'literal', fhirType: 'string', presentation: { value: 'string', parts: ['code-display'] }, display: 'Kind' }); - b.literal(c.A, tty, 'SCD'); - b.literal(c.B, st, 'done'); - b.link(c.A, site, c.C); - b.literal(c.A, kind, 'k1'); - }); - test('name_any_case and also_asked_as name a property; default_value; match_display', async () => { - const f = new SqliteV2Factory(op.i18n, file()); - await f.load(); - try { - const c = new Compiler({ store: f.store, dialect: {} }); - const codes = (n) => f.engine.evaluate(n).toArray().map((id) => f.store.conceptRows([id]).get(id).code).sort(); - expect(codes(c.filter('tty', '=', 'SCD'))).toEqual(['A']); - expect(codes(c.filter('place', '=', 'C'))).toEqual(['A']); - expect(codes(c.filter('site', '=', 'display C'))).toEqual(['A']); - expect(codes(c.filter('state', '=', 'none'))).toEqual(['A', 'C', 'X', 'root']); - expect(codes(c.filter('state', '=', 'done'))).toEqual(['B']); - const p = await f.build(op, []); - const params = []; - await p.extendLookup((await p.locate('A')).context, ['site', 'kind'], params); - expect(params.map((x) => x.part)).toEqual([ - [{ name: 'code', valueCode: 'site' }, { name: 'value', valueString: 'display C' }, { name: 'partCode', valueCode: 'C' }], - [{ name: 'code', valueCode: 'kind' }, { name: 'value', valueString: 'k1' }, { name: 'code-display', valueString: 'Kind' }]]); - } finally { f.store.close(); } - }); - test('a malformed presentation, or a catalog without the columns, is refused', () => { - const f = file(); - const bad = withMeta(f, {}); - const w = new Database(bad); - w.exec(`UPDATE property SET presentation = '{"value": "upper"}' WHERE code = 'kind'`); - w.close(); - expect(() => openStore(bad)).toThrow(/property kind has presentation/); - const old = withMeta(f, {}); - const w2 = new Database(old); - w2.exec('ALTER TABLE property DROP COLUMN presentation'); - w2.close(); - expect(() => openStore(old)).toThrow(/built before the catalog columns presentation existed/); - }); -}); - -describe('R3-11. listed filters over a stored property; concept in a relation; no hierarchy', () => { - const { OperationContext } = require('../../tx/operation-context'); - const { TestUtilities } = require('../test-utilities'); - const { SqliteV2Factory } = require('../../tx/sqlite-v2/provider'); - const { Compiler } = require('../../tx/sqlite-v2/engine/compile'); - test('behaviour.filters property and where; concept in X: the members of the relation X defines', () => { - const file = fixture((b, c) => { - const std = b.property({ code: 'standard', shape: 'literal', fhirType: 'code' }); - b.literal(c.A, std, 'S'); - b.literal(c.B, std, 'S'); - const set = b.property({ code: 'C', shape: 'record', concept: c.C, fields: [] }); - b.record(set, c.A, { fields: [] }); - b.record(set, c.X, { fields: [] }); - b.setBehaviour('filters', [{ code: 'tint', operator: ['=', 'in'], property: 'colour', where: { standard: 'S' } }, { code: 'concept', operator: ['in'] }]); - }); - withStore(file, (S) => { - const c = new Compiler({ store: S, dialect: {} }); - const { Engine } = require('../../tx/sqlite-v2/engine/engine'); - const codes = (n) => new Engine(S).evaluate(n).toArray().map((id) => S.conceptRows([id]).get(id).code).sort(); - expect(codes(c.filter('tint', '=', 'red'))).toEqual(['A']); - expect(codes(c.filter('tint', 'in', 'red,blue'))).toEqual(['A', 'B']); - expect(codes(c.filter('concept', 'in', 'C,B'))).toEqual(['A', 'B', 'X']); - }); - }); - test('a file with no hierarchy property: not-subsumed, even for the same code; no ancestors', async () => { - const op = new OperationContext('en', await TestUtilities.loadTranslations(await TestUtilities.loadLanguageDefinitions())); - 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 f = new SqliteV2Factory(op.i18n, dest); - await f.load(); - try { - const p = await f.build(op, []); - expect(await p.subsumesTest('a', 'a')).toBe('not-subsumed'); - expect(await p.subsumesTest('a', 'b')).toBe('not-subsumed'); - expect([...(await p.ancestorsOf('a'))]).toEqual([]); - } finally { f.store.close(); } - }); -}); diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js new file mode 100644 index 000000000..8b1cbf810 --- /dev/null +++ b/tests/tx/sqlite-v2-format.test.js @@ -0,0 +1,811 @@ +'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('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/); + }); + + test('an unknown compatibility member is refused; one this reader does not implement too', () => { + expect(() => openStore(withMeta(base, { compatibility: '{"keepEverything": true}' }))).toThrow(/meta compatibility = .* is not a value/); + expect(() => openStore(withMeta(base, { compatibility: '{"expansionKeepsRepeatedDesignations": true}' }))).toThrow(/expansionKeepsRepeatedDesignations is set .* which this server does not implement/); + expect(() => openStore(withMeta(base, { implicitMaps: '{"base": "http://x/", "maps": [], "used": "to-"}' }))).toThrow(/implicitMaps.used is set, which this server does not implement/); + expect(() => openStore(withSql(base, "UPDATE property SET alias_literals = '{}' WHERE code = 'colour'"))).toThrow(/property colour has alias_literals .* which this server does not implement/); + }); + + 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 and snomed 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(); + for (const g of ['icd11', 'cpt', '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').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('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('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('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 }); + }, { 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, 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); + expect(await fac.buildKnownValueSet('http://example.org/vs')).toMatchObject({ name: 'All', compose: { include: [{ system: 'http://example.org/cs', version: '1' }] } }); + expect((await fac.buildKnownValueSet('http://example.org/vs/root')).compose.include[0].concept).toEqual([{ code: 'B' }, { code: 'A' }]); + expect(await fac.buildKnownValueSet('http://example.org/vs/A')).toMatchObject({ description: 'below display A', + compose: { include: [{ filter: [{ property: 'concept', op: 'is-a', value: 'A' }] }] } }); + expect(await fac.buildKnownValueSet('http://example.org/vs/nope')).toBeNull(); + }); + + 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(); + }); + + test('expansionLimits: maxCodes is the expandLimitation (the usual path counts it); wholeSystem refuse: 500 with the compatibility text', 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' }); + 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/); + expect(broken('ANALYZE')).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'); + 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-mixed-providers.test.js b/tests/tx/sqlite-v2-mixed-providers.test.js index ae75dc84e..c13e076bb 100644 --- a/tests/tx/sqlite-v2-mixed-providers.test.js +++ b/tests/tx/sqlite-v2-mixed-providers.test.js @@ -33,8 +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) - b.reading({ filters: [{ code: 'concept', operators: ['is-a', 'descendent-of', '='], reads: 'concept' }] }); + // 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']) { diff --git a/tests/tx/sqlite-v2-regex.test.js b/tests/tx/sqlite-v2-regex.test.js index 4988c7ffd..5508fd8a8 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-sct-default-language.test.js b/tests/tx/sqlite-v2-sct-default-language.test.js index 347c27384..45b0320c1 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-version-check.test.js b/tests/tx/sqlite-v2-version-check.test.js index e05c31b7d..20189272f 100644 --- a/tests/tx/sqlite-v2-version-check.test.js +++ b/tests/tx/sqlite-v2-version-check.test.js @@ -1,8 +1,8 @@ 'use strict'; -// behaviour.versionAlgorithm through a real request (check-system-version on $expand): the file's -// algorithm, else what its stored CodeSystem resource declares, else an exact match (no guess from -// the version string). +// 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 by the versionAlgorithm its +// stored CodeSystem resource declares, else exactly (no guess from the version string). const fs = require('fs'); const os = require('os'); @@ -16,7 +16,7 @@ let app, tx, dir; const factories = []; const FILES = { 'http://example.org/v-none': {}, - 'http://example.org/v-semver': { algorithm: 'semver' }, + 'http://example.org/v-prefix': { version: { match: 'prefix' } }, 'http://example.org/v-resource': { resource: { resourceType: 'CodeSystem', versionAlgorithmString: 'semver' } }, }; @@ -30,7 +30,7 @@ beforeAll(async () => { 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.algorithm) b.setBehaviour('versionAlgorithm', o.algorithm); + if (o.version) b.reading({ meta: { version: o.version } }); b.finish(); const f = await loadSqliteV2Factory(tx.i18n, file); factories.push(f); @@ -61,10 +61,20 @@ test('no versionAlgorithm in the file or its resource: only the exact version ma expect(await status(u, '1.2.x')).toBe(400); }); -test('versionAlgorithm semver from the file, or from the stored resource: wildcards match', async () => { - for (const u of ['http://example.org/v-semver', 'http://example.org/v-resource']) { - expect(await status(u, '1.2.3')).toBe(200); - expect(await status(u, '1.2.x')).toBe(200); - expect(await status(u, '1.3.x')).toBe(400); - } +test('versionAlgorithm semver from the stored resource: wildcards match', 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(200); + 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 that states semver itself (the earlier behaviour.versionAlgorithm): meta version has no such +// value yet (waits on the spec, section 4.5) +test.todo('a file that states semver version matching in meta version'); diff --git a/tx/importers/sqlite-v2/indexes.js b/tx/importers/sqlite-v2/indexes.js index ae7d7be7e..d3bbeaa72 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -149,6 +149,14 @@ function setPropertyIds(db) { 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) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 3a48b8bd7..f4c69ceff 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -117,7 +117,7 @@ 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, 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, and the properties `conceptStatus` names. A closure source (LOINC `ancestor`) has none: its pairs are the kind 4 sets | +| `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) | @@ -195,7 +195,7 @@ The three shapes without rows of their own: 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 without the `value_prefix`, is not understood. +outside `allowed_values`, or (operators other than `exists`) without the `value_prefix`, is not understood. 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"): @@ -369,8 +369,7 @@ A row is reported under its `fhir_code` (else `code`); a property lists one targ **`$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) before literals before the rest (identifiers, mappings, item-use - values, readings); +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. @@ -608,6 +607,22 @@ generic provider serves any plain-code file (UNII). It refuses, naming the key: | NDC | `alias_literals` on `code11` (11-digit codes as codes in their own right) | | OMOP | `implicitMaps.used` | +## Where the JS reader keeps the previous answers (open points of the revision) + +Until the revision settles these, the JS reader answers as before at these places (each marked in the +code with the section it waits on): + +| point | this reader | +|---|---| +| the display designation's language ("Designations and display") | `code_system.default_language` (else `en`), not the language of an item with the display's text (which gives a LOINC part the language of a translation that happens to equal its display) | +| status text ("Concept status") | the status literal unless its value is `active` as written (LOINC `ACTIVE` is reported, RxNorm `active` is not) | +| `then_link` order | a row that reads only `concept` (LOINC `LIST`) lists in the stored order, as upstream does; other rows (and `enumerate`) in the list's order | +| `code-display` of an inverse row (SNOMED CT `child`) | not reported, as upstream does | +| version matching of a file without meta `version` | by the `versionAlgorithm` its stored CodeSystem resource declares (semver), else exactly | +| implicit value set names | as the templates state (the LOINC templates state none) | +| RxNorm `AUI:` filter values | no filter rows exist for them: not understood | +| `ix_set` kind 5 sets | also for the hierarchy property and for `search.candidates.hasLiteral` (child-of, the hierarchy walk and the search candidates read them) | + ## Contracts What every file keeps, and every reader may rely on. The builder checks those marked before it @@ -697,4 +712,3 @@ the fhir-reading revision, is refused at start-up with a message to re-import it | 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 | -| LOINC `LIST = LL...` in `$expand` | answers in the order they first appear in the release's answer-list file | the list's sequence (`then_link` order) | diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 245811783..dfdd10112 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -51,6 +51,8 @@ class Compiler { this.store = term.store; 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) } @@ -188,7 +190,8 @@ class Compiler { if (!hit) { const n = this.term.layers ? this.term.layers.filterNode(this, prop, op, value) : null; if (n) return n; - throw notUnderstood(prop, op, value); + // (a grammar may name the filter otherwise in the message: SNOMED CT reports code as concept) + throw notUnderstood(this.grammar.filterName ? this.grammar.filterName(this, prop) : prop, op, value); } return this.rowFilter(hit.row, hit.capture, prop, op, value); } @@ -196,7 +199,7 @@ class Compiler { /** 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(prop, op, value); + 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') { @@ -212,7 +215,8 @@ class Compiler { const m = this.ids(vals); if (!vals.every((v) => m.get(v.trim()) != null)) throw nu(); } - if (row.prefix != null) { + // (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)); } @@ -241,7 +245,12 @@ class Compiler { // list, in the order of the lists, each in its link.seq order) if (row.then) { const of = node; - node = { t: 'propOf', pids: pidsOf(row.then), sources: of, ...(row.then.ordered ? { order: 'lists', of } : {}) }; + // (Waits on spec 5.5.3 / 7.2: a row that reads only `concept` (LOINC LIST = LL...) is listed + // in the stored order, as the previous answers and cs-loinc.js (ORDER BY TargetKey: the stored + // rank) list it; the list order applies to the other then_link rows (answers-for)) + // (an implicit value set's `enumerate` lists the filter's own order: this.listOrder) + const listOrder = row.then.ordered && (this.listOrder || !(row.reads.length === 1 && row.reads[0] === 'concept')); + node = { t: 'propOf', pids: pidsOf(row.then), sources: of, ...(listOrder ? { order: 'lists', of } : {}) }; } return node; } diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 4f4c678b4..b5800bc7c 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -120,7 +120,11 @@ class SqliteV2Provider extends BaseCSServices { */ versionMatches(criteria, version = this.version()) { if (criteria === version) return true; - return this.store.versionRule.match === 'prefix' && !!criteria && String(version).startsWith(criteria); + if (this.store.versionRule.match === 'prefix') return !!criteria && String(version).startsWith(criteria); + // (Waits on spec 4.5: a file without meta version whose stored CodeSystem resource declares a + // versionAlgorithm (semver) matches by it, as the previous answers did; the spec's default is exact) + const algorithm = this.versionAlgorithm(); + return !this.store.meta.has('version') && algorithm != null ? VersionUtilities.versionMatchesByAlgorithm(criteria, version, algorithm) : false; } /** * A requested version is less detailed than the file's only where meta version.partial says so: @@ -181,7 +185,9 @@ class SqliteV2Provider extends BaseCSServices { 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) }); + // (Waits on spec 7.1: SNOMED CT's `child` row has code-display in its presentation, which + // neither the previous answers nor cs-snomed.js give; an inverse row reports no code-display) + else if (p === 'code-display' && !d.reverses) 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 }); @@ -309,14 +315,6 @@ class SqliteV2Provider extends BaseCSServices { for (const c of concepts) if (c.status === undefined && c.row) c.status = vals.has(c.id) ? vals.get(c.id) : null; } } - if (!withDesignations) { - // the language of each display (the display designation's), for a page read without its designations - const nl = concepts.filter((c) => c.displayLang === undefined && c.row && !c.desigs).map((c) => c.id); - if (nl.length) { - const langs = this.store.displayItemLanguages(nl, st); - for (const c of concepts) if (c.displayLang === undefined && c.row && !c.desigs) c.displayLang = langs.get(c.id) ?? null; - } - } if (withDesignations) { const nd = concepts.filter((c) => !c.desigs).map((c) => c.id); if (nd.length) { @@ -524,8 +522,14 @@ class SqliteV2Provider extends BaseCSServices { 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 && l.matches(d.language, exact)) return d.term; + 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 d.term; + } + } } } } @@ -575,7 +579,10 @@ class SqliteV2Provider extends BaseCSServices { c.status = v === undefined ? null : v; v = c.status; } - if (v != null && String(v).toLowerCase() !== 'active') return String(v); + // (Waits on spec 5.1, status text: it drops a status value `active` in any case, which would + // drop LOINC's ACTIVE; only the value `active` as written is no status text, which keeps the + // previous answers: LOINC ACTIVE reported, RxNorm active not) + if (v != null && String(v) !== 'active') return String(v); } return c.row.active ? null : 'inactive'; } @@ -643,19 +650,14 @@ class SqliteV2Provider extends BaseCSServices { } /** - * The language of the display designation (README.md "The display designation"): the language of - * the first item (designation order) whose text is the display and that has a language, else - * code_system.default_language, else en + * The language of the display designation: code_system.default_language, else en. + * (Waits on spec 5.2.2: its rule, the language of the first item whose text is the display, gives + * LOINC parts the language of a translation that happens to equal the display, e.g. el-GR for + * LP7786-9 "CHEM"; the default language keeps the previous answers: en-US for LOINC and RxNorm, + * en for UNII as spec 11 rows 2 and 22 say.) */ _displayLanguageOf(c) { - const display = c.row ? c.row.display : null; - if (c.desigs && display != null) { - for (const d of this._ordered(c.desigs)) if (d.language && d.term === display) return d.language; - } else if (display != null) { - // a page read for its displays only: the item that gives the display's language (read with the page's rows) - if (c.displayLang === undefined) c.displayLang = this.store.displayItemLanguages([c.id], this._stats()).get(c.id) ?? null; - if (c.displayLang) return c.displayLang; - } + void c; return this.store.defaultLanguage || this.defLang(); } @@ -822,9 +824,11 @@ class SqliteV2Provider extends BaseCSServices { /** * 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 before literals before the rest, 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. + * 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) { @@ -885,7 +889,7 @@ class SqliteV2Provider extends BaseCSServices { if (m.version) coding.version = m.version; coding.code = m.code; if (m.display) coding.display = m.display; - add(d, 2, [m.system, m.code], m.code, (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueCoding: coding }, + add(d, 3, [m.system, m.code], m.code, (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueCoding: coding }, { name: 'subproperty', part: [{ name: 'code', valueCode: 'equivalence' }, { name: 'value', valueCode: m.equivalence }] }] })); } } @@ -894,13 +898,13 @@ class SqliteV2Provider extends BaseCSServices { 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, 2, [it.rank ?? Infinity, it.id], it.term, (params) => this._addStringProperty(params, 'property', d.name, it.term, it.language)); + add(d, 4, [it.rank ?? Infinity, it.id], it.term, (params) => this._addStringProperty(params, 'property', d.name, it.term, it.language)); } } // 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, 2, [], 'true', (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueBoolean: true }] })); + if (has) add(d, 5, [], 'true', (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueBoolean: true }] })); } const cmpKey = (a, b) => { for (let i = 0; i < Math.max(a.length, b.length); i++) { @@ -1731,7 +1735,7 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { 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 }); + 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); diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index a097f04d1..ce1bc6e44 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -564,6 +564,14 @@ function sctId(v) { * 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'); diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index bd471ca0d..cd8aee4c0 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -690,21 +690,6 @@ class Store { return this._listed; } - /** - * concept id -> the language of its first item (designation order: rank, then id) whose text is the - * concept's display and that has a language (README.md "The display designation") - */ - displayItemLanguages(ids, stats) { - const out = new Map(); - if (!ids.length) return out; - const q = this.stmt(`SELECT c.id, (SELECT i.language FROM main.item i WHERE i.concept_id = c.id AND i.cs_id = ${this.csId} AND i.text = c.display - AND i.language IS NOT NULL AND (i.kind = 0 OR i.use_id IS NOT NULL)${this.propertyUseIds.length ? ` AND (i.use_id IS NULL OR i.use_id NOT IN (${this.propertyUseIds.join(',')}))` : ''} ORDER BY i.rank IS NULL, i.rank, i.id LIMIT 1) FROM main.concept c WHERE c.id IN (SELECT value FROM json_each(?))`).raw(); - const rows = q.all(json(ids)); - for (const [id, l] of rows) if (l != null) out.set(id, l); - if (stats) count(stats, this, q, rows.length); - return out; - } - /** 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; From 0553330182ca725bc3af1ee4b72148cdb32f7b1d Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 16:30:31 -0600 Subject: [PATCH 51/90] sqlite-v2 reader: follow the settled revision at its former open points The revision now settles the places where the reader kept its earlier answers: - status text: the status literal as stored (RxNorm `active` and LOINC `ACTIVE` included); where an operation reports it is the operation's rule (an expansion row leaves out `active` in any case; $validate-code reports it for an inactive concept unless it is `inactive`), so an active RxNorm concept's `active` is not reported (validate.js reads the status of an active concept only to compare it with `deprecated`; LOINC `ACTIVE` took these paths already); - versions: a file without meta version matches exactly, whatever versionAlgorithm its stored CodeSystem resource declares (no edition file lacks meta version); - code-display: no exception for an inverse row; the files state the parts (SNOMED CT `child` and `moduleId` have `description` only); - the display designation's language (the default language) and the then_link order (LIST in the order of any selection, answers-for and enumerate by the lists) were already the revision's rule: comments only. Co-Authored-By: Claude --- tests/tx/sqlite-v2-rxnorm-status.test.js | 6 +++-- tests/tx/sqlite-v2-version-check.test.js | 12 ++++------ tx/sqlite-v2/engine/compile.js | 8 +++---- tx/sqlite-v2/provider.js | 29 ++++++++---------------- 4 files changed, 23 insertions(+), 32 deletions(-) diff --git a/tests/tx/sqlite-v2-rxnorm-status.test.js b/tests/tx/sqlite-v2-rxnorm-status.test.js index 6adce9318..ad1cff068 100644 --- a/tests/tx/sqlite-v2-rxnorm-status.test.js +++ b/tests/tx/sqlite-v2-rxnorm-status.test.js @@ -93,9 +93,11 @@ 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('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]); diff --git a/tests/tx/sqlite-v2-version-check.test.js b/tests/tx/sqlite-v2-version-check.test.js index 20189272f..27ecf4c72 100644 --- a/tests/tx/sqlite-v2-version-check.test.js +++ b/tests/tx/sqlite-v2-version-check.test.js @@ -1,8 +1,8 @@ '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 by the versionAlgorithm its -// stored CodeSystem resource declares, else exactly (no guess from the version string). +// (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'); @@ -61,10 +61,10 @@ test('no versionAlgorithm in the file or its resource: only the exact version ma expect(await status(u, '1.2.x')).toBe(400); }); -test('versionAlgorithm semver from the stored resource: wildcards match', async () => { +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(200); + expect(await status(u, '1.2.x')).toBe(400); expect(await status(u, '1.3.x')).toBe(400); }); @@ -75,6 +75,4 @@ test('meta version.match prefix: a start of the version matches', async () => { expect(await status(u, '1.3')).toBe(400); }); -// a file that states semver itself (the earlier behaviour.versionAlgorithm): meta version has no such -// value yet (waits on the spec, section 4.5) -test.todo('a file that states semver version matching in meta version'); +// (a file cannot state semver matching: meta version.match is exact or prefix, README.md "Versions") diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index dfdd10112..0a7f0bdfe 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -245,10 +245,10 @@ class Compiler { // list, in the order of the lists, each in its link.seq order) if (row.then) { const of = node; - // (Waits on spec 5.5.3 / 7.2: a row that reads only `concept` (LOINC LIST = LL...) is listed - // in the stored order, as the previous answers and cs-loinc.js (ORDER BY TargetKey: the stored - // rank) list it; the list order applies to the other then_link rows (answers-for)) - // (an implicit value set's `enumerate` lists the filter's own order: this.listOrder) + // (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 || !(row.reads.length === 1 && row.reads[0] === 'concept')); node = { t: 'propOf', pids: pidsOf(row.then), sources: of, ...(listOrder ? { order: 'lists', of } : {}) }; } diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index b5800bc7c..76aee866e 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -120,11 +120,7 @@ class SqliteV2Provider extends BaseCSServices { */ versionMatches(criteria, version = this.version()) { if (criteria === version) return true; - if (this.store.versionRule.match === 'prefix') return !!criteria && String(version).startsWith(criteria); - // (Waits on spec 4.5: a file without meta version whose stored CodeSystem resource declares a - // versionAlgorithm (semver) matches by it, as the previous answers did; the spec's default is exact) - const algorithm = this.versionAlgorithm(); - return !this.store.meta.has('version') && algorithm != null ? VersionUtilities.versionMatchesByAlgorithm(criteria, version, algorithm) : false; + 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: @@ -185,9 +181,7 @@ class SqliteV2Provider extends BaseCSServices { 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 }); - // (Waits on spec 7.1: SNOMED CT's `child` row has code-display in its presentation, which - // neither the previous answers nor cs-snomed.js give; an inverse row reports no code-display) - else if (p === 'code-display' && !d.reverses) parts.push({ name: 'code-display', valueString: this._propertyDisplay(d) }); + 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 }); @@ -565,8 +559,10 @@ class SqliteV2Provider extends BaseCSServices { } /** - * The status text (README.md "Concept status"): the concept's status literal (role status) when it - * has one and it is not `active`; else `inactive` for an inactive concept; else none + * 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); @@ -579,10 +575,7 @@ class SqliteV2Provider extends BaseCSServices { c.status = v === undefined ? null : v; v = c.status; } - // (Waits on spec 5.1, status text: it drops a status value `active` in any case, which would - // drop LOINC's ACTIVE; only the value `active` as written is no status text, which keeps the - // previous answers: LOINC ACTIVE reported, RxNorm active not) - if (v != null && String(v) !== 'active') return String(v); + if (v != null) return String(v); } return c.row.active ? null : 'inactive'; } @@ -650,11 +643,9 @@ class SqliteV2Provider extends BaseCSServices { } /** - * The language of the display designation: code_system.default_language, else en. - * (Waits on spec 5.2.2: its rule, the language of the first item whose text is the display, gives - * LOINC parts the language of a translation that happens to equal the display, e.g. el-GR for - * LP7786-9 "CHEM"; the default language keeps the previous answers: en-US for LOINC and RxNorm, - * en for UNII as spec 11 rows 2 and 22 say.) + * 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; From 18b42db2d8565ff283325af73ee0853fdb0518f5 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 16:30:59 -0600 Subject: [PATCH 52/90] sqlite-v2 reader: the final revision's keys (expansionNeverNests, forwardOnly, operator of, mapping parts) - compatibility.expansionNeverNests (SNOMED CT, LOINC files): the provider says it has no parents (hasParents), and expand.js lists the rows of a whole-system walk flat when the code system has no parents, as its filter path already does. SNOMED CT's own hasParents() (true, by grammar) is gone: the file decides. - implicitMaps.forwardOnly: maps from this system only ($translate into it finds nothing; the implicit map has one group). - compatibility.translationDisplayIsSourceDisplay: a translated Coding carries the display of the concept translated. (OMOP's file sets both; it is still refused for implicitMaps.used.) - filter.operators may hold `of` (VCL `of` and set-valued `in`); it is no filter operator: a filter with it, or on a row that has only it, is not understood. - presentation parts `equivalence` and `version`, on mapping rows only: a mapping value carries its version and the equivalence subproperty only where its row's parts say (LOINC's map rows have both). - implicitValueSets texts: `{v_}` ({v} with - written _); a placeholder other than {v}, {v_}, {display}, {version} is refused. Tests: the new keys at open and refused when malformed, of rows, mapping parts, forwardOnly and the source display, {v_}; a $expand test of nesting with and without expansionNeverNests (it fails without the expand.js change). Co-Authored-By: Claude --- tests/tx/sqlite-v2-expansion-nesting.test.js | 80 ++++++++++++++++++++ tests/tx/sqlite-v2-format.test.js | 59 ++++++++++++++- tx/sqlite-v2/meta.js | 27 +++++-- tx/sqlite-v2/provider.js | 40 ++++++---- tx/sqlite-v2/snomed.js | 1 - tx/sqlite-v2/store.js | 20 +++-- tx/workers/expand.js | 4 + 7 files changed, 199 insertions(+), 32 deletions(-) create mode 100644 tests/tx/sqlite-v2-expansion-nesting.test.js 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 000000000..dab8968bd --- /dev/null +++ b/tests/tx/sqlite-v2-expansion-nesting.test.js @@ -0,0 +1,80 @@ +'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 its rows flat whatever the file says) + 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.test.js b/tests/tx/sqlite-v2-format.test.js index 8b1cbf810..c7a4e0918 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -160,6 +160,20 @@ describe('identification and the meta rule', () => { expect(() => openStore(withMeta(base, { 'ix.ix_order.walk.reached': '-1' }))).toThrow(/meta ix.ix_order.walk.reached = -1 is not a value/); }); + 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; one this reader does not implement too', () => { expect(() => openStore(withMeta(base, { compatibility: '{"keepEverything": true}' }))).toThrow(/meta compatibility = .* is not a value/); expect(() => openStore(withMeta(base, { compatibility: '{"expansionKeepsRepeatedDesignations": true}' }))).toThrow(/expansionKeepsRepeatedDesignations is set .* which this server does not implement/); @@ -481,6 +495,21 @@ describe('how properties are reported (property columns, order)', () => { 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); @@ -585,6 +614,17 @@ describe('filter rows', () => { }); }); + 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/); @@ -645,19 +685,21 @@ describe('versions, implicit value sets and maps, expansion limits, lookup name' 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, description: 'below {display}', include: { filter: [{ property: 'concept', op: 'is-a', 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); expect(await fac.buildKnownValueSet('http://example.org/vs')).toMatchObject({ name: 'All', compose: { include: [{ system: 'http://example.org/cs', version: '1' }] } }); expect((await fac.buildKnownValueSet('http://example.org/vs/root')).compose.include[0].concept).toEqual([{ code: 'B' }, { code: 'A' }]); - expect(await fac.buildKnownValueSet('http://example.org/vs/A')).toMatchObject({ description: 'below display A', + expect(await fac.buildKnownValueSet('http://example.org/vs/A')).toMatchObject({ name: 'BelowA', description: 'below display A', compose: { include: [{ filter: [{ property: 'concept', op: 'is-a', value: 'A' }] }] } }); + 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(); }); @@ -671,6 +713,19 @@ describe('versions, implicit value sets and maps, expansion limits, lookup name' 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', async () => { diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 6b39bb3bd..9e80fc31a 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -27,9 +27,15 @@ const WRITTEN_FEATURES = Object.freeze(['identifier-text', 'fhir-reading']); /** the marker of this revision */ const REVISION = 'fhir-reading'; -/** the FHIR filter operators (filter.operators) */ +/** 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']); @@ -93,20 +99,22 @@ const isVersion = (v) => isPlainObject(v) && onlyKeys(v, ['match', 'partial', 'd /** 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, isString) && opt(t.title, isString) && opt(t.description, isString))); + && 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?, associations?} */ -const isImplicitMaps = (v) => isPlainObject(v) && onlyKeys(v, ['base', 'maps', 'used', 'associations']) +/** 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.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))); @@ -126,10 +134,12 @@ const COMPATIBILITY = Object.freeze({ 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)), }); @@ -137,8 +147,9 @@ 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, unknownCodeMessage: null, - filterUnknownCodeMessage: null, filterRejectMessage: null, missingValueFiltersAs: {}, lookupRankWhenConceptHas: [], + 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)); @@ -261,6 +272,6 @@ function orderOf(order, member) { } module.exports = { - readMeta, orderOf, KEYS, WRITER_KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, FILTER_OPERATORS, STATUS_MEANINGS, ORDER_WORDS, + 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/provider.js b/tx/sqlite-v2/provider.js index 76aee866e..9b2600727 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -110,7 +110,11 @@ class SqliteV2Provider extends BaseCSServices { const walked = this.store.listed(this._stats()) || this.store.all(); return walked.andCardinality(this.store.active()); } - hasParents() { return !!this.store.hierarchy; } + /** + * 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; } contentMode() { return this.store.cs.content || 'complete'; } versionAlgorithm() { return this.f.versionAlgorithm(); } @@ -876,12 +880,14 @@ class SqliteV2Provider extends BaseCSServices { 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) coding.version = m.version; + if (m.version && parts.includes('version')) coding.version = m.version; coding.code = m.code; if (m.display) coding.display = m.display; - add(d, 3, [m.system, m.code], m.code, (params) => params.push({ name: 'property', part: [{ name: 'code', valueCode: d.name }, { name: 'value', valueCoding: coding }, - { name: 'subproperty', part: [{ name: 'code', valueCode: 'equivalence' }, { name: 'value', valueCode: m.equivalence }] }] })); + 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 @@ -1018,8 +1024,10 @@ class SqliteV2Provider extends BaseCSServices { /** * $translate over an implicit map: a map of meta implicitMaps.maps (the mapping rows of its - * system, both ways), or an association (implicitMaps.associations: the active record rows of the - * relation, subject -> target, forward only) + * 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) */ async getTranslations(map, coding, target, reverse) { const S = this.store; @@ -1041,15 +1049,18 @@ class SqliteV2Provider extends BaseCSServices { 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) }; 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: map.vurl, system: this.system(), version: this.version(), code: r.code, display, relationship: mapRelationship(r.equivalence, false) }); } } return out; @@ -1528,9 +1539,9 @@ function mapRelationship(equivalence, fromFile) { } } -/** substitute {v} (and the other names) in every string of a JSON value */ +/** 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|display|version)\}/g, (m, k) => (vars[k] != null ? vars[k] : m)); + 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; @@ -1717,7 +1728,7 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { if (t.mustBeCode) return undefined; } else row = this.store.conceptRows([id]).get(id); } - const vars = { v, display: row ? row.display : null, version: this.version() }; + 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(); @@ -1744,7 +1755,8 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { if (!maps.length || !dest) return; const me = this.system(); const destSystem = dest.split('|')[0]; - const other = source === me ? destSystem : destSystem === me ? source : null; + // (implicitMaps.forwardOnly: only maps from this system) + const other = source === me ? destSystem : destSystem === me && !this.store.implicitMapsSpec.forwardOnly ? source : null; const lm = maps.find((m) => m.system === other); if (!lm || conceptMaps.some((m) => m.url === lm.url)) return; if (code) { @@ -1772,7 +1784,7 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { const { ConceptMap } = require('../library/conceptmap'); const me = this.system(); const groups = [{ source: me, target: lm.system }]; - if (lm.system !== me) groups.push({ source: lm.system, target: me }); + 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 }); diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index ce1bc6e44..4d6737ebb 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -66,7 +66,6 @@ class NativeExprContext { class SnomedV2Provider extends SqliteV2Provider { name() { return `SNOMED CT ${editionName(this.f.edition()) || 'Unknown Edition'}`; } isNotClosed() { return true; } - hasParents() { return true; } hasMultiHierarchy() { return true; } hasAnyDisplays(languages) { diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index cd8aee4c0..7810bbf1d 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -24,7 +24,7 @@ const Database = require('better-sqlite3'); const { RoaringBitmap32 } = require('roaring'); -const { readMeta, orderOf, FILTER_OPERATORS } = require('./meta'); +const { readMeta, orderOf, FILTER_ROW_OPERATORS } = require('./meta'); const FORMAT = 'tx-terminology/1'; const USER_VERSION = 1; @@ -79,7 +79,7 @@ function setKey(kind, pid, value, vk = 0) { } -const FILTER_OPS = new Set(FILTER_OPERATORS); +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']); @@ -90,11 +90,15 @@ const REMOVED_COLUMNS = ['filterable', 'filter_ops', 'report', 'reported_as', 'n // what a filter row may read besides a property code (README.md "filter") const FILTER_READS = new Set(['concept', 'inactive', 'display', 'designations', 'grammar', '{1}']); -/** property.presentation: {value?: code|string|display|coding, parts?: [description|code-display|partCode]} */ -function isPresentation(v) { +/** + * property.presentation: {value?: code|string|display|coding, parts?: [description|code-display|partCode|equivalence|version]}; + * equivalence and version only on a mapping row + */ +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) => ['description', 'code-display', 'partCode'].includes(x)))); + && (v.parts === undefined || (Array.isArray(v.parts) && v.parts.every((x) => parts.includes(x)))); } const NODE_SHAPES = new Set(['link', 'union']); @@ -480,6 +484,8 @@ class Store { * capture of a code_pattern row: {row, capture}, or null */ filterRow(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 null; const n = String(name); for (const f of this.filters) { if (!f.operators.includes(op)) continue; @@ -616,7 +622,7 @@ class Store { 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)) throw bad(r, `presentation ${r.presentation}`); + 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); } @@ -1362,7 +1368,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) { diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 34fc4c002..90beb2448 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -2058,6 +2058,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); From fc3febec8ae3c555aaacdb50cadf35c62d44a608 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 16:31:04 -0600 Subject: [PATCH 53/90] sqlite-v2 importers: write the final revision - SNOMED CT: compatibility.expansionNeverNests; filter rows moduleId and the attribute pattern take `=` and `of`, new rows parent and child take `of` only (13 rows); presentation of moduleId and child is description only, of definitionStatusId description and code-display, as the reference files. - LOINC: compatibility.expansionNeverNests; the implicit value set templates carry upstream's names and descriptions ({v_}, {display}); the twelve map rows have presentation parts equivalence and version. - builder: filter rows may name `of`; reading().newProperties take a presentation. Co-Authored-By: Claude --- tx/importers/import-loinc-v2.module.js | 14 +++++++++----- tx/importers/sct-v2-common.js | 20 +++++++++++++------- tx/importers/sqlite-v2/builder.js | 8 ++++---- 3 files changed, 26 insertions(+), 16 deletions(-) diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index e1dac24c9..9d39f1518 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -234,9 +234,12 @@ const LOINC_READING = { search: { names: { display: 'en', items: { designations: true, excludeUses: ['RELATEDNAMES2'] } } }, version: { match: 'prefix' }, implicitValueSets: [ - { url: 'http://loinc.org/vs', include: {} }, - { url: 'http://loinc.org/vs/{v}', v: '^LP', mustBeCode: true, include: { filter: [{ property: 'ancestor', op: '=', value: '{v}' }] } }, - { url: 'http://loinc.org/vs/{v}', v: '^LL', mustBeCode: true, enumerate: { property: 'LIST', op: '=', value: '{v}' } }, + // (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 @@ -244,7 +247,7 @@ const LOINC_READING = { // 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, + displayDesignation: 'always', lookupNameIsTitle: true, expansionDeclaresProperties: false, expansionNeverNests: true, filterUnknownCodeMessage: 'Not a valid code: {code}', missingValueFiltersAs: { STATUS: 'NotStated' }, }, }, @@ -266,7 +269,8 @@ const LOINC_READING = { ], newProperties: [ { code: 'RELATEDNAMES2', shape: 'item-use', fhirType: 'string' }, - ...LOINC_MAPS.map(([, key]) => ({ code: key, shape: 'mapping', fhirType: 'Coding' })), + // 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 }, diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 37c29ae50..8479ea39d 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -93,7 +93,7 @@ const SNOMED_READING = { implicitValueSets: [{ grammar: 'fhir_vs' }], grammar: 'snomed', compatibility: { generalizesLeavesOutFocus: true, wholeSystemIncludeActiveOnly: true, isAListsFocusFirst: true, - lookupOmitsTextDefinitions: true, expansionDeclaresProperties: false }, + lookupOmitsTextDefinitions: true, expansionDeclaresProperties: false, expansionNeverNests: true }, }, // (an entry for each association reference set the file has rows of) associations: [ @@ -122,13 +122,16 @@ const SNOMED_READING = { { code: 'code', operators: CONCEPT_OPS, reads: 'concept' }, { code: 'inactive', operators: ['='], reads: 'inactive', allowedValues: ['true', 'false'] }, { code: 'display', operators: ['regex'], reads: 'designations' }, - { code: 'moduleId', operators: ['='], reads: 'moduleId' }, + { 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: ['='], reads: '{1}' }, + { 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]; @@ -293,8 +296,10 @@ class SnomedSink { // (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 }); - this.defStatus = b.property({ code: 'definitionStatusId', shape: 'link', display: 'Definition status', refinable: false, wildcard: false }); + 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] @@ -412,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) - this.b.property({ code: 'child', shape: 'link', display: 'Child', inverseOf: this.isA, 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++) { diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 09ee3ca29..9f602463f 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -33,7 +33,7 @@ const crypto = require('crypto'); const Database = require('better-sqlite3'); const { numberConcepts } = require('../sqlite-v2/numbering'); const { buildIndexes } = require('./indexes'); -const { readMeta, WRITTEN_FEATURES, FILTER_OPERATORS } = require('../../sqlite-v2/meta'); +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'); @@ -181,7 +181,7 @@ class TerminologyBuilder { * | {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}]: catalog rows after + * 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, codeAnyCase, valuePrefix, linksAsDisplay, @@ -528,7 +528,7 @@ class TerminologyBuilder { // 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 }); + 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()); @@ -1049,7 +1049,7 @@ function checkContracts(db) { if ((f.code == null) === (f.code_pattern == null)) fail(`${what}: exactly one of code and code_pattern`); 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_OPERATORS.includes(o)))) fail(`${what}: operators ${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}`); From 0f3f25a60d5f23d978804aef1ab481f4990fab8b Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 16:31:36 -0600 Subject: [PATCH 54/90] sqlite-v2 README: the final revision The format document states what the revision settled: filter operator `of` (VCL `of` and set-valued `in`; a row with only `of` names no filter), then_link order, presentation parts equivalence and version on mapping rows, the status text as stored (where an operation reports it is the operation's rule), the display designation in the default language, versions by meta version only, implicit value set texts with {v_}, implicitMaps.forwardOnly, compatibility.expansionNeverNests and translationDisplayIsSourceDisplay, SNOMED CT's 13 filter rows and the importers' presentation columns, LOINC `refset` not understood. The section on previous answers becomes the revision's open points and this reader's answer at each (RxNorm AUI values, SNOMED CT values that are not concept ids, a supplement's display, the supplement-designation dedupe, a value set's include display in $validate-code, kind 5 sets). Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 96 ++++++++++++++++++++++++++---------------- 1 file changed, 60 insertions(+), 36 deletions(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index f4c69ceff..dc1c54e89 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -144,7 +144,7 @@ rows that exist only to report something (shapes `item-use`, `mapping`, `reading | `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]}` | 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 | +| `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`); never reported, filtered or declared | | `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). The JS reader does not implement them and refuses a file that sets one | @@ -155,9 +155,11 @@ 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 with an - `equivalence` subproperty, ordered by system then code. Example: LOINC `sct` (12 such rows, one per - implicit map key). +- `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`). @@ -184,7 +186,7 @@ The three shapes without rows of their own: | `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 | required | the operators this row takes; two rows with one `code` have disjoint operators (LOINC `answers-for`) | +| `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`). `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:`) | @@ -217,6 +219,19 @@ minus the `in` selection; every selection is cut to the listed concepts, see "Co 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): ``` @@ -229,7 +244,8 @@ LIST ["="] "concept" allowed_values "codes `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. +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 @@ -287,9 +303,12 @@ those `compatibility.statusReadingsIgnored` lists. 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 `status` parameter of `$validate-code`, an expansion row's `status`): the - value of the concept's `role = 'status'` literal when it has one and that value is not `active` - (ignoring case); else `inactive` for an inactive concept; else none. +- **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: @@ -323,10 +342,10 @@ the default), else `preferredForLanguage` none. **The display designation**: `concept.display`, use none in the list (`preferredForLanguage` where a -designation needs one), language: that of the first item (list order) whose text is the display and -that has a language, else `code_system.default_language`. LOINC and RxNorm items are `en-US`, so their -display designation is `en-US`; UNII's file has no item equal to the display and default language -`en`. +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: @@ -488,7 +507,7 @@ memory; the other languages keep the stored index. | 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`) | +| `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`) | @@ -497,10 +516,12 @@ memory; the other languages keep the stored index. A list of templates, tried in order; the first whose `url` and `v` match answers. ```json -[{"url": "http://loinc.org/vs", "include": {}}, +[{"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}"}]}}, - {"url": "http://loinc.org/vs/{v}", "v": "^LL", "mustBeCode": true, "enumerate": {"property": "LIST", "op": "=", "value": "{v}"}}] + "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 | @@ -509,8 +530,8 @@ A list of templates, tried in order; the first whose `url` and `v` match answers | `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 and version the file's), `{v}` substituted in every string | -| `enumerate` | instead of `include`: one filter whose concepts, in the filter's order, are listed as `include.concept` | -| `name`, `title`, `description` | the resource's texts, with `{v}`, `{display}` (the display of concept `{v}`), `{version}` | +| `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. @@ -519,12 +540,15 @@ So `http://loinc.org/vs/LL6136-7` is the list's answers, enumerated in sequence; ```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, both ways. How a mapping row is reported by `$lookup` is decided by its - `property_id` only. + 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`: a member the JS reader does not implement (a file with it is refused). - `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 @@ -567,10 +591,12 @@ refuses a file with a member it does not implement, and refuses an unknown membe | `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 reader does not implement it: its expansion code removes repeats) | +| `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 @@ -583,12 +609,13 @@ What each importer writes (the reader knows none of it): | `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...` | none | none | +| `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 | -| `compatibility` | generalizesLeavesOutFocus, wholeSystemIncludeActiveOnly, isAListsFocusFirst, lookupOmitsTextDefinitions, expansionDeclaresProperties false | statusReadingsIgnored, displayDesignation always, lookupNameIsTitle, expansionDeclaresProperties false, filterUnknownCodeMessage, missingValueFiltersAs | displayDesignation once, designationUse none, expansionDeclaresProperties false | displayDesignation once, wholeSystemIncludeEmpty, unknownCodeMessage | -| `filter` rows | 11 (concept, code, inactive, display, moduleId, definitionStatusId, effectiveTime, constraint, expressions, attribute pattern, `mapped:` pattern) | 61 | 61 (TTY, STY, SAB any case; relationships with `CUI:`; concept, code) | 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) | 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 | | | The other systems of this format (ICD-11, CPT, NDC, OMOP) are written by other importers; their content is in the same keys. @@ -605,23 +632,20 @@ generic provider serves any plain-code file (UNII). It refuses, naming the key: | ICD-11 Foundation | `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_extension`) | | CPT | `grammar` `cpt` | | NDC | `alias_literals` on `code11` (11-digit codes as codes in their own right) | -| OMOP | `implicitMaps.used` | +| OMOP | `implicitMaps.used` (it implements `implicitMaps.forwardOnly` and `compatibility.translationDisplayIsSourceDisplay`, which OMOP's file also sets) | -## Where the JS reader keeps the previous answers (open points of the revision) +## Not settled in the revision -Until the revision settles these, the JS reader answers as before at these places (each marked in the -code with the section it waits on): +The revision leaves these open; the JS reader's answer at each: | point | this reader | |---|---| -| the display designation's language ("Designations and display") | `code_system.default_language` (else `en`), not the language of an item with the display's text (which gives a LOINC part the language of a translation that happens to equal its display) | -| status text ("Concept status") | the status literal unless its value is `active` as written (LOINC `ACTIVE` is reported, RxNorm `active` is not) | -| `then_link` order | a row that reads only `concept` (LOINC `LIST`) lists in the stored order, as upstream does; other rows (and `enumerate`) in the list's order | -| `code-display` of an inverse row (SNOMED CT `child`) | not reported, as upstream does | -| version matching of a file without meta `version` | by the `versionAlgorithm` its stored CodeSystem resource declares (semver), else exactly | -| implicit value set names | as the templates state (the LOINC templates state none) | -| RxNorm `AUI:` filter values | no filter rows exist for them: not understood | -| `ix_set` kind 5 sets | also for the hierarchy property and for `search.candidates.hasLiteral` (child-of, the hierarchy walk and the search candidates read them) | +| RxNorm `AUI:` filter values (files built with `--atom-relationships`) | no filter rows are designed for them: not understood (no installed file has them) | +| 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 From 4e484e2d0d1b410dd6aea066976c8825f4b40def Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 20:59:34 -0600 Subject: [PATCH 55/90] sqlite-v2 reader: alias_literals (NDC 11-digit codes in their own right) A code read through an identifier with resolves 2 reports its scheme's alias_literals instead of its concept's stored values ({code}: the concept's own code). A filter `=` a template's value on such a property lists the scheme's identifiers for which every filter holds, in their concepts' order; a membership check of such a code tests those properties by the template and the others by its concept. Composes that name such codes take the usual expansion path. alias_parameter and alias_extension are still refused. The library takes a `sqlite-v2:` source line for a file of any code system. Co-Authored-By: Claude --- tests/tx/sqlite-v2-alias-literals.test.js | 153 ++++++++++++++++++ tests/tx/sqlite-v2-format.test.js | 3 +- tx/README.md | 15 +- tx/library.js | 12 +- tx/sqlite-v2/README.md | 35 +++- tx/sqlite-v2/index.js | 5 +- tx/sqlite-v2/provider.js | 187 +++++++++++++++++++++- tx/sqlite-v2/store.js | 36 ++++- 8 files changed, 418 insertions(+), 28 deletions(-) create mode 100644 tests/tx/sqlite-v2-alias-literals.test.js 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 000000000..2b54eb4fb --- /dev/null +++ b/tests/tx/sqlite-v2-alias-literals.test.js @@ -0,0 +1,153 @@ +'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) { + const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(include) }]); + expect(res.status).toBe(200); + return (res.body.expansion.contains || []).map((c) => c.code); +} + +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); +}); diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index c7a4e0918..1dea62ba9 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -178,7 +178,8 @@ describe('identification and the meta rule', () => { expect(() => openStore(withMeta(base, { compatibility: '{"keepEverything": true}' }))).toThrow(/meta compatibility = .* is not a value/); expect(() => openStore(withMeta(base, { compatibility: '{"expansionKeepsRepeatedDesignations": true}' }))).toThrow(/expansionKeepsRepeatedDesignations is set .* which this server does not implement/); expect(() => openStore(withMeta(base, { implicitMaps: '{"base": "http://x/", "maps": [], "used": "to-"}' }))).toThrow(/implicitMaps.used is set, which this server does not implement/); - expect(() => openStore(withSql(base, "UPDATE property SET alias_literals = '{}' WHERE code = 'colour'"))).toThrow(/property colour has alias_literals .* which this server does not implement/); + // 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', () => { diff --git a/tx/README.md b/tx/README.md index 596fc2fc1..a0d25943c 100644 --- a/tx/README.md +++ b/tx/README.md @@ -633,18 +633,21 @@ 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` - code systems from sqlite-v2 files -Serve one release of SNOMED CT, LOINC or RxNorm from a sqlite-v2 terminology file instead of the -`snomed`, `loinc` or `rxnorm` file of the same release; 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). +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:` and `rxnorm-v2:` also check that the file holds that system, and +serve it instead of the `snomed`, `loinc` or `rxnorm` file of the same release. 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). ```yaml - loinc-v2!:loinc-2.83.db - snomed-v2!:sct-intl-20260701.db - rxnorm-v2:rxnorm-03022026.db +- sqlite-v2:ndc-20261117.db ``` #### `cpt` - CPT (Current Procedural Terminology) diff --git a/tx/library.js b/tx/library.js index d4c676df8..85e73c44f 100644 --- a/tx/library.js +++ b/tx/library.js @@ -79,8 +79,10 @@ 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' @@ -512,6 +514,7 @@ class Library { await this.loadIcd11(details, isDefault, mode); break; + case 'sqlite-v2': case 'snomed-v2': case 'loinc-v2': case 'rxnorm-v2': @@ -1127,8 +1130,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:`, 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. */ @@ -1140,7 +1144,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/sqlite-v2/README.md b/tx/sqlite-v2/README.md index dc1c54e89..66b40c2b6 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -147,7 +147,7 @@ rows that exist only to report something (shapes `item-use`, `mapping`, `reading | `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`); never reported, filtered or declared | -| `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). The JS reader does not implement them and refuses a file that sets one | +| `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". The JS reader implements `alias_literals`, and refuses a file that sets `alias_parameter` or `alias_extension` | | 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: @@ -406,6 +406,28 @@ rows with `expansion_rank` first, then the rest in the `$lookup` order. An expan (`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) and `alias_extension` (a URL): ICD-11's + classification-code form and the Coding extension that restates it. The JS reader does not + implement them yet, and refuses a file that sets one. + ## Expansion limits ```json @@ -623,17 +645,20 @@ content is in the same keys. ## What the JS reader serves It reads any file of this revision whose keys it implements, whatever the system: the library loads -SNOMED CT, LOINC and RxNorm files (`snomed-v2:`, `loinc-v2:`, `rxnorm-v2:` source lines), and the -generic provider serves any plain-code file (UNII). It refuses, naming the key: +a file of any code system from a `sqlite-v2:` source line (and SNOMED CT, LOINC and RxNorm files from +`snomed-v2:`, `loinc-v2:`, `rxnorm-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`). It refuses, +naming the key: | file | refused because | |---|---| -| ICD-11 MMS, ICF | `grammar` `icd11`; `compatibility.expansionKeepsRepeatedDesignations`; alias columns | +| ICD-11 MMS, ICF | `grammar` `icd11`; `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_parameter`, `alias_extension`) | | ICD-11 Foundation | `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_extension`) | | CPT | `grammar` `cpt` | -| NDC | `alias_literals` on `code11` (11-digit codes as codes in their own right) | | OMOP | `implicitMaps.used` (it implements `implicitMaps.forwardOnly` and `compatibility.translationDisplayIsSourceDisplay`, which OMOP's file also sets) | +It serves NDC (`alias_literals` on `code11`: "Alternate codes"). + ## Not settled in the revision The revision leaves these open; the JS reader's answer at each: diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js index 0c64f5bc7..1d9498944 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -1,8 +1,9 @@ 'use strict'; // sqlite-v2 terminology files: provider registration entry point. // -// A library source line `snomed-v2:`, `loinc-v2:` or `rxnorm-v2:` loads one file -// (Library.loadSqliteV2). Without such a line nothing here, nor roaring, is loaded. +// A library source line `sqlite-v2:` (any code system), `snomed-v2:`, `loinc-v2:` +// or `rxnorm-v2:` loads one file (Library.loadSqliteV2). Without such a line nothing here, nor +// roaring, is loaded. const Database = require('better-sqlite3'); const { SqliteV2Factory } = require('./provider'); diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 9b2600727..8c89fad45 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -56,8 +56,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 { @@ -433,7 +437,19 @@ 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; } @@ -485,7 +501,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); @@ -833,7 +850,17 @@ class SqliteV2Provider extends BaseCSServices { if (!rows.length) return []; const out = []; const rankOf = this._ranks(c, rows); - const add = (d, kind, key, text, emit) => out.push({ d, rank: rankOf(d), kind, key, name: d.name, text: String(text), emit }); + // 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) }); + } + } // 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(); @@ -1179,10 +1206,147 @@ 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; } + // ---- 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}] + * (the filter row that understands prop and op) + */ + _aliasReads(prop, op) { + const S = this.store; + if (!S.aliasSchemes.length) return []; + const hit = S.filterRow(prop, op); + if (!hit) return []; + const out = []; + 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}`); @@ -1281,6 +1445,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; } @@ -1301,6 +1467,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)); @@ -1324,14 +1495,14 @@ class SqliteV2Provider extends BaseCSServices { 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 (this._member(set, r.context.id)) return r.context; + 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) { @@ -1382,6 +1553,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]) { diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 7810bbf1d..6b36a8131 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -567,13 +567,43 @@ class Store { * 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()) { - for (const c of ['alias_parameter', 'alias_extension', 'alias_literals']) { - if (d[c] != null) throw new Error(`${this.file}: property ${d.code} has ${c} (identifier-aliased codes), which this server does not implement`); + 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; + } + // (alias_parameter, alias_extension: not implemented here) + for (const c of ['alias_parameter', 'alias_extension']) { + if (d[c] != null) throw new Error(`${this.file}: property ${d.code} has ${c}, which this server does not implement`); } + this.aliasSchemes.push(d); } } + /** + * 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; + } + _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'); @@ -878,7 +908,7 @@ 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(this._idProbe(value)) || null; if (stats) count(stats, this, q, r ? 1 : 0); From 695a27515fe6008f37e19a95fb22f4d267abe9a7 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 21:01:05 -0600 Subject: [PATCH 56/90] sqlite-v2 reader: implicitMaps.used (OMOP) With implicitMaps.used 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 (both ways; forwardOnly still finds nothing into the file's system), and a translation names the map it used `{base}{used}{key}|{version}`. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format.test.js | 2 +- tests/tx/sqlite-v2-implicit-maps-used.test.js | 106 ++++++++++++++++++ tx/sqlite-v2/README.md | 8 +- tx/sqlite-v2/provider.js | 23 ++-- tx/sqlite-v2/store.js | 2 - 5 files changed, 128 insertions(+), 13 deletions(-) create mode 100644 tests/tx/sqlite-v2-implicit-maps-used.test.js diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index 1dea62ba9..8f06eabe0 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -177,7 +177,7 @@ describe('identification and the meta rule', () => { test('an unknown compatibility member is refused; one this reader does not implement too', () => { expect(() => openStore(withMeta(base, { compatibility: '{"keepEverything": true}' }))).toThrow(/meta compatibility = .* is not a value/); expect(() => openStore(withMeta(base, { compatibility: '{"expansionKeepsRepeatedDesignations": true}' }))).toThrow(/expansionKeepsRepeatedDesignations is set .* which this server does not implement/); - expect(() => openStore(withMeta(base, { implicitMaps: '{"base": "http://x/", "maps": [], "used": "to-"}' }))).toThrow(/implicitMaps.used is set, which this server does not implement/); + 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/); }); 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 000000000..826b92a1c --- /dev/null +++ b/tests/tx/sqlite-v2-implicit-maps-used.test.js @@ -0,0 +1,106 @@ +'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.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(); +} + +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(); + } +}); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 66b40c2b6..40c76950c 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -571,7 +571,10 @@ So `http://loinc.org/vs/LL6136-7` is the list's answers, enumerated in sequence; `$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`: a member the JS reader does not implement (a file with it is refused). +- `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 @@ -655,9 +658,8 @@ naming the key: | ICD-11 MMS, ICF | `grammar` `icd11`; `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_parameter`, `alias_extension`) | | ICD-11 Foundation | `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_extension`) | | CPT | `grammar` `cpt` | -| OMOP | `implicitMaps.used` (it implements `implicitMaps.forwardOnly` and `compatibility.translationDisplayIsSourceDisplay`, which OMOP's file also sets) | -It serves NDC (`alias_literals` on `code11`: "Alternate codes"). +It serves NDC (`alias_literals` on `code11`: "Alternate codes"), OMOP (`implicitMaps.used`: "Implicit maps"). ## Not settled in the revision diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 8c89fad45..0da92cd01 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1054,7 +1054,8 @@ class SqliteV2Provider extends BaseCSServices { * 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) + * 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; @@ -1073,12 +1074,13 @@ class SqliteV2Provider extends BaseCSServices { const lm = map && map.jsonObj && map.jsonObj.loincMap; if (!lm) return []; 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; const display = S.compat.translationDisplayIsSourceDisplay ? sourceDisplay : r.display; if (display) t.display = display; @@ -1087,7 +1089,7 @@ class SqliteV2Provider extends BaseCSServices { } else if (!S.implicitMapsSpec.forwardOnly && coding.system === lm.system && (!targetSystem || targetSystem === this.system())) { for (const r of S.mapsTo(lm.system, coding.code)) { const display = S.compat.translationDisplayIsSourceDisplay ? r.source_display : r.display; - out.push({ map: map.vurl, system: this.system(), version: this.version(), code: r.code, display, relationship: mapRelationship(r.equivalence, false) }); + out.push({ map: usedMap, system: this.system(), version: this.version(), code: r.code, display, relationship: mapRelationship(r.equivalence, false) }); } } return out; @@ -1922,17 +1924,24 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { return vs; } - // the file's implicit concept maps over mapping rows (meta implicitMaps: {base}{key}) + /** + * 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) { const maps = implicitMaps(this.store); if (!maps.length || !dest) return; const me = this.system(); const destSystem = dest.split('|')[0]; - // (implicitMaps.forwardOnly: only maps from this system) - const other = source === me ? destSystem : destSystem === me && !this.store.implicitMapsSpec.forwardOnly ? source : null; + 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) { + if (code && !always) { const id = this.store.idOf(code); if (!this.store.hasMap(id, lm.system, code)) return; } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 6b36a8131..975006489 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -345,8 +345,6 @@ class Store { if (this.compat.expansionKeepsRepeatedDesignations) { throw new Error(`${this.file}: compatibility.expansionKeepsRepeatedDesignations is set (the server's expansion code removes repeated designations, which this reader does not control), which this server does not implement`); } - // implicitMaps.used (maps reported as used whether or not they translate): not implemented here - if (this.implicitMapsSpec.used !== undefined) throw new Error(`${this.file}: implicitMaps.used is set, which this server does not implement`); // compatibility.lookupListsCopyright: the notice $lookup lists (code_system.resource.copyright) this.copyright = null; if (this.compat.lookupListsCopyright) { From 934f937ef52f00aed10f118b729a4a773795c0f0 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 21:02:48 -0600 Subject: [PATCH 57/90] sqlite-v2 reader: the grammar cpt (codes with modifiers) cpt.js serves a file whose meta grammar is cpt: a code may be a base code followed by `:`-separated modifiers, valid by the rule set of tx/cs/cs-cpt.js, run through that provider's locate() over the parts as the file has them (literals as properties, named items as designations). $lookup of an expression lists the copyright, the base code's lookup and each modifier with its first designation. The filter that reads the grammar, modified =, selects no concept for true (the include stays open) and every concept for false; an expression is a member only of filters that are all modified = true. Co-Authored-By: Claude --- tests/tx/sqlite-v2-cpt-grammar.test.js | 137 ++++++++++++++++++ tests/tx/sqlite-v2-format.test.js | 7 +- tx/sqlite-v2/README.md | 7 +- tx/sqlite-v2/cpt.js | 187 +++++++++++++++++++++++++ tx/sqlite-v2/index.js | 3 + 5 files changed, 335 insertions(+), 6 deletions(-) create mode 100644 tests/tx/sqlite-v2-cpt-grammar.test.js create mode 100644 tx/sqlite-v2/cpt.js 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 000000000..649ff525f --- /dev/null +++ b/tests/tx/sqlite-v2-cpt-grammar.test.js @@ -0,0 +1,137 @@ +'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('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', { filter: [f('modified', '=', 'true')] })).result).toBe(false); + expect((await validate('A0001', { filter: [f('modified', '=', 'false')] })).result).toBe(true); +}); diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index 8f06eabe0..14f6697f8 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -196,11 +196,14 @@ describe('identification and the meta rule', () => { withStore(path.join(dir, 'prov.db'), (S) => expect(S.conceptCount).toBe(1)); }); - test('the grammar registry: plain codes and snomed served; any other grammar refused, whatever the system', async () => { + test('the grammar registry: plain codes, snomed and cpt 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(); - for (const g of ['icd11', 'cpt', 'klingon']) { + const cpt = await loadSqliteV2Factory(op.i18n, withMeta(base, { grammar: '"cpt"' })); + expect(cpt.constructor.grammar).toBe('cpt'); + cpt.store.close(); + for (const g of ['icd11', '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/); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 40c76950c..8f5952466 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -590,7 +590,7 @@ does not implement. There is no fallback by system URI. |---|---|---|---| | `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` | implemented (`snomed.js`) | | `icd11` | ICD-11 MMS, ICF | postcoordinated expressions | refused | -| `cpt` | CPT | codes with modifiers; the `modified` filter | refused | +| `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 @@ -650,16 +650,15 @@ content is in the same keys. It reads any file of this revision whose keys it implements, whatever the system: the library loads a file of any code system from a `sqlite-v2:` source line (and SNOMED CT, LOINC and RxNorm files from `snomed-v2:`, `loinc-v2:`, `rxnorm-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`). It refuses, +chooses the provider (index.js): none, the generic provider (`provider.js`); `snomed` (`snomed.js`), `cpt` (`cpt.js`). It refuses, naming the key: | file | refused because | |---|---| | ICD-11 MMS, ICF | `grammar` `icd11`; `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_parameter`, `alias_extension`) | | ICD-11 Foundation | `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_extension`) | -| CPT | `grammar` `cpt` | -It serves NDC (`alias_literals` on `code11`: "Alternate codes"), OMOP (`implicitMaps.used`: "Implicit maps"). +It serves NDC (`alias_literals` on `code11`: "Alternate codes"), OMOP (`implicitMaps.used`: "Implicit maps"), CPT (`grammar` `cpt`: `cpt.js`). ## Not settled in the revision diff --git a/tx/sqlite-v2/cpt.js b/tx/sqlite-v2/cpt.js new file mode 100644 index 000000000..3e2cfd504 --- /dev/null +++ b/tx/sqlite-v2/cpt.js @@ -0,0 +1,187 @@ +'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`) + */ + 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); + await super._extendLookup(c.focus, props, params); + 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); + const r = await this.locate(code); + if (!r.context) return r.message; + return this._expressionMember(set) ? r.context : null; + } + + 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/index.js b/tx/sqlite-v2/index.js index 1d9498944..b1f4c4001 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -8,6 +8,7 @@ const Database = require('better-sqlite3'); const { SqliteV2Factory } = require('./provider'); const { SnomedV2Factory } = require('./snomed'); +const { CptV2Factory } = require('./cpt'); const { checkFormat } = require('./store'); const { readMeta } = require('./meta'); @@ -19,6 +20,8 @@ const { readMeta } = require('./meta'); const GRAMMARS = Object.freeze({ // SNOMED CT expressions and ECL (snomed.js) snomed: SnomedV2Factory, + // codes with modifiers (cpt.js) + cpt: CptV2Factory, }); /** the factory class for a grammar; throws for a grammar this server does not implement */ From 531baac709cf2e14ab9f94fa86b433a7d0579dcc Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 21:04:32 -0600 Subject: [PATCH 58/90] sqlite-v2 reader: the grammar icd11, alias_parameter and alias_extension (ICD-11) icd11.js serves a file whose meta grammar is icd11: postcoordinated expressions parsed, bound and normalised by tx/cs/icd11-expressions.js over the record relations postcoordinationAxis and postcoordinationRoot; an expression's display, $lookup (stem, postcoordination) and validation issues as cs-icd11.js gives them, and a plain code's axes with post-coordination-metadata. No filter selects an expression. alias_parameter: a concept's identifier (resolves 1) of the scheme is its classification-code form, reported by $validate-code as classificationCode for a code written as its concept's code. alias_extension: the Coding extension of that URL is checked against it. A filter value or a listed code may be an identifier accepted as a code. compatibility.expansionKeepsRepeatedDesignations is read: the server's expansion code keeps repeated designations for every system. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format.test.js | 10 +- tests/tx/sqlite-v2-icd11-grammar.test.js | 177 +++++++++++ tx/sqlite-v2/README.md | 43 +-- tx/sqlite-v2/engine/compile.js | 2 +- tx/sqlite-v2/icd11.js | 368 +++++++++++++++++++++++ tx/sqlite-v2/index.js | 3 + tx/sqlite-v2/provider.js | 55 ++++ tx/sqlite-v2/store.js | 48 ++- 8 files changed, 675 insertions(+), 31 deletions(-) create mode 100644 tests/tx/sqlite-v2-icd11-grammar.test.js create mode 100644 tx/sqlite-v2/icd11.js diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index 14f6697f8..4d3a9510f 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -174,9 +174,9 @@ describe('identification and the meta rule', () => { 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; one this reader does not implement too', () => { + 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/); - expect(() => openStore(withMeta(base, { compatibility: '{"expansionKeepsRepeatedDesignations": true}' }))).toThrow(/expansionKeepsRepeatedDesignations is set .* which this server does not implement/); + 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/); @@ -196,14 +196,16 @@ describe('identification and the meta rule', () => { withStore(path.join(dir, 'prov.db'), (S) => expect(S.conceptCount).toBe(1)); }); - test('the grammar registry: plain codes, snomed and cpt served; any other grammar refused, whatever the system', async () => { + 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(); - for (const g of ['icd11', 'klingon']) { + // 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/); 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 000000000..d1211b452 --- /dev/null +++ b/tests/tx/sqlite-v2-icd11-grammar.test.js @@ -0,0 +1,177 @@ +'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]); + } + // 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('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); + expect(res.body.expansion.contains.map((x) => x.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/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 8f5952466..d837d1f5c 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -147,7 +147,7 @@ rows that exist only to report something (shapes `item-use`, `mapping`, `reading | `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`); never reported, filtered or declared | -| `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". The JS reader implements `alias_literals`, and refuses a file that sets `alias_parameter` or `alias_extension` | +| `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: @@ -424,9 +424,15 @@ written. The identifier's scheme (its `property` row) carries how such a code is 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) and `alias_extension` (a URL): ICD-11's - classification-code form and the Coding extension that restates it. The JS reader does not - implement them yet, and refuses a file that sets one. +- `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 @@ -589,7 +595,7 @@ 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` | implemented (`snomed.js`) | -| `icd11` | ICD-11 MMS, ICF | postcoordinated expressions | refused | +| `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, `$lookup` (`stem`, `postcoordination`) and validation issues; a plain code's axes in `$lookup` with `post-coordination-metadata`; no filter selects an expression | 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 @@ -615,7 +621,7 @@ refuses a file with a member it does not implement, and refuses an unknown membe | `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 reader does not implement it: its expansion code removes repeats) | +| `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 | @@ -647,18 +653,21 @@ content is in the same keys. ## What the JS reader serves -It reads any file of this revision whose keys it implements, whatever the system: the library loads -a file of any code system from a `sqlite-v2:` source line (and SNOMED CT, LOINC and RxNorm files from -`snomed-v2:`, `loinc-v2:`, `rxnorm-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`). It refuses, -naming the key: +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 CT, LOINC and RxNorm files from `snomed-v2:`, +`loinc-v2:`, `rxnorm-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 | refused because | -|---|---| -| ICD-11 MMS, ICF | `grammar` `icd11`; `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_parameter`, `alias_extension`) | -| ICD-11 Foundation | `compatibility.expansionKeepsRepeatedDesignations`; alias columns (`alias_extension`) | - -It serves NDC (`alias_literals` on `code11`: "Alternate codes"), OMOP (`implicitMaps.used`: "Implicit maps"), CPT (`grammar` `cpt`: `cpt.js`). +| 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 diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 0a7f0bdfe..bfc2a690d 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -60,7 +60,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; diff --git a/tx/sqlite-v2/icd11.js b/tx/sqlite-v2/icd11.js new file mode 100644 index 000000000..6b8d20a30 --- /dev/null +++ b/tx/sqlite-v2/icd11.js @@ -0,0 +1,368 @@ +'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) { + return (await this.display(part.v2)) || null; + } + + /** an expression's display (cs-icd11.js #expressionDisplay): the members as written, each value in brackets after its code */ + async _expressionDisplay(expr) { + const parts = []; + for (const m of expr.members) { + let text = (await this._title(m.head.concept)) || m.head.text; + for (const t of m.tail) text += ` [${(await this._title(t.concept)) || t.text}]`; + parts.push(text); + } + return parts.join(' / '); + } + + /** the language a display is in: the first requested language the file has names in, else the default */ + _requestedDisplayLanguage() { + const langs = this.displayLanguages(); + const have = this.f.languages().map((l) => String(l).toLowerCase().split('-')[0]); + for (const l of (langs && langs.languages) || []) { + const base = String((l && (l.language || l.code)) || '').toLowerCase().split('-')[0]; + if (base && have.includes(base)) return base; + } + return this.defLang(); + } + + async display(context) { + const c = await this._ensure(context); + return c instanceof ICD11Expression ? this._expressionDisplay(c) : 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 */ + async _designations(context, displays, significantOnly) { + const c = await this._ensure(context); + if (!(c instanceof ICD11Expression)) return super._designations(c, displays, significantOnly); + const text = await this._expressionDisplay(c); + if (text) displays.addDesignation(true, 'active', this._requestedDisplayLanguage(), 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 --------------- + + 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`; + return super._filterLocate(prep, set, code); + } + + 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); + } +} + +module.exports = { Icd11V2Factory, Icd11V2Provider }; diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js index b1f4c4001..ab9daa5e4 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -9,6 +9,7 @@ const Database = require('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'); @@ -22,6 +23,8 @@ const GRAMMARS = Object.freeze({ 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 */ diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 0da92cd01..d313559e6 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -453,6 +453,61 @@ class SqliteV2Provider extends BaseCSServices { 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; } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 975006489..e6d1981d7 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -341,10 +341,8 @@ class Store { this.implicitValueSets = m.get('implicitValueSets'); this.implicitMapsSpec = m.get('implicitMaps'); this.grammar = m.get('grammar'); - // compatibility members this server does not implement: refused, never ignored - if (this.compat.expansionKeepsRepeatedDesignations) { - throw new Error(`${this.file}: compatibility.expansionKeepsRepeatedDesignations is set (the server's expansion code removes repeated designations, which this reader does not control), which this server does not implement`); - } + // (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) { @@ -583,12 +581,24 @@ class Store { } d.aliasLiterals = v; } - // (alias_parameter, alias_extension: not implemented here) - for (const c of ['alias_parameter', 'alias_extension']) { - if (d[c] != null) throw new Error(`${this.file}: property ${d.code} has ${c}, which this server does not implement`); + 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; } /** @@ -602,6 +612,11 @@ class Store { 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'); @@ -855,7 +870,7 @@ class Store { // ---- 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; @@ -864,8 +879,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; } @@ -1155,6 +1179,12 @@ class Store { .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); From 793c1d5c23bafb9ad452a40308eba64f22a013db Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 23:01:03 -0600 Subject: [PATCH 59/90] sqlite-v2 reader: fhir_type date as a dateTime; the known differences on NDC, OMOP, CPT, ICD-11 A literal of fhir_type date (OMOP's valid-start-date, valid-end-date) is reported as a dateTime, as cs-omop.js reports it; it was reported as a string. The README lists the differences from upstream's providers found on the four terminologies' files. Co-Authored-By: Claude --- tests/tx/sqlite-v2-implicit-maps-used.test.js | 14 ++++++++++++++ tx/sqlite-v2/README.md | 8 +++++++- tx/sqlite-v2/provider.js | 4 +++- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/tests/tx/sqlite-v2-implicit-maps-used.test.js b/tests/tx/sqlite-v2-implicit-maps-used.test.js index 826b92a1c..b4176399f 100644 --- a/tests/tx/sqlite-v2-implicit-maps-used.test.js +++ b/tests/tx/sqlite-v2-implicit-maps-used.test.js @@ -24,6 +24,7 @@ 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: { @@ -34,6 +35,11 @@ function build(file, used) { }); 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('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 () => { @@ -104,3 +110,11 @@ test('without used: the map is offered only where it translates, and named by it 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/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index d837d1f5c..ca00bd179 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -138,7 +138,7 @@ rows that exist only to report something (shapes `item-use`, `mapping`, `reading | `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`) | +| `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 | @@ -771,3 +771,9 @@ the fhir-reading revision, is refused at start-up with a message to re-import it | 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 | +| NDC `code-type = 11-digit` | packages in import order (NDCKey) | the 11-digit forms in their concepts' stored order, then value (not compared on the same data) | +| CPT `$validate-code` of an expression against a `modified = true` include | not in the value set (validate.js asks `filterLocate`, which never finds an expression) | in it ("Grammar": cs-cpt.js `filterCheck`) | +| CPT modifier `95` | valid on a base code with the property `telemedicine` = `true` | never valid: the CPT 2023 file has no `telemedicine` property, so upstream's rule finds none | +| CPT a code with two values of one property (`kind`) | in the release's row order | by value (`order.literals` default) | +| ICD-11 an expression's display | each part's title in the request's language | each part's display (`concept.display`, English: ICD-11's files have no `language_display_rank` use) | +| OMOP `$lookup` | `synonym` properties (from its ConceptSynonyms); two links to one target in row order | no `synonym` (the 20240716 file has none); by `order.links` | diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index d313559e6..2eeab3182 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -197,7 +197,8 @@ class SqliteV2Provider extends BaseCSServices { /** * 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) + * 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) { @@ -205,6 +206,7 @@ class SqliteV2Provider extends BaseCSServices { 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 }; From e806ca0f37215c6c546d3c84c29399f59a8a14a8 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Fri, 4 Dec 2026 23:37:09 -0600 Subject: [PATCH 60/90] sqlite-v2 reader: SNOMED CT ancestors nearest first; an include's first filter keeps its order generalizes and ECL > list ancestors level by level from the concept's parents, as cs-snomed.js filterGeneralizes; is-a and generalizes keep their order when other filters of the include narrow them. Compared with main's provider in sqlite-v2-sct-parity-http. Co-Authored-By: Claude --- tests/tx/sqlite-v2-sct-parity-http.test.js | 27 ++++++++++++++++ tx/sqlite-v2/README.md | 8 +++-- tx/sqlite-v2/engine/engine.js | 37 ++++++++++++++++++++-- tx/sqlite-v2/store.js | 6 ++++ 4 files changed, 72 insertions(+), 6 deletions(-) diff --git a/tests/tx/sqlite-v2-sct-parity-http.test.js b/tests/tx/sqlite-v2-sct-parity-http.test.js index 7ced467c9..1dfcb6456 100644 --- a/tests/tx/sqlite-v2-sct-parity-http.test.js +++ b/tests/tx/sqlite-v2-sct-parity-http.test.js @@ -213,3 +213,30 @@ 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); + }); +}); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index ca00bd179..0b539d1d4 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -475,8 +475,10 @@ Each member is a list of words compared left to right; a final tie makes the ord 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, and -`child-of` lists the children in `ix_in` seq order. Example: SNOMED CT `["stored"]` and +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 @@ -611,7 +613,7 @@ refuses a file with a member it does not implement, and refuses an unknown membe | `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 | -| `isAListsFocusFirst` | bool | false | SNOMED CT | with `order.expansion` `stored`: `is-a` lists its focus first; `child-of` in `ix_in` seq order | +| `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` | diff --git a/tx/sqlite-v2/engine/engine.js b/tx/sqlite-v2/engine/engine.js index d73a7dfb7..2a8e17485 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') 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 : null; +} + class Engine { constructor(store, opts = {}) { this.store = store; @@ -186,10 +198,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 { @@ -290,6 +302,25 @@ class Engine { } 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 === '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/store.js b/tx/sqlite-v2/store.js index e6d1981d7..814398129 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -1212,6 +1212,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)]; From 12688006245d7353a91aba3c8bf4020d85ddc0ee Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 00:10:53 -0600 Subject: [PATCH 61/90] sqlite-v2 reader: CPT $lookup of an expression reports its own notSelectable after the modifiers The base code's notSelectable, added by its lookup, is taken out; the lookup then reports the expression's (never abstract) after everything the provider lists, as cs-cpt.js extendLookup does. Co-Authored-By: Claude --- tests/tx/sqlite-v2-cpt-grammar.test.js | 11 +++++++++++ tx/sqlite-v2/cpt.js | 9 ++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/tx/sqlite-v2-cpt-grammar.test.js b/tests/tx/sqlite-v2-cpt-grammar.test.js index 649ff525f..dcdd0097e 100644 --- a/tests/tx/sqlite-v2-cpt-grammar.test.js +++ b/tests/tx/sqlite-v2-cpt-grammar.test.js @@ -124,6 +124,17 @@ test('$lookup of an expression: the copyright, the base code\'s lookup (its copy 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')] }); diff --git a/tx/sqlite-v2/cpt.js b/tx/sqlite-v2/cpt.js index 3e2cfd504..494973cc1 100644 --- a/tx/sqlite-v2/cpt.js +++ b/tx/sqlite-v2/cpt.js @@ -111,13 +111,20 @@ class CptV2Provider extends SqliteV2Provider { /** * $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`) + * 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); From 10e74bc41208a33a613e0f7c56a76a083cff568e Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 00:10:53 -0600 Subject: [PATCH 62/90] sqlite-v2 reader: ICD-11 answers as upstream's provider; whole-system refusal diagnostics - a designation use without a display in item_use is a Coding without display (was null) - order.links `stored`: inverse links of one seq keep the ix_in order (then the subject), so ICD-11 child values list in release order, not by code - parent(): the first hierarchy link by order.links; the provider's own selection nests an include of one filter under first parents when the page holds everything, as expand.js's usual path does (ICD-11 is-a) - grammar icd11: the value set a postcoordinationAxis row names in valueSet (postcoordination scale), one include is-a per root of the axis, with upstream's names and texts - grammar icd11: a located code an include of one filter does not select is "'' is not in the value set", the code in its alias_parameter form - expansionLimits.wholeSystem refuse: the text is repeated as the issue's diagnostics (OMOP) Co-Authored-By: Claude --- tests/tx/sqlite-v2-expansion-nesting.test.js | 3 +- tests/tx/sqlite-v2-format.test.js | 4 +- tests/tx/sqlite-v2-icd11-grammar.test.js | 3 +- tests/tx/sqlite-v2-icd11-reading.test.js | 142 +++++++++++++++++++ tx/sqlite-v2/icd11.js | 69 ++++++++- tx/sqlite-v2/provider.js | 77 +++++++--- tx/workers/expand.js | 13 +- 7 files changed, 283 insertions(+), 28 deletions(-) create mode 100644 tests/tx/sqlite-v2-icd11-reading.test.js diff --git a/tests/tx/sqlite-v2-expansion-nesting.test.js b/tests/tx/sqlite-v2-expansion-nesting.test.js index dab8968bd..40ff5804a 100644 --- a/tests/tx/sqlite-v2-expansion-nesting.test.js +++ b/tests/tx/sqlite-v2-expansion-nesting.test.js @@ -29,7 +29,8 @@ function build(file, uri, compatibility) { 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 its rows flat whatever the file says) + // 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(); } diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index 4d3a9510f..19537a87d 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -734,12 +734,12 @@ describe('versions, implicit value sets and maps, expansion limits, lookup name' 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', async () => { + 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' }); + 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(); }); diff --git a/tests/tx/sqlite-v2-icd11-grammar.test.js b/tests/tx/sqlite-v2-icd11-grammar.test.js index d1211b452..3cb23016b 100644 --- a/tests/tx/sqlite-v2-icd11-grammar.test.js +++ b/tests/tx/sqlite-v2-icd11-grammar.test.js @@ -167,7 +167,8 @@ test('$lookup of an expression: code, classificationCode, stem, the valued axes; 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); - expect(res.body.expansion.contains.map((x) => x.code)).toEqual(['500', '501', '502']); + // (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 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 000000000..d16f9ae9b --- /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/tx/sqlite-v2/icd11.js b/tx/sqlite-v2/icd11.js index 6b8d20a30..75b0e5615 100644 --- a/tx/sqlite-v2/icd11.js +++ b/tx/sqlite-v2/icd11.js @@ -235,10 +235,20 @@ class Icd11V2Provider extends SqliteV2Provider { // ---- 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`; - return super._filterLocate(prep, set, code); + 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) { @@ -363,6 +373,63 @@ class Icd11V2Factory extends SqliteV2Factory { 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/provider.js b/tx/sqlite-v2/provider.js index 2eeab3182..254940b27 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -30,7 +30,29 @@ const { languageByte, languageCode, languageBytesFor } = require('../sct/languag const CHUNK = 500; // rows fetched per statement while iterating a filter set const primary = (l) => String(l || '').toLowerCase().split('-')[0]; -const PAGE_ROWS = 2000; // a processSelection page's rows read per statement, with a pause between +/** 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; + +/** 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 processSelection page's rows read per statement, with a pause between /** a concept handle: id (concept_id), code; row/designations filled lazily or by a page batch */ class V2Concept { @@ -416,11 +438,12 @@ class SqliteV2Provider extends BaseCSServices { /** * expansionLimits.wholeSystem refuse (README.md "expansionLimits"): 500, exception, the text of - * compatibility.wholeSystemRefusalMessage ({system} filled in) or the plain one + * 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); + 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 */ @@ -658,7 +681,28 @@ class SqliteV2Provider extends BaseCSServices { 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) { @@ -715,7 +759,7 @@ class SqliteV2Provider extends BaseCSServices { * (compatibility.designationUse source); for a preferred item without one (or whose use is not * reported), preferredForLanguage; else none */ - _useOf(d, map = (u) => ({ system: u.system, code: u.code, display: u.display })) { + _useOf(d, map = useCoding) { if (d.use && this.store.compat.designationUse === 'source') return map(d.use); return d.preferred ? { ...DesignationUse.DISPLAY } : null; } @@ -987,19 +1031,7 @@ class SqliteV2Provider extends BaseCSServices { 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 }] })); } - const cmpKey = (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; - }; - out.sort((a, b) => (a.rank - b.rank) || (a.kind - b.kind) || cmpKey(a.key, b.key) || cmpText(a.name, b.name) || cmpText(a.text, b.text)); + 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; } @@ -1014,7 +1046,10 @@ class SqliteV2Provider extends BaseCSServices { return (d) => (over.has(d.code) ? over.get(d.code) : d.lookupRank != null ? d.lookupRank : Infinity); } - /** a link's sort key by meta order.links, ending with property id, group, target code, target id */ + /** + * 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) + */ _linkKey(d, l, code) { const key = []; for (const w of this.store.orderWords('links')) { @@ -1022,7 +1057,9 @@ class SqliteV2Provider extends BaseCSServices { case 'property-id': key.push(d.id); break; case 'property': key.push(d.name); break; case 'group': key.push(l.g || 0); break; - case 'stored': key.push(l.q ?? 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; diff --git a/tx/workers/expand.js b/tx/workers/expand.js index 90beb2448..56c8156ed 100644 --- a/tx/workers/expand.js +++ b/tx/workers/expand.js @@ -1252,7 +1252,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)) { @@ -1263,11 +1270,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); } From 53f7f7ac6e9cab51c83f49bf6a05d87394bb2357 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 00:10:53 -0600 Subject: [PATCH 63/90] sqlite-v2 README: stored link order of inverse links, nesting, icd11 scale value sets; known differences on NDC, OMOP, ICD-11 text search Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 0b539d1d4..b775d3e09 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -443,7 +443,7 @@ written. The identifier's scheme (its `property` row) carries how such a code is | 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`; `count=0` of one include and no exclude is still counted (OMOP) | +| `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 @@ -463,7 +463,7 @@ Each member is a list of words compared left to right; a final tie makes the ord | word | concepts | links | literals | |---|---|---|---| | `id` | concept id | | | -| `stored` | `ix_order` `rank` (the file must have `rank` and `ids`) | `link.seq` (NULL as 0) | | +| `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) | | | `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 | | | @@ -472,6 +472,11 @@ Each member is a list of words compared left to right; a final tie makes the ord | `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. @@ -597,7 +602,7 @@ 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` | 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, `$lookup` (`stem`, `postcoordination`) and validation issues; a plain code's axes in `$lookup` with `post-coordination-metadata`; no filter selects an expression | implemented (`icd11.js`, with upstream's parser `tx/cs/icd11-expressions.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, `$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 @@ -774,6 +779,11 @@ the fhir-reading revision, is refused at start-up with a message to re-import it | 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 | | NDC `code-type = 11-digit` | packages in import order (NDCKey) | the 11-digit forms in their concepts' stored order, then value (not compared on the same data) | +| NDC a property with several values (`upc`) in `$lookup` | in the release's row order | by value (`order.literals` default): the NDC file stores every literal with group 0, so it has no row order to give | +| NDC `category = X` and `code-type = 11-digit` in one include | no codes, total 0: expand.js walks the first filter, whose packages are written in their 10-digit form, and cs-ndc.js's `code-type` check reads the written code (`check`, cs-ndc.js:541; the walk writes `row.Code`, :619) | the 11-digit forms of the category's packages ("Alternate codes") | +| NDC an include of the whole system with `count` > 0 | no codes, total 0: cs-ndc.js has no iterator (`iterator` of cs-api.js returns null), so expand.js walks nothing; `count=0` is counted (`countAllCodes`) | the codes in stored order, no total; `count=0` the same count | +| OMOP a `domain` filter (and the implicit domain value sets) | in the concept table's row order | by concept id (`order.expansion` default): the OMOP file has no `order.expansion` `stored` and no `ix_order` `rank`, so it has no row order to give | +| ICD-11 text search (`filter=`) | on a database without the `designation_text` index (the classic file compared): the concepts with a name containing the whole text (`LIKE`), in classification order (cs-icd11.js:1023-1035) | the `text-match/1` word rules, by score (`cholera`: the same 22 concepts in another order; `essential hypertension`: also 1210166201, whose index term `essential hypertensive cardiovascular disease` has both words by stem) | | CPT `$validate-code` of an expression against a `modified = true` include | not in the value set (validate.js asks `filterLocate`, which never finds an expression) | in it ("Grammar": cs-cpt.js `filterCheck`) | | CPT modifier `95` | valid on a base code with the property `telemedicine` = `true` | never valid: the CPT 2023 file has no `telemedicine` property, so upstream's rule finds none | | CPT a code with two values of one property (`kind`) | in the release's row order | by value (`order.literals` default) | From d8c37c4f9718f6e49cdf16d2ae202b44ddeb8d0d Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 00:12:19 -0600 Subject: [PATCH 64/90] sqlite-v2 provider: comment back on its constant Co-Authored-By: Claude --- tx/sqlite-v2/provider.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 254940b27..26f692282 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -38,7 +38,7 @@ const useCoding = (u) => { if (u.display != null) c.display = u.display; return c; }; -const PAGE_ROWS = 2000; +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) => { @@ -52,7 +52,7 @@ const cmpKeys = (a, b) => { if (r) return r; } return 0; -}; // a processSelection page's rows read per statement, with a pause between +}; /** a concept handle: id (concept_id), code; row/designations filled lazily or by a page batch */ class V2Concept { From e02a0d335c0c8487d4a68eb09491fa64a1d3e476 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 00:39:52 -0600 Subject: [PATCH 65/90] sqlite-v2 format: literal.seq, read by order.literals stored A concept's values of one literal property can carry their source order, as links carry link.seq: column literal.seq (nullable, NULL as 0, outside the primary key) and the word stored of order.literals. The reader reads the column only when order.literals names stored, so a file written before it is read as before. group_id stays the role group. - schema.sql: literal.seq; builder: literal(..., {seq}), staged and carried (a literal in several rows keeps its first seq, as a link does); contract: order.literals stored needs the column. Positional literal INSERTs in the importers name their columns. - meta.js: stored among the literals words; store.literalsOf reads seq as q when the word is named; provider _literalKey sorts by it. - README: the literal table, the order tables, the contract. - tests/tx/sqlite-v2-stored-orders.test.js: $lookup lists a multi-valued property in seq order (a repeated value again) with the word and by value without it; a where_literal filter lists in ix_order rank order under order.expansion stored. Co-Authored-By: Claude --- tests/tx/sqlite-v2-stored-orders.test.js | 144 +++++++++++++++++++++++ tx/importers/import-loinc-v2.module.js | 2 +- tx/importers/sct-v2-common.js | 2 +- tx/importers/sqlite-v2/builder.js | 18 ++- tx/importers/sqlite-v2/schema.sql | 1 + tx/sqlite-v2/README.md | 7 +- tx/sqlite-v2/meta.js | 2 +- tx/sqlite-v2/provider.js | 1 + tx/sqlite-v2/store.js | 7 +- 9 files changed, 171 insertions(+), 13 deletions(-) create mode 100644 tests/tx/sqlite-v2-stored-orders.test.js 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 000000000..96b324389 --- /dev/null +++ b/tests/tx/sqlite-v2-stored-orders.test.js @@ -0,0 +1,144 @@ +'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. A file without those words keeps the defaults. The +// fixtures have the shapes of the NDC and OMOP 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'; +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(); +} + +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')); + 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']); +}); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 9d39f1518..174fce98b 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -180,7 +180,7 @@ function loincCatalog(b) { 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 SELECT c.id, ?, 0, + 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); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 8479ea39d..7354c9d98 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -235,7 +235,7 @@ const DERIVED = [{ table: 'ix_key', name: 'normalForm' }, { table: 'ix_order', n 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 VALUES (?, ?, 0, ?, 1)'); + 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 diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 9f602463f..c7cd1d40f 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -118,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); @@ -128,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 (?,?,?,?,?,?,?)'), @@ -353,9 +353,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(); } @@ -593,8 +594,9 @@ 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)); @@ -989,6 +991,10 @@ function checkContracts(db) { 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'); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 2d071579b..ee81d9f3e 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -140,6 +140,7 @@ 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; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index b775d3e09..cfd2c3b75 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -105,7 +105,7 @@ Fact tables: | `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 | +| `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`) | @@ -458,12 +458,12 @@ Each member is a list of words compared left to right; a final tie makes the ord | `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`, `value` | `["property-id", "group", "value"]` | property id, group, value | +| `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) | | +| `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 | | | @@ -710,6 +710,7 @@ them on request. | `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 | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 9e80fc31a..849cc1d45 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -44,7 +44,7 @@ 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', 'value'], default: ['property-id', 'group', 'value'] }, + 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 */ diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 26f692282..50e40c36e 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1078,6 +1078,7 @@ class SqliteV2Provider extends BaseCSServices { 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; } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 814398129..f19b95386 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -1195,9 +1195,14 @@ class Store { 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); From cd0c478b976499737e388633bfb26c992b4d171f Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 00:39:52 -0600 Subject: [PATCH 66/90] sqlite-v2 README: NDC multi-valued literals and OMOP domain order now as upstream The NDC file of 20261117 stores literal.seq with order.literals stored (upc of 58151-155-77 in the release's row order) and the OMOP file of 20240716 stores order.expansion stored with ix_order rank and ids in the concept table's row order, so the two known differences go: the NDC and OMOP batteries answer as upstream's providers but for the two NDC expansions where upstream finds nothing (category with 11-digit forms; the whole system with count > 0). Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index cfd2c3b75..bedee8aef 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -780,10 +780,8 @@ the fhir-reading revision, is refused at start-up with a message to re-import it | 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 | | NDC `code-type = 11-digit` | packages in import order (NDCKey) | the 11-digit forms in their concepts' stored order, then value (not compared on the same data) | -| NDC a property with several values (`upc`) in `$lookup` | in the release's row order | by value (`order.literals` default): the NDC file stores every literal with group 0, so it has no row order to give | | NDC `category = X` and `code-type = 11-digit` in one include | no codes, total 0: expand.js walks the first filter, whose packages are written in their 10-digit form, and cs-ndc.js's `code-type` check reads the written code (`check`, cs-ndc.js:541; the walk writes `row.Code`, :619) | the 11-digit forms of the category's packages ("Alternate codes") | | NDC an include of the whole system with `count` > 0 | no codes, total 0: cs-ndc.js has no iterator (`iterator` of cs-api.js returns null), so expand.js walks nothing; `count=0` is counted (`countAllCodes`) | the codes in stored order, no total; `count=0` the same count | -| OMOP a `domain` filter (and the implicit domain value sets) | in the concept table's row order | by concept id (`order.expansion` default): the OMOP file has no `order.expansion` `stored` and no `ix_order` `rank`, so it has no row order to give | | ICD-11 text search (`filter=`) | on a database without the `designation_text` index (the classic file compared): the concepts with a name containing the whole text (`LIKE`), in classification order (cs-icd11.js:1023-1035) | the `text-match/1` word rules, by score (`cholera`: the same 22 concepts in another order; `essential hypertension`: also 1210166201, whose index term `essential hypertensive cardiovascular disease` has both words by stem) | | CPT `$validate-code` of an expression against a `modified = true` include | not in the value set (validate.js asks `filterLocate`, which never finds an expression) | in it ("Grammar": cs-cpt.js `filterCheck`) | | CPT modifier `95` | valid on a base code with the property `telemedicine` = `true` | never valid: the CPT 2023 file has no `telemedicine` property, so upstream's rule finds none | From 70454ab934af72ef14e913976e04746eba19c47b Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 00:49:32 -0600 Subject: [PATCH 67/90] sqlite-v2 README: ICD-11 text search equals the provider's on an indexed database Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index bedee8aef..4529f84cc 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -782,7 +782,7 @@ the fhir-reading revision, is refused at start-up with a message to re-import it | NDC `code-type = 11-digit` | packages in import order (NDCKey) | the 11-digit forms in their concepts' stored order, then value (not compared on the same data) | | NDC `category = X` and `code-type = 11-digit` in one include | no codes, total 0: expand.js walks the first filter, whose packages are written in their 10-digit form, and cs-ndc.js's `code-type` check reads the written code (`check`, cs-ndc.js:541; the walk writes `row.Code`, :619) | the 11-digit forms of the category's packages ("Alternate codes") | | NDC an include of the whole system with `count` > 0 | no codes, total 0: cs-ndc.js has no iterator (`iterator` of cs-api.js returns null), so expand.js walks nothing; `count=0` is counted (`countAllCodes`) | the codes in stored order, no total; `count=0` the same count | -| ICD-11 text search (`filter=`) | on a database without the `designation_text` index (the classic file compared): the concepts with a name containing the whole text (`LIKE`), in classification order (cs-icd11.js:1023-1035) | the `text-match/1` word rules, by score (`cholera`: the same 22 concepts in another order; `essential hypertension`: also 1210166201, whose index term `essential hypertensive cardiovascular disease` has both words by stem) | +| ICD-11 text search (`filter=`) | only on a database without the `designation_text` index: the concepts with a name containing the whole text (`LIKE`), in classification order (cs-icd11.js:1023-1035). With the index built (`import-icd11.js --text-index-only`) the answers are the same as here | the `text-match/1` word rules, by score | | CPT `$validate-code` of an expression against a `modified = true` include | not in the value set (validate.js asks `filterLocate`, which never finds an expression) | in it ("Grammar": cs-cpt.js `filterCheck`) | | CPT modifier `95` | valid on a base code with the property `telemedicine` = `true` | never valid: the CPT 2023 file has no `telemedicine` property, so upstream's rule finds none | | CPT a code with two values of one property (`kind`) | in the release's row order | by value (`order.literals` default) | From 2fc45312c328bd7ac7697c5ac50891dc60037b1c Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 02:09:40 -0600 Subject: [PATCH 68/90] sqlite-v2 engine: an include of the whole system walks the stored walk with wholeSystemIncludeActiveOnly too compile.js makes an include of the whole system an `and` of all and active (a node marked whole) when the file says compatibility.wholeSystemIncludeActiveOnly; the engine took the stored walk only for a node of type `all`, so such an include was listed in rank order (SNOMED CT: by code number, 101009 first) instead of from the roots (138875005 first), and its count=0 total was the active concepts, not every concept. The engine now walks any node marked whole (all, the listed concepts, or the active ones), as upstream's provider answers. A fixture test pages a whole-system expansion with and without the key. Co-Authored-By: Claude --- tests/tx/sqlite-v2-stored-orders.test.js | 62 +++++++++++++++++++++++- tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/engine/engine.js | 6 ++- 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/tests/tx/sqlite-v2-stored-orders.test.js b/tests/tx/sqlite-v2-stored-orders.test.js index 96b324389..dd193cf83 100644 --- a/tests/tx/sqlite-v2-stored-orders.test.js +++ b/tests/tx/sqlite-v2-stored-orders.test.js @@ -3,8 +3,10 @@ // 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. A file without those words keeps the defaults. The -// fixtures have the shapes of the NDC and OMOP importers' files, nothing in them real. +// 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'); @@ -18,6 +20,8 @@ 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 = []; @@ -79,12 +83,47 @@ function buildVocabulary(file) { 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; @@ -142,3 +181,22 @@ test('order.expansion stored: a where_literal filter lists its selection in ix_o 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/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 4529f84cc..f96ec7d14 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -617,7 +617,7 @@ refuses a file with a member it does not implement, and refuses an unknown membe |---|---|---|---|---| | `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 | +| `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 | diff --git a/tx/sqlite-v2/engine/engine.js b/tx/sqlite-v2/engine/engine.js index 2a8e17485..32f50cbb8 100644 --- a/tx/sqlite-v2/engine/engine.js +++ b/tx/sqlite-v2/engine/engine.js @@ -181,8 +181,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) From 7cf5ddd9dc877c23f628521781ce8fced04d9adf Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 02:18:14 -0600 Subject: [PATCH 69/90] sqlite-v2 README: known differences for whole-system count=0 of LOINC and UNII LOINC: main counts the Answer row with code '' that databases built before the importer skipped blank AnswerStringId rows still have. UNII: main adds totalCount's -1 (not known) to the total and so reports none, where the walk of the same include reports 0. Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index f96ec7d14..c542ddf4e 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -782,6 +782,8 @@ the fhir-reading revision, is refused at start-up with a message to re-import it | NDC `code-type = 11-digit` | packages in import order (NDCKey) | the 11-digit forms in their concepts' stored order, then value (not compared on the same data) | | NDC `category = X` and `code-type = 11-digit` in one include | no codes, total 0: expand.js walks the first filter, whose packages are written in their 10-digit form, and cs-ndc.js's `code-type` check reads the written code (`check`, cs-ndc.js:541; the walk writes `row.Code`, :619) | the 11-digit forms of the category's packages ("Alternate codes") | | NDC an include of the whole system with `count` > 0 | no codes, total 0: cs-ndc.js has no iterator (`iterator` of cs-api.js returns null), so expand.js walks nothing; `count=0` is counted (`countAllCodes`) | the codes in stored order, no total; `count=0` the same count | +| LOINC an include of the whole system with `count=0` | one more than the concepts (2.83: 257,267; 2.82: 252,208): `countAllCodes` is `codes.size` (cs-loinc.js:295), and `codes` holds every `Codes` row (cs-loinc.js:1949-1962), including an Answer row with code `''` and no display that databases built before import-loinc.module.js:1194-1199 have (the one row the 65 externally defined answer lists' blank `AnswerStringId` rows made). Upstream on the same database with that row deleted: 257,266 | 257,266 / 252,207 (the importer skips a row with no `AnswerStringId`, as import-loinc.module.js now does) | +| UNII an include of the whole system with `count=0` | no total: `countAllCodes` (cs-api.js:256) returns `totalCount()`, which is -1, "not known" (cs-unii.js:44-46), and expand.js adds it to the total as a count (expand.js:1423-1426, `addToTotal`), leaving -1, which is reported as no total (expand.js:2582). The same request without `count` walks the include and reports total 0 | total 0, as the expansion it counts (`wholeSystemIncludeEmpty`: no codes) | | ICD-11 text search (`filter=`) | only on a database without the `designation_text` index: the concepts with a name containing the whole text (`LIKE`), in classification order (cs-icd11.js:1023-1035). With the index built (`import-icd11.js --text-index-only`) the answers are the same as here | the `text-match/1` word rules, by score | | CPT `$validate-code` of an expression against a `modified = true` include | not in the value set (validate.js asks `filterLocate`, which never finds an expression) | in it ("Grammar": cs-cpt.js `filterCheck`) | | CPT modifier `95` | valid on a base code with the property `telemedicine` = `true` | never valid: the CPT 2023 file has no `telemedicine` property, so upstream's rule finds none | From 8b205eaa6ebf2060a9f045b1359a2f3109c83e10 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 03:13:25 -0600 Subject: [PATCH 70/90] sqlite-v2: code links from the file (meta codeLink) Upstream's v2 codeLink gave LOINC and RxNorm links by branching on the system URI, which the reader does not do. The link is now a file fact: meta codeLink, a URL with {code} (the code URI-encoded); absent, no link. The LOINC importers write https://loinc.org/{code}/, the RxNorm importer the RxNav search; the snomed grammar keeps its own links (snomed.js). Tests: code-links.test.js reads the templates the importers write; the format test checks the key (template, none, malformed); the LOINC test checks the importer's value and the link against cs-loinc.js. Co-Authored-By: Claude --- tests/cs/code-links.test.js | 15 +++++++++++---- tests/tx/sqlite-v2-format.test.js | 7 +++++++ tests/tx/sqlite-v2-loinc.test.js | 8 ++++++++ tx/importers/import-loinc-v2.module.js | 4 +++- tx/importers/import-rxnorm-v2.module.js | 4 +++- tx/sqlite-v2/README.md | 17 ++++++++++++++--- tx/sqlite-v2/meta.js | 2 ++ tx/sqlite-v2/provider.js | 10 +++++++--- tx/sqlite-v2/store.js | 1 + 9 files changed, 56 insertions(+), 12 deletions(-) diff --git a/tests/cs/code-links.test.js b/tests/cs/code-links.test.js index b7909e334..06c50a10f 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/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index 8f3ea5b24..ddfb3575d 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -158,6 +158,13 @@ describe('identification and the meta rule', () => { 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('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', () => { diff --git a/tests/tx/sqlite-v2-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js index 6fcba8049..c19059167 100644 --- a/tests/tx/sqlite-v2-loinc.test.js +++ b/tests/tx/sqlite-v2-loinc.test.js @@ -222,6 +222,7 @@ describe('LOINC v2 importer over the test fixture', () => { 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 }); @@ -347,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}`); diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 76db12998..8e74cc353 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -233,6 +233,8 @@ const LOINC_READING = { // 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' }, @@ -660,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, loincCatalogId, loincItemRank }; + 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 2d9df9c86..49dbaca40 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -71,6 +71,8 @@ const RXNORM_READING = { 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: [ @@ -370,4 +372,4 @@ class RxNormV2Module extends BaseTerminologyModule { } } -module.exports = { RxNormV2Module, importRxNormV2, rxnormCatalogId }; +module.exports = { RxNormV2Module, importRxNormV2, rxnormCatalogId, RXNORM_READING }; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 28e7d97db..0632e3e91 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -22,7 +22,7 @@ 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` | 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 | @@ -38,7 +38,7 @@ The FHIR reading maps these FHIR notions: | `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 | one meta key each | | +| 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 @@ -276,6 +276,7 @@ Every value below is JSON. An absent key has the default. | `implicitMaps` | `{}` | Implicit maps | | `grammar` | absent: plain codes | Grammar | | `compatibility` | `{}` | Compatibility | +| `codeLink` | absent: no link | Code links | Release facts and facts about indexes: @@ -607,6 +608,15 @@ So `http://loinc.org/vs/LL6136-7` is the list's answers, enumerated in sequence; `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 @@ -615,7 +625,7 @@ 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` | implemented (`snomed.js`) | +| `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, `$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`) | @@ -664,6 +674,7 @@ What each importer writes (the reader knows none of it): | `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) | none | | `item_use` | synonym, fsn roles | display roles, `language_display_rank`, `RELATEDNAMES2` as property | the term types | none | diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 849cc1d45..0da74e477 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -182,6 +182,8 @@ const KEYS = Object.freeze({ // 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), diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 943232365..9c613ccae 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1954,11 +1954,15 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { languages() { return this._langs; } /** - * The link a page gives a code: none here (a reader has no branch on a system's URI); the - * `snomed` grammar gives SNOMED CT's (snomed.js) + * 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) { - return undefined; + const template = this.store.codeLink; + if (!template || !context || !context.code) { + return undefined; + } + return template.split('{code}').join(encodeURIComponent(context.code)); } async build(opContext, supplements) { diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index ab2a0b60c..42449246b 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -341,6 +341,7 @@ class Store { 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) From d3ca088ebd1a2a652edfc72e8d0298f57a3429e2 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 03:14:59 -0600 Subject: [PATCH 71/90] sqlite-v2: hierarchyMeaning from code_system.hierarchy_meaning Upstream's providers gained hierarchyMeaning() ($subsumes refuses a hierarchy that is not is-a, triage B16). The file already holds the value; the provider reports it, null where the file does not say. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format.test.js | 6 ++++++ tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/provider.js | 2 ++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index ddfb3575d..fd89bd4f9 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -161,6 +161,12 @@ describe('identification and the meta rule', () => { 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(); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 0632e3e91..65c2983a6 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -111,7 +111,7 @@ 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_sensitive`, `hierarchy_meaning`, `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) | +| `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 | diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 9c613ccae..b36949940 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -142,6 +142,8 @@ class SqliteV2Provider extends BaseCSServices { */ 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(); } /** From 4a524b603c6ffed6cd89d7dadfd604589f35a04e Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 05:18:32 -0600 Subject: [PATCH 72/90] sqlite-v2 SNOMED CT: expressions in $validate-code; <<< X answers as X $validate-code of any SNOMED CT expression the reader keeps as an expression (a refined expression, or a single concept written <<< X) answered 500 "Invalid context": validate.js asks the provider for reportedClassificationCode, which snomed.js did not answer for an expression context, so the generic reader's _ensure got the NativeExprContext. classificationCode and reportedClassificationCode are now answered natively (none, as cs-snomed.js). A single concept written <<< X is the concept X for everything but its code (<< --- tests/tx/sqlite-v2-sct-parity-http.test.js | 36 ++++++++++++++++++++++ tx/sqlite-v2/snomed.js | 27 +++++++++++++--- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/tests/tx/sqlite-v2-sct-parity-http.test.js b/tests/tx/sqlite-v2-sct-parity-http.test.js index 1dfcb6456..003bf459e 100644 --- a/tests/tx/sqlite-v2-sct-parity-http.test.js +++ b/tests/tx/sqlite-v2-sct-parity-http.test.js @@ -240,3 +240,39 @@ describe('SNOMED CT row order of ancestor and is-a filters, as main', () => { 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/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index ad0de1b0d..3f95310cb 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -885,16 +885,35 @@ class SnomedV2Factory extends SqliteV2Factory { } -// 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); From 704cbcad0e970cf982db37972561f728958632c3 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 11:26:16 -0600 Subject: [PATCH 73/90] SNOMED CT classic import: append references without recopying the buffer SnomedReferences.post() rebuilt the master buffer with Buffer.concat on every call, and the closure build calls it once per concept, so the copy grew with the edition (quadratic in the size of the reference lists). post() now appends into a buffer with spare capacity, grown by doubling; doneBuild() releases the spare buffer. Only the RF2 -> classic .cache import (import-sct.module.js) builds references; readers of a cache, and snomed-v2-from-cache, read them with no builder. The test edition's cache is byte-identical before and after. Co-Authored-By: Claude --- tx/sct/structures.js | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tx/sct/structures.js b/tx/sct/structures.js index 7b2924834..6d84f677e 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 } From 239170afeb468c725576d650297fc96e5f745375 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 12:55:09 -0600 Subject: [PATCH 74/90] sqlite-v2 README: known differences from main, re-checked Every row was re-run against main's providers on files of the same release. Rows whose answers are now the same are removed (ECL description ids; the AU refset / code 0 / term attached / RxNorm PSN cases; generalizes order; NDC 11-digit order; LOINC count=0; ICD-11 text search; CPT modifier 95; CPT kind order; OMOP $lookup). The rest state the request and both answers; the description-refset and ICD-11 expression rows are corrected to what each side answers. Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 65c2983a6..b935f81b8 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -793,25 +793,21 @@ 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 | 422 FILTER_NOT_UNDERSTOOD (no filter row takes `AUI:`) | -| 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 | -| 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 | -| 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 | -| NDC `code-type = 11-digit` | packages in import order (NDCKey) | the 11-digit forms in their concepts' stored order, then value (not compared on the same data) | -| NDC `category = X` and `code-type = 11-digit` in one include | no codes, total 0: expand.js walks the first filter, whose packages are written in their 10-digit form, and cs-ndc.js's `code-type` check reads the written code (`check`, cs-ndc.js:541; the walk writes `row.Code`, :619) | the 11-digit forms of the category's packages ("Alternate codes") | -| NDC an include of the whole system with `count` > 0 | no codes, total 0: cs-ndc.js has no iterator (`iterator` of cs-api.js returns null), so expand.js walks nothing; `count=0` is counted (`countAllCodes`) | the codes in stored order, no total; `count=0` the same count | -| LOINC an include of the whole system with `count=0` | one more than the concepts (2.83: 257,267; 2.82: 252,208): `countAllCodes` is `codes.size` (cs-loinc.js:295), and `codes` holds every `Codes` row (cs-loinc.js:1949-1962), including an Answer row with code `''` and no display that databases built before import-loinc.module.js:1194-1199 have (the one row the 65 externally defined answer lists' blank `AnswerStringId` rows made). Upstream on the same database with that row deleted: 257,266 | 257,266 / 252,207 (the importer skips a row with no `AnswerStringId`, as import-loinc.module.js now does) | -| UNII an include of the whole system with `count=0` | no total: `countAllCodes` (cs-api.js:256) returns `totalCount()`, which is -1, "not known" (cs-unii.js:44-46), and expand.js adds it to the total as a count (expand.js:1423-1426, `addToTotal`), leaving -1, which is reported as no total (expand.js:2582). The same request without `count` walks the include and reports total 0 | total 0, as the expansion it counts (`wholeSystemIncludeEmpty`: no codes) | -| ICD-11 text search (`filter=`) | only on a database without the `designation_text` index: the concepts with a name containing the whole text (`LIKE`), in classification order (cs-icd11.js:1023-1035). With the index built (`import-icd11.js --text-index-only`) the answers are the same as here | the `text-match/1` word rules, by score | -| CPT `$validate-code` of an expression against a `modified = true` include | not in the value set (validate.js asks `filterLocate`, which never finds an expression) | in it ("Grammar": cs-cpt.js `filterCheck`) | -| CPT modifier `95` | valid on a base code with the property `telemedicine` = `true` | never valid: the CPT 2023 file has no `telemedicine` property, so upstream's rule finds none | -| CPT a code with two values of one property (`kind`) | in the release's row order | by value (`order.literals` default) | -| ICD-11 an expression's display | each part's title in the request's language | each part's display (`concept.display`, English: ICD-11's files have no `language_display_rank` use) | -| OMOP `$lookup` | `synonym` properties (from its ConceptSynonyms); two links to one target in row order | no `synonym` (the 20240716 file has none); by `order.links` | +| 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 | one code: 1000601000003105 itself. ECL `^ 1000601000003105` is refused by both with the same 400 | +| 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`, `has_ingredient = AUI:828` (or `RO = AUI:828`), on a file built with `--atom-relationships` | two codes, 105050 and 105446 | 422 FILTER_NOT_UNDERSTOOD. On a file built without the option both answer 422 | +| NDC `$expand`, `category = IND` and `code-type = 11-digit` in one include, `count=10` | no codes, total 0 | 70304000101 and 70304000201, total 2 | +| NDC `$expand` of the whole system, `count=5` | no codes, total 0 (`count=0`: total 1,049,697) | five codes in stored order, no total (`count=0`: total 1,049,697) | +| UNII `$expand` of the whole system, `count=0` | no total | total 0. Without `count`, or with `count=10`, both answer total 0 and no codes | +| CPT `$validate-code` of `99213:25` against an include with `modified = true` | `result` false, not in the value set | `result` true | +| ICD-11 MMS `$lookup` of the expression `1A00&XN8P1` with `displayLanguage=es` | the English display; its designation has language `en`; a warning that there is no display in `es` | the same English display; its designation has language `es`; no warning | From 61a8b4c629a2340d16bed3d5b31395610b1b1b98 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 13:00:09 -0600 Subject: [PATCH 75/90] sqlite-v2 icd11: label an expression's display with the language of its text An ICD-11 expression's designation was labelled with the first requested language the file has names in, whatever language its parts' displays were in: a $lookup of 1A00&XN8P1 with displayLanguage=es answered the English display labelled es, and so without the warning that there is no display in es. The generic reader now says which language a concept's display is in (_displayOf: the supplement's, the language-ranked item's, or the display designation's), and the expression is labelled with its parts' language where they share one, else the display designation's. The answer is now upstream main's, warning included. Co-Authored-By: Claude --- tests/tx/sqlite-v2-icd11-grammar.test.js | 15 ++++++++ tx/sqlite-v2/README.md | 3 +- tx/sqlite-v2/icd11.js | 49 ++++++++++++++---------- tx/sqlite-v2/provider.js | 20 +++++++--- 4 files changed, 59 insertions(+), 28 deletions(-) diff --git a/tests/tx/sqlite-v2-icd11-grammar.test.js b/tests/tx/sqlite-v2-icd11-grammar.test.js index 3cb23016b..4f08ca567 100644 --- a/tests/tx/sqlite-v2-icd11-grammar.test.js +++ b/tests/tx/sqlite-v2-icd11-grammar.test.js @@ -42,6 +42,9 @@ function build(file) { 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'] }); @@ -164,6 +167,18 @@ test('$lookup of an expression: code, classificationCode, stem, the valued axes; 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); diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index b935f81b8..4790aa194 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -626,7 +626,7 @@ 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, `$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`) | +| `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 @@ -810,4 +810,3 @@ rows are on the test edition (31000003106, 20250909). | NDC `$expand` of the whole system, `count=5` | no codes, total 0 (`count=0`: total 1,049,697) | five codes in stored order, no total (`count=0`: total 1,049,697) | | UNII `$expand` of the whole system, `count=0` | no total | total 0. Without `count`, or with `count=10`, both answer total 0 and no codes | | CPT `$validate-code` of `99213:25` against an include with `modified = true` | `result` false, not in the value set | `result` true | -| ICD-11 MMS `$lookup` of the expression `1A00&XN8P1` with `displayLanguage=es` | the English display; its designation has language `en`; a warning that there is no display in `es` | the same English display; its designation has language `es`; no warning | diff --git a/tx/sqlite-v2/icd11.js b/tx/sqlite-v2/icd11.js index 75b0e5615..ec8045aab 100644 --- a/tx/sqlite-v2/icd11.js +++ b/tx/sqlite-v2/icd11.js @@ -148,34 +148,39 @@ class Icd11V2Provider extends SqliteV2Provider { /** the display of a part: the concept's display (in a requested language where the file gives one) */ async _title(part) { - return (await this.display(part.v2)) || null; + 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 */ - async _expressionDisplay(expr) { + /** + * 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 this._title(m.head.concept)) || m.head.text; - for (const t of m.tail) text += ` [${(await this._title(t.concept)) || t.text}]`; + let text = await title(m.head); + for (const t of m.tail) text += ` [${await title(t)}]`; parts.push(text); } - return parts.join(' / '); - } - - /** the language a display is in: the first requested language the file has names in, else the default */ - _requestedDisplayLanguage() { - const langs = this.displayLanguages(); - const have = this.f.languages().map((l) => String(l).toLowerCase().split('-')[0]); - for (const l of (langs && langs.languages) || []) { - const base = String((l && (l.language || l.code)) || '').toLowerCase().split('-')[0]; - if (base && have.includes(base)) return base; - } - return this.defLang(); + 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 ? this._expressionDisplay(c) : super.display(c); + return c instanceof ICD11Expression ? (await this._expressionDisplayOf(c)).text : super.display(c); } async definition(context) { @@ -203,12 +208,14 @@ class Icd11V2Provider extends SqliteV2Provider { return c instanceof ICD11Expression ? null : super.getStatus(c); } - /** an expression has one designation: its display */ + /** 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); - const text = await this._expressionDisplay(c); - if (text) displays.addDesignation(true, 'active', this._requestedDisplayLanguage(), CodeSystem.makeUseForDisplay(), text); + // 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) { diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index b36949940..92d8e53f9 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -605,10 +605,20 @@ 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; - // 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 + if (s) return { term: s, language: null }; const uses = this.store.languageDisplayUses; const displayLangs = this.displayLanguages(); const langs = ((displayLangs && displayLangs.languages) || []).filter((l) => l && l.code !== '*'); @@ -624,13 +634,13 @@ class SqliteV2Provider extends BaseCSServices { 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 d.term; + 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) { From 70500b197566547e319fb4b4d5284886d3e22466 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 13:04:41 -0600 Subject: [PATCH 76/90] sqlite-v2: concept in a reference set of descriptions is refused, as ECL ^ is `concept in R` took R's members only when R's member set was non-empty, and otherwise R itself, as for a concept that is no reference set. A language reference set has no member set (its members are descriptions), so `concept in 1000601000003105` on the test edition answered the refset's own id. The member count was standing in for "is a reference set": now a concept that defines a record relation contributes its members, none when it has no active ones, and a language relation is refused with ECL ^'s reason (400 invalid), from one shared message. Co-Authored-By: Claude --- tests/tx/sqlite-v2-engine.test.js | 20 ++++++++++++-- tests/tx/sqlite-v2-sct-parity-http.test.js | 22 +++++++++++++++ tx/sqlite-v2/README.md | 4 +-- tx/sqlite-v2/engine/compile.js | 31 +++++++++++++--------- tx/sqlite-v2/provider.js | 2 ++ 5 files changed, 63 insertions(+), 16 deletions(-) diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index bd64eba60..7f053445a 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -374,12 +374,19 @@ describe('sqlite-v2 SNOMED concept in / code in', () => { 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')); }); @@ -397,6 +404,15 @@ 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', () => { diff --git a/tests/tx/sqlite-v2-sct-parity-http.test.js b/tests/tx/sqlite-v2-sct-parity-http.test.js index 003bf459e..7ccb710f1 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']; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 4790aa194..1a3db90e0 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -223,7 +223,7 @@ minus the `in` selection; every selection is cut to the listed concepts, see "Co | 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 | | with / without an identifier of the scheme | | | -| `concept` | the concept x (`in`: a concept that defines a record relation contributes its members) | | the code | `is-a`, `descendent-of`, `is-not-a`, `descendent-leaf`, `child-of`, `generalizes` by the hierarchy | +| `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 | | @@ -801,7 +801,7 @@ rows are on the test edition (31000003106, 20250909). | request | main | sqlite-v2 | |---|---|---| | 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 | one code: 1000601000003105 itself. ECL `^ 1000601000003105` is refused by both with the same 400 | +| 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 | diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index acd58eea4..99ddb9dc8 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -33,6 +33,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); } @@ -334,18 +342,19 @@ class Compiler { } /** - * concept in X,Y,...: a concept that defines a record relation with members (catalog relations: a - * reference set) contributes its members, any other concept itself + * 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) { + conceptIn(ids, op = 'in') { const S = this.store; - const rel = ids.filter((id) => S.relations && S.relations.has(id)); - const sets = rel.length ? S.loadSets(KIND.refset, 0, rel, this.stats) : new Map(); 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 (!(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: [] }; @@ -360,7 +369,7 @@ class Compiler { // 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 ids = uniqSorted(vals.map((v) => m.get(v)).filter((x) => x != null)); - const n = this.conceptIn(ids); + const n = this.conceptIn(ids, op); return op === 'in' ? n : { t: 'minus', a: { t: 'all' }, b: n }; } if (op === 'regex') return { t: 'text', field: 'code', re: value }; @@ -613,10 +622,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', '^ *'); diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 92d8e53f9..171e20fc6 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1464,6 +1464,8 @@ class SqliteV2Provider extends BaseCSServices { 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; } From 0c733bc290c63c3e87503767d8e909ad26fd0afa Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 13:27:27 -0600 Subject: [PATCH 77/90] sqlite-v2 rxnorm: REL / RELA = AUI: filters from the atom-level rows A file built with --atom-relationships now answers relationship filters whose values are atom ids, as main's rxnorm-v2 does. The importer writes, for each relationship filter, a second filter row of the same name with value prefix AUI: that reads the name's AUI: rows (the existing union of the (REL, RELA) identifier rows; an identifier row with no statements for a name without atom-level rows). The generic reader gains three general rules, no RxNorm case: - rows of one filter name may share operators when their value prefixes tell them apart; each value is read by the row whose prefix it has (in: the union, not-in: its complement) - an identifier property, or a union of identifier properties, read by = / in: the subjects of the identifiers with the value - a filter row may read an internal property (an internal row is still never a filter's name, reported or declared) Files without atom-level rows are unchanged and still refuse AUI: values. README: filter and property sections, RxNorm per-system content; the known difference and the open point are removed. Co-Authored-By: Claude --- tests/tx/sqlite-v2-builder.test.js | 11 ++++- tests/tx/sqlite-v2-format-cases.test.js | 30 ++++++++++-- tests/tx/sqlite-v2-format.test.js | 64 +++++++++++++++++++++++++ tx/importers/import-rxnorm-v2.module.js | 35 ++++++++++---- tx/importers/readme.md | 6 +-- tx/importers/sqlite-v2/builder.js | 36 +++++++++++--- tx/importers/sqlite-v2/schema.sql | 5 +- tx/sqlite-v2/README.md | 30 ++++++++---- tx/sqlite-v2/engine/compile.js | 34 ++++++++++--- tx/sqlite-v2/provider.js | 16 +++---- tx/sqlite-v2/store.js | 40 +++++++++++----- 11 files changed, 243 insertions(+), 64 deletions(-) diff --git a/tests/tx/sqlite-v2-builder.test.js b/tests/tx/sqlite-v2-builder.test.js index ad9d02bc3..8f67e5027 100644 --- a/tests/tx/sqlite-v2-builder.test.js +++ b/tests/tx/sqlite-v2-builder.test.js @@ -563,7 +563,7 @@ describe('sqlite-v2 the FHIR reading an importer declares', () => { } finally { d.close(); } }); - test('refused: a property spec of an earlier revision, an unknown reading member, a filter that reads an internal row', () => { + 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' }); expect(() => b.property({ code: 'p', shape: 'literal', fhirType: 'string', filterable: false })).toThrow(/filterable belong to an earlier revision/); @@ -574,6 +574,13 @@ describe('sqlite-v2 the FHIR reading an importer declares', () => { 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(/reads the internal property secret/); + 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-format-cases.test.js b/tests/tx/sqlite-v2-format-cases.test.js index 9cc6e93fb..67ebcdafc 100644 --- a/tests/tx/sqlite-v2-format-cases.test.js +++ b/tests/tx/sqlite-v2-format-cases.test.js @@ -201,9 +201,8 @@ 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 over the atom-level rows have no filter rows in the fhir-reading revision (waits on the - // spec: section 14, RxNorm atom-level relationships); a file built with them refuses AUI: values - test.skip.each(AUI)('every source\'s atom rows: as main (cs-rxnorm.js) %j', async (...filters) => { + // 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); expect(await run(rxAtoms, filters)).toEqual(want); @@ -222,6 +221,31 @@ 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 () => { const r = await run(rx, AUI[0]); expect(r.status).toBe(422); diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index fd89bd4f9..299a9733a 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -651,6 +651,70 @@ describe('filter rows', () => { }); }); +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 }); diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index 49dbaca40..47c9b7d72 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -28,8 +28,10 @@ // 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, -// internal); `AUI:` and `AUI:` are unions of the pairs (internal: no -// filter row reads them in this revision). No item is needed for another source's +// 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). @@ -58,14 +60,16 @@ async function* rrf(file) { const EQ_IN = ['=', 'in']; /** - * RxNorm's FHIR reading (tx/sqlite-v2/README.md; as cs-rxnorm.js presents RxNorm): status obsolete + * 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:). + * 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 RXNORM_READING = { +const rxnormReading = (atomRelationships) => ({ meta: { conceptStatus: [{ property: 'status', values: { obsolete: ['inactive'], archived: ['inactive', 'deprecated', 'unlisted'] } }], order: { expansion: ['stored'], searchTies: ['code'], links: ['property', 'code'] }, @@ -78,7 +82,7 @@ const RXNORM_READING = { rows: [ // the qualified (`@`) storage rows: union members only { codeContains: '@', internal: true }, - // the atom-level rows (--atom-relationships): storage only in this revision (no filter reads them) + // 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' }, @@ -90,10 +94,14 @@ const RXNORM_READING = { 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 */ @@ -112,7 +120,7 @@ async function importRxNormV2(cfg) { 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(RXNORM_READING); + b.reading(rxnormReading(!!cfg.atomRelationships)); 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) @@ -302,6 +310,13 @@ 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; }); @@ -362,7 +377,7 @@ class RxNormV2Module extends BaseTerminologyModule { .description('Import an unzipped RxNorm full release (rrf folder) into a terminology file') .requiredOption('-s, --source ', 'the rrf/ folder of the release') .requiredOption('-d, --dest ', 'destination .db') - .option('--atom-relationships', 'also store RXNREL\'s atom-level rows (storage only: no filter reads them in this format revision)'), version) + .option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI: filters (otherwise refused)'), version) .action(importAction(this, async (o) => { const c = await resolveCommonOptions(o, version); const s = await importRxNormV2({ source: o.source, dest: o.dest, version: c.version, @@ -372,4 +387,4 @@ class RxNormV2Module extends BaseTerminologyModule { } } -module.exports = { RxNormV2Module, importRxNormV2, rxnormCatalogId, RXNORM_READING }; +module.exports = { RxNormV2Module, importRxNormV2, rxnormCatalogId, RXNORM_READING, rxnormReading }; diff --git a/tx/importers/readme.md b/tx/importers/readme.md index db7048b9d..1c8ff4648 100644 --- a/tx/importers/readme.md +++ b/tx/importers/readme.md @@ -529,9 +529,9 @@ Importer-specific options: `auto`, which fixes caches built east of UTC); `--force` imports a cache with known defects. `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 (storage only: the - fhir-reading revision has no filter row for `REL` / `RELA` = `AUI:`, so those filters are - refused either way) +- `rxnorm-v2`: `--atom-relationships` also stores RXNREL's atom-level rows, for `REL` / `RELA` = + `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/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index c1f46191d..e0199d4d0 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -184,11 +184,12 @@ class TerminologyBuilder { * 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, codeAnyCase, valuePrefix, linksAsDisplay, + * 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 and reading that row; + * 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 * } @@ -799,7 +800,10 @@ function writeFilters(db, filters, props) { selectorOf(sel); for (const p of props) { if (!selects(sel, p) || (f.except || []).includes(p.code) || p.internal || p.shape === 'record') continue; - rows.push({ code: p.code, operators: f.operators, reads: p.code, codeAnyCase: f.codeAnyCase, valuePrefix: f.valuePrefix, + // 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 }); } } @@ -1029,6 +1033,19 @@ function checkContracts(db) { 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'); @@ -1053,6 +1070,8 @@ function checkContracts(db) { 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}`); @@ -1065,17 +1084,20 @@ function checkContracts(db) { if (x === '{1}' && !(f.code_pattern != null && firstGroup(f.code_pattern) != null)) fail(`${what}: reads {1} without a capture group`); continue; } - const d = byCode.get(x); - if (!d) fail(`${what}: reads ${x}, which is no property`); - if (d.internal) fail(`${what}: reads the internal property ${x}`); + 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 && JSON.parse(g.operators).some((o) => ops.includes(o))) fail(`${what}: shares an operator with filter ${g.id}`); + 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 diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index ee81d9f3e..387866690 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -101,7 +101,7 @@ CREATE TABLE property ( -- the catalog: one row per source propert -- 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, filtered or declared + 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 @@ -121,7 +121,8 @@ CREATE TABLE filter ( -- CodeSystem.filter, complete: a filter t 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 + 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 diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 1a3db90e0..62cddeb1f 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -160,7 +160,7 @@ rows that exist only to report something (shapes `item-use`, `mapping`, `reading | `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`); never reported, filtered or declared | +| `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 | @@ -200,10 +200,10 @@ The three shapes without rows of their own: | `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`). `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 | +| `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:`) | +| `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) | @@ -211,7 +211,9 @@ The three shapes without rows of their own: 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. +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"): @@ -222,7 +224,7 @@ minus the `in` selection; every selection is cut to the listed concepts, see "Co | 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 | | with / without an identifier of the scheme | | | +| 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` | | @@ -676,10 +678,20 @@ What each importer writes (the reader knows none of it): | `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) | none | +| `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. @@ -707,7 +719,6 @@ The revision leaves these open; the JS reader's answer at each: | point | this reader | |---|---| -| RxNorm `AUI:` filter values (files built with `--atom-relationships`) | no filter rows are designed for them: not understood (no installed file has them) | | 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 | @@ -728,9 +739,9 @@ them on request. | 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; `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 | +| `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; `reads` names catalog properties (none internal) 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 | +| `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 | @@ -805,7 +816,6 @@ rows are on the test edition (31000003106, 20250909). | 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`, `has_ingredient = AUI:828` (or `RO = AUI:828`), on a file built with `--atom-relationships` | two codes, 105050 and 105446 | 422 FILTER_NOT_UNDERSTOOD. On a file built without the option both answer 422 | | NDC `$expand`, `category = IND` and `code-type = 11-digit` in one include, `count=10` | no codes, total 0 | 70304000101 and 70304000201, total 2 | | NDC `$expand` of the whole system, `count=5` | no codes, total 0 (`count=0`: total 1,049,697) | five codes in stored order, no total (`count=0`: total 1,049,697) | | UNII `$expand` of the whole system, `count=0` | no total | total 0. Without `count`, or with `count=10`, both answer total 0 and no codes | diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 99ddb9dc8..96b9ef204 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -194,14 +194,31 @@ class Compiler { * FILTER_NOT_UNDERSTOOD. */ filter(prop, op, value) { - const hit = this.store.filterRow(prop, op); - if (!hit) { + 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 notUnderstood(this.grammar.filterName ? this.grammar.filterName(this, prop) : prop, op, value); + throw nu(); } - return this.rowFilter(hit.row, hit.capture, prop, op, value); + 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 (!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") */ @@ -312,8 +329,13 @@ class Compiler { propertyRead(row, d, op, v, prop) { const S = this.store; const nu = () => notUnderstood(prop, op, v); - if (d.shape === 'identifier') { - if (op !== 'exists') throw nu(); + 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 }; } diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 171e20fc6..c006ebbb9 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1323,19 +1323,19 @@ class SqliteV2Provider extends BaseCSServices { /** * The alias schemes whose alias_literals name a property a filter reads: [{scheme, template, row}] - * (the filter row that understands prop and op) + * (a filter row that understands prop and op) */ _aliasReads(prop, op) { const S = this.store; if (!S.aliasSchemes.length) return []; - const hit = S.filterRow(prop, op); - if (!hit) return []; const out = []; - 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 }); + 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; diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 42449246b..aa310bba4 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -444,10 +444,10 @@ class Store { if (x === '{1}' && !(pattern && /\((?!\?)/.test(r.code_pattern))) throw bad(r, 'reads {1} without a capture group'); continue; } - const d = this.catalog.get(x); - if (!d) throw bad(r, `reads ${x}, which is no property of the catalog`); - if (d.internal) throw bad(r, `reads ${x}, an internal property`); + // (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}`); @@ -467,33 +467,40 @@ class Store { 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 + // 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 && a.operators.some((o) => b.operators.includes(o))) throw bad(b, `shares an operator with filter ${a.id} of the same code`); + 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 row that understands a filter's name and operator (README.md "filter"), with the - * capture of a code_pattern row: {row, capture}, or null + * 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 */ - filterRow(name, op) { + 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 null; + 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 (f.code === n || (f.anyCase && f.code.toLowerCase() === n.toLowerCase())) return { row: f, capture: 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 }; + if (m) return [{ row: f, capture: m[1] ?? null }]; } } - return null; + return []; } /** @@ -677,6 +684,13 @@ 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 statement-valued properties by code (ECL attributes and supplement-layer filters read @@ -684,7 +698,7 @@ class Store { // 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 (!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; From 352a0821f5d6700594ae5ed9644be359aa5397d1 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 13:37:19 -0600 Subject: [PATCH 78/90] sqlite-v2 README: known difference, RxNorm = values with white space around them Main's RxNorm provider trims every = value before it removes CUI: / AUI:; this reader takes the value as written (a leading space before the prefix is not understood, TTY / STY values are matched as written). Found while comparing the AUI: filters; it applies to CUI:, TTY and STY values alike, and no file fact says a system's values are trimmed. Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 62cddeb1f..e5fbaaac6 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -816,6 +816,7 @@ rows are on the test edition (31000003106, 20250909). | 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 | | NDC `$expand`, `category = IND` and `code-type = 11-digit` in one include, `count=10` | no codes, total 0 | 70304000101 and 70304000201, total 2 | | NDC `$expand` of the whole system, `count=5` | no codes, total 0 (`count=0`: total 1,049,697) | five codes in stored order, no total (`count=0`: total 1,049,697) | | UNII `$expand` of the whole system, `count=0` | no total | total 0. Without `count`, or with `count=10`, both answer total 0 and no codes | From 0ababfb63324ec07c22b532a8cc656bf41f744fb Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 19:55:11 -0600 Subject: [PATCH 79/90] sqlite-v2: fix 6 parity bugs in SNOMED SCG/ECL/refsets, captured exists, and implicit ValueSets - SNOMED concrete-domain SCG $lookup (snomed.js): emit typed concrete refinement values (valueInteger/valueDecimal/valueString) via concreteValueOf + MRCM range instead of calling getDisplayName on NO_REFERENCE (0xFFFFFFFF), avoiding HTTP 500. - Captured filter unknown property with exists false (engine/compile.js): return { t: 'all' } instead of { t: 'empty' } when a captured property (e.g. mapped:447562003) is absent from the catalog and op is exists false. - Implicit ValueSet templates (provider.js): omit compose.include[0].version unless set by the template so caller system-version default overrides apply (matching cs-loinc.js). - ECL {{ D moduleId / effectiveTime }} (engine/compile.js, sct-main-ecl.js): reject with 400 UNSUPPORTED_ECL instead of falling back to sct-main-ecl.js with hardcoded module: 0 / date: 0 and returning empty 200. - SNOMED ?fhir_vs=refset (store.js, snomed.js): include populated language reference sets (role='language' in record) and the module dependency refset (900000000000534007 when meta moduleDependencies is non-empty). - ECL {{ + HISTORY-* }} ordering (engine/compile.js, engine/engine.js): preserve base focus-first ordering before added inactive history concepts. --- tests/tx/sqlite-v2-format.test.js | 33 ++++++++++++++-- tests/tx/sqlite-v2-sct-ecl.test.js | 23 ++++++++++++ tests/tx/sqlite-v2-sct-lookup.test.js | 28 ++++++++++++++ tests/tx/sqlite-v2-sct-postcoord.test.js | 48 ++++++++++++++++++++++-- tx/sqlite-v2/README.md | 2 +- tx/sqlite-v2/engine/compile.js | 10 +++-- tx/sqlite-v2/engine/engine.js | 6 +++ tx/sqlite-v2/provider.js | 4 +- tx/sqlite-v2/sct-main-ecl.js | 16 ++++++++ tx/sqlite-v2/snomed.js | 37 ++++++++++++++++-- tx/sqlite-v2/store.js | 11 ++++++ 11 files changed, 201 insertions(+), 17 deletions(-) diff --git a/tests/tx/sqlite-v2-format.test.js b/tests/tx/sqlite-v2-format.test.js index 299a9733a..9ff152186 100644 --- a/tests/tx/sqlite-v2-format.test.js +++ b/tests/tx/sqlite-v2-format.test.js @@ -778,14 +778,41 @@ describe('versions, implicit value sets and maps, expansion limits, lookup name' filters: [{ code: 'concept', operators: ALL_OPS, reads: 'concept' }, { code: 'list', operators: ['='], reads: 'concept', thenLink: 'member' }], } }); const { f: fac } = await provider(f); - expect(await fac.buildKnownValueSet('http://example.org/vs')).toMatchObject({ name: 'All', compose: { include: [{ system: 'http://example.org/cs', version: '1' }] } }); - expect((await fac.buildKnownValueSet('http://example.org/vs/root')).compose.include[0].concept).toEqual([{ code: 'B' }, { code: 'A' }]); - expect(await fac.buildKnownValueSet('http://example.org/vs/A')).toMatchObject({ name: 'BelowA', description: 'below display A', + 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' }); diff --git a/tests/tx/sqlite-v2-sct-ecl.test.js b/tests/tx/sqlite-v2-sct-ecl.test.js index 432203fff..42237924f 100644 --- a/tests/tx/sqlite-v2-sct-ecl.test.js +++ b/tests/tx/sqlite-v2-sct-ecl.test.js @@ -99,6 +99,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', () => { diff --git a/tests/tx/sqlite-v2-sct-lookup.test.js b/tests/tx/sqlite-v2-sct-lookup.test.js index 5788fe00d..05329e000 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 diff --git a/tests/tx/sqlite-v2-sct-postcoord.test.js b/tests/tx/sqlite-v2-sct-postcoord.test.js index 8a6eb5aa1..1255b67d9 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/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index e5fbaaac6..148907de6 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -581,7 +581,7 @@ A list of templates, tried in order; the first whose `url` and `v` match answers | `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 and version the file's), `{v}` substituted in every string | +| `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) | diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 96b9ef204..24884a809 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -295,7 +295,9 @@ class Compiler { 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 { t: 'empty' }; + 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) { @@ -747,7 +749,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 file holds 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) @@ -781,7 +785,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) { diff --git a/tx/sqlite-v2/engine/engine.js b/tx/sqlite-v2/engine/engine.js index 8ec97332c..89be712b9 100644 --- a/tx/sqlite-v2/engine/engine.js +++ b/tx/sqlite-v2/engine/engine.js @@ -302,6 +302,12 @@ 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') { diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index c006ebbb9..6af9cc1f8 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -2037,9 +2037,9 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { 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(), version: this.version(), concept: ids.map((id) => ({ code: rows.get(id).code })) }; + include = { system: this.system(), concept: ids.map((id) => ({ code: rows.get(id).code })) }; } else { - include = { system: this.system(), version: this.version(), ...substitute(t.include, vars) }; + include = { system: this.system(), ...substitute(t.include, vars) }; } vs.compose = { include: [include] }; return vs; diff --git a/tx/sqlite-v2/sct-main-ecl.js b/tx/sqlite-v2/sct-main-ecl.js index 0a37243e4..3bef53b29 100644 --- a/tx/sqlite-v2/sct-main-ecl.js +++ b/tx/sqlite-v2/sct-main-ecl.js @@ -511,10 +511,26 @@ function noTextIndexes() { return NO_TEXT_INDEXES || (NO_TEXT_INDEXES = new SnomedTextIndexes([], new Map()).serialize()); } +/** 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 file holds no description ${field === 'moduleid' ? 'modules' : 'effective times'}`); + } + } + } + for (const v of Object.values(node)) assertSupportedByFile(v); +} + async function evaluateEcl(store, text, opContext) { const { ECLLexer, ECLParser } = require('../sct/ecl'); const sv = servicesFor({ store }); const ast = new ECLParser(new ECLLexer(text).tokenize()).parse(); + 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)); diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 3f95310cb..5733fba4d 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -369,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); @@ -736,7 +759,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/')) { diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index aa310bba4..486144a4c 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -883,6 +883,17 @@ 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, opts = {}) { From f94979506fd72258dd99519bccf5101dcd5a64b2 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 20:15:48 -0600 Subject: [PATCH 80/90] sqlite-v2: align unsupported ECL description filter error wording --- tx/sqlite-v2/engine/compile.js | 2 +- tx/sqlite-v2/sct-main-ecl.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 24884a809..532613ee5 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -750,7 +750,7 @@ 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 if (field === 'moduleid' || field === 'effectivetime') { - throw new FilterError(`Unsupported ECL description filter ${f.field}: the edition file holds no description ${field === 'moduleid' ? 'modules' : 'effective times'}`); + 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; }); diff --git a/tx/sqlite-v2/sct-main-ecl.js b/tx/sqlite-v2/sct-main-ecl.js index 3bef53b29..d3da9d19f 100644 --- a/tx/sqlite-v2/sct-main-ecl.js +++ b/tx/sqlite-v2/sct-main-ecl.js @@ -519,7 +519,7 @@ function assertSupportedByFile(node) { 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 file holds no description ${field === 'moduleid' ? 'modules' : 'effective times'}`); + throw new Error(`Unsupported ECL description filter ${f.field}: the edition files hold no description ${field === 'moduleid' ? 'modules' : 'effective times'}`); } } } From 90bcb2679a729f81e11e9d1ebd77b3d1e2b07749 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 21:04:53 -0600 Subject: [PATCH 81/90] sqlite-v2: fix 5 ordering/dedup parity bugs (answers-for in, concept in, supplement filter order, ECL parents, link dedup) - LOINC answers-for in (engine/compile.js): restrict list-sequence ordering to op === '=' so answers-for in uses stored rank order (matching cs-loinc.js). - SNOMED concept in (engine/compile.js, engine/engine.js): preserve written order on plain-concept in under isAListsFocusFirst (matching cs-snomed.js). - Supplement-only filter order (layers.js, engine/compile.js): record conceptOrder in fillLayer and preserve supplement declaration order on supplement-only includes (matching expand.js #supplementFilterConcepts). - SNOMED ECL >>! and >! parents (engine/engine.js): handle 'parents' in orderedBy() and _eclOrdered() so focus comes first followed by direct parents in release order (fixing offset pagination on >>!). - Multi-group lookup link dedup (provider.js): sort candidate links by order.links (seq) before deduplicating by (property, target) so the earliest link wins (matching cs-snomed.js). --- tx/sqlite-v2/engine/compile.js | 15 ++++++++++++--- tx/sqlite-v2/engine/engine.js | 20 ++++++++++++++++---- tx/sqlite-v2/layers.js | 14 +++++++++----- tx/sqlite-v2/provider.js | 21 +++++++++++++-------- 4 files changed, 50 insertions(+), 20 deletions(-) diff --git a/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 532613ee5..7b5033555 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -160,8 +160,15 @@ 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((n) => n.op !== 'not-in' + && !(n.op === 'exists' && String(n.value).toLowerCase() === 'false') + && n.layer && n.layer.conceptOrder); + if (driver) 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 }; } @@ -274,7 +281,7 @@ class Compiler { // 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 || !(row.reads.length === 1 && row.reads[0] === 'concept')); + 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; @@ -392,8 +399,10 @@ class Compiler { const unknown = vals.filter((v) => m.get(v) == null); // 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 ids = uniqSorted(vals.map((v) => m.get(v)).filter((x) => x != null)); + 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 }; diff --git a/tx/sqlite-v2/engine/engine.js b/tx/sqlite-v2/engine/engine.js index 89be712b9..079298abd 100644 --- a/tx/sqlite-v2/engine/engine.js +++ b/tx/sqlite-v2/engine/engine.js @@ -67,10 +67,10 @@ class Result { * cs-snomed.js walks the first filter's list) */ function orderedBy(node) { - if (node.t === 'self' || node.t === 'anc') return 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 : null; + return first && (first.t === 'self' || first.t === 'anc' || first.t === 'parents') ? first : null; } class Engine { @@ -161,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) }); @@ -329,6 +330,17 @@ class Engine { 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/layers.js b/tx/sqlite-v2/layers.js index f8be8a16c..01eafd3f5 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; } } @@ -75,6 +76,8 @@ function fillLayer(db, base, json) { 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; @@ -149,7 +153,7 @@ function fillLayer(db, base, json) { }); tx(); db.pragma('user_version = 1'); - return { concepts, unknown, props }; + return { concepts, unknown, props, conceptOrder }; } /** @@ -161,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) */ @@ -285,7 +289,7 @@ class LayerSet { if (!def) continue; const { Compiler } = require('./engine/compile'); const node = new Compiler({ store: l.store, grammar: {} }, { stats: compiler.stats }).propertyFilter(def, op, value); - return { t: 'layer', layer: l, node, label: `supplement ${l.info.url} ${prop} ${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/provider.js b/tx/sqlite-v2/provider.js index 6af9cc1f8..c42e4cae0 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -983,18 +983,23 @@ class SqliteV2Provider extends BaseCSServices { 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 seen = new Set(); - const addLink = (d, l) => { + const linkEntries = []; + const pushLink = (d, l) => { const t = targets.get(l.other); if (!t) return; - // a property lists a target once + linkEntries.push({ d, t, rank: rankOf(d), key: this._linkKey(d, l, t.code) }); + }; + 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)) return; + if (seen.has(k)) continue; seen.add(k); - add(d, 0, this._linkKey(d, l, t.code), t.code, (params) => this._addReported(params, d, t.code, t.display)); - }; - for (const l of links) for (const d of byPid.get(l.p) || []) addLink(d, l); - for (const { d, l } of inverse) addLink(d, l); + 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) { From 7b68f96c3a61fe772bbe6dcc29c8416eec466ef6 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 21:22:47 -0600 Subject: [PATCH 82/90] sqlite-v2: support .details (e.g. ICD-11 source.details) in - tx/sqlite-v2/provider.js (_reportsDef): recognize .details requests for mapping properties (such as ICD-11 'source'). - tx/workers/lookup.js (doLookup): when .details is requested and the emitted Coding property carries no embedded subproperty/designation parts, enrich it with the target concept's definition, parent subproperties, and designations (matching classic cs-icd11.js #sourcePart). --- tx/sqlite-v2/provider.js | 7 +++++- tx/workers/lookup.js | 52 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index c42e4cae0..8dee55302 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -185,7 +185,12 @@ class SqliteV2Provider extends BaseCSServices { } if (d.lookup === 'never') return false; if (!props || props.length === 0) return d.lookup === 'default'; - return props.some((p) => p === '*' || this._names(d).includes(String(p).toLowerCase())); + 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 */ diff --git a/tx/workers/lookup.js b/tx/workers/lookup.js index f6d4baf9b..014fc7a56 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 From 0304a0c1d7d3d79634a1348da1a55b24cb8f5d04 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 21:52:56 -0600 Subject: [PATCH 83/90] Fix 5 sqlite-v2 SNOMED ECL & post-coordination bugs - evaluate.js: call _group directly from _mat instead of filterG to avoid infinite recursion (RangeError: Maximum call stack size exceeded) when a role-group cardinality base exceeds PROBE_MAX; chunk linksFrom in _group - sct-main-ecl.js + snomed.js: map V2View concept indices via the file's stored numeric-SCTID rank order and preserve sv._eclToIndexArray order on eclFallback so focus-first (<< X : ...) and descendant order match cs-snomed.js - sct-native.js: include concrete-value refinements (#num / "str") in exprRels() so exprSatisfies() evaluates concrete ECL constraints on SCGs - snomed.js: override doesFilter() to accept constraint = so invalid ECL in $validate-code reports 400 INVALID_ECL (matching cs-snomed.js) - snomed.js: guard decodeURIComponent and reject empty ?fhir_vs=ecl/ implicit ValueSet URLs (matching cs-snomed.js, avoiding URIError 500s) --- tests/tx/sqlite-v2-sct-lookup.test.js | 61 ++++++++++++++++++++++++++- tx/sqlite-v2/engine/evaluate.js | 43 +++++++++++-------- tx/sqlite-v2/sct-main-ecl.js | 38 +++++++++++++---- tx/sqlite-v2/sct-native.js | 8 +++- tx/sqlite-v2/snomed.js | 19 ++++++++- 5 files changed, 137 insertions(+), 32 deletions(-) diff --git a/tests/tx/sqlite-v2-sct-lookup.test.js b/tests/tx/sqlite-v2-sct-lookup.test.js index 05329e000..2bcf84216 100644 --- a/tests/tx/sqlite-v2-sct-lookup.test.js +++ b/tests/tx/sqlite-v2-sct-lookup.test.js @@ -139,9 +139,66 @@ 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); }); }); diff --git a/tx/sqlite-v2/engine/evaluate.js b/tx/sqlite-v2/engine/evaluate.js index c37fa3462..86f1574c9 100644 --- a/tx/sqlite-v2/engine/evaluate.js +++ b/tx/sqlite-v2/engine/evaluate.js @@ -276,7 +276,7 @@ class Evaluator { 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.lang || null)) || new RoaringBitmap32(); - case 'group': return yield* this.filterG(node, yield* this.matG({ t: 'and', items: node.attrs.map(attrNode) })); + 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); @@ -600,32 +600,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/sct-main-ecl.js b/tx/sqlite-v2/sct-main-ecl.js index d3da9d19f..ae1afd9fc 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); @@ -201,7 +208,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 +249,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) { @@ -435,7 +445,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)); @@ -526,14 +541,19 @@ function assertSupportedByFile(node) { for (const v of Object.values(node)) assertSupportedByFile(v); } -async function evaluateEcl(store, text, opContext) { +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 ------------------------------------ @@ -560,7 +580,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 aeced27d6..c1b7dca7b 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; diff --git a/tx/sqlite-v2/snomed.js b/tx/sqlite-v2/snomed.js index 5733fba4d..6ac22292c 100644 --- a/tx/sqlite-v2/snomed.js +++ b/tx/sqlite-v2/snomed.js @@ -558,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)) { @@ -626,7 +633,9 @@ const SNOMED_RULES = Object.freeze({ if ((err && err.eclInvalid) || /is not known/.test(msg)) throw new FilterError(msg, { eclUnknown: true }); throw new Unsupported('ecl-feature', msg); } - return { t: 'ids', ids: kept.bm.toArray(), label: 'ECL (main) ' + text.slice(0, 60) }; + const node = { t: 'ids', ids: kept.bm.toArray(), label: 'ECL (main) ' + text.slice(0, 60) }; + if (kept.order) node.order = kept.order; + return node; }, }); @@ -783,7 +792,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; From 5372ffb66ce3db20a1b990b0b89916f92d53e812 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sat, 5 Dec 2026 22:06:13 -0600 Subject: [PATCH 84/90] Fix sqlite-v2 _roots() whole-system walk order for explicit-closure systems (LOINC) When expand.js walks a multi-include ValueSet via iterator(null) (e.g. v3-DocumentSectionType importing v3-QualityMeasureSectionType + whole LOINC), _roots() returned raw concept-id order (LP100001-9 first) instead of the stored walk order (100000-9 first, matching classic cs-loinc.js). Use engine._order.walk and Array.from() in nextContext() so Uint32Array slices map cleanly to V2Concept instances. --- tests/tx/sqlite-v2-loinc.test.js | 14 ++++++++++++++ tx/sqlite-v2/provider.js | 8 ++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tests/tx/sqlite-v2-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js index c19059167..615035662 100644 --- a/tests/tx/sqlite-v2-loinc.test.js +++ b/tests/tx/sqlite-v2-loinc.test.js @@ -880,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/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 8dee55302..d49b4bb41 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -824,7 +824,11 @@ class SqliteV2Provider extends BaseCSServices { _roots() { const S = this.store; if (S.expansionLimits.wholeSystem === 'refuse') throw this._wholeSystemRefusal(); - if (S.hierarchy && S.closure != null) return S.all().toArray(); + 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(); + } if (!S.hierarchy) { const b = S.listed(this._stats()) || S.all(); return this.engine._order ? this.engine._ordered(b) : b.toArray(); @@ -845,7 +849,7 @@ class SqliteV2Provider extends BaseCSServices { 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; } From db5854b140c743b4374c6f059c25aa9d88578cba Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 07:27:52 -0600 Subject: [PATCH 85/90] sqlite-v2: refuse non-enumerable supplement-only filters on $expand (422 FILTER_NOT_UNDERSTOOD) --- tests/tx/sqlite-v2-engine.test.js | 11 ++++++++ tests/tx/sqlite-v2-mixed-providers.test.js | 30 ++++++++++++++++++++ tx/sqlite-v2/engine/compile.js | 33 +++++++++++++++------- tx/sqlite-v2/provider.js | 11 +++++++- 4 files changed, 74 insertions(+), 11 deletions(-) diff --git a/tests/tx/sqlite-v2-engine.test.js b/tests/tx/sqlite-v2-engine.test.js index 7f053445a..0713bf594 100644 --- a/tests/tx/sqlite-v2-engine.test.js +++ b/tests/tx/sqlite-v2-engine.test.js @@ -279,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'); diff --git a/tests/tx/sqlite-v2-mixed-providers.test.js b/tests/tx/sqlite-v2-mixed-providers.test.js index c13e076bb..b30a5f43b 100644 --- a/tests/tx/sqlite-v2-mixed-providers.test.js +++ b/tests/tx/sqlite-v2-mixed-providers.test.js @@ -257,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/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 7b5033555..05ef4097a 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -25,6 +25,11 @@ 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 = {}) { super(message); @@ -105,13 +110,13 @@ 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 @@ -120,7 +125,7 @@ class Compiler { if (!other || other.system !== this.store.system) throw new Unsupported('other-version', inc.version); 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) { @@ -128,7 +133,7 @@ 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 }] }; @@ -162,10 +167,18 @@ class Compiler { const node = items.length === 1 ? items[0] : { t: 'and', items }; let order = null; if (items.every((n) => n.t === 'layer')) { - const driver = items.find((n) => n.op !== 'not-in' - && !(n.op === 'exists' && String(n.value).toLowerCase() === 'false') - && n.layer && n.layer.conceptOrder); - if (driver) order = driver.layer.conceptOrder; + 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 }); @@ -1080,4 +1093,4 @@ function collectIds(n, out) { } } -module.exports = { Compiler, FilterError, Unsupported, notUnderstood, splitList, uniqSorted, litSets, pidsOf }; +module.exports = { Compiler, FilterError, Unsupported, notUnderstood, isEnumerableLayer, splitList, uniqSorted, litSets, pidsOf }; diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index d49b4bb41..836b0cf02 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -17,7 +17,7 @@ const { BaseCSServices } = require('../cs/cs-base'); const { Language } = require('../../library/i18n/languages'); const { openStore, KIND } = require('./store'); const { Engine } = require('./engine/engine'); -const { Compiler, FilterError, pidsOf } = require('./engine/compile'); +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'); @@ -1547,6 +1547,11 @@ class SqliteV2Provider extends BaseCSServices { async _executeFilters(prep) { if (!prep.nodes.length) return []; + 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 }); @@ -1702,6 +1707,10 @@ class SqliteV2Provider extends BaseCSServices { 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; } From 7cbc8e5769cb9e7b1cf145198fcd48bbde35d28c Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 09:09:43 -0600 Subject: [PATCH 86/90] sqlite-v2: handle DottedExpressionConstraint in SCG ECL membership --- tests/tx/sqlite-v2-sct-lookup.test.js | 36 +++++++++++++++++++++++++++ tx/sqlite-v2/sct-native.js | 34 ++++++++++++++++++++++++- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/tests/tx/sqlite-v2-sct-lookup.test.js b/tests/tx/sqlite-v2-sct-lookup.test.js index 2bcf84216..ce0770707 100644 --- a/tests/tx/sqlite-v2-sct-lookup.test.js +++ b/tests/tx/sqlite-v2-sct-lookup.test.js @@ -200,6 +200,42 @@ describe('sqlite-v2 SNOMED CT $lookup and implicit value sets, as main', () => { 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); + }); }); describe('sqlite-v2 SNOMED CT designation rank', () => { diff --git a/tx/sqlite-v2/sct-native.js b/tx/sqlite-v2/sct-native.js index c1b7dca7b..b45b499a6 100644 --- a/tx/sqlite-v2/sct-native.js +++ b/tx/sqlite-v2/sct-native.js @@ -346,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: { @@ -360,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); From ba4f5d146635c764433729af335ef88b1fbb8a19 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 09:43:14 -0600 Subject: [PATCH 87/90] sqlite-v2: ignore item-subject refset rows in ECL HISTORY supplements --- tests/tx/sqlite-v2-sct-ecl.test.js | 61 ++++++++++++++++++++++++++++++ tx/sqlite-v2/engine/evaluate.js | 20 ++++++---- tx/sqlite-v2/sct-main-ecl.js | 5 ++- tx/sqlite-v2/store.js | 7 +++- 4 files changed, 82 insertions(+), 11 deletions(-) diff --git a/tests/tx/sqlite-v2-sct-ecl.test.js b/tests/tx/sqlite-v2-sct-ecl.test.js index 42237924f..6ae9409aa 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'); @@ -158,3 +162,60 @@ describe('SNOMED CT ECL the engine hands to main\'s ECL (sct-main-ecl.js)', () = 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([]); + } finally { + s.close(); + } + }); +}); diff --git a/tx/sqlite-v2/engine/evaluate.js b/tx/sqlite-v2/engine/evaluate.js index 86f1574c9..c2e74614b 100644 --- a/tx/sqlite-v2/engine/evaluate.js +++ b/tx/sqlite-v2/engine/evaluate.js @@ -561,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); } diff --git a/tx/sqlite-v2/sct-main-ecl.js b/tx/sqlite-v2/sct-main-ecl.js index ae1afd9fc..6745e6144 100644 --- a/tx/sqlite-v2/sct-main-ecl.js +++ b/tx/sqlite-v2/sct-main-ecl.js @@ -355,8 +355,9 @@ function refSetIndexAndMembers(v) { }; 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, { 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: '[]' })) : []; } diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 486144a4c..d00eb0c77 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -1296,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); From e42b3cea54ca50c9320651150465e4dac2c5eab1 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 10:07:32 -0600 Subject: [PATCH 88/90] sqlite-v2: implement missing refSetMembers and refs methods in ECL fallback adapter --- tests/tx/sqlite-v2-sct-ecl.test.js | 22 +++++++++ tx/sqlite-v2/sct-main-ecl.js | 74 ++++++++++++++++++++++++++---- 2 files changed, 86 insertions(+), 10 deletions(-) diff --git a/tests/tx/sqlite-v2-sct-ecl.test.js b/tests/tx/sqlite-v2-sct-ecl.test.js index 6ae9409aa..67158c486 100644 --- a/tests/tx/sqlite-v2-sct-ecl.test.js +++ b/tests/tx/sqlite-v2-sct-ecl.test.js @@ -156,6 +156,28 @@ 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); diff --git a/tx/sqlite-v2/sct-main-ecl.js b/tx/sqlite-v2/sct-main-ecl.js index 6745e6144..b5e01f11a 100644 --- a/tx/sqlite-v2/sct-main-ecl.js +++ b/tx/sqlite-v2/sct-main-ecl.js @@ -195,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; + } }; } @@ -353,24 +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 const rel = S.relations.get(rid); - let rows = S.refsetMemberRows(rid, null, { conceptsOnly: true }); + 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 }); } @@ -385,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 }; } From fec10d4a76cd25fd8cf064bbc25e69d0787ff6b0 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 10:19:14 -0600 Subject: [PATCH 89/90] sqlite-v2: reject unknown attribute ConceptReference in ECL eclAttrIds --- tests/tx/sqlite-v2-sct-ecl.test.js | 1 + tx/sqlite-v2/engine/compile.js | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/tx/sqlite-v2-sct-ecl.test.js b/tests/tx/sqlite-v2-sct-ecl.test.js index 67158c486..c688e5c8d 100644 --- a/tests/tx/sqlite-v2-sct-ecl.test.js +++ b/tests/tx/sqlite-v2-sct-ecl.test.js @@ -236,6 +236,7 @@ describe('{{ + HISTORY-* }} ignores description-level association refsets (item 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/tx/sqlite-v2/engine/compile.js b/tx/sqlite-v2/engine/compile.js index 05ef4097a..bfa5e35c5 100644 --- a/tx/sqlite-v2/engine/compile.js +++ b/tx/sqlite-v2/engine/compile.js @@ -995,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, From 7c27a3f3ac2d09e02eabe7f6d65c45960e3f29e5 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Sun, 6 Dec 2026 12:39:40 -0600 Subject: [PATCH 90/90] sqlite-v2: harden NDC, UNII, and CPT support (closed-filter CPT #486, v2 source types, syndication, tests) --- library/server/config-check.js | 3 +- tests/library/server/config-check.test.js | 5 + tests/tx/library-sqlite-v2.test.js | 9 ++ tests/tx/sqlite-v2-alias-literals.test.js | 62 ++++++++- tests/tx/sqlite-v2-cpt-grammar.test.js | 27 ++++ tests/tx/sqlite-v2-unii.test.js | 149 ++++++++++++++++++++++ tests/tx/syndication-store.test.js | 43 ++++++- tx/README.md | 13 +- tx/library.js | 12 +- tx/sqlite-v2/README.md | 8 +- tx/sqlite-v2/cpt.js | 4 +- tx/sqlite-v2/index.js | 6 +- tx/sqlite-v2/provider.js | 1 + tx/syndication/syndication-store.js | 16 ++- 14 files changed, 330 insertions(+), 28 deletions(-) create mode 100644 tests/tx/sqlite-v2-unii.test.js diff --git a/library/server/config-check.js b/library/server/config-check.js index 35e543820..b860de381 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/library/server/config-check.test.js b/tests/library/server/config-check.test.js index 7c71ce9dc..46d0e72bc 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 b7718e295..323e9ec37 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 index 2b54eb4fb..6fd05c957 100644 --- a/tests/tx/sqlite-v2-alias-literals.test.js +++ b/tests/tx/sqlite-v2-alias-literals.test.js @@ -86,12 +86,18 @@ async function post(op, parameter) { return request(app).post(`/tx/r5/${op}`).send({ resourceType: 'Parameters', parameter }); } -async function expand(include) { - const res = await post('ValueSet/$expand', [{ name: 'valueSet', resource: vs(include) }]); +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); @@ -151,3 +157,55 @@ 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-cpt-grammar.test.js b/tests/tx/sqlite-v2-cpt-grammar.test.js index dcdd0097e..9075466a0 100644 --- a/tests/tx/sqlite-v2-cpt-grammar.test.js +++ b/tests/tx/sqlite-v2-cpt-grammar.test.js @@ -143,6 +143,33 @@ test('modified = true: no concept, an open expansion; an expression is a member 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-unii.test.js b/tests/tx/sqlite-v2-unii.test.js new file mode 100644 index 000000000..a239c23cd --- /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/syndication-store.test.js b/tests/tx/syndication-store.test.js index f1af9a885..87be59d51 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 504cf6826..b9c13a52d 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,12 @@ 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). -#### `sqlite-v2`, `snomed-v2`, `loinc-v2`, `rxnorm-v2` - code systems 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 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:` and `rxnorm-v2:` also check that the file holds that system, and -`snomed-v2:` and `loinc-v2:` serve it instead of the `snomed` or `loinc` file of the same release. +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 @@ -664,7 +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 -- sqlite-v2:ndc-20261117.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/library.js b/tx/library.js index c8ca6ba1a..74767c3c7 100644 --- a/tx/library.js +++ b/tx/library.js @@ -84,7 +84,10 @@ 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 { @@ -514,6 +517,9 @@ class Library { 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; @@ -1119,8 +1125,8 @@ class Library { /** * 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:`, which also check - * the system the file holds; with `!` as for the other types). + * 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. */ diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 148907de6..85aa391af 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -698,8 +698,8 @@ 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 CT, LOINC and RxNorm files from `snomed-v2:`, -`loinc-v2:`, `rxnorm-v2:` lines, which also check the system). The file's grammar chooses the +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. @@ -817,7 +817,3 @@ rows are on the test edition (31000003106, 20250909). | 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 | -| NDC `$expand`, `category = IND` and `code-type = 11-digit` in one include, `count=10` | no codes, total 0 | 70304000101 and 70304000201, total 2 | -| NDC `$expand` of the whole system, `count=5` | no codes, total 0 (`count=0`: total 1,049,697) | five codes in stored order, no total (`count=0`: total 1,049,697) | -| UNII `$expand` of the whole system, `count=0` | no total | total 0. Without `count`, or with `count=10`, both answer total 0 and no codes | -| CPT `$validate-code` of `99213:25` against an include with `modified = true` | `result` false, not in the value set | `result` true | diff --git a/tx/sqlite-v2/cpt.js b/tx/sqlite-v2/cpt.js index 494973cc1..c313c621a 100644 --- a/tx/sqlite-v2/cpt.js +++ b/tx/sqlite-v2/cpt.js @@ -144,9 +144,11 @@ class CptV2Provider extends SqliteV2Provider { 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 this._expressionMember(set) ? r.context : null; + return r.context; } async filterCheck(prep, set, concept) { diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js index 0bf41c334..0057742e2 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -1,9 +1,9 @@ 'use strict'; // sqlite-v2 terminology files: provider registration entry point. // -// A library source line `sqlite-v2:` (any code system), `snomed-v2:`, `loinc-v2:` -// or `rxnorm-v2:` loads one file (Library.loadSqliteV2). Without such a line nothing here, nor -// roaring, is loaded. +// 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'); diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 836b0cf02..39b35c62e 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -1770,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)) }; diff --git a/tx/syndication/syndication-store.js b/tx/syndication/syndication-store.js index f017a9641..aa1ebd065 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 } }); });