KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opensubsystems > core > persist > db > db2 > DB2DatabaseImpl


1 /*
2  * Copyright (c) 2003 - 2007 OpenSubsystems s.r.o. Slovak Republic. All rights reserved.
3  *
4  * Project: OpenSubsystems
5  *
6  * $Id: DB2DatabaseImpl.java,v 1.7 2007/01/07 06:14:38 bastafidli Exp $
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; version 2 of the License.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */

21
22 package org.opensubsystems.core.persist.db.db2;
23
24 import java.sql.CallableStatement JavaDoc;
25 import java.sql.Connection JavaDoc;
26 import java.sql.PreparedStatement JavaDoc;
27 import java.sql.SQLException JavaDoc;
28 import java.sql.Statement JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.logging.Level JavaDoc;
31 import java.util.logging.Logger JavaDoc;
32
33 import org.opensubsystems.core.data.BasicDataObject;
34 import org.opensubsystems.core.data.ModifiableDataObject;
35 import org.opensubsystems.core.error.OSSDatabaseAccessException;
36 import org.opensubsystems.core.error.OSSException;
37 import org.opensubsystems.core.persist.db.DatabaseConnectionFactoryImpl;
38 import org.opensubsystems.core.persist.db.DatabaseImpl;
39 import org.opensubsystems.core.persist.db.DatabaseTransactionFactoryImpl;
40 import org.opensubsystems.core.util.DatabaseUtils;
41 import org.opensubsystems.core.util.Log;
42
43 /**
44  * Management layer for IBM DB2 database (www.ibm.com/db2)
45  *
46  * @version $Id: DB2DatabaseImpl.java,v 1.7 2007/01/07 06:14:38 bastafidli Exp $
47  * @author Julo Legeny
48  * @code.reviewer Miro Halas
49  * @code.reviewed 1.2 2006/04/05 05:02:09 bastafidli
50  */

