Debian Codegraph @

src/main/org/h2/tools/RunScript.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.tools;
7
8 import java.io.BufferedReader;
9 import java.io.File;
10 import java.io.IOException;
11 import java.io.Reader;
12 import java.nio.charset.Charset;
13 import java.nio.charset.StandardCharsets;
14 import java.sql.Connection;
15 import java.sql.ResultSet;
16 import java.sql.SQLException;
17 import java.sql.Statement;
18 import java.util.concurrent.TimeUnit;
19
20 import org.h2.message.DbException;
21 import org.h2.store.fs.FileUtils;
22 import org.h2.util.IOUtils;
23 import org.h2.util.JdbcUtils;
24 import org.h2.util.ScriptReader;
25 import org.h2.util.StringUtils;
26 import org.h2.util.Tool;
27
28 /**
29 * Runs a SQL script against a database.
30 */
31 public class RunScript extends Tool {
32
33 private boolean showResults;
34 private boolean checkResults;
35
36 /**
37 * Options are case sensitive.
38 * <table>
39 * <caption>Supported options</caption>
40 * <tr><td>[-help] or [-?]</td>
41 * <td>Print the list of options</td></tr>
42 * <tr><td>[-url "&lt;url&gt;"]</td>
43 * <td>The database URL (jdbc:...)</td></tr>
44 * <tr><td>[-user &lt;user&gt;]</td>
45 * <td>The user name (default: sa)</td></tr>
46 * <tr><td>[-password &lt;pwd&gt;]</td>
47 * <td>The password</td></tr>
48 * <tr><td>[-script &lt;file&gt;]</td>
49 * <td>The script file to run (default: backup.sql)</td></tr>
50 * <tr><td>[-driver &lt;class&gt;]</td>
51 * <td>The JDBC driver class to use (not required in most cases)</td></tr>
52 * <tr><td>[-showResults]</td>
53 * <td>Show the statements and the results of queries</td></tr>
54 * <tr><td>[-checkResults]</td>
55 * <td>Check if the query results match the expected results</td></tr>
56 * <tr><td>[-continueOnError]</td>
57 * <td>Continue even if the script contains errors</td></tr>
58 * <tr><td>[-options ...]</td>
59 * <td>RUNSCRIPT options (embedded H2; -*Results not supported)</td></tr>
60 * </table>
61 *
62 * @param args the command line arguments
63 * @throws SQLException on failure
64 */
65 public static void main(String... args) throws SQLException {
66 new RunScript().runTool(args);
67 }
68
69 /**
70 * Executes the contents of a SQL script file against a database.
71 * This tool is usually used to create a database from script.
72 * It can also be used to analyze performance problems by running
73 * the tool using Java profiler settings such as:
74 * <pre>
75 * java -Xrunhprof:cpu=samples,depth=16 ...
76 * </pre>
77 * To include local files when using remote databases, use the special
78 * syntax:
79 * <pre>
80 * &#064;INCLUDE fileName
81 * </pre>
82 * This syntax is only supported by this tool. Embedded RUNSCRIPT SQL
83 * statements will be executed by the database.
84 *
85 * @param args the command line arguments
86 */
87 @Override
88 public void runTool(String... args) throws SQLException {
89 String url = null;
90 String user = "";
91 String password = "";
92 String script = "backup.sql";
93 String options = null;
94 boolean continueOnError = false;
95 boolean showTime = false;
96 for (int i = 0; args != null && i < args.length; i++) {
97 String arg = args[i];
98 if (arg.equals("-url")) {
99 url = args[++i];
100 } else if (arg.equals("-user")) {
101 user = args[++i];
102 } else if (arg.equals("-password")) {
103 password = args[++i];
104 } else if (arg.equals("-continueOnError")) {
105 continueOnError = true;
106 } else if (arg.equals("-checkResults")) {
107 checkResults = true;
108 } else if (arg.equals("-showResults")) {
109 showResults = true;
110 } else if (arg.equals("-script")) {
111 script = args[++i];
112 } else if (arg.equals("-time")) {
113 showTime = true;
114 } else if (arg.equals("-driver")) {
115 String driver = args[++i];
116 JdbcUtils.loadUserClass(driver);
117 } else if (arg.equals("-options")) {
118 StringBuilder buff = new StringBuilder();
119 i++;
120 for (; i < args.length; i++) {
121 buff.append(' ').append(args[i]);
122 }
123 options = buff.toString();
124 } else if (arg.equals("-help") || arg.equals("-?")) {
125 showUsage();
126 return;
127 } else {
128 showUsageAndThrowUnsupportedOption(arg);
129 }
130 }
131 if (url == null) {
132 showUsage();
133 throw new SQLException("URL not set");
134 }
135 long time = System.nanoTime();
136 if (options != null) {
137 processRunscript(url, user, password, script, options);
138 } else {
139 process(url, user, password, script, null, continueOnError);
140 }
141 if (showTime) {
142 time = System.nanoTime() - time;
143 out.println("Done in " + TimeUnit.NANOSECONDS.toMillis(time) + " ms");
144 }
145 }
146
147 /**
148 * Executes the SQL commands read from the reader against a database.
149 *
150 * @param conn the connection to a database
151 * @param reader the reader
152 * @return the last result set
153 * @throws SQLException on failure
154 */
155 public static ResultSet execute(Connection conn, Reader reader)
156 throws SQLException {
157 // can not close the statement because we return a result set from it
158 Statement stat = conn.createStatement();
159 ResultSet rs = null;
160 ScriptReader r = new ScriptReader(reader);
161 while (true) {
162 String sql = r.readStatement();
163 if (sql == null) {
164 break;
165 }
166 if (StringUtils.isWhitespaceOrEmpty(sql)) {
167 continue;
168 }
169 boolean resultSet = stat.execute(sql);
170 if (resultSet) {
171 if (rs != null) {
172 rs.close();
173 rs = null;
174 }
175 rs = stat.getResultSet();
176 }
177 }
178 return rs;
179 }
180
181 private void process(Connection conn, String fileName,
182 boolean continueOnError, Charset charset) throws SQLException,
183 IOException {
184 BufferedReader reader = FileUtils.newBufferedReader(fileName, charset);
185 try {
186 process(conn, continueOnError, FileUtils.getParent(fileName), reader, charset);
187 } finally {
188 IOUtils.closeSilently(reader);
189 }
190 }
191
192 private void process(Connection conn, boolean continueOnError, String path,
193 Reader reader, Charset charset) throws SQLException, IOException {
194 Statement stat = conn.createStatement();
195 ScriptReader r = new ScriptReader(reader);
196 while (true) {
197 String sql = r.readStatement();
198 if (sql == null) {
199 break;
200 }
201 String trim = sql.trim();
202 if (trim.isEmpty()) {
203 continue;
204 }
205 if (trim.startsWith("@") && StringUtils.toUpperEnglish(trim).
206 startsWith("@INCLUDE")) {
207 sql = StringUtils.trimSubstring(sql, "@INCLUDE".length());
208 if (!FileUtils.isAbsolute(sql)) {
209 sql = path + File.separatorChar + sql;
210 }
211 process(conn, sql, continueOnError, charset);
212 } else {
213 try {
214 if (showResults && !trim.startsWith("-->")) {
215 out.print(sql + ";");
216 }
217 if (showResults || checkResults) {
218 boolean query = stat.execute(sql);
219 if (query) {
220 ResultSet rs = stat.getResultSet();
221 int columns = rs.getMetaData().getColumnCount();
222 StringBuilder buff = new StringBuilder();
223 while (rs.next()) {
224 buff.append("\n-->");
225 for (int i = 0; i < columns; i++) {
226 String s = rs.getString(i + 1);
227 if (s != null) {
228 s = StringUtils.replaceAll(s, "\r\n", "\n");
229 s = StringUtils.replaceAll(s, "\n", "\n--> ");
230 s = StringUtils.replaceAll(s, "\r", "\r--> ");
231 }
232 buff.append(' ').append(s);
233 }
234 }
235 buff.append("\n;");
236 String result = buff.toString();
237 if (showResults) {
238 out.print(result);
239 }
240 if (checkResults) {
241 String expected = r.readStatement() + ";";
242 expected = StringUtils.replaceAll(expected, "\r\n", "\n");
243 expected = StringUtils.replaceAll(expected, "\r", "\n");
244 if (!expected.equals(result)) {
245 expected = StringUtils.replaceAll(expected, " ", "+");
246 result = StringUtils.replaceAll(result, " ", "+");
247 throw new SQLException(
248 "Unexpected output for:\n" + sql.trim() +
249 "\nGot:\n" + result + "\nExpected:\n" + expected);
250 }
251 }
252
253 }
254 } else {
255 stat.execute(sql);
256 }
257 } catch (Exception e) {
258 if (continueOnError) {
259 e.printStackTrace(out);
260 } else {
261 throw DbException.toSQLException(e);
262 }
263 }
264 }
265 }
266 }
267
268 private static void processRunscript(String url, String user, String password, String fileName, String options)
269 throws SQLException {
270 try (Connection conn = JdbcUtils.getConnection(null, url, user, password);
271 Statement stat = conn.createStatement()) {
272 String sql = "RUNSCRIPT FROM '" + fileName + "' " + options;
273 stat.execute(sql);
274 }
275 }
276
277 /**
278 * Executes the SQL commands in a script file against a database.
279 *
280 * @param url the database URL
281 * @param user the user name
282 * @param password the password
283 * @param fileName the script file
284 * @param charset the character set or null for UTF-8
285 * @param continueOnError if execution should be continued if an error
286 * occurs
287 * @throws SQLException on failure
288 */
289 public static void execute(String url, String user, String password,
290 String fileName, Charset charset, boolean continueOnError)
291 throws SQLException {
292 new RunScript().process(url, user, password, fileName, charset,
293 continueOnError);
294 }
295
296 /**
297 * Executes the SQL commands in a script file against a database.
298 *
299 * @param url the database URL
300 * @param user the user name
301 * @param password the password
302 * @param fileName the script file
303 * @param charset the character set or null for UTF-8
304 * @param continueOnError if execution should be continued if an error
305 * occurs
306 */
307 void process(String url, String user, String password, String fileName, Charset charset, boolean continueOnError)
308 throws SQLException {
309 if (charset == null) {
310 charset = StandardCharsets.UTF_8;
311 }
312 try (Connection conn = JdbcUtils.getConnection(null, url, user, password)) {
313 process(conn, fileName, continueOnError, charset);
314 } catch (IOException e) {
315 throw DbException.convertIOException(e, fileName);
316 }
317 }
318
319 }