001package io.ebean.migration.runner;
002
003import java.util.HashMap;
004import java.util.Map;
005
006/**
007 * Transforms a SQL script given a map of key/value substitutions.
008 */
009public class ScriptTransform {
010
011  /**
012   * Transform just ${table} with the table name.
013   */
014  public static String replace(String key, String value, String script) {
015    return script.replace(key, value);
016  }
017
018  private final Map<String,String> placeholders = new HashMap<>();
019
020  ScriptTransform(Map<String,String> map) {
021    for (Map.Entry<String, String> entry : map.entrySet()) {
022      placeholders.put(wrapKey(entry.getKey()), entry.getValue());
023    }
024  }
025
026  /**
027   * Build and return a ScriptTransform that replaces placeholder values in DDL scripts.
028   */
029  public static ScriptTransform build(String runPlaceholders, Map<String, String> runPlaceholderMap) {
030    Map<String, String> map = PlaceholderBuilder.build(runPlaceholders, runPlaceholderMap);
031    return new ScriptTransform(map);
032  }
033
034  private String wrapKey(String key) {
035    return "${"+key+"}";
036  }
037
038  /**
039   * Transform the script replacing placeholders in the form <code>${key}</code> with <code>value</code>.
040   */
041  public String transform(String source) {
042
043    for (Map.Entry<String, String> entry : placeholders.entrySet()) {
044      source = source.replace(entry.getKey(), entry.getValue());
045    }
046    return source;
047  }
048}