KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > jdbc > DBDumper


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.jdbc;
21
22 import java.io.PrintWriter JavaDoc;
23 import java.sql.Connection JavaDoc;
24 import java.sql.DatabaseMetaData JavaDoc;
25 import java.sql.PreparedStatement JavaDoc;
26 import java.sql.ResultSet JavaDoc;
27 import java.sql.SQLException JavaDoc;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31
32 /**
33  * Dumps the contents of a database to an output stream as SQL.
34  *
35  * @author Brett Smith <a HREF="mailto: brett@3sp.com">&lt;brett@3sp.com&gt;</a>
36  */

37
38 public class DBDumper {
39
40     final static Log log = LogFactory.getLog(DBDumper.class);
41
42     /**
43      * Dump table creation and data. It is up to the caller to close the stream and connections when
44      * finished with.
45      *
46      * @param writer write SQL to this writer.
47      * @param conx connection to get data from
48      * @param quoteChar character to use to quote strings
49      * @throws Exception on any error
50      */

51     public void dumpToSQL(PrintWriter JavaDoc writer, JDBCConnectionImpl conx, char quoteChar) throws Exception JavaDoc {
52         dumpTable(writer, conx, quoteChar, null);
53         dumpData(writer, conx, quoteChar, null);
54     }
55
56     /**
57      * Dump table creation SQL. It is up to the caller to close the stream and connections when
58      * finished with.
59      *
60      * @param writer write SQL to this writer.
61      * @param conx connection to get data from
62      * @param quoteChar character to use to quote strings
63      * @param tables array of table names or <code>null</code> to dump all in
64      * database
65      * @throws Exception on any error
66      */

67     public void dumpTable(PrintWriter JavaDoc writer, JDBCConnectionImpl conx, char quoteChar, String JavaDoc[] tables) throws Exception JavaDoc {
68         Connection JavaDoc jdbcConnection = conx.getConnection();
69         DatabaseMetaData JavaDoc dbMetaData = jdbcConnection.getMetaData();
70
71         if (tables == null) {
72             ResultSet JavaDoc rs = dbMetaData.getTables(null, null, null, null);
73             try {
74                 while (rs.next()) {
75                     String JavaDoc tableName = rs.getString("TABLE_NAME");
76                     String JavaDoc tableType = rs.getString("TABLE_TYPE");
77                     if (tableType.equalsIgnoreCase("TABLE")) {
78                         dumpTable(writer, conx, quoteChar, new String JavaDoc[] { tableName });
79                     }
80                 }
81             } finally {
82                 rs.close();
83             }
84         } else {
85             for (int i = 0; i < tables.length; i++) {
86                 String JavaDoc tableName = tables[i];
87                 log.info("Dumping table creation for " + tableName);
88                 writer.println("CREATE TABLE " + tableName + " (");
89                 boolean first = true;
90
91                 // Columns
92
ResultSet JavaDoc rs2 = dbMetaData.getColumns(null, null, tableName, "%");
93                 try {
94                     while (rs2.next()) {
95                         if (first) {
96                             first = false;
97                         } else {
98                             writer.println(",");
99                         }
100                         String JavaDoc columnName = rs2.getString("COLUMN_NAME");
101                         String JavaDoc columnType = rs2.getString("TYPE_NAME");
102                         int columnSize = rs2.getInt("COLUMN_SIZE");
103                         String JavaDoc nullable = rs2.getString("IS_NULLABLE");
104                         String JavaDoc nullString = "NULL";
105                         if ("NO".equalsIgnoreCase(nullable)) {
106                             nullString = "NOT NULL";
107                         }
108                         writer.print(" " + columnName + " " + columnType);
109                         if (columnSize != 0) {
110                             if (columnType.equalsIgnoreCase("varchar") && columnSize > 255) {
111                                 columnSize = 255;
112                             }
113                             writer.print(" (" + columnSize + ")");
114                         }
115                         writer.print(" " + nullString);
116
117                     }
118                 } finally {
119                     rs2.close();
120                 }
121
122                 // Keys
123
try {
124                     rs2 = dbMetaData.getPrimaryKeys(null, null, tableName);
125                     String JavaDoc primaryKeyName = null;
126                     StringBuffer JavaDoc primaryKeyColumns = new StringBuffer JavaDoc();
127                     while (rs2.next()) {
128                         String JavaDoc thisKeyName = rs2.getString("PK_NAME");
129                         if ((thisKeyName != null && primaryKeyName == null) || (thisKeyName == null && primaryKeyName != null)
130                                         || (thisKeyName != null && !thisKeyName.equals(primaryKeyName))
131                                         || (primaryKeyName != null && !primaryKeyName.equals(thisKeyName))) {
132                             if (primaryKeyColumns.length() > 0) {
133                                 writer.print(",\n PRIMARY KEY ");
134                                 if (primaryKeyName != null) {
135                                     writer.print(primaryKeyName);
136                                 }
137                                 writer.print("(" + primaryKeyColumns.toString() + ")");
138                             }
139                             primaryKeyColumns = new StringBuffer JavaDoc();
140                             primaryKeyName = thisKeyName;
141                         }
142                         if (primaryKeyColumns.length() > 0) {
143                             primaryKeyColumns.append(", ");
144                         }
145                         primaryKeyColumns.append(rs2.getString("COLUMN_NAME"));
146                     }
147                     if (primaryKeyColumns.length() > 0) {
148                         writer.print(",\n PRIMARY KEY ");
149                         if (primaryKeyName != null) {
150                             writer.print(primaryKeyName);
151                         }
152                         writer.print(" (" + primaryKeyColumns.toString() + ")");
153                     }
154                 } finally {
155                     rs2.close();
156                 }
157                 writer.println("\n);");
158                 writer.println();
159             }
160         }
161     }
162
163     /**
164      * Dump table creation SQL. It is up to the caller to close the stream and connections when
165      * finished with.
166      *
167      * @param writer write SQL to this writer.
168      * @param conx connection to get data from
169      * @param quoteChar character to use to quote strings
170      * @param tables array of table names or <code>null</code> to dump all in
171      * database
172      * @throws Exception on any error
173      */

174     public void dumpData(PrintWriter JavaDoc writer, JDBCConnectionImpl conx, char quoteChar, String JavaDoc[] tables) throws Exception JavaDoc {
175         Connection JavaDoc jdbcConnection = conx.getConnection();
176         DatabaseMetaData JavaDoc dbMetaData = jdbcConnection.getMetaData();
177
178         if (tables == null) {
179             ResultSet JavaDoc rs = dbMetaData.getTables(null, null, null, null);
180             try {
181                 while (rs.next()) {
182                     String JavaDoc tableName = rs.getString("TABLE_NAME");
183                     String JavaDoc tableType = rs.getString("TABLE_TYPE");
184                     if (tableType.equalsIgnoreCase("TABLE")) {
185                         dumpData(writer, conx, quoteChar, new String JavaDoc[] { tableName });
186                     }
187                 }
188             } finally {
189                 rs.close();
190             }
191         } else {
192             for (int i = 0; i < tables.length; i++) {
193                 String JavaDoc tableName = tables[i];
194                 log.info("Dumping data for table " + tableName);
195                 // Data
196
PreparedStatement JavaDoc stmt = jdbcConnection.prepareStatement("SELECT * FROM " + tableName);
197                 try {
198                     ResultSet JavaDoc rs2 = stmt.executeQuery();
199                     try {
200                         while (rs2.next()) {
201                             dumpRow(writer, rs2);
202                         }
203                     } finally {
204                         rs2.close();
205                     }
206                 } finally {
207                     stmt.close();
208                 }
209                 writer.println();
210             }
211         }
212     }
213     
214     /**
215      * Dump a single result set row as an INSERT statement.
216      *
217      * @param writer
218      * @param resultSet
219      * @throws SQLException
220      */

221     public void dumpRow(PrintWriter JavaDoc writer, ResultSet JavaDoc resultSet) throws SQLException JavaDoc {
222         String JavaDoc tableName = resultSet.getMetaData().getTableName(1);
223         int columnCount = resultSet.getMetaData().getColumnCount();
224         writer.print("INSERT INTO " + tableName + " VALUES (");
225         for (int j = 0; j < columnCount; j++) {
226             if (j > 0) {
227                 writer.print(", ");
228             }
229             Object JavaDoc value = resultSet.getObject(j + 1);
230             if (value == null) {
231                 writer.print("NULL");
232             } else {
233                 String JavaDoc outputValue = value.toString();
234                 if (value instanceof Number JavaDoc) {
235                     writer.print(outputValue);
236                 } else {
237                     /*
238                      * TODO
239                      *
240                      * This escaping will current only work
241                      * for HSQLDB. This needs to be moved up
242                      * into the engine.
243                      */

244                     outputValue = outputValue.replaceAll("'", "''");
245                     writer.print("'" + outputValue + "'");
246                 }
247             }
248         }
249         writer.println(");");
250     }
251
252 }
253
Popular Tags