My favorites | Sign in
Project Home Downloads Issues Source
New issue   Search
for
  Advanced search   Search tips   Subscriptions

Issue 519 attachment: ScriptRunner.java (8.4 KB)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package org.apache.ibatis.jdbc;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.*;

import org.apache.ibatis.jdbc.RuntimeSqlException;

import org.apache.ibatis.jdbc.PreparedStatementArguments;

public class ScriptRunner {

private static final String LINE_SEPARATOR = System.getProperty("line.separator","\n");

private static final String DEFAULT_DELIMITER = ";";

private Connection connection;

private boolean stopOnError;
private boolean autoCommit;
private boolean sendFullScript;

private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);

private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
private String characterSetName;

public ScriptRunner(Connection connection) {
this.connection = connection;
}

public void setCharacterSetName(String characterSetName) {
this.characterSetName = characterSetName;
}

public void setStopOnError(boolean stopOnError) {
this.stopOnError = stopOnError;
}

public void setAutoCommit(boolean autoCommit) {
this.autoCommit = autoCommit;
}

public void setSendFullScript(boolean sendFullScript) {
this.sendFullScript = sendFullScript;
}

public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}

public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}

public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}

public void setFullLineDelimiter(boolean fullLineDelimiter) {
this.fullLineDelimiter = fullLineDelimiter;
}

public void runScript(Reader reader) {
setAutoCommit();

try {
if (sendFullScript) {
executeFullScript(reader);
} else {
executeLineByLine(reader);
}
} finally {
rollbackConnection();
}
}

private void executeFullScript(Reader reader) {
StringBuffer script = new StringBuffer();
try {
BufferedReader lineReader = new BufferedReader(reader);
String line;
while ((line = lineReader.readLine()) != null) {
script.append(line);
script.append(LINE_SEPARATOR);
}
executeStatement(script.toString());
commitConnection();
} catch (Exception e) {
String message = "Error executing: " + script + ". Cause: " + e;
printlnError(message);
throw new RuntimeSqlException(message, e);
}
}

private void executeLineByLine(Reader reader) {
StringBuffer command = new StringBuffer();
try {
BufferedReader lineReader = new BufferedReader(reader);
String line;
while ((line = lineReader.readLine()) != null) {
command = handleLine(command, line);
}
commitConnection();
checkForMissingLineTerminator(command);
} catch (Exception e) {
String message = "Error executing: " + command + ". Cause: " + e;
printlnError(message);
throw new RuntimeSqlException(message, e);
}
}

public void closeConnection() {
try {
connection.close();
} catch (Exception e) {
// ignore
}
}

private void setAutoCommit() {
try {
if (autoCommit != connection.getAutoCommit()) {
connection.setAutoCommit(autoCommit);
}
} catch (Throwable t) {
throw new RuntimeSqlException("Could not set AutoCommit to " + autoCommit + ". Cause: " + t, t);
}
}

private void commitConnection() {
try {
if (!connection.getAutoCommit()) {
connection.commit();
}
} catch (Throwable t) {
throw new RuntimeSqlException("Could not commit transaction. Cause: " + t, t);
}
}

private void rollbackConnection() {
try {
if (!connection.getAutoCommit()) {
connection.rollback();
}
} catch (Throwable t) {
// ignore
}
}

private void checkForMissingLineTerminator(StringBuffer command) {
if (command != null && command.toString().trim().length() > 0) {
throw new RuntimeSqlException("Line missing end-of-line terminator (" + delimiter + ") => " + command);
}
}

private StringBuffer handleLine(StringBuffer command, String line) throws SQLException, UnsupportedEncodingException {
String trimmedLine = line.trim();
if (lineIsComment(trimmedLine)) {
println(trimmedLine);
} else if (commandReadyToExecute(trimmedLine)) {
command.append(line.substring(0, line.lastIndexOf(delimiter)));
command.append(LINE_SEPARATOR);
println(command);
executeStatement(command.toString());
command.setLength(0);
} else if (trimmedLine.length() > 0) {
command.append(line);
command.append(LINE_SEPARATOR);
}
return command;
}

private boolean lineIsComment(String trimmedLine) {
return trimmedLine.startsWith("//") || trimmedLine.startsWith("--");
}

private boolean commandReadyToExecute(String trimmedLine) {
return !fullLineDelimiter && trimmedLine.endsWith(delimiter)
|| fullLineDelimiter && trimmedLine.equals(delimiter);
}

private void executeStatement(String command) throws SQLException, UnsupportedEncodingException {
if(characterSetName != null){
command = new String(command.getBytes(), characterSetName);
}
PreparedStatementArguments.QueryValue queryObj = PreparedStatementArguments.getInstance().getQueryParams(command);
if (queryObj != null && queryObj.params.length > 0){
executePreparedStatement(queryObj.query, queryObj.params);
}
else
{
boolean hasResults = false;
Statement statement = connection.createStatement();
if (stopOnError) {
hasResults = statement.execute(command);
} else {
try {
hasResults = statement.execute(command);
} catch (SQLException e) {
String message = "Error executing: " + command + ". Cause: " + e;
printlnError(message);
}
}
printResults(statement, hasResults);
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in some connection pools
}
}
}

/**
* my changes:
* Caters for execution of oracle clob and invalid character issues in sql
* also allows query params to be read from external files
* @see PreparedStatementArguments for futher detail
* @param command
* @param args
* @throws SQLException
*/
private void executePreparedStatement(String command, final String[] args) throws SQLException{
final Statement statement = null;
try {
final PreparedStatement ps = connection.prepareStatement(command);
for (int i = 0; i < args.length; i++) {
ps.setString(i + 1, args[i]);
}
final int result = ps.executeUpdate();
ps.close();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (final SQLException e) {
throw e;
}
}


}

private void printResults(Statement statement, boolean hasResults) {
try {
if (hasResults) {
ResultSet rs = statement.getResultSet();
if (rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i + 1);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i + 1);
print(value + "\t");
}
println("");
}
}
}
} catch (SQLException e) {
printlnError("Error printing results: " + e.getMessage());
}
}

private void print(Object o) {
if (logWriter != null) {
logWriter.print(o);
logWriter.flush();
}
}

private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
logWriter.flush();
}
}

private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
errorLogWriter.flush();
}
}
}
Powered by Google Project Hosting