From e555282d84b60519afeefe2a06460e4d2236d8b2 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 13:39:40 -0600 Subject: [PATCH 1/5] text-match: name the stemmer of each language stemmerName(lang) gives the stemmer the text rules use for a language as 'natural:' (the natural package's stemmer classes, from the same table stemmerFor reads), or 'none' for a language without one, so a stored word index can record which stemmer made its stems. Co-Authored-By: Claude --- tx/library/text-match.js | 51 +++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 19 deletions(-) diff --git a/tx/library/text-match.js b/tx/library/text-match.js index 08a043a6..a8321313 100644 --- a/tx/library/text-match.js +++ b/tx/library/text-match.js @@ -46,25 +46,26 @@ const MAX_WORDS = 10; const WORD_RE = /[\p{L}\p{M}\p{N}]+/gu; const ACCENTED = /([\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}])\p{M}+/gu; -// The stemmers, by primary language subtag: the best that the natural package has. A language -// that isn't here isn't stemmed -const STEMMERS = { - en: natural.PorterStemmer, - de: natural.PorterStemmerDe, - es: natural.PorterStemmerEs, - fa: natural.PorterStemmerFa, - fr: natural.PorterStemmerFr, - id: natural.StemmerId, - it: natural.PorterStemmerIt, - nb: natural.PorterStemmerNo, - nl: natural.PorterStemmerNl, - nn: natural.PorterStemmerNo, - no: natural.PorterStemmerNo, - pt: natural.PorterStemmerPt, - ru: natural.PorterStemmerRu, - sv: natural.PorterStemmerSv, - uk: natural.PorterStemmerUk +// The stemmers, by primary language subtag: the best that the natural package has, by class name. A +// language that isn't here isn't stemmed +const STEMMER_CLASSES = { + en: 'PorterStemmer', + de: 'PorterStemmerDe', + es: 'PorterStemmerEs', + fa: 'PorterStemmerFa', + fr: 'PorterStemmerFr', + id: 'StemmerId', + it: 'PorterStemmerIt', + nb: 'PorterStemmerNo', + nl: 'PorterStemmerNl', + nn: 'PorterStemmerNo', + no: 'PorterStemmerNo', + pt: 'PorterStemmerPt', + ru: 'PorterStemmerRu', + sv: 'PorterStemmerSv', + uk: 'PorterStemmerUk' }; +const STEMMERS = Object.fromEntries(Object.entries(STEMMER_CLASSES).map(([lang, cls]) => [lang, natural[cls]])); const NO_STEMMER = { stem: (word) => word }; @@ -97,6 +98,18 @@ function hasStemmer(lang) { return Object.prototype.hasOwnProperty.call(STEMMERS, languageOf(lang)); } +/** + * The name of the stemmer for a language, as a terminology file's word index records it (meta + * ix.ix_word.stemmers): 'natural:' for a stemmer of the natural package, 'none' for a + * language without one (a word is its own stem) + * @param {string|Object|null} lang - a tag or a Language + * @returns {string} + */ +function stemmerName(lang) { + const l = languageOf(lang); + return Object.prototype.hasOwnProperty.call(STEMMER_CLASSES, l) ? 'natural:' + STEMMER_CLASSES[l] : 'none'; +} + /** * A text in lower case without accents (see the module comment) * @param {string} text @@ -574,6 +587,6 @@ function lowerBound(sorted, value) { module.exports = { STOP_WORDS, MAX_TEXT, MAX_WORDS, TEXT_INDEX_TOKENIZE, - languageOf, stemmerFor, hasStemmer, fold, words, stem, + languageOf, stemmerFor, hasStemmer, stemmerName, fold, words, stem, TextQuery, NameIndex, indexColumns, createTextIndexSql, isTextIndexSql, lowerBound, bestRanks }; From d0e879d3460a9c334ba487599ef48a55a02272a6 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 13:39:40 -0600 Subject: [PATCH 2/5] sqlite-v2: closed meta keys, requires, integrity facts, word-index facts The terminology file states facts about its content; a reader now checks them instead of accepting whatever it finds. - meta is a closed list of keys (tx/sqlite-v2/meta.js): an unknown key, a malformed value, or a required feature the reader does not know refuses the file; provenance.* stays open. `requires` lists the features the content uses; the one feature is identifier-text (identifier values are TEXT and probed as text). A file without requires (built before this) is accepted as before; readFileMeta is the one place that decides what such a file may hold (no integrity facts, INTEGER identifier values, the retired keys). - meta integrity = {items, schema, catalog} (tx/sqlite-v2/integrity.js): SHA-256 of sqlite_master and of the catalog tables rendered with quote(). The builder writes it when it finishes a file (finishFile, from finish() and vacuumFile(); indexes.js after a rebuild); the store checks a file with requires at open: file length, both digests, concept and item id ranges, the all and active set cardinalities. - The word index records its scope (the names it holds) and the stemmer of each language; the store uses it only when both are its own, else builds the index in memory. The counts row is written and read little-endian. - behaviour.* keeps only grammar. The presentation rules the other keys carried (expansion order, lookup name, description, version algorithm, designation uses, distinct designation texts, mixed links) are rules in code by system (dialects.js; the grammar for mixed links), equal to the values every existing file carries. A grammar the reader does not implement (icd11) refuses the file. - The builder checks the format's contracts before it finishes a file (checkContracts) and runs the reader's meta check on what it writes. - Unread columns removed: property.n_rows, property.target_kind, code_system.release_date, hierarchy_meaning, case_sensitive (codes are always matched exactly). ix.ix_key.normalForm.stats becomes provenance.normalFormStats. Co-Authored-By: Claude --- tests/tx/sqlite-v2-builder.test.js | 52 ++---- tests/tx/sqlite-v2-filter-text.test.js | 6 +- tests/tx/sqlite-v2-format-cases.test.js | 4 +- tests/tx/sqlite-v2-loinc.test.js | 6 +- tests/tx/sqlite-v2-rxnorm-filters.test.js | 4 +- tests/tx/sqlite-v2-sct-from-cache.test.js | 2 +- tx/importers/import-loinc-v2.module.js | 8 +- tx/importers/import-rxnorm-v2.module.js | 11 +- tx/importers/import-sct-v2-cache.module.js | 2 +- tx/importers/import-sct-v2.module.js | 2 +- tx/importers/sct-v2-common.js | 18 +- tx/importers/sqlite-v2/builder.js | 183 +++++++++++++++---- tx/importers/sqlite-v2/diff.js | 4 +- tx/importers/sqlite-v2/indexes.js | 33 +++- tx/importers/sqlite-v2/schema.sql | 47 +++-- tx/sqlite-v2/dialects.js | 27 +++ tx/sqlite-v2/index.js | 3 +- tx/sqlite-v2/integrity.js | 104 +++++++++++ tx/sqlite-v2/layers.js | 6 +- tx/sqlite-v2/meta.js | 126 +++++++++++++ tx/sqlite-v2/orders.js | 2 +- tx/sqlite-v2/provider.js | 20 +-- tx/sqlite-v2/store.js | 200 +++++++++++---------- tx/sqlite-v2/text-index.js | 29 ++- 24 files changed, 639 insertions(+), 260 deletions(-) create mode 100644 tx/sqlite-v2/integrity.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 ac1ed66a..7973beca 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', () => { @@ -197,12 +197,14 @@ describe('sqlite-v2 terminology file builder', () => { expect(db.prepare("SELECT rowid FROM ix_text_item WHERE ix_text_item MATCH 'eff'").pluck().all()).toEqual([15]); }); - test('meta: the format, the languages, provenance; PRAGMA user_version 1; a unique code index', () => { + test('meta: the format, requires, integrity, the languages, provenance; PRAGMA user_version 1; a unique code index', () => { const m = Object.fromEntries(db.prepare('SELECT key, value FROM meta').raw().all()); expect(m.format).toBe(FORMAT); expect(FORMAT).toBe('tx-terminology/1'); expect(JSON.parse(m.languages)).toEqual(['en']); expect(m['provenance.importer']).toBe('test'); + expect(JSON.parse(m.requires)).toEqual(['identifier-text']); + expect(Object.keys(JSON.parse(m.integrity))).toEqual(['items', 'schema', 'catalog']); expect(db.pragma('user_version', { simple: true })).toBe(1); expect(db.prepare("SELECT sql FROM sqlite_master WHERE name = 'concept_code'").pluck().get()).toMatch(/^CREATE UNIQUE INDEX/); }); @@ -352,44 +354,16 @@ 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: the grammar only; a builder refuses any other behaviour key (meta check)', () => { const S = openStore(file, { unregistered: true }); try { - expect(S.behaviour).toMatchObject({ grammar: null, expansionOrder: 'ids', lookupName: 'name', distinctDesignationTexts: false }); + expect(S.grammar).toBeNull(); + expect(S.expansionOrder).toBe('ids'); // a generic system without a stored order } finally { S.close(); } - const bad = (key, value, msg) => { - const f = path.join(dir, 'behaviour.db'); - fs.copyFileSync(file, f); - const w = new Database(f); - w.prepare('INSERT INTO meta VALUES (?, ?)').run(key, value); - w.close(); - expect(() => openStore(f)).toThrow(msg); - }; - bad('behaviour.colour', '"red"', /unknown behaviour setting behaviour.colour/); - bad('behaviour.designationUses', '"sometimes"', /behaviour.designationUses = "sometimes" is not a value this server knows/); - bad('behaviour.grammar', 'snomed', /is not JSON/); - bad('behaviour.preferredForLanguage', '"yes"', /behaviour.preferredForLanguage = "yes" is not a value/); - bad('behaviour.aliasLiterals', '{"code-type": 11}', /behaviour.aliasLiterals = .* is not a value/); - bad('behaviour.filters', '[{"code": "kind", "operator": ["like"]}]', /behaviour.filters = .* is not a value/); - bad('behaviour.filters', '[{"code": "kind", "operator": ["="], "values": "product"}]', /behaviour.filters = .* is not a value/); - const good = path.join(dir, 'behaviour-ok.db'); - fs.copyFileSync(file, good); - const w = new Database(good); - w.prepare('INSERT INTO meta VALUES (?, ?)').run('behaviour.preferredForLanguage', 'true'); - w.prepare('INSERT INTO meta VALUES (?, ?)').run('behaviour.aliasLiterals', '{"code-type": "11-digit", "synonym": "{code}"}'); - w.prepare('INSERT INTO meta VALUES (?, ?)').run('behaviour.filters', - '[{"code": "inactive", "operator": ["="], "values": ["true", "false"]}, {"code": "category", "operator": ["=", "in"]}]'); - w.close(); - const G = openStore(good, { unregistered: true }); - try { - expect(G.behaviour.preferredForLanguage).toBe(true); - expect(G.behaviour.aliasLiterals).toEqual({ 'code-type': '11-digit', synonym: '{code}' }); - expect(G.behaviour.filters.map((f) => f.code)).toEqual(['inactive', 'category']); - } finally { G.close(); } const b = new TerminologyBuilder(path.join(dir, 'never.db'), { overwrite: true, importer: 'test' }); b.codeSystem({ uri: 'http://example.org/x', version: '1' }); b.concept('a'); - b.setBehaviour('lookupName', 'nickname'); - expect(() => b.finish()).toThrow(/behaviour.lookupName = "nickname" is not a value/); + b.setBehaviour('lookupName', 'title'); + expect(() => b.finish()).toThrow(/unknown meta key behaviour.lookupName \(a retired key/); }); }); diff --git a/tests/tx/sqlite-v2-filter-text.test.js b/tests/tx/sqlite-v2-filter-text.test.js index 3adad8e7..337ee427 100644 --- a/tests/tx/sqlite-v2-filter-text.test.js +++ b/tests/tx/sqlite-v2-filter-text.test.js @@ -100,8 +100,10 @@ beforeAll(async () => { await importSnomedV2FromCache({ source: cache, dest: path.join(dir, 'sct.db'), overwrite: true, log: () => {} }); fs.copyFileSync(path.join(dir, 'sct.db'), path.join(dir, 'sct-bare.db')); const bare = new Database(path.join(dir, 'sct-bare.db')); - // without its word index (ix_word, and the rules it was made by, meta ix.ix_word.format) - bare.exec("DELETE FROM ix_word; DELETE FROM meta WHERE key = 'ix.ix_word.format'"); + // without its word index (ix_word, and its facts, meta ix.ix_word.*); finished again, as a tool + // that rewrites a finished file does (its integrity facts) + bare.exec("DELETE FROM ix_word; DELETE FROM meta WHERE key LIKE 'ix.ix\\_word.%' ESCAPE '\\'"); + require('../../tx/importers/sqlite-v2/builder').finishFile(bare, path.join(dir, 'sct-bare.db')); bare.close(); stored = await loadSqliteV2Factory(op.i18n, path.join(dir, 'sct.db')); memory = await loadSqliteV2Factory(op.i18n, path.join(dir, 'sct-bare.db')); diff --git a/tests/tx/sqlite-v2-format-cases.test.js b/tests/tx/sqlite-v2-format-cases.test.js index 50f26af5..a3153abe 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-loinc.test.js b/tests/tx/sqlite-v2-loinc.test.js index 55879f3b..fc0ae090 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, p.subject_kind 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, subject_kind: null }); + expect(row('AnswerList')).toEqual({ code: 'AnswerList', inverse_of: 'Answer|answers-for', filterable: 1, ordered: 0, subject_kind: null }); 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 f8a6f48f..b6303f1b 100644 --- a/tests/tx/sqlite-v2-rxnorm-filters.test.js +++ b/tests/tx/sqlite-v2-rxnorm-filters.test.js @@ -215,11 +215,11 @@ 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 code, shape, wildcard, subject_kind FROM property').raw().all().map(([c, ...r]) => [c, r])); for (const rela of ['has_ingredient', 'has_active_ingredient', 'tradename_of']) expect(rows[rela]).toBeDefined(); for (const rel of ['RO', 'RB', 'SY']) expect(rows[rel]).toBeDefined(); // has_active_ingredient: only other sources' atom-level rows have it, so it selects nothing - expect(rows.has_active_ingredient).toEqual(['link', 1, 0]); + expect(rows.has_active_ingredient).toEqual(['link', 1, null]); } finally { db.close(); } }); }); diff --git a/tests/tx/sqlite-v2-sct-from-cache.test.js b/tests/tx/sqlite-v2-sct-from-cache.test.js index 5b5cf328..6053ec43 100644 --- a/tests/tx/sqlite-v2-sct-from-cache.test.js +++ b/tests/tx/sqlite-v2-sct-from-cache.test.js @@ -186,7 +186,7 @@ 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, s1.expansionOrder); expect(stored.loadedBytes()).toBe(0); expect([stored.selfFirst, stored.hasWalk]).toEqual([true, true]); const n = stored.rank.length; diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index 653739bb..4c38d8db 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -174,13 +174,7 @@ function loincCatalog(b) { /** the code system row of a LOINC file */ function loincCodeSystem(b, version, description) { b.codeSystem({ uri: LOINC, version, name: 'LOINC', title: 'Logical Observation Identifier Names and Codes (LOINC)', - description, caseSensitive: true, hierarchyMeaning: 'is-a', defaultLanguage: 'en-US' }); - // as cs-loinc.js presents it: the stored order (main's key order and walk), $lookup's name the - // title, the description the name, versions compared naturally - b.setBehaviour('expansionOrder', 'stored'); - b.setBehaviour('lookupName', 'title'); - b.setBehaviour('description', 'name'); - b.setBehaviour('versionAlgorithm', 'natural'); + description, defaultLanguage: 'en-US' }); } /** @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 88cdcf8b..a1873233 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 @@ -57,15 +57,8 @@ async function importRxNormV2(cfg) { for (const n of ['RXNCONSO.RRF', 'RXNREL.RRF', 'RXNSTY.RRF', 'RXNATOMARCHIVE.RRF']) if (fs.existsSync(f(n))) b.addSource(f(n)); const v = cfg.version; b.codeSystem({ uri: RXNORM, version: v, name: 'RxNorm', title: 'RxNorm', - releaseDate: /^\d{8}$/.test(v) ? `${v.slice(4)}-${v.slice(0, 2)}-${v.slice(2, 4)}` : null, description: 'RxNorm normalized drug nomenclature (U.S. National Library of Medicine)', - caseSensitive: true, defaultLanguage: 'en-US' }); - // as cs-rxnorm.js presents it: by RXCUI as text (the stored order), each atom text once, no - // designation uses, versions by date - b.setBehaviour('expansionOrder', 'stored'); - b.setBehaviour('distinctDesignationTexts', true); - b.setBehaviour('designationUses', 'drop'); - b.setBehaviour('versionAlgorithm', 'date'); + defaultLanguage: 'en-US' }); // cs-rxnorm.js takes = and in only, on TTY, STY, SAB and the relationships const EQ_IN = ['=', 'in']; diff --git a/tx/importers/import-sct-v2-cache.module.js b/tx/importers/import-sct-v2-cache.module.js index 3a536032..bbe6b6ec 100644 --- a/tx/importers/import-sct-v2-cache.module.js +++ b/tx/importers/import-sct-v2-cache.module.js @@ -207,7 +207,7 @@ async function importSnomedV2FromCache(cfg) { const name = (editionName(edition) ? `SNOMED CT ${editionName(edition)}` : `SNOMED CT edition ${edition}`); const sink = new SnomedSink({ dest: cfg.dest, overwrite: cfg.overwrite, log, importer: 'sct-v2-from-cache', edition, - codeSystem: { uri: SCT, version: d.versionUri, name, title: name, releaseDate: isoDate(version), + codeSystem: { uri: SCT, version: d.versionUri, name, title: name, description: `SNOMED CT edition ${edition} version ${version}, from FHIRsmith cache v${d.cacheVersion} (${path.basename(cfg.source)})`, // the cache's default-language slot (cacheDefaultLanguage; en-US for English) defaultLanguage: defByte !== 1 && LANGUAGE[defByte] ? LANGUAGE[defByte] : 'en-US' }, diff --git a/tx/importers/import-sct-v2.module.js b/tx/importers/import-sct-v2.module.js index abf55708..afcabd38 100644 --- a/tx/importers/import-sct-v2.module.js +++ b/tx/importers/import-sct-v2.module.js @@ -26,7 +26,7 @@ async function importSnomedV2(cfg) { const displayRefsets = []; const sink = new SnomedSink({ dest: cfg.dest, overwrite: cfg.overwrite, log, importer: 'sct-v2', edition: cfg.edition, - codeSystem: { uri: SCT, version: versionUri, name, title: name, releaseDate: isoDate(cfg.version), + codeSystem: { uri: SCT, version: versionUri, name, title: name, description: `SNOMED CT RF2 Snapshot, module ${cfg.edition}, version ${cfg.version}`, defaultLanguage: 'en-US' }, displayRefsets, preferredRefset: US_ENGLISH, normalForms: cfg.normalForms, }); diff --git a/tx/importers/sct-v2-common.js b/tx/importers/sct-v2-common.js index 64ce70ca..f7403c90 100644 --- a/tx/importers/sct-v2-common.js +++ b/tx/importers/sct-v2-common.js @@ -32,12 +32,13 @@ // 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' (the codes are SNOMED CT expressions) // meta edition, displayContexts ({relations: the display refsets, ordered, preferred: // the acceptability that ranks, use: synonym}), moduleDependencies, // derived-by-importer: normal forms (ix_key 'normalForm') and the walk (ix_order -// 'walk', reached in meta 'ix.ix_order.walk.reached'), written after the build; -// then the file is vacuumed. +// 'walk', reached in meta 'ix.ix_order.walk.reached'), written after the build +// (normal-form statistics in provenance.normalFormStats); then the file is +// finished and vacuumed. const path = require('path'); const Database = require('better-sqlite3'); @@ -171,13 +172,10 @@ 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 }); + b.codeSystem({ compositional: true, ...cfg.codeSystem }); b.setMeta('edition', cfg.edition); - // how cs-snomed.js presents it: SNOMED CT expressions and ECL; results by concept id, an is-a - // filter's concept first; $lookup reads no link of a concrete-value attribute + // the codes are SNOMED CT expressions (and ECL applies) b.setBehaviour('grammar', 'snomed'); - b.setBehaviour('expansionOrder', 'stored-self-first'); - b.setBehaviour('lookupSkipsMixedLinks', true); b.setMeta('derived-by-importer', DERIVED); this.stats = { languageRows: 0, languageRowsSkipped: 0, descriptions: 0, relationships: 0, relationshipsSkipped: 0, concreteTypeLinks: 0, concreteValues: 0, identifiers: 0, refsetRows: 0, refsetRowsOnDescriptions: 0, @@ -446,12 +444,12 @@ function derivedIndexes(file, log = () => {}, normalForms = true) { t = Date.now(); const { Store } = require('../sqlite-v2/store'); const { buildNormalForms } = require('../sqlite-v2/sct-native'); - const store = new Store(file, { db, unregistered: true }); + const store = new Store(file, { db, unregistered: true, unfinished: true }); db.prepare("DELETE FROM main.ix_key WHERE name = 'normalForm'").run(); const ins = db.prepare("INSERT OR REPLACE INTO main.ix_key VALUES ('normalForm', ?, ?)"); const r = buildNormalForms(store, db, log, { write: (id, nf) => ins.run(nf, id) }); out.normalForms = { ...r, seconds: (Date.now() - t) / 1000 }; - db.prepare("INSERT OR REPLACE INTO main.meta VALUES ('ix.ix_key.normalForm.stats', ?)").run(JSON.stringify(out.normalForms)); + db.prepare("INSERT OR REPLACE INTO main.meta VALUES ('provenance.normalFormStats', ?)").run(JSON.stringify(out.normalForms)); log(`normal forms: ${r.written.toLocaleString()} stored (${r.failed} could not be built), ${out.normalForms.seconds.toFixed(1)} s`); } analyze(db, 'main.ix_key'); analyze(db, 'main.ix_order'); diff --git a/tx/importers/sqlite-v2/builder.js b/tx/importers/sqlite-v2/builder.js index 514f7e22..b9c6b01d 100644 --- a/tx/importers/sqlite-v2/builder.js +++ b/tx/importers/sqlite-v2/builder.js @@ -10,12 +10,14 @@ // 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()) and VACUUM (unless -// the importer still writes derived-by-importer rows: then it calls vacuumFile() after them). +// 5. writes meta (format, requires, provenance), ANALYZE (sqlite_stat1 only: analyze()), then +// finishes the file (finishFile: checks the contracts, writes meta integrity, checks meta as a +// reader does) 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,8 @@ const crypto = require('crypto'); const Database = require('better-sqlite3'); const { numberConcepts } = require('../sqlite-v2/numbering'); const { buildIndexes } = require('./indexes'); +const { computeIntegrity, integrityValue } = require('../../sqlite-v2/integrity'); +const { WRITTEN_FEATURES, readFileMeta } = require('../../sqlite-v2/meta'); const SCHEMA_PATH = path.join(__dirname, 'schema.sql'); const FORMAT = 'tx-terminology/1'; @@ -131,8 +135,8 @@ class TerminologyBuilder { /** * A code system row. The first one is the served system (cs_id 1); later ones are sources that * only contribute items (served = 0). Returns the cs_id. - * { uri, version, name, title, description, releaseDate, content, caseSensitive, hierarchyMeaning, defaultLanguage, - * compositional, resource } + * { uri, version, name, title, description, content, defaultLanguage, compositional, resource } + * (codes are always case-sensitive: matched exactly) */ codeSystem(spec) { if (!spec.uri || spec.version == null) throw new Error('codeSystem: uri and version are required'); @@ -140,7 +144,7 @@ class TerminologyBuilder { return this.systems.length; } - /** a behaviour setting (meta behaviour., a JSON value; tx/sqlite-v2/store.js BEHAVIOUR) */ + /** a behaviour fact (meta behaviour., a JSON value): only grammar (tx/sqlite-v2/meta.js) */ setBehaviour(key, value) { this.meta.set(`behaviour.${key}`, JSON.stringify(value)); } @@ -286,7 +290,8 @@ class TerminologyBuilder { identifier(property, value, subject, { resolves = 0 } = {}) { const r = resolves === true ? 1 : resolves === false ? 0 : resolves; if (r !== 0 && r !== 1 && r !== 2) throw new Error(`identifier ${value}: resolves is 0, 1 or 2`); - this.ins.identifier.run(property, externalIdValue(value), subject, r); + // identifier values are TEXT (meta requires identifier-text) + this.ins.identifier.run(property, value == null ? null : String(value), subject, r); this._count('identifiers'); this._tick(); } @@ -437,13 +442,12 @@ class TerminologyBuilder { run('item map', `INSERT INTO st.s_node SELECT -i.id, ${n} + row_number() OVER (ORDER BY m.new, i.id) FROM st.s_item i JOIN st.s_node m ON m.old = i.concept`); - const insCs = db.prepare(`INSERT INTO code_system (cs_id, uri, version, name, title, description, release_date, content, - case_sensitive, hierarchy_meaning, default_language, compositional, served, concept_count, active_count, resource) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + const insCs = db.prepare(`INSERT INTO code_system (cs_id, uri, version, name, title, description, content, + default_language, compositional, served, concept_count, active_count, resource) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`); const flag = (v) => (v == null ? null : (v ? 1 : 0)); this.systems.forEach((cs, k) => insCs.run(k + 1, cs.uri, String(cs.version), cs.name ?? null, cs.title ?? null, - cs.description ?? null, cs.releaseDate ?? null, cs.content, flag(cs.caseSensitive), - cs.hierarchyMeaning ?? null, cs.defaultLanguage ?? null, flag(cs.compositional), cs.served, cs.served ? n : 0, cs.served ? activeCount : 0, + cs.description ?? null, cs.content, 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); @@ -473,12 +477,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)) { @@ -489,7 +493,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 (?, ?)'); @@ -499,12 +502,13 @@ 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, requires and provenance (release facts were set by the importer), checked as a + // reader checks them (here before the indexes are built; finishFile checks the whole table) + this.meta.set('format', FORMAT); + this.meta.set('requires', JSON.stringify(WRITTEN_FEATURES)); + readFileMeta(this.meta, this.dest, { finished: false }); const insMeta = db.prepare('INSERT OR REPLACE INTO meta VALUES (?, ?)'); for (const [k, v] of [...this.meta].sort()) insMeta.run(k, v); - insMeta.run('format', FORMAT); // the languages of the served system's items, in order of first appearance (a release fact) insMeta.run('languages', JSON.stringify(db.prepare(`SELECT language FROM item WHERE cs_id = 1 AND language IS NOT NULL GROUP BY language ORDER BY min(id)`).pluck().all())); @@ -521,7 +525,10 @@ class TerminologyBuilder { this.timings.total = (Date.now() - this.t0) / 1000; insMeta.run('provenance.timings', JSON.stringify(this.timings)); db.pragma('journal_mode = DELETE'); - if (opts.vacuum !== false) this._time('vacuum', () => { db.exec('VACUUM'); }); + if (opts.vacuum !== false) { + this._time('finish', () => finishFile(db, this.dest)); + this._time('vacuum', () => { db.exec('VACUUM'); }); + } const tables = {}; for (const t of ['concept', 'item', 'property', 'link', 'literal', 'identifier', 'record', 'mapping', 'ix_set', 'ix_in', 'ix_order', 'ix_word']) { @@ -536,25 +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; } @@ -594,10 +600,115 @@ 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: check the contracts + * (checkContracts), write meta integrity (tx/sqlite-v2/integrity.js), and check the whole meta table + * as a reader does (tx/sqlite-v2/meta.js). 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); + db.prepare("INSERT OR REPLACE INTO main.meta VALUES ('integrity', ?)").run(integrityValue(computeIntegrity(db))); + readFileMeta(db.prepare('SELECT key, value FROM main.meta').raw().all(), file); +} + +/** 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'); + if (one("SELECT count(*) FROM main.identifier WHERE typeof(value) <> 'text'")) fail('an identifier value is not TEXT'); + // 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`); + } + // the secondary indexes of the schema; sqlite_stat1 and no sqlite_stat4 + for (const [name, unique] of schemaIndexes()) { + const sql = one("SELECT sql FROM main.sqlite_master WHERE type = 'index' AND name = ?", name); + if (sql == null) fail(`the index ${name} is missing`); + if (unique && !/^CREATE UNIQUE INDEX/.test(sql)) fail(`the index ${name} is not unique`); + } + if (one("SELECT count(*) FROM main.sqlite_master WHERE name = 'sqlite_stat1'") !== 1) fail('no sqlite_stat1'); + if (one("SELECT count(*) FROM main.sqlite_master WHERE name = 'sqlite_stat4'")) fail('sqlite_stat4 is present'); + return true; } -module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, analyze, externalIdValue }; +module.exports = { TerminologyBuilder, FORMAT, USER_VERSION, schemaSections, vacuumFile, finishFile, checkContracts, analyze, externalIdValue }; diff --git a/tx/importers/sqlite-v2/diff.js b/tx/importers/sqlite-v2/diff.js index 398d89a1..e4a0f528 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 a5119598..9565e5c8 100644 --- a/tx/importers/sqlite-v2/indexes.js +++ b/tx/importers/sqlite-v2/indexes.js @@ -19,7 +19,9 @@ // 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) +// tx/sqlite-v2/text-index.js eachSearchName lists), with meta ix.ix_word.format, +// .scope (the dialect whose names it holds) and .stemmers (each language's +// stemmer, tx/library/text-match.js stemmerName); the counts row little-endian // ix_key nothing generic (SNOMED normal forms are derived-by-importer) const Database = require('better-sqlite3'); @@ -66,6 +68,8 @@ function dropIndexes(db) { for (const k of db.prepare("SELECT key FROM meta WHERE key LIKE 'ix.%'").pluck().all()) { if (!keepKeys.some((p) => k.startsWith(p))) db.prepare('DELETE FROM meta WHERE key = ?').run(k); } + // the integrity facts no longer hold: the step that finishes the file writes them again + db.prepare("DELETE FROM meta WHERE key = 'integrity'").run(); } /** @@ -95,7 +99,7 @@ function buildIndexes(db, opts = {}) { 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 { 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)); @@ -103,9 +107,15 @@ function buildIndexes(db, opts = {}) { stats.order = time('ix_order', () => writeOrder(db, computeOrder(db, kind, n, { walk: false }), derived)); } if (indexed(dialect)) { - const store = new Store(db.name, { db, unregistered: true }); - stats.words = time('ix_word', () => writeWords(db, computeTextIndexFrom((fn) => store.eachSearchName(dialect, fn), dialect, n), stem)); - db.prepare("INSERT OR REPLACE INTO main.meta VALUES ('ix.ix_word.format', ?)").run(FORMAT); + // a file mid-build: its integrity facts are written when it is finished + const store = new Store(db.name, { db, unregistered: true, unfinished: true }); + const byLang = computeTextIndexFrom((fn) => store.eachSearchName(dialect, fn), dialect, n); + stats.words = time('ix_word', () => writeWords(db, byLang, stem)); + const setMeta = db.prepare('INSERT OR REPLACE INTO main.meta VALUES (?, ?)'); + setMeta.run('ix.ix_word.format', FORMAT); + // which names it holds (the dialect's), and the stemmer that made each language's stems + setMeta.run('ix.ix_word.scope', dialect); + 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 +300,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 +311,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; } @@ -313,7 +324,9 @@ 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. After +// a rebuild a file with meta requires is finished again (contracts, meta integrity: builder.js +// finishFile); a file without (written before requires existed) is left without integrity facts. if (require.main === module) { const [file, flag] = process.argv.slice(2); const db = new Database(file); @@ -322,7 +335,9 @@ 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); + if (db.prepare("SELECT 1 FROM main.meta WHERE key = 'requires'").get()) finishFile(db, file); console.log(JSON.stringify({ seconds: (Date.now() - t0) / 1000, ...s })); } db.close(); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 1941df72..4387a503 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -12,25 +12,35 @@ -- -- 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 every file keeps (tx/sqlite-v2/README.md "Contracts"; the builder checks those it can +-- before it finishes a file): concept ids are exactly 1..N (N = concept_count), 1..A active +-- (A = active_count), A+1..N inactive; item ids exactly N+1..N+M; at most one property with +-- subsumption = 1 and at most one ordered = 1 link property; codes unique per system and matched +-- exactly (binary); identifier.value TEXT; ix_set key conventions, kind 4 sets without their anchor, +-- bitmaps of concept ids only; 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; the secondary +-- indexes below exist. A finished file states integrity facts in meta `integrity` (README.md), which +-- a reader checks at open. -- @facts CREATE TABLE code_system ( cs_id INTEGER PRIMARY KEY, uri TEXT NOT NULL, version TEXT NOT NULL, - name TEXT, title TEXT, description TEXT, release_date TEXT, - content TEXT NOT NULL, case_sensitive INTEGER, hierarchy_meaning TEXT, default_language TEXT, + name TEXT, title TEXT, description TEXT, + content TEXT NOT NULL, -- codes are always case-sensitive: matched exactly + default_language TEXT, compositional INTEGER, -- FHIR CodeSystem.compositional: codes may be expressions, so no -- expansion of the system is closed (SNOMED CT) served INTEGER NOT NULL, -- 1 for the file's system; 0 for sources that only contribute items concept_count INTEGER NOT NULL, active_count INTEGER NOT NULL, resource TEXT -- FHIR CodeSystem JSON without concepts, when there is one ); --- release facts with no column (displayContexts, moduleDependencies, languages, edition, titles), the format --- and provenance, facts about indexes (ix.*), and behaviour settings: behaviour. = a JSON value, --- how the system is presented (grammar, lookupName, description, versionAlgorithm, expansionOrder, --- designationUses, distinctDesignationTexts, lookupSkipsMixedLinks, aliasProperty, aliasExtension, --- preferredForLanguage, aliasLiterals, filters; --- values and defaults in tx/sqlite-v2/README.md). A reader refuses a file with a key or value it --- does not know. +-- A closed list of keys (tx/sqlite-v2/README.md "Meta keys"): format, requires (the features beyond +-- the base format the content uses), integrity (facts checked at open), release facts with no column +-- (languages, displayContexts, moduleDependencies, edition, titles), derived-by-importer, facts about +-- indexes (ix.ix_word.format / stemmers / scope, ix.ix_order.walk.reached), behaviour.grammar (the +-- grammar of the codes), and provenance.* (open: informational, never read). A reader refuses a file +-- with any other key, a malformed value of a key it reads, or a required feature it does not know. CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID; CREATE TABLE concept ( @@ -60,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 @@ -72,7 +81,9 @@ CREATE TABLE property ( -- the catalog: properties, refsets, relat by_target INTEGER NOT NULL DEFAULT 0, -- its links are read by target (ix_in); set per property by the importer by_subject INTEGER NOT NULL DEFAULT 0, -- shape 'identifier': its rows are read by subject (ix_by_subject); the -- builder's default for an identifier row is 1, an importer sets 0 for - -- rows only ever read by value (RxNorm atom relationships AUI:*) + -- rows only ever read by value (RxNorm atom relationships AUI:*). The + -- index builder reads it at every rebuild: it says which rows + -- ix_by_subject holds 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) @@ -103,7 +114,8 @@ 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 NOT NULL, -- TEXT (meta requires identifier-text; a file without requires 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 @@ -184,10 +196,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 +-- word index (tx/sqlite-v2/text-index.js rules; format in meta 'ix.ix_word.format', the names it +-- holds in 'ix.ix_word.scope', each language's stemmer in 'ix.ix_word.stemmers'): 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 '' 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 scope keeps them (snomed). 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/sqlite-v2/dialects.js b/tx/sqlite-v2/dialects.js index 4a06bfdf..a08c01d5 100644 --- a/tx/sqlite-v2/dialects.js +++ b/tx/sqlite-v2/dialects.js @@ -357,6 +357,33 @@ const snomed = { const generic = { name: 'generic' }; +// ---- how each system is presented ------------------------------------------------------------- +// Each dialect's presentation rules, as the built-in provider of the system presents it (files +// written before meta `requires` also stated them as behaviour.* keys, which a reader now ignores): +// expansionOrder(store) 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) +// description, lookupName the code system's 'name' or 'title' (a provider's description, the name +// $lookup reports) +// versionAlgorithm CodeSystem.versionAlgorithm ('natural', 'date', or null) +// designationUses 'keep': a designation reports its use; 'drop': none does +// distinctDesignationTexts true: a concept's designations are its items' distinct texts +// SNOMED CT's description, lookup name and version algorithm are the SNOMED CT provider's +// (snomed.js); whether a 'both' attribute's links are read where no property is named follows the +// grammar (store.js). +const PRESENTATION = { + snomed: { expansionOrder: () => 'stored-self-first', description: 'title', lookupName: 'name', versionAlgorithm: null, designationUses: 'keep', distinctDesignationTexts: false }, + // cs-loinc.js: the stored order (main's key order and walk), $lookup's name the title, the + // description the name, versions compared naturally + loinc: { expansionOrder: () => 'stored', description: 'name', lookupName: 'title', versionAlgorithm: 'natural', designationUses: 'keep', distinctDesignationTexts: false }, + // cs-rxnorm.js: by RXCUI as text (the stored order), each atom text once, no designation uses, + // versions by date + rxnorm: { expansionOrder: () => 'stored', description: 'title', lookupName: 'name', versionAlgorithm: 'date', designationUses: 'drop', distinctDesignationTexts: true }, + // any other system: the stored order where the file has one (ix_order rank), else concept ids + generic: { expansionOrder: (store) => (store.hasStoredOrder() ? 'stored' : 'ids'), description: 'title', lookupName: 'name', versionAlgorithm: null, designationUses: 'keep', distinctDesignationTexts: false }, +}; +for (const d of [snomed, loinc, rxnorm, generic]) Object.assign(d, PRESENTATION[d.name]); + function dialectFor(system) { if (system === LOINC) return loinc; if (system === RXNORM) return rxnorm; diff --git a/tx/sqlite-v2/index.js b/tx/sqlite-v2/index.js index 3502f22a..c5c8169e 100644 --- a/tx/sqlite-v2/index.js +++ b/tx/sqlite-v2/index.js @@ -15,7 +15,8 @@ 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 store checks the value at load (meta.js); here only 'snomed' picks the factory + grammar = db.prepare("SELECT value FROM main.meta WHERE key = 'behaviour.grammar'").pluck().get() === '"snomed"' ? 'snomed' : null; } finally { db.close(); } diff --git a/tx/sqlite-v2/integrity.js b/tx/sqlite-v2/integrity.js new file mode 100644 index 00000000..1c14bb67 --- /dev/null +++ b/tx/sqlite-v2/integrity.js @@ -0,0 +1,104 @@ +'use strict'; +// Integrity facts of a terminology file (meta `integrity`, README.md "Integrity facts"): written by +// the step that finishes a file (tx/importers/sqlite-v2/builder.js finishFile), checked by a reader +// at open (checkIntegrity) for a file with `requires`. Every check reads the catalog tables and a +// few index pages only. +// +// 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'], +]); + +// min and max in separate statements: SQLite reads one end of the rowid b-tree for a lone min() or +// max(), and scans the table for both in one statement +const minMax = (db, table) => [db.prepare(`SELECT min(id) FROM main.${table}`).pluck().get(), db.prepare(`SELECT max(id) FROM main.${table}`).pluck().get()]; + +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 }); +} + +/** + * The checks a reader makes at open (a file with `requires`). Throws, naming the check, on the first + * failure. + * @param {Database} db an open connection to the file + * @param {string|null} file its path (null: no length check, e.g. an in-memory database) + * @param {{items, schema, catalog}} stored meta integrity + * @param {{n: number, a: number}} counts code_system concept_count and active_count of the served system + */ +function checkIntegrity(db, file, stored, { n, a }) { + const name = file || 'the file'; + const fail = (check, detail) => { throw new Error(`${name}: integrity check failed: ${check} (${detail}); the file is damaged or was changed after it was built`); }; + // 1. length: catches truncation and appended bytes + if (file) { + const size = fs.statSync(file).size; + const pages = db.pragma('main.page_count', { simple: true }) * db.pragma('main.page_size', { simple: true }); + if (size !== pages) fail('file length', `${size} bytes, page_count * page_size = ${pages}`); + } + // 2. schema + const schema = schemaDigest(db); + if (schema !== stored.schema) fail('schema digest', `${schema}, meta integrity says ${stored.schema}`); + // 3. catalog + const catalog = catalogDigest(db); + if (catalog !== stored.catalog) fail('catalog digest', `${catalog}, meta integrity says ${stored.catalog}`); + // 4. concept ids 1..N, 1..A active + const [lo, hi] = minMax(db, 'concept'); + if (n > 0 ? (lo !== 1 || hi !== n) : lo != null) fail('concept ids', `min ${lo}, max ${hi}, concept_count ${n}`); + const activeOf = (id) => db.prepare('SELECT active FROM main.concept WHERE id = ?').pluck().get(id); + if (a > 0 && activeOf(a) !== 1) fail('active concepts', `concept ${a} (active_count) is not active`); + if (a < n && activeOf(a + 1) !== 0) fail('active concepts', `concept ${a + 1} (active_count + 1) is not inactive`); + // 5. items N+1 .. N+M + const m = stored.items; + const [ilo, ihi] = minMax(db, 'item'); + if (m > 0 ? (ilo !== n + 1 || ihi !== n + m) : ilo != null) fail('item ids', `min ${ilo}, max ${ihi}, expected ${n + 1} .. ${n + m}`); + // 6. the all and active sets + const card = (kind) => db.prepare('SELECT card FROM main.ix_set WHERE kind = ? AND property_id = 0 AND value = 0 AND value_kind = 0').pluck().get(kind) ?? 0; + const all = card(1), act = card(2); + if (all !== n) fail('ix_set all', `card ${all}, concept_count ${n}`); + if (act !== a) fail('ix_set active', `card ${act}, active_count ${a}`); +} + +module.exports = { CATALOG, schemaText, catalogText, schemaDigest, catalogDigest, computeIntegrity, integrityValue, checkIntegrity }; diff --git a/tx/sqlite-v2/layers.js b/tx/sqlite-v2/layers.js index 07083f8b..620abe8f 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/meta.js b/tx/sqlite-v2/meta.js new file mode 100644 index 00000000..39fe17cc --- /dev/null +++ b/tx/sqlite-v2/meta.js @@ -0,0 +1,126 @@ +'use strict'; +// The meta table of a terminology file (tx-terminology/1): a closed list of keys. A reader knows +// every key below and refuses a file with any other key (the one open namespace is `provenance.`: +// informational, never read), and refuses a malformed value of a key it reads. The builder runs the +// same check on what it writes (tx/importers/sqlite-v2/builder.js). +// +// `requires` lists the features beyond the base format that the file's content uses; a feature this +// reader does not know refuses the file. A file without `requires` was written before it existed +// (a pre-requires file); readFileMeta is the one place that decides what that allows. + +const FORMAT = 'tx-terminology/1'; + +/** the features a file may require, and what each means (README.md) */ +const KNOWN_FEATURES = Object.freeze(['identifier-text']); + +/** the features every file written from now on requires (the builder writes them) */ +const WRITTEN_FEATURES = Object.freeze(['identifier-text']); + +/** the word index scopes (which names the word index holds: tx/sqlite-v2/text-index.js) */ +const WORD_SCOPES = Object.freeze(['snomed', 'loinc', 'rxnorm']); + +/** the code grammars a file may state (behaviour.grammar) */ +const GRAMMARS = Object.freeze([null, 'snomed', 'icd11']); + +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 isHex64 = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v); +const isCount = (v) => Number.isSafeInteger(v) && v >= 0; +const onlyKeys = (o, keys) => Object.keys(o).every((k) => keys.includes(k)); +const DECIMAL = /^(0|[1-9][0-9]*)$/; + +/** a JSON value check: the text parses and the value passes */ +const json = (check) => ({ json: true, check }); +const text = (check) => ({ json: false, check }); + +/** key -> value check (the complete list; provenance.* aside) */ +const KEYS = Object.freeze({ + format: text((v) => v === FORMAT), + requires: json((v) => isStrings(v) && new Set(v).size === v.length), + integrity: json((v) => isPlainObject(v) && onlyKeys(v, ['items', 'schema', 'catalog']) && isCount(v.items) && isHex64(v.schema) && isHex64(v.catalog)), + languages: json(isStrings), + displayContexts: json((v) => isPlainObject(v) && onlyKeys(v, ['relations', 'preferred', 'use']) && isStrings(v.relations) + && isString(v.preferred) && (v.use == null || (isPlainObject(v.use) && onlyKeys(v.use, ['system', 'code']) && isString(v.use.code) + && (v.use.system == null || isString(v.use.system))))), + moduleDependencies: json((v) => Array.isArray(v) && v.every((r) => isStrings(r) && r.length === 4)), + edition: text((v) => v !== ''), + titles: json((v) => isPlainObject(v) && Object.values(v).every(isString)), + 'derived-by-importer': json((v) => Array.isArray(v) && v.every((d) => isPlainObject(d) && onlyKeys(d, ['table', 'name']) && isString(d.table) && isString(d.name))), + 'ix.ix_word.format': text((v) => v !== ''), + 'ix.ix_word.stemmers': json((v) => isPlainObject(v) && Object.values(v).every((s) => isString(s) && s !== '')), + 'ix.ix_word.scope': text((v) => WORD_SCOPES.includes(v)), + 'ix.ix_order.walk.reached': text((v) => DECIMAL.test(v) && Number.isSafeInteger(Number(v))), + 'behaviour.grammar': json((v) => GRAMMARS.includes(v)), +}); + +/** + * Keys a pre-requires file may carry, accepted and ignored there (a file with `requires` that has + * one is refused, as for any unknown key): every behaviour.* key but grammar (they told a server how + * to present the system; each server keeps those rules in code, tx/sqlite-v2/dialects.js), + * linkOrder, searchTieBreak, and ix.ix_key.normalForm.stats (now provenance.normalFormStats). + */ +function isRetiredKey(key) { + return (key.startsWith('behaviour.') && key !== 'behaviour.grammar') + || key === 'linkOrder' || key === 'searchTieBreak' || key === 'ix.ix_key.normalForm.stats'; +} + +const isProvenance = (key) => key.startsWith('provenance.'); + +/** + * Check a file's meta and return what the reader uses of it. Throws, naming the key, on an unknown + * key, a malformed value, an unknown required feature, or (a finished file with `requires`) a missing + * integrity, ix.ix_word.stemmers or ix.ix_word.scope. + * @param {Map|Iterable<[string,string]>} meta every row of the table (provenance.* is skipped) + * @param {string} file the file's name, for messages + * @param {object} [opts] { finished: false for a file still being built (the keys its last step + * writes may be missing) } + * @returns {{preRequires: boolean, requires: string[]|null, integrity: object|null, grammar: string|null, + * values: Map}} values: the parsed value of every listed key present (retired keys left out) + */ +function readFileMeta(meta, file, opts = {}) { + const name = typeof file === 'string' ? file : 'the file'; + const rows = new Map(meta); + // the one place that decides what a file written before `requires` existed is allowed + const preRequires = !rows.has('requires'); + const values = new Map(); + for (const [key, raw] of rows) { + if (isProvenance(key)) continue; + const spec = KEYS[key]; + if (!spec) { + if (preRequires && isRetiredKey(key)) continue; + throw new Error(`${name}: unknown meta key ${key}${isRetiredKey(key) ? ' (a retired key, refused in a file with requires)' : ''}`); + } + 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} is not JSON: ${raw.slice(0, 200)}`); } + } + if (!spec.check(v)) throw new Error(`${name}: meta ${key} has a malformed value: ${raw.slice(0, 200)}`); + values.set(key, v); + } + if (!values.has('format')) throw new Error(`${name}: no meta format`); + const requires = preRequires ? null : values.get('requires'); + if (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(', ')})`); + } + if (opts.finished !== false) { + if (!values.has('integrity')) throw new Error(`${name}: a file with requires carries meta integrity; it has none`); + if (values.has('ix.ix_word.format')) { + for (const k of ['ix.ix_word.stemmers', 'ix.ix_word.scope']) { + if (!values.has(k)) throw new Error(`${name}: a file with requires and ix.ix_word.format carries meta ${k}; it has none`); + } + } + } + } + return { + preRequires, + requires, + integrity: preRequires ? null : (values.get('integrity') || null), + grammar: values.has('behaviour.grammar') ? values.get('behaviour.grammar') : null, + values, + }; +} + +module.exports = { readFileMeta, isRetiredKey, KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, WORD_SCOPES, GRAMMARS, FORMAT }; diff --git a/tx/sqlite-v2/orders.js b/tx/sqlite-v2/orders.js index ed3e8b53..2b59dc8e 100644 --- a/tx/sqlite-v2/orders.js +++ b/tx/sqlite-v2/orders.js @@ -101,7 +101,7 @@ 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 + // expansion order 'stored-self-first' (dialects.js): an is-a / << filter lists its concept first selfFirst: kind === 'stored-self-first', hasWalk: meta.has('walk'), stored: true, diff --git a/tx/sqlite-v2/provider.js b/tx/sqlite-v2/provider.js index 0b4e0318..1f2b90a4 100644 --- a/tx/sqlite-v2/provider.js +++ b/tx/sqlite-v2/provider.js @@ -113,7 +113,7 @@ class SqliteV2Provider extends BaseCSServices { isNotClosed() { return !!this.store.notClosed; } contentMode() { return this.store.cs.content || 'complete'; } versionAlgorithm() { return this.f.versionAlgorithm(); } - isCaseSensitive() { return this.store.caseSensitive; } + isCaseSensitive() { return true; } // codes are matched exactly (binary) sourcePackage() { return null; } /** @@ -481,8 +481,8 @@ class SqliteV2Provider extends BaseCSServices { } } 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 }); + // use where the system's rule says so: dialects.js designationUses) + const use = (d) => (this.dialect.designationUses === 'drop' || !d.use ? null : { system: d.use.system, code: d.use.code, display: d.use.display }); displays.addDesignation(true, 'active', 'en-US', null, c.row.display || ''); let skipped = false; for (const d of c.desigs) { @@ -1348,8 +1348,8 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { async load() { this.store = openStore(this.file, this.opts); this.dialect = dialectFor(this.store.system); - // behaviour.expansionOrder: concept ids, or the stored order (ix_order) - const kind = this.store.behaviour.expansionOrder; + // the system's expansion order (dialects.js): concept ids, or the stored order (ix_order) + const kind = this.store.expansionOrder; const order = kind !== 'ids' ? this._systemOrder(kind) : null; this.engine = new Engine(this.store, order ? { ...this.opts, order } : this.opts); // SNOMED CT text search ranks ties by the built-in concept order (text-index.js) @@ -1375,10 +1375,10 @@ 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(); } + // the system's description / lookup name (dialects.js): the code system's name or its title + // (LOINC: description 'LOINC', $lookup name the title, as cs-loinc.js) + description() { return this.dialect.description === 'name' ? this.name() : (this.store.cs.title || this.name()); } + lookupName() { return this.dialect.lookupName === 'title' ? (this.store.cs.title || this.name()) : this.name(); } defLang() { return 'en'; } /** * RxNorm: the concepts in RXNCONSO, as cs-rxnorm.js counts them (its totalCodeCount), not those @@ -1392,7 +1392,7 @@ class SqliteV2Factory extends CodeSystemFactoryProvider { } return this._liveCount; } - versionAlgorithm() { return this.store.behaviour.versionAlgorithm; } + versionAlgorithm() { return this.dialect.versionAlgorithm; } /** * The factory id, as main's provider for the same system forms it (read.js and search.js serve * it as CodeSystem/x-; tx.fhir.org uses the same ids): LOINC 'loinc' + version diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 3e93d87f..3614ad03 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -11,15 +11,19 @@ // 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. +// meta is a closed list of keys (meta.js: an unknown key, malformed value or unknown required feature +// is an error at open); a file with `requires` is checked against its integrity facts at open +// (integrity.js). The code grammar is a fact of the file (behaviour.grammar); how the server presents +// the system (order, names, version algorithm) is its rule for the system (dialects.js). The catalog +// columns filter_ops and report say which filters a property takes and when $lookup reports it. // // 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 { readFileMeta } = require('./meta'); +const { checkIntegrity } = require('./integrity'); const FORMAT = 'tx-terminology/1'; const USER_VERSION = 1; @@ -60,8 +64,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); @@ -74,80 +79,22 @@ 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. - */ -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'); -} +/** the code grammars this server implements (behaviour.grammar; meta.js lists those a file may state) */ +const IMPLEMENTED_GRAMMARS = [null, 'snomed']; + const FILTER_OPS = new Set(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'exists']); const REPORT = new Set([null, 'named', 'always']); -/** meta behaviour.* -> settings object (every key, defaults filled); throws on an unknown key or value */ -function readBehaviour(meta, file) { - const out = {}; - for (const [k, d] of Object.entries(BEHAVIOUR)) out[k] = d.default; - for (const [key, raw] of meta) { - if (!key.startsWith('behaviour.')) continue; - const k = key.substring('behaviour.'.length); - const d = BEHAVIOUR[k]; - if (!d) throw new Error(`${file}: unknown behaviour setting ${key} (this server knows ${Object.keys(BEHAVIOUR).join(', ')})`); - let v; - try { v = JSON.parse(raw); } catch (e) { throw new Error(`${file}: ${key} is not JSON: ${raw}`); } - if (d.values ? !d.values.includes(v) : !d.check(v)) throw new Error(`${file}: ${key} = ${raw} is not a value this server knows`); - out[k] = v; - } - return Object.freeze(out); +/** + * A file's meta, checked (meta.js readFileMeta), and its grammar one this server implements. + * opts.finished false: a file still being built (the index builder reads it through a store). + */ +function checkMeta(meta, file, opts = {}) { + const m = readFileMeta(meta, file, opts); + if (!IMPLEMENTED_GRAMMARS.includes(m.grammar)) { + throw new Error(`${file}: its codes have the grammar ${m.grammar} (behaviour.grammar), which this server does not implement`); + } + return m; } const NODE_SHAPES = new Set(['link', 'union']); @@ -183,7 +130,9 @@ class Store { /** * @param {string} file path, or ':memory:' style handle for a layer * @param {object} [opts] { db: an already open better-sqlite3 handle, stmts: a statement map - * shared by stores of one file, unregistered } + * shared by stores of one file, unregistered, unfinished: a file still being built (the index + * builder's and an importer's own reads): the checks of a finished file (its integrity facts, + * the keys its last step writes) are skipped } */ constructor(file, opts = {}) { @@ -201,7 +150,7 @@ class Store { this.uid = ++ownerSeq; try { checkFormat(this.db, file); - this._loadMeta(); + this._loadMeta(!opts.unfinished); } catch (e) { if (!opts.db) this.db.close(); throw e; @@ -365,27 +314,37 @@ class Store { // ---- metadata and catalog ----------------------------------------------------------------- - _loadMeta() { + _loadMeta(finished = true) { const db = this.db; const cs = db.prepare('SELECT * FROM main.code_system WHERE served = 1').get(); if (!cs) throw new Error(`${this.file}: no served code_system row (not a terminology file?)`); - this.meta = new Map(db.prepare("SELECT key, value FROM main.meta WHERE key NOT LIKE 'provenance.%'").raw().all()); + this.meta = new Map(db.prepare("SELECT key, value FROM main.meta WHERE substr(key, 1, 11) <> 'provenance.'").raw().all()); + const m = checkMeta(this.meta, this.file, { finished }); + // a file written before meta requires existed (meta.js decides what that allows) + this.preRequires = m.preRequires; + this.requires = m.requires; + // identifier values are all text: probes bind text (else an integer value is bound as INTEGER) + this.identifierText = !!(m.requires && m.requires.includes('identifier-text')); + if (finished && m.integrity) { + checkIntegrity(db, db.memory ? null : db.name, m.integrity, { n: cs.concept_count, a: cs.active_count }); + } this.format = this.meta.get('format'); this.csId = cs.cs_id; this.cs = { id: cs.cs_id, uri: cs.uri, version: cs.version, name: cs.name, title: cs.title, description: cs.description, - release_date: cs.release_date, content: cs.content, edition: this.meta.get('edition') ?? null, - concept_count: cs.concept_count, active_count: cs.active_count, case_sensitive: cs.case_sensitive, hierarchy_meaning: cs.hierarchy_meaning }; + content: cs.content, edition: this.meta.get('edition') ?? null, concept_count: cs.concept_count, active_count: cs.active_count }; this.system = cs.uri; this.version = cs.version; this.conceptCount = cs.concept_count; this.activeCount = cs.active_count; this.lo = 1; this.hi = cs.concept_count; - this.behaviour = readBehaviour(this.meta, this.file); + // the grammar of the system's codes: 'snomed' (SNOMED CT expressions and ECL) or null (plain codes) + this.grammar = m.grammar; + // how this server presents the system (dialects.js) + this.presentation = require('./dialects').dialectFor(cs.uri); // a compositional system's expansions are never closed (post-coordinated expressions are codes) this.notClosed = cs.compositional === 1; this.defaultLanguage = cs.default_language || null; - this.caseSensitive = cs.case_sensitive !== 0; const metaJson = (k, d) => (this.meta.has(k) ? JSON.parse(this.meta.get(k)) : d); const dc = metaJson('displayContexts', null); this.displayRefsets = dc && dc.relations ? dc.relations.map(String) : null; @@ -414,7 +373,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) @@ -449,8 +408,10 @@ 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; + // descendants sets), and in SNOMED CT (grammar 'snomed') not a 'both' attribute: cs-snomed.js keeps + // one value kind per attribute and never reads them ($lookup, main's ECL over the store); a filter + // or ECL refinement naming the attribute does + const skipBoth = this.grammar === 'snomed'; this.hiddenLinks = [...this.catalog.values()].filter((d) => (skipBoth && d.shape === 'both') || closureSources.has(d.id)).map((d) => d.id); // the reference sets: record relations by their concept; the language ones rank displays this.relations = new Map(); @@ -494,6 +455,18 @@ class Store { /** the languages of the served system's items (meta, a release fact) */ languages() { return JSON.parse(this.meta.get('languages') || '[]'); } + /** + * the order of an expansion: 'ids', 'stored' or 'stored-self-first' (the rule for the system, + * dialects.js expansionOrder) + */ + get expansionOrder() { return this.presentation.expansionOrder(this); } + + /** whether the file stores a system order (ix_order rank) */ + hasStoredOrder() { return !!this.db.prepare("SELECT 1 FROM main.ix_order WHERE name = 'rank' LIMIT 1").get(); } + + /** 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); } @@ -652,7 +625,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; } @@ -755,7 +728,7 @@ class Store { 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; + const distinct = this.presentation.distinctDesignationTexts; let l = null, lid = null, seen = null; for (const r of rows) { if (r[1] !== lid) { @@ -1028,8 +1001,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 in a file that requires 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)); @@ -1046,7 +1020,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) { @@ -1092,12 +1066,42 @@ class Store { // ---- text ------------------------------------------------------------------------------- - textIndex() { - if (this._textIndex === undefined) { - const words = require('./text-index').FORMAT; - this._textIndex = this.meta.get('ix.ix_word.format') === words ? new (require('./text-index').WordIndex)(this) : null; + /** + * The stored word index (text-index.js WordIndex) for the names the dialect's text search reads, + * or null (the search builds one in memory) + */ + textIndex(dialect) { + if (!this._textIndex) this._textIndex = new Map(); + if (!this._textIndex.has(dialect)) { + const w = this.wordIndexState(dialect); + this._textIndex.set(dialect, w.used ? w.index : null); + } + return this._textIndex.get(dialect); + } + + /** + * Whether the stored word index serves the dialect's text search: {used, reason, index}. It does + * when it is made by this server's rules (meta ix.ix_word.format text-match/1) and, in a file with + * requires, holds the names this server's search reads (ix.ix_word.scope) stemmed by this server's + * stemmer for each of its languages (ix.ix_word.stemmers); otherwise a stored stem may not equal + * the query's stem, and a match would be missed + */ + wordIndexState(dialect) { + const ti = require('./text-index'); + const format = this.meta.get('ix.ix_word.format'); + if (format !== ti.FORMAT) return { used: false, reason: format == null ? 'no word index' : `ix.ix_word.format ${format}` }; + const index = new ti.WordIndex(this); + if (this.preRequires) return { used: true, index }; + const scope = this.meta.get('ix.ix_word.scope'); + if (scope !== dialect) return { used: false, reason: `ix.ix_word.scope ${scope}, this server's search reads ${dialect}` }; + const stemmers = JSON.parse(this.meta.get('ix.ix_word.stemmers')); + const { stemmerName } = require('../library/text-match'); + for (const lang of new Set([...Object.keys(stemmers), ...index.langs])) { + if (stemmers[lang] !== stemmerName(lang)) { + return { used: false, reason: `language ${lang}: stemmer ${stemmers[lang] ?? '(none recorded)'}, this server's is ${stemmerName(lang)}` }; + } } - return this._textIndex; + return { used: true, index }; } /** @@ -1131,4 +1135,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, checkMeta, IMPLEMENTED_GRAMMARS, 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 146ed8bf..14a42d17 100644 --- a/tx/sqlite-v2/text-index.js +++ b/tx/sqlite-v2/text-index.js @@ -36,8 +36,11 @@ // 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), 'ix.ix_word.scope' the names it holds (the dialect whose +// names eachSearchName lists) and 'ix.ix_word.stemmers' the stemmer of each language +// (text-match.js stemmerName). The counts row is little-endian. A file without an index made by +// these rules, for the names and with the stemmers this server's search uses (store.js +// wordIndexState), has it built in memory on the first search, as the built-in providers do. const { RoaringBitmap32 } = require('roaring'); const { TextQuery, words: textWords, stem: stemOf, languageOf } = require('../library/text-match'); @@ -157,6 +160,20 @@ function computeTextIndexFrom(each, dialect, n) { // ---- reading the index ------------------------------------------------------------------------ +/** 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; +} + /** the word index the index builder stored (ix_word) */ class WordIndex { constructor(store) { @@ -169,7 +186,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; @@ -253,7 +270,7 @@ class MemoryTextIndex { /** the file's index: stored in the file, else built in memory now */ function textIndexOf(store, dialect) { - const stored = store.textIndex(); + const stored = store.textIndex(dialect); 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()); @@ -475,7 +492,7 @@ function* rankSct(store, kept, ordinal, counts, q, lang, several, stats) { */ function sctTextLanguages(store) { if (!store._textLangs) { - const idx = store.textIndex(); + const idx = store.textIndex('snomed'); const stored = idx ? idx.languages() : null; if (stored) store._textLangs = new Set(stored); else { @@ -665,7 +682,7 @@ const genericTextSearch = (...a) => runSync(genericTextSearchG(...a)); module.exports = { FORMAT, WordIndex, blockConcepts, indexed, eachSearchName, searchNamesOf, rxSearchable, - computeTextIndexFrom, textIndexOf, primaryLanguage, + computeTextIndexFrom, textIndexOf, primaryLanguage, countsFromLE, countsToLE, sctTextSearch, sctTextLanguages, loincTextSearch, rxTextSearch, genericTextSearch, rateConcepts, sctTextSearchG, loincTextSearchG, rxTextSearchG, genericTextSearchG }; From c1bd66a21302a37c05dd56b6aa937fe9521d6da6 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 13:39:40 -0600 Subject: [PATCH 3/5] sqlite-v2: tests for meta keys, requires, integrity checks and contracts Unknown required features and meta keys refused; retired keys refused in a file with requires and ignored in one without; each integrity check at open tripping on a changed copy; identifier probes on mixed and text-only files; the little-endian counts row; the in-memory word index on a stemmer or scope mismatch; the builder's contract checks; grammar icd11 refused. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-integrity.test.js | 348 ++++++++++++++++++++ 1 file changed, 348 insertions(+) create mode 100644 tests/tx/sqlite-v2-format-integrity.test.js diff --git a/tests/tx/sqlite-v2-format-integrity.test.js b/tests/tx/sqlite-v2-format-integrity.test.js new file mode 100644 index 00000000..89ed0189 --- /dev/null +++ b/tests/tx/sqlite-v2-format-integrity.test.js @@ -0,0 +1,348 @@ +'use strict'; + +// The file-level rules of the terminology format (tx/sqlite-v2/README.md): the closed meta key list +// and `requires`, files written before `requires`, the integrity facts checked at open, the word +// index facts (scope, stemmers, the little-endian counts row), text identifier values, the grammar a +// reader implements, and the contracts the builder checks before it finishes a file. + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const Database = require('better-sqlite3'); +const { RoaringBitmap32 } = require('roaring'); +const { TerminologyBuilder, finishFile, vacuumFile } = require('../../tx/importers/sqlite-v2/builder'); +const { openStore } = require('../../tx/sqlite-v2/store'); +const { computeIntegrity, schemaText, catalogText } = require('../../tx/sqlite-v2/integrity'); +const { readFileMeta } = require('../../tx/sqlite-v2/meta'); +const { countsFromLE, countsToLE, textIndexOf, WordIndex } = require('../../tx/sqlite-v2/text-index'); +const { stemmerName } = require('../../tx/library/text-match'); +const { importSnomedV2 } = require('../../tx/importers/import-sct-v2.module'); + +const SRC = path.resolve(__dirname, '../../tx/data/snomed'); +let dir; +beforeAll(() => { dir = fs.mkdtempSync(path.join(process.env.SQLITE_V2_TEST_TMP || os.tmpdir(), 'sqlite-v2-integrity-')); }); +afterAll(() => { fs.rmSync(dir, { recursive: true, force: true }); }); + +/** a small file: a hierarchy, an inactive concept, items, text and integer-looking identifiers */ +function build(dest, { vacuum = true } = {}) { + const b = new TerminologyBuilder(dest, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/cs', version: '1' }); + const isa = b.property({ code: 'isa', shape: 'link', subsumption: true }); + const part = b.property({ code: 'part', shape: 'link' }); + const alt = b.property({ code: 'alt', shape: 'identifier' }); + const c = {}; + for (const code of ['root', 'A', 'B', 'C', 'X']) c[code] = b.concept(code, { active: code !== 'X', display: `display ${code}` }); + b.link(c.A, isa, c.root); b.link(c.B, isa, c.A); b.link(c.C, isa, c.root); b.link(c.X, isa, c.root); + b.link(c.B, part, c.C); + b.identifier(alt, '123', c.A, { resolves: 1 }); + b.identifier(alt, 'K9', c.B, { resolves: 1 }); + b.identifier(alt, 77, c.C); + for (const code of ['A', 'B', 'C']) b.item(c[code], { language: 'en', text: `term ${code}` }); + const summary = b.finish({}, { vacuum }); + return summary; +} + +/** a copy of `file` changed by fn(db) */ +function changed(file, name, fn, { refinish = false } = {}) { + const f = path.join(dir, name); + fs.copyFileSync(file, f); + const db = new Database(f); + try { + fn(db); + if (refinish) finishFile(db, f); + } finally { db.close(); } + return f; +} + +/** make a copy a file written before `requires` existed */ +const preRequires = (db) => db.exec("DELETE FROM meta WHERE key IN ('requires', 'integrity', 'ix.ix_word.stemmers', 'ix.ix_word.scope')"); + +let file; +beforeAll(() => { + file = path.join(dir, 'small.db'); + build(file); +}); + +describe('meta: the closed key list and requires', () => { + test('a built file requires identifier-text and states its integrity facts, which a reader recomputes', () => { + const db = new Database(file, { readonly: true }); + try { + const m = new Map(db.prepare('SELECT key, value FROM meta').raw().all()); + expect(JSON.parse(m.get('requires'))).toEqual(['identifier-text']); + expect(JSON.parse(m.get('integrity'))).toEqual(computeIntegrity(db)); + expect(JSON.parse(m.get('integrity')).items).toBe(3); + // the digest texts as the format states them: rows joined by LF, no trailing LF + expect(schemaText(db)).toMatch(/^index\tconcept_code\tconcept\tCREATE UNIQUE INDEX/m); + expect(schemaText(db).endsWith('\n')).toBe(false); + const cat = catalogText(db).split('\n'); + expect(cat[0]).toBe("code_system\t1,'http://example.org/cs','1',NULL,NULL,NULL,'complete',NULL,NULL,1,5,4,NULL"); + expect(cat.filter((l) => l.startsWith('meta\t')).map((l) => l.split(',')[0])).toEqual(["meta\t'format'", "meta\t'languages'", "meta\t'requires'"]); + expect(cat.some((l) => /provenance\.|'integrity'/.test(l))).toBe(false); + expect(m.has('behaviour.expansionOrder')).toBe(false); + } finally { db.close(); } + const S = openStore(file, { unregistered: true }); + try { expect([S.preRequires, S.requires, S.identifierText]).toEqual([false, ['identifier-text'], true]); } finally { S.close(); } + }); + + test('a required feature the reader does not know is refused, naming it', () => { + const f = changed(file, 'req.db', (db) => db.exec(`UPDATE meta SET value = '["identifier-text","colour-codes"]' WHERE key = 'requires'`), { refinish: false }); + expect(() => openStore(f)).toThrow(/requires the feature colour-codes, which this server does not know/); + expect(() => readFileMeta([['format', 'tx-terminology/1'], ['requires', '["a","a"]']], 'x')).toThrow(/meta requires has a malformed value/); + }); + + test('an unknown key is refused; provenance.* is open; a malformed value is refused, not ignored', () => { + expect(() => openStore(changed(file, 'key.db', (db) => db.exec("INSERT INTO meta VALUES ('colour', 'red')")))).toThrow(/unknown meta key colour/); + expect(() => openStore(changed(file, 'case.db', (db) => db.exec("INSERT INTO meta VALUES ('Provenance.x', 'y')")))).toThrow(/unknown meta key Provenance\.x/); + const prov = changed(file, 'prov.db', (db) => db.exec("INSERT INTO meta VALUES ('provenance.anything', 'at all')")); + openStore(prov, { unregistered: true }).close(); + expect(() => openStore(changed(file, 'lang.db', (db) => db.exec("UPDATE meta SET value = 'en' WHERE key = 'languages'")))).toThrow(/meta languages is not JSON/); + expect(() => openStore(changed(file, 'integ.db', (db) => db.exec(`UPDATE meta SET value = '{"items": 3}' WHERE key = 'integrity'`)))) + .toThrow(/meta integrity has a malformed value/); + expect(() => openStore(changed(file, 'none.db', (db) => db.exec("DELETE FROM meta WHERE key = 'integrity'")))).toThrow(/carries meta integrity; it has none/); + }); + + test('a retired key is refused in a file with requires, accepted and ignored in a file without', () => { + expect(() => openStore(changed(file, 'retired.db', (db) => db.exec(`INSERT INTO meta VALUES ('behaviour.expansionOrder', '"stored"')`), { refinish: true }))) + .toThrow(/unknown meta key behaviour.expansionOrder \(a retired key/); + expect(() => openStore(changed(file, 'retired2.db', (db) => db.exec("INSERT INTO meta VALUES ('ix.ix_key.normalForm.stats', '{}')")))) + .toThrow(/unknown meta key ix.ix_key.normalForm.stats/); + const old = changed(file, 'old.db', (db) => { + preRequires(db); + db.exec(`INSERT INTO meta VALUES ('behaviour.expansionOrder', '"stored"'), ('behaviour.lookupName', '"title"'), ('linkOrder', 'seq'), + ('searchTieBreak', 'rank'), ('ix.ix_key.normalForm.stats', '{}')`); + db.exec("UPDATE code_system SET name = 'not checked: no integrity facts'"); + }); + const S = openStore(old, { unregistered: true }); + try { + expect(S.preRequires).toBe(true); + expect(S.expansionOrder).toBe('ids'); // the retired value is ignored: the rule for the system + expect(S.idOf('B')).toBeGreaterThan(0); + } finally { S.close(); } + // the builder refuses to write one + 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('linkOrder', 'seq'); + expect(() => b.finish()).toThrow(/unknown meta key linkOrder/); + }); + + test('grammar: icd11 is a grammar this reader does not implement: refused; an unknown grammar is malformed', () => { + expect(() => openStore(changed(file, 'icd.db', (db) => db.exec(`INSERT INTO meta VALUES ('behaviour.grammar', '"icd11"')`), { refinish: true }))) + .toThrow(/grammar icd11 \(behaviour.grammar\), which this server does not implement/); + expect(() => openStore(changed(file, 'icd-old.db', (db) => { preRequires(db); db.exec(`INSERT INTO meta VALUES ('behaviour.grammar', '"icd11"')`); }))) + .toThrow(/does not implement/); + expect(() => openStore(changed(file, 'gram.db', (db) => db.exec(`INSERT INTO meta VALUES ('behaviour.grammar', '"cpt"')`)))) + .toThrow(/meta behaviour.grammar has a malformed value/); + }); +}); + +describe('integrity facts: each check at open trips on a changed copy', () => { + const trips = (name, fn, msg) => expect(() => openStore(changed(file, name, fn))).toThrow(msg); + + test('1. file length', () => { + const f = path.join(dir, 'long.db'); + fs.copyFileSync(file, f); + fs.appendFileSync(f, Buffer.alloc(100)); + expect(() => openStore(f)).toThrow(/integrity check failed: file length/); + const t = path.join(dir, 'short.db'); + fs.writeFileSync(t, fs.readFileSync(file).subarray(0, fs.statSync(file).size - 4096)); + expect(() => openStore(t)).toThrow(/integrity check failed: file length|malformed|not a database/); + }); + + test('2. schema digest', () => trips('schema.db', (db) => db.exec('CREATE INDEX extra ON concept(display)'), /integrity check failed: schema digest/)); + + test('3. catalog digest: code_system, catalog, meta', () => { + trips('cs.db', (db) => db.exec("UPDATE code_system SET title = 'another title'"), /integrity check failed: catalog digest/); + trips('prop.db', (db) => db.exec("UPDATE property SET filterable = 0 WHERE code = 'part'"), /integrity check failed: catalog digest/); + trips('meta.db', (db) => db.exec(`UPDATE meta SET value = '["en","fr"]' WHERE key = 'languages'`), /integrity check failed: catalog digest/); + // provenance is not in it + const ok = changed(file, 'prov2.db', (db) => db.exec("UPDATE meta SET value = 'someone else' WHERE key = 'provenance.importer'")); + openStore(ok, { unregistered: true }).close(); + }); + + test('4. concept ids and the active prefix', () => { + trips('lastc.db', (db) => db.exec('DELETE FROM concept WHERE id = (SELECT max(id) FROM concept)'), /integrity check failed: concept ids/); + trips('act.db', (db) => db.exec('UPDATE concept SET active = 0 WHERE id = (SELECT active_count FROM code_system)'), /integrity check failed: active concepts/); + trips('inact.db', (db) => db.exec('UPDATE concept SET active = 1 WHERE id = (SELECT active_count + 1 FROM code_system)'), /integrity check failed: active concepts/); + }); + + test('5. item ids', () => { + trips('item.db', (db) => db.exec('DELETE FROM item WHERE id = (SELECT max(id) FROM item)'), /integrity check failed: item ids/); + }); + + test('6. the all and active sets', () => { + trips('all.db', (db) => db.exec('UPDATE ix_set SET card = card + 1 WHERE kind = 1'), /integrity check failed: ix_set all/); + trips('active.db', (db) => db.exec('DELETE FROM ix_set WHERE kind = 2'), /integrity check failed: ix_set active/); + }); + + test('the index builder skips the checks of a finished file mid-build; the default does not', () => { + const f = changed(file, 'mid.db', (db) => db.exec("DELETE FROM meta WHERE key = 'integrity'")); + const db = new Database(f, { readonly: true }); + try { + const { Store } = require('../../tx/sqlite-v2/store'); + expect(() => new Store(f, { db, unregistered: true })).toThrow(/carries meta integrity/); + expect(new Store(f, { db, unregistered: true, unfinished: true }).idOf('A')).toBeGreaterThan(0); + } finally { db.close(); } + }); +}); + +describe('identifier values', () => { + test('a file with requires: every value TEXT, probes bind 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 DISTINCT typeof(value) FROM ix_by_subject').pluck().all()).toEqual(['text']); + // item.external_id is unchanged (none here) + } finally { db.close(); } + const S = openStore(file, { unregistered: true }); + try { + expect(S.identifierAsCode('123').code).toBe('A'); + expect(S.identifierAsCode('K9').code).toBe('B'); + expect(S.identifierAsCode(123).code).toBe('A'); + const alt = S.catalog.get('alt'); + expect(S.subjectsOfIdentifiers(alt, ['77', 'K9'])).toEqual([S.idOf('C'), S.idOf('B')].sort((a, b) => a - b)); + } finally { S.close(); } + }); + + test('a file without requires: INTEGER and TEXT values, probes typed as before', () => { + const f = changed(file, 'mixed.db', (db) => { + preRequires(db); + db.exec("UPDATE identifier SET value = CAST(value AS INTEGER) WHERE value GLOB '[0-9]*'"); + db.exec("UPDATE ix_by_subject SET value = CAST(value AS INTEGER) WHERE value GLOB '[0-9]*'"); + }); + const db = new Database(f, { readonly: true }); + try { expect(db.prepare('SELECT typeof(value) FROM identifier ORDER BY 1').pluck().all()).toEqual(['integer', 'integer', 'text']); } finally { db.close(); } + const S = openStore(f, { unregistered: true }); + try { + expect(S.identifierText).toBe(false); + expect(S.identifierAsCode('123').code).toBe('A'); + expect(S.identifierAsCode('K9').code).toBe('B'); + expect(S.subjectsOfIdentifiers(S.catalog.get('alt'), ['77', 'K9'])).toEqual([S.idOf('C'), S.idOf('B')].sort((a, b) => a - b)); + } finally { S.close(); } + }); +}); + +describe('the word index facts', () => { + let sct; + const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)])); + beforeAll(async () => { + // the RF2 subset's modules merged into one snapshot (as tests/tx/sqlite-v2-format-cases.test.js) + const snap = path.join(dir, 'Snapshot'); + const groups = new Map(); + for (const f of walk(SRC)) { + if (!f.endsWith('.txt') || /Readme|license/i.test(f)) continue; + const rel = path.relative(SRC, f); + const key = path.join(path.dirname(rel), path.basename(rel).replace(/_(INT|TEST1000003|LO1010000)_/, '_MERGED_')); + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(f); + } + for (const [k, files] of groups) { + const out = path.join(snap, k); + fs.mkdirSync(path.dirname(out), { recursive: true }); + fs.writeFileSync(out, files.flatMap((f, i) => fs.readFileSync(f, 'utf8').split(/\r?\n/).filter(Boolean).slice(i ? 1 : 0)).join('\n') + '\n'); + } + sct = path.join(dir, 'sct.db'); + await importSnomedV2({ source: snap, dest: sct, edition: '31000003106', version: '20250909', overwrite: true, normalForms: false, log: () => {} }); + }, 120000); + + test('scope and stemmers recorded; the stored index used when they are this reader\'s', () => { + const S = openStore(sct, { unregistered: true }); + try { + expect(S.meta.get('ix.ix_word.scope')).toBe('snomed'); + const st = JSON.parse(S.meta.get('ix.ix_word.stemmers')); + expect(Object.keys(st).length).toBeGreaterThan(0); + for (const [lang, name] of Object.entries(st)) expect(name).toBe(stemmerName(lang)); + expect(st.en).toBe('natural:PorterStemmer'); + expect(S.wordIndexState('snomed').used).toBe(true); + expect(textIndexOf(S, 'snomed')).toBeInstanceOf(WordIndex); + // the scope is the dialect's: another dialect's search does not use it + expect(S.wordIndexState('loinc')).toMatchObject({ used: false, reason: expect.stringMatching(/scope snomed/) }); + } finally { S.close(); } + expect(stemmerName('nb-NO')).toBe('natural:PorterStemmerNo'); + expect(stemmerName('ja')).toBe('none'); + }); + + test('the counts row: 2 * (N + 1) bytes, little-endian on every host', () => { + const db = new Database(sct, { readonly: true }); + try { + const n = db.prepare('SELECT concept_count FROM code_system WHERE served = 1').pluck().get(); + const b = db.prepare("SELECT ids FROM ix_word WHERE lang = 'en' AND word = ''").pluck().get(); + expect(b.length).toBe(2 * (n + 1)); + const counts = countsFromLE(b); + for (let i = 0; i < counts.length; i++) expect(counts[i]).toBe(b[2 * i] | (b[2 * i + 1] << 8)); + expect(Buffer.compare(countsToLE(counts), b)).toBe(0); + expect(counts.some((c) => c > 0)).toBe(true); + } finally { db.close(); } + expect(Array.from(countsFromLE(Buffer.from([1, 0, 0, 1, 0xff, 0xff])))).toEqual([1, 256, 65535]); + expect([...countsToLE(Uint16Array.from([1, 256]))]).toEqual([1, 0, 0, 1]); + }); + + test('another stemmer or scope: the stored index is not used, the search builds one in memory and answers the same', () => { + const search = (f) => { + const S = openStore(f, { unregistered: true }); + try { return { state: S.wordIndexState('snomed'), index: textIndexOf(S, 'snomed').constructor.name, hits: S.searchText('fracture', null, 'designation', 'en').toArray() }; } finally { S.close(); } + }; + const base = search(sct); + expect(base.index).toBe('WordIndex'); + expect(base.hits.length).toBeGreaterThan(0); + const stem = search(changed(sct, 'sct-stem.db', (db) => db.exec(`UPDATE meta SET value = json_set(value, '$.en', 'snowball:english') WHERE key = 'ix.ix_word.stemmers'`), { refinish: true })); + expect(stem.state).toMatchObject({ used: false, reason: expect.stringMatching(/language en: stemmer snowball:english/) }); + expect(stem.index).toBe('MemoryTextIndex'); + expect(stem.hits).toEqual(base.hits); + const scope = search(changed(sct, 'sct-scope.db', (db) => db.exec("UPDATE meta SET value = 'loinc' WHERE key = 'ix.ix_word.scope'"), { refinish: true })); + expect(scope.state).toMatchObject({ used: false, reason: expect.stringMatching(/scope loinc/) }); + expect(scope.index).toBe('MemoryTextIndex'); + expect(scope.hits).toEqual(base.hits); + // a file without requires uses its stored index as before + const old = search(changed(sct, 'sct-old.db', preRequires)); + expect(old.index).toBe('WordIndex'); + }); +}); + +describe('the builder checks the contracts before it finishes a file', () => { + /** an unfinished build (finish without vacuum), changed, then finished: the error vacuumFile throws */ + const broken = (name, fn) => { + const f = path.join(dir, name); + build(f, { vacuum: false }); + const db = new Database(f); + try { fn(db); } finally { db.close(); } + let err = null; + try { vacuumFile(f); } catch (e) { err = e; } + return err; + }; + + test('an unchanged build finishes', () => { + expect(broken('fine.db', () => {})).toBeNull(); + openStore(path.join(dir, 'fine.db'), { unregistered: true }).close(); + }); + + test('a kind 4 set that contains its anchor', () => { + const e = broken('anchor.db', (db) => { + const r = db.prepare('SELECT value, data FROM ix_set WHERE kind = 4 LIMIT 1').get(); + const bm = RoaringBitmap32.deserialize(r.data, 'portable'); + bm.add(r.value); + db.prepare('UPDATE ix_set SET data = ?, card = ? WHERE kind = 4 AND value = ?').run(Buffer.from(bm.serialize('portable')), bm.size, r.value); + }); + expect(e && e.message).toMatch(/contract: the descendants of concept \d+ \(ix_set kind 4\) include the concept itself/); + }); + + test('ix_in without every link of a by_target property', () => { + const e = broken('ixin.db', (db) => db.exec('DELETE FROM ix_in WHERE (target_id, subject_id) = (SELECT target_id, subject_id FROM ix_in LIMIT 1)')); + expect(e && e.message).toMatch(/contract: ix_in does not hold exactly the \d+ links of the by_target properties/); + }); + + test('a second subsumption property', () => { + const e = broken('sub.db', (db) => db.exec("UPDATE property SET subsumption = 1 WHERE code = 'part'")); + expect(e && e.message).toMatch(/contract: more than one property with subsumption = 1/); + }); + + test('an INTEGER identifier value; a set with an id outside 1..N; a short ix_order block; a missing index', () => { + expect(broken('int.db', (db) => db.exec("UPDATE identifier SET value = 123 WHERE value = '123'")).message).toMatch(/contract: an identifier value is not TEXT/); + expect(broken('range.db', (db) => { + const bm = new RoaringBitmap32([1, 2, 99]); + db.prepare('UPDATE ix_set SET data = ?, card = 3 WHERE kind = 4 AND value = (SELECT value FROM ix_set WHERE kind = 4 LIMIT 1)').run(Buffer.from(bm.serialize('portable'))); + }).message).toMatch(/contract: ix_set kind 4 value \d+ holds an id outside 1\.\.5/); + expect(broken('order.db', (db) => db.exec("INSERT INTO ix_order VALUES ('rank', 0, x'00000000')")).message).toMatch(/contract: ix_order rank has 1 entries, not 6/); + expect(broken('index.db', (db) => db.exec('DROP INDEX item_definition')).message).toMatch(/contract: the index item_definition is missing/); + }); +}); From 609f36ee5c773d137a7927424904021c4cfdfb95 Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 13:39:40 -0600 Subject: [PATCH 4/5] sqlite-v2 README: meta keys, integrity facts, word-index facts, contracts The format document states the strictness rule, requires and its known features, the meta key table, the integrity facts and the checks at open, the word-index facts, the contracts and which the builder checks, the remaining behaviour key with where each retired key's rule now lives, and the removed columns. Co-Authored-By: Claude --- tx/sqlite-v2/README.md | 209 ++++++++++++++++++++++++++++++++++------- 1 file changed, 174 insertions(+), 35 deletions(-) diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 994b4d44..105ed1ab 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -3,7 +3,8 @@ 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`. +and `PRAGMA user_version = 1`. The file states facts about terminology content; how a server presents +a system is that server's rule for the system (`dialects.js`), not something the file says. ## The model @@ -41,9 +42,9 @@ A file holds one code system version as **nodes**, a **catalog** and **statement 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. +- **Meta.** A closed list of keys (below): a reader refuses a file with a key it does not know, a + malformed value, or a required feature (`requires`) it does not know. A finished file states + integrity facts that a reader checks at open. ## Tables @@ -51,20 +52,20 @@ Fact tables: | table | holds | |---|---| -| `code_system` | the served system (`served = 1`; other rows only for sources that contribute items): uri, version, name, title, description, release date, content, case sensitivity, hierarchy meaning, default language, `compositional` (codes may be expressions: no expansion is closed), counts, `resource` (a CodeSystem resource without concepts, where there is one) | -| `meta` | release facts with no column (`displayContexts`, `moduleDependencies`, `languages`, `edition`, `titles`), the format, provenance (`provenance.*`: importer, sources with sha256, timings), facts about indexes (`ix..`), behaviour settings (`behaviour.*`) | +| `code_system` | the served system (`served = 1`; other rows only for sources that contribute items): uri, version, name, title, description, content, default language, `compositional` (codes may be expressions: no expansion is closed), counts, `resource` (a CodeSystem resource without concepts, where there is one). Codes are always case-sensitive: matched exactly | +| `meta` | the closed list of keys under "Meta keys": the format, `requires`, `integrity`, release facts with no column (`languages`, `displayContexts`, `moduleDependencies`, `edition`, `titles`), `derived-by-importer`, facts about indexes (`ix.
.`), `behaviour.grammar`, and provenance (`provenance.*`: importer, sources with sha256, timings, normal-form statistics) | | `concept` | id, code, active, display (derived) | | `item` | id (> N), concept, kind (0 term, 1 definition), external id (description SCTID, RXAUI: INTEGER when a canonical decimal integer, else TEXT), language, use, text, active, preferred (the source's own flag), rank (derived display order). A definition is a designation too only when it has a use. An inactive item is still a designation of its concept: RxNorm stores an archived concept's RXNATOMARCHIVE atoms with `active = 0`, and they are that concept's designations | | `item_use` | the uses (SNOMED CT description types, LOINC name kinds, RxNorm TTYs) | | `property`, `property_member` | the catalog; a union property's members | | `link` | subject, property, role group, target, active, seq (source order) | | `literal` | subject, property, role group, value, active | -| `identifier` | property (the scheme), value (INTEGER when a canonical decimal integer, else TEXT; compared as text), subject, `resolves`: 0 not a code; 1 an alias, accepted as a code and answered with the subject's own code (ICD-11 short codes); 2 a code in its own right, answered as written (NDC 11-digit forms). A concept code always wins over an identifier with the same value. A probe for codes that are identifiers says `resolves > 0` as well as `value = ?`: only then does SQLite use the partial index `identifier_code` (the readers' probes do); without it the probe scans every identifier row. The catalog's `by_subject` says which properties' rows are also read by subject (`ix_by_subject`) | +| `identifier` | property (the scheme), value (TEXT: feature `identifier-text`; a file without `requires` may hold INTEGER for a canonical decimal integer), 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) | +| `node_extra` | FHIR extensions of a node, for round trip (none of the three systems has one; package-store files write and read it) | Index tables (rebuildable): @@ -73,35 +74,164 @@ 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` | per-concept arrays (little-endian u32) in 1,024-entry blocks 0..k, all full but the last: `rank`, `ids` (the system order, N+1 entries each), `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: word, stem, concept bitmap; the row with word `''` and stem `''` holds per-concept word counts (unsigned 16-bit little-endian by concept id 0..N). Facts in meta `ix.ix_word.*` ("Word index facts") | | `ix_text_display`, `ix_text_item` | FTS5 trigram indexes over displays and item texts (regex prefilter) | -## Behaviour settings - -`meta` keys `behaviour.`, JSON values. A key that is absent has its default. A reader refuses a -file with a key or value it does not know (the importers check the same at build). - -| key | values | default | written by | -|---|---|---|---| -| `grammar` | `"snomed"`, `"icd11"`, `null` | `null` (plain codes) | SNOMED CT: `"snomed"` (expressions, ECL; the SNOMED CT provider). ICD-11 MMS and ICF files: `"icd11"` (postcoordinated expressions, bound over the `postcoordinationAxis` and `postcoordinationRoot` records) | -| `expansionOrder` | `"ids"`, `"stored"`, `"stored-self-first"` | `"ids"` | SNOMED CT `"stored-self-first"`; LOINC, RxNorm `"stored"`; NDC files `"stored"` (every selection, filtered or not, in `ix_order` `rank`) | -| `lookupName` | `"name"`, `"title"` | `"name"` | LOINC `"title"` | -| `description` | `"name"`, `"title"` | `"title"` | LOINC `"name"` | -| `versionAlgorithm` | a string, `null` | `null` | LOINC `"natural"`, RxNorm `"date"` | -| `designationUses` | `"keep"`, `"drop"` | `"keep"` | RxNorm `"drop"` | -| `distinctDesignationTexts` | `true`, `false` | `false` | RxNorm `true` (each atom text once, as cs-rxnorm.js) | -| `lookupSkipsMixedLinks` | `true`, `false` | `false` | SNOMED CT `true`: a `both` attribute's links are not read where no property is named (main keeps one value kind per attribute) | -| `aliasProperty` | a property code, `null` | `null` | ICD-11 MMS and ICF files `"classificationCode"`: $validate-code of a code written in its canonical form also returns its alias (an identifier with `resolves = 1`) as an output parameter of this name | -| `aliasExtension` | a URL, `null` | `null` | ICD-11 files: a Coding extension that restates the alias form of its code; $validate-code checks it against the code's alias (an error where the file has no `aliasProperty`, or the code is not in canonical form, has no alias, or the value is not its alias) | -| `preferredForLanguage` | `true`, `false` | `false` | ICD-11 and NDC files `true`: a designation whose item has `preferred = 1` and no use is reported with the use `preferredForLanguage` (`http://terminology.hl7.org/CodeSystem/hl7TermMaintInfra`) in its own language; other designations keep their stored use | -| `aliasLiterals` | an object, property code -> value | `{}` | NDC files `{"code-type": "11-digit", "synonym": "{code}"}`: a concept read through an identifier code (`resolves` 1 or 2) reports these literal values instead of its stored values of those properties; `{code}` is the concept's own code | -| `filters` | a list, `null` | `null` (every property with `filterable = 1`, with its `filter_ops`, and the server's built-in filters) | NDC files: the only filters the system understands, as FHIR CodeSystem.filter: `{"code", "operator": [...], "values": [...]}`; `values` (optional) lists the only values a filter accepts (each item of an `in` list). Any other filter, operator or value is FILTER_NOT_UNDERSTOOD. `code` names a catalog property, or `inactive` (FHIR's concept status: `= true` the inactive concepts, `= false` the active ones) | - -Release facts in `meta` that a reader also presents: `titles` (JSON object, language -> the system's -title in that language; ICD-11 files). With `lookupName` = `"title"`, $lookup reports the title in the -first requested language that has one (by primary subtag), else `code_system.title`. +## Meta keys + +**The rule.** `meta` is a closed vocabulary. A reader knows every key listed below and refuses a file +that has any other key, with a message naming the key. The one open namespace is `provenance.`: +those keys are informational, never read, and any of them may appear. A reader checks the value of +every listed key and refuses a malformed value (it does not treat it as absent). The builder runs the +same check (`meta.js` `readFileMeta`) on what it writes. + +**`requires`** (JSON list of distinct strings): the features beyond the base format that the file's +content uses. A reader refuses a file whose `requires` names a feature it does not know, with a message +naming it. The known features: + +| feature | meaning | written by | +|---|---|---| +| `identifier-text` | every `identifier.value` is TEXT; a reader probes identifiers with text values | every writer, every file (also a file with no identifier rows) | + +**Files without `requires`** were written before it existed. A reader accepts them, and for such a file +only (`readFileMeta` is the one place that decides it): + +- `integrity`, `ix.ix_word.stemmers` and `ix.ix_word.scope` are absent and not checked; the stored word + index is used when `ix.ix_word.format` is `text-match/1`; +- `identifier.value` may be INTEGER (a canonical decimal integer) or TEXT; probes bind a canonical + decimal as INTEGER and anything else as TEXT; +- the retired keys are accepted and ignored: `behaviour.` for every key but `grammar`, + `linkOrder`, `searchTieBreak`, `ix.ix_key.normalForm.stats`. + +A file with `requires` carries `integrity`, and `ix.ix_word.stemmers` and `ix.ix_word.scope` whenever it +carries `ix.ix_word.format`. A retired key in such a file is an unknown key (refused). + +The keys (any other key outside `provenance.` is refused): + +| key | value | present | +|---|---|---| +| `format` | `tx-terminology/1` (checked first) | always | +| `requires` | JSON list of feature names | every file written from now on | +| `integrity` | JSON object ("Integrity facts") | with `requires` | +| `languages` | JSON list of language tags: the served system's item languages, in order of first appearance | always written | +| `displayContexts` | JSON `{"relations": [codes], "preferred": code, "use": {"system", "code"}}` | SNOMED CT | +| `moduleDependencies` | JSON `[[module, dependency, sourceEffectiveTime, targetEffectiveTime]]`, strings | SNOMED CT | +| `edition` | text: the SNOMED CT edition module | SNOMED CT | +| `titles` | JSON object, language -> the system's title in that language | ICD-11 | +| `derived-by-importer` | JSON `[{"table", "name"}]` | when an importer wrote ix rows (kept at an index rebuild) | +| `ix.ix_word.format` | `text-match/1` (another value: the stored word index is not used) | with ix_word rows | +| `ix.ix_word.stemmers` | JSON object: language (primary subtag of every ix_word language) -> stemmer name | with `ix.ix_word.format` (files with `requires`) | +| `ix.ix_word.scope` | `snomed`, `loinc` or `rxnorm`: which names the word index holds | with `ix.ix_word.format` (files with `requires`) | +| `ix.ix_order.walk.reached` | decimal integer: how many concepts the walk reaches | when a walk is stored | +| `behaviour.grammar` | JSON `"snomed"`, `"icd11"` or `null` ("Behaviour") | SNOMED CT, ICD-11 MMS and ICF | +| `provenance.*` | anything | informational: importer, builtAt, sources (with sha256), timings, `normalFormStats` (SNOMED CT normal forms) | + +## Integrity facts + +`meta` `integrity` = JSON `{"items": M, "schema": "", "catalog": ""}`, written by +the step that finishes a file (the builder's `finishFile`: at the end of `finish()`, or in `vacuumFile()` +after an importer's derived-by-importer rows; `indexes.js ` after a rebuild), after every other +table, meta row and ANALYZE. A tool that rewrites a finished file writes it again (`finishFile`). + +- `items`: the number of `item` rows. Item ids are exactly N+1 .. N+M (N = `concept_count`). +- `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 of the table in `PRAGMA table_info` order as SQLite's `quote(column)`, joined + by `,` (in SQL: `SELECT quote("c1")||','||quote("c2")... FROM t ORDER BY ...`); all rows of all tables + joined by LF, no trailing LF. + +A reader checks a file with `requires` at open (`integrity.js`); each failure refuses the file with a +message naming the check. No check reads more than the catalog tables and a few index pages. + +| check | catches | +|---|---| +| 1. the file length equals `page_count * page_size` | truncation, appended bytes | +| 2. `schema` equals the recomputed digest | a changed table, column or index | +| 3. `catalog` equals the recomputed digest | a hand-edited catalog, meta or code_system | +| 4. `min(concept.id) = 1`, `max(concept.id) = N`; concept A (= `active_count`) is active when A > 0, concept A+1 inactive when A < N | concept rows that do not match the counts | +| 5. `min(item.id) = N+1`, `max(item.id) = N+M` (no rows when M = 0) | item rows that do not match `items` | +| 6. `ix_set` kind 1 (property 0, value 0, value kind 0) has `card = N`, kind 2 `card = A` | indexes rebuilt from other facts | + +## Word index facts + +- `ix.ix_word.scope` names which names the word index holds (a reader's text search for the system + reads the same names, `text-index.js` `eachSearchName`): + - `snomed`: the active items of the served system that are designations (kind 0, or a use), each in + its language's primary subtag (NULL language: the code system's default language); with the + per-concept counts row; + - `loinc`: every concept display (as `en`) and every item of the served system whose use is not + RELATEDNAMES2 and whose text is not empty, each in its primary subtag (NULL: the default language); + - `rxnorm`: every item of the concepts that have a SUPPRESS literal, as `en`. +- `ix.ix_word.stemmers`: for every language of the word index, the stemmer that made its `stem` + column. Names: `none` (stem = word); `natural:` for a stemmer class of the `natural` package + (this server's: `natural:PorterStemmer` for en, `natural:PorterStemmerDe`, `...Es`, `...Fa`, `...Fr`, + `natural:StemmerId`, `...It`, `...No` (nb, nn, no), `...Nl`, `...Pt`, `...Ru`, `...Sv`, `...Uk`; + `tx/library/text-match.js` `stemmerName`); another writer may record `snowball:` for a + Snowball algorithm (`snowball:german`, `spanish`, ...). +- A reader uses the stored word index only when `ix.ix_word.format` is `text-match/1` and, in a file + with `requires`, `ix.ix_word.scope` is the scope its text search reads for the system and every + entry of `ix.ix_word.stemmers` (and every language of the index) names the reader's own stemmer for + that language: otherwise a stored stem may not equal the query's stem, and a match would be + missed. Otherwise it builds the index in memory on the first search (`store.js` `wordIndexState`). +- The counts row (word `''`, stem `''`): per concept id 0..N an unsigned 16-bit count, + little-endian, so `length(ids) = 2 * (N + 1)`. Written and read little-endian on every host (files + without `requires` were written in host order on little-endian hosts: the same bytes). + +## Contracts + +What every file keeps, and which of them the builder checks before it finishes a file +(`builder.js` `checkContracts`, after the derived-by-importer rows; a broken one throws `contract: ...`): + +| contract | checked by the builder | +|---|---| +| concept ids are exactly 1..N, N = `concept_count`; concepts 1..A active, A+1..N inactive | yes | +| item ids are exactly N+1..N+M, in one id space with concepts | yes | +| at most one property with `subsumption = 1` (the hierarchy) | yes | +| at most one `ordered = 1` link property (the list property) | yes | +| codes are unique per system and matched exactly (binary, case-sensitive) | yes (the unique index `concept_code`) | +| `identifier.value` is TEXT | yes | +| `ix_set` kinds 1, 2, 3 have property_id 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 contain `value` | yes (every kind 4 set decoded) | +| `ix_set` bitmaps hold concept ids only (1..N) | yes (kinds 1, 2 and 4 decoded; kinds 1 and 2 have N and A members) | +| `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, blocks 0..k of 1,024 entries, all full but the last; `rank` and `ids` have N+1 entries; `walk` and `active` at most N; `ix.ix_order.walk.reached` at most the walk's length | yes | +| the `ix_word` counts row is 2*(N+1) bytes; every `ix_word` language has an `ix.ix_word.stemmers` entry | yes | +| a record's `fields` is a JSON array in the order of the relation's non-target fields (positional) | stated (not checked: it needs a JSON parse of every record row) | +| a record with no `target_id` whose relation has a target field holds the target value as the last element of `fields` | stated (not checked, as above) | +| ancestors are numbered before descendants | not a contract (no reader relies on it; the builder numbers them so for compact sets) | +| the secondary indexes of the schema exist; `sqlite_stat1` exists, `sqlite_stat4` does not | yes | +| meta follows "Meta keys" (keys, values, `requires`) | yes (the builder runs the reader's meta check) | + +## Behaviour + +Only `behaviour.grammar` remains: the grammar of the system's codes, a fact about the content. +`"snomed"`: codes are SNOMED CT expressions and ECL applies (this server serves the file with the +SNOMED CT provider); `"icd11"`: codes may be ICD-11 postcoordinated expressions over the +`postcoordinationAxis` / `postcoordinationRoot` records; absent or `null`: plain codes. A reader that +does not implement a file's grammar refuses the file: this server refuses `"icd11"`. + +Retired keys (they told a server how to present the system; this server keeps each rule in code, by +system). A file without `requires` may still carry them (with the values below); they are ignored. + +| retired key | where the rule is now | +|---|---| +| `expansionOrder` | `dialects.js` `expansionOrder`: SNOMED CT `stored-self-first`; LOINC and RxNorm `stored`; any other system `stored` when the file has an `ix_order` `rank` (the content fact), else `ids` | +| `lookupName`, `description` | `dialects.js`: LOINC lookup name the title, description the name; RxNorm and others lookup name the name, description the title; SNOMED CT: the SNOMED CT provider (`snomed.js`) | +| `versionAlgorithm` | `dialects.js`: LOINC `natural`, RxNorm `date`, others none; SNOMED CT `url` (`snomed.js`) | +| `designationUses` | `dialects.js`: RxNorm `drop` (no designation reports its use) | +| `distinctDesignationTexts` | `dialects.js`: RxNorm (each atom text once) | +| `lookupSkipsMixedLinks` | `store.js`: grammar `snomed` (a `both` attribute's links are not read where no property is named) | +| `aliasProperty`, `aliasExtension`, `preferredForLanguage`, `aliasLiterals`, `filters` | not used by this server (systems it does not serve from a file) | + +`linkOrder`, `searchTieBreak` and `ix.ix_key.normalForm.stats` (now `provenance.normalFormStats`) are +retired the same way. 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; @@ -109,6 +239,14 @@ 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`). +## Removed columns + +`property.n_rows`, `property.target_kind`, `code_system.release_date`, `code_system.hierarchy_meaning` +and `code_system.case_sensitive` are not in the schema any more (no reader used them; codes are always +case-sensitive: matched exactly). Files that have them still open: readers read columns by name. +Kept: `property.by_subject` (it says which identifier rows `ix_by_subject` holds; the index builder +reads it at every rebuild) and the table `node_extra` (as it is). + ## How each terminology maps | source | becomes | @@ -174,7 +312,8 @@ reads it from the cache) and `-y, --yes` to replace an existing destination; see `snomed-v2-from-cache` and `loinc-v2-classic` reverse-load the files main's providers use, for releases that are not at hand. Every importer stages into `.stage` beside the destination, -then numbers the concepts, writes the fact tables in key order, builds the indexes, and VACUUMs. +then numbers the concepts, writes the fact tables in key order, builds the indexes, finishes the +file (checks the contracts, writes `integrity`) and VACUUMs. `tx/importers/sqlite-v2/diff.js A.db B.db` compares two files by codes (the reverse loaders are checked against release builds with it); `verify-indexes.js ` drops and rebuilds every index table and compares. From 7d3f8c5aea465f4a54c08e3929618f523d7fb3cc Mon Sep 17 00:00:00 2001 From: Josh Mandel Date: Thu, 3 Dec 2026 15:52:23 -0600 Subject: [PATCH 5/5] sqlite-v2: grammar cpt; behaviour.filters stays a format key behaviour.grammar gains "cpt": codes may be written :[:...], the modifier rules being the grammar's. This reader does not implement it and refuses such a file, as for icd11. behaviour.filters is a format key again (no longer retired), in files with and without requires: null, or the only filters the system understands as FHIR CodeSystem.filter [{code, operator, values?}], where code is a catalog property, inactive, or a filter the file's grammar defines. A malformed value is refused. This reader does not apply such a list, and the generic provider could otherwise serve a file that carries one, so it refuses the file; the README says a reader that serves such a file must apply it. Co-Authored-By: Claude --- tests/tx/sqlite-v2-format-integrity.test.js | 47 ++++++++++++++++++++- tx/importers/sqlite-v2/schema.sql | 4 +- tx/sqlite-v2/README.md | 22 +++++----- tx/sqlite-v2/meta.js | 20 ++++++--- tx/sqlite-v2/store.js | 8 +++- 5 files changed, 83 insertions(+), 18 deletions(-) diff --git a/tests/tx/sqlite-v2-format-integrity.test.js b/tests/tx/sqlite-v2-format-integrity.test.js index 89ed0189..9bf8443b 100644 --- a/tests/tx/sqlite-v2-format-integrity.test.js +++ b/tests/tx/sqlite-v2-format-integrity.test.js @@ -131,11 +131,56 @@ describe('meta: the closed key list and requires', () => { .toThrow(/grammar icd11 \(behaviour.grammar\), which this server does not implement/); expect(() => openStore(changed(file, 'icd-old.db', (db) => { preRequires(db); db.exec(`INSERT INTO meta VALUES ('behaviour.grammar', '"icd11"')`); }))) .toThrow(/does not implement/); - expect(() => openStore(changed(file, 'gram.db', (db) => db.exec(`INSERT INTO meta VALUES ('behaviour.grammar', '"cpt"')`)))) + expect(() => openStore(changed(file, 'gram.db', (db) => db.exec(`INSERT INTO meta VALUES ('behaviour.grammar', '"loinc"')`)))) .toThrow(/meta behaviour.grammar has a malformed value/); }); }); +describe('behaviour: grammar and filters', () => { + const MODIFIED = [{ code: 'modified', operator: ['='], values: ['true', 'false'] }, { code: 'inactive', operator: ['='] }]; + + test('grammar cpt: a grammar this reader does not implement: the file is written and checked, then refused to serve', () => { + const f = path.join(dir, 'cpt.db'); + const b = new TerminologyBuilder(f, { overwrite: true, importer: 'test' }); + b.codeSystem({ uri: 'http://example.org/modifiers', version: '1' }); + b.concept('a'); + b.setBehaviour('grammar', 'cpt'); + b.setBehaviour('filters', MODIFIED); + b.finish(); + const db = new Database(f, { readonly: true }); + try { + const m = readFileMeta(db.prepare('SELECT key, value FROM meta').raw().all(), f); + expect([m.preRequires, m.grammar, m.filters]).toEqual([false, 'cpt', MODIFIED]); + } finally { db.close(); } + expect(() => openStore(f)).toThrow(/grammar cpt \(behaviour.grammar\), which this server does not implement/); + }); + + test('filters: accepted in a file with requires (a grammar-defined code) and in one without; this reader refuses to serve a restricted list', () => { + const f = changed(file, 'filters.db', (db) => db.prepare("INSERT INTO meta VALUES ('behaviour.filters', ?)").run(JSON.stringify(MODIFIED)), { refinish: true }); + const db = new Database(f, { readonly: true }); + try { + expect(readFileMeta(db.prepare('SELECT key, value FROM meta').raw().all(), f).filters).toEqual(MODIFIED); + } finally { db.close(); } + expect(() => openStore(f)).toThrow(/restricts the filters the system understands \(behaviour.filters\), which this server does not apply/); + const old = changed(file, 'filters-old.db', (db) => { preRequires(db); db.prepare("INSERT INTO meta VALUES ('behaviour.filters', ?)").run(JSON.stringify(MODIFIED)); }); + expect(() => openStore(old)).toThrow(/behaviour.filters\), which this server does not apply/); + // null: no restriction + const none = changed(file, 'filters-null.db', (db) => db.exec("INSERT INTO meta VALUES ('behaviour.filters', 'null')"), { refinish: true }); + openStore(none, { unregistered: true }).close(); + }); + + test('a malformed filters value is refused, in a file with requires or without', () => { + const meta = (v, pre = false) => [['format', 'tx-terminology/1'], ...(pre ? [] : [['requires', '["identifier-text"]'], ['integrity', JSON.stringify({ items: 0, schema: 'a'.repeat(64), catalog: 'b'.repeat(64) })]]), ['behaviour.filters', v]]; + for (const pre of [false, true]) { + for (const bad of ['[{"code": "kind", "operator": ["like"]}]', '[{"code": "kind", "operator": []}]', '[{"code": "kind", "operator": ["="], "values": "product"}]', + '[{"code": "kind", "operator": ["="], "other": 1}]', '{"code": "kind"}', 'modified']) { + expect(() => readFileMeta(meta(bad, pre), 'x')).toThrow(/meta behaviour.filters (has a malformed value|is not JSON)/); + } + expect(readFileMeta(meta('[{"code": "kind", "operator": ["=", "in"], "values": ["product"]}]', pre), 'x').filters).toEqual([{ code: 'kind', operator: ['=', 'in'], values: ['product'] }]); + } + }); +}); + describe('integrity facts: each check at open trips on a changed copy', () => { const trips = (name, fn, msg) => expect(() => openStore(changed(file, name, fn))).toThrow(msg); diff --git a/tx/importers/sqlite-v2/schema.sql b/tx/importers/sqlite-v2/schema.sql index 4387a503..1d219d24 100644 --- a/tx/importers/sqlite-v2/schema.sql +++ b/tx/importers/sqlite-v2/schema.sql @@ -39,7 +39,9 @@ CREATE TABLE code_system ( -- the base format the content uses), integrity (facts checked at open), release facts with no column -- (languages, displayContexts, moduleDependencies, edition, titles), derived-by-importer, facts about -- indexes (ix.ix_word.format / stemmers / scope, ix.ix_order.walk.reached), behaviour.grammar (the --- grammar of the codes), and provenance.* (open: informational, never read). A reader refuses a file +-- grammar of the codes: "snomed", "icd11", "cpt" or null), behaviour.filters (null, or the only +-- filters the system understands, as FHIR CodeSystem.filter), and provenance.* (open: informational, +-- never read). A reader refuses a file -- with any other key, a malformed value of a key it reads, or a required feature it does not know. CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index 105ed1ab..80011807 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -53,7 +53,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, content, default language, `compositional` (codes may be expressions: no expansion is closed), counts, `resource` (a CodeSystem resource without concepts, where there is one). Codes are always case-sensitive: matched exactly | -| `meta` | the closed list of keys under "Meta keys": the format, `requires`, `integrity`, release facts with no column (`languages`, `displayContexts`, `moduleDependencies`, `edition`, `titles`), `derived-by-importer`, facts about indexes (`ix.
.`), `behaviour.grammar`, and provenance (`provenance.*`: importer, sources with sha256, timings, normal-form statistics) | +| `meta` | the closed list of keys under "Meta keys": the format, `requires`, `integrity`, release facts with no column (`languages`, `displayContexts`, `moduleDependencies`, `edition`, `titles`), `derived-by-importer`, facts about indexes (`ix.
.`), `behaviour.grammar`, `behaviour.filters`, and provenance (`provenance.*`: importer, sources with sha256, timings, normal-form statistics) | | `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) | @@ -102,8 +102,8 @@ only (`readFileMeta` is the one place that decides it): index is used when `ix.ix_word.format` is `text-match/1`; - `identifier.value` may be INTEGER (a canonical decimal integer) or TEXT; probes bind a canonical decimal as INTEGER and anything else as TEXT; -- the retired keys are accepted and ignored: `behaviour.` for every key but `grammar`, - `linkOrder`, `searchTieBreak`, `ix.ix_key.normalForm.stats`. +- the retired keys are accepted and ignored: `behaviour.` for every key but `grammar` and + `filters`, `linkOrder`, `searchTieBreak`, `ix.ix_key.normalForm.stats`. A file with `requires` carries `integrity`, and `ix.ix_word.stemmers` and `ix.ix_word.scope` whenever it carries `ix.ix_word.format`. A retired key in such a file is an unknown key (refused). @@ -125,7 +125,8 @@ The keys (any other key outside `provenance.` is refused): | `ix.ix_word.stemmers` | JSON object: language (primary subtag of every ix_word language) -> stemmer name | with `ix.ix_word.format` (files with `requires`) | | `ix.ix_word.scope` | `snomed`, `loinc` or `rxnorm`: which names the word index holds | with `ix.ix_word.format` (files with `requires`) | | `ix.ix_order.walk.reached` | decimal integer: how many concepts the walk reaches | when a walk is stored | -| `behaviour.grammar` | JSON `"snomed"`, `"icd11"` or `null` ("Behaviour") | SNOMED CT, ICD-11 MMS and ICF | +| `behaviour.grammar` | JSON `"snomed"`, `"icd11"`, `"cpt"` or `null` ("Behaviour") | SNOMED CT, ICD-11 MMS and ICF, CPT | +| `behaviour.filters` | JSON `null`, or a list of `{"code", "operator": [...], "values": [...]}` ("Behaviour") | systems that understand only some filters (NDC, CPT) | | `provenance.*` | anything | informational: importer, builtAt, sources (with sha256), timings, `normalFormStats` (SNOMED CT normal forms) | ## Integrity facts @@ -211,11 +212,12 @@ What every file keeps, and which of them the builder checks before it finishes a ## Behaviour -Only `behaviour.grammar` remains: the grammar of the system's codes, a fact about the content. -`"snomed"`: codes are SNOMED CT expressions and ECL applies (this server serves the file with the -SNOMED CT provider); `"icd11"`: codes may be ICD-11 postcoordinated expressions over the -`postcoordinationAxis` / `postcoordinationRoot` records; absent or `null`: plain codes. A reader that -does not implement a file's grammar refuses the file: this server refuses `"icd11"`. +Two `behaviour.*` keys remain, both facts about the content: + +| key | values | meaning | +|---|---|---| +| `grammar` | `"snomed"`, `"icd11"`, `"cpt"`, `null` | the grammar of the system's codes. `"snomed"`: codes are SNOMED CT expressions and ECL applies (this server serves the file with the SNOMED CT provider); `"icd11"`: codes may be ICD-11 postcoordinated expressions over the `postcoordinationAxis` / `postcoordinationRoot` records; `"cpt"`: codes may be written `:[:...]`, the modifier rules being the grammar's (the reader's), not data in the file; absent or `null`: plain codes. A reader that does not implement a file's grammar refuses the file: this server refuses `"icd11"` and `"cpt"` | +| `filters` | `null` (absent), or a list of `{"code", "operator": [...], "values": [...]}` | the only filters the system understands, as FHIR CodeSystem.filter. `operator` lists FHIR filter operators (at least one); `values` (optional) the only values a filter accepts (each item of an `in` list). `code` is a catalog property, `inactive` (concept status: `= true` the inactive concepts, `= false` the active ones), or a filter the file's grammar defines (the CPT grammar: `modified`, operator `=`, values `true` / `false`: `true` selects no stored concept and leaves the selection open, `false` selects every concept). Any other filter, operator or value is FILTER_NOT_UNDERSTOOD. A reader that serves such a file must apply the list; this server does not, and refuses a file that carries one (a file it serves, of any system, could otherwise answer filters the system does not understand) | Retired keys (they told a server how to present the system; this server keeps each rule in code, by system). A file without `requires` may still carry them (with the values below); they are ignored. @@ -228,7 +230,7 @@ system). A file without `requires` may still carry them (with the values below); | `designationUses` | `dialects.js`: RxNorm `drop` (no designation reports its use) | | `distinctDesignationTexts` | `dialects.js`: RxNorm (each atom text once) | | `lookupSkipsMixedLinks` | `store.js`: grammar `snomed` (a `both` attribute's links are not read where no property is named) | -| `aliasProperty`, `aliasExtension`, `preferredForLanguage`, `aliasLiterals`, `filters` | not used by this server (systems it does not serve from a file) | +| `aliasProperty`, `aliasExtension`, `preferredForLanguage`, `aliasLiterals` | not used by this server (systems it does not serve from a file) | `linkOrder`, `searchTieBreak` and `ix.ix_key.normalForm.stats` (now `provenance.normalFormStats`) are retired the same way. diff --git a/tx/sqlite-v2/meta.js b/tx/sqlite-v2/meta.js index 39fe17cc..898c69a7 100644 --- a/tx/sqlite-v2/meta.js +++ b/tx/sqlite-v2/meta.js @@ -20,7 +20,15 @@ const WRITTEN_FEATURES = Object.freeze(['identifier-text']); const WORD_SCOPES = Object.freeze(['snomed', 'loinc', 'rxnorm']); /** the code grammars a file may state (behaviour.grammar) */ -const GRAMMARS = Object.freeze([null, 'snomed', 'icd11']); +const GRAMMARS = Object.freeze([null, 'snomed', 'icd11', 'cpt']); + +/** the FHIR filter operators (behaviour.filters) */ +const FILTER_OPERATORS = Object.freeze(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', 'in', 'not-in', 'generalizes', 'child-of', 'descendent-leaf', 'exists']); + +/** 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)); const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); const isString = (v) => typeof v === 'string'; @@ -52,16 +60,17 @@ const KEYS = Object.freeze({ 'ix.ix_word.scope': text((v) => WORD_SCOPES.includes(v)), 'ix.ix_order.walk.reached': text((v) => DECIMAL.test(v) && Number.isSafeInteger(Number(v))), 'behaviour.grammar': json((v) => GRAMMARS.includes(v)), + 'behaviour.filters': json((v) => v === null || (Array.isArray(v) && v.every(isFilterSpec))), }); /** * Keys a pre-requires file may carry, accepted and ignored there (a file with `requires` that has - * one is refused, as for any unknown key): every behaviour.* key but grammar (they told a server how + * one is refused, as for any unknown key): every behaviour.* key but grammar and filters (they told a server how * to present the system; each server keeps those rules in code, tx/sqlite-v2/dialects.js), * linkOrder, searchTieBreak, and ix.ix_key.normalForm.stats (now provenance.normalFormStats). */ function isRetiredKey(key) { - return (key.startsWith('behaviour.') && key !== 'behaviour.grammar') + return (key.startsWith('behaviour.') && key !== 'behaviour.grammar' && key !== 'behaviour.filters') || key === 'linkOrder' || key === 'searchTieBreak' || key === 'ix.ix_key.normalForm.stats'; } @@ -75,7 +84,7 @@ const isProvenance = (key) => key.startsWith('provenance.'); * @param {string} file the file's name, for messages * @param {object} [opts] { finished: false for a file still being built (the keys its last step * writes may be missing) } - * @returns {{preRequires: boolean, requires: string[]|null, integrity: object|null, grammar: string|null, + * @returns {{preRequires: boolean, requires: string[]|null, integrity: object|null, grammar: string|null, filters: object[]|null, * values: Map}} values: the parsed value of every listed key present (retired keys left out) */ function readFileMeta(meta, file, opts = {}) { @@ -119,8 +128,9 @@ function readFileMeta(meta, file, opts = {}) { requires, integrity: preRequires ? null : (values.get('integrity') || null), grammar: values.has('behaviour.grammar') ? values.get('behaviour.grammar') : null, + filters: values.has('behaviour.filters') ? values.get('behaviour.filters') : null, values, }; } -module.exports = { readFileMeta, isRetiredKey, KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, WORD_SCOPES, GRAMMARS, FORMAT }; +module.exports = { readFileMeta, isRetiredKey, KEYS, KNOWN_FEATURES, WRITTEN_FEATURES, WORD_SCOPES, GRAMMARS, FILTER_OPERATORS, FORMAT }; diff --git a/tx/sqlite-v2/store.js b/tx/sqlite-v2/store.js index 3614ad03..4556a409 100644 --- a/tx/sqlite-v2/store.js +++ b/tx/sqlite-v2/store.js @@ -86,7 +86,10 @@ const FILTER_OPS = new Set(['=', 'is-a', 'descendent-of', 'is-not-a', 'regex', ' const REPORT = new Set([null, 'named', 'always']); /** - * A file's meta, checked (meta.js readFileMeta), and its grammar one this server implements. + * A file's meta, checked (meta.js readFileMeta), and its grammar one this server implements + * ('icd11' and 'cpt' are grammars a file may state that this server does not). A file whose + * behaviour.filters restricts the filters the system understands is refused too: this server does not + * apply such a list, and would answer filters the system does not understand. * opts.finished false: a file still being built (the index builder reads it through a store). */ function checkMeta(meta, file, opts = {}) { @@ -94,6 +97,9 @@ function checkMeta(meta, file, opts = {}) { if (!IMPLEMENTED_GRAMMARS.includes(m.grammar)) { throw new Error(`${file}: its codes have the grammar ${m.grammar} (behaviour.grammar), which this server does not implement`); } + if (m.filters !== null) { + throw new Error(`${file}: it restricts the filters the system understands (behaviour.filters), which this server does not apply`); + } return m; }