diff --git a/rest/README.md b/rest/README.md index 7d0e1268..4d42eb85 100644 --- a/rest/README.md +++ b/rest/README.md @@ -18,6 +18,10 @@ run it. `:iterate`), `_summary`, `_elements`, `_total`, and paging through stored results - `:below` and `:above` on tokens through a closure table, kept up to date with the endpoint's terminology server's `$closure`; `:in` and `:not-in` through its `$expand` +- full-text search: `_text` (the narrative) and `_content` (the whole resource) +- contained resources indexed with their own search parameters, so chains reach into them + and `_contained` / `_containedType` search them; a reference to a contained resource that + isn't there is a 422 - `$meta`, `$meta-add`, `$meta-delete`, and `Patient/[id]/$everything` - AuditEvents for writes (and, if set, reads and failures), stored on the endpoint - a subscription queue (`SubscriptionQueue`), filled by every write; nothing delivers it yet @@ -26,7 +30,7 @@ run it. What search supports, parameter by parameter, is in [search.md](search.md). Not yet: XML, subscription delivery, validation on write, SMART on FHIR, asynchronous -operations, `$lastn`, `_text` and `_content`, FHIRPath Patch, admin pages. +operations, `$lastn`, FHIRPath Patch, admin pages. ## Configuration diff --git a/rest/database/schema.js b/rest/database/schema.js index 9f6c61b6..211e97f3 100644 --- a/rest/database/schema.js +++ b/rest/database/schema.js @@ -20,7 +20,7 @@ * @module rest/database/schema */ -const SCHEMA_VERSION = 1; +const SCHEMA_VERSION = 3; // columns every index table has const INDEX_COMMON = [ @@ -168,6 +168,18 @@ const TABLES = [ } ]; +/** + * Contained resources that their container refers to: each is indexed with its own type's + * search parameters, under the key -ContainedKey (negative, so it can never be a resource's key: + * chains reach it through IndexReferences.TargetKey, and nothing that looks in Ids finds it). + * Made at schema version 3, so not in TABLES. + */ +const CONTAINED_TABLE = { + name: 'Contained', + columns: [['ContainedKey', 'key'], ['ResourceKey', 'bigint', { notNull: true }], ['TypeKey', 'bigint'], ['LocalId', 'str(64)', { notNull: true }]], + indexes: [{ name: 'SK_Contained_Resource', columns: ['ResourceKey'] }] +}; + const INDEX_TABLES = ['IndexStrings', 'IndexTokens', 'IndexDates', 'IndexNumbers', 'IndexQuantities', 'IndexReferences', 'IndexUris']; function columnType(type, dialect) { @@ -223,9 +235,33 @@ const MIGRATIONS = { await q.exec(sql); } } + }, + // full-text search (_text, _content): the TextIndex table, which each engine makes its own way + // (indexing/fulltext.js). Resources already there are reindexed in the background to fill it + 2: async (q) => { + for (const sql of require('../indexing/fulltext').ddl(q.dialect.name)) { + await q.exec(sql); + } + await flagReindexAll(q); + }, + // contained resources: indexed with their own search parameters, so chains reach into them + 3: async (q) => { + for (const sql of tableDDL(CONTAINED_TABLE, q.dialect.name)) { + await q.exec(sql); + } + await flagReindexAll(q); } }; +/** Everything already there gets reindexed in the background (Endpoint.reindexBatch) */ +async function flagReindexAll(q) { + const any = await q.get('SELECT ResourceKey FROM Ids WHERE MostRecent IS NOT NULL LIMIT 1'); + const flagged = await q.get("SELECT Value FROM Config WHERE Name = 'reindexAll'"); + if (any && !flagged) { + await q.run("INSERT INTO Config (Name, Value) VALUES ('reindexAll', '1')"); + } +} + async function tableExists(q, name) { if (q.dialect.name === 'sqlite') { const row = await q.get("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?", [name]); @@ -296,4 +332,4 @@ async function waitForSchema(db, timeoutMs = 120000) { } } -module.exports = { SCHEMA_VERSION, TABLES, INDEX_TABLES, tableDDL, migrate, waitForSchema, schemaVersion }; +module.exports = { SCHEMA_VERSION, TABLES, CONTAINED_TABLE, INDEX_TABLES, tableDDL, migrate, waitForSchema, schemaVersion }; diff --git a/rest/endpoint/endpoint.js b/rest/endpoint/endpoint.js index b05f30c6..9b09a5fb 100644 --- a/rest/endpoint/endpoint.js +++ b/rest/endpoint/endpoint.js @@ -187,6 +187,9 @@ class Endpoint { } async apply(loaded) { + // everything is being reindexed (a schema migration added something every resource needs: + // the full-text index at version 2, the Contained table at 3) + this.reindexAll = !!(await this.db.read(q => q.get('SELECT Value FROM Config WHERE Name = ?', ['reindexAll']))); this.generation = loaded.generation; this.settings = loaded.endpoint; this.types = loaded.types; @@ -596,7 +599,7 @@ class Endpoint { * @returns {Promise} how many resources were reindexed */ async reindexBatch() { - if (!this.definitions.reindexing || this.definitions.reindexing.size === 0) { + if ((!this.definitions.reindexing || this.definitions.reindexing.size === 0) && !this.reindexAll) { return 0; } const fromRow = await this.db.read(q => q.get('SELECT Value FROM Config WHERE Name = ?', ['reindexFrom'])); @@ -608,7 +611,7 @@ class Endpoint { const v = await q.get('SELECT v.Compressed, v.Content FROM Ids i JOIN Versions v ON v.VersionKey = i.MostRecent WHERE i.ResourceKey = ? AND i.Deleted = 0', [r.ResourceKey]); const resource = v ? decode(v) : null; if (resource) { - await this.indexer.index(q, { resourceKey: Number(r.ResourceKey), resource, deferChecks: true }); + await this.indexer.index(q, { resourceKey: Number(r.ResourceKey), resource, deferChecks: true, lenient: true }); } } if (rows.length) { @@ -621,11 +624,13 @@ class Endpoint { // done: clear the flags, and tell every process await q.run('UPDATE SearchParams SET Reindex = 0 WHERE Reindex = 1'); await q.run('DELETE FROM Config WHERE Name = ?', ['reindexFrom']); + await q.run('DELETE FROM Config WHERE Name = ?', ['reindexAll']); await settingsStore.bumpGeneration(q); } }); if (!rows.length) { this.definitions.reindexing = new Set(); + this.reindexAll = false; this.log.info(`Rest ${this.path}: reindexing finished`); } return rows.length; diff --git a/rest/indexing/definitions.js b/rest/indexing/definitions.js index 8b2c176b..dd2cca2d 100644 --- a/rest/indexing/definitions.js +++ b/rest/indexing/definitions.js @@ -110,10 +110,14 @@ function fhirpathOptions(model) { target = t ? { resourceType: t } : null; } else if (d && typeof d === 'object') { if (typeof d.reference === 'string' && d.reference.startsWith('#')) { - // a contained resource: the resource itself + // a contained resource: the resource itself; '#' alone is the container const root = rootOf(input); const id = d.reference.substring(1); - target = (root && Array.isArray(root.contained) && root.contained.find(c => c && c.id === id)) || null; + if (!id) { + target = (root && CONTAINERS.get(root)) || root; + } else { + target = (root && Array.isArray(root.contained) && root.contained.find(c => c && c.id === id)) || null; + } } else { const t = d.type || referenceType(d.reference); target = t ? { resourceType: t } : null; @@ -189,6 +193,13 @@ function splitUnion(expression) { return out.filter(x => x); } +/** + * A contained resource being indexed is evaluated as a copy that carries its container's + * contained list (so its own '#id' references find its siblings); this maps that copy to its + * container (so '#' alone finds the container). + */ +const CONTAINERS = new WeakMap(); + function rootOf(node) { let n = node; while (n && n.parentResNode) { @@ -488,4 +499,4 @@ class Definitions { } } -module.exports = { forEvaluation, splitUnion, Definitions, deriveDefinitions, loadDerived, corePackage, majorMinor, referenceType, SPECIAL_PARAMS, modelFor }; +module.exports = { CONTAINERS, forEvaluation, splitUnion, Definitions, deriveDefinitions, loadDerived, corePackage, majorMinor, referenceType, SPECIAL_PARAMS, modelFor }; diff --git a/rest/indexing/fulltext.js b/rest/indexing/fulltext.js new file mode 100644 index 00000000..c6deb5d6 --- /dev/null +++ b/rest/indexing/fulltext.js @@ -0,0 +1,366 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * Full-text search: _text (the narrative) and _content (the whole resource). + * + * Each resource has a row in TextIndex with two columns: Narrative, the text of text.div with + * the markup taken out, and Content, every string in the resource (the narrative's text + * included, base64 data left out). Both are normalised as string search values are (accents + * and case folded), so the engines' own folding doesn't matter, and both are written in the + * resource's write transaction, as the other index rows are. + * + * SQLite an FTS5 table (rowid = ResourceKey), searched with MATCH + * MySQL an InnoDB table with a FULLTEXT index on each column, searched with + * MATCH ... AGAINST in boolean mode + * + * The search value is never handed to the engine as it is: it is parsed (words, "phrases", + * AND, OR, NOT or a leading -, brackets) and written out again in each engine's syntax, with + * only letters and digits inside the terms. A word matches as a prefix (chalm finds Chalmers); + * a phrase matches as it is. + * + * @module rest/indexing/fulltext + */ + +const { badRequest } = require('../library/errors'); +const { normalise } = require('./values'); + +// the most text kept for a resource's column (characters) +const MAX_TEXT = 1000000; +// the longest search value, and the most terms in it +const MAX_QUERY = 1000; +const MAX_TERMS = 32; + +// ---- the text ---- + +const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: ' ' }; + +function decodeEntities(s) { + return s.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-zA-Z]{2,8});/g, (m, e) => { + if (e[0] === '#') { + const n = e[1] === 'x' || e[1] === 'X' ? parseInt(e.substring(2), 16) : parseInt(e.substring(1), 10); + return n > 0 && n <= 0x10FFFF ? String.fromCodePoint(n) : ' '; + } + return ENTITIES[e.toLowerCase()] || ' '; + }); +} + +/** + * The words of a narrative: the markup taken out (by a scan, not a pattern that could + * backtrack on a long run of '<'), entities decoded. + * @param {string} div + * @returns {string} + */ +function narrativeText(div) { + if (typeof div !== 'string' || !div) { + return ''; + } + let out = ''; + let i = 0; + for (;;) { + const lt = div.indexOf('<', i); + if (lt < 0) { + out += div.substring(i); + break; + } + out += div.substring(i, lt) + ' '; + const gt = div.indexOf('>', lt); + if (gt < 0) { + break; + } + i = gt + 1; + } + return decodeEntities(out).replace(/\s+/g, ' ').trim(); +} + +/** + * Every string in a resource (and the narrative's text), but not base64 data, not the + * narrative's markup, and not the names of the elements. + * @param {Object} resource + * @returns {string} + */ +function contentText(resource) { + const parts = []; + let size = 0; + const walk = (v, key) => { + if (size > MAX_TEXT) { + return; + } + if (typeof v === 'string') { + if (key === 'div') { + v = narrativeText(v); + } else if (key === 'data' || key === 'resourceType') { + return; + } + parts.push(v); + size += v.length + 1; + } else if (typeof v === 'number' || typeof v === 'boolean') { + if (key !== 'versionId') { + parts.push(String(v)); + size += 8; + } + } else if (Array.isArray(v)) { + for (const x of v) { + walk(x, key); + } + } else if (v && typeof v === 'object') { + for (const [k, x] of Object.entries(v)) { + if (k !== 'meta') { + walk(x, k); + } + } + } + }; + walk(resource, null); + return parts.join(' '); +} + +/** Text as it is stored and searched: normalised, as string search values are */ +function folded(text) { + return normalise(text).substring(0, MAX_TEXT); +} + +// ---- the search value ---- + +/** + * The words in a piece of text, as the index splits it (letters and digits). + * @param {string} text + * @returns {string[]} + */ +function words(text) { + return folded(text).split(/[^\p{L}\p{N}]+/u).filter(w => w); +} + +function lex(value) { + const tokens = []; + let i = 0; + while (i < value.length) { + const c = value[i]; + if (/\s/.test(c)) { + i++; + } else if (c === '(' || c === ')') { + tokens.push({ t: c }); + i++; + } else if (c === '"') { + const close = value.indexOf('"', i + 1); + if (close < 0) { + throw badRequest('_text/_content: a quoted phrase is not closed'); + } + tokens.push({ t: 'phrase', v: value.substring(i + 1, close) }); + i = close + 1; + } else if (c === '-' && i + 1 < value.length && !/\s/.test(value[i + 1])) { + tokens.push({ t: 'NOT' }); + i++; + } else { + let j = i; + while (j < value.length && !/[\s()"]/.test(value[j])) { + j++; + } + const w = value.substring(i, j); + if (w === 'AND' || w === 'OR' || w === 'NOT') { + tokens.push({ t: w }); + } else { + tokens.push({ t: 'word', v: w }); + } + i = j; + } + } + return tokens; +} + +/** + * Parse a _text or _content value into a tree: + * { op: 'or', items } { op: 'and', items } { op: 'not', item } { op: 'term', words, prefix } + * Terms next to each other are AND'd; OR binds more loosely than AND; NOT (or -) applies to the + * term or bracket after it. + * @param {string} value + */ +function parseQuery(value) { + if (typeof value !== 'string' || !value.trim()) { + throw badRequest('_text/_content needs some words to search for'); + } + if (value.length > MAX_QUERY) { + throw badRequest(`_text/_content is limited to ${MAX_QUERY} characters`); + } + const tokens = lex(value); + let pos = 0; + let terms = 0; + const peek = () => tokens[pos]; + const orExpr = (depth) => { + if (depth > 10) { + throw badRequest('_text/_content: brackets nested too deeply'); + } + const items = [andExpr(depth)]; + while (peek() && peek().t === 'OR') { + pos++; + items.push(andExpr(depth)); + } + return items.length === 1 ? items[0] : { op: 'or', items }; + }; + const andExpr = (depth) => { + const items = [unary(depth)]; + while (peek() && peek().t !== 'OR' && peek().t !== ')') { + if (peek().t === 'AND') { + pos++; + } + items.push(unary(depth)); + } + return items.length === 1 ? items[0] : { op: 'and', items }; + }; + const unary = (depth) => { + const tok = tokens[pos++]; + if (!tok) { + throw badRequest('_text/_content: the expression is incomplete'); + } + if (tok.t === 'NOT') { + return { op: 'not', item: unary(depth) }; + } + if (tok.t === '(') { + const e = orExpr(depth + 1); + if (!peek() || peek().t !== ')') { + throw badRequest('_text/_content: a bracket is not closed'); + } + pos++; + return e; + } + if (tok.t === 'word' || tok.t === 'phrase') { + const w = words(tok.v); + if (!w.length) { + throw badRequest(`_text/_content: '${tok.v}' has no letters or digits to search for`); + } + if (++terms > MAX_TERMS) { + throw badRequest(`_text/_content is limited to ${MAX_TERMS} words and phrases`); + } + // one word is a prefix; a phrase, or a word the index splits (a@b.org), is matched as it is + return { op: 'term', words: w, prefix: tok.t === 'word' && w.length === 1 }; + } + throw badRequest(`_text/_content: unexpected '${tok.t}'`); + }; + const tree = orExpr(0); + if (pos < tokens.length) { + throw badRequest(`_text/_content: unexpected '${tokens[pos].t === 'word' ? tokens[pos].v : tokens[pos].t}'`); + } + checkPositive(tree); + return tree; +} + +/** Every branch must find something: NOT on its own (or everything negated) can't be searched */ +function checkPositive(node) { + const positive = (n) => { + switch (n.op) { + case 'term': return true; + case 'not': return false; + case 'and': return n.items.some(positive); + case 'or': return n.items.every(positive); + } + return false; + }; + if (!positive(node)) { + throw badRequest('_text/_content: each part of the search needs a word that isn\'t negated'); + } +} + +// ---- each engine's syntax ---- + +/** FTS5: "w"* for a word, "w1 w2" for a phrase; AND, OR, NOT as binary operators */ +function fts5(node) { + switch (node.op) { + case 'term': + return node.prefix ? `"${node.words[0]}"*` : `"${node.words.join(' ')}"`; + case 'or': + return '(' + node.items.map(fts5).join(' OR ') + ')'; + case 'and': { + const pos = node.items.filter(n => n.op !== 'not').map(fts5); + const neg = node.items.filter(n => n.op === 'not').map(n => fts5(n.item)); + let s = '(' + pos.join(' AND ') + ')'; + if (neg.length) { + s += ' NOT (' + neg.join(' OR ') + ')'; + } + return '(' + s + ')'; + } + case 'not': + // only inside an and (checkPositive): a not on its own never reaches here + throw badRequest('_text/_content: NOT needs something to be NOT of'); + } + return ''; +} + +/** + * MySQL boolean mode: +word* required, -word excluded, "phrase"; an OR is a bracket of + * optional parts, of which one must match. + */ +function mysqlBoolean(node, required = true) { + const sign = required ? '+' : ''; + switch (node.op) { + case 'term': + return sign + (node.prefix ? `${node.words[0]}*` : `"${node.words.join(' ')}"`); + case 'or': + return `${sign}(${node.items.map(n => mysqlBoolean(n, false)).join(' ')})`; + case 'and': { + const parts = node.items.map(n => n.op === 'not' ? '-' + mysqlBoolean(n.item, false).replace(/^\+/, '') : mysqlBoolean(n, true)); + return `${sign}(${parts.join(' ')})`; + } + case 'not': + throw badRequest('_text/_content: NOT needs something to be NOT of'); + } + return ''; +} + +/** + * The SQL condition on a resource key for a full-text search. + * @param {string} dialect - 'sqlite' or 'mysql' + * @param {string} key - the resource key expression + * @param {'Narrative'|'Content'} column + * @param {Object} tree - from parseQuery + */ +function condition(dialect, key, column, tree) { + if (column !== 'Narrative' && column !== 'Content') { + throw new Error(`Unknown full-text column ${column}`); + } + if (dialect === 'sqlite') { + return { sql: `${key} IN (SELECT rowid FROM TextIndex WHERE TextIndex MATCH ?)`, args: [`${column} : (${fts5(tree)})`] }; + } + return { sql: `${key} IN (SELECT ResourceKey FROM TextIndex WHERE MATCH(${column}) AGAINST (? IN BOOLEAN MODE))`, args: [mysqlBoolean(tree, true)] }; +} + +// ---- storage ---- + +/** The statements that make the TextIndex table */ +function ddl(dialect) { + if (dialect === 'sqlite') { + // the text is already folded: the tokenizer only splits it + return ['CREATE VIRTUAL TABLE TextIndex USING fts5(Narrative, Content, tokenize = \'unicode61 remove_diacritics 0\')']; + } + return ['CREATE TABLE TextIndex (ResourceKey BIGINT NOT NULL PRIMARY KEY, Narrative MEDIUMTEXT, Content MEDIUMTEXT, ' + + 'FULLTEXT KEY FT_TextIndex_Narrative (Narrative), FULLTEXT KEY FT_TextIndex_Content (Content)) ' + + 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin']; +} + +/** Take a resource's text out of the index */ +async function remove(q, resourceKey) { + if (q.dialect.name === 'sqlite') { + await q.run('DELETE FROM TextIndex WHERE rowid = ?', [resourceKey]); + } else { + await q.run('DELETE FROM TextIndex WHERE ResourceKey = ?', [resourceKey]); + } +} + +/** Index a resource's text (replacing what was there) */ +async function write(q, resourceKey, resource) { + await remove(q, resourceKey); + const narrative = folded(narrativeText(resource && resource.text && resource.text.div)); + const content = folded(contentText(resource)); + if (!narrative && !content) { + return; + } + if (q.dialect.name === 'sqlite') { + await q.run('INSERT INTO TextIndex (rowid, Narrative, Content) VALUES (?, ?, ?)', [resourceKey, narrative, content]); + } else { + await q.run('INSERT INTO TextIndex (ResourceKey, Narrative, Content) VALUES (?, ?, ?)', [resourceKey, narrative, content]); + } +} + +module.exports = { narrativeText, contentText, words, parseQuery, fts5, mysqlBoolean, condition, ddl, write, remove, MAX_TERMS, MAX_QUERY }; diff --git a/rest/indexing/indexer.js b/rest/indexing/indexer.js index 14af33c5..78b24910 100644 --- a/rest/indexing/indexer.js +++ b/rest/indexing/indexer.js @@ -20,6 +20,11 @@ const { extractValues } = require('./values'); const { INDEX_TABLES } = require('../database/schema'); const { chunks } = require('../database/lookups'); const { unprocessable } = require('../library/errors'); +const fulltext = require('./fulltext'); +const { CONTAINERS } = require('./definitions'); + +// the most contained resources indexed for one container +const MAX_CONTAINED = 100; // the most rows one search parameter can add for one resource const MAX_ROWS_PER_PARAM = 200; @@ -37,7 +42,7 @@ const COLUMNS = { function rowKey(r) { const cols = COLUMNS[r.table]; return r.table + '|' + r.Comp + '|' + r.GroupNo + '|' + cols.map(c => r[c] === undefined ? '' : r[c]).join('|') + - '|' + (r.system || '') + '|' + (r.targetType || '') + '|' + (r.targetId || ''); + '|' + (r.system || '') + '|' + (r.targetType || '') + '|' + (r.targetId || '') + '|' + (r.contained === undefined ? '' : '#' + r.contained); } class Indexer { @@ -158,6 +163,36 @@ class Indexer { async index(q, entry) { const { resourceKey, resource } = entry; await this.remove(q, resourceKey); + // the contained resources the resource refers to are indexed too, each under its own + // (negative) key: see resolveContained + const state = { containerKey: resourceKey, container: resource, keys: new Map(), queue: [] }; + const top = await this.indexOne(q, resourceKey, resource, entry, state); + const unresolved = [...top.unresolved]; + while (state.queue.length) { + const c = state.queue.shift(); + const r = await this.indexOne(q, c.key, c.view, entry, state); + unresolved.push(...r.unresolved); + } + + // the text, for _text and _content (the container's: the contained resources are in it) + await fulltext.write(q, resourceKey, resource); + + // compartments + const comps = this.compartmentRows(resource, top.rows, resourceKey); + if (comps.length) { + for (const c of chunks(comps, 500)) { + await q.run('INSERT INTO Compartments (ResourceKey, CompType, CompId, CompKey) VALUES ' + c.map(() => '(?, ?, ?, ?)').join(', '), + c.flatMap(x => [resourceKey, x.type, x.id, x.key])); + } + } + return { unresolved: [...new Set(unresolved)] }; + } + + /** + * The index rows of one resource (the resource itself, or one it contains), written under key. + * @returns {Promise<{rows: Object[], unresolved: string[]}>} + */ + async indexOne(q, resourceKey, resource, entry, state) { const { rows, problems } = this.extract(resource); for (const p of problems) { this.log('debug', `Indexing ${resource.resourceType}/${resource.id}: ${p}`); @@ -200,8 +235,9 @@ class Indexer { } } - // local references + // local references, and references to contained resources const unresolved = await this.resolveReferences(q, rows, entry); + await this.resolveContained(q, rows, entry, state); // insert const byTable = new Map(); @@ -223,15 +259,61 @@ class Indexer { } } - // compartments - const comps = this.compartmentRows(resource, rows, resourceKey); - if (comps.length) { - for (const c of chunks(comps, 500)) { - await q.run('INSERT INTO Compartments (ResourceKey, CompType, CompId, CompKey) VALUES ' + c.map(() => '(?, ?, ?, ?)').join(', '), - c.flatMap(x => [resourceKey, x.type, x.id, x.key])); + return { rows, unresolved }; + } + + /** + * References to contained resources ('#id'): each contained resource referred to gets a row + * in Contained, and its key, -ContainedKey, is the reference's target. It is then indexed + * (state.queue) with its own type's search parameters, as a copy that carries the + * container's contained list, so its own '#id' references find its siblings, and '#' finds + * the container (CONTAINERS). '#' alone is the container itself. + * + * A reference to a contained resource that isn't there makes the resource invalid: 422, + * except when reindexing what is already stored (entry.lenient). + */ + async resolveContained(q, rows, entry, state) { + const container = state.container; + for (const r of rows) { + if (r.table !== 'IndexReferences' || r.contained === undefined) { + continue; + } + if (r.contained === '') { + r.TargetKey = state.containerKey; + r.TargetType = container.resourceType; + r.TargetId = container.id || null; + continue; } + const c = Array.isArray(container.contained) ? container.contained.find(x => x && x.id === r.contained && x.resourceType) : null; + if (!c) { + if (!entry.lenient) { + throw unprocessable(`The resource refers to #${r.contained}, but it contains no resource with that id`); + } + r.TargetKey = null; + r.TargetType = null; + r.TargetId = null; + continue; + } + let key = state.keys.get(r.contained); + if (key === undefined) { + if (state.keys.size >= MAX_CONTAINED) { + this.log('debug', `Indexing ${container.resourceType}/${container.id}: more than ${MAX_CONTAINED} contained resources; the rest are not indexed`); + key = null; + } else { + const typeKey = this.typeKeys.get(c.resourceType); + const ins = await q.run('INSERT INTO Contained (ResourceKey, TypeKey, LocalId) VALUES (?, ?, ?)', + [state.containerKey, typeKey === undefined ? null : typeKey, String(r.contained).substring(0, 64)]); + key = -Number(ins.lastId); + const view = { ...c, contained: container.contained }; + CONTAINERS.set(view, container); + state.queue.push({ key, view }); + } + state.keys.set(r.contained, key); + } + r.TargetKey = key; + r.TargetType = c.resourceType; + r.TargetId = null; } - return { unresolved }; } async resolveReferences(q, rows, entry) { @@ -343,6 +425,18 @@ class Indexer { await q.run(`DELETE FROM ${t} WHERE ResourceKey = ?`, [resourceKey]); } await q.run('DELETE FROM Compartments WHERE ResourceKey = ?', [resourceKey]); + await fulltext.remove(q, resourceKey); + // and the contained resources it was indexed with + const contained = await q.all('SELECT ContainedKey FROM Contained WHERE ResourceKey = ?', [resourceKey]); + if (contained.length) { + const keys = contained.map(c => -Number(c.ContainedKey)); + for (const c of chunks(keys, 500)) { + for (const t of INDEX_TABLES) { + await q.run(`DELETE FROM ${t} WHERE ResourceKey IN (${c.map(() => '?').join(', ')})`, c); + } + } + await q.run('DELETE FROM Contained WHERE ResourceKey = ?', [resourceKey]); + } } /** diff --git a/rest/indexing/values.js b/rest/indexing/values.js index 95b305d7..b812ddaa 100644 --- a/rest/indexing/values.js +++ b/rest/indexing/values.js @@ -276,6 +276,12 @@ function referenceValues(type, d, out, ctx) { return; } if (typeof d === 'object') { + if (typeof d.reference === 'string' && d.reference.startsWith('#')) { + // a contained resource (or, '#' alone, the container): the indexer gives it its key + out.push({ table: 'IndexReferences', local: false, contained: d.reference.substring(1), targetType: null, targetId: null, + TargetVersion: null, Url: null, UrlVersion: null, identSystem: null, IdentValue: null }); + return; + } const p = typeof d.reference === 'string' ? parseReference(d.reference, ctx.baseUrls) : null; const ident = d.identifier && d.identifier.value ? d.identifier : null; if (p || ident) { diff --git a/rest/interactions/capabilities.js b/rest/interactions/capabilities.js index 33a92c79..b62cdc16 100644 --- a/rest/interactions/capabilities.js +++ b/rest/interactions/capabilities.js @@ -18,7 +18,9 @@ const { OPERATIONS } = require('../operations/operations'); const COMMON = [ { name: '_id', type: 'token' }, { name: '_lastUpdated', type: 'date' }, { name: '_tag', type: 'token' }, { name: '_security', type: 'token' }, { name: '_profile', type: 'uri' }, { name: '_has', type: 'string' }, - { name: '_filter', type: 'string' }, { name: '_list', type: 'string' } + { name: '_filter', type: 'string' }, { name: '_list', type: 'string' }, + { name: '_text', type: 'string', documentation: 'Words in the narrative: words match as prefixes, "phrases" as they are; AND, OR, NOT (or -), brackets' }, + { name: '_content', type: 'string', documentation: 'Words anywhere in the resource: as for _text' } ]; function capabilities(ep, freq) { diff --git a/rest/search.md b/rest/search.md index 5bd1bbca..8a63e8e2 100644 --- a/rest/search.md +++ b/rest/search.md @@ -45,12 +45,116 @@ Several values separated by commas are OR'd; a parameter repeated is AND'd. | `_profile` | `:below`, `:not`, `:missing` | | `_list` | the id of a List on the endpoint | | `_type` | on a search of the whole endpoint | +| `_text`, `_content` | full-text: see below | | `_has` | `_has:Type:reference:parameter=value`, nested up to 3 levels | | chains | `subject.name=x`, `subject:Patient.name=x`, up to 3 links | | `_filter` | operators `eq` `ne` `co` `sw` `ew` `gt` `lt` `ge` `le` `ap` `sa` `eb` `pr` `po` `ss` `sb` `in` `ni` `re`; `and`, `or`, `not`, brackets; chains through reference parameters. `sw` on a uri is `:below`; `ss` and `sb` on a token are `:below` and `:above` | Compartment searches (`Patient/123/Observation`, `Patient/123/*`) are supported too. +### Filters on a path step in `_filter` + +A chain step can carry a filter in brackets: conditions the same target must meet, before the +path carries on. + +``` +performer[family eq Smith].active eq true +``` + +is an Observation with a performer who is both called Smith and active. Without the brackets, + +``` +performer.family eq Smith and performer.active eq true +``` + +each half is matched on its own, so an Observation whose performers are an inactive Smith and +an active Jones matches too. The two only differ when the reference can repeat (`performer`, +`participant`, `general-practitioner`...). + +The filter in brackets is a whole `_filter` expression (`and`, `or`, `not`, its own chains and +brackets), about the reference's target types. Brackets go only on reference parameters, and +always with a parameter after them (`performer[...].active eq true`, not `performer[...] pr +true`). Chains, brackets included, are limited to 3 links. + +## Full-text search: `_text` and `_content` + +`_text` searches the narrative (the text of `text.div`, without the markup); `_content` searches +the whole resource: every string and number in it, the narrative's text included, but not the +names of the elements, the `meta`, or base64 `data`. + +The value is words and phrases: + +| | | +|---|---| +| `chest pain` | both words (terms next to each other are AND'd) | +| `chest AND pain` | the same | +| `pain OR ache` | either | +| `chest -child`, `chest NOT child` | chest, but not child | +| `"blood pressure"` | the phrase, as it is | +| `(pain OR ache) chest` | brackets group | + +- A word matches as a prefix (`chalm` finds Chalmers); a phrase matches as it is. Accents and + case are folded, as for string parameters (`muller` finds Müller). +- A word the index splits into several (`anna@example.org`) is matched as a phrase. +- Each part of the search needs a word that isn't negated (`-child` on its own can't be + searched). At most 32 words and phrases, and 1,000 characters. +- `_text` and `_content` work on a chain (`Observation?subject._text=pressure`) and with + `_type`. They can't be used in `_filter` yet, and take no modifiers. + +The text is indexed with the resource, in its write transaction. A database made before +full-text search (schema version 1) gets the index when the server starts, and the master fills +it in the background; until it has, searches using `_text` or `_content` say so in the result's +OperationOutcome. + +What differs between the engines: + +- **MySQL ignores short words and stopwords.** Words shorter than `innodb_ft_min_token_size` + (3 by default) aren't indexed, so they find nothing, and nor do words on MySQL's stopword + list ("about", "the", ...). SQLite indexes every word. +- **Inside a transaction, MySQL doesn't see the transaction's own writes**: a `_text` search in + a transaction's GET entry finds what was there before the transaction (MySQL updates a + FULLTEXT index at commit). SQLite sees them. + +## Contained resources + +A contained resource that the resource refers to (`#id`) is indexed with its own type's +search parameters, so a chain reaches into it: `Patient?general-practitioner.name=smith` +finds a patient whose GP is contained, as well as one whose GP is a Practitioner of its own. +A contained resource's references are indexed too: `#id` finds a sibling, `#` the container, +and references to other resources are kept, so a chain can go on through them +(`Observation?subject:Patient.organization.name=acme`). + +By default, searching a type (`Practitioner?name=smith`) doesn't find contained resources, +nor does `_has`, nor does `_include` bring them in: they come back in the resource that +contains them. `_contained` changes what a search finds: + +| `_contained` | finds | +| --- | --- | +| `false` (the default) | resources of their own | +| `true` | contained resources only | +| `both` | either | + +and `_containedType` what comes back for a contained resource that matches: + +| `_containedType` | returns | +| --- | --- | +| `container` (the default) | the resource that contains it, once however many of its contained resources match, with mode `match`; `total` counts containers | +| `contained` | the contained resource itself, with the fullUrl `[base]/[container type]/[container id]#[local id]`; `total` counts contained resources | + +For a contained resource, `_id` is its local id, and `_lastUpdated` its container's; +`_tag`, `_profile`, `_security`, `_list`, `_text` and `_content` don't find it. A compartment +search (`Patient/123/Observation?_contained=true`), and a user limited to compartments, go by +the container. Sorting and paging work as for anything else; `_include` and `_revinclude` +work from contained matches (`Practitioner?_contained=true&_containedType=contained&_revinclude=Patient:general-practitioner` +brings in the patients that contain them). + +A contained resource that nothing refers to isn't indexed, so no search finds it, nor is one +past the first 100 in a resource. + +A reference to a contained resource that isn't there (`#nobody`) makes the resource invalid: +422. (Resources that were stored before this was checked are indexed regardless, with the +reference going nowhere.) + ## Results | Parameter | | @@ -73,5 +177,5 @@ user who ran the search. - `:above` and `:below` on references (canonical version matching) - `:not` on anything but tokens and `_id`, `_tag`, `_security`, `_profile` - `:code-text` as it is defined (matching the code's display): it is treated as `:text` -- `_text`, `_content`, `_query`, `_contained`, `_containedType` -- filters on path elements in `_filter` (`name[...]`) +- `_query` +- `_text` and `_content` in `_filter`, relevance ranking, and `:text-advanced` diff --git a/rest/search/filter.js b/rest/search/filter.js index 7f318713..43fed84b 100644 --- a/rest/search/filter.js +++ b/rest/search/filter.js @@ -12,11 +12,14 @@ * andExpr = unary ("and" unary)* * unary = "not" "(" expr ")" | "(" expr ")" | comparison * comparison = path op value - * path = name ("." name)* a chain through reference parameters + * path = name ("[" filter "]")? ("." path)? a chain through reference parameters * op = eq ne co sw ew gt lt ge le ap sa eb pr po ss sb in ni re * value = "quoted string" | token * - * Filters on path elements (name[filter]) are not supported yet. + * A chain (subject.name eq x) asks for a reference to a resource that matches; a filter in + * brackets on a step (performer[name sw Smith].active eq true) adds conditions the same + * target must meet: unlike performer.name sw Smith and performer.active eq true, which two + * different performers could meet between them. * * @module rest/search/filter */ @@ -65,9 +68,16 @@ function tokenise(text) { i++; out.push({ t: 'str', v: s }); } else { + // a word; a [...] in it (a filter on a path step) is kept whole, spaces and all let s = ''; while (i < text.length && !/[\s()]/.test(text[i])) { - s += text[i++]; + if (text[i] === '[') { + const end = closingBracket(text, i); + s += text.substring(i, end + 1); + i = end + 1; + } else { + s += text[i++]; + } } out.push({ t: 'word', v: s }); } @@ -75,8 +85,76 @@ function tokenise(text) { return out; } +/** + * Where the ] that closes the [ at start is: brackets nest, and brackets inside quoted + * strings don't count. + */ +function closingBracket(text, start) { + let depth = 0; + for (let i = start; i < text.length; i++) { + const c = text[i]; + if (c === '"') { + i++; + while (i < text.length && text[i] !== '"') { + if (text[i] === '\\') { + i++; + } + i++; + } + } else if (c === '[') { + depth++; + } else if (c === ']') { + depth--; + if (depth === 0) { + return i; + } + } + } + throw badRequest('_filter: a [ is not closed'); +} + +/** + * The first step of a path: its parameter, the filter in brackets on it (or null), and the + * rest of the path after the '.' (or null). + * @param {string} path + */ +function splitPath(path) { + let i = 0; + while (i < path.length && path[i] !== '[' && path[i] !== '.') { + i++; + } + const code = path.substring(0, i); + let filter = null; + if (path[i] === '[') { + const end = closingBracket(path, i); + filter = path.substring(i + 1, end).trim(); + if (!filter) { + throw badRequest(`_filter: the [] on ${code} is empty`); + } + i = end + 1; + } + let rest = null; + if (i < path.length) { + if (path[i] !== '.' || i + 1 >= path.length) { + throw badRequest(`_filter: '${path}' is not a parameter path`); + } + rest = path.substring(i + 1); + } + if (!code) { + throw badRequest(`_filter: '${path}' is not a parameter path`); + } + return { code, filter, rest }; +} + class FilterParser { - constructor(sp, types, text) { + /** + * @param {Object} sp - the SearchParser + * @param {string[]} types - the types the filter is about + * @param {string} text + * @param {number} [depth] - how many chain links in this filter is (a filter in brackets) + */ + constructor(sp, types, text, depth = 0) { + this.depth = depth; this.sp = sp; this.types = types; if (text.length > MAX_LENGTH) { @@ -159,30 +237,29 @@ class FilterParser { if (!path || path.t !== 'word' || !op || op.t !== 'word' || !value || (value.t !== 'word' && value.t !== 'str')) { throw badRequest('_filter: expected parameter operator value'); } - if (path.v.includes('[')) { - throw badRequest('_filter: filters on path elements ([...]) are not supported yet'); - } const o = op.v.toLowerCase(); if (!OPS.has(o)) { throw badRequest(`_filter: unknown operator '${op.v}'`); } - return this.compare(this.types, path.v, o, value.v, 0); + return this.compare(this.types, path.v, o, value.v, this.depth); } compare(types, path, op, value, depth) { const sp = this.sp; - const dot = path.indexOf('.'); - if (dot > 0) { + const step = splitPath(path); + if (step.filter !== null && step.rest === null) { + throw badRequest(`_filter: a filter in brackets on ${step.code} needs a parameter after it (${step.code}[...].parameter)`); + } + if (step.rest !== null) { if (depth >= 3) { throw badRequest('_filter: chains are limited to 3 links'); } - const code = path.substring(0, dot); + const code = step.code; const l = sp.lookup(types, code); if (!l || l.spType !== 'reference') { - throw badRequest(`_filter: '${code}' is not a reference parameter`); + throw badRequest(`_filter: '${code}' is not a reference parameter${step.filter !== null ? ', so it can\'t have a filter in brackets' : ''}`); } - const rest = path.substring(dot + 1); - const nextCode = rest.split('.')[0]; + const nextCode = splitPath(step.rest).code; let targets = [...new Set(l.defs.flatMap(d => d.target || []))].filter(t => sp.ep.typeKeys.has(t)); if (!nextCode.startsWith('_')) { targets = targets.filter(t => sp.defs.param(t, nextCode)); @@ -190,7 +267,13 @@ class FilterParser { if (!targets.length) { throw badRequest(`_filter: none of the targets of ${code} has a parameter '${nextCode}'`); } - return { kind: 'chain', keys: l.keys, targetTypes: null, inner: this.compare(targets, rest, op, value, depth + 1) }; + let inner = this.compare(targets, step.rest, op, value, depth + 1); + if (step.filter !== null) { + // the bracket's conditions and the rest of the path, on the same target + const filter = new FilterParser(sp, targets, step.filter, depth + 1).parse(); + inner = { kind: 'and', items: [filter, inner] }; + } + return { kind: 'chain', keys: l.keys, targetTypes: null, inner }; } if (path === '_id') { if (op !== 'eq' && op !== 'ne') { @@ -296,4 +379,4 @@ function parseFilter(sp, types, text) { return new FilterParser(sp, types, text).parse(); } -module.exports = { parseFilter, tokenise, asSearchValue }; +module.exports = { parseFilter, tokenise, asSearchValue, splitPath }; diff --git a/rest/search/parser.js b/rest/search/parser.js index 0b895233..5ec05226 100644 --- a/rest/search/parser.js +++ b/rest/search/parser.js @@ -142,7 +142,8 @@ class SearchParser { const ignored = []; const warnings = []; this.keysUsed = new Set(); - const control = { sort: [], include: [], revinclude: [], count: null, total: null, summary: null, elements: null }; + this.fullTextUsed = false; + const control = { sort: [], include: [], revinclude: [], count: null, total: null, summary: null, elements: null, contained: 'false', containedType: 'container' }; for (const [name, value] of p.params) { const base = name.split(':')[0].split('.')[0]; if (CONTROL.has(base)) { @@ -175,6 +176,9 @@ class SearchParser { } } } + if (this.fullTextUsed && this.ep.reindexAll) { + warnings.push('The full-text index is still being built: _text and _content may not find everything yet'); + } for (const k of this.keysUsed) { const def = [...this.defs.byUrl.values()].find(d => d.key === k); if (def && this.defs.reindexing && this.defs.reindexing.has(def.url)) { @@ -193,6 +197,18 @@ class SearchParser { } control.count = Number(value); break; + case '_contained': + if (!['true', 'false', 'both'].includes(value)) { + throw badRequest(`_contained is true, false or both, not '${value}'`); + } + control.contained = value; + break; + case '_containedType': + if (!['container', 'contained'].includes(value)) { + throw badRequest(`_containedType is container or contained, not '${value}'`); + } + control.containedType = value; + break; case '_total': if (!['none', 'estimate', 'accurate'].includes(value)) { throw badRequest(`_total is none, estimate or accurate, not '${value}'`); @@ -290,6 +306,11 @@ class SearchParser { return require('./filter').parseFilter(this, types, value); case '_text': case '_content': + if (modifier) { + throw new Unsupported(`${code}:${modifier} is not supported`); + } + this.fullTextUsed = true; + return { kind: 'fulltext', column: code === '_text' ? 'Narrative' : 'Content', tree: require('../indexing/fulltext').parseQuery(value) }; case '_query': throw new Unsupported(`${code} is not supported yet`); default: diff --git a/rest/search/search.js b/rest/search/search.js index 9b3da379..f36a5e92 100644 --- a/rest/search/search.js +++ b/rest/search/search.js @@ -85,39 +85,64 @@ class Searcher { } /** - * Parse and build the condition for a search. - * @returns {Promise<{where: string, args: Array, parsed: Object, types: string[]}>} + * Parse and build the query for a search: SELECT ... FROM ${from} WHERE ${where}, with + * fromArgs then args. What is searched is "i": Ids, or with _contained=true or both, the + * contained resources (Contained, as Ids-like rows keyed -ContainedKey, with their container's + * MostRecent and Deleted) in place of or as well as them. i.ContainerKey is the resource + * itself, or a contained resource's container: compartments, and access, go by that. + * @returns {Promise<{from: string, fromArgs: Array, where: string, args: Array, containerKey: string, parsed: Object, types: string[]}>} */ async prepare(q, types, params, options) { const ep = this.ep; const parsed = new SearchParser(ep).parse({ types, params, strict: options.strict }); - const items = [...parsed.criteria.items]; - if (options.compartment) { - items.push({ kind: 'compartment', type: options.compartment.type, id: options.compartment.id }); + const mode = options.noContained ? 'false' : parsed.control.contained; + const all = [...ep.typeKeys.keys()].filter(t => ep.typeSupported(t)); + const typeKeys = types.length < all.length ? types.map(t => ep.typeKeys.get(t)) : null; + const typeIn = (col) => typeKeys === null ? '' : typeKeys.length === 0 ? ' WHERE 1 = 0' : ` WHERE ${col} IN (${typeKeys.map(() => '?').join(', ')})`; + let from = 'Ids i'; + const fromArgs = []; + let containerKey = 'i.ResourceKey'; + if (mode !== 'false') { + const branches = []; + if (mode === 'both') { + branches.push('SELECT ResourceKey AS ResourceKey, TypeKey AS TypeKey, Id AS Id, MostRecent AS MostRecent, Deleted AS Deleted, ResourceKey AS ContainerKey FROM Ids' + typeIn('TypeKey')); + fromArgs.push(...(typeKeys || [])); + } + branches.push('SELECT -c.ContainedKey AS ResourceKey, c.TypeKey AS TypeKey, c.LocalId AS Id, ci.MostRecent AS MostRecent, ci.Deleted AS Deleted, ' + + 'c.ResourceKey AS ContainerKey FROM Contained c JOIN Ids ci ON ci.ResourceKey = c.ResourceKey' + typeIn('c.TypeKey')); + fromArgs.push(...(typeKeys || [])); + from = `(${branches.join(' UNION ALL ')}) i`; + containerKey = 'i.ContainerKey'; } const b = new SqlBuilder(ep, q); + b.contained = mode !== 'false'; + const items = [...parsed.criteria.items]; const crit = await b.build({ kind: 'and', items }, 'i.ResourceKey'); const where = ['i.Deleted = 0', 'i.MostRecent IS NOT NULL']; const args = []; - const all = [...ep.typeKeys.keys()].filter(t => ep.typeSupported(t)); - if (types.length < all.length) { - if (types.length === 0) { + if (typeKeys !== null) { + if (typeKeys.length === 0) { where.push('1 = 0'); } else { - where.push(`i.TypeKey IN (${types.map(() => '?').join(', ')})`); - args.push(...types.map(t => ep.typeKeys.get(t))); + where.push(`i.TypeKey IN (${typeKeys.map(() => '?').join(', ')})`); + args.push(...typeKeys); } } if (crit.sql !== '1 = 1') { where.push(crit.sql); args.push(...crit.args); } - const comp = ep.compartmentFilter(options.access, 'i.ResourceKey'); + if (options.compartment) { + const c = await b.build({ kind: 'compartment', type: options.compartment.type, id: options.compartment.id }, containerKey); + where.push(c.sql); + args.push(...c.args); + } + const comp = ep.compartmentFilter(options.access, containerKey); if (comp) { where.push(comp.sql); args.push(...comp.args); } - return { where: where.join(' AND '), args, parsed, types }; + return { from, fromArgs, where: where.join(' AND '), args, containerKey, mode, parsed, types }; } orderBy(sort) { @@ -144,7 +169,7 @@ class Searcher { * @returns {Promise} */ async matchKeys(q, type, params, options = {}) { - const p = await this.prepare(q, [type], params, { access: options.access, strict: options.strict }); + const p = await this.prepare(q, [type], params, { access: options.access, strict: options.strict, noContained: true }); if (p.parsed.used.length === 0 && p.parsed.criteria.items.length === 0) { throw badRequest('The search criteria have no parameters this server knows'); } @@ -166,18 +191,25 @@ class Searcher { const p = await this.prepare(q, types, freq.params, { access: ctx.access, strict: strict(freq), compartment: freq.compartment }); const control = p.parsed.control; const count = control.count === null ? ep.settings.defaultCount : Math.min(control.count, ep.settings.maxCount); + // a contained resource that matches brings back its container, once, unless + // _containedType=contained asks for the contained resource itself + const containers = p.mode !== 'false' && control.containedType === 'container'; + const countSql = `SELECT COUNT(${containers ? 'DISTINCT i.ContainerKey' : '*'}) AS N FROM ${p.from} WHERE ${p.where}`; + const allArgs = [...p.fromArgs, ...p.args]; if (control.summary === 'count' || count === 0) { - const row = await q.get(`SELECT COUNT(*) AS N FROM Ids i WHERE ${p.where}`, p.args); + const row = await q.get(countSql, allArgs); return { p, count, keys: [], total: Number(row.N), countOnly: true }; } - const rows = await q.all(`SELECT i.ResourceKey FROM Ids i WHERE ${p.where} ${this.orderBy(control.sort)} LIMIT ${max + 1}`, p.args); - let keys = rows.map(r => Number(r.ResourceKey)); + const rows = await q.all(`SELECT i.ResourceKey, ${p.containerKey} AS ContainerKey FROM ${p.from} WHERE ${p.where} ${this.orderBy(control.sort)} LIMIT ${max + 1}`, allArgs); + const truncated = rows.length > max; + let keys = rows.slice(0, max).map(r => Number(containers ? r.ContainerKey : r.ResourceKey)); + if (containers) { + keys = [...new Set(keys)]; + } let total = null; - const truncated = keys.length > max; if (truncated) { - keys = keys.slice(0, max); if (control.total === 'accurate') { - const row = await q.get(`SELECT COUNT(*) AS N FROM Ids i WHERE ${p.where}`, p.args); + const row = await q.get(countSql, allArgs); total = Number(row.N); } } else if (control.total !== 'none') { @@ -269,7 +301,7 @@ class Searcher { async buildPage(freq, ctx, pg) { const ep = this.ep; const { found, included } = await ep.inRead(ctx, async (q) => { - const f = await ep.store.byKeys(q, pg.keys); + const f = await this.byKeys(q, pg.keys); const inc = await this.includes(q, f, pg.control, ctx.access); return { found: f, included: inc }; }); @@ -292,7 +324,7 @@ class Searcher { } const shapeControl = { summary: pg.control.summary, elements: pg.control.elements }; bundle.entry = found.map(r => ({ - fullUrl: `${freq.base}/${r.type}/${r.id}`, resource: ep.shapeResource(r.resource, freq, shapeControl), search: { mode: 'match' } + fullUrl: r.container ? `${freq.base}/${r.container.type}/${r.container.id}#${r.id}` : `${freq.base}/${r.type}/${r.id}`, resource: ep.shapeResource(r.resource, freq, shapeControl), search: { mode: 'match' } })); for (const r of included) { bundle.entry.push({ fullUrl: `${freq.base}/${r.type}/${r.id}`, resource: ep.shapeResource(r.resource, freq, shapeControl), search: { mode: 'include' } }); @@ -300,7 +332,36 @@ class Searcher { if (pg.warnings.length) { bundle.entry.push(this.outcomeEntry(pg.warnings)); } - return { status: 200, resource: bundle, searchKeys: found.map(r => r.resourceKey) }; + return { status: 200, resource: bundle, searchKeys: found.map(r => r.container ? r.container.resourceKey : r.resourceKey) }; + } + + /** + * The resources for a page's keys, in order: contained resources (_containedType=contained) + * are keyed -ContainedKey, and come out of their container's current version, with + * container set (and id their local id). + */ + async byKeys(q, keys) { + const ep = this.ep; + const neg = keys.filter(k => k < 0).map(k => -k); + if (!neg.length) { + return ep.store.byKeys(q, keys); + } + const rows = []; + for (let i = 0; i < neg.length; i += 500) { + const c = neg.slice(i, i + 500); + rows.push(...await q.all(`SELECT ContainedKey, ResourceKey, LocalId FROM Contained WHERE ContainedKey IN (${c.map(() => '?').join(', ')})`, c)); + } + const containerKeys = [...new Set(rows.map(r => Number(r.ResourceKey)))]; + const loaded = await ep.store.byKeys(q, [...new Set([...keys.filter(k => k > 0), ...containerKeys])]); + const byKey = new Map(loaded.map(r => [r.resourceKey, r])); + for (const r of rows) { + const container = byKey.get(Number(r.ResourceKey)); + const res = container && Array.isArray(container.resource.contained) ? container.resource.contained.find(c => c && c.id === r.LocalId) : null; + if (res) { + byKey.set(-Number(r.ContainedKey), { resourceKey: -Number(r.ContainedKey), type: res.resourceType, id: r.LocalId, resource: res, container }); + } + } + return keys.map(k => byKey.get(k)).filter(x => x); } /** @@ -326,7 +387,8 @@ class Searcher { } for (let i = 0; i < src.length; i += 500) { const c = src.slice(i, i + 500); - const conds = [`r.ResourceKey IN (${c.map(() => '?').join(', ')})`, 'r.TargetKey IS NOT NULL']; + // (a contained target, TargetKey < 0, is in the resource already) + const conds = [`r.ResourceKey IN (${c.map(() => '?').join(', ')})`, 'r.TargetKey > 0']; const args = [...c]; if (inc.key) { conds.push('r.ParamKey = ?'); diff --git a/rest/search/sql.js b/rest/search/sql.js index afc29e94..4bd6e669 100644 --- a/rest/search/sql.js +++ b/rest/search/sql.js @@ -41,6 +41,18 @@ class SqlBuilder { this.ep = ep; this.q = q; this.n = 0; + // whether the keys searched include contained resources (-ContainedKey): then _id is the + // contained resource's local id, and _lastUpdated its container's + this.contained = false; + } + + /** a's ResourceKey is key, or (for a contained resource) its container's */ + selfOrContainer(a, key) { + if (!this.contained) { + return `${a}.ResourceKey = ${key}`; + } + const ca = this.alias('ca'); + return `(${a}.ResourceKey = ${key} OR ${a}.ResourceKey = (SELECT ${ca}.ResourceKey FROM Contained ${ca} WHERE ${ca}.ContainedKey = -(${key})))`; } alias(p) { @@ -80,14 +92,20 @@ class SqlBuilder { return NOTHING; case 'id': { const a = this.alias('z'); - const sql = `EXISTS (SELECT 1 FROM Ids ${a} WHERE ${a}.ResourceKey = ${key} AND ${a}.Id IN (${inList(node.ids.length)}))`; - return { sql: node.negate ? 'NOT ' + sql : sql, args: node.ids }; + let sql = `EXISTS (SELECT 1 FROM Ids ${a} WHERE ${a}.ResourceKey = ${key} AND ${a}.Id IN (${inList(node.ids.length)}))`; + let args = node.ids; + if (this.contained) { + const ca = this.alias('ca'); + sql = `(${sql} OR EXISTS (SELECT 1 FROM Contained ${ca} WHERE ${ca}.ContainedKey = -(${key}) AND ${ca}.LocalId IN (${inList(node.ids.length)})))`; + args = [...node.ids, ...node.ids]; + } + return { sql: node.negate ? 'NOT ' + sql : sql, args }; } case 'lastUpdated': { const a = this.alias('z'); const v = this.alias('zv'); const parts = node.values.map(x => dateClause({ lo: `${v}.LastUpdated`, hi: `(${v}.LastUpdated + 1)` }, x.prefix, x.range)); - return { sql: `EXISTS (SELECT 1 FROM Ids ${a} JOIN Versions ${v} ON ${v}.VersionKey = ${a}.MostRecent WHERE ${a}.ResourceKey = ${key} AND (${parts.map(p => p.sql).join(' OR ')}))`, + return { sql: `EXISTS (SELECT 1 FROM Ids ${a} JOIN Versions ${v} ON ${v}.VersionKey = ${a}.MostRecent WHERE ${this.selfOrContainer(a, key)} AND (${parts.map(p => p.sql).join(' OR ')}))`, args: parts.flatMap(p => p.args) }; } case 'tag': @@ -135,6 +153,8 @@ class SqlBuilder { } case 'param': return this.param(node, key); + case 'fulltext': + return require('../indexing/fulltext').condition(this.q.dialect.name, key, node.column, node.tree); } throw new Error(`Unknown search node ${node.kind}`); } diff --git a/rest/web.js b/rest/web.js index 28ed5054..2e3d0eb3 100644 --- a/rest/web.js +++ b/rest/web.js @@ -41,10 +41,13 @@ const HINTS = { quantity: 'value|system|code, e.g. gt5.4|http://unitsofmeasure.org|mmol/L', reference: 'Type/id, or a URL', uri: 'a URI (:below, :above)', - composite: 'values separated by $' + composite: 'values separated by $', + text: 'e.g. chest pain, "blood pressure" -child' }; const COMMON = [ + { code: '_text', type: 'text', description: 'Words in the narrative. Words match as prefixes, "phrases" as they are; AND, OR, NOT (or -), brackets' }, + { code: '_content', type: 'text', description: 'Words anywhere in the resource, as for _text' }, { code: '_id', type: 'token', description: 'The resource\'s id' }, { code: '_lastUpdated', type: 'date', description: 'When the resource was last changed' }, { code: '_tag', type: 'token', description: 'A tag in the resource\'s meta' }, @@ -53,7 +56,7 @@ const COMMON = [ ]; // the parameters that control a search rather than choose what it finds -const CONTROL = new Set(['_format', '_pretty', '_count', '_sort', '_summary', '_elements', '_total', '_include', '_revinclude']); +const CONTROL = new Set(['_format', '_pretty', '_count', '_sort', '_summary', '_elements', '_total', '_include', '_revinclude', '_contained', '_containedType']); let i18nPromise = null; @@ -352,7 +355,7 @@ class RestWeb { `${escape(p.description || '')}`; } html += ''; - const sortable = params.filter(p => p.type !== 'composite'); + const sortable = params.filter(p => p.type !== 'composite' && p.type !== 'text'); html += '

'; html += '   '; html += `   `; - html += ' '; + html += '   '; + html += ' ' + + ''; html += '

'; html += '

' + 'Empty fields are left out. Repeat a parameter in the URL to AND values; separate values with commas to OR them.

'; @@ -423,12 +430,15 @@ class RestWeb { `${escape(e.response && e.response.lastModified ? e.response.lastModified : '')}`; continue; } - const link = `${base}/${encodeURIComponent(r.resourceType)}/${encodeURIComponent(r.id)}`; + // a contained resource (_containedType=contained): its fullUrl is its container's, #id + const hash = typeof e.fullUrl === 'string' ? e.fullUrl.indexOf('#') : -1; + const container = hash > 0 ? e.fullUrl.substring(0, hash).split('/').slice(-2) : null; + const link = container ? `${base}/${container.map(encodeURIComponent).join('/')}` : `${base}/${encodeURIComponent(r.resourceType)}/${encodeURIComponent(r.id)}`; const vid = r.meta && r.meta.versionId; const vlink = vid ? `${link}/_history/${encodeURIComponent(vid)}` : link; const mode = e.search && e.search.mode === 'include' ? ' included' : ''; const op = req2 ? ` (${escape(req2.method === 'POST' ? 'created' : req2.method === 'PUT' ? 'updated' : req2.method)})` : ''; - html += `${escape(r.resourceType)}/${escape(r.id)}${mode}` + + html += `${container ? escape(r.resourceType) + ' #' + escape(r.id) + ' in ' + escape(container.join('/')) + '' : escape(r.resourceType) + '/' + escape(r.id) + ''}${mode}` + `${escape(displayOf(r))}${escape(vid || '')}${op}` + `${escape(r.meta && r.meta.lastUpdated ? r.meta.lastUpdated.replace('T', ' ').replace(/\.\d+Z$/, 'Z') : '')}` + `JSON`; diff --git a/tests/cs/cs-omop.test.js b/tests/cs/cs-omop.test.js index 42c1cb6d..61a409e4 100644 --- a/tests/cs/cs-omop.test.js +++ b/tests/cs/cs-omop.test.js @@ -359,6 +359,27 @@ describe('OMOP Provider', () => { } }); + test('a filter prepared for checking (not iterating) agrees with one that iterates', async () => { + // validation prepares filters with iterate = false: the filter is never run, so + // filterCheck has to ask about the code itself rather than look in rows it doesn't have + if (testData.domains.length > 0 && testData.sampleConcepts.length > 0) { + const conceptResult = await provider.locate(testData.sampleConcepts[0]); + const concept = conceptResult.context; + + if (concept && concept.domain) { + const answers = []; + for (const iterate of [true, false]) { + const filterContext = await provider.getPrepContext(iterate); + await provider.filter(filterContext, iterate, 'domain', '=', concept.domain); + const filters = await provider.executeFilters(filterContext); + answers.push(await provider.filterCheck(filterContext, filters[0], concept)); + await provider.filterFinish(filterContext); + } + expect(answers[1]).toBe(answers[0]); + } + } + }); + test('should have closed filters', async () => { if (testData.domains.length > 0) { const filterContext = await provider.getPrepContext(true); diff --git a/tests/rest/contained.test.js b/tests/rest/contained.test.js new file mode 100644 index 00000000..a7e70729 --- /dev/null +++ b/tests/rest/contained.test.js @@ -0,0 +1,263 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +// Contained resources: each one a resource refers to ('#id') is indexed with its own type's +// search parameters, under its own key, so chains reach into it; nothing else finds it. + +const request = require('supertest'); +const { engines, makeApp, body, invariants, snapshot, FHIR_JSON } = require('./helpers'); + +const gp = (family, extra = {}) => ({ resourceType: 'Practitioner', id: 'gp', name: [{ family }], ...extra }); + +describe.each(engines())('contained resources (%s)', (engine) => { + let t; + + const send = (method, url, resource) => request(t.app)[method](url).set('Content-Type', FHIR_JSON).send(body(resource)); + const post = async (resource) => { + const r = await send('post', `/r4/${resource.resourceType}`, resource); + if (r.status !== 201) { + throw new Error(`create failed: ${r.status} ${JSON.stringify(r.body)}`); + } + return r.body.id; + }; + const found = async (url) => { + const r = await request(t.app).get(url); + expect(r.status).toBe(200); + return (r.body.entry || []).filter(e => e.search.mode === 'match').map(e => e.resource.id).sort(); + }; + const containedRows = () => t.ep.db.read(q => q.all('SELECT ResourceKey, LocalId FROM Contained ORDER BY LocalId')); + + beforeEach(async () => { + t = await makeApp(engine); + }); + afterEach(async () => { + expect(await invariants(t.ep)).toEqual([]); + await t.close(); + }); + + test('a chain reaches into a contained resource, with its own search parameters', async () => { + const id = await post({ resourceType: 'Patient', name: [{ family: 'Smith' }], contained: [gp('Platypus')], + generalPractitioner: [{ reference: '#gp' }] }); + await post({ resourceType: 'Patient', name: [{ family: 'Jones' }], contained: [gp('Echidna')], generalPractitioner: [{ reference: '#gp' }] }); + expect(await found('/r4/Patient?general-practitioner.name=platypus')).toEqual([id]); + expect(await found('/r4/Patient?general-practitioner:Practitioner.family=Platypus')).toEqual([id]); + expect(await found('/r4/Patient?general-practitioner:Organization.name=platypus')).toEqual([]); + expect(await found('/r4/Patient?general-practitioner.name=wombat')).toEqual([]); + }); + + test('contained resources are not found by searching their type, and _include leaves them out', async () => { + const real = await post(gp('Platypus', { id: undefined })); + const id = await post({ resourceType: 'Patient', contained: [gp('Platypus')], generalPractitioner: [{ reference: '#gp' }, { reference: `Practitioner/${real}` }] }); + expect(await found('/r4/Practitioner?name=platypus')).toEqual([real]); + expect(await found('/r4/Practitioner')).toEqual([real]); + const r = await request(t.app).get(`/r4/Patient?_id=${id}&_include=Patient:general-practitioner`); + expect(r.body.entry.map(e => `${e.search.mode}:${e.resource.resourceType}/${e.resource.id}`).sort()) + .toEqual([`include:Practitioner/${real}`, `match:Patient/${id}`]); + }); + + test('a contained resource that is not referred to is not indexed', async () => { + await post({ resourceType: 'Patient', contained: [gp('Platypus')] }); + expect(await containedRows()).toEqual([]); + }); + + test('a contained resource\'s references to its siblings, and to real resources, are indexed too', async () => { + const org = await post({ resourceType: 'Organization', name: 'Acme' }); + // an Observation about a contained patient, whose GP is contained alongside it + const id = await post({ resourceType: 'Observation', status: 'final', code: { text: 'x' }, + contained: [ + { resourceType: 'Patient', id: 'p', name: [{ family: 'Smith' }], generalPractitioner: [{ reference: '#gp' }], + managingOrganization: { reference: `Organization/${org}` } }, + gp('Platypus') + ], + subject: { reference: '#p' } }); + expect(await found('/r4/Observation?subject:Patient.general-practitioner.name=platypus')).toEqual([id]); + expect(await found('/r4/Observation?subject:Patient.organization.name=acme')).toEqual([id]); + expect(await found('/r4/Observation?subject:Patient.organization.name=other')).toEqual([]); + expect(await found(`/r4/Observation?subject:Patient.organization=Organization/${org}`)).toEqual([id]); + // each contained resource once, however often it is referred to + expect((await containedRows()).map(c => c.LocalId)).toEqual(['gp', 'p']); + }); + + test('"#" is the container itself', async () => { + const id = await post({ resourceType: 'Observation', status: 'final', code: { text: 'x' }, + contained: [{ resourceType: 'Patient', id: 'p', link: [{ other: { reference: '#' }, type: 'seealso' }] }], + subject: { reference: '#p' } }); + const rows = await t.ep.db.read(q => q.all(`SELECT r.TargetKey, r.TargetType, r.TargetId FROM IndexReferences r + JOIN Ids i ON i.ResourceKey = r.TargetKey WHERE r.ResourceKey < 0`)); + expect(rows.map(r => `${r.TargetType}/${r.TargetId}`)).toEqual([`Observation/${id}`]); + }); + + test('a reference to a contained resource that isn\'t there is an error, and nothing is written', async () => { + const before = await snapshot(t.ep); + const r = await send('post', '/r4/Patient', { resourceType: 'Patient', contained: [gp('Platypus')], generalPractitioner: [{ reference: '#nobody' }] }); + expect(r.status).toBe(422); + expect(JSON.stringify(r.body)).toMatch(/#nobody/); + expect(await snapshot(t.ep)).toEqual(before); + }); + + test('an update replaces the contained resources, and a delete removes them', async () => { + const id = await post({ resourceType: 'Patient', contained: [gp('Platypus')], generalPractitioner: [{ reference: '#gp' }] }); + expect(await found('/r4/Patient?general-practitioner.name=platypus')).toEqual([id]); + let r = await send('put', `/r4/Patient/${id}`, { resourceType: 'Patient', id, contained: [gp('Echidna')], generalPractitioner: [{ reference: '#gp' }] }); + expect(r.status).toBe(200); + expect(await found('/r4/Patient?general-practitioner.name=platypus')).toEqual([]); + expect(await found('/r4/Patient?general-practitioner.name=echidna')).toEqual([id]); + expect(await containedRows()).toHaveLength(1); + r = await send('put', `/r4/Patient/${id}`, { resourceType: 'Patient', id }); + expect(r.status).toBe(200); + expect(await containedRows()).toEqual([]); + expect(await found('/r4/Patient?general-practitioner.name=echidna')).toEqual([]); + + const id2 = await post({ resourceType: 'Patient', contained: [gp('Wombat')], generalPractitioner: [{ reference: '#gp' }] }); + r = await request(t.app).delete(`/r4/Patient/${id2}`); + expect(r.status).toBeLessThan(300); + expect(await containedRows()).toEqual([]); + const left = await t.ep.db.read(q => q.get('SELECT COUNT(*) AS N FROM IndexStrings WHERE ResourceKey < 0')); + expect(Number(left.N)).toBe(0); + }); + + test('in a transaction: contained resources alongside references to entries', async () => { + const tx = { + resourceType: 'Bundle', type: 'transaction', entry: [ + { fullUrl: 'urn:uuid:11111111-1111-1111-1111-111111111111', resource: { resourceType: 'Organization', name: 'Acme' }, + request: { method: 'POST', url: 'Organization' } }, + { fullUrl: 'urn:uuid:22222222-2222-2222-2222-222222222222', request: { method: 'POST', url: 'Observation' }, + resource: { resourceType: 'Observation', status: 'final', code: { text: 'x' }, subject: { reference: '#p' }, + contained: [{ resourceType: 'Patient', id: 'p', managingOrganization: { reference: 'urn:uuid:11111111-1111-1111-1111-111111111111' } }] } } + ] + }; + const r = await send('post', '/r4', tx); + expect(r.status).toBe(200); + const obs = r.body.entry[1].response.location.split('/')[1]; + expect(await found('/r4/Observation?subject:Patient.organization.name=acme')).toEqual([obs]); + // the contained patient's reference was rewritten to the new organization + const o = await request(t.app).get(`/r4/Observation/${obs}`); + expect(o.body.contained[0].managingOrganization.reference).toMatch(/^Organization\/[^/]+$/); + + // and a dangling contained reference rolls the whole transaction back + const before = await snapshot(t.ep); + const bad = JSON.parse(JSON.stringify(tx)); + bad.entry[1].resource.subject.reference = '#q'; + const b = await send('post', '/r4', bad); + expect(b.status).toBe(422); + expect(await snapshot(t.ep)).toEqual(before); + }); + + test('reindexing is lenient about what is already stored, and puts the contained resources back', async () => { + const id = await post({ resourceType: 'Patient', contained: [gp('Platypus')], generalPractitioner: [{ reference: '#gp' }] }); + // something stored before references to contained resources were checked + const bad = await post({ resourceType: 'Patient', name: [{ family: 'Bad' }] }); + await t.ep.db.write(async (q) => { + const v = await q.get('SELECT i.MostRecent FROM Ids i WHERE i.Id = ?', [bad]); + const res = { resourceType: 'Patient', id: bad, name: [{ family: 'Bad' }], generalPractitioner: [{ reference: '#nobody' }] }; + await q.run('UPDATE Versions SET Compressed = 0, Content = ? WHERE VersionKey = ?', [Buffer.from(JSON.stringify(res)), v.MostRecent]); + await q.exec('DELETE FROM Contained'); + await q.exec('DELETE FROM IndexReferences'); + await q.exec('DELETE FROM IndexStrings WHERE ResourceKey < 0'); + await q.run("INSERT INTO Config (Name, Value) VALUES ('reindexAll', '1')"); + }); + t.ep.reindexAll = true; + while (await t.ep.reindexBatch() > 0) { + // the next batch + } + expect(await found('/r4/Patient?general-practitioner.name=platypus')).toEqual([id]); + expect(await containedRows()).toHaveLength(1); + }); + + describe('_contained and _containedType', () => { + const ids = {}; + const bundle = async (url) => { + const r = await request(t.app).get(url); + expect(r.status).toBe(200); + return r.body; + }; + const entries = (b) => (b.entry || []).filter(e => e.search.mode !== 'outcome') + .map(e => `${e.search.mode} ${e.fullUrl.replace('http://test.example/r4/', '')}`).sort(); + + beforeEach(async () => { + ids.real = await post(gp('Platypus', { id: undefined })); + ids.p1 = await post({ resourceType: 'Patient', name: [{ family: 'One' }], + contained: [gp('Platypus'), { resourceType: 'Practitioner', id: 'gp2', name: [{ family: 'Platypus' }, { family: 'Wombat' }] }], + generalPractitioner: [{ reference: '#gp' }, { reference: '#gp2' }] }); + ids.p2 = await post({ resourceType: 'Patient', name: [{ family: 'Two' }], contained: [gp('Echidna')], generalPractitioner: [{ reference: '#gp' }] }); + }); + + test('false (the default) finds only resources of their own', async () => { + expect(entries(await bundle('/r4/Practitioner?name=platypus'))).toEqual([`match Practitioner/${ids.real}`]); + expect(entries(await bundle('/r4/Practitioner?name=platypus&_contained=false'))).toEqual([`match Practitioner/${ids.real}`]); + }); + + test('true finds contained resources, and returns their containers, once each', async () => { + const b = await bundle('/r4/Practitioner?name=platypus&_contained=true'); + expect(entries(b)).toEqual([`match Patient/${ids.p1}`]); + expect(b.total).toBe(1); + expect(entries(await bundle('/r4/Practitioner?_contained=true'))).toEqual([`match Patient/${ids.p1}`, `match Patient/${ids.p2}`]); + expect((await bundle('/r4/Practitioner?name=platypus&_contained=true&_summary=count')).total).toBe(1); + expect((await bundle('/r4/Practitioner?_contained=true&_summary=count')).total).toBe(2); + }); + + test('both finds either', async () => { + expect(entries(await bundle('/r4/Practitioner?name=platypus&_contained=both'))) + .toEqual([`match Patient/${ids.p1}`, `match Practitioner/${ids.real}`]); + }); + + test('_containedType=contained returns the contained resources themselves', async () => { + const b = await bundle('/r4/Practitioner?name=platypus&_contained=true&_containedType=contained'); + expect(entries(b)).toEqual([`match Patient/${ids.p1}#gp`, `match Patient/${ids.p1}#gp2`]); + expect(b.total).toBe(2); + expect(b.entry.every(e => e.resource.resourceType === 'Practitioner')).toBe(true); + expect(b.entry.find(e => e.resource.id === 'gp2').resource.name).toHaveLength(2); + expect(entries(await bundle('/r4/Practitioner?name=platypus&_contained=both&_containedType=contained'))) + .toEqual([`match Patient/${ids.p1}#gp`, `match Patient/${ids.p1}#gp2`, `match Practitioner/${ids.real}`]); + expect((await bundle('/r4/Practitioner?_contained=true&_containedType=contained&_summary=count')).total).toBe(3); + }); + + test('_id is the local id, and _lastUpdated the container\'s', async () => { + expect(entries(await bundle('/r4/Practitioner?_id=gp&_contained=true&_containedType=contained'))) + .toEqual([`match Patient/${ids.p1}#gp`, `match Patient/${ids.p2}#gp`]); + expect(entries(await bundle('/r4/Practitioner?_id:not=gp&_contained=true&_containedType=contained'))).toEqual([`match Patient/${ids.p1}#gp2`]); + expect(entries(await bundle(`/r4/Practitioner?_id=${ids.real}&_contained=both`))).toEqual([`match Practitioner/${ids.real}`]); + expect((await bundle('/r4/Practitioner?_lastUpdated=gt2020-01-01&_contained=true&_containedType=contained&_summary=count')).total).toBe(3); + expect((await bundle('/r4/Practitioner?_lastUpdated=lt2020-01-01&_contained=true&_summary=count')).total).toBe(0); + }); + + test('sorting, and paging through contained resources', async () => { + const b = await bundle('/r4/Practitioner?_contained=both&_containedType=contained&_sort=-family,_id&_count=2'); + const url = (e) => e.fullUrl.replace('http://test.example/r4/', ''); + const seen = b.entry.filter(e => e.search.mode === 'match').map(url); + let next = b.link.find(l => l.relation === 'next'); + while (next) { + const nb = await bundle(next.url.replace('http://test.example', '')); + seen.push(...nb.entry.filter(e => e.search.mode === 'match').map(url)); + next = nb.link.find(l => l.relation === 'next'); + } + // gp2 is Platypus and Wombat: it sorts by the highest, Wombat; the two other Platypuses tie + expect(seen).toHaveLength(4); + expect(seen[0]).toBe(`Patient/${ids.p1}#gp2`); + expect(seen.slice(1, 3).sort()).toEqual([`Patient/${ids.p1}#gp`, `Practitioner/${ids.real}`].sort()); + expect(seen[3]).toBe(`Patient/${ids.p2}#gp`); + }); + + test('_include and _revinclude work from contained matches', async () => { + const b = await bundle('/r4/Practitioner?name=echidna&_contained=true&_containedType=contained&_revinclude=Patient:general-practitioner'); + expect(entries(b)).toEqual([`include Patient/${ids.p2}`, `match Patient/${ids.p2}#gp`]); + }); + + test('a compartment search goes by the container', async () => { + const pat = await post({ resourceType: 'Patient', name: [{ family: 'Three' }] }); + const list = await post({ resourceType: 'List', status: 'current', mode: 'working', subject: { reference: `Patient/${pat}` }, + contained: [{ resourceType: 'Observation', id: 'o', status: 'final', code: { text: 'x' } }], entry: [{ item: { reference: '#o' } }] }); + expect(entries(await bundle(`/r4/Patient/${pat}/Observation?_contained=true`))).toEqual([`match List/${list}`]); + expect(entries(await bundle(`/r4/Patient/${pat}/Observation?_contained=true&_containedType=contained`))).toEqual([`match List/${list}#o`]); + expect(entries(await bundle(`/r4/Patient/${ids.p1}/Observation?_contained=true`))).toEqual([]); + }); + + test('bad values are errors', async () => { + expect((await request(t.app).get('/r4/Practitioner?_contained=maybe')).status).toBe(400); + expect((await request(t.app).get('/r4/Practitioner?_contained=true&_containedType=either')).status).toBe(400); + }); + }); +}); diff --git a/tests/rest/fulltext.test.js b/tests/rest/fulltext.test.js new file mode 100644 index 00000000..bd30f3bf --- /dev/null +++ b/tests/rest/fulltext.test.js @@ -0,0 +1,208 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +const request = require('supertest'); +const { engines, makeApp, body, invariants, FHIR_JSON } = require('./helpers'); +const { narrativeText, contentText, parseQuery, fts5, mysqlBoolean } = require('../../rest/indexing/fulltext'); +const { SCHEMA_VERSION } = require('../../rest/database/schema'); + +describe('full-text: text and query syntax', () => { + test('the narrative\'s text: markup out, entities decoded', () => { + expect(narrativeText('

Peter James&Chalmers <x>

')) + .toBe('Peter James &Chalmers '); + expect(narrativeText('')).toBe(''); + expect(narrativeText(null)).toBe(''); + expect(narrativeText('unclosed '.repeat(200000)); + expect(Date.now() - start).toBeLessThan(1000); + }); + + test('the content\'s text: the values, not the element names, the meta or base64 data', () => { + const t = contentText({ resourceType: 'Patient', meta: { versionId: '3', tag: [{ code: 'secret-tag' }] }, active: true, + name: [{ family: 'Chalmers', given: ['Peter'] }], photo: [{ data: 'QUJDREVGR0g=' }], text: { div: '

Narrative words

' } }); + expect(t).toContain('Chalmers'); + expect(t).toContain('Peter'); + expect(t).toContain('Narrative words'); + expect(t).toContain('true'); + expect(t).not.toContain('family'); + expect(t).not.toContain('Patient'); + expect(t).not.toContain('QUJD'); + expect(t).not.toContain('secret-tag'); + expect(t).not.toContain('

'); + }); + + test('the query: words, phrases, AND, OR, NOT, brackets', () => { + expect(parseQuery('chest pain')).toEqual({ op: 'and', items: [{ op: 'term', words: ['chest'], prefix: true }, { op: 'term', words: ['pain'], prefix: true }] }); + expect(parseQuery('"Chest Pain"')).toEqual({ op: 'term', words: ['chest', 'pain'], prefix: false }); + expect(parseQuery('Müller')).toEqual({ op: 'term', words: ['muller'], prefix: true }); + // a word the index splits is matched as a phrase + expect(parseQuery('anna@example.org')).toEqual({ op: 'term', words: ['anna', 'example', 'org'], prefix: false }); + expect(parseQuery('a OR b c').op).toBe('or'); + expect(parseQuery('a AND (b OR c) -d NOT e')).toMatchObject({ op: 'and', items: [{ op: 'term' }, { op: 'or' }, { op: 'not' }, { op: 'not' }] }); + }); + + test('the query in each engine\'s syntax', () => { + const q = parseQuery('chest "blood pressure" (pain OR ache) -child'); + expect(fts5(q)).toBe('(("chest"* AND "blood pressure" AND ("pain"* OR "ache"*)) NOT ("child"*))'); + expect(mysqlBoolean(q)).toBe('+(+chest* +"blood pressure" +(pain* ache*) -child*)'); + expect(fts5(parseQuery('x'))).toBe('"x"*'); + expect(mysqlBoolean(parseQuery('x'))).toBe('+x*'); + }); + + test('what the engines are given has only letters, digits and the operators', () => { + const q = parseQuery('a*b "c:d" e\'f NEAR(x) {col}:y ^z'); + for (const s of [fts5(q), mysqlBoolean(q)]) { + expect(s).not.toMatch(/[:'{}^]/); + } + }); + + test('values that can\'t be searched', () => { + for (const v of ['', ' ', '"unclosed', '-alone', 'NOT x', '(a', 'a)', 'a OR', '***', 'a OR -b', 'x'.repeat(1001), Array(40).fill('w').join(' ')]) { + expect(() => parseQuery(v)).toThrow(); + } + }); +}); + +describe.each(engines())('full-text search (%s)', (engine) => { + let t; + const ids = {}; + const post = async (r) => { + const res = await request(t.app).post(`/r4/${r.resourceType}`).set('Content-Type', FHIR_JSON).send(body(r)); + expect(res.status).toBe(201); + return res.body.id; + }; + const found = async (url, status = 200) => { + const r = await request(t.app).get(url); + expect(r.status).toBe(status); + return (r.body.entry || []).filter(e => e.search && e.search.mode === 'match').map(e => e.resource.id).sort(); + }; + const div = (s) => ({ status: 'generated', div: `

${s}
` }); + + beforeAll(async () => { + t = await makeApp(engine); + ids.p1 = await post({ resourceType: 'Patient', text: div('

Peter James Chalmers, seen for chest pain

'), name: [{ family: 'Chalmers', given: ['Peter'] }], + identifier: [{ system: 'urn:mrn', value: 'MRN12345' }] }); + ids.p2 = await post({ resourceType: 'Patient', text: div('

Anna Müller: blood pressure check

'), name: [{ family: 'Müller', given: ['Anna'] }], + telecom: [{ system: 'email', value: 'anna@example.org' }] }); + ids.p3 = await post({ resourceType: 'Patient', text: div('

Child, chest infection

'), name: [{ family: 'Smith' }], photo: [{ contentType: 'text/plain', data: Buffer.from('hidden-in-base64').toString('base64') }] }); + ids.o1 = await post({ resourceType: 'Observation', status: 'final', code: { coding: [{ system: 'http://loinc.org', code: '85354-9', display: 'Blood pressure panel' }] }, + subject: { reference: `Patient/${ids.p2}` }, text: div('

Systolic 140

') }); + }); + afterAll(async () => { + await t.close(); + }); + + test('_text: words in the narrative, as prefixes, accents and case folded', async () => { + expect(await found('/r4/Patient?_text=chalmers')).toEqual([ids.p1]); + expect(await found('/r4/Patient?_text=CHALM')).toEqual([ids.p1]); + expect(await found('/r4/Patient?_text=muller')).toEqual([ids.p2]); + expect(await found('/r4/Patient?_text=Müller')).toEqual([ids.p2]); + expect(await found('/r4/Patient?_text=chest')).toEqual([ids.p1, ids.p3].sort()); + }); + + test('_text: AND (implied), OR, NOT, phrases, brackets', async () => { + expect(await found('/r4/Patient?_text=' + encodeURIComponent('chest pain'))).toEqual([ids.p1]); + expect(await found('/r4/Patient?_text=' + encodeURIComponent('chest AND infection'))).toEqual([ids.p3]); + expect(await found('/r4/Patient?_text=' + encodeURIComponent('pain OR pressure'))).toEqual([ids.p1, ids.p2].sort()); + expect(await found('/r4/Patient?_text=' + encodeURIComponent('chest -child'))).toEqual([ids.p1]); + expect(await found('/r4/Patient?_text=' + encodeURIComponent('chest NOT child'))).toEqual([ids.p1]); + expect(await found('/r4/Patient?_text=' + encodeURIComponent('"blood pressure"'))).toEqual([ids.p2]); + expect(await found('/r4/Patient?_text=' + encodeURIComponent('"pressure blood"'))).toEqual([]); + expect(await found('/r4/Patient?_text=' + encodeURIComponent('(pain OR infection) chest'))).toEqual([ids.p1, ids.p3].sort()); + }); + + test('_content: anywhere in the resource, but not element names or base64 data', async () => { + expect(await found('/r4/Patient?_content=mrn12345')).toEqual([ids.p1]); + expect(await found('/r4/Patient?_content=' + encodeURIComponent('anna@example.org'))).toEqual([ids.p2]); + expect(await found('/r4/Observation?_content=panel')).toEqual([ids.o1]); + // the narrative's words are content too + expect(await found('/r4/Observation?_content=systolic')).toEqual([ids.o1]); + // but _text is only the narrative + expect(await found('/r4/Observation?_text=panel')).toEqual([]); + expect(await found('/r4/Patient?_content=family')).toEqual([]); + expect(await found('/r4/Patient?_content=hidden')).toEqual([]); + }); + + test('with other parameters, through a chain, and across types', async () => { + expect(await found('/r4/Patient?_text=chest&family=smith')).toEqual([ids.p3]); + expect(await found('/r4/Observation?subject._text=pressure')).toEqual([ids.o1]); + const all = await request(t.app).get('/r4?_type=Patient,Observation&_content=pressure'); + expect(all.body.total).toBe(2); + }); + + test('the index follows the resource: updates and deletes', async () => { + const id = await post({ resourceType: 'Patient', text: div('

Zebrafish

') }); + expect(await found('/r4/Patient?_text=zebrafish')).toEqual([id]); + await request(t.app).put(`/r4/Patient/${id}`).set('Content-Type', FHIR_JSON).send(body({ resourceType: 'Patient', id, text: div('

Aardvark

') })); + expect(await found('/r4/Patient?_text=zebrafish')).toEqual([]); + expect(await found('/r4/Patient?_text=aardvark')).toEqual([id]); + await request(t.app).delete(`/r4/Patient/${id}`); + expect(await found('/r4/Patient?_text=aardvark')).toEqual([]); + expect(await invariants(t.ep)).toEqual([]); + }); + + test('a transaction that fails leaves no text behind', async () => { + const r = await request(t.app).post('/r4').set('Content-Type', FHIR_JSON).send(body({ resourceType: 'Bundle', type: 'transaction', entry: [ + { resource: { resourceType: 'Patient', text: div('

Quokka

') }, request: { method: 'POST', url: 'Patient' } }, + { resource: { resourceType: 'Observation', status: 'final', code: { text: 'x' }, subject: { reference: 'Patient/nobody' } }, request: { method: 'POST', url: 'Observation' } } + ] })); + expect(r.status).toBe(422); + expect(await found('/r4/Patient?_text=quokka')).toEqual([]); + expect(await invariants(t.ep)).toEqual([]); + }); + + test('bad values are refused', async () => { + await found('/r4/Patient?_text=' + encodeURIComponent('"unclosed'), 400); + await found('/r4/Patient?_text=' + encodeURIComponent('-only'), 400); + await found('/r4/Patient?_text:exact=x', 200); + const strict = await request(t.app).get('/r4/Patient?_text:exact=x').set('Prefer', 'handling=strict'); + expect(strict.status).toBe(400); + }); + + test('in the CapabilityStatement', async () => { + const cs = (await request(t.app).get('/r4/metadata')).body; + const names = cs.rest[0].searchParam.map(p => p.name); + expect(names).toContain('_text'); + expect(names).toContain('_content'); + }); +}); + +describe.each(engines())('full-text: a version 1 database is brought up to date (%s)', (engine) => { + test('the table is made, and what was there is reindexed in the background', async () => { + let t = await makeApp(engine); + const r = await request(t.app).post('/r4/Patient').set('Content-Type', FHIR_JSON) + .send(body({ resourceType: 'Patient', text: { status: 'generated', div: '
Platypus
' } })); + const id = r.body.id; + // back to version 1: no full-text table (nor the Contained table of version 3) + await t.ep.db.write(async (q) => { + await q.exec('DROP TABLE TextIndex'); + await q.exec('DROP TABLE Contained'); + await q.run('UPDATE Config SET Value = ? WHERE Name = ?', ['1', 'schemaVersion']); + }); + await t.mod.shutdown(); + t = await makeApp(engine, { dir: t.dir, keep: true }); + try { + const v = await t.ep.db.read(q => q.get('SELECT Value FROM Config WHERE Name = ?', ['schemaVersion'])); + expect(v.Value).toBe(String(SCHEMA_VERSION)); + expect(t.ep.reindexAll).toBe(true); + // not indexed yet: found nothing, and says why + const before = await request(t.app).get('/r4/Patient?_text=platypus'); + expect(before.body.total).toBe(0); + expect(before.body.entry.some(e => e.search.mode === 'outcome' && /still being built/.test(JSON.stringify(e.resource)))).toBe(true); + while (await t.ep.reindexBatch() > 0) { + // the next batch + } + expect(t.ep.reindexAll).toBe(false); + const after = await request(t.app).get('/r4/Patient?_text=platypus'); + expect(after.body.entry.map(e => e.resource.id)).toEqual([id]); + expect(await t.ep.db.read(q => q.get('SELECT Value FROM Config WHERE Name = ?', ['reindexAll']))).toBeFalsy(); + } finally { + await t.close(); + } + }); +}); diff --git a/tests/rest/helpers.js b/tests/rest/helpers.js index 99a63236..ff59b30a 100644 --- a/tests/rest/helpers.js +++ b/tests/rest/helpers.js @@ -53,8 +53,8 @@ async function emptyMysql(cfg) { const conn = await mysql.createConnection({ host: cfg.host, port: cfg.port, user: cfg.user, password: process.env[cfg.passwordEnv], database: cfg.database }); try { await conn.query('SET FOREIGN_KEY_CHECKS = 0'); - for (const t of TABLES) { - await conn.query(`DROP TABLE IF EXISTS ${t.name}`); + for (const t of [...TABLES.map(x => x.name), 'TextIndex', 'Contained']) { + await conn.query(`DROP TABLE IF EXISTS ${t}`); } } finally { await conn.end(); @@ -121,9 +121,9 @@ function body(resource) { async function snapshot(ep) { return ep.db.read(async (q) => { const out = {}; - for (const t of TABLES) { - const r = await q.get(`SELECT COUNT(*) AS N FROM ${t.name}`); - out[t.name] = Number(r.N); + for (const t of [...TABLES.map(x => x.name), 'TextIndex', 'Contained']) { + const r = await q.get(`SELECT COUNT(*) AS N FROM ${t}`); + out[t] = Number(r.N); } return out; }); @@ -174,10 +174,28 @@ async function invariants(ep) { if (Number(r.N)) { problems.push(`${t} has ${r.N} rows for deleted resources`); } - const o = await q.get(`SELECT COUNT(*) AS N FROM ${t} x LEFT JOIN Ids i ON i.ResourceKey = x.ResourceKey WHERE i.ResourceKey IS NULL`); + const o = await q.get(`SELECT COUNT(*) AS N FROM ${t} x LEFT JOIN Ids i ON i.ResourceKey = x.ResourceKey WHERE i.ResourceKey IS NULL AND x.ResourceKey > 0`); if (Number(o.N)) { problems.push(`${t} has ${o.N} rows for resources that don't exist`); } + // contained resources are indexed under -ContainedKey + const c = await q.get(`SELECT COUNT(*) AS N FROM ${t} x LEFT JOIN Contained c ON c.ContainedKey = -x.ResourceKey WHERE x.ResourceKey < 0 AND c.ContainedKey IS NULL`); + if (Number(c.N)) { + problems.push(`${t} has ${c.N} rows for contained resources that aren't in Contained`); + } + } + const cDeleted = await q.get('SELECT COUNT(*) AS N FROM Contained c JOIN Ids i ON i.ResourceKey = c.ResourceKey WHERE i.Deleted = 1'); + if (Number(cDeleted.N)) { + problems.push(`Contained has ${cDeleted.N} rows for deleted resources`); + } + const cOrphans = await q.get('SELECT COUNT(*) AS N FROM Contained c LEFT JOIN Ids i ON i.ResourceKey = c.ResourceKey WHERE i.ResourceKey IS NULL'); + if (Number(cOrphans.N)) { + problems.push(`Contained has ${cOrphans.N} rows for resources that don't exist`); + } + const cDangling = await q.get(`SELECT COUNT(*) AS N FROM IndexReferences r LEFT JOIN Contained c ON c.ContainedKey = -r.TargetKey + WHERE r.TargetKey < 0 AND c.ContainedKey IS NULL`); + if (Number(cDangling.N)) { + problems.push(`${cDangling.N} references to contained resources that aren't in Contained`); } const unkeyed = await q.all(`SELECT r.TargetType, r.TargetId FROM IndexReferences r JOIN Ids i ON i.Id = r.TargetId JOIN Types t ON t.TypeKey = i.TypeKey AND t.Name = r.TargetType WHERE r.TargetKey IS NULL AND i.MostRecent IS NOT NULL`); @@ -189,6 +207,15 @@ async function invariants(ep) { for (const u of wrong) { problems.push(`a reference to ${u.TargetType}/${u.TargetId} is keyed to another resource`); } + const ftKey = q.dialect.name === 'sqlite' ? 'rowid' : 'ResourceKey'; + const ftDeleted = await q.get(`SELECT COUNT(*) AS N FROM TextIndex f JOIN Ids i ON i.ResourceKey = f.${ftKey} WHERE i.Deleted = 1`); + if (Number(ftDeleted.N)) { + problems.push(`TextIndex has ${ftDeleted.N} rows for deleted resources`); + } + const ftOrphans = await q.get(`SELECT COUNT(*) AS N FROM TextIndex f LEFT JOIN Ids i ON i.ResourceKey = f.${ftKey} WHERE i.ResourceKey IS NULL`); + if (Number(ftOrphans.N)) { + problems.push(`TextIndex has ${ftOrphans.N} rows for resources that don't exist`); + } const sq = await q.get('SELECT COUNT(*) AS N FROM SubscriptionQueue'); if (Number(sq.N) !== versions.length) { problems.push(`${sq.N} subscription queue rows for ${versions.length} versions`); diff --git a/tests/rest/search.test.js b/tests/rest/search.test.js index 8cc083d1..3eb7fcaa 100644 --- a/tests/rest/search.test.js +++ b/tests/rest/search.test.js @@ -260,6 +260,38 @@ describe.each(engines())('rest search (%s)', (engine) => { expect(found(r.body)).toEqual([ids.p3]); }); + test('_filter: a filter in brackets on a path step applies to the same target', async () => { + const fam = 'Brack' + Date.now().toString(36); + const org = await post({ resourceType: 'Organization', name: 'Bracket Clinic' }); + const smithOff = await post({ resourceType: 'Practitioner', name: [{ family: fam }], active: false }); + const jonesOn = await post({ resourceType: 'Practitioner', name: [{ family: 'Other' + fam }], active: true }); + const smithOn = await post({ resourceType: 'Practitioner', name: [{ family: fam }], active: true }); + const obs = (performers, extra = {}) => post({ resourceType: 'Observation', status: 'final', code: { text: fam }, + performer: performers.map(p => ({ reference: p })), ...extra }); + // two performers who meet the conditions only between them + const between = await obs([`Practitioner/${smithOff}`, `Practitioner/${jonesOn}`]); + // one performer who meets both + const one = await obs([`Practitioner/${smithOn}`]); + const f = (x) => search('/r4/Observation?_filter=' + encodeURIComponent(x)).then(found); + expect(await f(`performer.family eq ${fam} and performer.active eq true`)).toEqual([between, one].sort()); + expect(await f(`performer[family eq ${fam}].active eq true`)).toEqual([one]); + expect(await f(`performer[family eq ${fam} and active eq false].family eq ${fam}`)).toEqual([between]); + expect(await f(`performer[family eq ${fam}].active eq true or code eq nothing`)).toEqual([one]); + expect(await f(`not (performer[family eq ${fam}].active eq true) and performer.family eq ${fam}`)).toEqual([between]); + // nested: a bracket in a later step + const pid = await post({ resourceType: 'Patient', name: [{ family: fam }], managingOrganization: { reference: `Organization/${org}` } }); + const sub = await obs([], { subject: { reference: `Patient/${pid}` } }); + expect(await f(`subject[family eq ${fam}].organization[name sw bracket].name sw bracket`)).toEqual([sub]); + expect(await f(`subject[family eq nobody].organization.name sw bracket`)).toEqual([]); + // what isn't a path with a filter + await search('/r4/Observation?_filter=' + encodeURIComponent(`performer[family eq ${fam}] pr true`), 400); + await search('/r4/Observation?_filter=' + encodeURIComponent('status[x eq y].z eq 1'), 400); + await search('/r4/Observation?_filter=' + encodeURIComponent('performer[family eq x.active eq true'), 400); + await search('/r4/Observation?_filter=' + encodeURIComponent('performer[].active eq true'), 400); + await search('/r4/Observation?_filter=' + encodeURIComponent('performer[nonsense eq 1].active eq true'), 400); + await search('/r4/Observation?_filter=' + encodeURIComponent('subject[organization[name eq a].organization[name eq b].name eq c].family eq d'), 400); + }); + test('_filter values are literal: backslashes, commas and dollars in them are just characters', async () => { // the value has two backslashes in a row, a comma and a dollar: a\\b,c$d const value = 'a' + '\\'.repeat(2) + 'b,c$d'; diff --git a/tests/rest/web.test.js b/tests/rest/web.test.js index 34627dc4..38bad117 100644 --- a/tests/rest/web.test.js +++ b/tests/rest/web.test.js @@ -13,13 +13,15 @@ const HTML = { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/ describe('rest web pages', () => { let t; let pid; + let oid; beforeAll(async () => { t = await makeApp('sqlite', { settings: { name: 'Web Test', description: 'Pages over the API' } }); pid = (await request(t.app).post('/r4/Patient').set('Content-Type', FHIR_JSON).send(body({ resourceType: 'Patient', identifier: [{ system: 'urn:mrn', value: '42' }], name: [{ family: 'Smith', given: ['Jo'] }], text: { status: 'generated', div: '

Jo Smith

' } }))).body.id; - await request(t.app).post('/r4/Observation').set('Content-Type', FHIR_JSON).send(body({ resourceType: 'Observation', status: 'final', - code: { coding: [{ system: 'http://loinc.org', code: '1-8', display: 'Thing' }] }, subject: { reference: `Patient/${pid}` } })); + oid = (await request(t.app).post('/r4/Observation').set('Content-Type', FHIR_JSON).send(body({ resourceType: 'Observation', status: 'final', + code: { coding: [{ system: 'http://loinc.org', code: '1-8', display: 'Thing' }] }, subject: { reference: `Patient/${pid}` }, + contained: [{ resourceType: 'Practitioner', id: 'gp', name: [{ family: 'Who' }] }], performer: [{ reference: '#gp' }] }))).body.id; }); afterAll(async () => { await t.close(); @@ -63,6 +65,10 @@ describe('rest web pages', () => { expect(inc).toContain('included'); const h = await page('/r4/_history'); expect(h).toContain('(created)'); + // a contained resource links to its container + const c = await page('/r4/Practitioner?_contained=true&_containedType=contained'); + expect(c).toContain(`Practitioner #gp in Observation/${oid}`); + expect(await page('/r4/Practitioner')).toContain('name="_contained"'); }); test('a resource: what identifies it, its narrative, its JSON', async () => { diff --git a/tx/cs/cs-omop.js b/tx/cs/cs-omop.js index 47ad5075..2416012e 100644 --- a/tx/cs/cs-omop.js +++ b/tx/cs/cs-omop.js @@ -657,7 +657,19 @@ class OMOPServices extends BaseCSServices { return false; } - return set.rows.some(row => row.concept_id.toString() === concept.code); + // a filter prepared for checking codes (not iterating) is never run - its query asks about + // one concept_id - so it has no rows, and the code is asked about directly. (Checking the + // empty rows meant no code was ever in an OMOP domain filter.) Never run the whole filter + // just to check one code: it's every standard concept in the domain, turned into objects on + // the event loop + if (!set.executed) { + const row = await set.executeForLocate([set.value, concept.code]); + return !!row && String(row.concept_id) === concept.code; + } + if (!set.codes) { + set.codes = new Set(set.rows.map(row => String(row.concept_id))); + } + return set.codes.has(concept.code); } async filterFinish(filterContext) { diff --git a/tx/cs/cs-rxnorm.js b/tx/cs/cs-rxnorm.js index e0926ac5..fa7ee000 100644 --- a/tx/cs/cs-rxnorm.js +++ b/tx/cs/cs-rxnorm.js @@ -707,8 +707,14 @@ class RxNormServices extends BaseCSServices { return false; } + // a filter that has already been run (an expansion, or a value set whose filter results are + // kept between requests) answers from its rows. One that hasn't is not run just to check one + // code: tty = SCD alone is 40,000 rows, all turned into objects on the event loop, and a + // client that sends its value sets as tx-resource has every filter run again on every request + // (tx.fhir.org, 2026-11-23). Asking the database about the one code costs a few ms, off the + // event loop if (!set.executed) { - await this.#executeFilter(set); + return (await this.filterLocate(filterContext, set, concept.code)) !== null; } if (!set.codes) { set.codes = new Set(set.results.map(row => row[this.getCodeField()])); diff --git a/tx/vs/vs-vsac.js b/tx/vs/vs-vsac.js index de0ee47c..b400dd8e 100644 --- a/tx/vs/vs-vsac.js +++ b/tx/vs/vs-vsac.js @@ -491,6 +491,9 @@ class VSACValueSetProvider extends AbstractValueSetProvider { this.isRefreshing = true; const runId = await this.database.startRun(); + // what phase 2 has written (phases 1 and 1b only read): a run that fails before writing + // anything has nothing for the followers to catch up with + let tracking = { totalFetched: 0, totalNew: 0, totalUpdated: 0, count: 0, newCount : 0 }; try { // phase 1: list all value sets @@ -555,7 +558,6 @@ class VSACValueSetProvider extends AbstractValueSetProvider { this.queue = [...new Set([...leftover, ...this.queue])]; await this._savePendingQueue(this.queue); - let tracking = { totalFetched: 0, totalNew: 0, totalUpdated: 0, count: 0, newCount : 0 }; // URLs that fail even after a requeue are permanently dropped this run; we // hold the watermark back when this is non-zero so they get re-scanned. let permanentFailures = 0; @@ -621,8 +623,10 @@ class VSACValueSetProvider extends AbstractValueSetProvider { debugLog(error, 'Error during VSAC refresh:'); this.stats.taskError('VSAC Sync', `Error (${error.message})`); await this.database.failRun(runId, error.message); - if (this.cluster) { - // what the run wrote before it failed is in the database + if (this.cluster && (tracking.totalNew > 0 || tracking.totalUpdated > 0)) { + // what the run wrote before it failed is in the database. A run that wrote nothing + // (VSAC refusing the first request, say) leaves the followers alone: catching up + // drops every process's recently used value sets for nothing await this.database.bumpGeneration(); } throw error; @@ -703,6 +707,51 @@ class VSACValueSetProvider extends AbstractValueSetProvider { return { newCount, updatedCount }; } + /** + * The error for a failed request to VSAC, saying what VSAC said: the status alone doesn't + * (the status text is empty over HTTP/2), and a 401 with a key that works before and after + * can't be looked into without the body and the WWW-Authenticate header. Our own + * Authorization header is never included + * @param {Error} error - the axios error + * @param {string} url - the URL asked for (relative to the base URL) + * @returns {Error} + * @private + */ + _httpError(error, url) { + let msg; + if (error.response) { + const res = error.response; + msg = `HTTP ${res.status}${res.statusText ? ' ' + res.statusText : ''} for ${url}`; + const challenge = res.headers && res.headers['www-authenticate']; + if (challenge) { + msg += ` (WWW-Authenticate: ${challenge})`; + } + let body = res.data; + if (body !== undefined && body !== null && body !== '') { + if (Buffer.isBuffer(body)) { + body = body.toString('utf8'); + } else if (typeof body !== 'string') { + try { + body = JSON.stringify(body); + } catch (e) { + body = String(body); + } + } + body = body.replace(/\s+/g, ' ').trim(); + msg += `: ${body.length > 300 ? body.substring(0, 300) + '...' : body}`; + } + } else if (error.request) { + msg = `Network error: No response received for ${url}${error.code ? ' (' + error.code + ')' : ''}`; + } else { + msg = `Request error for ${url}: ${error.message}`; + } + const result = new Error(msg); + if (error.response) { + result.status = error.response.status; + } + return result; + } + /** * Fetch a FHIR Bundle from the server * @param {string} url - Relative URL to fetch @@ -719,13 +768,7 @@ class VSACValueSetProvider extends AbstractValueSetProvider { throw new Error('VSAC Response is not a FHIR Bundle'); } } catch (error) { - if (error.response) { - throw new Error(`HTTP ${error.response.status}: ${error.response.statusText}`); - } else if (error.request) { - throw new Error('Network error: No response received'); - } else { - throw new Error(`Request error: ${error.message}`); - } + throw this._httpError(error, url); } } @@ -745,13 +788,7 @@ class VSACValueSetProvider extends AbstractValueSetProvider { throw new Error('VSAC Response is not a FHIR ValueSet'); } } catch (error) { - if (error.response) { - throw new Error(`HTTP ${error.response.status}: ${error.response.statusText}`); - } else if (error.request) { - throw new Error('Network error: No response received'); - } else { - throw new Error(`Request error: ${error.message}`); - } + throw this._httpError(error, "/ValueSet/"+id); } }