Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion rest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down
40 changes: 38 additions & 2 deletions rest/database/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
* @module rest/database/schema
*/

const SCHEMA_VERSION = 1;
const SCHEMA_VERSION = 3;

// columns every index table has
const INDEX_COMMON = [
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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]);
Expand Down Expand Up @@ -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 };
9 changes: 7 additions & 2 deletions rest/endpoint/endpoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -596,7 +599,7 @@ class Endpoint {
* @returns {Promise<number>} 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']));
Expand All @@ -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) {
Expand All @@ -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;
Expand Down
17 changes: 14 additions & 3 deletions rest/indexing/definitions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 };
Loading
Loading