fhirsmith 0.5.2 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tx/cs/cs-db.js DELETED
@@ -1,1308 +0,0 @@
1
- const sqlite3 = require('sqlite3').verbose();
2
- const assert = require('assert');
3
- const { CodeSystem } = require('../library/codesystem');
4
- const { Language, Languages} = require('../../library/languages');
5
- const { CodeSystemProvider, CodeSystemFactoryProvider} = require('./cs-api');
6
- const { validateOptionalParameter, validateArrayParameter} = require("../../library/utilities");
7
-
8
- class CachedDesignation {
9
- constructor(display, language, use) {
10
- this.display = display;
11
- this.language = language;
12
- this.use = use;
13
- }
14
- }
15
-
16
- class CodeDBProviderContext {
17
- constructor(key, code, display, definition, status) {
18
- this.key = key;
19
- this.code = code;
20
- this.display = display;
21
- this.definition = definition;
22
- this.status = status;
23
- this.designations = null; // Array of CachedDesignation
24
- this.children = null; // Will be Set of keys if this has children
25
- }
26
-
27
- addChild(key) {
28
- if (!this.children) {
29
- this.children = new Set();
30
- }
31
- this.children.add(key);
32
- }
33
- }
34
-
35
-
36
- class CodeDBIteratorContext {
37
- constructor(context, keys) {
38
- this.context = context;
39
- this.keys = keys || [];
40
- this.current = 0;
41
- this.total = this.keys.length;
42
- }
43
-
44
- more() {
45
- return this.current < this.total;
46
- }
47
-
48
- next() {
49
- this.current++;
50
- }
51
- }
52
-
53
- class CodeDBFilterHolder {
54
- constructor() {
55
- this.keys = [];
56
- this.cursor = 0;
57
- this.lsql = '';
58
- }
59
-
60
- hasKey(key) {
61
- // Binary search since keys are sorted
62
- let l = 0;
63
- let r = this.keys.length - 1;
64
- while (l <= r) {
65
- const m = Math.floor((l + r) / 2);
66
- if (this.keys[m] < key) {
67
- l = m + 1;
68
- } else if (this.keys[m] > key) {
69
- r = m - 1;
70
- } else {
71
- return true;
72
- }
73
- }
74
- return false;
75
- }
76
- }
77
-
78
- class CodeDBPrep {
79
- constructor() {
80
- this.filters = [];
81
- }
82
- }
83
-
84
- class CodeDBServices extends CodeSystemProvider {
85
- constructor(opContext, supplements, db, sharedData) {
86
- super(opContext, supplements);
87
- this.db = db;
88
-
89
- // Shared data from factory
90
- this.langs = sharedData.langs;
91
- this.codes = sharedData.codes;
92
- this.codeList = sharedData.codeList;
93
- this.codeSystem = sharedData.codeSystem;
94
- this.root = sharedData.root;
95
- this.firstCodeKey = sharedData.firstCodeKey;
96
- this.relationships = sharedData.relationships;
97
- this.propertyList = sharedData.propertyList;
98
- this.statusKeys = sharedData.statusKeys;
99
- this.statusCodes = sharedData.statusCodes;
100
- }
101
-
102
- close() {
103
- if (this.db) {
104
- this.db.close();
105
- this.db = null;
106
- }
107
- }
108
-
109
- // Metadata methods
110
- system() {
111
- return this.codeSystem.url;
112
- }
113
-
114
- version() {
115
- return this.codeSystem.version;
116
- }
117
-
118
- name() {
119
- return this.codeSystem.name;
120
- }
121
-
122
- description() {
123
- return this.codeSystem.description;
124
- }
125
-
126
- async totalCount() {
127
- return this.codes.size;
128
- }
129
-
130
- hasParents() {
131
- return this.codeSystem.hierarchical;
132
- }
133
-
134
- hasAnyDisplays(languages) {
135
- const langs = this._ensureLanguages(languages);
136
-
137
- // Check supplements first
138
- if (this._hasAnySupplementDisplays(langs)) {
139
- return true;
140
- }
141
-
142
- // Check if any requested languages are available in code system data
143
- for (const requestedLang of langs.languages) {
144
- for (const [codeDBLangCode] of this.langs) {
145
- const codeDBLang = new Language(codeDBLangCode);
146
- if (codeDBLang.matchesForDisplay(requestedLang)) {
147
- return true;
148
- }
149
- }
150
- }
151
-
152
- return super.hasAnyDisplays(langs);
153
- }
154
-
155
- // Core concept methods
156
- async code(context) {
157
-
158
- const ctxt = await this.#ensureContext(context);
159
- return ctxt ? ctxt.code : null;
160
- }
161
-
162
- async display(context) {
163
-
164
- const ctxt = await this.#ensureContext(context);
165
- if (!ctxt) {
166
- return null;
167
- }
168
-
169
- // Check supplements first
170
- let disp = this._displayFromSupplements(ctxt.code);
171
- if (disp) {
172
- return disp;
173
- }
174
-
175
- // Use language-aware display logic
176
- if (this.opContext.langs && !this.opContext.langs.isEnglishOrNothing()) {
177
- await this.#loadDesignationsForContext(ctxt);
178
-
179
- // Try to find exact language match
180
- for (const lang of this.opContext.langs.langs) {
181
- for (const display of ctxt.designations) {
182
- if (lang.matches(display.language, true)) {
183
- return display.value;
184
- }
185
- }
186
- }
187
-
188
- // Try partial language match
189
- for (const lang of this.opContext.langs.langs) {
190
- for (const display of ctxt.designations) {
191
- if (lang.matches(display.language, false)) {
192
- return display.value;
193
- }
194
- }
195
- }
196
- }
197
-
198
- return ctxt.display || '';
199
- }
200
-
201
- async definition(context) {
202
- const ctxt = await this.#ensureContext(context);
203
- return ctxt.definition;
204
- }
205
-
206
- async isAbstract(context) {
207
- const ctxt = await this.#ensureContext(context);
208
- return ctxt.abstract;
209
- }
210
-
211
- async isInactive(context) {
212
- const ctxt = await this.#ensureContext(context);
213
- return ctxt.status == 'inactive';
214
- }
215
-
216
- async getStatus(context) {
217
- const ctxt = await this.#ensureContext(context);
218
- return ctxt.status;
219
- }
220
-
221
- async isDeprecated(context) {
222
- const ctxt = await this.#ensureContext(context);
223
- return ctxt.status == 'deprecated';
224
- }
225
-
226
- async designations(context, displays) {
227
- const ctxt = await this.#ensureContext(context);
228
- if (ctxt) {
229
- await this.#loadDesignationsForContext(ctxt);
230
- ctxt.designations
231
- // Add main display
232
- displays.addDesignation(true, 'active', this.codeSystem.language, CodeSystem.makeUseForDisplay(), ctxt.desc.trim());
233
-
234
- // Add cached designations
235
- if (ctxt.displays.length === 0) {
236
- await this.#loadDesignationsForContext(ctxt);
237
- }
238
-
239
- for (const entry of ctxt.designations) {
240
- let use = undefined;
241
- if (entry.type) {
242
- use = {
243
- system: this.codeSystem.url,
244
- code: entry.type
245
- }
246
- }
247
- if (!use) {
248
- use = entry.display ? CodeSystem.makeUseForDisplay() : null;
249
- }
250
- displays.addDesignation(false, 'active', entry.lang, use, entry.value.trim());
251
- }
252
-
253
- // Add supplement designations
254
- this._listSupplementDesignations(ctxt.code, displays);
255
- }
256
-
257
- }
258
-
259
- async extendLookup(ctxt, props, params) {
260
- validateArrayParameter(props, 'props', String);
261
- validateArrayParameter(params, 'params', Object);
262
-
263
-
264
- if (typeof ctxt === 'string') {
265
- const located = await this.locate(ctxt);
266
- if (!located.context) {
267
- throw new Error(located.message);
268
- }
269
- ctxt = located.context;
270
- }
271
-
272
- if (!(ctxt instanceof CodeDBProviderContext)) {
273
- throw new Error('Invalid context for CodeDB lookup');
274
- }
275
-
276
- await this.#addConceptProperties(ctxt, params);
277
- await this.#addStatusProperty(ctxt, params);
278
- }
279
-
280
- async #addConceptProperties(ctxt, params) {
281
- return new Promise((resolve, reject) => {
282
- const sql = `
283
- SELECT PropertyTypes.Description, PropertyValues.Value
284
- FROM Properties, PropertyTypes, PropertyValues
285
- WHERE Properties.CodeKey = ?
286
- AND Properties.PropertyTypeKey = PropertyTypes.PropertyTypeKey
287
- AND Properties.PropertyValueKey = PropertyValues.PropertyValueKey
288
- `;
289
-
290
- this.db.all(sql, [ctxt.key], (err, rows) => {
291
- if (err) {
292
- reject(err);
293
- } else {
294
- for (const row of rows) {
295
- this.#addStringProperty(params, 'property', row.Description, row.Value);
296
- }
297
- resolve();
298
- }
299
- });
300
- });
301
- }
302
-
303
- async #addStatusProperty(ctxt, params) {
304
- if (ctxt.status) {
305
- this.#addStringProperty(params, 'property', 'STATUS', ctxt.status);
306
- }
307
- }
308
-
309
- #addProperty(params, type, name, value, language = null) {
310
-
311
- const property = {
312
- name: type,
313
- part: [
314
- { name: 'code', valueCode: name },
315
- { name: 'value', valueString: value }
316
- ]
317
- };
318
-
319
- if (language) {
320
- property.part.push({ name: 'language', valueCode: language });
321
- }
322
-
323
- params.push(property);
324
- }
325
-
326
- #addCodeProperty(params, type, name, value, language = null) {
327
-
328
- const property = {
329
- name: type,
330
- part: [
331
- { name: 'code', valueCode: name },
332
- { name: 'value', valueCode: value }
333
- ]
334
- };
335
-
336
- if (language) {
337
- property.part.push({ name: 'language', valueCode: language });
338
- }
339
-
340
- params.push(property);
341
- }
342
-
343
- #addStringProperty(params, type, name, value, language = null) {
344
-
345
- const property = {
346
- name: type,
347
- part: [
348
- { name: 'code', valueCode: name },
349
- { name: 'value', valueString: value }
350
- ]
351
- };
352
-
353
- if (language) {
354
- property.part.push({ name: 'language', valueCode: language });
355
- }
356
-
357
- params.push(property);
358
- }
359
-
360
- #addSupplementDisplays(displays, code) {
361
- if (this.supplements) {
362
- for (const supplement of this.supplements) {
363
- const concept = supplement.getConceptByCode(code);
364
- if (concept) {
365
- if (concept.display) {
366
- displays.push(new LoincDisplay(supplement.jsonObj.language || 'en', concept.display));
367
- }
368
- if (concept.designation) {
369
- for (const designation of concept.designation) {
370
- const lang = designation.language || supplement.jsonObj.language || 'en';
371
- displays.push(new LoincDisplay(lang, designation.value));
372
- }
373
- }
374
- }
375
- }
376
- }
377
- }
378
-
379
- async #loadDesignationsForContext(ctxt) {
380
- if (!ctxt.designations) {
381
- ctxt.designations = [];
382
- return new Promise((resolve, reject) => {
383
- const sql = `
384
- SELECT Languages.Code as Lang, DescriptionTypes.Description as DType, Descriptions.Value
385
- FROM Descriptions,
386
- Languages,
387
- DescriptionTypes
388
- WHERE Descriptions.CodeKey = ?
389
- AND Descriptions.DescriptionTypeKey != 4
390
- AND Descriptions.DescriptionTypeKey = DescriptionTypes.DescriptionTypeKey
391
- AND Descriptions.LanguageKey = Languages.LanguageKey
392
- `;
393
-
394
- this.db.all(sql, [ctxt.key], (err, rows) => {
395
- if (err) {
396
- reject(err);
397
- } else {
398
- for (const row of rows) {
399
- const isDisplay = row.DType === 'LONG_COMMON_NAME';
400
- ctxt.designations.push(new CachedDesignation(row.Value, , row.Lang, row.DType));
401
- }
402
- resolve();
403
- }
404
- });
405
- });
406
- }
407
- }
408
-
409
- async #ensureContext(context) {
410
- if (!context) {
411
- return null;
412
- }
413
- if (typeof context === 'string') {
414
- const ctxt = await this.locate(context);
415
- if (!ctxt.context) {
416
- throw new Error(ctxt.message);
417
- } else {
418
- return ctxt.context;
419
- }
420
- }
421
- if (context instanceof CodeDBProviderContext) {
422
- return context;
423
- }
424
- throw new Error("Unknown Type at #ensureContext: " + (typeof context));
425
- }
426
-
427
- // Lookup methods
428
- async locate(code) {
429
-
430
- assert(!code || typeof code === 'string', 'code must be string');
431
- if (!code) return { context: null, message: 'Empty code' };
432
-
433
- const context = this.codes.get(code);
434
- if (context) {
435
- return { context: context, message: null };
436
- }
437
-
438
- return { context: null, message: undefined };
439
- }
440
-
441
- // Iterator methods
442
- async iterator(context) {
443
-
444
-
445
- if (!context) {
446
- // Iterate all codes starting from first code
447
- const keys = Array.from({ length: this.codeList.length - this.firstCodeKey }, (_, i) => i + this.firstCodeKey);
448
- return new LoincIteratorContext(null, keys);
449
- } else {
450
- const ctxt = await this.#ensureContext(context);
451
- if (ctxt.kind === LoincProviderContextKind.PART && ctxt.children) {
452
- return new LoincIteratorContext(ctxt, Array.from(ctxt.children));
453
- } else {
454
- return new LoincIteratorContext(ctxt, []);
455
- }
456
- }
457
- }
458
-
459
- async nextContext(iteratorContext) {
460
-
461
-
462
- if (!iteratorContext.more()) {
463
- return null;
464
- }
465
-
466
- const key = iteratorContext.keys[iteratorContext.current];
467
- iteratorContext.next();
468
-
469
- return this.codeList[key];
470
- }
471
-
472
- // Filter support
473
- async doesFilter(prop, op, value) {
474
- // Relationship filters
475
- if (this.relationships.has(prop) && ['=', 'in', 'exists', 'regex'].includes(op)) {
476
- return true;
477
- }
478
-
479
- // Property filters
480
- if (this.propertyList.has(prop) && ['=', 'in', 'exists', 'regex'].includes(op)) {
481
- return true;
482
- }
483
-
484
- // Status filter
485
- if (prop === 'STATUS' && op === '=' && this.statusKeys.has(value)) {
486
- return true;
487
- }
488
-
489
- // LIST filter
490
- if (prop === 'LIST' && op === '=' && this.codes.has(value)) {
491
- return true;
492
- }
493
-
494
- // CLASSSTYPE filter
495
- if (prop === 'CLASSTYPE' && op === '=' && ["1", "2", "3", "4"].includes(value)) {
496
- return true;
497
- }
498
-
499
- // answers-for filter
500
- if (prop === 'answers-for' && op === '=') {
501
- return true;
502
- }
503
-
504
- // concept filters
505
- if (prop === 'concept' && ['is-a', 'descendent-of', '=', 'in', 'not-in'].includes(op)) {
506
- return true;
507
- }
508
-
509
- // code filters (VSAC workaround)
510
- if (prop === 'code' && ['is-a', 'descendent-of', '='].includes(op)) {
511
- return true;
512
- }
513
-
514
- // copyright filter
515
- if (prop === 'copyright' && op === '=' && ['LOINC', '3rdParty'].includes(value)) {
516
- return true;
517
- }
518
-
519
- return false;
520
- }
521
-
522
- async getPrepContext(iterate) {
523
- return new LoincPrep(iterate);
524
- }
525
-
526
- async filter(filterContext, prop, op, value) {
527
-
528
-
529
- const filter = new LoincFilterHolder();
530
- await this.#executeFilterQuery(prop, op, value, filter);
531
- filterContext.filters.push(filter);
532
- }
533
-
534
- async #executeFilterQuery(prop, op, value, filter) {
535
- let sql = '';
536
- let lsql = '';
537
-
538
- // LIST filter
539
- if (prop === 'LIST' && op === '=' && this.codes.has(value)) {
540
- sql = `SELECT TargetKey as Key FROM Relationships
541
- WHERE RelationshipTypeKey = ${this.relationships.get('Answer')}
542
- AND SourceKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
543
- ORDER BY SourceKey ASC`;
544
- lsql = `SELECT COUNT(TargetKey) FROM Relationships
545
- WHERE RelationshipTypeKey = ${this.relationships.get('Answer')}
546
- AND SourceKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
547
- AND TargetKey = `;
548
- }
549
- // answers-for filter
550
- else if (prop === 'answers-for' && op === '=') {
551
- if (value.startsWith('LL')) {
552
- sql = `SELECT TargetKey as Key FROM Relationships
553
- WHERE RelationshipTypeKey = ${this.relationships.get('Answer')}
554
- AND SourceKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
555
- ORDER BY SourceKey ASC`;
556
- lsql = `SELECT COUNT(TargetKey) FROM Relationships
557
- WHERE RelationshipTypeKey = ${this.relationships.get('Answer')}
558
- AND SourceKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
559
- AND TargetKey = `;
560
- } else {
561
- sql = `SELECT TargetKey as Key FROM Relationships
562
- WHERE RelationshipTypeKey = ${this.relationships.get('Answer')}
563
- AND SourceKey IN (
564
- SELECT SourceKey FROM Relationships
565
- WHERE RelationshipTypeKey = ${this.relationships.get('answers-for')}
566
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
567
- )
568
- ORDER BY SourceKey ASC`;
569
- lsql = `SELECT COUNT(TargetKey) FROM Relationships
570
- WHERE RelationshipTypeKey = ${this.relationships.get('Answer')}
571
- AND SourceKey IN (SELECT SourceKey FROM Relationships
572
- WHERE RelationshipTypeKey = ${this.relationships.get('answers-for')}
573
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}'))
574
- AND TargetKey = `;
575
- }
576
- }
577
- // Relationship equal filter
578
- else if (this.relationships.has(prop) && op === '=') {
579
- if (this.codes.has(value)) {
580
- sql = `SELECT SourceKey as Key FROM Relationships
581
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
582
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
583
- ORDER BY SourceKey ASC`;
584
- lsql = `SELECT COUNT(SourceKey) FROM Relationships
585
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
586
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
587
- AND SourceKey = `;
588
- } else {
589
- sql = `SELECT SourceKey as Key FROM Relationships
590
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
591
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Description = '${this.#sqlWrapString(value)}' COLLATE NOCASE)
592
- ORDER BY SourceKey ASC`;
593
- lsql = `SELECT COUNT(SourceKey) FROM Relationships
594
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
595
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Description = '${this.#sqlWrapString(value)}' COLLATE NOCASE)
596
- AND SourceKey = `;
597
- }
598
- }
599
- // Relationship 'in' filter
600
- else if (this.relationships.has(prop) && op === 'in') {
601
- const codes = this.#commaListOfCodes(value);
602
- sql = `SELECT SourceKey as Key FROM Relationships
603
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
604
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Code IN (${codes}))
605
- ORDER BY SourceKey ASC`;
606
- lsql = `SELECT COUNT(SourceKey) FROM Relationships
607
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
608
- AND TargetKey IN (SELECT CodeKey FROM Codes WHERE Code IN (${codes}))
609
- AND SourceKey = `;
610
- }
611
- // Relationship 'exists' filter
612
- else if (this.relationships.has(prop) && op === 'exists') {
613
- if (this.codes.has(value)) {
614
- sql = `SELECT SourceKey as Key FROM Relationships
615
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
616
- AND EXISTS (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
617
- ORDER BY SourceKey ASC`;
618
- lsql = `SELECT COUNT(SourceKey) FROM Relationships
619
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
620
- AND EXISTS (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
621
- AND SourceKey = `;
622
- } else {
623
- sql = `SELECT SourceKey as Key FROM Relationships
624
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
625
- AND EXISTS (SELECT CodeKey FROM Codes WHERE Description = '${this.#sqlWrapString(value)}' COLLATE NOCASE)
626
- ORDER BY SourceKey ASC`;
627
- lsql = `SELECT COUNT(SourceKey) FROM Relationships
628
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
629
- AND EXISTS (SELECT CodeKey FROM Codes WHERE Description = '${this.#sqlWrapString(value)}' COLLATE NOCASE)
630
- AND SourceKey = `;
631
- }
632
- }
633
- // Relationship regex filter
634
- else if (this.relationships.has(prop) && op === 'regex') {
635
- const matchingKeys = await this.#findRegexMatches(
636
- `SELECT CodeKey as Key, Description FROM Codes
637
- WHERE CodeKey IN (SELECT TargetKey FROM Relationships WHERE RelationshipTypeKey = ${this.relationships.get(prop)})`,
638
- value,
639
- 'Description'
640
- );
641
- if (matchingKeys.length > 0) {
642
- sql = `SELECT SourceKey as Key FROM Relationships
643
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
644
- AND TargetKey IN (${matchingKeys.join(',')})
645
- ORDER BY SourceKey ASC`;
646
- lsql = `SELECT COUNT(SourceKey) FROM Relationships
647
- WHERE RelationshipTypeKey = ${this.relationships.get(prop)}
648
- AND TargetKey IN (${matchingKeys.join(',')})
649
- AND SourceKey = `;
650
- }
651
- }
652
- // Property equal filter (with CLASSTYPE handling)
653
- else if (this.propertyList.has(prop) && op === '=') {
654
- let actualValue = value;
655
- if (prop === 'CLASSTYPE' && ['1', '2', '3', '4'].includes(value)) {
656
- const classTypes = {
657
- '1': 'Laboratory class',
658
- '2': 'Clinical class',
659
- '3': 'Claims attachments',
660
- '4': 'Surveys'
661
- };
662
- actualValue = classTypes[value];
663
- }
664
- sql = `SELECT CodeKey as Key FROM Properties, PropertyValues
665
- WHERE Properties.PropertyTypeKey = ${this.propertyList.get(prop)}
666
- AND Properties.PropertyValueKey = PropertyValues.PropertyValueKey
667
- AND PropertyValues.Value = '${this.#sqlWrapString(actualValue)}' COLLATE NOCASE
668
- ORDER BY CodeKey ASC`;
669
- lsql = `SELECT COUNT(CodeKey) FROM Properties, PropertyValues
670
- WHERE Properties.PropertyTypeKey = ${this.propertyList.get(prop)}
671
- AND Properties.PropertyValueKey = PropertyValues.PropertyValueKey
672
- AND PropertyValues.Value = '${this.#sqlWrapString(actualValue)}' COLLATE NOCASE
673
- AND CodeKey = `;
674
- }
675
- // Property 'in' filter
676
- else if (this.propertyList.has(prop) && op === 'in') {
677
- const codes = this.#commaListOfCodes(value);
678
- sql = `SELECT CodeKey as Key FROM Properties, PropertyValues
679
- WHERE Properties.PropertyTypeKey = ${this.propertyList.get(prop)}
680
- AND Properties.PropertyValueKey = PropertyValues.PropertyValueKey
681
- AND PropertyValues.Value IN (${codes}) COLLATE NOCASE
682
- ORDER BY CodeKey ASC`;
683
- lsql = `SELECT COUNT(CodeKey) FROM Properties, PropertyValues
684
- WHERE Properties.PropertyTypeKey = ${this.propertyList.get(prop)}
685
- AND Properties.PropertyValueKey = PropertyValues.PropertyValueKey
686
- AND PropertyValues.Value IN (${codes}) COLLATE NOCASE
687
- AND CodeKey = `;
688
- }
689
- // Property 'exists' filter
690
- else if (this.propertyList.has(prop) && op === 'exists') {
691
- sql = `SELECT DISTINCT CodeKey as Key FROM Properties
692
- WHERE Properties.PropertyTypeKey = ${this.propertyList.get(prop)}
693
- ORDER BY CodeKey ASC`;
694
- lsql = `SELECT COUNT(CodeKey) FROM Properties
695
- WHERE Properties.PropertyTypeKey = ${this.propertyList.get(prop)}
696
- AND CodeKey = `;
697
- }
698
- // Property regex filter
699
- else if (this.propertyList.has(prop) && op === 'regex') {
700
- const matchingKeys = await this.#findRegexMatches(
701
- `SELECT PropertyValueKey, Value FROM PropertyValues
702
- WHERE PropertyValueKey IN (SELECT PropertyValueKey FROM Properties WHERE PropertyTypeKey = ${this.propertyList.get(prop)})`,
703
- value,
704
- 'Value',
705
- 'PropertyValueKey'
706
- );
707
- if (matchingKeys.length > 0) {
708
- sql = `SELECT CodeKey as Key FROM Properties
709
- WHERE PropertyTypeKey = ${this.propertyList.get(prop)}
710
- AND PropertyValueKey IN (${matchingKeys.join(',')})
711
- ORDER BY CodeKey ASC`;
712
- lsql = `SELECT COUNT(CodeKey) FROM Properties
713
- WHERE PropertyTypeKey = ${this.propertyList.get(prop)}
714
- AND PropertyValueKey IN (${matchingKeys.join(',')})
715
- AND CodeKey = `;
716
- }
717
- }
718
- // Status filter
719
- else if (prop === 'STATUS' && op === '=' && this.statusKeys.has(value)) {
720
- sql = `SELECT CodeKey as Key FROM Codes
721
- WHERE StatusKey = ${this.statusKeys.get(value)}
722
- ORDER BY CodeKey ASC`;
723
- lsql = `SELECT COUNT(CodeKey) FROM Codes
724
- WHERE StatusKey = ${this.statusKeys.get(value)}
725
- AND CodeKey = `;
726
- }
727
- // Concept hierarchy filters (is-a, descendent-of)
728
- else if (prop === 'concept' && ['is-a', 'descendent-of'].includes(op)) {
729
- sql = `SELECT DescendentKey as Key FROM Closure
730
- WHERE AncestorKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
731
- ORDER BY DescendentKey ASC`;
732
- lsql = `SELECT COUNT(DescendentKey) FROM Closure
733
- WHERE AncestorKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
734
- AND DescendentKey = `;
735
- }
736
- // Concept equal filter (workaround for VSAC misuse)
737
- else if (prop === 'concept' && op === '=') {
738
- sql = `SELECT CodeKey as Key FROM Codes
739
- WHERE Code = '${this.#sqlWrapString(value)}'
740
- ORDER BY CodeKey ASC`;
741
- lsql = `SELECT COUNT(CodeKey) FROM Codes
742
- WHERE Code = '${this.#sqlWrapString(value)}'
743
- AND CodeKey = `;
744
- }
745
- // Concept 'in' filter (workaround for VSAC misuse)
746
- else if (prop === 'concept' && op === 'in') {
747
- const codes = this.#commaListOfCodes(value);
748
- sql = `SELECT CodeKey as Key FROM Codes
749
- WHERE Code IN (${codes})
750
- ORDER BY CodeKey ASC`;
751
- lsql = `SELECT COUNT(CodeKey) FROM Codes
752
- WHERE Code IN (${codes})
753
- AND CodeKey = `;
754
- }
755
- // Code property filters (workaround for VSAC misuse)
756
- else if (prop === 'code' && ['is-a', 'descendent-of'].includes(op)) {
757
- sql = `SELECT DescendentKey as Key FROM Closure
758
- WHERE AncestorKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
759
- ORDER BY DescendentKey ASC`;
760
- lsql = `SELECT COUNT(DescendentKey) FROM Closure
761
- WHERE AncestorKey IN (SELECT CodeKey FROM Codes WHERE Code = '${this.#sqlWrapString(value)}')
762
- AND DescendentKey = `;
763
- }
764
- else if (prop === 'code' && op === '=') {
765
- sql = `SELECT CodeKey as Key FROM Codes
766
- WHERE Code = '${this.#sqlWrapString(value)}'
767
- ORDER BY CodeKey ASC`;
768
- lsql = `SELECT COUNT(CodeKey) FROM Codes
769
- WHERE Code = '${this.#sqlWrapString(value)}'
770
- AND CodeKey = `;
771
- }
772
- // Copyright filters
773
- else if (prop === 'copyright' && op === '=') {
774
- if (value === 'LOINC') {
775
- sql = `SELECT CodeKey as Key FROM Codes
776
- WHERE NOT CodeKey IN (SELECT CodeKey FROM Properties WHERE PropertyTypeKey = 9)
777
- ORDER BY CodeKey ASC`;
778
- lsql = `SELECT COUNT(CodeKey) FROM Codes
779
- WHERE NOT CodeKey IN (SELECT CodeKey FROM Properties WHERE PropertyTypeKey = 9)
780
- AND CodeKey = `;
781
- } else if (value === '3rdParty') {
782
- sql = `SELECT CodeKey as Key FROM Codes
783
- WHERE CodeKey IN (SELECT CodeKey FROM Properties WHERE PropertyTypeKey = 9)
784
- ORDER BY CodeKey ASC`;
785
- lsql = `SELECT COUNT(CodeKey) FROM Codes
786
- WHERE CodeKey IN (SELECT CodeKey FROM Properties WHERE PropertyTypeKey = 9)
787
- AND CodeKey = `;
788
- }
789
- }
790
-
791
- if (sql) {
792
- await this.#executeSQL(sql, filter);
793
- filter.lsql = lsql;
794
- } else {
795
- throw new Error(`The filter "${prop} ${op} ${value}" is not supported for LOINC`);
796
- }
797
- }
798
-
799
- // Helper method for regex matching
800
- async #findRegexMatches(sql, pattern, valueColumn, keyColumn = 'Key') {
801
- return new Promise((resolve, reject) => {
802
- const regex = new RegExp(pattern);
803
- const matchingKeys = [];
804
-
805
- this.db.all(sql, (err, rows) => {
806
- if (err) {
807
- reject(err);
808
- } else {
809
- for (const row of rows) {
810
- if (regex.test(row[valueColumn])) {
811
- matchingKeys.push(row[keyColumn]);
812
- }
813
- }
814
- resolve(matchingKeys);
815
- }
816
- });
817
- });
818
- }
819
-
820
- // Helper method for comma-separated code lists
821
- #commaListOfCodes(source) {
822
- const codes = source.split(',')
823
- .filter(s => this.codes.has(s.trim()))
824
- .map(s => `'${this.#sqlWrapString(s.trim())}'`);
825
- return codes.join(',');
826
- }
827
-
828
- async #executeSQL(sql, filter) {
829
- return new Promise((resolve, reject) => {
830
- this.db.all(sql, (err, rows) => {
831
- if (err) {
832
- reject(err);
833
- } else {
834
- filter.keys = rows.map(row => row.Key).filter(key => key !== 0);
835
- resolve();
836
- }
837
- });
838
- });
839
- }
840
-
841
- #sqlWrapString(str) {
842
- return str.replace(/'/g, "''");
843
- }
844
-
845
- async executeFilters(filterContext) {
846
-
847
- return filterContext.filters;
848
- }
849
-
850
- async filterSize(filterContext, set) {
851
-
852
- return set.keys.length;
853
- }
854
-
855
- async filterMore(filterContext, set) {
856
-
857
- set.cursor = set.cursor || 0;
858
- return set.cursor < set.keys.length;
859
- }
860
-
861
- async filterConcept(filterContext, set) {
862
-
863
-
864
- if (set.cursor >= set.keys.length) {
865
- return null;
866
- }
867
-
868
- const key = set.keys[set.cursor];
869
- set.cursor++;
870
-
871
- return this.codeList[key];
872
- }
873
-
874
- async filterLocate(filterContext, set, code) {
875
- const context = this.codes.get(code);
876
- if (!context) {
877
- return `Not a valid code: ${code}`;
878
- }
879
-
880
- if (!set.lsql) {
881
- return 'Filter not understood';
882
- }
883
-
884
- // Check if this context's key is in the filter
885
- if (set.hasKey(context.key)) {
886
- return context;
887
- } else {
888
- return null; // `Code ${code} is not in the specified filter`;
889
- }
890
- }
891
-
892
- async filterCheck(filterContext, set, concept) {
893
- if (!(concept instanceof LoincProviderContext)) {
894
- return false;
895
- }
896
-
897
- return set.hasKey(concept.key);
898
- }
899
-
900
- // Search filter - placeholder for text search
901
- // eslint-disable-next-line no-unused-vars
902
- async searchFilter(filterContext, filter, sort) {
903
-
904
- throw new Error('Text search not implemented yet');
905
- }
906
-
907
- // Subsumption testing
908
- async subsumesTest(codeA, codeB) {
909
- await this.#ensureContext(codeA);
910
- await this.#ensureContext(codeB);
911
-
912
- return 'not-subsumed'; // Not implemented yet
913
- }
914
-
915
- versionAlgorithm() {
916
- return 'natural';
917
- }
918
-
919
- isDisplay(designation) {
920
- return designation.use.code == "SHORTNAME" || designation.use.code == "LONG_COMMON_NAME" || designation.use.code == "LinguisticVariantDisplayName";
921
- }
922
- }
923
-
924
- class LoincServicesFactory extends CodeSystemFactoryProvider {
925
- constructor(i18n, dbPath) {
926
- super(i18n);
927
- this.dbPath = dbPath;
928
- this.uses = 0;
929
- this._loaded = false;
930
- this._sharedData = null;
931
- }
932
-
933
- system() {
934
- return 'http://loinc.org';
935
- }
936
-
937
- version() {
938
- return this._sharedData._version;
939
- }
940
-
941
- name() {
942
- return 'LOINC';
943
- }
944
-
945
- async #ensureLoaded() {
946
- if (!this._loaded) {
947
- await this.load();
948
- }
949
- }
950
-
951
- async load() {
952
- const db = new sqlite3.Database(this.dbPath);
953
-
954
- // Enable performance optimizations
955
- await this.#optimizeDatabase(db);
956
-
957
- try {
958
- this._sharedData = {
959
- langs: new Map(),
960
- codes: new Map(),
961
- codeList: [null],
962
- relationships: new Map(),
963
- propertyList: new Map(),
964
- statusKeys: new Map(),
965
- statusCodes: new Map(),
966
- _version: '',
967
- root: '',
968
- firstCodeKey: 0
969
- };
970
-
971
- // Load small lookup tables in parallel
972
- // eslint-disable-next-line no-unused-vars
973
- const [langs, statusCodes, relationships, propertyList, config] = await Promise.all([
974
- this.#loadLanguages(db),
975
- this.#loadStatusCodes(db),
976
- this.#loadRelationshipTypes(db),
977
- this.#loadPropertyTypes(db),
978
- this.#loadConfig(db)
979
- ]);
980
-
981
- // Load codes (largest operation)
982
- await this.#loadCodes(db);
983
-
984
- // Load dependent data in parallel
985
- await Promise.all([
986
- // this.#loadDesignationsCache(db),
987
- this.#loadHierarchy(db)
988
- ]);
989
-
990
- } finally {
991
- db.close();
992
- }
993
- this._loaded = true;
994
- }
995
-
996
- async #optimizeDatabase(db) {
997
- return new Promise((resolve) => {
998
- db.serialize(() => {
999
- db.run('PRAGMA journal_mode = WAL');
1000
- db.run('PRAGMA synchronous = NORMAL');
1001
- db.run('PRAGMA cache_size = 10000');
1002
- db.run('PRAGMA temp_store = MEMORY');
1003
- db.run('PRAGMA mmap_size = 268435456'); // 256MB
1004
- resolve();
1005
- });
1006
- });
1007
- }
1008
-
1009
- async #loadLanguages(db) {
1010
- return new Promise((resolve, reject) => {
1011
- db.all('SELECT LanguageKey, Code FROM Languages', (err, rows) => {
1012
- if (err) {
1013
- reject(err);
1014
- } else {
1015
- for (const row of rows) {
1016
- this._sharedData.langs.set(row.Code, row.LanguageKey);
1017
- }
1018
- resolve();
1019
- }
1020
- });
1021
- });
1022
- }
1023
-
1024
- async #loadStatusCodes(db) {
1025
- return new Promise((resolve, reject) => {
1026
- db.all('SELECT StatusKey, Description FROM StatusCodes', (err, rows) => {
1027
- if (err) {
1028
- reject(err);
1029
- } else {
1030
- for (const row of rows) {
1031
- this._sharedData.statusKeys.set(row.Description, row.StatusKey.toString());
1032
- this._sharedData.statusCodes.set(row.StatusKey.toString(), row.Description);
1033
- }
1034
- resolve();
1035
- }
1036
- });
1037
- });
1038
- }
1039
-
1040
- async #loadRelationshipTypes(db) {
1041
- return new Promise((resolve, reject) => {
1042
- db.all('SELECT RelationshipTypeKey, Description FROM RelationshipTypes', (err, rows) => {
1043
- if (err) {
1044
- reject(err);
1045
- } else {
1046
- for (const row of rows) {
1047
- this._sharedData.relationships.set(row.Description, row.RelationshipTypeKey.toString());
1048
- }
1049
- resolve();
1050
- }
1051
- });
1052
- });
1053
- }
1054
-
1055
- async #loadPropertyTypes(db) {
1056
- return new Promise((resolve, reject) => {
1057
- db.all('SELECT PropertyTypeKey, Description FROM PropertyTypes', (err, rows) => {
1058
- if (err) {
1059
- reject(err);
1060
- } else {
1061
- for (const row of rows) {
1062
- this._sharedData.propertyList.set(row.Description, row.PropertyTypeKey.toString());
1063
- }
1064
- resolve();
1065
- }
1066
- });
1067
- });
1068
- }
1069
-
1070
- async #loadCodes(db) {
1071
- return new Promise((resolve, reject) => {
1072
- // First get the count to pre-allocate array
1073
- db.get('SELECT MAX(CodeKey) as maxKey FROM Codes', (err, row) => {
1074
- if (err) return reject(err);
1075
-
1076
- // Pre-allocate the array to avoid repeated resizing
1077
- const maxKey = row.maxKey || 0;
1078
- this._sharedData.codeList = new Array(maxKey + 1).fill(null);
1079
-
1080
- // Now load all codes
1081
- db.all('SELECT CodeKey, Code, Type, Codes.Description, StatusCodes.Description as Status FROM Codes, StatusCodes where StatusCodes.StatusKey = Codes.StatusKey order by CodeKey Asc', (err, rows) => {
1082
- if (err) return reject(err);
1083
-
1084
- // Batch process rows
1085
- for (const row of rows) {
1086
- const context = new LoincProviderContext(
1087
- row.CodeKey,
1088
- row.Type - 1,
1089
- row.Code,
1090
- row.Description,
1091
- row.Status
1092
- );
1093
-
1094
- this._sharedData.codes.set(row.Code, context);
1095
- this._sharedData.codeList[row.CodeKey] = context;
1096
-
1097
- if (this._sharedData.firstCodeKey === 0 && context.kind === LoincProviderContextKind.CODE) {
1098
- this._sharedData.firstCodeKey = context.key;
1099
- }
1100
- }
1101
- resolve();
1102
- });
1103
- });
1104
- });
1105
- }
1106
-
1107
- async #loadDesignationsCache(db) {
1108
- return new Promise((resolve, reject) => {
1109
- const sql = `
1110
- SELECT
1111
- d.CodeKey,
1112
- l.Code as Lang,
1113
- dt.Description as DType,
1114
- d.Value,
1115
- dt.Description = 'LONG_COMMON_NAME' as IsDisplay
1116
- FROM Descriptions d
1117
- JOIN Languages l ON d.LanguageKey = l.LanguageKey
1118
- JOIN DescriptionTypes dt ON d.DescriptionTypeKey = dt.DescriptionTypeKey
1119
- WHERE d.DescriptionTypeKey != 4
1120
- ORDER BY d.CodeKey
1121
- `;
1122
-
1123
- db.all(sql, (err, rows) => {
1124
- if (err) return reject(err);
1125
-
1126
- // Batch process by CodeKey to reduce lookups
1127
- let currentKey = null;
1128
- let currentContext = null;
1129
-
1130
- for (const row of rows) {
1131
- if (row.CodeKey !== currentKey) {
1132
- currentKey = row.CodeKey;
1133
- currentContext = this._sharedData.codeList[currentKey];
1134
- }
1135
-
1136
- if (currentContext) {
1137
- currentContext.displays.push(
1138
- new DescriptionCacheEntry(row.IsDisplay, row.Lang, row.Value, row.DType)
1139
- );
1140
- }
1141
- }
1142
- resolve();
1143
- });
1144
- });
1145
- }
1146
-
1147
- async #loadHierarchy(db) {
1148
- const childRelKey = this._sharedData.relationships.get('child');
1149
- if (!childRelKey) {
1150
- return; // No child relationships defined
1151
- }
1152
-
1153
- return new Promise((resolve, reject) => {
1154
- const sql = `
1155
- SELECT SourceKey, TargetKey FROM Relationships
1156
- WHERE RelationshipTypeKey = ${childRelKey}
1157
- `;
1158
-
1159
- db.all(sql, (err, rows) => {
1160
- if (err) {
1161
- reject(err);
1162
- } else {
1163
- for (const row of rows) {
1164
- if (row.SourceKey !== 0 && row.TargetKey !== 0) {
1165
- const parentContext = this._sharedData.codeList[row.SourceKey];
1166
- if (parentContext) {
1167
- parentContext.addChild(row.TargetKey);
1168
- }
1169
- }
1170
- }
1171
- resolve();
1172
- }
1173
- });
1174
- });
1175
- }
1176
-
1177
- async #loadConfig(db) {
1178
- return new Promise((resolve, reject) => {
1179
- db.all('SELECT ConfigKey, Value FROM Config WHERE ConfigKey IN (2, 3)', (err, rows) => {
1180
- if (err) {
1181
- reject(err);
1182
- } else {
1183
- for (const row of rows) {
1184
- if (row.ConfigKey === 2) {
1185
- this._sharedData._version = row.Value;
1186
- } else if (row.ConfigKey === 3) {
1187
- this._sharedData.root = row.Value;
1188
- }
1189
- }
1190
- resolve();
1191
- }
1192
- });
1193
- });
1194
- }
1195
-
1196
- defaultVersion() {
1197
- return this._sharedData?._version || 'unknown';
1198
- }
1199
-
1200
- async build(opContext, supplements) {
1201
- await this.#ensureLoaded();
1202
- this.recordUse();
1203
-
1204
- // Create fresh database connection for this provider instance
1205
- const db = new sqlite3.Database(this.dbPath);
1206
-
1207
- return new LoincServices(opContext, supplements, db, this._sharedData);
1208
- }
1209
-
1210
- useCount() {
1211
- return this.uses;
1212
- }
1213
-
1214
- recordUse() {
1215
- this.uses++;
1216
- }
1217
-
1218
- async buildKnownValueSet(url, version) {
1219
-
1220
- if (version && version != this.version()) {
1221
- return null;
1222
- }
1223
- if (!url.startsWith('http://loinc.org/vs')) {
1224
- return null;
1225
- }
1226
- if (url == 'http://loinc.org/vs') {
1227
- // All LOINC codes
1228
- return {
1229
- resourceType: 'ValueSet', url: 'http://loinc.org/vs', version: this.version(), status: 'active',
1230
- name: 'LOINC Value Set - all LOINC codes', description: 'All LOINC codes',
1231
- date: new Date().toISOString(), experimental: false,
1232
- compose: { include: [{ system: this.system() }] }
1233
- };
1234
- }
1235
-
1236
- if (url.startsWith('http://loinc.org/vs/')) {
1237
- const code = url.substring(20);
1238
- const ci = this._sharedData.codes.get(code);
1239
- if (!ci) {
1240
- return null;
1241
- }
1242
-
1243
- if (ci.kind === LoincProviderContextKind.PART) {
1244
- // Part-based value set with ancestor filter
1245
- return {
1246
- resourceType: 'ValueSet', url: url, version: this.version(), status: 'active',
1247
- name: 'LOINCValueSetFor' + ci.code.replace(/-/g, '_'), description: 'LOINC value set for code ' + ci.code + ': ' + ci.desc,
1248
- date: new Date().toISOString(), experimental: false,
1249
- compose: { include: [{ system: this.system(), filter: [{ property: 'ancestor', op: '=', value: code }] }]
1250
- }
1251
- };
1252
- }
1253
-
1254
- if (ci.kind === LoincProviderContextKind.LIST) {
1255
- // Answer list - enumerate concepts from database
1256
- const concepts = await this.#getAnswerListConcepts(ci.key);
1257
- return {
1258
- resourceType: 'ValueSet', url: url, version: this.version(), status: 'active',
1259
- name: 'LOINCAnswerList' + ci.code.replace(/-/g, '_'), description: 'LOINC Answer list for code ' + ci.code + ': ' + ci.desc,
1260
- date: new Date().toISOString(), experimental: false,
1261
- compose: { include: [{ system: this.system(), concept: concepts }] }
1262
- };
1263
- }
1264
- }
1265
-
1266
- return null;
1267
- }
1268
-
1269
- /**
1270
- * Get answer list concepts from database
1271
- * @param {number} sourceKey - Key of the answer list
1272
- * @returns {Promise<Array>} Array of {code, display} objects
1273
- */
1274
- async #getAnswerListConcepts(sourceKey) {
1275
- return new Promise((resolve, reject) => {
1276
- let db = new sqlite3.Database(this.dbPath);
1277
- const sql = `
1278
- SELECT Code, Description
1279
- FROM Relationships, Codes
1280
- WHERE SourceKey = ?
1281
- AND RelationshipTypeKey = 40
1282
- AND Relationships.TargetKey = Codes.CodeKey
1283
- `;
1284
-
1285
- db.all(sql, [sourceKey], (err, rows) => {
1286
- if (err) {
1287
- reject(err);
1288
- } else {
1289
- const concepts = rows.map(row => ({
1290
- code: row.Code
1291
- }));
1292
- resolve(concepts);
1293
- }
1294
- });
1295
- });
1296
- }
1297
-
1298
- id() {
1299
- return "loinc"+this.version();
1300
- }
1301
- }
1302
-
1303
- module.exports = {
1304
- LoincServices,
1305
- LoincServicesFactory,
1306
- LoincProviderContext,
1307
- LoincProviderContextKind
1308
- };