1 package org.cacert.gigi.util;
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;
15 public class DatabaseManager {
17 public static String readFile(File f) throws IOException {
18 return new String(Files.readAllBytes(f.toPath()));
21 public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
23 if (args.length >= 1 && args[0].equals("--test")) {
25 String[] ne = new String[args.length - 1];
26 System.arraycopy(args, 1, ne, 0, ne.length);
29 if (args.length == 0) {
30 Properties p = new Properties();
31 p.load(new FileReader("config/gigi.properties"));
33 p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"), p.getProperty("sql.password")
36 if (args.length < 4) {
37 System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
40 run(args, test ? ImportType.TEST : ImportType.PRODUCTION);
43 public static enum ImportType {
45 * Execute Script as-as
49 * Execute Script, but changing Engine=InnoDB to Engine=Memory
53 * Execute INSERT statements as-is, and TRUNCATE instead of DROPPING
58 public static void run(String[] args, ImportType truncate) throws ClassNotFoundException, SQLException, IOException {
59 Class.forName(args[0]);
60 Connection conn = DriverManager.getConnection(args[1], args[2], args[3]);
61 conn.setAutoCommit(false);
62 Statement stmt = conn.createStatement();
63 addFile(stmt, new File("doc/tableStructure.sql"), truncate);
64 File localData = new File("doc/sampleData.sql");
65 if (localData.exists()) {
66 addFile(stmt, localData, ImportType.PRODUCTION);
73 private static void addFile(Statement stmt, File f, ImportType type) throws IOException, SQLException {
74 String sql = readFile(f);
75 sql = sql.replaceAll("--[^\n]+\n", "\n");
76 String[] stmts = sql.split(";");
77 Pattern p = Pattern.compile("\\s*DROP TABLE IF EXISTS `([^`]+)`");
78 for (String string : stmts) {
79 Matcher m = p.matcher(string);
80 string = string.trim();
81 if (string.equals("")) {
84 if (m.matches() && type == ImportType.TRUNCATE) {
85 String sql2 = "TRUNCATE `" + m.group(1) + "`";
89 if (type == ImportType.PRODUCTION || string.startsWith("INSERT")) {
90 stmt.addBatch(string);
91 } else if (type == ImportType.TEST) {
92 stmt.addBatch(string.replace("ENGINE=InnoDB", "ENGINE=Memory"));