1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package net.sourceforge.addam.ddlrun.runners;
23
24 import net.sourceforge.addam.ddlrun.grammars.ScriptGrammar;
25 import net.sourceforge.addam.ddlrun.utils.ResourceReader;
26 import net.sourceforge.addam.ddlrun.utils.ResourceReaderFactory;
27
28 /**
29 * Used to run a single SQL script.
30 *
31 * @author TIM3
32 * @since Mar 5, 2005
33 */
34 public class JDBCScriptRunner implements Runner {
35
36 /**
37 * Constructs a JDBCScriptRunner.
38 *
39 * @param readerFactory used to locate and read scripts
40 * @param grammar used to parse the SQL file
41 * @param statementRunner used to run individual statements
42 */
43 public JDBCScriptRunner(ResourceReaderFactory readerFactory, ScriptGrammar grammar,
44 Runner statementRunner) {
45 this.statementRunner = statementRunner;
46 this.readerFactory = readerFactory;
47 this.grammar = grammar;
48 }
49
50
51 public void run(String resource) throws Exception {
52 ResourceReader reader = readerFactory.getReader(resource);
53 StringBuffer buf = new StringBuffer();
54 boolean simpleStatement = false;
55 boolean complexStatement = false;
56 for (String line = reader.readLine(); line != null; line = reader.readLine()) {
57 if (simpleStatement) {
58
59 if (buf.length() > 0) {
60 buf.append("\n");
61 }
62 buf.append(line);
63
64 if (grammar.hasSimpleStatementTerminator(buf.toString())) {
65 String bufferString = grammar.removeSimpleStatementTerminator(buf.toString().trim());
66 runStatement(bufferString);
67 simpleStatement = false;
68 buf.setLength(0);
69 continue;
70 }
71 } else if (complexStatement) {
72
73 if (buf.length() > 0) {
74 buf.append("\n");
75 }
76 buf.append(line);
77 if (grammar.hasComplexStatementTerminator(buf.toString())) {
78 String bufferString = grammar.removeComplexStatementTerminator(buf.toString().trim());
79 runStatement(bufferString);
80 simpleStatement = false;
81 complexStatement = false;
82 buf.setLength(0);
83 }
84 } else {
85
86
87 if (grammar.shouldIgnore(line)) {
88
89 continue;
90 }
91
92
93 if (grammar.beginsComplexStatement(line)) {
94 complexStatement = true;
95 buf.append(line);
96 continue;
97 }
98
99
100 if (grammar.hasSimpleStatementTerminator(line)) {
101 line = grammar.removeSimpleStatementTerminator(line);
102 runStatement(line);
103 continue;
104 }
105
106
107 simpleStatement = true;
108 buf.append(line);
109 }
110 }
111 }
112
113 private void runStatement(String statement) throws Exception {
114 try {
115 if (statement.length() > 0) {
116 statementRunner.run(statement);
117 }
118 } catch (Exception e) {
119 System.err.println("failed to execute:\n" + statement);
120 throw e;
121 }
122 }
123
124 private final ResourceReaderFactory readerFactory;
125 private final ScriptGrammar grammar;
126 private final Runner statementRunner;
127 }