ScriptUtils.java 18.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright 2002-2014 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.jdbc.datasource.init;

import java.io.IOException;
import java.io.LineNumberReader;
S
Sam Brannen 已提交
21
import java.sql.Connection;
22
import java.sql.SQLException;
S
Sam Brannen 已提交
23
import java.sql.Statement;
24 25 26 27 28
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
29
import org.springframework.core.io.Resource;
30
import org.springframework.core.io.support.EncodedResource;
S
Sam Brannen 已提交
31
import org.springframework.util.Assert;
32 33 34
import org.springframework.util.StringUtils;

/**
S
Sam Brannen 已提交
35 36 37 38 39 40 41 42 43 44
 * Generic utility methods for working with SQL scripts. Mainly for internal use
 * within the framework.
 *
 * @author Thomas Risberg
 * @author Sam Brannen
 * @author Juergen Hoeller
 * @author Keith Donald
 * @author Dave Syer
 * @author Chris Beams
 * @author Oliver Gierke
45 46 47 48 49
 * @author Chris Baldwin
 * @since 4.0.3
 */
public abstract class ScriptUtils {

S
Sam Brannen 已提交
50 51 52 53 54 55 56
	private static final Log logger = LogFactory.getLog(ScriptUtils.class);

	/**
	 * Default statement separator within SQL scripts.
	 */
	public static final String DEFAULT_STATEMENT_SEPARATOR = ";";

57 58 59 60 61 62 63
	/**
	 * Fallback statement separator within SQL scripts.
	 * <p>Used if neither a custom defined separator nor the
	 * {@link #DEFAULT_STATEMENT_SEPARATOR} is present in a given script.
	 */
	public static final String FALLBACK_STATEMENT_SEPARATOR = "\n";

S
Sam Brannen 已提交
64 65 66
	/**
	 * Default prefix for line comments within SQL scripts.
	 */
67 68
	public static final String DEFAULT_COMMENT_PREFIX = "--";

S
Sam Brannen 已提交
69 70 71
	/**
	 * Default start delimiter for block comments within SQL scripts.
	 */
72
	public static final String DEFAULT_BLOCK_COMMENT_START_DELIMITER = "/*";
S
Sam Brannen 已提交
73 74 75 76

	/**
	 * Default end delimiter for block comments within SQL scripts.
	 */
77 78
	public static final String DEFAULT_BLOCK_COMMENT_END_DELIMITER = "*/";

S
Sam Brannen 已提交
79 80 81 82 83 84 85 86

	/**
	 * Prevent instantiation of this utility class.
	 */
	private ScriptUtils() {
		/* no-op */
	}

87 88
	/**
	 * Split an SQL script into separate statements delimited by the provided
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	 * separator character. Each individual statement will be added to the
	 * provided {@code List}.
	 * <p>Within the script, {@value #DEFAULT_COMMENT_PREFIX} will be used as the
	 * comment prefix; any text beginning with the comment prefix and extending to
	 * the end of the line will be omitted from the output. Similarly,
	 * {@value #DEFAULT_BLOCK_COMMENT_START_DELIMITER} and
	 * {@value #DEFAULT_BLOCK_COMMENT_END_DELIMITER} will be used as the
	 * <em>start</em> and <em>end</em> block comment delimiters: any text enclosed
	 * in a block comment will be omitted from the output. In addition, multiple
	 * adjacent whitespace characters will be collapsed into a single space.
	 * @param script the SQL script
	 * @param separator character separating each statement &mdash; typically a ';'
	 * @param statements the list that will contain the individual statements
	 * @see #splitSqlScript(String, String, List)
	 * @see #splitSqlScript(EncodedResource, String, String, String, String, String, List)
	 */
	public static void splitSqlScript(String script, char separator, List<String> statements) throws ScriptException {
		splitSqlScript(script, String.valueOf(separator), statements);
	}

