KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > util > DatabaseManagerCommon


1 /* Copyright (c) 1995-2000, The Hypersonic SQL Group.
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of the Hypersonic SQL Group nor the names of its
15  * contributors may be used to endorse or promote products derived from this
16  * software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * This software consists of voluntary contributions made by many individuals
31  * on behalf of the Hypersonic SQL Group.
32  *
33  *
34  * For work added by the HSQL Development Group:
35  *
36  * Copyright (c) 2001-2005, The HSQL Development Group
37  * All rights reserved.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions are met:
41  *
42  * Redistributions of source code must retain the above copyright notice, this
43  * list of conditions and the following disclaimer.
44  *
45  * Redistributions in binary form must reproduce the above copyright notice,
46  * this list of conditions and the following disclaimer in the documentation
47  * and/or other materials provided with the distribution.
48  *
49  * Neither the name of the HSQL Development Group nor the names of its
50  * contributors may be used to endorse or promote products derived from this
51  * software without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
54  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
57  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
60  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
61  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
62  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  */

65
66
67 package org.hsqldb.util;
68
69 import java.io.BufferedReader JavaDoc;
70 import java.io.FileReader JavaDoc;
71 import java.io.FileWriter JavaDoc;
72 import java.io.IOException JavaDoc;
73 import java.sql.SQLException JavaDoc;
74 import java.sql.Statement JavaDoc;
75 import java.util.Random JavaDoc;
76
77 // sqlbob@users 20020401 - patch 1.7.0 by sqlbob (RMP) - enhancements
78
// sqlbob@users 20020407 - patch 1.7.0 - reengineering
79
// nickferguson@users 20021005 - patch 1.7.1 - enhancements
80
// fredt@users 20021012 - patch 1.7.1 - changes to test database DDL
81
// weconsultants@users 20041116 - patch 1.8.0 - in 'TestHelp' added 'IF EXISTS for both DROPS.
82
// Now catching the execption that was never caught before.
83

84 /**
85  * Common code in Swing and AWT versions of DatabaseManager
86  *
87  * New class based on Hypersonic original
88  *
89  * @author Thomas Mueller (Hypersonic SQL Group)
90  * @version 1.8.0
91  * @since 1.7.0
92  */

