]> WPIA git - gigi.git/blob - src/org/cacert/gigi/database/SQLFileManager.java
add: split API and add CATS import API
[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-is
16          */
17         PRODUCTION,
18         /**
19          * Execute Script, but change 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         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("")) {
38                 continue;
39             }
40             if ((string.contains("profiles") || string.contains("cacerts") || string.contains("cats_type")) && type != ImportType.PRODUCTION) {
41                 continue;
42             }
43             string = DatabaseConnection.preprocessQuery(string);
44             if (m.matches() && type == ImportType.TRUNCATE) {
45                 String sql2 = "DELETE FROM \"" + m.group(1) + "\"";
46                 stmt.addBatch(sql2);
47                 continue;
48             }
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"));
53             }
54         }
55     }
56
57     private static String readFile(InputStream f) throws IOException {
58         ByteArrayOutputStream baos = new ByteArrayOutputStream();
59         int len;
60         byte[] buf = new byte[4096];
61         while ((len = f.read(buf)) > 0) {
62             baos.write(buf, 0, len);
63         }
64         return new String(baos.toByteArray(), "UTF-8");
65     }
66 }