KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > dba > openbase > OpenBasePkGenerator


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56 package org.objectstyle.cayenne.dba.openbase;
57
58 import java.sql.Connection JavaDoc;
59 import java.sql.ResultSet JavaDoc;
60 import java.sql.Statement JavaDoc;
61 import java.util.ArrayList JavaDoc;
62 import java.util.Collections JavaDoc;
63 import java.util.Iterator JavaDoc;
64 import java.util.List JavaDoc;
65
66 import org.objectstyle.cayenne.CayenneRuntimeException;
67 import org.objectstyle.cayenne.access.DataNode;
68 import org.objectstyle.cayenne.access.QueryLogger;
69 import org.objectstyle.cayenne.dba.JdbcPkGenerator;
70 import org.objectstyle.cayenne.map.DbAttribute;
71 import org.objectstyle.cayenne.map.DbEntity;
72 import org.objectstyle.cayenne.map.DerivedDbEntity;
73
74 /**
75  * @author <a HREF="mailto:mkienenb@alaska.net">Mike Kienenberger</a>
76  * @author Andrei Adamchik
77  *
78  * @since 1.1
79  */

80 public class OpenBasePkGenerator extends JdbcPkGenerator {
81
82     /**
83      * @deprecated Since 1.2 corresponding interface method is unused and deprecated.
84      */

85     public String JavaDoc generatePkForDbEntityString(DbEntity ent) {
86         return newIDString(ent);
87     }
88
89     /**
90      * Returns a non-repeating primary key for a given entity. Since
91      * OpenBase-specific mechanism is used, key caching is disabled.
92      * Instead a database operation is performed on every call.
93      */

94     public Object JavaDoc generatePkForDbEntity(DataNode node, DbEntity entity)
95         throws Exception JavaDoc {
96         // check for binary pk
97
Object JavaDoc binPK = binaryPK(entity);
98         if (binPK != null) {
99             return binPK;
100         }
101         return new Integer JavaDoc(pkFromDatabase(node, entity));
102     }
103
104     /**
105      * Generates new (unique and non-repeating) primary key for specified
106      * DbEntity. Executed SQL looks like this:
107      *
108      * <pre>NEWID FOR Table Column</pre>
109      *
110      * COLUMN must be marked as UNIQUE in order for this to work properly.
111      */

112     protected int pkFromDatabase(DataNode node, DbEntity entity) throws Exception JavaDoc {
113         String JavaDoc sql = newIDString(entity);
114         QueryLogger.logQuery(QueryLogger.DEFAULT_LOG_LEVEL, sql, Collections.EMPTY_LIST);
115
116         Connection JavaDoc con = node.getDataSource().getConnection();
117         try {
118             Statement JavaDoc st = con.createStatement();
119             try {
120
121                 ResultSet JavaDoc rs = st.executeQuery(sql);
122                 try {
123                     //Object pk = null;
124
if (!rs.next()) {
125                         throw new CayenneRuntimeException(
126                             "Error generating pk for DbEntity " + entity.getName());
127                     }
128                     return rs.getInt(1);
129                 }
130                 finally {
131                     rs.close();
132                 }
133             }
134             finally {
135                 st.close();
136             }
137         }
138         finally {
139             con.close();
140         }
141     }
142
143     /**
144      * Returns SQL string that can generate new (unique and non-repeating)
145      * primary key for specified DbEntity. No actual database operations
146      * are performed.
147      *
148      * @since 1.2
149      */

150     protected String JavaDoc newIDString(DbEntity ent) {
151         if ((null == ent.getPrimaryKey()) || (1 != ent.getPrimaryKey().size())) {
152             throw new CayenneRuntimeException(
153                 "Error generating pk for DbEntity "
154                     + ent.getName()
155                     + ": pk must be single attribute");
156         }
157         DbAttribute primaryKeyAttribute = (DbAttribute) ent.getPrimaryKey().get(0);
158
159         StringBuffer JavaDoc buf = new StringBuffer JavaDoc("NEWID FOR ");
160         buf.append(ent.getName()).append(' ').append(primaryKeyAttribute.getName());
161         return buf.toString();
162     }
163     
164     public void createAutoPk(DataNode node, List JavaDoc dbEntities) throws Exception JavaDoc {
165         // looks like generating a PK on top of an existing one does not
166
// result in errors...
167

168         // create needed sequences
169
Iterator JavaDoc it = dbEntities.iterator();
170         while (it.hasNext()) {
171             DbEntity entity = (DbEntity) it.next();
172
173             // the caller must take care of giving us the right entities
174
// but lets check anyway
175
if (!canCreatePK(entity)) {
176                 continue;
177             }
178
179             runUpdate(node, createPKString(entity));
180             runUpdate(node, createUniquePKIndexString(entity));
181         }
182     }
183
184     /**
185      *
186      */

187     public List JavaDoc createAutoPkStatements(List JavaDoc dbEntities) {
188         List JavaDoc list = new ArrayList JavaDoc(2 * dbEntities.size());
189         Iterator JavaDoc it = dbEntities.iterator();
190         while (it.hasNext()) {
191             DbEntity entity = (DbEntity) it.next();
192
193             // the caller must take care of giving us the right entities
194
// but lets check anyway
195
if (!canCreatePK(entity)) {
196                 continue;
197             }
198
199             list.add(createPKString(entity));
200             list.add(createUniquePKIndexString(entity));
201         }
202
203         return list;
204     }
205
206     protected boolean canCreatePK(DbEntity entity) {
207         if (entity instanceof DerivedDbEntity) {
208             return false;
209         }
210
211         List JavaDoc pk = entity.getPrimaryKey();
212         if (pk == null || pk.size() == 0) {
213             return false;
214         }
215         return true;
216     }
217
218     /**
219      *
220      */

221     public void dropAutoPk(DataNode node, List JavaDoc dbEntities) throws Exception JavaDoc {
222         // there is no simple way to do that... probably requires
223
// editing metadata tables...
224
// Good thing is that it doesn't matter, since PK support
225
// is attached to the table itself, so if a table is dropped,
226
// it will be dropped as well
227
}
228
229     /**
230      * Returns an empty list, since OpenBase doesn't support this operation.
231      */

232     public List JavaDoc dropAutoPkStatements(List JavaDoc dbEntities) {
233         return Collections.EMPTY_LIST;
234     }
235
236     /**
237      * Returns a String to create PK support for an entity.
238      */

239     protected String JavaDoc createPKString(DbEntity entity) {
240         List JavaDoc pk = entity.getPrimaryKey();
241
242         if (pk == null || pk.size() == 0) {
243             throw new CayenneRuntimeException(
244                 "Entity '" + entity.getName() + "' has no PK defined.");
245         }
246
247         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
248         buffer.append("CREATE PRIMARY KEY ").append(entity.getName()).append(" (");
249
250         Iterator JavaDoc it = pk.iterator();
251
252         // at this point we know that there is at least on PK column
253
DbAttribute firstColumn = (DbAttribute) it.next();
254         buffer.append(firstColumn.getName());
255
256         while (it.hasNext()) {
257             DbAttribute column = (DbAttribute) it.next();
258             buffer.append(", ").append(column.getName());
259         }
260
261         buffer.append(")");
262         return buffer.toString();
263     }
264
265     /**
266      * Returns a String to create a unique index on table primary key columns per
267      * OpenBase recommendations.
268      */

269     protected String JavaDoc createUniquePKIndexString(DbEntity entity) {
270         List JavaDoc pk = entity.getPrimaryKey();
271
272         if (pk == null || pk.size() == 0) {
273             throw new CayenneRuntimeException(
274                 "Entity '" + entity.getName() + "' has no PK defined.");
275         }
276
277         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
278
279         // compound PK doesn't work well with UNIQUE index...
280
// create a regular one in this case
281
buffer
282             .append(pk.size() == 1 ? "CREATE UNIQUE INDEX " : "CREATE INDEX ")
283             .append(entity.getName())
284             .append(" (");
285
286         Iterator JavaDoc it = pk.iterator();
287
288         // at this point we know that there is at least on PK column
289
DbAttribute firstColumn = (DbAttribute) it.next();
290         buffer.append(firstColumn.getName());
291
292         while (it.hasNext()) {
293             DbAttribute column = (DbAttribute) it.next();
294             buffer.append(", ").append(column.getName());
295         }
296         buffer.append(")");
297         return buffer.toString();
298     }
299
300     public void reset() {
301         // noop
302
}
303
304     /**
305      * Returns zero, since PK caching is not feasible with OpenBase PK
306      * generation mechanism.
307      */

308     public int getPkCacheSize() {
309         return 0;
310     }
311
312     public void setPkCacheSize(int pkCacheSize) {
313         // noop, no PK caching
314
}
315
316 }
Popular Tags