]> WPIA git - gigi.git/blobdiff - src/org/cacert/gigi/database/SQLFileManager.java
ADD: scheme versioning, last time "Please execute database manager" ;-)
[gigi.git] / src / org / cacert / gigi / database / SQLFileManager.java
diff --git a/src/org/cacert/gigi/database/SQLFileManager.java b/src/org/cacert/gigi/database/SQLFileManager.java
new file mode 100644 (file)
index 0000000..676d9e6
--- /dev/null
@@ -0,0 +1,61 @@
+package org.cacert.gigi.database;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class SQLFileManager {
+
+    public static enum ImportType {
+        /**
+         * Execute Script as-as
+         */
+        PRODUCTION,
+        /**
+         * Execute Script, but changing Engine=InnoDB to Engine=Memory
+         */
+        TEST,
+        /**
+         * Execute INSERT statements as-is, and TRUNCATE instead of DROPPING
+         */
+        TRUNCATE
+    }
+
+    public static void addFile(Statement stmt, InputStream f, ImportType type) throws IOException, SQLException {
+        String sql = readFile(f);
+        sql = sql.replaceAll("--[^\n]+\n", "\n");
+        String[] stmts = sql.split(";");
+        Pattern p = Pattern.compile("\\s*DROP TABLE IF EXISTS `([^`]+)`");
+        for (String string : stmts) {
+            Matcher m = p.matcher(string);
+            string = string.trim();
+            if (string.equals("")) {
+                continue;
+            }
+            if (m.matches() && type == ImportType.TRUNCATE) {
+                String sql2 = "TRUNCATE `" + m.group(1) + "`";
+                stmt.addBatch(sql2);
+                continue;
+            }
+            if (type == ImportType.PRODUCTION || string.startsWith("INSERT")) {
+                stmt.addBatch(string);
+            } else if (type == ImportType.TEST) {
+                stmt.addBatch(string.replace("ENGINE=InnoDB", "ENGINE=Memory"));
+            }
+        }
+    }
+
+    private static String readFile(InputStream f) throws IOException {
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        int len;
+        byte[] buf = new byte[4096];
+        while ((len = f.read(buf)) > 0) {
+            baos.write(buf, 0, len);
+        }
+        return new String(baos.toByteArray());
+    }
+}