KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > tools > RunScript


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.tools;
6
7 import java.io.BufferedInputStream JavaDoc;
8 import java.io.File JavaDoc;
9 import java.io.FileInputStream JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.io.InputStreamReader JavaDoc;
13 import java.io.Reader JavaDoc;
14 import java.sql.Connection JavaDoc;
15 import java.sql.DriverManager JavaDoc;
16 import java.sql.ResultSet JavaDoc;
17 import java.sql.SQLException JavaDoc;
18 import java.sql.Statement JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.Iterator JavaDoc;
21
22 import org.h2.engine.Constants;
23 import org.h2.message.Message;
24 import org.h2.util.JdbcUtils;
25 import org.h2.util.ScriptReader;
26 import org.h2.util.StringUtils;
27
28 /**
29  * Executes the contents of a SQL script file against a database.
30  *
31  * @author Tom
32  *
33  */

34 public class RunScript {
35
36     private static final boolean MULTI_THREAD = false;
37
38     private void showUsage() {
39         System.out.println("java " + getClass().getName() + " -url <url> -user <user> [-password <pwd>] [-script <file>] [-driver <driver] [-options <option> ...]");
40     }
41
42     /**
43      * The command line interface for this tool. The options must be split into strings like this: "-user", "sa",... The
44      * following options are supported:
45      * <ul>
46      * <li>-help or -? (print the list of options)
47      * <li>-url jdbc:h2:... (database URL)
48      * <li>-user username
49      * <li>-password password
50      * <li>-script filename (default file name is backup.sql)
51      * <li>-driver driver the JDBC driver class name (not required for H2)
52      * <li>-options to specify a list of options (only for H2 and only when using the embedded mode)
53      * </ul>
54      * To include local files when using remote databases, use the special syntax:
55      * <pre>
56      * &#64;INCLUDE fileName
57      * </pre>
58      * This syntax is only supported by this tool.
59      * Embedded RUNSCRIPT SQL statements will be executed by the database.
60      *
61      * @param args the command line arguments
62      * @throws SQLException
63      */

64     public static void main(String JavaDoc[] args) throws SQLException JavaDoc {
65         new RunScript().run(args);
66     }
67
68     private void run(String JavaDoc[] args) throws SQLException JavaDoc {
69         String JavaDoc url = null;
70         String JavaDoc user = null;
71         String JavaDoc password = "";
72         String JavaDoc script = "backup.sql";
73         String JavaDoc options = null;
74         boolean continueOnError = false;
75         for (int i = 0; args != null && i < args.length; i++) {
76             if (args[i].equals("-url")) {
77                 url = args[++i];
78             } else if (args[i].equals("-user")) {
79                 user = args[++i];
80             } else if (args[i].equals("-password")) {
81                 password = args[++i];
82             } else if (args[i].equals("-continueOnError")) {
83                 continueOnError = true;
84             } else if (args[i].equals("-script")) {
85                 script = args[++i];
86             } else if (args[i].equals("-driver")) {
87                 String JavaDoc driver = args[++i];
88                 try {
89                     Class.forName(driver);
90                 } catch (ClassNotFoundException JavaDoc e) {
91                     throw Message.convert(e);
92                 }
93             } else if (args[i].equals("-options")) {
94                 StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
95                 i++;
96                 for (; i < args.length; i++) {
97                     buff.append(' ');
98                     buff.append(args[i]);
99                 }
100                 options = buff.toString();
101             } else {
102                 showUsage();
103                 return;
104             }
105         }
106         if (url == null || user == null || password == null || script == null) {
107             showUsage();
108             return;
109         }
110         // long time = System.currentTimeMillis();
111
// for(int i=0; i<10; i++) {
112
// int test;
113
if (options != null) {
114             executeRunscript(url, user, password, script, options);
115         } else {
116             execute(url, user, password, script, null, continueOnError);
117         }
118         // }
119
// time = System.currentTimeMillis() - time;
120
// System.out.println("Done in " + time + " ms");
121
}
122
123     /**
124      * Executes the SQL commands in a script file against a database.
125      *
126      * @param conn the connection to a database
127      * @param reader the reader
128      * @return the last result set
129      */

130     public static ResultSet JavaDoc execute(Connection JavaDoc conn, Reader JavaDoc reader) throws SQLException JavaDoc {
131         Statement JavaDoc stat = conn.createStatement();
132         ResultSet JavaDoc rs = null;
133         ScriptReader r = new ScriptReader(reader);
134         while (true) {
135             String JavaDoc sql = r.readStatement();
136             if (sql == null) {
137                 break;
138             }
139             boolean resultset = stat.execute(sql);
140             if (resultset) {
141                 if (rs != null) {
142                     rs.close();
143                     rs = null;
144                 }
145                 rs = stat.getResultSet();
146             }
147         }
148         return rs;
149     }
150
151     private static void execute(Connection JavaDoc conn, HashMap JavaDoc threadMap, String JavaDoc fileName, boolean continueOnError, String JavaDoc charsetName) throws SQLException JavaDoc, IOException JavaDoc {
152         InputStream JavaDoc in = new FileInputStream JavaDoc(fileName);
153         String JavaDoc path = new File JavaDoc(fileName).getAbsoluteFile().getParent();
154         try {
155             BufferedInputStream JavaDoc bin = new BufferedInputStream JavaDoc(in, Constants.IO_BUFFER_SIZE);
156             InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(bin, charsetName);
157             execute(conn, threadMap, continueOnError, path, reader, charsetName);
158         } finally {
159             in.close();
160         }
161     }
162
163     private static void execute(Connection JavaDoc conn, HashMap JavaDoc threadMap, boolean continueOnError, String JavaDoc path, Reader JavaDoc reader, String JavaDoc charsetName) throws SQLException JavaDoc, IOException JavaDoc {
164         Statement JavaDoc stat = conn.createStatement();
165         ScriptReader r = new ScriptReader(reader);
166         while (true) {
167             String JavaDoc sql = r.readStatement();
168             if (sql == null) {
169                 break;
170             }
171             sql = sql.trim();
172             if (sql.startsWith("@") && StringUtils.toUpperEnglish(sql).startsWith("@INCLUDE")) {
173                 sql = sql.substring("@INCLUDE".length()).trim();
174                 if(!new File JavaDoc(sql).isAbsolute()) {
175                     sql = path + File.separator + sql;
176                 }
177                 execute(conn, threadMap, sql, continueOnError, charsetName);
178             } else if (MULTI_THREAD && sql.startsWith("/*")) {
179                 int idx = sql.indexOf(']');
180                 Integer JavaDoc id = new Integer JavaDoc(Integer.parseInt(sql.substring("/*".length(), idx)));
181                 RunScriptThread thread = (RunScriptThread) threadMap.get(id);
182                 if (thread == null) {
183                     Connection JavaDoc c = DriverManager.getConnection(conn.getMetaData().getURL());
184                     thread = new RunScriptThread(id.intValue(), c);
185                     threadMap.put(id, thread);
186                     thread.start();
187                 }
188                 sql = sql.substring(sql.indexOf("*/") + 2).trim();
189                 String JavaDoc up = StringUtils.toUpperEnglish(sql);
190                 thread.addStatement(sql);
191                 if (up.startsWith("CREATE") || up.startsWith("DROP") || up.startsWith("ALTER")) {
192                     thread.executeAll();
193                 } else {
194                 }
195             } else {
196                 try {
197                     stat.execute(sql);
198                 } catch (SQLException JavaDoc e) {
199                     if (continueOnError) {
200                         e.printStackTrace();
201                     } else {
202                         throw e;
203                     }
204                 }
205             }
206         }
207         Iterator JavaDoc it = threadMap.values().iterator();
208         while (it.hasNext()) {
209             RunScriptThread thread = (RunScriptThread) it.next();
210             try {
211                 thread.join();
212             } catch (InterruptedException JavaDoc e) {
213                 e.printStackTrace();
214             }
215         }
216     }
217
218     private static void executeRunscript(String JavaDoc url, String JavaDoc user, String JavaDoc password, String JavaDoc fileName, String JavaDoc options) throws SQLException JavaDoc {
219         Connection JavaDoc conn = null;
220         Statement JavaDoc stat = null;
221         try {
222             org.h2.Driver.load();
223             conn = DriverManager.getConnection(url, user, password);
224             stat = conn.createStatement();
225             String JavaDoc sql = "RUNSCRIPT FROM '" + fileName + "' " + options;
226             stat.execute(sql);
227         } catch (Exception JavaDoc e) {
228             throw Message.convert(e);
229         } finally {
230             JdbcUtils.closeSilently(stat);
231             JdbcUtils.closeSilently(conn);
232         }
233     }
234
235     /**
236      * Executes the SQL commands in a script file against a database.
237      *
238      * @param url the database URL
239      * @param user the user name
240      * @param password the password
241      * @param fileName the script file
242      * @param charsetName the character set name or null for UTF-8
243      * @param continueOnError if execution should be continued if an error occurs
244      * @throws SQLException
245      */

246     public static void execute(String JavaDoc url, String JavaDoc user, String JavaDoc password, String JavaDoc fileName, String JavaDoc charsetName, boolean continueOnError) throws SQLException JavaDoc {
247         try {
248             org.h2.Driver.load();
249             Connection JavaDoc conn = DriverManager.getConnection(url, user, password);
250             if (charsetName == null) {
251                 charsetName = Constants.UTF8;
252             }
253             HashMap JavaDoc threadMap = new HashMap JavaDoc();
254             try {
255                 execute(conn, threadMap, fileName, continueOnError, charsetName);
256             } finally {
257                 conn.close();
258             }
259         } catch (Exception JavaDoc e) {
260             throw Message.convert(e);
261         }
262     }
263
264 }
265
Popular Tags