KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > dba > db2 > DB2Adapter


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
57 package org.objectstyle.cayenne.dba.db2;
58
59 import java.sql.PreparedStatement JavaDoc;
60 import java.util.Iterator JavaDoc;
61
62 import org.objectstyle.cayenne.CayenneRuntimeException;
63 import org.objectstyle.cayenne.access.DataNode;
64 import org.objectstyle.cayenne.access.trans.QualifierTranslator;
65 import org.objectstyle.cayenne.access.trans.QueryAssembler;
66 import org.objectstyle.cayenne.access.types.BooleanType;
67 import org.objectstyle.cayenne.access.types.CharType;
68 import org.objectstyle.cayenne.access.types.ExtendedTypeMap;
69 import org.objectstyle.cayenne.dba.JdbcAdapter;
70 import org.objectstyle.cayenne.dba.PkGenerator;
71 import org.objectstyle.cayenne.dba.TypesMapping;
72 import org.objectstyle.cayenne.map.DbAttribute;
73 import org.objectstyle.cayenne.map.DbEntity;
74 import org.objectstyle.cayenne.map.DerivedDbEntity;
75 import org.objectstyle.cayenne.query.Query;
76 import org.objectstyle.cayenne.query.SQLAction;
77
78 /**
79  * DbAdapter implementation for the <a HREF="http://www.ibm.com/db2/"> DB2 RDBMS </a>.
80  * Sample <a target="_top"
81  * HREF="../../../../../../../developerguide/unit-tests.html">connection settings </a> to
82  * use with DB2 are shown below:
83  *
84  * <pre>
85  *
86  * test-db2.cayenne.adapter = org.objectstyle.cayenne.dba.db2.DB2Adapter
87  * test-db2.jdbc.username = test
88  * test-db2.jdbc.password = secret
89  * test-db2.jdbc.url = jdbc:db2://servername:50000/databasename
90  * test-db2.jdbc.driver = com.ibm.db2.jcc.DB2Driver
91  *
92  * </pre>
93  *
94  * @author Holger Hoffstaette
95  */

96 public class DB2Adapter extends JdbcAdapter {
97
98     /**
99      * Uses DB2ActionBuilder to create the right action.
100      *
101      * @since 1.2
102      */

103     public SQLAction getAction(Query query, DataNode node) {
104         return query.createSQLAction(new DB2ActionBuilder(this, node.getEntityResolver()));
105     }
106
107     /**
108      * Creates a DB2 specific PK Generator.
109      */

110     protected PkGenerator createPkGenerator() {
111         return new DB2PkGenerator();
112     }
113
114     protected void configureExtendedTypes(ExtendedTypeMap map) {
115         super.configureExtendedTypes(map);
116
117         // create specially configured CharType handler
118
map.registerType(new CharType(true, true));
119
120         // configure boolean type to work with numeric columns
121
map.registerType(new DB2BooleanType());
122     }
123
124     /**
125      * Returns a SQL string that can be used to create database table corresponding to
126      * <code>ent</code> parameter.
127      */

128     public String JavaDoc createTable(DbEntity ent) {
129         // later we may support view creation
130
// for derived DbEntities
131
if (ent instanceof DerivedDbEntity) {
132             throw new CayenneRuntimeException("Can't create table for derived DbEntity '"
133                     + ent.getName()
134                     + "'.");
135         }
136
137         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
138         buf.append("CREATE TABLE ").append(ent.getFullyQualifiedName()).append(" (");
139
140         // columns
141
Iterator JavaDoc it = ent.getAttributes().iterator();
142         boolean first = true;
143         while (it.hasNext()) {
144             if (first) {
145                 first = false;
146             }
147             else {
148                 buf.append(", ");
149             }
150
151             DbAttribute at = (DbAttribute) it.next();
152
153             // attribute may not be fully valid, do a simple check
154
if (at.getType() == TypesMapping.NOT_DEFINED) {
155                 throw new CayenneRuntimeException("Undefined type for attribute '"
156                         + ent.getFullyQualifiedName()
157                         + "."
158                         + at.getName()
159                         + "'.");
160             }
161
162             String JavaDoc[] types = externalTypesForJdbcType(at.getType());
163             if (types == null || types.length == 0) {
164                 throw new CayenneRuntimeException("Undefined type for attribute '"
165                         + ent.getFullyQualifiedName()
166                         + "."
167                         + at.getName()
168                         + "': "
169                         + at.getType());
170             }
171
172             String JavaDoc type = types[0];
173             buf.append(at.getName()).append(' ').append(type);
174
175             // append size and precision (if applicable)
176
if (TypesMapping.supportsLength(at.getType())) {
177                 int len = at.getMaxLength();
178                 int prec = TypesMapping.isDecimal(at.getType()) ? at.getPrecision() : -1;
179
180                 // sanity check
181
if (prec > len) {
182                     prec = -1;
183                 }
184
185                 if (len > 0) {
186                     buf.append('(').append(len);
187
188                     if (prec >= 0) {
189                         buf.append(", ").append(prec);
190                     }
191
192                     buf.append(')');
193                 }
194             }
195
196             if (at.isMandatory()) {
197                 buf.append(" NOT NULL");
198             }
199         }
200
201         // primary key clause
202
Iterator JavaDoc pkit = ent.getPrimaryKey().iterator();
203         if (pkit.hasNext()) {
204             if (first)
205                 first = false;
206             else
207                 buf.append(", ");
208
209             buf.append("PRIMARY KEY (");
210             boolean firstPk = true;
211             while (pkit.hasNext()) {
212                 if (firstPk)
213                     firstPk = false;
214                 else
215                     buf.append(", ");
216
217                 DbAttribute at = (DbAttribute) pkit.next();
218                 buf.append(at.getName());
219             }
220             buf.append(')');
221         }
222         buf.append(')');
223         return buf.toString();
224     }
225
226     /**
227      * Returns a trimming translator.
228      */

229     public QualifierTranslator getQualifierTranslator(QueryAssembler queryAssembler) {
230         return new DB2QualifierTranslator(queryAssembler, "RTRIM");
231     }
232
233     final class DB2BooleanType extends BooleanType {
234
235         public void setJdbcObject(
236                 PreparedStatement JavaDoc st,
237                 Object JavaDoc val,
238                 int pos,
239                 int type,
240                 int precision) throws Exception JavaDoc {
241
242             if (val != null) {
243                 st.setInt(pos, ((Boolean JavaDoc) val).booleanValue() ? 1 : 0);
244             }
245             else {
246                 st.setNull(pos, type);
247             }
248         }
249     }
250
251 }
Popular Tags