93 class DatabaseManagerCommon {
94
95     private static Random JavaDoc rRandom = new Random JavaDoc(100);
96     static String JavaDoc[] selectHelp = {
97         "SELECT * FROM ",
98         "SELECT [LIMIT n m] [DISTINCT] \n"
99         + "{ selectExpression | table.* | * } [, ... ] \n"
100         + "[INTO [CACHED|TEMP|TEXT] newTable] \n" + "FROM tableList \n"
101         + "[WHERE Expression] \n"
102         + "[ORDER BY selectExpression [{ASC | DESC}] [, ...] ] \n"
103         + "[GROUP BY Expression [, ...] ] \n"
104         + "[UNION [ALL] selectStatement]"
105     };
106     static String JavaDoc[] insertHelp = {
107         "INSERT INTO ",
108         "INSERT INTO table [ (column [,...] ) ] \n"
109         + "{ VALUES(Expression [,...]) | SelectStatement }"
110     };
111     static String JavaDoc[] updateHelp = {
112         "UPDATE ",
113         "UPDATE table SET column = Expression [, ...] \n"
114         + "[WHERE Expression]"
115     };
116     static String JavaDoc[] deleteHelp = {
117         "DELETE FROM ", "DELETE FROM table [WHERE Expression]"
118     };
119     static String JavaDoc[] createTableHelp = {
120         "CREATE TABLE ",
121         "CREATE [TEMP] [CACHED|MEMORY|TEXT] TABLE name \n"
122         + "( columnDefinition [, ...] ) \n\n" + "columnDefinition: \n"
123         + "column DataType [ [NOT] NULL] [PRIMARY KEY] \n" + "DataType: \n"
124         + "{ INTEGER | DOUBLE | VARCHAR | DATE | TIME |... }"
125     };
126     static String JavaDoc[] dropTableHelp = {
127         "DROP TABLE ", "DROP TABLE table"
128     };
129     static String JavaDoc[] createIndexHelp = {
130         "CREATE INDEX ",
131         "CREATE [UNIQUE] INDEX index ON \n" + "table (column [, ...])"
132     };
133     static String JavaDoc[] dropIndexHelp = {
134         "DROP INDEX ", "DROP INDEX table.index"
135     };
136     static String JavaDoc[] checkpointHelp = {
137         "CHECKPOINT", "(HSQLDB SQL only)"
138     };
139     static String JavaDoc[] scriptHelp = {
140         "SCRIPT", "SCRIPT ['file']\n\n" + "(HSQLDB SQL only)"
141     };
142     static String JavaDoc[] shutdownHelp = {
143         "SHUTDOWN", "SHUTDOWN [COMPACT|IMMEDIATELY]\n\n" + "(HSQLDB SQL only)"
144     };
145     static String JavaDoc[] setHelp = {
146         "SET ",
147         "AUTOCOMMIT { TRUE | FALSE }\n" + "IGNORECASE { TRUE | FALSE }\n"
148         + "LOGSIZE size\n" + "MAXROWS maxrows\n" + "PASSWORD password\n"
149         + "READONLY { TRUE | FALSE }\n"
150         + "REFERENTIAL_INTEGRITY { TRUE | FALSE }\n"
151         + "TABLE table READONLY { TRUE | FALSE }\n"
152         + "TABLE table SOURCE \"file\" [DESC]\n"
153         + "WRITE_DELAY { TRUE | FALSE }\n\n" + "(HSQLDB SQL only)"
154     };
155     static String JavaDoc[] testHelp = {
156         "-->>>TEST<<<-- ;\n" + "--#1000;\n" + "DROP TABLE Test IF EXISTS;\n"
157         + "CREATE TABLE Test(\n" + " Id INTEGER PRIMARY KEY,\n"
158         + " FirstName VARCHAR(20),\n" + " Name VARCHAR(50),\n"
159         + " ZIP INTEGER) ;\n" + "INSERT INTO Test \n"
160         + " VALUES(#,'Julia','Peterson-Clancy',#) ;\n"
161         + "UPDATE Test SET Name='Hans' WHERE Id=# ;\n"
162         + "SELECT * FROM Test WHERE Id=# ;\n"
163         + "DELETE FROM Test WHERE Id=# ;\n" + "DROP TABLE Test IF EXISTS;",
164         "This test script is parsed by the DatabaseManager\n"
165         + "It may be changed manually. Rules:\n"
166         + "- it must start with -->>>TEST<<<--.\n"
167         + "- each line must end with ';' (no spaces after)\n"
168         + "- lines starting with -- are comments\n"
169         + "- lines starting with --#<count> means set new count\n"
170     };
171     static String JavaDoc[] testDataSql = {
172         "SELECT * FROM Product", "SELECT * FROM Invoice",
173         "SELECT * FROM Item",
174         "SELECT * FROM Customer a INNER JOIN Invoice i ON a.ID=i.CustomerID",
175         "SELECT * FROM Customer a LEFT OUTER JOIN Invoice i ON a.ID=i.CustomerID",
176         "SELECT * FROM Invoice d INNER JOIN Item i ON d.ID=i.InvoiceID",
177         "SELECT * FROM Customer WHERE Street LIKE '1%' ORDER BY Lastname",
178         "SELECT a.id, a.firstname, a.lastname, count(i.Total) \"COUNT\", "
179         + "COALESCE(sum(i.Total), 0) \"TOTAL\", COALESCE(AVG(i.Total),0) \"AVG\" FROM Customer a "
180         + "LEFT OUTER JOIN Invoice i ON a.ID=i.CustomerID GROUP BY a.id, a.firstname, a.lastname"
181     };
182
183     /**
184      * Method declaration
185      *
186      *
187      * @param s
188      *
189      * @return
190      */

191     static String JavaDoc random(String JavaDoc[] s) {
192         return s[random(s.length)];
193     }
194
195     /**
196      * Method declaration
197      *
198      *
199      * @param i
200      *
201      * @return
202      */

203     static int random(int i) {
204
205         i = rRandom.nextInt() % i;
206
207         return i < 0 ? -i
208                      : i;
209     }
210
211     /**
212      * Method declaration
213      *
214      */

215     static void createTestTables(Statement JavaDoc sStatement) {
216
217         String JavaDoc[] demo = {
218             "DROP TABLE Item IF EXISTS;", "DROP TABLE Invoice IF EXISTS;",
219             "DROP TABLE Product IF EXISTS;", "DROP TABLE Customer IF EXISTS;",
220             "CREATE TABLE Customer(ID INTEGER PRIMARY KEY,FirstName VARCHAR,"
221             + "LastName VARCHAR,Street VARCHAR,City VARCHAR);",
222             "CREATE TABLE Product(ID INTEGER PRIMARY KEY,Name VARCHAR,"
223             + "Price DECIMAL);",
224             "CREATE TABLE Invoice(ID INTEGER PRIMARY KEY,CustomerID INTEGER,"
225             + "Total DECIMAL, FOREIGN KEY (CustomerId) "
226             + "REFERENCES Customer(ID) ON DELETE CASCADE);",
227             "CREATE TABLE Item(InvoiceID INTEGER,Item INTEGER,"
228             + "ProductID INTEGER,Quantity INTEGER,Cost DECIMAL,"
229             + "PRIMARY KEY(InvoiceID,Item), "
230             + "FOREIGN KEY (InvoiceId) REFERENCES "
231             + "Invoice (ID) ON DELETE CASCADE, FOREIGN KEY (ProductId) "
232             + "REFERENCES Product(ID) ON DELETE CASCADE);"
233         };
234
235         for (int i = 0; i < demo.length; i++) {
236
237             // drop table may fail
238
try {
239                 sStatement.execute(demo[i]);
240             } catch (SQLException JavaDoc e) {
241                 ;
242             }
243         }
244     }
245
246     /**
247      * Method declaration
248      *
249      */

250     static String JavaDoc createTestData(Statement JavaDoc sStatement) throws SQLException JavaDoc {
251
252         String JavaDoc[] name = {
253             "White", "Karsen", "Smith", "Ringer", "May", "King", "Fuller",
254             "Miller", "Ott", "Sommer", "Schneider", "Steel", "Peterson",
255             "Heiniger", "Clancy"
256         };
257         String JavaDoc[] firstname = {
258             "Mary", "James", "Anne", "George", "Sylvia", "Robert", "Janet",
259             "Michael", "Andrew", "Bill", "Susanne", "Laura", "Bob", "Julia",
260             "John"
261         };
262         String JavaDoc[] street = {
263             "Upland Pl.", "College Av.", "- 20th Ave.", "Seventh Av."
264         };
265         String JavaDoc[] city = {
266             "New York", "Dallas", "Boston", "Chicago", "Seattle",
267             "San Francisco", "Berne", "Oslo", "Paris", "Lyon", "Palo Alto",
268             "Olten"
269         };
270         String JavaDoc[] product = {
271             "Iron", "Ice Tea", "Clock", "Chair", "Telephone", "Shoe"
272         };
273         int max = 50;
274
275         sStatement.execute("SET REFERENTIAL_INTEGRITY FALSE");
276
277         for (int i = 0; i < max; i++) {
278             sStatement.execute("INSERT INTO Customer VALUES(" + i + ",'"
279                                + random(firstname) + "','" + random(name)
280                                + "','" + random(554) + " " + random(street)
281                                + "','" + random(city) + "')");
282             sStatement.execute("INSERT INTO Product VALUES(" + i + ",'"
283                                + random(product) + " " + random(product)
284                                + "'," + (20 + 2 * random(120)) + ")");
285             sStatement.execute("INSERT INTO Invoice VALUES(" + i + ","
286                                + random(max) + ",0.0)");
287
288             for (int j = random(20) + 2; j >= 0; j--) {
289                 sStatement.execute("INSERT INTO Item VALUES(" + i + "," + j
290                                    + "," + random(max) + ","
291                                    + (1 + random(24)) + ",1.5)");
292             }
293         }
294
295         sStatement.execute("SET REFERENTIAL_INTEGRITY TRUE");
296         sStatement.execute("UPDATE Product SET Price=ROUND(Price*.1,2)");
297         sStatement.execute(
298             "UPDATE Item SET Cost=Cost*"
299             + "SELECT Price FROM Product prod WHERE ProductID=prod.ID");
300         sStatement.execute(
301             "UPDATE Invoice SET Total=SELECT SUM(Cost*"
302             + "Quantity) FROM Item WHERE InvoiceID=Invoice.ID");
303
304         return ("SELECT * FROM Customer");
305     }
306
307     /**
308      * Method declaration
309      * Redid this file to remove sizing requirements and to make it faster
310      * Speeded it up 10 fold.
311      * @param file
312      * @return
313      */

314     static String JavaDoc readFile(String JavaDoc file) {
315
316         try {
317             FileReader JavaDoc reader = new FileReader JavaDoc(file);
318             BufferedReader JavaDoc read = new BufferedReader JavaDoc(reader);
319             StringBuffer JavaDoc b = new StringBuffer JavaDoc();
320             String JavaDoc s = null;
321             int count = 0;
322
323             while ((s = read.readLine()) != null) {
324                 count++;
325
326                 b.append(s);
327                 b.append('\n');
328             }
329
330             read.close();
331             reader.close();
332
333             return b.toString();
334         } catch (IOException JavaDoc e) {
335             return e.getMessage();
336         }
337     }
338
339     /**
340      * Method declaration
341      *
342      *
343      * @param file
344      * @param text
345      */

346     static void writeFile(String JavaDoc file, String JavaDoc text) {
347
348         try {
349             FileWriter JavaDoc write = new FileWriter JavaDoc(file);
350
351             write.write(text.toCharArray());
352             write.close();
353         } catch (IOException JavaDoc e) {
354             e.printStackTrace();
355         }
356     }
357
358     /**
359      * Method declaration
360      *
361      *
362      * @param sql
363      * @param max
364      *
365      * @return
366      *
367      * @throws SQLException
368      */

369     static long testStatement(Statement JavaDoc sStatement, String JavaDoc sql,
370                               int max) throws SQLException JavaDoc {
371
372         long start = System.currentTimeMillis();
373
374         if (sql.indexOf('#') == -1) {
375             max = 1;
376         }
377
378         for (int i = 0; i < max; i++) {
379             String JavaDoc s = sql;
380
381             while (true) {
382                 int j = s.indexOf("#r#");
383
384                 if (j == -1) {
385                     break;
386                 }
387
388                 s = s.substring(0, j) + ((int) (Math.random() * i))
389                     + s.substring(j + 3);
390             }
391
392             while (true) {
393                 int j = s.indexOf('#');
394
395                 if (j == -1) {
396                     break;
397                 }
398
399                 s = s.substring(0, j) + i + s.substring(j + 1);
400             }
401
402             sStatement.execute(s);
403         }
404
405         return (System.currentTimeMillis() - start);
406     }
407
408     private DatabaseManagerCommon() {}
409 }
410
Popular Tags