1 package org.hibernate.dialect.function; 3 4 import org.hibernate.QueryException; 5 import org.hibernate.engine.Mapping; 6 import org.hibernate.engine.SessionFactoryImplementor; 7 import org.hibernate.type.Type; 8 9 import java.util.ArrayList ; 10 import java.util.List ; 11 12 23 public class SQLFunctionTemplate implements SQLFunction { 24 private final Type type; 25 private final boolean hasArguments; 26 private final boolean hasParenthesesIfNoArgs; 27 28 private final String template; 29 private final String [] chunks; 30 private final int[] paramIndexes; 31 32 public SQLFunctionTemplate(Type type, String template) { 33 this( type, template, true ); 34 } 35 36 public SQLFunctionTemplate(Type type, String template, boolean hasParenthesesIfNoArgs) { 37 this.type = type; 38 this.template = template; 39 40 List chunkList = new ArrayList (); 41 List paramList = new ArrayList (); 42 StringBuffer chunk = new StringBuffer ( 10 ); 43 StringBuffer index = new StringBuffer ( 2 ); 44 45 for ( int i = 0; i < template.length(); ++i ) { 46 char c = template.charAt( i ); 47 if ( c == '?' ) { 48 chunkList.add( chunk.toString() ); 49 chunk.delete( 0, chunk.length() ); 50 51 while ( ++i < template.length() ) { 52 c = template.charAt( i ); 53 if ( Character.isDigit( c ) ) { 54 index.append( c ); 55 } 56 else { 57 chunk.append( c ); 58 break; 59 } 60 } 61 62 paramList.add( new Integer ( Integer.parseInt( index.toString() ) - 1 ) ); 63 index.delete( 0, index.length() ); 64 } 65 else { 66 chunk.append( c ); 67 } 68 } 69 70 if ( chunk.length() > 0 ) { 71 chunkList.add( chunk.toString() ); 72 } 73 74 chunks = ( String [] ) chunkList.toArray( new String [chunkList.size()] ); 75 paramIndexes = new int[paramList.size()]; 76 for ( int i = 0; i < paramIndexes.length; ++i ) { 77 paramIndexes[i] = ( ( Integer ) paramList.get( i ) ).intValue(); 78 } 79 80 hasArguments = paramIndexes.length > 0; 81 this.hasParenthesesIfNoArgs = hasParenthesesIfNoArgs; 82 } 83 84 90 public String render(List args, SessionFactoryImplementor factory) { 91 StringBuffer buf = new StringBuffer (); 92 for ( int i = 0; i < chunks.length; ++i ) { 93 if ( i < paramIndexes.length ) { 94 Object arg = paramIndexes[i] < args.size() ? args.get( paramIndexes[i] ) : null; 95 if ( arg != null ) { 96 buf.append( chunks[i] ).append( arg ); 97 } 98 } 99 else { 100 buf.append( chunks[i] ); 101 } 102 } 103 return buf.toString(); 104 } 105 106 108 public Type getReturnType(Type columnType, Mapping mapping) throws QueryException { 109 return type; 110 } 111 112 public boolean hasArguments() { 113 return hasArguments; 114 } 115 116 public boolean hasParenthesesIfNoArguments() { 117 return hasParenthesesIfNoArgs; 118 } 119 120 public String toString() { 121 return template; 122 } 123 } 124 | Popular Tags |