From 5ed26efafc1be02a70159491b4314d274694713f Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Thu, 3 Dec 2026 06:40:10 +1100 Subject: [PATCH 1/2] bring importers into line, and improve documentation --- CHANGELOG.md | 2 +- tests/tx/sqlite-v2-cli-options.test.js | 106 ++++++++++++++++++ .../import-loinc-v2-classic.module.js | 17 +-- tx/importers/import-loinc-v2.module.js | 15 +-- tx/importers/import-rxnorm-v2.module.js | 17 +-- tx/importers/import-sct-v2-cache.module.js | 13 ++- tx/importers/import-sct-v2.module.js | 17 +-- tx/importers/readme.md | 64 ++++++++++- tx/importers/sqlite-v2/cli-options.js | 86 ++++++++++++++ tx/sqlite-v2/README.md | 6 +- 10 files changed, 303 insertions(+), 40 deletions(-) create mode 100644 tests/tx/sqlite-v2-cli-options.test.js create mode 100644 tx/importers/sqlite-v2/cli-options.js diff --git a/CHANGELOG.md b/CHANGELOG.md index f3507a1b0..72f7bb60b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed -- +- tx-import: the sqlite-v2 importers (`loinc-v2`, `loinc-v2-classic`, `snomed-v2`, `snomed-v2-from-cache`, `rxnorm-v2`) take the classic importers' options: `-v, --version` for the release's version (`snomed-v2`'s was `--snomed-version`) and `-y, --yes` to replace an existing destination; without `-y` an existing destination is asked about. The earlier names (`--loinc-version`, `--rxnorm-version`, `--snomed-version`, `--overwrite`) still work. Documented in tx/importers/readme.md ### Fixed diff --git a/tests/tx/sqlite-v2-cli-options.test.js b/tests/tx/sqlite-v2-cli-options.test.js new file mode 100644 index 000000000..230623d41 --- /dev/null +++ b/tests/tx/sqlite-v2-cli-options.test.js @@ -0,0 +1,106 @@ +/** + * The sqlite-v2 importers take the classic importers' options (tx/importers/sqlite-v2/cli-options.js): + * -v, --version and -y, --yes, with their earlier names (--loinc-version, --overwrite...) still + * working, hidden. An existing destination without -y is asked about, or refused with no one to ask. + */ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { Command } = require('commander'); +const inquirer = require('inquirer'); +const { addCommonOptions, resolveCommonOptions, importAction } = require('../../tx/importers/sqlite-v2/cli-options'); + +const VERSION = { arg: 'version', help: 'e.g. 2.83', oldFlag: 'loinc-version', required: true }; + +// parse args as tx-import import would, and resolve the common options +async function run(args, version = VERSION) { + let result; + const program = new Command().exitOverride(); + addCommonOptions(program.command('import') + .requiredOption('-s, --source ', 'source') + .requiredOption('-d, --dest ', 'dest'), version) + .exitOverride() + .action(async (o) => { + result = await resolveCommonOptions(o, version); + }); + await program.parseAsync(['import', ...args], { from: 'user' }); + return result; +} + +describe('sqlite-v2 importer options', () => { + let dir; + let dest; + let tty; + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'v2-cli-')); + dest = path.join(dir, 'loinc.db'); + tty = process.stdin.isTTY; + }); + afterEach(() => { + process.stdin.isTTY = tty; + jest.restoreAllMocks(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + test('-v and --version give the version; the earlier name still works', async () => { + expect((await run(['-s', dir, '-d', dest, '-v', '2.83'])).version).toBe('2.83'); + expect((await run(['-s', dir, '-d', dest, '--version', '2.83'])).version).toBe('2.83'); + expect((await run(['-s', dir, '-d', dest, '--loinc-version', '2.83'])).version).toBe('2.83'); + }); + + test('a required version that is missing is an error that says how to give it', async () => { + await expect(run(['-s', dir, '-d', dest])).rejects.toThrow('-v, --version is required (e.g. 2.83)'); + }); + + test('an importer that takes no version has no -v', async () => { + await expect(run(['-s', dir, '-d', dest, '-v', 'x'], null)).rejects.toThrow(/unknown option '-v'/); + expect((await run(['-s', dir, '-d', dest], null)).version).toBeUndefined(); + }); + + test('a destination that isn\'t there needs nothing; -y, --yes or --overwrite replace one that is', async () => { + expect((await run(['-s', dir, '-d', dest, '-v', '1'])).overwrite).toBe(false); + fs.writeFileSync(dest, 'x'); + expect((await run(['-s', dir, '-d', dest, '-v', '1', '-y'])).overwrite).toBe(true); + expect((await run(['-s', dir, '-d', dest, '-v', '1', '--yes'])).overwrite).toBe(true); + expect((await run(['-s', dir, '-d', dest, '-v', '1', '--overwrite'])).overwrite).toBe(true); + }); + + test('an existing destination without -y is asked about, or refused with no one to ask', async () => { + fs.writeFileSync(dest, 'x'); + process.stdin.isTTY = false; + await expect(run(['-s', dir, '-d', dest, '-v', '1'])).rejects.toThrow('use -y, --yes to replace it'); + process.stdin.isTTY = true; + const prompt = jest.spyOn(inquirer, 'prompt').mockResolvedValueOnce({ replace: true }).mockResolvedValueOnce({ replace: false }); + expect((await run(['-s', dir, '-d', dest, '-v', '1'])).overwrite).toBe(true); + await expect(run(['-s', dir, '-d', dest, '-v', '1'])).rejects.toThrow('Import cancelled'); + expect(prompt).toHaveBeenCalledTimes(2); + }); + + test('a failure is reported as the classic importers do, with exit code 1, not thrown', async () => { + const logged = []; + const module = { getName: () => 'loinc-v2', logError: (m) => logged.push(m) }; + const exitCode = process.exitCode; + const stack = jest.spyOn(console, 'error').mockImplementation(() => {}); + try { + await importAction(module, async () => { throw new Error('required LOINC file missing'); })({}); + expect(logged).toEqual(['loinc-v2 import failed: required LOINC file missing']); + expect(process.exitCode).toBe(1); + expect(stack).not.toHaveBeenCalled(); + await importAction(module, async () => { throw new Error('x'); })({ verbose: true }); + expect(stack).toHaveBeenCalledTimes(1); + } finally { + process.exitCode = exitCode; + } + }); + + test('the help shows -v, --version and -y, --yes, not the earlier names', () => { + const program = new Command(); + const cmd = addCommonOptions(program.command('import'), VERSION); + const help = cmd.helpInformation(); + expect(help).toContain('-v, --version '); + expect(help).toContain('-y, --yes'); + expect(help).toContain('--verbose'); + expect(help).not.toContain('--loinc-version'); + expect(help).not.toContain('--overwrite'); + }); +}); diff --git a/tx/importers/import-loinc-v2-classic.module.js b/tx/importers/import-loinc-v2-classic.module.js index b1dab5914..379b11e00 100644 --- a/tx/importers/import-loinc-v2-classic.module.js +++ b/tx/importers/import-loinc-v2-classic.module.js @@ -31,6 +31,7 @@ // literal either way, as cs-loinc.js reports them). const fs = require('fs'); +const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options'); const Database = require('better-sqlite3'); const { BaseTerminologyModule } = require('./tx-import-base'); const { TerminologyBuilder, vacuumFile } = require('./sqlite-v2/builder'); @@ -237,17 +238,17 @@ class LoincV2ClassicModule extends BaseTerminologyModule { getSupportedFormats() { return ['sqlite']; } registerCommands(cmd) { - cmd.command('import') + const version = { arg: 'version', help: 'checked against the classic Config (default: its version)', oldFlag: 'loinc-version' }; + addCommonOptions(cmd.command('import') .description('Convert a classic FHIRsmith LOINC .db into a terminology file') .requiredOption('-s, --source ', 'classic LOINC .db (e.g. loinc-2.77-a.db)') - .requiredOption('-d, --dest ', 'destination .db') - .option('-v, --loinc-version ', 'checked against the classic Config (default: its version)') - .option('--overwrite', 'replace the destination') - .action(async (o) => { - const s = await importLoincV2FromClassic({ source: o.source, dest: o.dest, version: o.loincVersion, - overwrite: !!o.overwrite, log: (m) => this.logInfo(m) }); + .requiredOption('-d, --dest ', 'destination .db'), version) + .action(importAction(this, async (o) => { + const c = await resolveCommonOptions(o, version); + const s = await importLoincV2FromClassic({ source: o.source, dest: o.dest, version: c.version, + overwrite: c.overwrite, log: (m) => this.logInfo(m) }); this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); - }); + })); } } diff --git a/tx/importers/import-loinc-v2.module.js b/tx/importers/import-loinc-v2.module.js index b73066415..653739bb6 100644 --- a/tx/importers/import-loinc-v2.module.js +++ b/tx/importers/import-loinc-v2.module.js @@ -30,6 +30,7 @@ // parent / child entry order) only when the parent links' seq does not reproduce it. const fs = require('fs'); +const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options'); const path = require('path'); const Database = require('better-sqlite3'); const { TerminologyBuilder, vacuumFile, analyze } = require('./sqlite-v2/builder'); @@ -519,16 +520,16 @@ class LoincV2Module extends BaseTerminologyModule { getSupportedFormats() { return ['directory']; } registerCommands(cmd) { - cmd.command('import') + const version = { arg: 'version', help: 'e.g. 2.83', oldFlag: 'loinc-version', required: true }; + addCommonOptions(cmd.command('import') .description('Import an unzipped LOINC release into a terminology file') .requiredOption('-s, --source ', 'release root (contains LoincTable/ and AccessoryFiles/)') - .requiredOption('-d, --dest ', 'destination .db') - .requiredOption('-v, --loinc-version ', 'e.g. 2.83') - .option('--overwrite', 'replace the destination') - .action(async (o) => { - const s = await importLoincV2({ source: o.source, dest: o.dest, version: o.loincVersion, overwrite: !!o.overwrite, log: (m) => this.logInfo(m) }); + .requiredOption('-d, --dest ', 'destination .db'), version) + .action(importAction(this, async (o) => { + const c = await resolveCommonOptions(o, version); + const s = await importLoincV2({ source: o.source, dest: o.dest, version: c.version, overwrite: c.overwrite, log: (m) => this.logInfo(m) }); this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); - }); + })); } } diff --git a/tx/importers/import-rxnorm-v2.module.js b/tx/importers/import-rxnorm-v2.module.js index e56567cc6..88cdcf8b4 100644 --- a/tx/importers/import-rxnorm-v2.module.js +++ b/tx/importers/import-rxnorm-v2.module.js @@ -31,6 +31,7 @@ // order concepts by (primary TTY rank, ingredient group): the numbering's sort key. const fs = require('fs'); +const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options'); const path = require('path'); const { BaseTerminologyModule } = require('./tx-import-base'); const { TerminologyBuilder } = require('./sqlite-v2/builder'); @@ -289,18 +290,18 @@ class RxNormV2Module extends BaseTerminologyModule { getSupportedFormats() { return ['directory']; } registerCommands(cmd) { - cmd.command('import') + const version = { arg: 'MMDDYYYY', help: 'e.g. 03022026', oldFlag: 'rxnorm-version', required: true }; + addCommonOptions(cmd.command('import') .description('Import an unzipped RxNorm full release (rrf folder) into a terminology file') .requiredOption('-s, --source ', 'the rrf/ folder of the release') .requiredOption('-d, --dest ', 'destination .db') - .requiredOption('-v, --rxnorm-version ', 'e.g. 03022026') - .option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI: filters (otherwise refused)') - .option('--overwrite', 'replace the destination') - .action(async (o) => { - const s = await importRxNormV2({ source: o.source, dest: o.dest, version: o.rxnormVersion, - overwrite: !!o.overwrite, atomRelationships: !!o.atomRelationships, log: (m) => this.logInfo(m) }); + .option('--atom-relationships', 'also store RXNREL\'s atom-level rows, for REL / RELA = AUI: filters (otherwise refused)'), version) + .action(importAction(this, async (o) => { + const c = await resolveCommonOptions(o, version); + const s = await importRxNormV2({ source: o.source, dest: o.dest, version: c.version, + overwrite: c.overwrite, atomRelationships: !!o.atomRelationships, log: (m) => this.logInfo(m) }); this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); - }); + })); } } diff --git a/tx/importers/import-sct-v2-cache.module.js b/tx/importers/import-sct-v2-cache.module.js index cf0cef6b9..3a536032f 100644 --- a/tx/importers/import-sct-v2-cache.module.js +++ b/tx/importers/import-sct-v2-cache.module.js @@ -16,6 +16,7 @@ // b082f98); known defects of older cache vintages stop the import unless forced. const path = require('path'); +const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options'); const { BaseTerminologyModule } = require('./tx-import-base'); const { SnomedStrings, SnomedReferences, SnomedDescriptions, SnomedConceptList, SnomedRelationshipList, @@ -367,18 +368,18 @@ class SnomedV2FromCacheModule extends BaseTerminologyModule { getSupportedFormats() { return ['file']; } registerCommands(cmd) { - cmd.command('import') + addCommonOptions(cmd.command('import') .description('Reverse-load a FHIRsmith SNOMED CT cache (*.cache) into a terminology file') .requiredOption('-s, --source ', 'the .cache file') .requiredOption('-d, --dest ', 'destination .db') .option('--date-shift ', 'days to add to every cache date (auto: fix caches built east of UTC)', 'auto') - .option('--overwrite', 'replace the destination') - .option('--force', 'import a cache with known defects (see the warnings)') - .action(async (o) => { - const s = await importSnomedV2FromCache({ source: o.source, dest: o.dest, overwrite: !!o.overwrite, + .option('--force', 'import a cache with known defects (see the warnings)')) + .action(importAction(this, async (o) => { + const c = await resolveCommonOptions(o); + const s = await importSnomedV2FromCache({ source: o.source, dest: o.dest, overwrite: c.overwrite, dateShift: o.dateShift, force: !!o.force, log: (msg) => this.logInfo(msg) }); this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); - }); + })); cmd.command('inspect') .description('Check FHIRsmith SNOMED CT caches for the known defects of older cache vintages (no import)') .argument('', '.cache files') diff --git a/tx/importers/import-sct-v2.module.js b/tx/importers/import-sct-v2.module.js index b1e65d480..abf557089 100644 --- a/tx/importers/import-sct-v2.module.js +++ b/tx/importers/import-sct-v2.module.js @@ -8,6 +8,7 @@ // module dependency refset as meta moduleDependencies). const path = require('path'); +const { addCommonOptions, resolveCommonOptions, importAction } = require('./sqlite-v2/cli-options'); const { BaseTerminologyModule } = require('./tx-import-base'); const { tsvRows, firstLine } = require('./sqlite-v2/text'); const { @@ -153,20 +154,20 @@ class SnomedV2Module extends BaseTerminologyModule { getSupportedFormats() { return ['directory']; } registerCommands(cmd) { - cmd.command('import') + const version = { arg: 'YYYYMMDD', help: 'release date', oldFlag: 'snomed-version', required: true }; + addCommonOptions(cmd.command('import') .description('Import an RF2 Snapshot into a terminology file') .requiredOption('-s, --source ', 'unzipped RF2 release (the Snapshot folder is used)') .requiredOption('-d, --dest ', 'destination .db') .requiredOption('-e, --edition ', 'edition module id') - .requiredOption('--snomed-version ', 'release date') .option('--version-uri ', 'version URI to record') - .option('--overwrite', 'replace the destination') - .option('-l, --language ', 'default language code') - .action(async (o) => { - const s = await importSnomedV2({ source: o.source, dest: o.dest, edition: o.edition, version: o.snomedVersion, - versionUri: o.versionUri, language: o.language, overwrite: !!o.overwrite, log: (m) => this.logInfo(m) }); + .option('-l, --language ', 'default language code'), version) + .action(importAction(this, async (o) => { + const c = await resolveCommonOptions(o, version); + const s = await importSnomedV2({ source: o.source, dest: o.dest, edition: o.edition, version: c.version, + versionUri: o.versionUri, language: o.language, overwrite: c.overwrite, log: (m) => this.logInfo(m) }); this.logSuccess(`${s.concepts.toLocaleString()} concepts -> ${o.dest}`); - }); + })); } } diff --git a/tx/importers/readme.md b/tx/importers/readme.md index ac74bb64f..706225252 100644 --- a/tx/importers/readme.md +++ b/tx/importers/readme.md @@ -12,6 +12,7 @@ additional terminologies. - [Common Commands](#common-commands) - [Configuration Management](#configuration-management) - [Terminology-Specific Usage](#terminology-specific-usage) + - [sqlite-v2 Terminology Files](#sqlite-v2-terminology-files) - [Advanced Features](#advanced-features) - [Troubleshooting](#troubleshooting) @@ -65,6 +66,7 @@ additional terminologies. | **RxNorm Subset** | `rxnorm-subset` | Create RxNorm subsets for testing | 10-30 min | | **UNII** | `unii` | Unique Ingredient Identifier (FDA) | 15-45 min | | **NDC** | `ndc` | National Drug Code Directory | 30-90 min | +| **sqlite-v2 files** | `loinc-v2`, `loinc-v2-classic`, `snomed-v2`, `snomed-v2-from-cache`, `rxnorm-v2` | LOINC, SNOMED CT and RxNorm as sqlite-v2 terminology files - see [sqlite-v2 Terminology Files](#sqlite-v2-terminology-files) | varies | ## Common Commands @@ -495,6 +497,65 @@ json is the same data as product.txt and unfinished_product.txt, so it adds no c tx-import ndc versions --source /path/to/ndc ``` +### sqlite-v2 Terminology Files + +The sqlite-v2 importers write a terminology file in the sqlite-v2 format: one SQLite file per +code system version, served by the sqlite-v2 providers (`loinc-v2:`, `snomed-v2:` and `rxnorm-v2:` +sources in the library - see [tx/README.md](../README.md) and +[tx/sqlite-v2/README.md](../sqlite-v2/README.md) for the format and the providers). They are +separate from the importers above, whose files the other providers read. + +| Command | From | To | +|---------|------|----| +| `loinc-v2` | an unzipped LOINC release | `loinc-v2:` file | +| `loinc-v2-classic` | a classic LOINC `.db` (made by `loinc` above) | `loinc-v2:` file | +| `snomed-v2` | an unzipped RF2 release (the Snapshot is used) | `snomed-v2:` file | +| `snomed-v2-from-cache` | a SNOMED CT `.cache` (made by `snomed` above) | `snomed-v2:` file | +| `rxnorm-v2` | the `rrf/` folder of an unzipped RxNorm full release | `rxnorm-v2:` file | + +The `-classic` and `-from-cache` importers rebuild a sqlite-v2 file from a file the other +providers use, for a release that isn't at hand any more. + +```bash +tx-import loinc-v2 import -s /path/to/loinc_release -d ./data/loinc-2.83.db -v 2.83 +tx-import loinc-v2-classic import -s ./data/loinc-2.77-a.db -d ./data/loinc-2.77.db +tx-import snomed-v2 import -s /path/to/SnomedCT_InternationalRF2 -d ./data/sct-intl-20260701.db \ + -e 900000000000207008 -v 20260701 +tx-import snomed-v2-from-cache import -s ./data/sct_uk_20261021.cache -d ./data/sct-uk-20261021.db +tx-import rxnorm-v2 import -s /path/to/RxNorm_full/rrf -d ./data/rxnorm-03022026.db -v 03022026 +``` + +**Options:** `-s, --source`, `-d, --dest`, `-v, --version` and `-y, --yes` as in +[Common Import Options](#common-import-options), with these differences: +- `--source` and `--dest` are required: these importers don't ask for them, and don't remember + them (no configuration history) +- `-v, --version` is the release's version: the LOINC version (`2.83`), the RxNorm release + (`MMDDYYYY`), the SNOMED CT release date (`YYYYMMDD`). `loinc-v2-classic` checks it against the + classic file (it defaults to the file's version); `snomed-v2-from-cache` takes it from the cache +- `-y, --yes` replaces an existing destination without asking. Without it, an existing + destination is asked about, or refused when there is no one to ask +- the earlier names `--loinc-version`, `--rxnorm-version`, `--snomed-version` and `--overwrite` + still work +- they always report each step; `--verbose` adds the stack trace to an error. There is no + `--no-indexes`: the indexes are part of the format +- `loinc-v2` has no `--main-only` or `--languages`: every language variant is imported + +Importer-specific options: +- `snomed-v2`: `-e, --edition ` (required) the edition's module id; `--version-uri ` + the version URI to record; `-l, --language ` the default language +- `snomed-v2-from-cache`: `--date-shift ` days to add to every cache date (default + `auto`, which fixes caches built east of UTC); `--force` imports a cache with known defects. + `tx-import snomed-v2-from-cache inspect ` checks caches for those defects + without importing +- `rxnorm-v2`: `--atom-relationships` also stores RXNREL's atom-level rows, for `REL` / `RELA` = + `AUI:` filters (refused otherwise) + +Each importer keeps its working tables in `.stage` beside the destination (so the disk needs +room for both). An existing destination is deleted when the import starts, so an import that +fails leaves none: import to a new name if the old file is still in use. A file of the earlier +sqlite-v2 schema is refused at start-up with a message to import it again: there is no in-place +upgrade. + ## Advanced Features ### Progress Tracking @@ -631,4 +692,5 @@ tx-import help - **UNII**: SQLite database with simple structure - **NDC**: SQLite database supporting multiple versions - **LOINC Subset**: File-based subset matching original structure -- **RxNorm Subset**: RRF file-based subset matching original structure \ No newline at end of file +- **RxNorm Subset**: RRF file-based subset matching original structure +- **sqlite-v2** (`loinc-v2`, `snomed-v2`, `rxnorm-v2` and the rebuilding importers): one SQLite terminology file per code system version - [tx/sqlite-v2/README.md](../sqlite-v2/README.md) \ No newline at end of file diff --git a/tx/importers/sqlite-v2/cli-options.js b/tx/importers/sqlite-v2/cli-options.js new file mode 100644 index 000000000..c9cee46f9 --- /dev/null +++ b/tx/importers/sqlite-v2/cli-options.js @@ -0,0 +1,86 @@ +/** + * The command-line options the sqlite-v2 importers share with the classic ones (the "Common + * Import Options" in tx/importers/readme.md): -v, --version for the release's version, -y, --yes + * to replace an existing destination without asking, and --verbose for the stack of an error. + * Without -y, an existing destination is asked about, as the classic importers do (and refused + * when there is no one to ask). Their earlier names still work, hidden: --loinc-version, + * --rxnorm-version, --snomed-version and --overwrite. (tx-import's own version is + * -V, --cli-version, so --version reaches the importer) + */ +const fs = require('fs'); +const { Option } = require('commander'); +const inquirer = require('inquirer'); + +/** + * Adds -v, --version (with the importer's earlier name for it, hidden) and -y, --yes (with + * --overwrite, hidden) to an import command + * @param {import('commander').Command} cmd + * @param {Object} [version] - none for an importer that takes the version from its source + * @param {string} version.arg - the value's name in the help, e.g. 'version' or 'MMDDYYYY' + * @param {string} version.help - what it is, e.g. 'e.g. 2.83' + * @param {string} version.oldFlag - the earlier long name, e.g. 'loinc-version' + * @returns {import('commander').Command} cmd + */ +function addCommonOptions(cmd, version) { + if (version) { + cmd.option(`-v, --version <${version.arg}>`, version.help); + cmd.addOption(new Option(`--${version.oldFlag} <${version.arg}>`).hideHelp()); + } + cmd.option('-y, --yes', 'replace an existing destination without asking'); + cmd.addOption(new Option('--overwrite').hideHelp()); + cmd.option('--verbose', 'show the stack trace of an error'); + return cmd; +} + +/** + * The import command's action, reporting a failure as the classic importers do: " import + * failed: " (the stack too with --verbose), and exit code 1 - not an uncaught rejection + * @param {Object} module - the importer module (BaseTerminologyModule) + * @param {function(Object): Promise} fn - the action + * @returns {function(Object): Promise} + */ +function importAction(module, fn) { + return async (o) => { + try { + await fn(o); + } catch (error) { + module.logError(`${module.getName()} import failed: ${error.message}`); + if (o.verbose) { + console.error(error.stack); + } + process.exitCode = 1; + } + }; +} + +/** + * The version and overwrite settings from the parsed options, asking about an existing + * destination when neither -y nor --overwrite was given + * @param {Object} o - the parsed options (with dest) + * @param {Object} [version] - as for addCommonOptions, with required: true when there is no default + * @returns {Promise<{version: string|undefined, overwrite: boolean}>} + */ +async function resolveCommonOptions(o, version) { + let value; + if (version) { + const oldKey = version.oldFlag.replace(/-([a-z])/g, (m, c) => c.toUpperCase()); + value = o.version !== undefined ? o.version : o[oldKey]; + if (version.required && (value === undefined || value === '')) { + throw new Error(`-v, --version <${version.arg}> is required (${version.help})`); + } + } + let overwrite = !!(o.yes || o.overwrite); + if (!overwrite && o.dest && fs.existsSync(o.dest)) { + if (!process.stdin.isTTY) { + throw new Error(`${o.dest} exists: use -y, --yes to replace it`); + } + const { replace } = await inquirer.prompt([{ type: 'confirm', name: 'replace', message: `${o.dest} exists. Replace it?`, default: false }]); + if (!replace) { + throw new Error('Import cancelled: the destination exists'); + } + overwrite = true; + } + return { version: value, overwrite }; +} + +module.exports = { addCommonOptions, resolveCommonOptions, importAction }; diff --git a/tx/sqlite-v2/README.md b/tx/sqlite-v2/README.md index dd78b13dc..994b4d44c 100644 --- a/tx/sqlite-v2/README.md +++ b/tx/sqlite-v2/README.md @@ -160,7 +160,7 @@ system's text-search names and ranking; the $lookup property lists and order. ## Importers ``` -node tx/importers/tx-import.js snomed-v2 import -s -d sct-intl-20260701.db -e 900000000000207008 --snomed-version 20260701 +node tx/importers/tx-import.js snomed-v2 import -s -d sct-intl-20260701.db -e 900000000000207008 -v 20260701 node tx/importers/tx-import.js snomed-v2-from-cache import -s sct_uk_20261021.cache -d sct-uk-20261021.db node tx/importers/tx-import.js snomed-v2-from-cache inspect node tx/importers/tx-import.js loinc-v2 import -s -d loinc-2.83.db -v 2.83 @@ -168,6 +168,10 @@ node tx/importers/tx-import.js loinc-v2-classic import -s loinc-2.77-a.db -d loi node tx/importers/tx-import.js rxnorm-v2 import -s -d rxnorm-03022026.db -v 03022026 [--atom-relationships] ``` +Every importer takes `-v, --version` for the release's version (not `snomed-v2-from-cache`, which +reads it from the cache) and `-y, --yes` to replace an existing destination; see +[tx/importers/readme.md](../importers/readme.md#sqlite-v2-terminology-files) for all the options. + `snomed-v2-from-cache` and `loinc-v2-classic` reverse-load the files main's providers use, for releases that are not at hand. Every importer stages into `.stage` beside the destination, then numbers the concepts, writes the fact tables in key order, builds the indexes, and VACUUMs. From a57bd37bd2b934c6d0e51a8e930dd3323be1f93f Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Thu, 3 Dec 2026 11:12:10 +1100 Subject: [PATCH 2/2] fix bug handling --verbose on import --- CHANGELOG.md | 1 + library/server/daily-report.js | 1 + rest/endpoint/endpoint.js | 8 +++- rest/rest.js | 56 +++++++++++++++++++++++ shl/shl.js | 2 +- tests/server/module-daily-reports.test.js | 20 ++++++++ tests/tx/sqlite-v2-cli-options.test.js | 18 ++++++++ tx/importers/sqlite-v2/cli-options.js | 19 +++++++- tx/vs/vs-database.js | 2 +- 9 files changed, 122 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72f7bb60b..660ac9737 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - tests: the ValueSet, ConceptMap and NamingSystem library tests (tests/library/*.tests.js, 104 tests) were never run, as jest runs only *.test.js; renamed, and a test now fails when a file of tests is one jest won't run - tx: a request with no client side cache over uncachedMaxBodyMB, behind the cluster launcher, mostly got a 502 "the tx process did not answer (EPIPE)", not the 413 too-costly: the process answered and closed the connection with the body still coming. It now takes the rest of the body (without parsing it) and then answers (#461) - tx: a JSON Bundle (a search page, say) was made in one go: a search for CodeSystems, 200 a page, with no _summary or _elements, made a page of 89 MB and held the server for 3 seconds (tx.fhir.org). A Bundle is now made an entry at a time, letting other requests run between, and written out in its parts (with no ETag: it isn't hashed) +- The shl module and the VSAC value set database turned on sqlite3's verbose mode, which is for the whole process: every query of every module (the XIG and packages on npm.fhir.org) then captured a stack trace and formatted its arguments, to make the stack of an error longer. It is no longer turned on ### Removed diff --git a/library/server/daily-report.js b/library/server/daily-report.js index 8685983c5..92adb3d95 100644 --- a/library/server/daily-report.js +++ b/library/server/daily-report.js @@ -39,6 +39,7 @@ const MODULE_TITLES = { tx: 'Terminology server', registry: 'Terminology server registry', packages: 'Packages', + rest: 'FHIR REST', xig: 'XIG', shl: 'SMART Health Links', ips: 'IPS', diff --git a/rest/endpoint/endpoint.js b/rest/endpoint/endpoint.js index e41ab740c..5400dd034 100644 --- a/rest/endpoint/endpoint.js +++ b/rest/endpoint/endpoint.js @@ -772,7 +772,13 @@ class Endpoint { } } finally { if (this.options.stats) { - this.options.stats.countRequest(interaction, Date.now() - start); + // under the endpoint, for the daily report (rest.js); a bundle as what it is + let name = interaction; + if (name === 'bundle') { + const type = freq && freq.body && freq.body.type; + name = type === 'transaction' || type === 'batch' ? type : 'bundle'; + } + this.options.stats.countRequest(name, Date.now() - start, this.path); } } } diff --git a/rest/rest.js b/rest/rest.js index e63e7570a..feafe67b4 100644 --- a/rest/rest.js +++ b/rest/rest.js @@ -146,6 +146,48 @@ class RestModule { return this.endpoints.map(ep => ep.path); } + /** + * The module's paragraph in the daily report (library/server/daily-report.js): for each + * endpoint, its reads, searches, writes and transactions over the period (and batches, + * and anything else, when there were any) + */ + dailyReport({ since, now }) { + if (!this.stats) { + return null; + } + const counts = this.stats.countsSince(since, now); + // the configured endpoints first, in order, then any counted that aren't configured now + const paths = this.endpoints.map(ep => ep.path); + for (const p of Object.keys(counts.endpoints || {})) { + if (!paths.includes(p)) { + paths.push(p); + } + } + if (!paths.length) { + return null; + } + const n = (count, word, plural) => `${count.toLocaleString('en-US')} ${count === 1 ? word : (plural || word + 's')}`; + const lines = paths.map(p => { + const ops = (counts.endpoints && counts.endpoints[p]) || {}; + const k = { reads: 0, searches: 0, writes: 0, transactions: 0, batches: 0, other: 0 }; + for (const [op, c] of Object.entries(ops)) { + k[categoryOf(op)] += c; + } + let line = `- ${p || '(no endpoint)'}: ${n(k.reads, 'read')}, ${n(k.searches, 'search', 'searches')}, ${n(k.writes, 'write')}, ${n(k.transactions, 'transaction')}`; + const more = []; + if (k.batches) { + more.push(n(k.batches, 'batch', 'batches')); + } + if (k.other) { + more.push(n(k.other, 'other request')); + } + return more.length ? `${line} (and ${more.join(', ')})` : line; + }); + const total = counts.total || 0; + const head = total === 0 ? 'No requests were served.' : `${n(total, 'request')} ${total === 1 ? 'was' : 'were'} served.`; + return `${head}\n\n${lines.join('\n')}`; + } + getStatus() { return { enabled: true, endpoints: this.endpoints.map(ep => ({ path: ep.path, fhirVersion: ep.settings && ep.settings.fhirVersion, database: ep.cfg.database.type })) }; } @@ -162,4 +204,18 @@ class RestModule { } } +// what each counted interaction is, for the daily report: other is history, operations, +// capabilities, and requests that weren't a FHIR interaction +const CATEGORIES = { + read: 'reads', vread: 'reads', + 'search-type': 'searches', 'search-system': 'searches', + create: 'writes', update: 'writes', patch: 'writes', delete: 'writes', + 'conditional-update': 'writes', 'conditional-delete': 'writes', 'conditional-patch': 'writes', + transaction: 'transactions', batch: 'batches' +}; + +function categoryOf(interaction) { + return CATEGORIES[interaction] || 'other'; +} + module.exports = RestModule; diff --git a/shl/shl.js b/shl/shl.js index 6942c58b3..932e57770 100644 --- a/shl/shl.js +++ b/shl/shl.js @@ -5,7 +5,7 @@ // const express = require('express'); -const sqlite3 = require('sqlite3').verbose(); +const sqlite3 = require('sqlite3'); const path = require('path'); const crypto = require('crypto'); const cron = require('node-cron'); diff --git a/tests/server/module-daily-reports.test.js b/tests/server/module-daily-reports.test.js index 3e4f88229..79f8750e4 100644 --- a/tests/server/module-daily-reports.test.js +++ b/tests/server/module-daily-reports.test.js @@ -17,6 +17,7 @@ const PublisherModule = require('../../publisher/publisher'); const TestingModule = require('../../testing/testing'); const { TestReportStore: TestingStore } = require('../../testing/store'); const IpsModule = require('../../ips/ips'); +const RestModule = require('../../rest/rest'); const { IpsStore } = require('../../ips/store'); const HOUR = 60 * 60 * 1000; @@ -118,6 +119,25 @@ describe('module paragraphs', () => { }); + test('rest: reads, searches, writes and transactions for each endpoint', () => { + const module = Object.create(RestModule.prototype); + module.endpoints = [{ path: '/fhir/r4' }, { path: '/fhir/r5' }]; + const r4 = { read: 1000, vread: 200, 'search-type': 40, 'search-system': 2, create: 3, update: 4, 'conditional-update': 1, + patch: 1, delete: 1, transaction: 2, batch: 1, 'history-instance': 5, operation: 3 }; + const old = { read: 1 }; // an endpoint no longer configured + const total = [r4, old].reduce((t, o) => t + Object.values(o).reduce((a, b) => a + b, 0), 0); + module.stats = { countsSince: () => ({ total, operations: {}, endpoints: { '/fhir/r4': r4, '/fhir/old': old }, persisted: true }) }; + expect(module.dailyReport({ since: SINCE, now: NOW })).toBe('1,264 requests were served.\n\n' + + '- /fhir/r4: 1,200 reads, 42 searches, 10 writes, 2 transactions (and 1 batch, 8 other requests)\n' + + '- /fhir/r5: 0 reads, 0 searches, 0 writes, 0 transactions\n' + + '- /fhir/old: 1 read, 0 searches, 0 writes, 0 transactions'); + + module.stats = statsWith({}); + expect(module.dailyReport({ since: SINCE, now: NOW })).toBe('No requests were served.\n\n' + + '- /fhir/r4: 0 reads, 0 searches, 0 writes, 0 transactions\n' + + '- /fhir/r5: 0 reads, 0 searches, 0 writes, 0 transactions'); + }); + test('registry: client requests, servers registered, and those that never answered', () => { const data = new ServerRegistries(); const registry = new ServerRegistry(); diff --git a/tests/tx/sqlite-v2-cli-options.test.js b/tests/tx/sqlite-v2-cli-options.test.js index 230623d41..40a73a578 100644 --- a/tests/tx/sqlite-v2-cli-options.test.js +++ b/tests/tx/sqlite-v2-cli-options.test.js @@ -93,6 +93,24 @@ describe('sqlite-v2 importer options', () => { } }); + test('--verbose shows the stack wherever it is on the command line (tx-import has a --verbose of its own)', async () => { + const module = { getName: () => 'loinc-v2', logError: () => {} }; + const exitCode = process.exitCode; + const stack = jest.spyOn(console, 'error').mockImplementation(() => {}); + try { + for (const args of [['loinc-v2', 'import', '-d', 'x.db', '--verbose'], ['--verbose', 'loinc-v2', 'import', '-d', 'x.db']]) { + stack.mockClear(); + const program = new Command().exitOverride().option('--verbose', 'enable verbose logging'); + addCommonOptions(program.command('loinc-v2').command('import').option('-d, --dest ')) + .action(importAction(module, async () => { throw new Error('required LOINC file missing'); })); + await program.parseAsync(args, { from: 'user' }); + expect(stack).toHaveBeenCalledTimes(1); + } + } finally { + process.exitCode = exitCode; + } + }); + test('the help shows -v, --version and -y, --yes, not the earlier names', () => { const program = new Command(); const cmd = addCommonOptions(program.command('import'), VERSION); diff --git a/tx/importers/sqlite-v2/cli-options.js b/tx/importers/sqlite-v2/cli-options.js index c9cee46f9..8c6d3062a 100644 --- a/tx/importers/sqlite-v2/cli-options.js +++ b/tx/importers/sqlite-v2/cli-options.js @@ -40,12 +40,12 @@ function addCommonOptions(cmd, version) { * @returns {function(Object): Promise} */ function importAction(module, fn) { - return async (o) => { + return async (o, cmd) => { try { await fn(o); } catch (error) { module.logError(`${module.getName()} import failed: ${error.message}`); - if (o.verbose) { + if (verboseOf(o, cmd)) { console.error(error.stack); } process.exitCode = 1; @@ -53,6 +53,21 @@ function importAction(module, fn) { }; } +/** + * Whether --verbose was given. tx-import has a --verbose of its own, and commander gives a flag + * to the program wherever it appears on the command line, so the import command's own options + * never have it: it's in the options with the globals + * @param {Object} o - the import command's parsed options + * @param {Object} [cmd] - the import command (commander passes it after the options) + * @returns {boolean} + */ +function verboseOf(o, cmd) { + if (o && o.verbose) { + return true; + } + return !!(cmd && typeof cmd.optsWithGlobals === 'function' && cmd.optsWithGlobals().verbose); +} + /** * The version and overwrite settings from the parsed options, asking about an existing * destination when neither -y nor --overwrite was given diff --git a/tx/vs/vs-database.js b/tx/vs/vs-database.js index 32482ede9..ce5284ef7 100644 --- a/tx/vs/vs-database.js +++ b/tx/vs/vs-database.js @@ -1,6 +1,6 @@ const fs = require('fs').promises; const crypto = require('crypto'); -const sqlite3 = require('sqlite3').verbose(); +const sqlite3 = require('sqlite3'); const { VersionUtilities } = require('../../library/fhir/version-utilities'); const ValueSet = require("../library/valueset"); const { guarded } = require('../library/sqlite-utilities');