Advertisement
Guest User

ScriptRunner - remove package name

a guest
Feb 16th, 2011
1,614
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.01 KB | None | 0 0
  1. /*
  2.  * Modified by Pantelis Sopasakis <chvng@mail.ntua.gr> to take care of DILIMITER
  3.  * statements. This way you can execute scripts that contain some TRIGGER creation
  4.  * code. New version using REGEXPs!
  5.  * Latest modification: Cater for a NullPointerException while parsing.
  6.  * Date: Feb 16, 2011, 11:48 EET
  7.  */
  8. /*
  9.  * Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
  10.  * from the iBATIS Apache project. Only removed dependency on Resource class
  11.  * and a constructor
  12.  */
  13. /*
  14.  *  Copyright 2004 Clinton Begin
  15.  *
  16.  *  Licensed under the Apache License, Version 2.0 (the "License");
  17.  *  you may not use this file except in compliance with the License.
  18.  *  You may obtain a copy of the License at
  19.  *
  20.  *      http://www.apache.org/licenses/LICENSE-2.0
  21.  *
  22.  *  Unless required by applicable law or agreed to in writing, software
  23.  *  distributed under the License is distributed on an "AS IS" BASIS,
  24.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25.  *  See the License for the specific language governing permissions and
  26.  *  limitations under the License.
  27.  */
  28.  
  29. import java.io.IOException;
  30. import java.io.LineNumberReader;
  31. import java.io.PrintWriter;
  32. import java.io.Reader;
  33. import java.sql.Connection;
  34. import java.sql.ResultSet;
  35. import java.sql.ResultSetMetaData;
  36. import java.sql.SQLException;
  37. import java.sql.Statement;
  38. import java.util.regex.Matcher;
  39. import java.util.regex.Pattern;
  40.  
  41. /**
  42.  * Tool to run database scripts
  43.  */
  44. public class ScriptRunner {
  45.  
  46.     private static final String DEFAULT_DELIMITER = ";";
  47.     private Connection connection;
  48.     private boolean stopOnError;
  49.     private boolean autoCommit;
  50.     private PrintWriter logWriter = new PrintWriter(System.out);
  51.     private PrintWriter errorLogWriter = new PrintWriter(System.err);
  52.     private String delimiter = DEFAULT_DELIMITER;
  53.     private boolean fullLineDelimiter = false;
  54.     private static final String DELIMITER_LINE_REGEX = "(?i)DELIMITER.+";
  55.     private static final String DELIMITER_LINE_SPLIT_REGEX = "(?i)DELIMITER";
  56.  
  57.     /**
  58.      * Default constructor
  59.      */
  60.     public ScriptRunner(Connection connection, boolean autoCommit,
  61.             boolean stopOnError) {
  62.         this.connection = connection;
  63.         this.autoCommit = autoCommit;
  64.         this.stopOnError = stopOnError;
  65.     }
  66.  
  67.     public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
  68.         this.delimiter = delimiter;
  69.         this.fullLineDelimiter = fullLineDelimiter;
  70.     }
  71.  
  72.     /**
  73.      * Setter for logWriter property
  74.      *
  75.      * @param logWriter
  76.      *            - the new value of the logWriter property
  77.      */
  78.     public void setLogWriter(PrintWriter logWriter) {
  79.         this.logWriter = logWriter;
  80.     }
  81.  
  82.     /**
  83.      * Setter for errorLogWriter property
  84.      *
  85.      * @param errorLogWriter
  86.      *            - the new value of the errorLogWriter property
  87.      */
  88.     public void setErrorLogWriter(PrintWriter errorLogWriter) {
  89.         this.errorLogWriter = errorLogWriter;
  90.     }
  91.  
  92.     /**
  93.      * Runs an SQL script (read in using the Reader parameter)
  94.      *
  95.      * @param reader
  96.      *            - the source of the script
  97.      */
  98.     public void runScript(Reader reader) throws IOException, SQLException {
  99.         try {
  100.             boolean originalAutoCommit = connection.getAutoCommit();
  101.             try {
  102.                 if (originalAutoCommit != this.autoCommit) {
  103.                     connection.setAutoCommit(this.autoCommit);
  104.                 }
  105.                 runScript(connection, reader);
  106.             } finally {
  107.                 connection.setAutoCommit(originalAutoCommit);
  108.             }
  109.         } catch (IOException e) {
  110.             throw e;
  111.         } catch (SQLException e) {
  112.             throw e;
  113.         } catch (Exception e) {
  114.             throw new RuntimeException("Error running script.  Cause: " + e, e);
  115.         }
  116.     }
  117.  
  118.     /**
  119.      * Runs an SQL script (read in using the Reader parameter) using the
  120.      * connection passed in
  121.      *
  122.      * @param conn
  123.      *            - the connection to use for the script
  124.      * @param reader
  125.      *            - the source of the script
  126.      * @throws SQLException
  127.      *             if any SQL errors occur
  128.      * @throws IOException
  129.      *             if there is an error reading from the Reader
  130.      */
  131.     private void runScript(Connection conn, Reader reader) throws IOException,
  132.             SQLException {
  133.         StringBuffer command = null;
  134.         try {
  135.             LineNumberReader lineReader = new LineNumberReader(reader);
  136.             String line = null;
  137.             while ((line = lineReader.readLine()) != null) {
  138.                 if (command == null) {
  139.                     command = new StringBuffer();
  140.                 }
  141.                 String trimmedLine = line.trim();
  142.                 if (trimmedLine.startsWith("--")) {
  143.                     println(trimmedLine);
  144.                 } else if (trimmedLine.length() < 1
  145.                         || trimmedLine.startsWith("//")) {
  146.                     // Do nothing
  147.                 } else if (trimmedLine.length() < 1
  148.                         || trimmedLine.startsWith("--")) {
  149.                     // Do nothing
  150.                 } else if (!fullLineDelimiter
  151.                         && trimmedLine.endsWith(getDelimiter())
  152.                         || fullLineDelimiter
  153.                         && trimmedLine.equals(getDelimiter())) {
  154.  
  155.  
  156.                     Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
  157.                     Matcher matcher = pattern.matcher(trimmedLine);
  158.                     if (matcher.matches()) {
  159.                         setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter);
  160.                         line = lineReader.readLine();
  161.                         if (line == null) {
  162.                             break;
  163.                         }
  164.                         trimmedLine = line.trim();
  165.                     }
  166.  
  167.                     command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
  168.                     command.append(" ");
  169.                     Statement statement = conn.createStatement();
  170.  
  171.                     println(command);
  172.  
  173.                     boolean hasResults = false;
  174.                     if (stopOnError) {
  175.                         hasResults = statement.execute(command.toString());
  176.                     } else {
  177.                         try {
  178.                             statement.execute(command.toString());
  179.                         } catch (SQLException e) {
  180.                             e.fillInStackTrace();
  181.                             printlnError("Error executing: " + command);
  182.                             printlnError(e);
  183.                         }
  184.                     }
  185.  
  186.                     if (autoCommit && !conn.getAutoCommit()) {
  187.                         conn.commit();
  188.                     }
  189.  
  190.                     ResultSet rs = statement.getResultSet();
  191.                     if (hasResults && rs != null) {
  192.                         ResultSetMetaData md = rs.getMetaData();
  193.                         int cols = md.getColumnCount();
  194.                         for (int i = 0; i < cols; i++) {
  195.                             String name = md.getColumnLabel(i);
  196.                             print(name + "\t");
  197.                         }
  198.                         println("");
  199.                         while (rs.next()) {
  200.                             for (int i = 1; i <= cols; i++) {
  201.                                 String value = rs.getString(i);
  202.                                 print(value + "\t");
  203.                             }
  204.                             println("");
  205.                         }
  206.                     }
  207.                    
  208.                     command = null;
  209.                     try {
  210.                         rs.close();
  211.                     } catch (Exception e) {
  212.                         e.printStackTrace();
  213.                     }
  214.                     try {
  215.                         statement.close();
  216.                     } catch (Exception e) {
  217.                         e.printStackTrace();
  218.                         // Ignore to workaround a bug in Jakarta DBCP
  219.                     }
  220.                     Thread.yield();
  221.                 } else {
  222.                     Pattern pattern = Pattern.compile(DELIMITER_LINE_REGEX);
  223.                     Matcher matcher = pattern.matcher(trimmedLine);
  224.                     if (matcher.matches()) {
  225.                         setDelimiter(trimmedLine.split(DELIMITER_LINE_SPLIT_REGEX)[1].trim(), fullLineDelimiter);
  226.                         line = lineReader.readLine();
  227.                         if (line == null) {
  228.                             break;
  229.                         }
  230.                         trimmedLine = line.trim();
  231.                     }
  232.                     command.append(line);
  233.                     command.append(" ");
  234.                 }
  235.             }
  236.             if (!autoCommit) {
  237.                 conn.commit();
  238.             }
  239.         } catch (SQLException e) {
  240.             e.fillInStackTrace();
  241.             printlnError("Error executing: " + command);
  242.             printlnError(e);
  243.             throw e;
  244.         } catch (IOException e) {
  245.             e.fillInStackTrace();
  246.             printlnError("Error executing: " + command);
  247.             printlnError(e);
  248.             throw e;
  249.         } finally {
  250.             conn.rollback();
  251.             flush();
  252.         }
  253.     }
  254.  
  255.     private String getDelimiter() {
  256.         return delimiter;
  257.     }
  258.  
  259.     private void print(Object o) {
  260.         if (logWriter != null) {
  261.             System.out.print(o);
  262.         }
  263.     }
  264.  
  265.     private void println(Object o) {
  266.         if (logWriter != null) {
  267.             logWriter.println(o);
  268.         }
  269.     }
  270.  
  271.     private void printlnError(Object o) {
  272.         if (errorLogWriter != null) {
  273.             errorLogWriter.println(o);
  274.         }
  275.     }
  276.  
  277.     private void flush() {
  278.         if (logWriter != null) {
  279.             logWriter.flush();
  280.         }
  281.         if (errorLogWriter != null) {
  282.             errorLogWriter.flush();
  283.         }
  284.     }
  285. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement