001package org.hl7.fhir.r4.utils.sql; 002 003import java.math.BigDecimal; 004import java.util.ArrayList; 005import java.util.List; 006 007import lombok.extern.slf4j.Slf4j; 008import org.apache.commons.codec.binary.Base64; 009import org.hl7.fhir.exceptions.FHIRException; 010import org.hl7.fhir.exceptions.PathEngineException; 011import org.hl7.fhir.r4.context.IWorkerContext; 012import org.hl7.fhir.r4.fhirpath.ExpressionNode; 013import org.hl7.fhir.r4.fhirpath.FHIRPathEngine; 014import org.hl7.fhir.r4.fhirpath.TypeDetails; 015import org.hl7.fhir.r4.fhirpath.ExpressionNode.CollectionStatus; 016import org.hl7.fhir.r4.fhirpath.IHostApplicationServices; 017import org.hl7.fhir.r4.fhirpath.FHIRPathUtilityClasses.FunctionDetails; 018import org.hl7.fhir.r4.model.*; 019import org.hl7.fhir.utilities.MarkedToMoveToAdjunctPackage; 020import org.hl7.fhir.utilities.fhirpath.FHIRPathConstantEvaluationMode; 021import org.hl7.fhir.utilities.json.model.JsonObject; 022import org.hl7.fhir.utilities.validation.ValidationMessage; 023 024 025/** 026 * How to use the Runner: 027 * 028 * create a resource, and fill out: 029 * the context (supports the FHIRPathEngine) 030 * a store that handles the output 031 * a tracker - if you want 032 * 033 * Once it's created, you either run it as a batch, or in trickle mode 034 * 035 * (1) Batch Mode 036 * 037 * * provide a provider 038 * * call execute() with a ViewDefinition 039 * * wait... (watch with an observer if you want to track progress) 040 * 041 * (2) Trickle Mode 042 * * call 'prepare', and keep the WorkContext that's returned 043 * * each time there's a resource to process, call processResource and pass in the workContext and the resource 044 * * when done, call finish(WorkContext) 045 */ 046 047@MarkedToMoveToAdjunctPackage 048@Slf4j 049public class Runner implements IHostApplicationServices { 050 051 public interface IRunnerObserver { 052 public void handleRow(Base resource, int total, int cursor); 053 } 054 055 public class WorkContext { 056 private JsonObject vd; 057 private Store store; 058 protected WorkContext(JsonObject vd) { 059 super(); 060 this.vd = vd; 061 } 062 063 } 064 private IWorkerContext context; 065 private Provider provider; 066 private Storage storage; 067 private IRunnerObserver observer; 068 private List<String> prohibitedNames = new ArrayList<String>(); 069 private FHIRPathEngine fpe; 070 071 private String resourceName; 072 private List<ValidationMessage> issues; 073 private int resCount; 074 075 076 public IWorkerContext getContext() { 077 return context; 078 } 079 public void setContext(IWorkerContext context) { 080 this.context = context; 081 } 082 083 public Provider getProvider() { 084 return provider; 085 } 086 public void setProvider(Provider provider) { 087 this.provider = provider; 088 } 089 090 public Storage getStorage() { 091 return storage; 092 } 093 public void setStorage(Storage storage) { 094 this.storage = storage; 095 } 096 097 public List<String> getProhibitedNames() { 098 return prohibitedNames; 099 } 100 101 public void execute(JsonObject viewDefinition) { 102 execute("$", viewDefinition); 103 } 104 105 public void execute(String path, JsonObject viewDefinition) { 106 WorkContext wc = prepare(path, viewDefinition); 107 try { 108 evaluate(wc); 109 } finally { 110 finish(wc); 111 } 112 } 113 114 private void evaluate(WorkContext wc) { 115 List<Base> data = provider.fetch(resourceName); 116 117 int i = 0; 118 for (Base b : data) { 119 if (observer != null) { 120 observer.handleRow(b, data.size(), i); 121 } 122 processResource(wc.vd, wc.store, b); 123 i++; 124 } 125 } 126 127 public WorkContext prepare(String path, JsonObject viewDefinition) { 128 WorkContext wc = new WorkContext(viewDefinition); 129 if (context == null) { 130 throw new FHIRException("No context provided"); 131 } 132 fpe = new FHIRPathEngine(context); 133 fpe.setHostServices(this); 134 fpe.setEmitSQLonFHIRWarning(true); 135 if (viewDefinition == null) { 136 throw new FHIRException("No viewDefinition provided"); 137 } 138 if (provider == null) { 139 throw new FHIRException("No provider provided"); 140 } 141 if (storage == null) { 142 throw new FHIRException("No storage provided"); 143 } 144 Validator validator = new Validator(context, fpe, prohibitedNames, storage.supportsArrays(), storage.supportsComplexTypes(), storage.needsName()); 145 validator.checkViewDefinition(path, viewDefinition); 146 issues = validator.getIssues(); 147 validator.dump(); 148 validator.check(); 149 resourceName = validator.getResourceName(); 150 wc.store = storage.createStore(wc.vd.asString("name"), (List<Column>) wc.vd.getUserData("columns")); 151 return wc; 152 } 153 154 public void processResource(WorkContext wc, Base b) { 155 if (observer != null) { 156 observer.handleRow(b, -1, resCount); 157 } 158 processResource(wc.vd, wc.store, b); 159 resCount++; 160 wc.store.flush(); 161 } 162 163 private void processResource(JsonObject vd, Store store, Base b) { 164 boolean ok = true; 165 for (JsonObject w : vd.getJsonObjects("where")) { 166 String expr = w.asString("path"); 167 ExpressionNode node = fpe.parse(expr); 168 boolean pass = fpe.evaluateToBoolean(vd, b, b, b, node); 169 if (!pass) { 170 ok = false; 171 break; 172 } 173 } 174 if (ok) { 175 List<List<Cell>> rows = new ArrayList<>(); 176 rows.add(new ArrayList<Cell>()); 177 178 for (JsonObject select : vd.getJsonObjects("select")) { 179 executeSelect(vd, select, b, rows); 180 } 181 for (List<Cell> row : rows) { 182 storage.addRow(store, row); 183 } 184 } 185 } 186 187 public void finish(WorkContext wc) { 188 storage.finish(wc.store); 189 } 190 191 private void executeSelect(JsonObject vd, JsonObject select, Base b, List<List<Cell>> rows) { 192 List<Base> focus = new ArrayList<>(); 193 194 if (select.has("forEach")) { 195 focus.addAll(executeForEach(vd, select, b)); 196 } else if (select.has("forEachOrNull")) { 197 198 focus.addAll(executeForEachOrNull(vd, select, b)); 199 if (focus.isEmpty()) { 200 List<Column> columns = (List<Column>) select.getUserData("columns"); 201 for (List<Cell> row : rows) { 202 for (Column c : columns) { 203 Cell cell = cell(row, c.getName()); 204 if (cell == null) { 205 row.add(new Cell(c, null)); 206 } 207 } 208 } 209 return; 210 } 211 } else { 212 focus.add(b); 213 } 214 215 // } else if (select.has("unionAll")) { 216 // focus.addAll(executeUnion(select, b)); 217 218 List<List<Cell>> tempRows = new ArrayList<>(); 219 tempRows.addAll(rows); 220 rows.clear(); 221 222 for (Base f : focus) { 223 List<List<Cell>> rowsToAdd = cloneRows(tempRows); 224 225 for (JsonObject column : select.getJsonObjects("column")) { 226 executeColumn(vd, column, f, rowsToAdd); 227 } 228 229 for (JsonObject sub : select.getJsonObjects("select")) { 230 executeSelect(vd, sub, f, rowsToAdd); 231 } 232 233 executeUnionAll(vd, select.getJsonObjects("unionAll"), f, rowsToAdd); 234 235 rows.addAll(rowsToAdd); 236 } 237 } 238 239 private void executeUnionAll(JsonObject vd, List<JsonObject> unionList, Base b, List<List<Cell>> rows) { 240 if (unionList.isEmpty()) { 241 return; 242 } 243 List<List<Cell>> sourceRows = new ArrayList<>(); 244 sourceRows.addAll(rows); 245 rows.clear(); 246 247 for (JsonObject union : unionList) { 248 List<List<Cell>> tempRows = new ArrayList<>(); 249 tempRows.addAll(sourceRows); 250 executeSelect(vd, union, b, tempRows); 251 rows.addAll(tempRows); 252 } 253 } 254 255 private List<List<Cell>> cloneRows(List<List<Cell>> rows) { 256 List<List<Cell>> list = new ArrayList<>(); 257 for (List<Cell> row : rows) { 258 list.add(cloneRow(row)); 259 } 260 return list; 261 } 262 263 private List<Cell> cloneRow(List<Cell> cells) { 264 List<Cell> list = new ArrayList<>(); 265 for (Cell cell : cells) { 266 list.add(cell.copy()); 267 } 268 return list; 269 } 270 271 private List<Base> executeForEach(JsonObject vd, JsonObject focus, Base b) { 272 ExpressionNode n = (ExpressionNode) focus.getUserData("forEach"); 273 List<Base> result = new ArrayList<>(); 274 result.addAll(fpe.evaluate(vd, b, n)); 275 return result; 276 } 277 278 private List<Base> executeForEachOrNull(JsonObject vd, JsonObject focus, Base b) { 279 ExpressionNode n = (ExpressionNode) focus.getUserData("forEachOrNull"); 280 List<Base> result = new ArrayList<>(); 281 result.addAll(fpe.evaluate(vd, b, n)); 282 return result; 283 } 284 285 private void executeColumn(JsonObject vd, JsonObject column, Base b, List<List<Cell>> rows) { 286 ExpressionNode n = (ExpressionNode) column.getUserData("path"); 287 List<Base> bl2 = new ArrayList<>(); 288 if (b != null) { 289 bl2.addAll(fpe.evaluate(vd, b, n)); 290 } 291 Column col = (Column) column.getUserData("column"); 292 if (col == null) { 293 log.error("Error"); 294 } else { 295 for (List<Cell> row : rows) { 296 Cell c = cell(row, col.getName()); 297 if (c == null) { 298 c = new Cell(col); 299 row.add(c); 300 } 301 if (!bl2.isEmpty()) { 302 if (bl2.size() + c.getValues().size() > 1) { 303 // this is a problem if collection != true or if the storage can't deal with it 304 // though this should've been picked up before now - but there are circumstances where it wouldn't be 305 if (!c.getColumn().isColl()) { 306 throw new FHIRException("The column "+c.getColumn().getName()+" is not allowed multiple values, but at least one row has multiple values"); 307 } 308 } 309 for (Base b2 : bl2) { 310 c.getValues().add(genValue(c.getColumn(), b2)); 311 } 312 } 313 } 314 } 315 } 316 317 318 private Value genValue(Column column, Base b) { 319 if (column.getKind() == null) { 320 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to an unknown column type (null) for column "+column.getName()); // can't happen 321 } 322 switch (column.getKind()) { 323 case Binary: 324 if (b instanceof Base64BinaryType) { 325 Base64BinaryType bb = (Base64BinaryType) b; 326 return Value.makeBinary(bb.primitiveValue(), bb.getValue()); 327 } else if (b.isBooleanPrimitive()) { // ElementModel 328 return Value.makeBinary(b.primitiveValue(), Base64.decodeBase64(b.primitiveValue())); 329 } else { 330 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to a binary column for column "+column.getName()); 331 } 332 case Boolean: 333 if (b instanceof BooleanType) { 334 BooleanType bb = (BooleanType) b; 335 return Value.makeBoolean(bb.primitiveValue(), bb.booleanValue()); 336 } else if (b.isBooleanPrimitive()) { // ElementModel 337 return Value.makeBoolean(b.primitiveValue(), "true".equals(b.primitiveValue())); 338 } else { 339 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to a boolean column for column "+column.getName()); 340 } 341 case Complex: 342 if (b.isPrimitive()) { 343 throw new FHIRException("Attempt to add a primitive type "+b.fhirType()+" to a complex column for column "+column.getName()); 344 } else { 345 return Value.makeComplex(b); 346 } 347 case DateTime: 348 if (b instanceof BaseDateTimeType) { 349 BaseDateTimeType d = (BaseDateTimeType) b; 350 return Value.makeDate(d.primitiveValue(), d.getValue()); 351 } else if (b.isPrimitive() && b.isDateTime()) { // ElementModel 352 return Value.makeDate(b.primitiveValue(), b.dateTimeValue().getValue()); 353 } else { 354 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to an integer column for column "+column.getName()); 355 } 356 case Decimal: 357 if (b instanceof DecimalType) { 358 DecimalType d = (DecimalType) b; 359 return Value.makeDecimal(d.primitiveValue(), d.getValue()); 360 } else if (b.isPrimitive()) { // ElementModel 361 return Value.makeDecimal(b.primitiveValue(), new BigDecimal(b.primitiveValue())); 362 } else { 363 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to an integer column for column "+column.getName()); 364 } 365 case Integer: 366 if (b instanceof IntegerType) { 367 IntegerType i = (IntegerType) b; 368 return Value.makeInteger(i.primitiveValue(), i.getValue()); 369 } else if (b.isPrimitive()) { // ElementModel 370 return Value.makeInteger(b.primitiveValue(), Integer.valueOf(b.primitiveValue())); 371 } else { 372 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to an integer column for column "+column.getName()); 373 } 374 case String: 375 if (b.isPrimitive()) { 376 return Value.makeString(b.primitiveValue()); 377 } else { 378 throw new FHIRException("Attempt to add a complex type "+b.fhirType()+" to a string column for column "+column.getName()); 379 } 380 case Time: 381 if (b.fhirType().equals("time")) { 382 return Value.makeString(b.primitiveValue()); 383 } else { 384 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to a time column for column "+column.getName()); 385 } 386 default: 387 throw new FHIRException("Attempt to add a type "+b.fhirType()+" to an unknown column type for column "+column.getName()); 388 } 389 } 390 391 private Column column(String columnName, List<Column> columns) { 392 for (Column t : columns) { 393 if (t.getName().equalsIgnoreCase(columnName)) { 394 return t; 395 } 396 } 397 return null; 398 } 399 400 private Cell cell(List<Cell> cells, String columnName) { 401 for (Cell t : cells) { 402 if (t.getColumn().getName().equalsIgnoreCase(columnName)) { 403 return t; 404 } 405 } 406 return null; 407 } 408 409 @Override 410 public List<Base> resolveConstant(FHIRPathEngine engine, Object appContext, String name, FHIRPathConstantEvaluationMode mode) throws PathEngineException { 411 List<Base> list = new ArrayList<Base>(); 412 if (mode == FHIRPathConstantEvaluationMode.EXPLICIT) { 413 JsonObject vd = (JsonObject) appContext; 414 JsonObject constant = findConstant(vd, name); 415 if (constant != null) { 416 Base b = (Base) constant.getUserData("value"); 417 if (b != null) { 418 list.add(b); 419 } 420 } 421 } 422 return list; 423 } 424 425 @Override 426 public TypeDetails resolveConstantType(FHIRPathEngine engine, Object appContext, String name, FHIRPathConstantEvaluationMode mode) throws PathEngineException { 427 if (mode == FHIRPathConstantEvaluationMode.EXPLICIT) { 428 JsonObject vd = (JsonObject) appContext; 429 JsonObject constant = findConstant(vd, name.substring(1)); 430 if (constant != null) { 431 Base b = (Base) constant.getUserData("value"); 432 if (b != null) { 433 return new TypeDetails(CollectionStatus.SINGLETON, b.fhirType()); 434 } 435 } 436 } 437 return null; 438 } 439 440 private JsonObject findConstant(JsonObject vd, String name) { 441 for (JsonObject o : vd.getJsonObjects("constant")) { 442 if (name.equals(o.asString("name"))) { 443 return o; 444 } 445 } 446 return null; 447 } 448 @Override 449 public boolean log(String argument, List<Base> focus) { 450 throw new Error("Not implemented yet: log"); 451 } 452 453 @Override 454 public FunctionDetails resolveFunction(FHIRPathEngine engine, String functionName) { 455 switch (functionName) { 456 case "getResourceKey" : return new FunctionDetails("Unique Key for resource", 0, 0); 457 case "getReferenceKey" : return new FunctionDetails("Unique Key for resource that is the target of the reference", 0, 1); 458 default: return null; 459 } 460 } 461 @Override 462 public TypeDetails checkFunction(FHIRPathEngine engine, Object appContext, String functionName, TypeDetails focus, List<TypeDetails> parameters) throws PathEngineException { 463 switch (functionName) { 464 case "getResourceKey" : return new TypeDetails(CollectionStatus.SINGLETON, "string"); 465 case "getReferenceKey" : return new TypeDetails(CollectionStatus.SINGLETON, "string"); 466 default: throw new Error("Not known: "+functionName); 467 } 468 } 469 470 @Override 471 public List<Base> executeFunction(FHIRPathEngine engine, Object appContext, List<Base> focus, String functionName, List<List<Base>> parameters) { 472 switch (functionName) { 473 case "getResourceKey" : return executeResourceKey(focus); 474 case "getReferenceKey" : return executeReferenceKey(null, focus, parameters); 475 default: throw new Error("Not known: "+functionName); 476 } 477 } 478 479 private List<Base> executeResourceKey(List<Base> focus) { 480 List<Base> base = new ArrayList<Base>(); 481 if (focus.size() == 1) { 482 Base res = focus.get(0); 483 if (!res.hasUserData("Storage.key")) { 484 String key = storage.getKeyForSourceResource(res); 485 if (key == null) { 486 throw new FHIRException("Unidentified resource: "+res.fhirType()+"/"+res.getIdBase()); 487 } else { 488 res.setUserData("Storage.key", key); 489 } 490 } 491 base.add(new StringType(res.getUserString("Storage.key"))); 492 } 493 return base; 494 } 495 496 private List<Base> executeReferenceKey(Base rootResource, List<Base> focus, List<List<Base>> parameters) { 497 String rt = null; 498 if (parameters.size() > 0) { 499 rt = parameters.get(0).get(0).primitiveValue(); 500 if (rt.startsWith("FHIR.")) { 501 rt = rt.substring(5); 502 } 503 } 504 List<Base> base = new ArrayList<Base>(); 505 if (focus.size() == 1) { 506 Base res = focus.get(0); 507 String ref = null; 508 if (res.fhirType().equals("Reference")) { 509 ref = getRef(res); 510 } else if (res.isPrimitive()) { 511 ref = res.primitiveValue(); 512 } else { 513 throw new FHIRException("Unable to generate a reference key based on a "+res.fhirType()); 514 } 515 if (ref != null) { 516 Base target = provider.resolveReference(rootResource, ref, rt); 517 if (target != null) { 518 if (!res.hasUserData("Storage.key")) { 519 String key = storage.getKeyForTargetResource(target); 520 if (key == null) { 521 throw new FHIRException("Unidentified resource: "+res.fhirType()+"/"+res.getIdBase()); 522 } else { 523 res.setUserData("Storage.key", key); 524 } 525 } 526 base.add(new StringType(res.getUserString("Storage.key"))); 527 } 528 } 529 } 530 return base; 531 } 532 533 private String getRef(Base res) { 534 Property prop = res.getChildByName("reference"); 535 if (prop != null && prop.getValues().size() == 1) { 536 return prop.getValues().get(0).primitiveValue(); 537 } 538 return null; 539 } 540 541 @Override 542 public Base resolveReference(FHIRPathEngine engine, Object appContext, String url, Identifier identifier, Base refContext) throws FHIRException { 543 throw new Error("Not implemented yet: resolveReference"); 544 } 545 546 @Override 547 public boolean conformsToProfile(FHIRPathEngine engine, Object appContext, Base item, String url) throws FHIRException { 548 throw new Error("Not implemented yet: conformsToProfile"); 549 } 550 551 @Override 552 public ValueSet resolveValueSet(FHIRPathEngine engine, Object appContext, String url) { 553 throw new Error("Not implemented yet: resolveValueSet"); 554 } 555 @Override 556 public boolean paramIsType(String name, int index) { 557 return "getReferenceKey".equals(name); 558 } 559 public List<ValidationMessage> getIssues() { 560 return issues; 561 } 562 563 564}