	/**
	 * Split an SQL script into separate statements delimited by the provided
	 * separator string. Each individual statement will be added to the
112
	 * provided {@code List}.
S
Sam Brannen 已提交
113 114 115 116 117 118 119 120
	 * <p>Within the script, {@value #DEFAULT_COMMENT_PREFIX} will be used as the
	 * comment prefix; any text beginning with the comment prefix and extending to
	 * the end of the line will be omitted from the output. Similarly,
	 * {@value #DEFAULT_BLOCK_COMMENT_START_DELIMITER} and
	 * {@value #DEFAULT_BLOCK_COMMENT_END_DELIMITER} will be used as the
	 * <em>start</em> and <em>end</em> block comment delimiters: any text enclosed
	 * in a block comment will be omitted from the output. In addition, multiple
	 * adjacent whitespace characters will be collapsed into a single space.
121
	 * @param script the SQL script
122
	 * @param separator text separating each statement &mdash; typically a ';' or newline character
123
	 * @param statements the list that will contain the individual statements
124
	 * @see #splitSqlScript(String, char, List)
S
Sam Brannen 已提交
125
	 * @see #splitSqlScript(EncodedResource, String, String, String, String, String, List)
126
	 */
127 128 129
	public static void splitSqlScript(String script, String separator, List<String> statements) throws ScriptException {
		splitSqlScript(null, script, separator, DEFAULT_COMMENT_PREFIX, DEFAULT_BLOCK_COMMENT_START_DELIMITER,
			DEFAULT_BLOCK_COMMENT_END_DELIMITER, statements);
130 131 132 133
	}

	/**
	 * Split an SQL script into separate statements delimited by the provided
134
	 * separator string. Each individual statement will be added to the provided
135
	 * {@code List}.
S
Sam Brannen 已提交
136
	 * <p>Within the script, the provided {@code commentPrefix} will be honored:
137
	 * any text beginning with the comment prefix and extending to the end of the
S
Sam Brannen 已提交
138 139 140 141 142 143 144
	 * line will be omitted from the output. Similarly, the provided
	 * {@code blockCommentStartDelimiter} and {@code blockCommentEndDelimiter}
	 * delimiters will be honored: any text enclosed in a block comment will be
	 * omitted from the output. In addition, multiple adjacent whitespace characters
	 * will be collapsed into a single space.
	 * @param resource the resource from which the script was read
	 * @param script the SQL script; never {@code null} or empty
145 146
	 * @param separator text separating each statement &mdash; typically a ';' or
	 * newline character; never {@code null}
S
Sam Brannen 已提交
147 148 149 150 151 152 153
	 * @param commentPrefix the prefix that identifies SQL line comments &mdash;
	 * typically "--"; never {@code null} or empty
	 * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter;
	 * never {@code null} or empty
	 * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter;
	 * never {@code null} or empty
	 * @param statements the list that will contain the individual statements
154
	 */
155
	public static void splitSqlScript(EncodedResource resource, String script, String separator, String commentPrefix,
S
Sam Brannen 已提交
156 157 158 159
			String blockCommentStartDelimiter, String blockCommentEndDelimiter, List<String> statements)
			throws ScriptException {

		Assert.hasText(script, "script must not be null or empty");
160
		Assert.notNull(separator, "separator must not be null");
S
Sam Brannen 已提交
161 162 163 164
		Assert.hasText(commentPrefix, "commentPrefix must not be null or empty");
		Assert.hasText(blockCommentStartDelimiter, "blockCommentStartDelimiter must not be null or empty");
		Assert.hasText(blockCommentEndDelimiter, "blockCommentEndDelimiter must not be null or empty");

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
		StringBuilder sb = new StringBuilder();
		boolean inLiteral = false;
		boolean inEscape = false;
		char[] content = script.toCharArray();
		for (int i = 0; i < script.length(); i++) {
			char c = content[i];
			if (inEscape) {
				inEscape = false;
				sb.append(c);
				continue;
			}
			// MySQL style escapes
			if (c == '\\') {
				inEscape = true;
				sb.append(c);
				continue;
			}
			if (c == '\'') {
				inLiteral = !inLiteral;
			}
			if (!inLiteral) {
186
				if (script.startsWith(separator, i)) {
187 188 189 190 191
					// we've reached the end of the current statement
					if (sb.length() > 0) {
						statements.add(sb.toString());
						sb = new StringBuilder();
					}
192
					i += separator.length() - 1;
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
					continue;
				}
				else if (script.startsWith(commentPrefix, i)) {
					// skip over any content from the start of the comment to the EOL
					int indexOfNextNewline = script.indexOf("\n", i);
					if (indexOfNextNewline > i) {
						i = indexOfNextNewline;
						continue;
					}
					else {
						// if there's no EOL, we must be at the end
						// of the script, so stop here.
						break;
					}
				}
S
Sam Brannen 已提交
208
				else if (script.startsWith(blockCommentStartDelimiter, i)) {
209
					// skip over any block comments
S
Sam Brannen 已提交
210 211 212
					int indexOfCommentEnd = script.indexOf(blockCommentEndDelimiter, i);
					if (indexOfCommentEnd > i) {
						i = indexOfCommentEnd + blockCommentEndDelimiter.length() - 1;
213 214 215
						continue;
					}
					else {
S
Sam Brannen 已提交
216 217
						throw new ScriptParseException(String.format("Missing block comment end delimiter [%s].",
							blockCommentEndDelimiter), resource);
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
					}
				}
				else if (c == ' ' || c == '\n' || c == '\t') {
					// avoid multiple adjacent whitespace characters
					if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') {
						c = ' ';
					}
					else {
						continue;
					}
				}
			}
			sb.append(c);
		}
		if (StringUtils.hasText(sb)) {
			statements.add(sb.toString());
		}
	}

	/**
S
Sam Brannen 已提交
238 239
	 * Read a script from the given resource, using "{@code --}" as the comment prefix
	 * and "{@code ;}" as the statement separator, and build a String containing the lines.
240 241 242 243
	 * @param resource the {@code EncodedResource} to be read
	 * @return {@code String} containing the script lines
	 * @throws IOException in case of I/O errors
	 */
