1 package org.cacert.gigi.database;
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.sql.SQLException;
7 import java.sql.Statement;
8 import java.util.regex.Matcher;
9 import java.util.regex.Pattern;
11 public class SQLFileManager {
13 public static enum ImportType {
15 * Execute Script as-is
19 * Execute Script, but change Engine=InnoDB to Engine=Memory
23 * Execute INSERT statements as-is, and TRUNCATE instead of DROPPING
28 public static void addFile(Statement stmt, InputStream f, ImportType type) throws IOException, SQLException {
29 String sql = readFile(f);
30 sql = sql.replaceAll("--[^\n]*\n", "\n");
31 sql = sql.replaceAll("#[^\n]*\n", "\n");
32 String[] stmts = sql.split(";");
33 Pattern p = Pattern.compile("\\s*DROP TABLE IF EXISTS \"([^\"]+)\"");
34 for (String string : stmts) {
35 Matcher m = p.matcher(string);
36 string = string.trim();
37 if (string.equals("")) {
40 if ((string.contains("profiles") || string.contains("cacerts") || string.contains("cats_type")) && type != ImportType.PRODUCTION) {
43 string = DatabaseConnection.preprocessQuery(string);
44 if (m.matches() && type == ImportType.TRUNCATE) {
45 String sql2 = "DELETE FROM \"" + m.group(1) + "\"";
49 if (type == ImportType.PRODUCTION || string.startsWith("INSERT")) {
50 stmt.addBatch(string);
51 } else if (type == ImportType.TEST) {
52 stmt.addBatch(string.replace("ENGINE=InnoDB", "ENGINE=Memory"));
57 private static String readFile(InputStream f) throws IOException {
58 ByteArrayOutputStream baos = new ByteArrayOutputStream();
60 byte[] buf = new byte[4096];
61 while ((len = f.read(buf)) > 0) {
62 baos.write(buf, 0, len);
64 return new String(baos.toByteArray(), "UTF-8");