51 public class DB2DatabaseImpl extends DatabaseImpl
52 {
53    // Cached values ////////////////////////////////////////////////////////////
54

55    /**
56     * Logger for this class
57     */

58    private static Logger JavaDoc s_logger = Log.getInstance(DB2DatabaseImpl.class);
59
60    // Constructors /////////////////////////////////////////////////////////////
61

62    /**
63     * Default constructor for empty database.
64     *
65     * @throws OSSException - problem connecting to database
66     */

67    public DB2DatabaseImpl(
68    ) throws OSSException
69    {
70       super();
71    }
72    
73    // Database administration //////////////////////////////////////////////////
74

75    /**
76     * {@inheritDoc}
77     *
78     * Note: For DB2 there must exist username within the OS
79     */

80    protected void createUser(
81       Connection JavaDoc cntAdminDBConnection
82    ) throws OSSException
83    {
84       // Now create the user
85
// !!! IMPORTANT !!! For DB2 there must exist username within the OS
86
PreparedStatement JavaDoc pstmQuery = null;
87       try
88       {
89          StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
90          
91          buffer.append("GRANT CONNECT, CREATETAB ON DATABASE TO USER ");
92          buffer.append(DatabaseConnectionFactoryImpl.getInstance().getDatabaseUser());
93
94          pstmQuery = cntAdminDBConnection.prepareStatement(buffer.toString());
95          if (pstmQuery.execute())
96          {
97             // Close any results
98
pstmQuery.getMoreResults(Statement.CLOSE_ALL_RESULTS);
99          }
100
101          // At this point we don't know if this is just a single operation
102
// and we need to commit or if it is a part of bigger transaction
103
// and the commit is not desired until all operations proceed.
104
// Therefore let the DatabaseTransactionFactory resolve it
105
DatabaseTransactionFactoryImpl.getInstance().commitTransaction(
106                                                  cntAdminDBConnection);
107          
108          s_logger.log(Level.FINER, "Database user "
109                              + DatabaseConnectionFactoryImpl.getInstance().getDatabaseUser()
110                              + " with password "
111                              + DatabaseConnectionFactoryImpl.getInstance().getDatabasePassword()
112                              + " created.");
113       }
114       catch (SQLException JavaDoc sqleExc)
115       {
116          try
117          {
118             // At this point we don't know if this is just a single operation
119
// and we need to commit or if it is a part of bigger transaction
120
// and the commit is not desired until all operations proceed.
121
// Therefore let the DatabaseTransactionFactory resolve it
122
DatabaseTransactionFactoryImpl.getInstance().rollbackTransaction(
123                cntAdminDBConnection);
124          }
125          catch (SQLException JavaDoc sqleExc2)
126          {
127             // Ignore this
128
s_logger.log(Level.WARNING,
129                                 "Failed to rollback changes for creation of user.",
130                                 sqleExc2);
131          }
132          s_logger.log(Level.SEVERE,
133                              "Unable to create default database user.",
134                              sqleExc);
135          throw new OSSDatabaseAccessException("Unable to create default database user.",
136                                               sqleExc);
137       }
138       finally
139       {
140          DatabaseUtils.closeStatement(pstmQuery);
141       }
142    }
143
144    /**
145     * {@inheritDoc}
146     */

147    public void startDatabaseServer() throws OSSException
148    {
149       // TODO: Feature: Implement starting database server
150
}
151
152    /**
153     * {@inheritDoc}
154     */

155    public void createDatabaseInstance() throws OSSException
156    {
157       // TODO: Feature: Implement creating database instance
158
}
159
160    /**
161     * {@inheritDoc}
162     */

163    public void stop(
164    ) throws OSSException
165    {
166       s_logger.entering(this.getClass().getName(), "stop");
167
168       // TODO: Feature: Implement this so we can safely stop the database when
169
// the application is finished.
170
super.stop();
171
172       s_logger.entering(this.getClass().getName(), "stop");
173    }
174
175    /**
176     * {@inheritDoc}
177     */

178    public int getDatabaseType()
179    {
180       return DatabaseImpl.DB2_DATABASE_TYPE;
181    }
182
183    /**
184     * {@inheritDoc}
185     */

186    public String JavaDoc getDatabaseTypeIdentifier()
187    {
188       return DatabaseImpl.DB2_DATABASE_TYPE_IDENTIFIER;
189    }
190
191    /**
192     * {@inheritDoc}
193     */

194    public String JavaDoc getCurrentTimestampFunctionCall()
195    {
196       // IBM DB2 requries use select into particular system table
197
return "CURRENT TIMESTAMP";
198    }
199
200    /**
201     * {@inheritDoc}
202     */

203    public String JavaDoc getSQLCountFunctionCall()
204    {
205       // For DB2 is best for performance use COUNT(*)
206
return "count(*)";
207    }
208
209    /**
210     * {@inheritDoc}
211     */

212    public boolean preferCountToLast(
213    )
214    {
215       // For IBM DB2 it is generally faster to execute count(1) than to do last().
216
// We can speed up performance by using select ... ROWNUMBER() ... that allows us
217
// to retrieve just specified range of items. But when we use ROWNUMBER()
218
// we cannot use last()
219
return true;
220    }
221
222    /**
223     * {@inheritDoc}
224     */

225    public boolean hasSelectListRangeSupport(
226    )
227    {
228       // IBM DB2 supports rows limitation by using clause ROWNUMBER()
229
return true;
230    }
231
232    /**
233     * {@inheritDoc}
234     */

235    public Object JavaDoc[] getSQLAnalyzeFunctionCall(
236       Map JavaDoc mapTableNames
237    )
238    {
239       // TODO: For Julo: Find out how to update statistics for a table in db2.
240
// following code is commented becouse it works just for installed db2 fixpack7
241
/*
242       // IBM DB2 uses RUNSTATS ON TABLE <tablename> WITH DISTRIBUTION AND INDEXES ALL to
243       // update indexes and increase performance.
244       StringBuffer buffer = new StringBuffer();
245       Iterator itItem;
246       int iIndex = 0;
247
248       itItem = mapTableNames.values().iterator();
249       while (itItem.hasNext())
250       {
251          // construct analyze query for each table from the array
252          buffer.append("RUNSTATS ON TABLE ");
253          buffer.append((String)itItem.next());
254          buffer.append(" WITH DISTRIBUTION AND INDEXES ALL; ");
255       }
256
257       return buffer.toString();
258       */

259       return null;
260    }
261
262    /**
263     * {@inheritDoc}
264     */

265    public boolean isCallableStatement(
266       String JavaDoc strQuery
267    )
268    {
269       return strQuery.indexOf("call ") != -1;
270    }
271
272    /**
273     * {@inheritDoc}
274     */

275    public void insertAndFetchGeneratedValues(
276       Connection JavaDoc dbConnection,
277       PreparedStatement JavaDoc insertStatement,
278       boolean bIsInDomain,
279       String JavaDoc strTableName,
280       int iIndex,
281       BasicDataObject data
282    ) throws SQLException JavaDoc,
283             OSSException
284    {
285       DB2DataUtils.insertAndFetchGeneratedValues((CallableStatement JavaDoc)insertStatement,
286                                                  iIndex, data);
287    }
288
289    /**
290     * {@inheritDoc}
291     */

292    public void updatedAndFetchGeneratedValues(
293       String JavaDoc strDataName,
294       Connection JavaDoc dbConnection,
295       PreparedStatement JavaDoc updateStatement,
296       boolean bIsInDomain,
297       String JavaDoc strTableName,
298       int iIndex,
299       ModifiableDataObject data
300    ) throws SQLException JavaDoc,
301             OSSException
302    {
303       DB2DataUtils.updateAndFetchGeneratedValues((CallableStatement JavaDoc)updateStatement,
304                                                  iIndex, data);
305    }
306 }
307
Popular Tags