KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cayenne > dba > db2 > DB2PkGenerator


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

19 package org.apache.cayenne.dba.db2;
20
21 import java.sql.Connection JavaDoc;
22 import java.sql.ResultSet JavaDoc;
23 import java.sql.SQLException JavaDoc;
24 import java.sql.Statement JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Collection JavaDoc;
27 import java.util.Collections JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30
31 import org.apache.cayenne.CayenneRuntimeException;
32 import org.apache.cayenne.access.DataNode;
33 import org.apache.cayenne.access.QueryLogger;
34 import org.apache.cayenne.dba.JdbcPkGenerator;
35 import org.apache.cayenne.map.DbEntity;
36
37 /**
38  * A sequence-based PK generator used by {@link DB2Adapter}.
39  *
40  * @author Andrus Adamchik
41  */

42 public class DB2PkGenerator extends JdbcPkGenerator {
43
44     private static final String JavaDoc _SEQUENCE_PREFIX = "S_";
45
46     /**
47      * @deprecated since 2.0 - other generators do not expose the default prefix.
48      */

49     public static final String JavaDoc SEQUENCE_PREFIX = "S_";
50
51     protected int pkFromDatabase(DataNode node, DbEntity ent) throws Exception JavaDoc {
52
53         String JavaDoc pkGeneratingSequenceName = sequenceName(ent);
54
55         Connection JavaDoc con = node.getDataSource().getConnection();
56         try {
57             Statement JavaDoc st = con.createStatement();
58             try {
59                 String JavaDoc sql = "SELECT NEXTVAL FOR "
60                         + pkGeneratingSequenceName
61                         + " FROM SYSIBM.SYSDUMMY1";
62                 QueryLogger.logQuery(sql, Collections.EMPTY_LIST);
63                 ResultSet JavaDoc rs = st.executeQuery(sql);
64                 try {
65                     // Object pk = null;
66
if (!rs.next()) {
67                         throw new CayenneRuntimeException(
68                                 "Error generating pk for DbEntity " + ent.getName());
69                     }
70                     return rs.getInt(1);
71                 }
72                 finally {
73                     rs.close();
74                 }
75             }
76             finally {
77                 st.close();
78             }
79         }
80         finally {
81             con.close();
82         }
83     }
84
85     public void createAutoPk(DataNode node, List JavaDoc dbEntities) throws Exception JavaDoc {
86         Collection JavaDoc sequences = getExistingSequences(node);
87         Iterator JavaDoc it = dbEntities.iterator();
88
89         while (it.hasNext()) {
90             DbEntity entity = (DbEntity) it.next();
91             if (!sequences.contains(sequenceName(entity))) {
92                 this.runUpdate(node, createSequenceString(entity));
93             }
94         }
95     }
96
97     /**
98      * Creates a list of CREATE SEQUENCE statements for the list of DbEntities.
99      */

100     public List JavaDoc createAutoPkStatements(List JavaDoc dbEntities) {
101         List JavaDoc list = new ArrayList JavaDoc(dbEntities.size());
102         Iterator JavaDoc it = dbEntities.iterator();
103
104         while (it.hasNext()) {
105             DbEntity ent = (DbEntity) it.next();
106             list.add(createSequenceString(ent));
107         }
108
109         return list;
110     }
111
112     /**
113      * Drops PK sequences for all specified DbEntities.
114      */

115     public void dropAutoPk(DataNode node, List JavaDoc dbEntities) throws Exception JavaDoc {
116         Collection JavaDoc sequences = getExistingSequences(node);
117
118         Iterator JavaDoc it = dbEntities.iterator();
119         while (it.hasNext()) {
120             DbEntity ent = (DbEntity) it.next();
121             if (sequences.contains(sequenceName(ent))) {
122                 runUpdate(node, dropSequenceString(ent));
123             }
124         }
125     }
126
127     /**
128      * Creates a list of DROP SEQUENCE statements for the list of DbEntities.
129      */

130     public List JavaDoc dropAutoPkStatements(List JavaDoc dbEntities) {
131
132         List JavaDoc list = new ArrayList JavaDoc(dbEntities.size());
133         Iterator JavaDoc it = dbEntities.iterator();
134
135         while (it.hasNext()) {
136             DbEntity entity = (DbEntity) it.next();
137             list.add(dropSequenceString(entity));
138         }
139
140         return list;
141     }
142
143     /**
144      * Fetches a list of existing sequences that might match Cayenne generated ones.
145      */

146     protected List JavaDoc getExistingSequences(DataNode node) throws SQLException JavaDoc {
147
148         // check existing sequences
149
Connection JavaDoc con = node.getDataSource().getConnection();
150
151         try {
152             Statement JavaDoc sel = con.createStatement();
153             try {
154                 StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
155                 buffer.append("SELECT SEQNAME FROM SYSCAT.SEQUENCES ").append(
156                         "WHERE SEQNAME LIKE '").append(_SEQUENCE_PREFIX).append("%'");
157
158                 String JavaDoc sql = buffer.toString();
159                 QueryLogger.logQuery(sql, Collections.EMPTY_LIST);
160                 ResultSet JavaDoc rs = sel.executeQuery(sql);
161                 try {
162                     List JavaDoc sequenceList = new ArrayList JavaDoc();
163                     while (rs.next()) {
164                         sequenceList.add(rs.getString(1));
165                     }
166                     return sequenceList;
167                 }
168                 finally {
169                     rs.close();
170                 }
171             }
172             finally {
173                 sel.close();
174             }
175         }
176         finally {
177             con.close();
178         }
179     }
180
181     /**
182      * Returns default sequence name for DbEntity.
183      */

184     protected String JavaDoc sequenceName(DbEntity entity) {
185
186         String JavaDoc entName = entity.getName();
187         String JavaDoc seqName = _SEQUENCE_PREFIX + entName;
188
189         if (entity.getSchema() != null && entity.getSchema().length() > 0) {
190             seqName = entity.getSchema() + "." + seqName;
191         }
192         return seqName;
193     }
194
195     /**
196      * Returns DROP SEQUENCE statement.
197      */

198     protected String JavaDoc dropSequenceString(DbEntity entity) {
199         return "DROP SEQUENCE " + sequenceName(entity) + " RESTRICT ";
200     }
201
202     /**
203      * Returns CREATE SEQUENCE statement for entity.
204      */

205     protected String JavaDoc createSequenceString(DbEntity entity) {
206         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
207         buf
208                 .append("CREATE SEQUENCE ")
209                 .append(sequenceName(entity))
210                 .append(" START WITH 200")
211                 .append(" INCREMENT BY ")
212                 .append(getPkCacheSize())
213                 .append(" NO MAXVALUE ")
214                 .append(" NO CYCLE ")
215                 .append(" CACHE ")
216                 .append(getPkCacheSize());
217         return buf.toString();
218     }
219 }
220
Popular Tags