KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exolab > jms > tools > db > RDBMSTool


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "Exolab" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of Exoffice Technologies. For written permission,
18  * please contact info@exolab.org.
19  *
20  * 4. Products derived from this Software may not be called "Exolab"
21  * nor may "Exolab" appear in their names without prior written
22  * permission of Exoffice Technologies. Exolab is a registered
23  * trademark of Exoffice Technologies.
24  *
25  * 5. Due credit should be given to the Exolab Project
26  * (http://www.exolab.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2001-2005 (C) Exoffice Technologies Inc. All Rights Reserved.
42  *
43  * $Id: RDBMSTool.java,v 1.2 2005/04/08 13:52:14 tanderson Exp $
44  */

45 package org.exolab.jms.tools.db;
46
47 import java.sql.Connection JavaDoc;
48 import java.sql.SQLException JavaDoc;
49 import java.sql.Statement JavaDoc;
50
51 import org.apache.commons.logging.Log;
52 import org.apache.commons.logging.LogFactory;
53
54 import org.exolab.jms.persistence.PersistenceException;
55 import org.exolab.jms.persistence.SQLHelper;
56
57
58 /**
59  * This class provides support for creating and destroying tables in RDBMS
60  * databases.
61  *
62  * @version $Revision: 1.2 $ $Date: 2005/04/08 13:52:14 $
63  * @author <a HREF="mailto:tma@netspace.net.au">Tim Anderson</a>
64  */

65 public class RDBMSTool {
66
67     /**
68      * The connection to the database.
69      */

70     private Connection JavaDoc _connection = null;
71
72     /**
73      * The schema browser.
74      */

75     private SchemaBrowser _browser = null;
76
77     /**
78      * The logger
79      */

80     private static final Log _log = LogFactory.getLog(RDBMSTool.class);
81
82
83     /**
84      * Construct a new <code>RDBMSTool</code>.
85      *
86      * @param connection the JDBC connection
87      * @throws PersistenceException if database meta-data can't be obtained
88      */

89     public RDBMSTool(Connection JavaDoc connection) throws PersistenceException {
90         _connection = connection;
91         try {
92             _connection.setAutoCommit(true);
93         } catch (SQLException JavaDoc exception) {
94             throw new PersistenceException("Failed to set auto-commit on",
95                 exception);
96         }
97         _browser = new SchemaBrowser(_connection);
98     }
99
100     /**
101      * Creates the database.
102      *
103      * @param schema the database schema
104      * @throws PersistenceException if elements cannot be created in the
105      * database
106      */

107     public void create(Database schema) throws PersistenceException {
108         Table[] tables = schema.getTable();
109         for (int i = 0; i < tables.length; ++i) {
110             create(tables[i]);
111         }
112     }
113
114     /**
115      * Drops tables from the database.
116      *
117      * @param schema the database schema
118      * @throws PersistenceException if elements cannot be dropped from the
119      * database
120      */

121     public void drop(Database schema) throws PersistenceException {
122         Table[] tables = schema.getTable();
123         for (int i = 0; i < tables.length; ++i) {
124             drop(tables[i]);
125         }
126         Deprecated JavaDoc[] redundant = schema.getDeprecated();
127         for (int i = 0; i < redundant.length; ++i) {
128             dropTable(redundant[i].getName());
129         }
130     }
131
132     /**
133      * Close the connection to the database.
134      */

135     public void close() {
136         SQLHelper.close(_connection);
137     }
138
139     /**
140      * Creates a table in the database.
141      *
142      * @param table the table to create
143      * @throws PersistenceException if the table exists, or cannot be created
144      */

145     public void create(Table table) throws PersistenceException {
146         String JavaDoc name = table.getName();
147         if (_browser.getTableExists(name)) {
148             throw new PersistenceException(
149                 "An object already exists in the database named " + name);
150         }
151
152         StringBuffer JavaDoc sql = new StringBuffer JavaDoc("create table ");
153         sql.append(name);
154         sql.append(" (");
155
156         _log.debug("Creating table: " + name);
157         Attribute[] attributes = table.getAttribute();
158         for (int i = 0; i < attributes.length; ++i) {
159             if (i > 0) {
160                 sql.append(", ");
161             }
162             sql.append(attributes[i].getName());
163             sql.append(" ");
164             sql.append(getSQLType(attributes[i]));
165         }
166         sql.append(")");
167
168         _log.debug("SQL=" + sql);
169         Statement JavaDoc statement = null;
170         try {
171             statement = _connection.createStatement();
172             statement.executeUpdate(sql.toString());
173         } catch (SQLException JavaDoc exception) {
174             throw new PersistenceException("Failed to create table=" + name,
175                 exception);
176         } finally {
177             SQLHelper.close(statement);
178         }
179         createIndexes(table);
180     }
181
182     /**
183      * Drops a table from the database. If the table doesn't exist, then
184      * it will be ignored.
185      *
186      * @param table the table to drop
187      * @throws PersistenceException for any database error
188      */

189     public void drop(Table table) throws PersistenceException {
190         dropTable(table.getName());
191     }
192
193     /**
194      * Returns the schema browser.
195      *
196      * @return the schema browser
197      */

198     public SchemaBrowser getSchemaBrowser() {
199         return _browser;
200     }
201
202     /**
203      * Create indexes for a table.
204      *
205      * @param table the table to add indexes for
206      * @throws PersistenceException
207      */

208     private void createIndexes(Table table) throws PersistenceException {
209         Index[] indexes = table.getIndex();
210         for (int i = 0; i < indexes.length; ++i) {
211             Index index = indexes[i];
212             StringBuffer JavaDoc sql = new StringBuffer JavaDoc("create ");
213             if (index.getUnique()) {
214                 sql.append("unique ");
215             }
216             sql.append("index ");
217             sql.append(index.getName());
218             sql.append(" on ");
219             sql.append(table.getName());
220             sql.append("(");
221             Column[] columns = index.getColumn();
222             for (int j = 0; j < columns.length; ++j) {
223                 if (j > 0) {
224                     sql.append(", ");
225                 }
226                 sql.append(columns[j].getName());
227             }
228             sql.append(")");
229             _log.debug("SQL=" + sql);
230             Statement JavaDoc statement = null;
231             try {
232                 statement = _connection.createStatement();
233                 statement.executeUpdate(sql.toString());
234             } catch (SQLException JavaDoc exception) {
235                 throw new PersistenceException(
236                     "Failed to create index=" + index.getName() + " on table "
237                     + table.getName());
238             } finally {
239                 SQLHelper.close(statement);
240             }
241         }
242     }
243
244     /**
245      * Drop a table.
246      *
247      * @param name the name of the table to drop
248      * @throws PersistenceException if the drop fails
249      */

250     private void dropTable(String JavaDoc name) throws PersistenceException {
251         if (_browser.getTableExists(name)) {
252             String JavaDoc sql = "drop table " + name;
253             _log.debug("SQL=" + sql);
254             Statement JavaDoc statement = null;
255             try {
256                 statement = _connection.createStatement();
257                 statement.executeUpdate(sql);
258             } catch (SQLException JavaDoc exception) {
259                 throw new PersistenceException("Failed to drop table=" + name,
260                     exception);
261             } finally {
262                 SQLHelper.close(statement);
263             }
264         }
265     }
266
267     /**
268      * Returns the SQL type for a given attribute.
269      *
270      * @param attribute the attribute
271      * @return a string representation of the type
272      * @throws PersistenceException if {@link Attribute#getType} is invalid, or
273      * the RDBMS doesn't support the type
274      */

275     private String JavaDoc getSQLType(Attribute attribute)
276         throws PersistenceException {
277         Type result = _browser.getType(attribute);
278         _log.debug("attribute=" + attribute.getName() + "->" + result);
279         return result.getSQL();
280     }
281
282 }
283
Popular Tags