S
Sam Brannen 已提交
244 245
	static String readScript(EncodedResource resource) throws IOException {
		return readScript(resource, DEFAULT_COMMENT_PREFIX, DEFAULT_STATEMENT_SEPARATOR);
246
	}
S
Sam Brannen 已提交
247

248
	/**
249 250
	 * Read a script from the provided resource, using the supplied comment prefix
	 * and statement separator, and build a {@code String} containing the lines.
251 252 253 254 255
	 * <p>Lines <em>beginning</em> with the comment prefix are excluded from the
	 * results; however, line comments anywhere else &mdash; for example, within
	 * a statement &mdash; will be included in the results.
	 * @param resource the {@code EncodedResource} containing the script
	 * to be processed
S
Sam Brannen 已提交
256 257
	 * @param commentPrefix the prefix that identifies comments in the SQL script &mdash;
	 * typically "--"
258 259 260
	 * @param separator the statement separator in the SQL script &mdash; typically ";"
	 * @return a {@code String} containing the script lines
	 */
S
Sam Brannen 已提交
261 262
	private static String readScript(EncodedResource resource, String commentPrefix, String separator)
			throws IOException {
263 264 265 266 267 268 269 270
		LineNumberReader lnr = new LineNumberReader(resource.getReader());
		try {
			return readScript(lnr, commentPrefix, separator);
		}
		finally {
			lnr.close();
		}
	}
S
Sam Brannen 已提交
271

272 273
	/**
	 * Read a script from the provided {@code LineNumberReader}, using the supplied
S
Sam Brannen 已提交
274 275
	 * comment prefix and statement separator, and build a {@code String} containing
	 * the lines.
276 277 278 279 280
	 * <p>Lines <em>beginning</em> with the comment prefix are excluded from the
	 * results; however, line comments anywhere else &mdash; for example, within
	 * a statement &mdash; will be included in the results.
	 * @param lineNumberReader the {@code LineNumberReader} containing the script
	 * to be processed
S
Sam Brannen 已提交
281 282
	 * @param commentPrefix the prefix that identifies comments in the SQL script &mdash;
	 * typically "--"
283 284 285
	 * @param separator the statement separator in the SQL script &mdash; typically ";"
	 * @return a {@code String} containing the script lines
	 */
