KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > derby > impl > sql > compile > GroupByList


1 /*
2
3    Derby - Class org.apache.derby.impl.sql.compile.GroupByList
4
5    Licensed to the Apache Software Foundation (ASF) under one or more
6    contributor license agreements. See the NOTICE file distributed with
7    this work for additional information regarding copyright ownership.
8    The ASF licenses this file to you under the Apache License, Version 2.0
9    (the "License"); you may not use this file except in compliance with
10    the License. You may obtain a copy of the License at
11
12       http://www.apache.org/licenses/LICENSE-2.0
13
14    Unless required by applicable law or agreed to in writing, software
15    distributed under the License is distributed on an "AS IS" BASIS,
16    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17    See the License for the specific language governing permissions and
18    limitations under the License.
19
20  */

21
22 package org.apache.derby.impl.sql.compile;
23
24 import org.apache.derby.iapi.sql.compile.C_NodeTypes;
25
26 import org.apache.derby.iapi.services.sanity.SanityManager;
27
28 import org.apache.derby.iapi.error.StandardException;
29
30 import org.apache.derby.iapi.sql.dictionary.DataDictionary;
31
32 import org.apache.derby.iapi.reference.SQLState;
33 import org.apache.derby.iapi.reference.Limits;
34
35 import org.apache.derby.impl.sql.compile.ActivationClassBuilder;
36
37 import org.apache.derby.iapi.util.ReuseFactory;
38
39 import java.util.Vector JavaDoc;
40
41 /**
42  * A GroupByList represents the list of expressions in a GROUP BY clause in
43  * a SELECT statement.
44  *
45  * @author Jeff Lichtman
46  */

