1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.migration.hook;
17
18 import java.io.ByteArrayOutputStream;
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.IOException;
22 import java.io.PrintStream;
23 import java.io.StringReader;
24 import java.util.Map;
25 import java.util.Properties;
26
27 import org.apache.ibatis.migration.MigrationException;
28 import org.apache.ibatis.migration.VariableReplacer;
29 import org.apache.ibatis.migration.utils.Util;
30
31 public class SqlHookScript implements HookScript {
32
33 protected final File scriptFile;
34 protected final String charset;
35 protected final Properties variables;
36 protected final PrintStream printStream;
37 protected final VariableReplacer replacer;
38
39 public SqlHookScript(File scriptFile, String charset, String[] options, Properties variables,
40 PrintStream printStream) {
41 this.scriptFile = scriptFile;
42 this.charset = charset;
43 this.variables = variables;
44 this.printStream = printStream;
45
46 for (String option : options) {
47 int sep = option.indexOf('=');
48 if (sep > -1) {
49 this.variables.put(option.substring(0, sep), option.substring(sep + 1));
50 }
51 }
52 replacer = new VariableReplacer(this.variables);
53 }
54
55 @Override
56 public void execute(Map<String, Object> bindingMap) {
57 HookContext context = (HookContext) bindingMap.get(MigrationHook.HOOK_CONTEXT);
58 printStream.println(Util.horizontalLine("Applying SQL hook: " + scriptFile.getName(), 80));
59
60 try (FileInputStream inputStream = new FileInputStream(scriptFile);
61 ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
62 byte[] buffer = new byte[1024];
63 int length;
64 while ((length = inputStream.read(buffer)) != -1) {
65 outputStream.write(buffer, 0, length);
66 }
67 try (StringReader reader = new StringReader(replacer.replace(outputStream.toString(charset)))) {
68 context.executeSql(reader);
69 }
70 } catch (IOException e) {
71 throw new MigrationException("Error occurred while running SQL hook script.", e);
72 }
73 }
74 }