S
Sam Brannen 已提交
286 287
	public static String readScript(LineNumberReader lineNumberReader, String commentPrefix, String separator)
			throws IOException {
288 289 290
		String currentStatement = lineNumberReader.readLine();
		StringBuilder scriptBuilder = new StringBuilder();
		while (currentStatement != null) {
291
			if (commentPrefix != null && !currentStatement.startsWith(commentPrefix)) {
292 293 294 295 296 297 298
				if (scriptBuilder.length() > 0) {
					scriptBuilder.append('\n');
				}
				scriptBuilder.append(currentStatement);
			}
			currentStatement = lineNumberReader.readLine();
		}
299
		appendSeparatorToScriptIfNecessary(scriptBuilder, separator);
300 301 302
		return scriptBuilder.toString();
	}

303
	private static void appendSeparatorToScriptIfNecessary(StringBuilder scriptBuilder, String separator) {
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
		if (separator == null) {
			return;
		}
		String trimmed = separator.trim();
		if (trimmed.length() == separator.length()) {
			return;
		}
		// separator ends in whitespace, so we might want to see if the script is trying
		// to end the same way
		if (scriptBuilder.lastIndexOf(trimmed) == scriptBuilder.length() - trimmed.length()) {
			scriptBuilder.append(separator.substring(trimmed.length()));
		}
	}

	/**
	 * Does the provided SQL script contain the specified delimiter?
	 * @param script the SQL script
	 * @param delim String delimiting each statement - typically a ';' character
	 */
	public static boolean containsSqlScriptDelimiters(String script, String delim) {
		boolean inLiteral = false;
		char[] content = script.toCharArray();
		for (int i = 0; i < script.length(); i++) {
			if (content[i] == '\'') {
				inLiteral = !inLiteral;
			}
			if (!inLiteral && script.startsWith(delim, i)) {
				return true;
			}
		}
		return false;
	}

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
	/**
	 * Execute the given SQL script using default settings for separator separators,
	 * comment delimiters, and exception handling flags.
	 * <p>Statement separators and comments will be removed before executing
	 * individual statements within the supplied script.
	 * <p><b>Do not use this method to execute DDL if you expect rollback.</b>
	 * @param connection the JDBC connection to use to execute the script; already
	 * configured and ready to use
	 * @param resource the resource to load the SQL script from; encoded with the
	 * current platform's default encoding
	 * @see #executeSqlScript(Connection, EncodedResource, boolean, boolean, String, String, String, String)
	 * @see #DEFAULT_COMMENT_PREFIX
	 * @see #DEFAULT_STATEMENT_SEPARATOR
	 * @see #DEFAULT_BLOCK_COMMENT_START_DELIMITER
	 * @see #DEFAULT_BLOCK_COMMENT_END_DELIMITER
	 */
	public static void executeSqlScript(Connection connection, Resource resource) throws SQLException, ScriptException {
		executeSqlScript(connection, new EncodedResource(resource));
	}

	/**
	 * Execute the given SQL script using default settings for separator separators,
	 * comment delimiters, and exception handling flags.
	 * <p>Statement separators and comments will be removed before executing
	 * individual statements within the supplied script.
	 * <p><b>Do not use this method to execute DDL if you expect rollback.</b>
	 * @param connection the JDBC connection to use to execute the script; already
	 * configured and ready to use
	 * @param resource the resource (potentially associated with a specific encoding)
	 * to load the SQL script from
	 * @see #executeSqlScript(Connection, EncodedResource, boolean, boolean, String, String, String, String)
	 * @see #DEFAULT_COMMENT_PREFIX
	 * @see #DEFAULT_STATEMENT_SEPARATOR
	 * @see #DEFAULT_BLOCK_COMMENT_START_DELIMITER
	 * @see #DEFAULT_BLOCK_COMMENT_END_DELIMITER
	 */
	public static void executeSqlScript(Connection connection, EncodedResource resource) throws SQLException,
			ScriptException {
		executeSqlScript(connection, resource, false, false, DEFAULT_COMMENT_PREFIX, DEFAULT_STATEMENT_SEPARATOR,
			DEFAULT_BLOCK_COMMENT_START_DELIMITER, DEFAULT_BLOCK_COMMENT_END_DELIMITER);
	}

