You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SQLExec.java 32 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package org.apache.tools.ant.taskdefs;
  19. import org.apache.tools.ant.BuildException;
  20. import org.apache.tools.ant.Project;
  21. import org.apache.tools.ant.util.FileUtils;
  22. import org.apache.tools.ant.util.StringUtils;
  23. import org.apache.tools.ant.types.EnumeratedAttribute;
  24. import org.apache.tools.ant.types.FileSet;
  25. import org.apache.tools.ant.types.Resource;
  26. import org.apache.tools.ant.types.ResourceCollection;
  27. import org.apache.tools.ant.types.resources.FileResource;
  28. import org.apache.tools.ant.types.resources.Union;
  29. import java.io.File;
  30. import java.io.PrintStream;
  31. import java.io.BufferedOutputStream;
  32. import java.io.FileOutputStream;
  33. import java.io.IOException;
  34. import java.io.Reader;
  35. import java.io.BufferedReader;
  36. import java.io.StringReader;
  37. import java.io.InputStream;
  38. import java.io.InputStreamReader;
  39. import java.util.Enumeration;
  40. import java.util.Iterator;
  41. import java.util.Locale;
  42. import java.util.StringTokenizer;
  43. import java.util.Vector;
  44. import java.sql.Connection;
  45. import java.sql.Statement;
  46. import java.sql.SQLException;
  47. import java.sql.SQLWarning;
  48. import java.sql.ResultSet;
  49. import java.sql.ResultSetMetaData;
  50. import java.sql.Types;
  51. /**
  52. * Executes a series of SQL statements on a database using JDBC.
  53. *
  54. * <p>Statements can
  55. * either be read in from a text file using the <i>src</i> attribute or from
  56. * between the enclosing SQL tags.</p>
  57. *
  58. * <p>Multiple statements can be provided, separated by semicolons (or the
  59. * defined <i>delimiter</i>). Individual lines within the statements can be
  60. * commented using either --, // or REM at the start of the line.</p>
  61. *
  62. * <p>The <i>autocommit</i> attribute specifies whether auto-commit should be
  63. * turned on or off whilst executing the statements. If auto-commit is turned
  64. * on each statement will be executed and committed. If it is turned off the
  65. * statements will all be executed as one transaction.</p>
  66. *
  67. * <p>The <i>onerror</i> attribute specifies how to proceed when an error occurs
  68. * during the execution of one of the statements.
  69. * The possible values are: <b>continue</b> execution, only show the error;
  70. * <b>stop</b> execution and commit transaction;
  71. * and <b>abort</b> execution and transaction and fail task.</p>
  72. *
  73. * @since Ant 1.2
  74. *
  75. * @ant.task name="sql" category="database"
  76. */
  77. public class SQLExec extends JDBCTask {
  78. /**
  79. * delimiters we support, "normal" and "row"
  80. */
  81. public static class DelimiterType extends EnumeratedAttribute {
  82. /** The enumerated strings */
  83. public static final String NORMAL = "normal", ROW = "row";
  84. /** @return the enumerated strings */
  85. public String[] getValues() {
  86. return new String[] {NORMAL, ROW};
  87. }
  88. }
  89. private int goodSql = 0;
  90. private int totalSql = 0;
  91. /**
  92. * Database connection
  93. */
  94. private Connection conn = null;
  95. /**
  96. * files to load
  97. */
  98. private Union resources;
  99. /**
  100. * SQL statement
  101. */
  102. private Statement statement = null;
  103. /**
  104. * SQL input file
  105. */
  106. private File srcFile = null;
  107. /**
  108. * SQL input command
  109. */
  110. private String sqlCommand = "";
  111. /**
  112. * SQL transactions to perform
  113. */
  114. private Vector transactions = new Vector();
  115. /**
  116. * SQL Statement delimiter
  117. */
  118. private String delimiter = ";";
  119. /**
  120. * The delimiter type indicating whether the delimiter will
  121. * only be recognized on a line by itself
  122. */
  123. private String delimiterType = DelimiterType.NORMAL;
  124. /**
  125. * Print SQL results.
  126. */
  127. private boolean print = false;
  128. /**
  129. * Print header columns.
  130. */
  131. private boolean showheaders = true;
  132. /**
  133. * Print SQL stats (rows affected)
  134. */
  135. private boolean showtrailers = true;
  136. /**
  137. * Results Output file.
  138. */
  139. private File output = null;
  140. /**
  141. * Action to perform if an error is found
  142. */
  143. private String onError = "abort";
  144. /**
  145. * Encoding to use when reading SQL statements from a file
  146. */
  147. private String encoding = null;
  148. /**
  149. * Append to an existing file or overwrite it?
  150. */
  151. private boolean append = false;
  152. /**
  153. * Keep the format of a sql block?
  154. */
  155. private boolean keepformat = false;
  156. /**
  157. * Argument to Statement.setEscapeProcessing
  158. *
  159. * @since Ant 1.6
  160. */
  161. private boolean escapeProcessing = true;
  162. /**
  163. * should properties be expanded in text?
  164. * false for backwards compatibility
  165. *
  166. * @since Ant 1.7
  167. */
  168. private boolean expandProperties = true;
  169. /**
  170. * should we print raw BLOB data?
  171. * @since Ant 1.7.1
  172. */
  173. private boolean rawBlobs;
  174. /**
  175. * delimers must match in case and whitespace is significant.
  176. * @since Ant 1.8.0
  177. */
  178. private boolean strictDelimiterMatching = true;
  179. /**
  180. * whether to show SQLWarnings as WARN messages.
  181. * @since Ant 1.8.0
  182. */
  183. private boolean showWarnings = false;
  184. /**
  185. * The column separator used when printing the results.
  186. *
  187. * <p>Defaults to ","</p>
  188. *
  189. * @since Ant 1.8.0
  190. */
  191. private String csvColumnSep = ",";
  192. /**
  193. * The character used to quote column values.
  194. *
  195. * <p>If set, columns that contain either the column separator or
  196. * the quote character itself will be surrounded by the quote
  197. * character. The quote character itself will be doubled if it
  198. * appears inside of the column's value.</p>
  199. *
  200. * <p>If this value is not set (the default), no column values
  201. * will be quoted, not even if they contain the column
  202. * separator.</p>
  203. *
  204. * <p><b>Note:<b> BLOB values will never be quoted.</p>
  205. *
  206. * <p>Defaults to "not set"</p>
  207. *
  208. * @since Ant 1.8.0
  209. */
  210. private String csvQuoteChar = null;
  211. /**
  212. * Whether a warning is an error - in which case onError aplies.
  213. * @since Ant 1.8.0
  214. */
  215. private boolean treatWarningsAsErrors = false;
  216. /**
  217. * Set the name of the SQL file to be run.
  218. * Required unless statements are enclosed in the build file
  219. * @param srcFile the file containing the SQL command.
  220. */
  221. public void setSrc(File srcFile) {
  222. this.srcFile = srcFile;
  223. }
  224. /**
  225. * Enable property expansion inside nested text
  226. *
  227. * @param expandProperties if true expand properties.
  228. * @since Ant 1.7
  229. */
  230. public void setExpandProperties(boolean expandProperties) {
  231. this.expandProperties = expandProperties;
  232. }
  233. /**
  234. * is property expansion inside inline text enabled?
  235. *
  236. * @return true if properties are to be expanded.
  237. * @since Ant 1.7
  238. */
  239. public boolean getExpandProperties() {
  240. return expandProperties;
  241. }
  242. /**
  243. * Set an inline SQL command to execute.
  244. * NB: Properties are not expanded in this text unless {@link #expandProperties}
  245. * is set.
  246. * @param sql an inline string containing the SQL command.
  247. */
  248. public void addText(String sql) {
  249. //there is no need to expand properties here as that happens when Transaction.addText is
  250. //called; to do so here would be an error.
  251. this.sqlCommand += sql;
  252. }
  253. /**
  254. * Adds a set of files (nested fileset attribute).
  255. * @param set a set of files contains SQL commands, each File is run in
  256. * a separate transaction.
  257. */
  258. public void addFileset(FileSet set) {
  259. add(set);
  260. }
  261. /**
  262. * Adds a collection of resources (nested element).
  263. * @param rc a collection of resources containing SQL commands,
  264. * each resource is run in a separate transaction.
  265. * @since Ant 1.7
  266. */
  267. public void add(ResourceCollection rc) {
  268. if (rc == null) {
  269. throw new BuildException("Cannot add null ResourceCollection");
  270. }
  271. synchronized (this) {
  272. if (resources == null) {
  273. resources = new Union();
  274. }
  275. }
  276. resources.add(rc);
  277. }
  278. /**
  279. * Add a SQL transaction to execute
  280. * @return a Transaction to be configured.
  281. */
  282. public Transaction createTransaction() {
  283. Transaction t = new Transaction();
  284. transactions.addElement(t);
  285. return t;
  286. }
  287. /**
  288. * Set the file encoding to use on the SQL files read in
  289. *
  290. * @param encoding the encoding to use on the files
  291. */
  292. public void setEncoding(String encoding) {
  293. this.encoding = encoding;
  294. }
  295. /**
  296. * Set the delimiter that separates SQL statements. Defaults to &quot;;&quot;;
  297. * optional
  298. *
  299. * <p>For example, set this to "go" and delimitertype to "ROW" for
  300. * Sybase ASE or MS SQL Server.</p>
  301. * @param delimiter the separator.
  302. */
  303. public void setDelimiter(String delimiter) {
  304. this.delimiter = delimiter;
  305. }
  306. /**
  307. * Set the delimiter type: "normal" or "row" (default "normal").
  308. *
  309. * <p>The delimiter type takes two values - normal and row. Normal
  310. * means that any occurrence of the delimiter terminate the SQL
  311. * command whereas with row, only a line containing just the
  312. * delimiter is recognized as the end of the command.</p>
  313. * @param delimiterType the type of delimiter - "normal" or "row".
  314. */
  315. public void setDelimiterType(DelimiterType delimiterType) {
  316. this.delimiterType = delimiterType.getValue();
  317. }
  318. /**
  319. * Print result sets from the statements;
  320. * optional, default false
  321. * @param print if true print result sets.
  322. */
  323. public void setPrint(boolean print) {
  324. this.print = print;
  325. }
  326. /**
  327. * Print headers for result sets from the
  328. * statements; optional, default true.
  329. * @param showheaders if true print headers of result sets.
  330. */
  331. public void setShowheaders(boolean showheaders) {
  332. this.showheaders = showheaders;
  333. }
  334. /**
  335. * Print trailing info (rows affected) for the SQL
  336. * Addresses Bug/Request #27446
  337. * @param showtrailers if true prints the SQL rows affected
  338. * @since Ant 1.7
  339. */
  340. public void setShowtrailers(boolean showtrailers) {
  341. this.showtrailers = showtrailers;
  342. }
  343. /**
  344. * Set the output file;
  345. * optional, defaults to the Ant log.
  346. * @param output the output file to use for logging messages.
  347. */
  348. public void setOutput(File output) {
  349. this.output = output;
  350. }
  351. /**
  352. * whether output should be appended to or overwrite
  353. * an existing file. Defaults to false.
  354. *
  355. * @since Ant 1.5
  356. * @param append if true append to an existing file.
  357. */
  358. public void setAppend(boolean append) {
  359. this.append = append;
  360. }
  361. /**
  362. * Action to perform when statement fails: continue, stop, or abort
  363. * optional; default &quot;abort&quot;
  364. * @param action the action to perform on statement failure.
  365. */
  366. public void setOnerror(OnError action) {
  367. this.onError = action.getValue();
  368. }
  369. /**
  370. * whether or not format should be preserved.
  371. * Defaults to false.
  372. *
  373. * @param keepformat The keepformat to set
  374. */
  375. public void setKeepformat(boolean keepformat) {
  376. this.keepformat = keepformat;
  377. }
  378. /**
  379. * Set escape processing for statements.
  380. * @param enable if true enable escape processing, default is true.
  381. * @since Ant 1.6
  382. */
  383. public void setEscapeProcessing(boolean enable) {
  384. escapeProcessing = enable;
  385. }
  386. /**
  387. * Set whether to print raw BLOBs rather than their string (hex) representations.
  388. * @param rawBlobs whether to print raw BLOBs.
  389. * @since Ant 1.7.1
  390. */
  391. public void setRawBlobs(boolean rawBlobs) {
  392. this.rawBlobs = rawBlobs;
  393. }
  394. /**
  395. * If false, delimiters will be searched for in a case-insesitive
  396. * manner (i.e. delimer="go" matches "GO") and surrounding
  397. * whitespace will be ignored (delimter="go" matches "GO ").
  398. * @since Ant 1.8.0
  399. */
  400. public void setStrictDelimiterMatching(boolean b) {
  401. strictDelimiterMatching = b;
  402. }
  403. /**
  404. * whether to show SQLWarnings as WARN messages.
  405. * @since Ant 1.8.0
  406. */
  407. public void setShowWarnings(boolean b) {
  408. showWarnings = b;
  409. }
  410. /**
  411. * Whether a warning is an error - in which case onError aplies.
  412. * @since Ant 1.8.0
  413. */
  414. public void setTreatWarningsAsErrors(boolean b) {
  415. treatWarningsAsErrors = b;
  416. }
  417. /**
  418. * The column separator used when printing the results.
  419. *
  420. * <p>Defaults to ","</p>
  421. *
  422. * @since Ant 1.8.0
  423. */
  424. public void setCsvColumnSeparator(String s) {
  425. csvColumnSep = s;
  426. }
  427. /**
  428. * The character used to quote column values.
  429. *
  430. * <p>If set, columns that contain either the column separator or
  431. * the quote character itself will be surrounded by the quote
  432. * character. The quote character itself will be doubled if it
  433. * appears inside of the column's value.</p>
  434. *
  435. * <p>If this value is not set (the default), no column values
  436. * will be quoted, not even if they contain the column
  437. * separator.</p>
  438. *
  439. * <p><b>Note:<b> BLOB values will never be quoted.</p>
  440. *
  441. * <p>Defaults to "not set"</p>
  442. *
  443. * @since Ant 1.8.0
  444. */
  445. public void setCsvQuoteCharacter(String s) {
  446. if (s != null && s.length() > 1) {
  447. throw new BuildException("The quote character must be a single"
  448. + " character.");
  449. }
  450. csvQuoteChar = s;
  451. }
  452. /**
  453. * Load the sql file and then execute it
  454. * @throws BuildException on error.
  455. */
  456. public void execute() throws BuildException {
  457. Vector savedTransaction = (Vector) transactions.clone();
  458. String savedSqlCommand = sqlCommand;
  459. sqlCommand = sqlCommand.trim();
  460. try {
  461. if (srcFile == null && sqlCommand.length() == 0 && resources == null) {
  462. if (transactions.size() == 0) {
  463. throw new BuildException("Source file or resource collection, "
  464. + "transactions or sql statement "
  465. + "must be set!", getLocation());
  466. }
  467. }
  468. if (srcFile != null && !srcFile.isFile()) {
  469. throw new BuildException("Source file " + srcFile
  470. + " is not a file!", getLocation());
  471. }
  472. if (resources != null) {
  473. // deal with the resources
  474. Iterator iter = resources.iterator();
  475. while (iter.hasNext()) {
  476. Resource r = (Resource) iter.next();
  477. // Make a transaction for each resource
  478. Transaction t = createTransaction();
  479. t.setSrcResource(r);
  480. }
  481. }
  482. // Make a transaction group for the outer command
  483. Transaction t = createTransaction();
  484. t.setSrc(srcFile);
  485. t.addText(sqlCommand);
  486. if (getConnection() == null) {
  487. // not a valid rdbms
  488. return;
  489. }
  490. try {
  491. PrintStream out = System.out;
  492. try {
  493. if (output != null) {
  494. log("Opening PrintStream to output file " + output, Project.MSG_VERBOSE);
  495. out = new PrintStream(new BufferedOutputStream(
  496. new FileOutputStream(output.getAbsolutePath(), append)));
  497. }
  498. // Process all transactions
  499. for (Enumeration e = transactions.elements();
  500. e.hasMoreElements();) {
  501. ((Transaction) e.nextElement()).runTransaction(out);
  502. if (!isAutocommit()) {
  503. log("Committing transaction", Project.MSG_VERBOSE);
  504. getConnection().commit();
  505. }
  506. }
  507. } finally {
  508. FileUtils.close(out);
  509. }
  510. } catch (IOException e) {
  511. closeQuietly();
  512. if (onError.equals("abort")) {
  513. throw new BuildException(e, getLocation());
  514. }
  515. } catch (SQLException e) {
  516. closeQuietly();
  517. if (onError.equals("abort")) {
  518. throw new BuildException(e, getLocation());
  519. }
  520. } finally {
  521. try {
  522. if (getStatement() != null) {
  523. getStatement().close();
  524. }
  525. } catch (SQLException ex) {
  526. // ignore
  527. }
  528. try {
  529. if (getConnection() != null) {
  530. getConnection().close();
  531. }
  532. } catch (SQLException ex) {
  533. // ignore
  534. }
  535. }
  536. log(goodSql + " of " + totalSql + " SQL statements executed successfully");
  537. } finally {
  538. transactions = savedTransaction;
  539. sqlCommand = savedSqlCommand;
  540. }
  541. }
  542. /**
  543. * read in lines and execute them
  544. * @param reader the reader contains sql lines.
  545. * @param out the place to output results.
  546. * @throws SQLException on sql problems
  547. * @throws IOException on io problems
  548. */
  549. protected void runStatements(Reader reader, PrintStream out)
  550. throws SQLException, IOException {
  551. StringBuffer sql = new StringBuffer();
  552. String line;
  553. BufferedReader in = new BufferedReader(reader);
  554. while ((line = in.readLine()) != null) {
  555. if (!keepformat) {
  556. line = line.trim();
  557. }
  558. if (expandProperties) {
  559. line = getProject().replaceProperties(line);
  560. }
  561. if (!keepformat) {
  562. if (line.startsWith("//")) {
  563. continue;
  564. }
  565. if (line.startsWith("--")) {
  566. continue;
  567. }
  568. StringTokenizer st = new StringTokenizer(line);
  569. if (st.hasMoreTokens()) {
  570. String token = st.nextToken();
  571. if ("REM".equalsIgnoreCase(token)) {
  572. continue;
  573. }
  574. }
  575. }
  576. sql.append(keepformat ? "\n" : " ").append(line);
  577. // SQL defines "--" as a comment to EOL
  578. // and in Oracle it may contain a hint
  579. // so we cannot just remove it, instead we must end it
  580. if (!keepformat && line.indexOf("--") >= 0) {
  581. sql.append("\n");
  582. }
  583. int lastDelimPos = lastDelimiterPosition(sql, line);
  584. if (lastDelimPos > -1) {
  585. execSQL(sql.substring(0, lastDelimPos), out);
  586. sql.replace(0, sql.length(), "");
  587. }
  588. }
  589. // Catch any statements not followed by ;
  590. if (sql.length() > 0) {
  591. execSQL(sql.toString(), out);
  592. }
  593. }
  594. /**
  595. * Exec the sql statement.
  596. * @param sql the SQL statement to execute
  597. * @param out the place to put output
  598. * @throws SQLException on SQL problems
  599. */
  600. protected void execSQL(String sql, PrintStream out) throws SQLException {
  601. // Check and ignore empty statements
  602. if ("".equals(sql.trim())) {
  603. return;
  604. }
  605. ResultSet resultSet = null;
  606. try {
  607. totalSql++;
  608. log("SQL: " + sql, Project.MSG_VERBOSE);
  609. boolean ret;
  610. int updateCount = 0, updateCountTotal = 0;
  611. ret = getStatement().execute(sql);
  612. updateCount = getStatement().getUpdateCount();
  613. do {
  614. if (updateCount != -1) {
  615. updateCountTotal += updateCount;
  616. }
  617. if (ret) {
  618. resultSet = getStatement().getResultSet();
  619. printWarnings(resultSet.getWarnings(), false);
  620. resultSet.clearWarnings();
  621. if (print) {
  622. printResults(resultSet, out);
  623. }
  624. }
  625. ret = getStatement().getMoreResults();
  626. updateCount = getStatement().getUpdateCount();
  627. } while (ret || updateCount != -1);
  628. printWarnings(getStatement().getWarnings(), false);
  629. getStatement().clearWarnings();
  630. log(updateCountTotal + " rows affected", Project.MSG_VERBOSE);
  631. if (print && showtrailers) {
  632. out.println(updateCountTotal + " rows affected");
  633. }
  634. SQLWarning warning = getConnection().getWarnings();
  635. printWarnings(warning, true);
  636. getConnection().clearWarnings();
  637. goodSql++;
  638. } catch (SQLException e) {
  639. log("Failed to execute: " + sql, Project.MSG_ERR);
  640. if (!onError.equals("abort")) {
  641. log(e.toString(), Project.MSG_ERR);
  642. }
  643. if (!onError.equals("continue")) {
  644. throw e;
  645. }
  646. } finally {
  647. if (resultSet != null) {
  648. try {
  649. resultSet.close();
  650. } catch (SQLException e) {
  651. //ignore
  652. }
  653. }
  654. }
  655. }
  656. /**
  657. * print any results in the statement
  658. * @deprecated since 1.6.x.
  659. * Use {@link #printResults(java.sql.ResultSet, java.io.PrintStream)
  660. * the two arg version} instead.
  661. * @param out the place to print results
  662. * @throws SQLException on SQL problems.
  663. */
  664. protected void printResults(PrintStream out) throws SQLException {
  665. ResultSet rs = getStatement().getResultSet();
  666. try {
  667. printResults(rs, out);
  668. } finally {
  669. if (rs != null) {
  670. rs.close();
  671. }
  672. }
  673. }
  674. /**
  675. * print any results in the result set.
  676. * @param rs the resultset to print information about
  677. * @param out the place to print results
  678. * @throws SQLException on SQL problems.
  679. * @since Ant 1.6.3
  680. */
  681. protected void printResults(ResultSet rs, PrintStream out) throws SQLException {
  682. if (rs != null) {
  683. log("Processing new result set.", Project.MSG_VERBOSE);
  684. ResultSetMetaData md = rs.getMetaData();
  685. int columnCount = md.getColumnCount();
  686. if (columnCount > 0) {
  687. if (showheaders) {
  688. out.print(md.getColumnName(1));
  689. for (int col = 2; col <= columnCount; col++) {
  690. out.print(csvColumnSep);
  691. out.print(maybeQuote(md.getColumnName(col)));
  692. }
  693. out.println();
  694. }
  695. while (rs.next()) {
  696. printValue(rs, 1, out);
  697. for (int col = 2; col <= columnCount; col++) {
  698. out.print(csvColumnSep);
  699. printValue(rs, col, out);
  700. }
  701. out.println();
  702. printWarnings(rs.getWarnings(), false);
  703. }
  704. }
  705. }
  706. out.println();
  707. }
  708. private void printValue(ResultSet rs, int col, PrintStream out)
  709. throws SQLException {
  710. if (rawBlobs && rs.getMetaData().getColumnType(col) == Types.BLOB) {
  711. new StreamPumper(rs.getBlob(col).getBinaryStream(), out).run();
  712. } else {
  713. out.print(maybeQuote(rs.getString(col)));
  714. }
  715. }
  716. private String maybeQuote(String s) {
  717. if (csvQuoteChar == null || s == null
  718. || (s.indexOf(csvColumnSep) == -1 && s.indexOf(csvQuoteChar) == -1)
  719. ) {
  720. return s;
  721. }
  722. StringBuffer sb = new StringBuffer(csvQuoteChar);
  723. int len = s.length();
  724. char q = csvQuoteChar.charAt(0);
  725. for (int i = 0; i < len; i++) {
  726. char c = s.charAt(i);
  727. if (c == q) {
  728. sb.append(q);
  729. }
  730. sb.append(c);
  731. }
  732. return sb.append(csvQuoteChar).toString();
  733. }
  734. /*
  735. * Closes an unused connection after an error and doesn't rethrow
  736. * a possible SQLException
  737. * @since Ant 1.7
  738. */
  739. private void closeQuietly() {
  740. if (!isAutocommit() && getConnection() != null && onError.equals("abort")) {
  741. try {
  742. getConnection().rollback();
  743. } catch (SQLException ex) {
  744. // ignore
  745. }
  746. }
  747. }
  748. /**
  749. * Caches the connection returned by the base class's getConnection method.
  750. *
  751. * <p>Subclasses that need to provide a different connection than
  752. * the base class would, should override this method but keep in
  753. * mind that this class expects to get the same connection
  754. * instance on consecutive calls.</p>
  755. *
  756. * <p>returns null if the connection does not connect to the
  757. * expected RDBMS.</p>
  758. */
  759. protected Connection getConnection() {
  760. if (conn == null) {
  761. conn = super.getConnection();
  762. if (!isValidRdbms(conn)) {
  763. conn = null;
  764. }
  765. }
  766. return conn;
  767. }
  768. /**
  769. * Creates and configures a Statement instance which is then
  770. * cached for subsequent calls.
  771. *
  772. * <p>Subclasses that want to provide different Statement
  773. * instances, should override this method but keep in mind that
  774. * this class expects to get the same connection instance on
  775. * consecutive calls.</p>
  776. */
  777. protected Statement getStatement() throws SQLException {
  778. if (statement == null) {
  779. statement = getConnection().createStatement();
  780. statement.setEscapeProcessing(escapeProcessing);
  781. }
  782. return statement;
  783. }
  784. /**
  785. * The action a task should perform on an error,
  786. * one of "continue", "stop" and "abort"
  787. */
  788. public static class OnError extends EnumeratedAttribute {
  789. /** @return the enumerated values */
  790. public String[] getValues() {
  791. return new String[] {"continue", "stop", "abort"};
  792. }
  793. }
  794. /**
  795. * Contains the definition of a new transaction element.
  796. * Transactions allow several files or blocks of statements
  797. * to be executed using the same JDBC connection and commit
  798. * operation in between.
  799. */
  800. public class Transaction {
  801. private Resource tSrcResource = null;
  802. private String tSqlCommand = "";
  803. /**
  804. * Set the source file attribute.
  805. * @param src the source file
  806. */
  807. public void setSrc(File src) {
  808. //there are places (in this file, and perhaps elsewhere, where it is assumed
  809. //that null is an acceptable parameter.
  810. if (src != null) {
  811. setSrcResource(new FileResource(src));
  812. }
  813. }
  814. /**
  815. * Set the source resource attribute.
  816. * @param src the source file
  817. * @since Ant 1.7
  818. */
  819. public void setSrcResource(Resource src) {
  820. if (tSrcResource != null) {
  821. throw new BuildException("only one resource per transaction");
  822. }
  823. tSrcResource = src;
  824. }
  825. /**
  826. * Set inline text
  827. * @param sql the inline text
  828. */
  829. public void addText(String sql) {
  830. if (sql != null) {
  831. this.tSqlCommand += sql;
  832. }
  833. }
  834. /**
  835. * Set the source resource.
  836. * @param a the source resource collection.
  837. * @since Ant 1.7
  838. */
  839. public void addConfigured(ResourceCollection a) {
  840. if (a.size() != 1) {
  841. throw new BuildException("only single argument resource "
  842. + "collections are supported.");
  843. }
  844. setSrcResource((Resource) a.iterator().next());
  845. }
  846. /**
  847. *
  848. */
  849. private void runTransaction(PrintStream out)
  850. throws IOException, SQLException {
  851. if (tSqlCommand.length() != 0) {
  852. log("Executing commands", Project.MSG_INFO);
  853. runStatements(new StringReader(tSqlCommand), out);
  854. }
  855. if (tSrcResource != null) {
  856. log("Executing resource: " + tSrcResource.toString(),
  857. Project.MSG_INFO);
  858. InputStream is = null;
  859. Reader reader = null;
  860. try {
  861. is = tSrcResource.getInputStream();
  862. reader = (encoding == null) ? new InputStreamReader(is)
  863. : new InputStreamReader(is, encoding);
  864. runStatements(reader, out);
  865. } finally {
  866. FileUtils.close(is);
  867. FileUtils.close(reader);
  868. }
  869. }
  870. }
  871. }
  872. public int lastDelimiterPosition(StringBuffer buf, String currentLine) {
  873. if (strictDelimiterMatching) {
  874. if ((delimiterType.equals(DelimiterType.NORMAL)
  875. && StringUtils.endsWith(buf, delimiter)) ||
  876. (delimiterType.equals(DelimiterType.ROW)
  877. && currentLine.equals(delimiter))) {
  878. return buf.length() - delimiter.length();
  879. }
  880. // no match
  881. return -1;
  882. } else {
  883. String d = delimiter.trim().toLowerCase(Locale.US);
  884. if (delimiterType.equals(DelimiterType.NORMAL)) {
  885. // still trying to avoid wasteful copying, see
  886. // StringUtils.endsWith
  887. int endIndex = delimiter.length() - 1;
  888. int bufferIndex = buf.length() - 1;
  889. while (bufferIndex >= 0
  890. && Character.isWhitespace(buf.charAt(bufferIndex))) {
  891. --bufferIndex;
  892. }
  893. if (bufferIndex < endIndex) {
  894. return -1;
  895. }
  896. while (endIndex >= 0) {
  897. if (buf.substring(bufferIndex, bufferIndex + 1)
  898. .toLowerCase(Locale.US).charAt(0)
  899. != d.charAt(endIndex)) {
  900. return -1;
  901. }
  902. bufferIndex--;
  903. endIndex--;
  904. }
  905. return bufferIndex + 1;
  906. } else {
  907. return currentLine.trim().toLowerCase(Locale.US).equals(d)
  908. ? buf.length() - currentLine.length() : -1;
  909. }
  910. }
  911. }
  912. private void printWarnings(SQLWarning warning, boolean force)
  913. throws SQLException {
  914. SQLWarning initialWarning = warning;
  915. if (showWarnings || force) {
  916. while (warning != null) {
  917. log(warning + " sql warning",
  918. showWarnings ? Project.MSG_WARN : Project.MSG_VERBOSE);
  919. warning = warning.getNextWarning();
  920. }
  921. }
  922. if (treatWarningsAsErrors && initialWarning != null) {
  923. throw initialWarning;
  924. }
  925. }
  926. }