47
48 public class GroupByList extends OrderedColumnList
49 {
50     int numGroupingColsAdded = 0;
51
52     /**
53         Add a column to the list
54
55         @param column The column to add to the list
56      */

57     public void addGroupByColumn(GroupByColumn column)
58     {
59         addElement(column);
60     }
61
62     /**
63         Get a column from the list
64
65         @param position The column to get from the list
66      */

67     public GroupByColumn getGroupByColumn(int position)
68     {
69         if (SanityManager.DEBUG)
70         {
71             SanityManager.ASSERT(position >=0 && position < size(),
72                     "position (" + position +
73                     ") expected to be between 0 and " + size());
74         }
75         return (GroupByColumn) elementAt(position);
76     }
77
78     /**
79         Print the list.
80
81         @param depth The depth at which to indent the sub-nodes
82      */

83     public void printSubNodes(int depth)
84     {
85         if (SanityManager.DEBUG)
86         {
87             for (int index = 0; index < size(); index++)
88             {
89                 ( (GroupByColumn) elementAt(index) ).treePrint(depth);
90             }
91         }
92     }
93
94     /**
95      * Get the number of grouping columns that need to be added to the SELECT list.
96      *
97      * @return int The number of grouping columns that need to be added to
98      * the SELECT list.
99      */

100     public int getNumNeedToAddGroupingCols()
101     {
102         return numGroupingColsAdded;
103     }
104
105     /**
106      * Bind the group by list. Verify:
107      * o Number of grouping columns matches number of non-aggregates in
108      * SELECT's RCL.
109      * o Names in the group by list are unique
110      * o Names of grouping columns match names of non-aggregate
111      * expressions in SELECT's RCL.
112      *
113      * @param select The SelectNode
114      * @param aggregateVector The aggregate vector being built as we find AggregateNodes
115      *
116      * @exception StandardException Thrown on error
117      */

118     public void bindGroupByColumns(SelectNode select,
119                                    Vector JavaDoc aggregateVector)
120                     throws StandardException
121     {
122         FromList fromList = select.getFromList();
123         ResultColumnList selectRCL = select.getResultColumns();
124         SubqueryList dummySubqueryList =
125                                     (SubqueryList) getNodeFactory().getNode(
126                                                     C_NodeTypes.SUBQUERY_LIST,
127                                                     getContextManager());
128         int numColsAddedHere = 0;
129         int size = size();
130
131         /* Only 32677 columns allowed in GROUP BY clause */
132         if (size > Limits.DB2_MAX_ELEMENTS_IN_GROUP_BY)
133         {
134             throw StandardException.newException(SQLState.LANG_TOO_MANY_ELEMENTS);
135         }
136
137         /* Bind the grouping column */
138         for (int index = 0; index < size; index++)
139         {
140             GroupByColumn groupByCol = (GroupByColumn) elementAt(index);
141             groupByCol.bindExpression(fromList,
142                                       dummySubqueryList, aggregateVector);
143         }
144
145         
146         int rclSize = selectRCL.size();
147         for (int index = 0; index < size; index++)
148         {
149             boolean matchFound = false;
150             GroupByColumn groupingCol = (GroupByColumn) elementAt(index);
151
152             /* Verify that this entry in the GROUP BY list matches a
153              * grouping column in the select list.
154              */

155             for (int inner = 0; inner < rclSize; inner++)
156             {
157                 ResultColumn selectListRC = (ResultColumn) selectRCL.elementAt(inner);
158                 if (!(selectListRC.getExpression() instanceof ColumnReference)) {
159                     continue;
160                 }
161                 
162                 ColumnReference selectListCR = (ColumnReference) selectListRC.getExpression();
163
164                 if (selectListCR.isEquivalent(groupingCol.getColumnExpression())) {
165                     /* Column positions for grouping columns are 0-based */
166                     groupingCol.setColumnPosition(inner + 1);
167
168                     /* Mark the RC in the SELECT list as a grouping column */
169                     selectListRC.markAsGroupingColumn();
170                     matchFound = true;
171                     break;
172                 }
173             }
174             /* If no match found in the SELECT list, then add a matching
175              * ResultColumn/ColumnReference pair to the SelectNode's RCL.
176              */

177             if (! matchFound &&
178                 groupingCol.getColumnExpression() instanceof ColumnReference)
179             {
180                     // only add matching columns for column references not
181
// expressions yet. See DERBY-883 for details.
182
ResultColumn newRC;
183
184                 /* Get a new ResultColumn */
185                 newRC = (ResultColumn) getNodeFactory().getNode(
186                                 C_NodeTypes.RESULT_COLUMN,
187                                 groupingCol.getColumnName(),
188                                 groupingCol.getColumnExpression().getClone(),
189                                 getContextManager());
190                 newRC.setVirtualColumnId(selectRCL.size() + 1);
191                 newRC.markGenerated();
192                 newRC.markAsGroupingColumn();
193
194                 /* Add the new RC/CR to the RCL */
195                 selectRCL.addElement(newRC);
196
197                 /* Set the columnPosition in the GroupByColumn, now that it
198                 * has a matching entry in the SELECT list.
199                 */

200                 groupingCol.setColumnPosition(selectRCL.size());
201
202                 /*
203                 ** Track the number of columns that we have added
204                 ** in this routine. We track this separately
205                 ** than the total number of columns added by this
206                 ** object (numGroupingColsAdded) because we
207                 ** might be bound (though not gagged) more than
208                 ** once (in which case numGroupingColsAdded will
209                 ** already be set).
210                 */

211                 numColsAddedHere++;
212             }
213         }
214
215         /* Verify that no subqueries got added to the dummy list */
216         if (SanityManager.DEBUG)
217         {
218             SanityManager.ASSERT(dummySubqueryList.size() == 0,
219                 "dummySubqueryList.size() is expected to be 0");
220         }
221
222         numGroupingColsAdded+= numColsAddedHere;
223     }
224
225     
226
227     /**
228      * Find the matching grouping column if any for the given expression
229      *
230      * @param node an expression for which we are trying to find a match
231      * in the group by list.
232      *
233      * @return the matching GroupByColumn if one exists, null otherwise.
234      *
235      * @throws StandardException
236      */

237     public GroupByColumn findGroupingColumn(ValueNode node)
238             throws StandardException
239     {
240         int sz = size();
241         for (int i = 0; i < sz; i++)
242         {
243             GroupByColumn gbc = (GroupByColumn)elementAt(i);
244             if (gbc.getColumnExpression().isEquivalent(node))
245             {
246                 return gbc;
247             }
248         }
249         return null;
250     }
251     
252     /**
253      * Remap all ColumnReferences in this tree to be clones of the
254      * underlying expression.
255      *
256      * @exception StandardException Thrown on error
257      */

258     public void remapColumnReferencesToExpressions() throws StandardException
259     {
260         GroupByColumn gbc;
261         int size = size();
262
263         /* This method is called when flattening a FromTable. We should
264          * not be flattening a FromTable if the underlying expression that
265          * will get returned out, after chopping out the redundant ResultColumns,
266          * is not a ColumnReference. (See ASSERT below.)
267          */

268         for (int index = 0; index < size; index++)
269         {
270             ValueNode retVN;
271             gbc = (GroupByColumn) elementAt(index);
272
273             retVN = gbc.getColumnExpression().remapColumnReferencesToExpressions();
274
275             if (SanityManager.DEBUG)
276             {
277                 SanityManager.ASSERT(retVN instanceof ColumnReference,
278                     "retVN expected to be instanceof ColumnReference, not " +
279                     retVN.getClass().getName());
280             }
281
282             gbc.setColumnExpression(retVN);
283         }
284     }
285
286     /**
287      * Print it out, baby
288      */

289     public String JavaDoc toString()
290     {
291         if (SanityManager.DEBUG)
292         {
293             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
294
295             for (int index = 0; index < size(); index++)
296             {
297                 GroupByColumn groupingCol = (GroupByColumn) elementAt(index);
298
299                 buf.append(groupingCol.toString());
300             }
301             return buf.toString();
302         }
303         else
304         {
305             return "";
306         }
307     }
308
309     public void preprocess(
310             int numTables, FromList fromList, SubqueryList whereSubquerys,
311             PredicateList wherePredicates) throws StandardException
312     {
313         for (int index = 0; index < size(); index++)
314         {
315             GroupByColumn groupingCol = (GroupByColumn) elementAt(index);
316             groupingCol.setColumnExpression(
317                     groupingCol.getColumnExpression().preprocess(
318                             numTables, fromList, whereSubquerys, wherePredicates));
319         }
320     }
321 }
322
Popular Tags