|
| 1 | +package io.github.eaxdev.jsonsql4j.query.update; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import io.github.eaxdev.jsonsql4j.exception.JsonSQL4JParseException; |
| 6 | +import io.github.eaxdev.jsonsql4j.model.Update; |
| 7 | +import io.github.eaxdev.jsonsql4j.query.ClauseBuilder; |
| 8 | +import io.github.eaxdev.jsonsql4j.query.Query; |
| 9 | +import io.github.eaxdev.jsonsql4j.query.WhereClauseBuilder; |
| 10 | + |
| 11 | +import java.util.Objects; |
| 12 | +import java.util.stream.Collectors; |
| 13 | + |
| 14 | +/** |
| 15 | + * @author eaxdev |
| 16 | + */ |
| 17 | +public class UpdateQuery implements Query { |
| 18 | + |
| 19 | + private static final ObjectMapper MAPPER = new ObjectMapper(); |
| 20 | + |
| 21 | + private final Update update; |
| 22 | + |
| 23 | + private final ClauseBuilder whereBuilder; |
| 24 | + |
| 25 | + public UpdateQuery(String jsonQuery) { |
| 26 | + //validate by schema |
| 27 | + try { |
| 28 | + this.update = MAPPER.readValue(jsonQuery, Update.class); |
| 29 | + } catch (JsonProcessingException e) { |
| 30 | + throw new JsonSQL4JParseException("Can not parse json query: [" + jsonQuery + "]", e); |
| 31 | + } |
| 32 | + whereBuilder = new WhereClauseBuilder(update.getCriteria()); |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public String getQuery() { |
| 37 | + return "UPDATE " + update.getTableView() + " SET " + constructUpdate() + whereBuilder.build() + ";"; |
| 38 | + } |
| 39 | + |
| 40 | + private String constructUpdate() { |
| 41 | + return update.getModify().entrySet().stream() |
| 42 | + .map(entry -> { |
| 43 | + if (entry.getValue() instanceof String) { |
| 44 | + return entry.getKey() + " = '" + entry.getValue().toString() + "'"; |
| 45 | + } else { |
| 46 | + return Objects.isNull(entry.getValue()) ? "" : entry.getKey() + " = " + entry.getValue().toString(); |
| 47 | + } |
| 48 | + }) |
| 49 | + .collect(Collectors.joining(", ")); |
| 50 | + } |
| 51 | +} |
0 commit comments