379 380
	/**
	 * Execute the given SQL script.
S
Sam Brannen 已提交
381 382
	 * <p>Statement separators and comments will be removed before executing
	 * individual statements within the supplied script.
383
	 * <p><b>Do not use this method to execute DDL if you expect rollback.</b>
S
Sam Brannen 已提交
384 385 386 387 388 389 390 391 392 393 394
	 * @param connection the JDBC connection to use to execute the script; already
	 * configured and ready to use
	 * @param resource the resource (potentially associated with a specific encoding)
	 * to load the SQL script from
	 * @param continueOnError whether or not to continue without throwing an exception
	 * in the event of an error
	 * @param ignoreFailedDrops whether or not to continue in the event of specifically
	 * an error on a {@code DROP} statement
	 * @param commentPrefix the prefix that identifies comments in the SQL script &mdash;
	 * typically "--"
	 * @param separator the script statement separator; defaults to
395 396
	 * {@value #DEFAULT_STATEMENT_SEPARATOR} if not specified and falls back to
	 * {@value #FALLBACK_STATEMENT_SEPARATOR} as a last resort
S
Sam Brannen 已提交
397 398 399 400
	 * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter; never
	 * {@code null} or empty
	 * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter; never
	 * {@code null} or empty
401
	 */
S
Sam Brannen 已提交
402 403 404
	public static void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError,
			boolean ignoreFailedDrops, String commentPrefix, String separator, String blockCommentStartDelimiter,
			String blockCommentEndDelimiter) throws SQLException, ScriptException {
405 406 407 408 409 410 411 412 413 414 415 416 417

		if (logger.isInfoEnabled()) {
			logger.info("Executing SQL script from " + resource);
		}
		long startTime = System.currentTimeMillis();
		List<String> statements = new LinkedList<String>();
		String script;
		try {
			script = readScript(resource, commentPrefix, separator);
		}
		catch (IOException ex) {
			throw new CannotReadScriptException(resource, ex);
		}
S
Sam Brannen 已提交
418

419 420
		if (separator == null) {
			separator = DEFAULT_STATEMENT_SEPARATOR;
421 422 423
		}
		if (!containsSqlScriptDelimiters(script, separator)) {
			separator = FALLBACK_STATEMENT_SEPARATOR;
424
		}
S
Sam Brannen 已提交
425 426 427

		splitSqlScript(resource, script, separator, commentPrefix, blockCommentStartDelimiter,
			blockCommentEndDelimiter, statements);
428
		int lineNumber = 0;
S
Sam Brannen 已提交
429 430 431 432 433 434 435
		Statement stmt = connection.createStatement();
		try {
			for (String statement : statements) {
				lineNumber++;
				try {
					stmt.execute(statement);
					int rowsAffected = stmt.getUpdateCount();
436
					if (logger.isDebugEnabled()) {
S
Sam Brannen 已提交
437
						logger.debug(rowsAffected + " returned as updateCount for SQL: " + statement);
438 439
					}
				}
S
Sam Brannen 已提交
440 441 442 443 444 445 446 447 448 449 450
				catch (SQLException ex) {
					boolean dropStatement = StringUtils.startsWithIgnoreCase(statement.trim(), "drop");
					if (continueOnError || (dropStatement && ignoreFailedDrops)) {
						if (logger.isDebugEnabled()) {
							logger.debug("Failed to execute SQL script statement at line " + lineNumber
									+ " of resource " + resource + ": " + statement, ex);
						}
					}
					else {
						throw new ScriptStatementFailedException(statement, lineNumber, resource, ex);
					}
451 452 453
				}
			}
		}
S
Sam Brannen 已提交
454 455 456 457 458 459 460 461 462
		finally {
			try {
				stmt.close();
			}
			catch (Throwable ex) {
				logger.debug("Could not close JDBC Statement", ex);
			}
		}

463 464
		long elapsedTime = System.currentTimeMillis() - startTime;
		if (logger.isInfoEnabled()) {
S
Sam Brannen 已提交
465
			logger.info("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
466 467 468 469
		}
	}

}