import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class CreateVideoDev {
    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            System.err.println("Usage: CreateVideoDev <sql-file>");
            System.exit(1);
        }

        String url = "jdbc:dm://8.142.21.6:5236?schema=JZ_TEST";
        String username = "SYSDBA";
        String password = "Dameng1@34";
        String sqlFile = args[0];

        Class.forName("dm.jdbc.driver.DmDriver");
        Connection conn = DriverManager.getConnection(url, username, password);
        conn.setAutoCommit(false);
        Statement stmt = conn.createStatement();

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(new FileInputStream(sqlFile), StandardCharsets.UTF_8));
        StringBuilder sqlBuilder = new StringBuilder();
        String line;
        int count = 0;

        while ((line = reader.readLine()) != null) {
            // strip UTF-8 BOM if present on first line
            if (count == 0 && line.length() > 0 && line.charAt(0) == '\uFEFF') {
                line = line.substring(1);
            }
            line = line.trim();
            if (line.isEmpty() || line.startsWith("--")) {
                continue;
            }
            sqlBuilder.append(line).append(" ");
            if (line.endsWith(";")) {
                String sql = sqlBuilder.toString().trim();
                System.out.println("EXEC: " + sql);
                stmt.executeUpdate(sql);
                count++;
                sqlBuilder = new StringBuilder();
            }
        }

        conn.commit();
        reader.close();
        stmt.close();
        conn.close();
        System.out.println("Done. statements=" + count);
    }
}
