KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > impl > tools > dblook > DB_Key


1 /*
2
3    Derby - Class org.apache.derby.impl.tools.dblook.DB_Key
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to you under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derby.impl.tools.dblook;
23
24 import java.sql.Connection JavaDoc;
25 import java.sql.Statement JavaDoc;
26 import java.sql.PreparedStatement JavaDoc;
27 import java.sql.ResultSet JavaDoc;
28 import java.sql.SQLException JavaDoc;
29
30 import java.util.HashMap JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.StringTokenizer JavaDoc;
33
34 import org.apache.derby.tools.dblook;
35
36 public class DB_Key {
37
38     // Prepared statements used throughout the DDL
39
// generation process.
40
private static PreparedStatement JavaDoc getReferenceCols;
41     private static boolean printedHeader;
42
43     /* ************************************************
44      * Generate the DDL for all keys in a given
45      * database.
46      * @param conn Connection to the source database.
47      * @return The DDL for the keys has been written
48      * to output via Logs.java.
49      ****/

50
51     public static void doKeys(Connection JavaDoc conn)
52         throws SQLException JavaDoc
53     {
54
55         printedHeader = false;
56         getReferenceCols = conn.prepareStatement("SELECT CG.TABLEID, " +
57             "CG.DESCRIPTOR FROM SYS.SYSCONGLOMERATES CG, SYS.SYSKEYS K WHERE " +
58             "K.CONSTRAINTID = ? AND K.CONGLOMERATEID = CG.CONGLOMERATEID");
59
60         // Non-foreign keys, first.
61
Statement JavaDoc stmt = conn.createStatement();
62         ResultSet JavaDoc rs = stmt.executeQuery("SELECT CS.CONSTRAINTNAME, CS.TYPE, " +
63             "CS.TABLEID, CS.CONSTRAINTID, CS.SCHEMAID, CG.DESCRIPTOR, CG.ISCONSTRAINT " +
64             "FROM SYS.SYSCONSTRAINTS CS, SYS.SYSCONGLOMERATES CG, SYS.SYSKEYS K " +
65             "WHERE CS.STATE != 'D' AND CS.CONSTRAINTID = K.CONSTRAINTID AND " +
66             "CG.CONGLOMERATEID = K.CONGLOMERATEID ORDER BY CS.TABLEID");
67         createKeysFrom(rs);
68
69         // Now, foreign keys.
70
rs = stmt.executeQuery("SELECT CS.CONSTRAINTNAME, CS.TYPE, CS.TABLEID, " +
71             "CS.CONSTRAINTID, CS.SCHEMAID, CG.DESCRIPTOR, CG.ISCONSTRAINT, " +
72             "K.DELETERULE, K.UPDATERULE, K.KEYCONSTRAINTID FROM SYS.SYSCONSTRAINTS CS, " +
73             "SYS.SYSCONGLOMERATES CG, SYS.SYSFOREIGNKEYS K WHERE CS.STATE != 'D' " +
74             "AND CS.CONSTRAINTID = K.CONSTRAINTID AND CG.CONGLOMERATEID = " +
75             "K.CONGLOMERATEID ORDER BY CS.TABLEID");
76         createKeysFrom(rs);
77
78         getReferenceCols.close();
79         stmt.close();
80         rs.close();
81         return;
82
83     }
84
85     /* ************************************************
86      * Generate the DDL for the a set of keys in the
87      * source database.
88      * @param rs Info on keys to dump; either a set of non-
89      * foreign keys (primary and unique), or a set of
90      * foreign keys.
91      * @return DDL for the receive set of keys has
92      * been written to output via Logs.java.
93      ****/

94
95     private static void createKeysFrom (ResultSet JavaDoc rs)
96         throws SQLException JavaDoc
97     {
98
99         boolean firstTime = true;
100         while (rs.next()) {
101
102             if (!rs.getBoolean(7))
103             // this row is NOT for a constraint, so skip it.
104
continue;
105
106             String JavaDoc tableId = rs.getString(3);
107             String JavaDoc tableName = dblook.lookupTableId(tableId);
108             if (dblook.isExcludedTable(tableName))
109             // table isn't included in user-given list; skip it.
110
continue;
111
112             if (firstTime) {
113                 printHeader();
114                 if (rs.getString(2).equals("F"))
115                     Logs.reportMessage("DBLOOK_ForeignHeader");
116                 else
117                     Logs.reportMessage("DBLOOK_PrimUniqueHeader");
118             }
119
120             StringBuffer JavaDoc kString = createKeyString(tableId, tableName, rs);
121
122             if (rs.getString(2).equals("F")) {
123             // foreign key; we have to figure out the references info.
124
kString.append(makeFKReferenceClause(rs.getString(10),
125                     rs.getString(8).charAt(0), rs.getString(9).charAt(0)));
126             }
127
128             Logs.writeToNewDDL(kString.toString());
129             Logs.writeStmtEndToNewDDL();
130             Logs.writeNewlineToNewDDL();
131             firstTime = false;
132
133         }
134
135         return;
136
137     }
138
139     /* ************************************************
140      * Generate DDL for a specific key.
141      * @param tableId Id of table on which the key exists.
142      * @param tableName Name of table on which the key exists.
143      * @param aKey Info on the key to generate.
144      * @return DDL for the specified key is returned as
145      * a string.
146      ****/

