1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.dao.orm.hibernate;
24  
25  import com.liferay.portal.kernel.dao.jdbc.DataAccess;
26  import com.liferay.portal.tools.sql.DBUtil;
27  
28  import java.sql.CallableStatement;
29  import java.sql.Connection;
30  import java.sql.DatabaseMetaData;
31  import java.sql.ResultSet;
32  import java.sql.SQLException;
33  
34  import java.util.Enumeration;
35  import java.util.Map;
36  import java.util.Properties;
37  import java.util.Set;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  
42  import org.hibernate.HibernateException;
43  import org.hibernate.LockMode;
44  import org.hibernate.MappingException;
45  import org.hibernate.dialect.DB2400Dialect;
46  import org.hibernate.dialect.Dialect;
47  import org.hibernate.dialect.DialectFactory;
48  import org.hibernate.dialect.SybaseDialect;
49  import org.hibernate.dialect.lock.LockingStrategy;
50  import org.hibernate.exception.SQLExceptionConverter;
51  import org.hibernate.exception.ViolatedConstraintNameExtracter;
52  import org.hibernate.persister.entity.Lockable;
53  import org.hibernate.sql.CaseFragment;
54  import org.hibernate.sql.JoinFragment;
55  
56  /**
57   * <a href="DynamicDialect.java.html"><b><i>View Source</i></b></a>
58   *
59   * @author Brian Wing Shun Chan
60   * @author Bruno Farache
61   *
62   */
63  public class DynamicDialect extends Dialect {
64  
65      public DynamicDialect() {
66  
67          // Instantiate the proper dialect
68  
69          Connection con = null;
70  
71          try {
72              con = DataAccess.getConnection();
73  
74              DatabaseMetaData metaData = con.getMetaData();
75  
76              String dbName = metaData.getDatabaseProductName();
77              int dbMajorVersion = metaData.getDatabaseMajorVersion();
78  
79              if (_log.isInfoEnabled()) {
80                  _log.info(
81                      "Determining dialect for " + dbName + " " + dbMajorVersion);
82              }
83  
84              if (dbName.startsWith("HSQL")) {
85                  if (_log.isWarnEnabled()) {
86                      _log.warn(
87                          "Liferay is configured to use Hypersonic as its " +
88                              "database. Do NOT use Hypersonic in production. " +
89                                  "Hypersonic is an embedded database useful " +
90                                      "for development and demo'ing purposes.");
91                  }
92              }
93  
94              if (dbName.equals("ASE") && (dbMajorVersion == 15)) {
95                  _dialect = new SybaseDialect();
96              }
97              else if (dbName.startsWith("DB2") && (dbMajorVersion == 9)) {
98                  _dialect = new DB2Dialect();
99              }
100             else {
101                 _dialect = DialectFactory.determineDialect(
102                     dbName, dbMajorVersion);
103             }
104 
105             DBUtil.setInstance(_dialect);
106 
107             if (_log.isInfoEnabled()) {
108                 _log.info("Using dialect " + _dialect.getClass().getName());
109             }
110         }
111         catch (Exception e) {
112             String msg = e.getMessage();
113 
114             if (msg.indexOf("explicitly set for database: DB2") != -1) {
115                 _dialect = new DB2400Dialect();
116 
117                 if (_log.isWarnEnabled()) {
118                     _log.warn(
119                         "DB2400Dialect was dynamically chosen as the " +
120                             "Hibernate dialect for DB2. This can be " +
121                                 "overriden in portal.properties");
122                 }
123             }
124             else {
125                 _log.error(e, e);
126             }
127         }
128         finally {
129             DataAccess.cleanUp(con);
130         }
131 
132         if (_dialect == null) {
133             throw new RuntimeException("No dialect found");
134         }
135 
136         // Synchorize default properties
137 
138         Properties dynamicDefaultProps = getDefaultProperties();
139         Properties dialectDefaultProps = _dialect.getDefaultProperties();
140 
141         dynamicDefaultProps.clear();
142 
143         Enumeration<String> enu =
144             (Enumeration<String>)dialectDefaultProps.propertyNames();
145 
146         while (enu.hasMoreElements()) {
147             String key = enu.nextElement();
148 
149             String value = dialectDefaultProps.getProperty(key);
150 
151             dynamicDefaultProps.setProperty(key, value);
152         }
153     }
154 
155     public Dialect getWrappedDialect() {
156         return _dialect;
157     }
158 
159     public String appendIdentitySelectToInsert(String insertSQL) {
160         return _dialect.appendIdentitySelectToInsert(insertSQL);
161     }
162 
163     public String appendLockHint(LockMode mode, String tableName) {
164         return _dialect.appendLockHint(mode, tableName);
165     }
166 
167     public String applyLocksToSql(
168         String sql, Map aliasedLockModes, Map keyColumnNames) {
169 
170         return _dialect.applyLocksToSql(sql, aliasedLockModes, keyColumnNames);
171     }
172 
173     public boolean areStringComparisonsCaseInsensitive() {
174         return _dialect.areStringComparisonsCaseInsensitive();
175     }
176 
177     public boolean bindLimitParametersFirst() {
178         return _dialect.bindLimitParametersFirst();
179     }
180 
181     public boolean bindLimitParametersInReverseOrder() {
182         return _dialect.bindLimitParametersInReverseOrder();
183     }
184 
185     public SQLExceptionConverter buildSQLExceptionConverter() {
186         return _dialect.buildSQLExceptionConverter();
187     }
188 
189     public char closeQuote() {
190         return _dialect.closeQuote();
191     }
192 
193     public CaseFragment createCaseFragment() {
194         return _dialect.createCaseFragment();
195     }
196 
197     public JoinFragment createOuterJoinFragment() {
198         return _dialect.createOuterJoinFragment();
199     }
200 
201     public boolean doesReadCommittedCauseWritersToBlockReaders() {
202         return _dialect.doesReadCommittedCauseWritersToBlockReaders();
203     }
204 
205     public boolean doesRepeatableReadCauseReadersToBlockWriters() {
206         return _dialect.doesRepeatableReadCauseReadersToBlockWriters();
207     }
208 
209     public boolean dropConstraints() {
210         return _dialect.dropConstraints();
211     }
212 
213     public boolean dropTemporaryTableAfterUse() {
214         return _dialect.dropTemporaryTableAfterUse();
215     }
216 
217     public boolean forUpdateOfColumns() {
218         return _dialect.forUpdateOfColumns();
219     }
220 
221     public String generateTemporaryTableName(String baseTableName) {
222         return _dialect.generateTemporaryTableName(baseTableName);
223     }
224 
225     public String getAddColumnString() {
226         return _dialect.getAddColumnString();
227     }
228 
229     public String getAddForeignKeyConstraintString(
230         String constraintName, String[] foreignKey, String referencedTable,
231         String[] primaryKey, boolean referencesPrimaryKey) {
232 
233         return _dialect.getAddForeignKeyConstraintString(
234             constraintName, foreignKey, referencedTable, primaryKey,
235             referencesPrimaryKey);
236     }
237 
238     public String getAddPrimaryKeyConstraintString(String constraintName) {
239         return _dialect.getAddPrimaryKeyConstraintString(constraintName);
240     }
241 
242     public String getCascadeConstraintsString() {
243         return _dialect.getCascadeConstraintsString();
244     }
245 
246     public String getCastTypeName(int code) {
247         return _dialect.getCastTypeName(code);
248     }
249 
250     public String getColumnComment(String comment) {
251         return _dialect.getColumnComment(comment);
252     }
253 
254     public String getCreateMultisetTableString() {
255         return _dialect.getCreateMultisetTableString();
256     }
257 
258     /**
259      * @deprecated
260      */
261     public String[] getCreateSequenceStrings(String sequenceName)
262         throws MappingException {
263 
264         return _dialect.getCreateSequenceStrings(sequenceName);
265     }
266 
267     public String[] getCreateSequenceStrings(
268             String sequenceName, int initialValue, int incrementSize)
269         throws MappingException {
270 
271         return _dialect.getCreateSequenceStrings(
272             sequenceName, initialValue, incrementSize);
273     }
274 
275     public String getCreateTableString() {
276         return _dialect.getCreateTableString();
277     }
278 
279     public String getCreateTemporaryTablePostfix() {
280         return _dialect.getCreateTemporaryTablePostfix();
281     }
282 
283     public String getCreateTemporaryTableString() {
284         return _dialect.getCreateTemporaryTableString();
285     }
286 
287     public String getCurrentTimestampSelectString() {
288         return _dialect.getCurrentTimestampSelectString();
289     }
290 
291     public String getCurrentTimestampSQLFunctionName() {
292         return _dialect.getCurrentTimestampSQLFunctionName();
293     }
294 
295     public String getDropForeignKeyString() {
296         return _dialect.getDropForeignKeyString();
297     }
298 
299     public String[] getDropSequenceStrings(String sequenceName)
300         throws MappingException {
301 
302         return _dialect.getDropSequenceStrings(sequenceName);
303     }
304 
305     public String getForUpdateNowaitString() {
306         return _dialect.getForUpdateNowaitString();
307     }
308 
309     public String getForUpdateNowaitString(String aliases) {
310         return _dialect.getForUpdateNowaitString(aliases);
311     }
312 
313     public String getForUpdateString() {
314         return _dialect.getForUpdateString();
315     }
316 
317     public String getForUpdateString(LockMode lockMode) {
318         return _dialect.getForUpdateString(lockMode);
319     }
320 
321     public String getForUpdateString(String aliases) {
322         return _dialect.getForUpdateString(aliases);
323     }
324 
325     public String getHibernateTypeName(int code) throws HibernateException {
326         return _dialect.getHibernateTypeName(code);
327     }
328 
329     public String getHibernateTypeName(
330             int code, int length, int precision, int scale)
331         throws HibernateException {
332 
333         return _dialect.getHibernateTypeName(code, length, precision, scale);
334     }
335 
336     public String getIdentityColumnString(int type) throws MappingException {
337         return _dialect.getIdentityColumnString(type);
338     }
339 
340     public String getIdentityInsertString() {
341         return _dialect.getIdentityInsertString();
342     }
343 
344     public String getIdentitySelectString(String table, String column, int type)
345         throws MappingException {
346 
347         return _dialect.getIdentitySelectString(table, column, type);
348     }
349 
350     public Set<String> getKeywords() {
351         return _dialect.getKeywords();
352     }
353 
354     public String getLimitString(String querySelect, int hasOffset, int limit) {
355         return _dialect.getLimitString(querySelect, hasOffset, limit);
356     }
357 
358     public LockingStrategy getLockingStrategy(
359         Lockable lockable, LockMode lockMode) {
360 
361         return _dialect.getLockingStrategy(lockable, lockMode);
362     }
363 
364     public String getLowercaseFunction() {
365         return _dialect.getLowercaseFunction();
366     }
367 
368     public int getMaxAliasLength() {
369         return _dialect.getMaxAliasLength();
370     }
371 
372     public Class<?> getNativeIdentifierGeneratorClass() {
373         return _dialect.getNativeIdentifierGeneratorClass();
374     }
375 
376     public String getNoColumnsInsertString() {
377         return _dialect.getNoColumnsInsertString();
378     }
379 
380     public String getNullColumnString() {
381         return _dialect.getNullColumnString();
382     }
383 
384     public String getQuerySequencesString() {
385         return _dialect.getQuerySequencesString();
386     }
387 
388     public ResultSet getResultSet(CallableStatement ps) throws SQLException {
389         return _dialect.getResultSet(ps);
390     }
391 
392     public String getSelectClauseNullString(int sqlType) {
393         return _dialect.getSelectClauseNullString(sqlType);
394     }
395 
396     public String getSelectGUIDString() {
397         return _dialect.getSelectGUIDString();
398     }
399 
400     public String getSelectSequenceNextValString(String sequenceName)
401         throws MappingException {
402 
403         return _dialect.getSelectSequenceNextValString(sequenceName);
404     }
405 
406     public String getSequenceNextValString(String sequenceName)
407         throws MappingException {
408 
409         return _dialect.getSequenceNextValString(sequenceName);
410     }
411 
412     public String getTableComment(String comment) {
413         return _dialect.getTableComment(comment);
414     }
415 
416     public String getTableTypeString() {
417         return _dialect.getTableTypeString();
418     }
419 
420     public String getTypeName(int code) throws HibernateException {
421         return _dialect.getTypeName(code);
422     }
423 
424     public String getTypeName(int code, int length, int precision, int scale)
425         throws HibernateException {
426 
427         return _dialect.getTypeName(code, length, precision, scale);
428     }
429 
430     public ViolatedConstraintNameExtracter
431         getViolatedConstraintNameExtracter() {
432 
433         return _dialect.getViolatedConstraintNameExtracter();
434     }
435 
436     public boolean hasAlterTable() {
437         return _dialect.hasAlterTable();
438     }
439 
440     public boolean hasDataTypeInIdentityColumn() {
441         return _dialect.hasDataTypeInIdentityColumn();
442     }
443 
444     public boolean hasSelfReferentialForeignKeyBug() {
445         return _dialect.hasSelfReferentialForeignKeyBug();
446     }
447 
448     public boolean isCurrentTimestampSelectStringCallable() {
449         return _dialect.isCurrentTimestampSelectStringCallable();
450     }
451 
452     public char openQuote() {
453         return _dialect.openQuote();
454     }
455 
456     public Boolean performTemporaryTableDDLInIsolation() {
457         return _dialect.performTemporaryTableDDLInIsolation();
458     }
459 
460     public boolean qualifyIndexName() {
461         return _dialect.qualifyIndexName();
462     }
463 
464     public int registerResultSetOutParameter(
465             CallableStatement statement, int col)
466         throws SQLException {
467 
468         return _dialect.registerResultSetOutParameter(statement, col);
469     }
470 
471     public boolean supportsBindAsCallableArgument() {
472         return _dialect.supportsBindAsCallableArgument();
473     }
474 
475     public boolean supportsCascadeDelete() {
476         return _dialect.supportsCascadeDelete();
477     }
478 
479     public boolean supportsCircularCascadeDeleteConstraints() {
480         return _dialect.supportsCircularCascadeDeleteConstraints();
481     }
482 
483     public boolean supportsColumnCheck() {
484         return _dialect.supportsColumnCheck();
485     }
486 
487     public boolean supportsCommentOn() {
488         return _dialect.supportsCommentOn();
489     }
490 
491     public boolean supportsCurrentTimestampSelection() {
492         return _dialect.supportsCurrentTimestampSelection();
493     }
494 
495     public boolean supportsEmptyInList() {
496         return _dialect.supportsEmptyInList();
497     }
498 
499     public boolean supportsExistsInSelect() {
500         return _dialect.supportsExistsInSelect();
501     }
502 
503     public boolean supportsExpectedLobUsagePattern() {
504         return _dialect.supportsExpectedLobUsagePattern();
505     }
506 
507     public boolean supportsIdentityColumns() {
508         return _dialect.supportsIdentityColumns();
509     }
510 
511     public boolean supportsIfExistsAfterTableName() {
512         return _dialect.supportsIfExistsAfterTableName();
513     }
514 
515     public boolean supportsIfExistsBeforeTableName() {
516         return _dialect.supportsIfExistsBeforeTableName();
517     }
518 
519     public boolean supportsInsertSelectIdentity() {
520         return _dialect.supportsInsertSelectIdentity();
521     }
522 
523     public boolean supportsLimit() {
524         return _dialect.supportsLimit();
525     }
526 
527     public boolean supportsLimitOffset() {
528         return _dialect.supportsLimitOffset();
529     }
530 
531     public boolean supportsLobValueChangePropogation() {
532         return _dialect.supportsLobValueChangePropogation();
533     }
534 
535     public boolean supportsNotNullUnique() {
536         return _dialect.supportsNotNullUnique();
537     }
538 
539     public boolean supportsOuterJoinForUpdate() {
540         return _dialect.supportsOuterJoinForUpdate();
541     }
542 
543     public boolean supportsParametersInInsertSelect() {
544         return _dialect.supportsParametersInInsertSelect();
545     }
546 
547     public boolean supportsPooledSequences() {
548         return _dialect.supportsPooledSequences();
549     }
550 
551     public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() {
552         return _dialect.
553             supportsResultSetPositionQueryMethodsOnForwardOnlyCursor();
554     }
555 
556     public boolean supportsRowValueConstructorSyntax() {
557         return _dialect.supportsRowValueConstructorSyntax();
558     }
559 
560     public boolean supportsRowValueConstructorSyntaxInInList() {
561         return _dialect.supportsRowValueConstructorSyntaxInInList();
562     }
563 
564     public boolean supportsSequences() {
565         return _dialect.supportsSequences();
566     }
567 
568     public boolean supportsSubqueryOnMutatingTable() {
569         return _dialect.supportsSubqueryOnMutatingTable();
570     }
571 
572     public boolean supportsSubselectAsInPredicateLHS() {
573         return _dialect.supportsSubselectAsInPredicateLHS();
574     }
575 
576     public boolean supportsTableCheck() {
577         return _dialect.supportsTableCheck();
578     }
579 
580     public boolean supportsTemporaryTables() {
581         return _dialect.supportsTemporaryTables();
582     }
583 
584     public boolean supportsUnboundedLobLocatorMaterialization() {
585         return _dialect.supportsUnboundedLobLocatorMaterialization();
586     }
587 
588     public boolean supportsUnionAll() {
589         return _dialect.supportsUnionAll();
590     }
591 
592     public boolean supportsUnique() {
593         return _dialect.supportsUnique();
594     }
595 
596     public boolean supportsUniqueConstraintInCreateAlterTable() {
597         return _dialect.supportsUniqueConstraintInCreateAlterTable();
598     }
599 
600     public boolean supportsVariableLimit() {
601         return _dialect.supportsVariableLimit();
602     }
603 
604     public String toBooleanValueString(boolean bool) {
605         return _dialect.toBooleanValueString(bool);
606     }
607 
608     public String toString() {
609         if (_dialect != null) {
610             return _dialect.toString();
611         }
612         else {
613             return null;
614         }
615     }
616 
617     public String transformSelectString(String select) {
618         return _dialect.transformSelectString(select);
619     }
620 
621     public boolean useInputStreamToInsertBlob() {
622         return _dialect.useInputStreamToInsertBlob();
623     }
624 
625     public boolean useMaxForLimit() {
626         return _dialect.useMaxForLimit();
627     }
628 
629     private static Log _log = LogFactory.getLog(DynamicDialect.class);
630 
631     private Dialect _dialect;
632 
633 }