Debian Codegraph @

src/tools/org/h2/dev/util/Migrate.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.dev.util;
7
8 import java.io.BufferedInputStream;
9 import java.io.ByteArrayOutputStream;
10 import java.io.File;
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.OutputStream;
14 import java.io.PrintStream;
15 import java.io.RandomAccessFile;
16 import java.net.URL;
17 import java.nio.charset.StandardCharsets;
18 import java.security.MessageDigest;
19 import java.security.NoSuchAlgorithmException;
20 import java.util.concurrent.TimeUnit;
21
22 import org.h2.engine.Constants;
23 import org.h2.tools.RunScript;
24
25 /**
26 * Migrate a H2 database version 1.1.x (page store not enabled) to 1.2.x (page
27 * store format). This will download the H2 jar file version 1.2.127 from
28 * maven.org if it doesn't exist, execute the Script tool (using Runtime.exec)
29 * to create a backup.sql script, rename the old database file to *.backup,
30 * created a new database (using the H2 jar file in the class path) using the
31 * Script tool, and then delete the backup.sql file. Most utility methods are
32 * copied from h2/src/tools/org/h2/build/BuildBase.java.
33 */
34 public class Migrate {
35
36 private static final String USER = "sa";
37 private static final String PASSWORD = "sa";
38 private static final File OLD_H2_FILE = new File("./h2-1.2.127.jar");
39 private static final String DOWNLOAD_URL =
40 "https://repo1.maven.org/maven2/com/h2database/h2/1.2.127/h2-1.2.127.jar";
41 private static final String CHECKSUM =
42 "056e784c7cf009483366ab9cd8d21d02fe47031a";
43 private static final String TEMP_SCRIPT = "backup.sql";
44 private final PrintStream sysOut = System.out;
45 private boolean quiet;
46
47 /**
48 * Migrate databases. The user name and password are both "sa".
49 *
50 * @param args the path (default is the current directory)
51 * @throws Exception if conversion fails
52 */
53 public static void main(String... args) throws Exception {
54 new Migrate().execute(new File(args.length == 1 ? args[0] : "."), true,
55 USER, PASSWORD, false);
56 }
57
58 /**
59 * Migrate a database.
60 *
61 * @param file the database file (must end with .data.db) or directory
62 * @param recursive if the file parameter is in fact a directory (in which
63 * case the directory is scanned recursively)
64 * @param user the user name of the database
65 * @param password the password
66 * @param runQuiet to run in quiet mode
67 * @throws Exception if conversion fails
68 */
69 public void execute(File file, boolean recursive, String user,
70 String password, boolean runQuiet) throws Exception {
71 String pathToJavaExe = getJavaExecutablePath();
72 this.quiet = runQuiet;
73 if (file.isDirectory() && recursive) {
74 for (File f : file.listFiles()) {
75 execute(f, recursive, user, password, runQuiet);
76 }
77 return;
78 }
79 if (!file.getName().endsWith(Constants.SUFFIX_OLD_DATABASE_FILE)) {
80 return;
81 }
82 println("Migrating " + file.getName());
83 if (!OLD_H2_FILE.exists()) {
84 download(OLD_H2_FILE.getAbsolutePath(), DOWNLOAD_URL, CHECKSUM);
85 }
86 String url = "jdbc:h2:" + file.getAbsolutePath();
87 url = url.substring(0, url.length() - Constants.SUFFIX_OLD_DATABASE_FILE.length());
88 exec(new String[] {
89 pathToJavaExe,
90 "-Xmx128m",
91 "-cp", OLD_H2_FILE.getAbsolutePath(),
92 "org.h2.tools.Script",
93 "-script", TEMP_SCRIPT,
94 "-url", url,
95 "-user", user,
96 "-password", password
97 });
98 file.renameTo(new File(file.getAbsoluteFile() + ".backup"));
99 RunScript.execute(url, user, password, TEMP_SCRIPT, StandardCharsets.UTF_8, true);
100 new File(TEMP_SCRIPT).delete();
101 }
102
103 private static String getJavaExecutablePath() {
104 String pathToJava;
105 if (File.separator.equals("\\")) {
106 pathToJava = System.getProperty("java.home") + File.separator
107 + "bin" + File.separator + "java.exe";
108 } else {
109 pathToJava = System.getProperty("java.home") + File.separator
110 + "bin" + File.separator + "java";
111 }
112 if (!new File(pathToJava).exists()) {
113 // Fallback to old behaviour
114 pathToJava = "java";
115 }
116 return pathToJava;
117 }
118
119 private void download(String target, String fileURL, String sha1Checksum) {
120 File targetFile = new File(target);
121 if (targetFile.exists()) {
122 return;
123 }
124 mkdirs(targetFile.getAbsoluteFile().getParentFile());
125 ByteArrayOutputStream buff = new ByteArrayOutputStream();
126 try {
127 println("Downloading " + fileURL);
128 URL url = new URL(fileURL);
129 InputStream in = new BufferedInputStream(url.openStream());
130 long last = System.nanoTime();
131 int len = 0;
132 while (true) {
133 long now = System.nanoTime();
134 if (now > last + TimeUnit.SECONDS.toNanos(1)) {
135 println("Downloaded " + len + " bytes");
136 last = now;
137 }
138 int x = in.read();
139 len++;
140 if (x < 0) {
141 break;
142 }
143 buff.write(x);
144 }
145 in.close();
146 } catch (IOException e) {
147 throw new RuntimeException("Error downloading", e);
148 }
149 byte[] data = buff.toByteArray();
150 String got = getSHA1(data);
151 if (sha1Checksum == null) {
152 println("SHA1 checksum: " + got);
153 } else {
154 if (!got.equals(sha1Checksum)) {
155 throw new RuntimeException("SHA1 checksum mismatch; got: " + got);
156 }
157 }
158 writeFile(targetFile, data);
159 }
160
161 private static void mkdirs(File f) {
162 if (!f.exists()) {
163 if (!f.mkdirs()) {
164 throw new RuntimeException("Can not create directory " + f.getAbsolutePath());
165 }
166 }
167 }
168
169 private void println(String s) {
170 if (!quiet) {
171 sysOut.println(s);
172 }
173 }
174
175 private void print(String s) {
176 if (!quiet) {
177 sysOut.print(s);
178 }
179 }
180
181 private static String getSHA1(byte[] data) {
182 MessageDigest md;
183 try {
184 md = MessageDigest.getInstance("SHA-1");
185 return convertBytesToString(md.digest(data));
186 } catch (NoSuchAlgorithmException e) {
187 throw new RuntimeException(e);
188 }
189 }
190
191 private static String convertBytesToString(byte[] value) {
192 StringBuilder buff = new StringBuilder(value.length * 2);
193 for (byte c : value) {
194 int x = c & 0xff;
195 buff.append(Integer.toString(x >> 4, 16)).
196 append(Integer.toString(x & 0xf, 16));
197 }
198 return buff.toString();
199 }
200
201 private static void writeFile(File file, byte[] data) {
202 try {
203 RandomAccessFile ra = new RandomAccessFile(file, "rw");
204 ra.write(data);
205 ra.setLength(data.length);
206 ra.close();
207 } catch (IOException e) {
208 throw new RuntimeException("Error writing to file " + file, e);
209 }
210 }
211
212 private int exec(String[] command) {
213 try {
214 for (String c : command) {
215 print(c + " ");
216 }
217 println("");
218 Process p = Runtime.getRuntime().exec(command);
219 copyInThread(p.getInputStream(), quiet ? null : sysOut);
220 copyInThread(p.getErrorStream(), quiet ? null : sysOut);
221 p.waitFor();
222 return p.exitValue();
223 } catch (Exception e) {
224 throw new RuntimeException(e);
225 }
226 }
227
228 private static void copyInThread(final InputStream in, final OutputStream out) {
229 new Thread() {
230 @Override
231 public void run() {
232 try {
233 while (true) {
234 int x = in.read();
235 if (x < 0) {
236 return;
237 }
238 if (out != null) {
239 out.write(x);
240 }
241 }
242 } catch (Exception e) {
243 throw new RuntimeException(e);
244 }
245 }
246 }.start();
247 }
248
249 }