1 package com.quadcap.sql; 2 3 40 41 import java.io.IOException ; 42 43 import java.util.Vector ; 44 45 import java.sql.SQLException ; 46 47 import com.quadcap.util.Debug; 48 49 56 public class AggregateCursor extends FilterCursor { 57 GroupByCursor gcursor = null; 58 Vector aggregates = null; 59 Row row = null; 60 int currentRowNum = 0; 61 boolean first = true; 62 boolean isItemCursor = false; 63 ItemsCursor itemsCursor = null; 64 Cursor baseCursor = null; 65 66 public AggregateCursor(Session session, Cursor cursor, 67 GroupByCursor gcursor, 68 Vector aggregates) throws SQLException { 69 super(session, cursor); 70 isItemCursor = (cursor instanceof ItemsCursor); 71 if (isItemCursor) { 72 itemsCursor = (ItemsCursor)cursor; 73 baseCursor = itemsCursor.getBaseCursor(); 74 } else { 75 baseCursor = cursor; 76 } 77 this.gcursor = gcursor; 78 this.aggregates = aggregates; 79 } 80 81 public void resetAggregates() throws SQLException { 82 if (aggregates != null) { 83 for (int i = 0; i < aggregates.size(); i++) { 84 try { 85 ((AggregateExpression)aggregates.elementAt(i)).reset(session); 86 } catch (IOException e) { 87 throw DbException.wrapThrowable(e); 88 } 89 } 90 } 91 } 92 93 public void updateAggregates(Cursor c) throws SQLException { 94 if (aggregates != null) { 95 for (int i = 0; i < aggregates.size(); i++) { 96 AggregateExpression ae = 97 (AggregateExpression)aggregates.elementAt(i); 98 ae.updateAggregate(session, c); 99 } 100 } 101 } 102 103 public Row getRow() throws SQLException { 104 return row; 105 } 106 107 public void updateRow(Row row) throws SQLException { 108 throw new SQLException ("Aggregate expressions aren't updateable", 109 "42000"); 110 } 111 112 public void deleteRow() throws SQLException { 113 throw new SQLException ("Aggregate expressions aren't updateable", 114 "42000"); 115 } 116 117 public void beforeFirst() throws SQLException { 118 cursor.beforeFirst(); 119 first = true; 120 } 121 122 132 public boolean next() throws SQLException { 133 boolean any = false; 134 boolean ret = first; 135 first = false; 136 resetAggregates(); 137 while (cursor.next()) { 138 updateAggregates(baseCursor); 139 ret = true; 140 if (gcursor != null && gcursor.lastRowOfGroup()) { 141 any = true; 142 break; 143 } 144 } 145 if (ret) { 146 if (isItemCursor) { 147 if (any) { 148 row = cursor.getRow(); 149 if (row == null) { 150 row = itemsCursor.getEmptyAggregate(); 151 } 152 } else if (gcursor == null) { 153 row = itemsCursor.getEmptyAggregate(); 154 } else { 155 ret = false; 156 } 157 } else { 158 ret = false; 159 } 160 } 161 return ret; 162 } 163 164 public boolean isWritable(int col) throws SQLException { 165 return false; 166 } 167 168 171 public long size() { return -1; } 172 173 public void close() throws SQLException { 174 resetAggregates(); 175 cursor.close(); 176 } 177 } 178 | Popular Tags |