]> WPIA git - gigi.git/blob - util/org/cacert/gigi/util/DatabaseManager.java
457e11ff27b0c42a3a92e89f42422eba917aedef
[gigi.git] / util / org / cacert / gigi / util / DatabaseManager.java
1 package org.cacert.gigi.util;
2
3 import java.io.File;
4 import java.io.FileReader;
5 import java.io.IOException;
6 import java.nio.file.Files;
7 import java.sql.Connection;
8 import java.sql.DriverManager;
9 import java.sql.SQLException;
10 import java.sql.Statement;
11 import java.util.Properties;
12 import java.util.regex.Matcher;
13 import java.util.regex.Pattern;
14
15 public class DatabaseManager {
16
17     public static String readFile(File f) throws IOException {
18         return new String(Files.readAllBytes(f.toPath()));
19     }
20
21     public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
22         if (args.length == 0) {
23             Properties p = new Properties();
24             p.load(new FileReader("config/gigi.properties"));
25             args = new String[] {
26                     p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"), p.getProperty("sql.password")
27             };
28         }
29         if (args.length < 4) {
30             System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
31             return;
32         }
33         run(args, false);
34     }
35
36     public static void run(String[] args, boolean truncate) throws ClassNotFoundException, SQLException, IOException {
37         Class.forName(args[0]);
38         Connection conn = DriverManager.getConnection(args[1], args[2], args[3]);
39         Statement stmt = conn.createStatement();
40         addFile(stmt, new File("doc/tableStructure.sql"), truncate);
41         File localData = new File("doc/sampleData.sql");
42         if (localData.exists()) {
43             addFile(stmt, localData, false);
44         }
45         stmt.executeBatch();
46         stmt.close();
47     }
48
49     private static void addFile(Statement stmt, File f, boolean truncate) throws IOException, SQLException {
50         String sql = readFile(f);
51         String[] stmts = sql.split(";");
52         Pattern p = Pattern.compile("\\s*DROP TABLE IF EXISTS `([^`]+)`");
53         for (String string : stmts) {
54             Matcher m = p.matcher(string);
55             if (m.matches()) {
56                 String sql2 = "TRUNCATE `" + m.group(1) + "`";
57                 stmt.addBatch(sql2);
58             }
59             if ( !string.trim().equals("") && ( !truncate || string.contains("INSERT"))) {
60                 stmt.addBatch(string.replace("ENGINE=Memory", ""));
61             }
62         }
63     }
64 }