Advertisement
Guest User

joe

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