KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > dialect > function > CastFunction


1 //$Id: CastFunction.java,v 1.7 2005/07/04 02:54:27 oneovthafew Exp $
2
package org.hibernate.dialect.function;
3
4 import java.util.List JavaDoc;
5
6 import org.hibernate.QueryException;
7 import org.hibernate.engine.Mapping;
8 import org.hibernate.engine.SessionFactoryImplementor;
9 import org.hibernate.type.Type;
10 import org.hibernate.type.TypeFactory;
11
12 /**
13  * ANSI-SQL style <tt>cast(foo as type)</tt> where the type is
14  * a Hibernate type
15  * @author Gavin King
16  */

17 public class CastFunction implements SQLFunction {
18
19     public Type getReturnType(Type columnType, Mapping mapping) throws QueryException {
20         return columnType; //note there is a wierd implementation in the client side
21
}
22
23     public boolean hasArguments() {
24         return true;
25     }
26
27     public boolean hasParenthesesIfNoArguments() {
28         return true;
29     }
30
31     public String JavaDoc render(List JavaDoc args, SessionFactoryImplementor factory) throws QueryException {
32         if ( args.size()!=2 ) {
33             throw new QueryException("cast() requires two arguments");
34         }
35         String JavaDoc type = (String JavaDoc) args.get(1);
36         int[] sqlTypeCodes = TypeFactory.heuristicType(type).sqlTypes(factory);
37         if ( sqlTypeCodes.length!=1 ) {
38             throw new QueryException("invalid Hibernate type for cast()");
39         }
40         String JavaDoc sqlType = factory.getDialect().getCastTypeName( sqlTypeCodes[0] );
41         if (sqlType==null) {
42             //TODO: never reached, since getTypeName() actually throws an exception!
43
sqlType = type;
44         }
45         /*else {
46             //trim off the length/precision/scale
47             int loc = sqlType.indexOf('(');
48             if (loc>-1) {
49                 sqlType = sqlType.substring(0, loc);
50             }
51         }*/

52         return "cast(" + args.get(0) + " as " + sqlType + ')';
53     }
54
55 }
56
Popular Tags