147
148     private static StringBuffer JavaDoc createKeyString (String JavaDoc tableId,
149         String JavaDoc tableName, ResultSet JavaDoc aKey)
150         throws SQLException JavaDoc
151     {
152
153         StringBuffer JavaDoc sb = new StringBuffer JavaDoc ("ALTER TABLE ");
154         sb.append(tableName);
155         sb.append(" ADD");
156
157         String JavaDoc constraintName = dblook.addQuotes(
158             dblook.expandDoubleQuotes(aKey.getString(1)));
159         sb.append(" CONSTRAINT ");
160         sb.append(constraintName);
161         sb.append(expandKeyType(aKey.getString(2).charAt(0)));
162
163         // For keys, we need to get the column list.
164
sb.append("(");
165         sb.append(dblook.getColumnListFromDescription(
166             tableId, aKey.getString(6)));
167         sb.append(")");
168
169         return sb;
170
171     }
172
173     /* ************************************************
174      * Takes a character representing a key type and
175      * returns the full type name (as it will appear in
176      * in the DDL).
177      * @param keyType Key type as a char.
178      * @return Key type as a full string.
179      ****/

180
181     private static String JavaDoc expandKeyType(char keyType) {
182
183         switch (keyType) {
184             case 'P':
185                 return " PRIMARY KEY ";
186             case 'U':
187                 return " UNIQUE ";
188             case 'F':
189                 return " FOREIGN KEY ";
190             default:
191                 // shouldn't happen.
192
Logs.debug("INTERNAL ERROR: unexpected key type" +
193                     keyType, (String JavaDoc)null);
194                 return "";
195         }
196
197     }
198
199     /* ************************************************
200      * Generate the DDL for a foreign key's "REFERENCES"
201      * clause.
202      * @param constraintId Id of the foreign key constraint.
203      * @param deleteChar What action to take on delete.
204      * @param updateChar What action to take on update.
205      * @return The DDL for the references clause of the
206      * foreign key, returned as a string.
207      ****/

208     
209     private static String JavaDoc makeFKReferenceClause(String JavaDoc constraintId,
210         char deleteChar, char updateChar)
211         throws SQLException JavaDoc
212     {
213
214         StringBuffer JavaDoc refClause = new StringBuffer JavaDoc();
215
216         getReferenceCols.setString(1, constraintId);
217         ResultSet JavaDoc colsRS = getReferenceCols.executeQuery();
218         colsRS.next();
219         refClause.append(" REFERENCES ");
220         refClause.append(dblook.lookupTableId(colsRS.getString(1)));
221         refClause.append(" (");
222         refClause.append(dblook.getColumnListFromDescription(
223             colsRS.getString(1), colsRS.getString(2)));
224         refClause.append(")");
225
226         // On delete.
227
refClause.append(" ON DELETE ");
228         switch (deleteChar) {
229             case 'R': refClause.append("NO ACTION"); break;
230             case 'S': refClause.append("RESTRICT"); break;
231             case 'C': refClause.append("CASCADE"); break;
232             case 'U': refClause.append("SET NULL"); break;
233             default: // shouldn't happen.
234
Logs.debug("INTERNAL ERROR: unexpected 'on-delete' action: " +
235                             deleteChar, (String JavaDoc)null);
236                         break;
237         }
238
239         // On update
240
refClause.append(" ON UPDATE ");
241         switch (updateChar) {
242             case 'R': refClause.append("NO ACTION"); break;
243             case 'S': refClause.append("RESTRICT"); break;
244             default: // shouldn't happen.
245
Logs.debug("INTERNAL ERROR: unexpected 'on-update' action: " +
246                             updateChar, (String JavaDoc)null);
247                         break;
248         }
249
250         colsRS.close();
251         return refClause.toString();
252
253     }
254
255     /* ************************************************
256      * Print a simple header to output.
257      ****/

258
259     private static void printHeader() {
260
261         if (printedHeader)
262             return;
263
264         Logs.reportString("----------------------------------------------");
265         Logs.reportMessage("DBLOOK_KeysHeader");
266         Logs.reportString("----------------------------------------------\n");
267         printedHeader = true;
268
269     }
270
271 }
272
Popular Tags