]> WPIA git - gigi.git/blob - src/org/cacert/gigi/database/SQLFileManager.java
fix: several testcases to the new configuration/structure
[gigi.git] / src / org / cacert / gigi / database / SQLFileManager.java
1 package org.cacert.gigi.database;
2
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;
10
11 public class SQLFileManager {
12
13     public static enum ImportType {
14         /**
15          * Execute Script as-as
16          */
17         PRODUCTION,
18         /**
19          * Execute Script, but changing Engine=InnoDB to Engine=Memory
20          */
21         TEST,
22         /**
23          * Execute INSERT statements as-is, and TRUNCATE instead of DROPPING
24          */
25         TRUNCATE
26     }
27
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("")) {
37                 continue;
38             }
39             if ((string.contains("profiles") || string.contains("cacerts")) && type != ImportType.PRODUCTION) {
40                 continue;
41             }
42             if (m.matches() && type == ImportType.TRUNCATE) {
43                 String sql2 = "TRUNCATE `" + m.group(1) + "`";
44                 stmt.addBatch(sql2);
45                 continue;
46             }
47             if (type == ImportType.PRODUCTION || string.startsWith("INSERT")) {
48                 stmt.addBatch(string);
49             } else if (type == ImportType.TEST) {
50                 stmt.addBatch(string.replace("ENGINE=InnoDB", "ENGINE=Memory"));
51             }
52         }
53     }
54
55     private static String readFile(InputStream f) throws IOException {
56         ByteArrayOutputStream baos = new ByteArrayOutputStream();
57         int len;
58         byte[] buf = new byte[4096];
59         while ((len = f.read(buf)) > 0) {
60             baos.write(buf, 0, len);
61         }
62         return new String(baos.toByteArray(), "UTF-8");
63     }
64 }