001package org.hl7.fhir.r5.utils.sql; 002 003import java.util.List; 004 005import org.hl7.fhir.r5.model.Base; 006import org.hl7.fhir.utilities.json.model.JsonArray; 007import org.hl7.fhir.utilities.json.model.JsonBoolean; 008import org.hl7.fhir.utilities.json.model.JsonElement; 009import org.hl7.fhir.utilities.json.model.JsonNull; 010import org.hl7.fhir.utilities.json.model.JsonNumber; 011import org.hl7.fhir.utilities.json.model.JsonObject; 012import org.hl7.fhir.utilities.json.model.JsonString; 013 014public class StorageJson implements Storage { 015 016 private String name; 017 private JsonArray rows; 018 019 @Override 020 public boolean supportsArrays() { 021 return true; 022 } 023 024 @Override 025 public Store createStore(String name, List<Column> columns) { 026 this.name = name; 027 this.rows = new JsonArray(); 028 return new Store(name); // we're not doing anything with this 029 } 030 031 @Override 032 public void addRow(Store store, List<Cell> cells) { 033 JsonObject row = new JsonObject(); 034 rows.add(row); 035 for (Cell cell : cells) { 036 if (cell.getValues().size() == 0) { 037 row.add(cell.getColumn().getName(), new JsonNull()); 038 } else if (cell.getValues().size() == 1) { 039 row.add(cell.getColumn().getName(), makeJsonNode(cell.getValues().get(0))); 040 } else { 041 JsonArray arr = new JsonArray(); 042 row.add(cell.getColumn().getName(), arr); 043 for (Value value : cell.getValues()) { 044 arr.add(makeJsonNode(value)); 045 } 046 } 047 } 048 } 049 050 private JsonElement makeJsonNode(Value value) { 051 if (value == null) { 052 return new JsonNull(); 053 } else if (value.getValueInt() != null) { 054 return new JsonNumber(value.getValueInt().intValue()); 055 } 056 if (value.getValueBoolean() != null) { 057 return new JsonBoolean(value.getValueBoolean().booleanValue()); 058 } 059 if (value.getValueDecimal() != null) { 060 return new JsonNumber(value.getValueDecimal().toPlainString()); 061 } 062 return new JsonString(value.getValueString()); 063 } 064 065 @Override 066 public void finish(Store store) { 067 // nothing 068 } 069 070 public String getName() { 071 return name; 072 } 073 074 public JsonArray getRows() { 075 return rows; 076 } 077 078 @Override 079 public boolean supportsComplexTypes() { 080 return true; 081 } 082 083 @Override 084 public boolean needsName() { 085 return false; 086 } 087 088 @Override 089 public String getKeyForSourceResource(Base res) { 090 return res.getIdBase(); 091 } 092 093 @Override 094 public String getKeyForTargetResource(Base res) { 095 return res.fhirType()+"/"+res.getIdBase(); 096 } 097 098}