1 28 29 package com.caucho.db.sql; 30 31 import com.caucho.log.Log; 32 import com.caucho.util.L10N; 33 34 import java.sql.SQLException ; 35 import java.util.logging.Logger ; 36 37 public class AvgExpr extends FunExpr implements GroupExpr { 38 protected static final L10N L = new L10N(SumExpr.class); 39 private static final Logger log = Log.open(SumExpr.class); 40 41 private Expr _expr; 42 private int _groupField; 43 44 protected void addArg(Expr expr) 45 throws SQLException 46 { 47 if (_expr != null) 48 throw new SQLException (L.l("sum requires a single argument")); 49 50 _expr = expr; 51 } 52 53 56 public Class getType() 57 { 58 return double.class; 59 } 60 61 protected Expr bind(Query query) 62 throws SQLException 63 { 64 _groupField = query.getDataFields(); 65 66 query.setDataFields(_groupField + 2); 67 query.setGroup(true); 68 69 _expr = _expr.bind(query); 70 71 return this; 72 } 73 74 79 public void initGroup(QueryContext context) 80 throws SQLException 81 { 82 context.setGroupDouble(_groupField, 0); 83 context.setGroupDouble(_groupField + 1, 0); 84 } 85 86 91 public void evalGroup(QueryContext context) 92 throws SQLException 93 { 94 if (_expr.isNull(context)) 95 return; 96 97 double count = context.getGroupDouble(_groupField); 98 99 context.setGroupDouble(_groupField, count + 1); 100 101 double value = _expr.evalDouble(context); 102 double sum = context.getGroupDouble(_groupField + 1); 103 104 context.setGroupDouble(_groupField + 1, sum + value); 105 } 106 107 114 public boolean isNull(QueryContext context) 115 throws SQLException 116 { 117 return context.isGroupNull(_groupField); 118 } 119 120 127 public double evalDouble(QueryContext context) 128 throws SQLException 129 { 130 double count = context.getGroupDouble(_groupField); 131 132 if (count == 0) 133 return 0; 134 else 135 return context.getGroupDouble(_groupField + 1) / count; 136 } 137 138 145 public long evalLong(QueryContext context) 146 throws SQLException 147 { 148 return (long) evalDouble(context); 149 } 150 151 158 public String evalString(QueryContext context) 159 throws SQLException 160 { 161 return String.valueOf(evalDouble(context)); 162 } 163 } 164 | Popular Tags |