📄 torquesqlexec.java
字号:
// We want to make sure that the base schemas // are inserted first. if (sqlfile.indexOf("schema.sql") != -1) { files.add(0, sqlfile); } else { files.add(sqlfile); } } Iterator eachDatabase = databases.keySet().iterator(); while (eachDatabase.hasNext()) { String db = (String) eachDatabase.next(); List transactions = new ArrayList(); eachFileName = ((List) databases.get(db)).iterator(); while (eachFileName.hasNext()) { String fileName = (String) eachFileName.next(); File file = new File(srcDir, fileName); if (file.exists()) { Transaction transaction = new Transaction(); transaction.setSrc(file); transactions.add(transaction); } else { super.log("File '" + fileName + "' in sqldbmap does not exist, so skipping it."); } } insertDatabaseSqlFiles(url, db, transactions); } } /** * Take the base url, the target database and insert a set of SQL * files into the target database. * * @param url * @param database * @param transactions */ private void insertDatabaseSqlFiles(String url, String database, List transactions) { url = StringUtils.replace(url, "@DB@", database); System.out.println("Our new url -> " + url); Driver driverInstance = null; try { Class dc; if (classpath != null) { log("Loading " + driver + " using AntClassLoader with classpath " + classpath, Project.MSG_VERBOSE); loader = new AntClassLoader(project, classpath); dc = loader.loadClass(driver); } else { log("Loading " + driver + " using system loader.", Project.MSG_VERBOSE); dc = Class.forName(driver); } driverInstance = (Driver) dc.newInstance(); } catch (ClassNotFoundException e) { throw new BuildException("Class Not Found: JDBC driver " + driver + " could not be loaded", location); } catch (IllegalAccessException e) { throw new BuildException("Illegal Access: JDBC driver " + driver + " could not be loaded", location); } catch (InstantiationException e) { throw new BuildException("Instantiation Exception: JDBC driver " + driver + " could not be loaded", location); } try { log("connecting to " + url, Project.MSG_VERBOSE); Properties info = new Properties(); info.put("user", userId); info.put("password", password); conn = driverInstance.connect(url, info); if (conn == null) { // Driver doesn't understand the URL throw new SQLException("No suitable Driver for " + url); } if (!isValidRdbms(conn)) { return; } conn.setAutoCommit(autocommit); statement = conn.createStatement(); PrintStream out = System.out; try { if (output != null) { log("Opening PrintStream to output file " + output, Project.MSG_VERBOSE); out = new PrintStream(new BufferedOutputStream( new FileOutputStream(output))); } // Process all transactions for (Iterator it = transactions.iterator(); it.hasNext();) { ((Transaction) it.next()).runTransaction(out); if (!autocommit) { log("Commiting transaction", Project.MSG_VERBOSE); conn.commit(); } } } finally { if (out != null && out != System.out) { out.close(); } } } catch (IOException e) { if (!autocommit && conn != null && onError.equals("abort")) { try { conn.rollback(); } catch (SQLException ex) { // do nothing. } } throw new BuildException(e, location); } catch (SQLException e) { if (!autocommit && conn != null && onError.equals("abort")) { try { conn.rollback(); } catch (SQLException ex) { // do nothing. } } throw new BuildException(e, location); } finally { try { if (statement != null) { statement.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { } } log(goodSql + " of " + totalSql + " SQL statements executed successfully"); } /** * Read the statements from the .sql file and execute them. * Lines starting with '//', '--' or 'REM ' are ignored. * * @param reader * @param out * @throws SQLException * @throws IOException */ protected void runStatements(Reader reader, PrintStream out) throws SQLException, IOException { String sql = ""; String line = ""; BufferedReader in = new BufferedReader(reader); try { while ((line = in.readLine()) != null) { line = line.trim(); line = ProjectHelper.replaceProperties(project, line, project.getProperties()); if (line.startsWith("//") || line.startsWith("--")) { continue; } if (line.length() > 4 && line.substring(0, 4).equalsIgnoreCase("REM ")) { continue; } sql += " " + line; sql = sql.trim(); // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (line.indexOf("--") >= 0) { sql += "\n"; } if (delimiterType.equals(DelimiterType.NORMAL) && sql.endsWith(delimiter) || delimiterType.equals(DelimiterType.ROW) && line.equals(delimiter)) { log("SQL: " + sql, Project.MSG_VERBOSE); execSQL(sql.substring(0, sql.length() - delimiter.length()), out); sql = ""; } } // Catch any statements not followed by ; if (!sql.equals("")) { execSQL(sql, out); } } catch (SQLException e) { throw e; } } /** * Verify if connected to the correct RDBMS * * @param conn */ protected boolean isValidRdbms(Connection conn) { if (rdbms == null && version == null) { return true; } try { DatabaseMetaData dmd = conn.getMetaData(); if (rdbms != null) { String theVendor = dmd.getDatabaseProductName().toLowerCase(); log("RDBMS = " + theVendor, Project.MSG_VERBOSE); if (theVendor == null || theVendor.indexOf(rdbms) < 0) { log("Not the required RDBMS: " + rdbms, Project.MSG_VERBOSE); return false; } } if (version != null) { String theVersion = dmd.getDatabaseProductVersion() .toLowerCase(); log("Version = " + theVersion, Project.MSG_VERBOSE); if (theVersion == null || !(theVersion.startsWith(version) || theVersion.indexOf(" " + version) >= 0)) { log("Not the required version: \"" + version + "\"", Project.MSG_VERBOSE); return false; } } } catch (SQLException e) { // Could not get the required information log("Failed to obtain required RDBMS information", Project.MSG_ERR); return false; } return true; } /** * Exec the sql statement. * * @param sql * @param out * @throws SQLException */ protected void execSQL(String sql, PrintStream out) throws SQLException { // Check and ignore empty statements if ("".equals(sql.trim())) { return; } try { totalSql++; if (!statement.execute(sql)) { log(statement.getUpdateCount() + " rows affected", Project.MSG_VERBOSE); } else { if (print) { printResults(out); } } SQLWarning warning = conn.getWarnings(); while (warning != null) { log(warning + " sql warning", Project.MSG_VERBOSE); warning = warning.getNextWarning(); } conn.clearWarnings(); goodSql++; } catch (SQLException e) { log("Failed to execute: " + sql, Project.MSG_ERR); if (!onError.equals("continue")) { throw e; } log(e.toString(), Project.MSG_ERR); } } /** * print any results in the statement. * * @param out * @throws SQLException */ protected void printResults(PrintStream out) throws java.sql.SQLException { ResultSet rs = null; do { rs = statement.getResultSet(); if (rs != null) { log("Processing new result set.", Project.MSG_VERBOSE); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); StringBuffer line = new StringBuffer(); if (showheaders) { for (int col = 1; col < columnCount; col++) { line.append(md.getColumnName(col)); line.append(","); } line.append(md.getColumnName(columnCount)); out.println(line); line.setLength(0); } while (rs.next()) { boolean first = true; for (int col = 1; col <= columnCount; col++) { String columnValue = rs.getString(col); if (columnValue != null) { columnValue = columnValue.trim(); } if (first) { first = false; } else { line.append(","); } line.append(columnValue); } out.println(line); line.setLength(0); } } } while (statement.getMoreResults()); out.println(); } /** * Enumerated attribute with the values "continue", "stop" and "abort" * for the onerror attribute. */ public static class OnError extends EnumeratedAttribute { public String[] getValues() { return new String[] {"continue", "stop", "abort"}; } } /** * Contains the definition of a new transaction element. * Transactions allow several files or blocks of statements * to be executed using the same JDBC connection and commit * operation in between. */ public class Transaction { private File tSrcFile = null; private String tSqlCommand = ""; public void setSrc(File src) { this.tSrcFile = src; } public void addText(String sql) { this.tSqlCommand += sql; } private void runTransaction(PrintStream out) throws IOException, SQLException { if (tSqlCommand.length() != 0) { log("Executing commands", Project.MSG_INFO); runStatements(new StringReader(tSqlCommand), out); } if (tSrcFile != null) { log("Executing file: " + tSrcFile.getAbsolutePath(), Project.MSG_INFO); Reader reader = (encoding == null) ? new FileReader(tSrcFile) : new InputStreamReader(new FileInputStream(tSrcFile), encoding); runStatements(reader, out); reader.close(); } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -