]> WPIA git - gigi.git/blob - util/org/cacert/gigi/util/DatabaseManager.java
UPD: change "email"-constructor to match the syntax of the
[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         conn.setAutoCommit(false);
40         Statement stmt = conn.createStatement();
41         addFile(stmt, new File("doc/tableStructure.sql"), truncate);
42         File localData = new File("doc/sampleData.sql");
43         if (localData.exists()) {
44             addFile(stmt, localData, false);
45         }
46         stmt.executeBatch();
47         conn.commit();
48         stmt.close();
49     }
50
51     private static void addFile(Statement stmt, File f, boolean truncate) throws IOException, SQLException {
52         String sql = readFile(f);
53         sql = sql.replaceAll("--[^\n]+\n", "\n");
54         String[] stmts = sql.split(";");
55         Pattern p = Pattern.compile("\\s*DROP TABLE IF EXISTS `([^`]+)`");
56         for (String string : stmts) {
57             Matcher m = p.matcher(string);
58             if (m.matches()) {
59                 String sql2 = "TRUNCATE `" + m.group(1) + "`";
60                 stmt.addBatch(sql2);
61             }
62             if ( !string.trim().equals("") && ( !truncate || string.contains("INSERT"))) {
63                 stmt.addBatch(string.replace("ENGINE=Memory", ""));
64             }
65         }
66     }
67 }