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-as
19 * Execute Script, but changing 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 String[] stmts = sql.split(";");
32 Pattern p = Pattern.compile("\\s*DROP TABLE IF EXISTS `([^`]+)`");
33 for (String string : stmts) {
34 Matcher m = p.matcher(string);
35 string = string.trim();
36 if (string.equals("")) {
39 if (m.matches() && type == ImportType.TRUNCATE) {
40 String sql2 = "TRUNCATE `" + m.group(1) + "`";
44 if (type == ImportType.PRODUCTION || string.startsWith("INSERT")) {
45 stmt.addBatch(string);
46 } else if (type == ImportType.TEST) {
47 stmt.addBatch(string.replace("ENGINE=InnoDB", "ENGINE=Memory"));
52 private static String readFile(InputStream f) throws IOException {
53 ByteArrayOutputStream baos = new ByteArrayOutputStream();
55 byte[] buf = new byte[4096];
56 while ((len = f.read(buf)) > 0) {
57 baos.write(buf, 0, len);
59 return new String(baos.toByteArray());