blob: 1fe885f51edc0cafb05155c48834e03982e2544c [file] [log] [blame]
drh7d10d5a2008-08-20 16:35:10 +00001/*
2** 2008 August 18
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12**
13** This file contains routines used for walking the parser tree and
14** resolve all identifiers by associating them with a particular
15** table and column.
16**
drhf7828b52009-06-15 23:15:59 +000017** $Id: resolve.c,v 1.30 2009/06/15 23:15:59 drh Exp $
drh7d10d5a2008-08-20 16:35:10 +000018*/
19#include "sqliteInt.h"
20#include <stdlib.h>
21#include <string.h>
22
23/*
drh8b213892008-08-29 02:14:02 +000024** Turn the pExpr expression into an alias for the iCol-th column of the
25** result set in pEList.
26**
27** If the result set column is a simple column reference, then this routine
28** makes an exact copy. But for any other kind of expression, this
29** routine make a copy of the result set column as the argument to the
30** TK_AS operator. The TK_AS operator causes the expression to be
31** evaluated just once and then reused for each alias.
32**
33** The reason for suppressing the TK_AS term when the expression is a simple
34** column reference is so that the column reference will be recognized as
35** usable by indices within the WHERE clause processing logic.
36**
37** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
38** that in a GROUP BY clause, the expression is evaluated twice. Hence:
39**
40** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
41**
42** Is equivalent to:
43**
44** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
45**
46** The result of random()%5 in the GROUP BY clause is probably different
47** from the result in the result-set. We might fix this someday. Or
48** then again, we might not...
49*/
50static void resolveAlias(
51 Parse *pParse, /* Parsing context */
52 ExprList *pEList, /* A result set */
53 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
54 Expr *pExpr, /* Transform this into an alias to the result set */
55 const char *zType /* "GROUP" or "ORDER" or "" */
56){
57 Expr *pOrig; /* The iCol-th column of the result set */
58 Expr *pDup; /* Copy of pOrig */
59 sqlite3 *db; /* The database connection */
60
61 assert( iCol>=0 && iCol<pEList->nExpr );
62 pOrig = pEList->a[iCol].pExpr;
63 assert( pOrig!=0 );
64 assert( pOrig->flags & EP_Resolved );
65 db = pParse->db;
drhb7916a72009-05-27 10:31:29 +000066 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
67 pDup = sqlite3ExprDup(db, pOrig, 0);
drh8b213892008-08-29 02:14:02 +000068 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
69 if( pDup==0 ) return;
70 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +000071 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +000072 }
73 pDup->iTable = pEList->a[iCol].iAlias;
drh0b0745a2009-05-28 12:49:53 +000074 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
75 pDup = sqlite3ExprDup(db, pOrig, 0);
drh2c220452009-05-28 14:34:49 +000076 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +000077 }else{
drh33e619f2009-05-28 01:00:55 +000078 char *zToken = pOrig->u.zToken;
drh73c0fdc2009-06-15 18:32:36 +000079 assert( zToken!=0 );
drh33e619f2009-05-28 01:00:55 +000080 pOrig->u.zToken = 0;
drhb7916a72009-05-27 10:31:29 +000081 pDup = sqlite3ExprDup(db, pOrig, 0);
drh33e619f2009-05-28 01:00:55 +000082 pOrig->u.zToken = zToken;
drhb7916a72009-05-27 10:31:29 +000083 if( pDup==0 ) return;
drh73c0fdc2009-06-15 18:32:36 +000084 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
85 pDup->flags2 |= EP2_MallocedToken;
86 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
drh8b213892008-08-29 02:14:02 +000087 }
88 if( pExpr->flags & EP_ExpCollate ){
89 pDup->pColl = pExpr->pColl;
90 pDup->flags |= EP_ExpCollate;
91 }
drh10fe8402008-10-11 16:47:35 +000092 sqlite3ExprClear(db, pExpr);
drh8b213892008-08-29 02:14:02 +000093 memcpy(pExpr, pDup, sizeof(*pExpr));
94 sqlite3DbFree(db, pDup);
95}
96
97/*
drh7d10d5a2008-08-20 16:35:10 +000098** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
99** that name in the set of source tables in pSrcList and make the pExpr
100** expression node refer back to that source column. The following changes
101** are made to pExpr:
102**
103** pExpr->iDb Set the index in db->aDb[] of the database X
104** (even if X is implied).
105** pExpr->iTable Set to the cursor number for the table obtained
106** from pSrcList.
107** pExpr->pTab Points to the Table structure of X.Y (even if
108** X and/or Y are implied.)
109** pExpr->iColumn Set to the column number within the table.
110** pExpr->op Set to TK_COLUMN.
111** pExpr->pLeft Any expression this points to is deleted
112** pExpr->pRight Any expression this points to is deleted.
113**
drhb7916a72009-05-27 10:31:29 +0000114** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000115** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000116** can be used. The zTable variable is the name of the table (the "Y"). This
117** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000118** means that the form of the name is Z and that columns from any table
119** can be used.
120**
121** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000122** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000123*/
124static int lookupName(
125 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000126 const char *zDb, /* Name of the database containing table, or NULL */
127 const char *zTab, /* Name of table containing column, or NULL */
128 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000129 NameContext *pNC, /* The name context used to resolve the name */
130 Expr *pExpr /* Make this EXPR node point to the selected column */
131){
drh7d10d5a2008-08-20 16:35:10 +0000132 int i, j; /* Loop counters */
133 int cnt = 0; /* Number of matching column names */
134 int cntTab = 0; /* Number of matching table names */
135 sqlite3 *db = pParse->db; /* The database connection */
136 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
137 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
138 NameContext *pTopNC = pNC; /* First namecontext in the list */
139 Schema *pSchema = 0; /* Schema of the expression */
dan165921a2009-08-28 18:53:45 +0000140 int isTrigger = 0; /* True if a new.* or old.* reference. */
drh7d10d5a2008-08-20 16:35:10 +0000141
drhb7916a72009-05-27 10:31:29 +0000142 assert( pNC ); /* the name context cannot be NULL. */
143 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh33e619f2009-05-28 01:00:55 +0000144 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000145
146 /* Initialize the node to no-match */
147 pExpr->iTable = -1;
148 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000149 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000150
151 /* Start at the inner-most context and move outward until a match is found */
152 while( pNC && cnt==0 ){
153 ExprList *pEList;
154 SrcList *pSrcList = pNC->pSrcList;
155
156 if( pSrcList ){
157 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
158 Table *pTab;
159 int iDb;
160 Column *pCol;
161
162 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000163 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000164 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
165 assert( pTab->nCol>0 );
166 if( zTab ){
167 if( pItem->zAlias ){
168 char *zTabName = pItem->zAlias;
169 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
170 }else{
171 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000172 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
173 continue;
174 }
drh7d10d5a2008-08-20 16:35:10 +0000175 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
176 continue;
177 }
178 }
179 }
180 if( 0==(cntTab++) ){
181 pExpr->iTable = pItem->iCursor;
182 pExpr->pTab = pTab;
183 pSchema = pTab->pSchema;
184 pMatch = pItem;
185 }
186 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
187 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
188 IdList *pUsing;
189 cnt++;
190 pExpr->iTable = pItem->iCursor;
191 pExpr->pTab = pTab;
192 pMatch = pItem;
193 pSchema = pTab->pSchema;
194 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000195 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000196 if( i<pSrcList->nSrc-1 ){
197 if( pItem[1].jointype & JT_NATURAL ){
198 /* If this match occurred in the left table of a natural join,
199 ** then skip the right table to avoid a duplicate match */
200 pItem++;
201 i++;
202 }else if( (pUsing = pItem[1].pUsing)!=0 ){
203 /* If this match occurs on a column that is in the USING clause
204 ** of a join, skip the search of the right table of the join
205 ** to avoid a duplicate match there. */
206 int k;
207 for(k=0; k<pUsing->nId; k++){
208 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
209 pItem++;
210 i++;
211 break;
212 }
213 }
214 }
215 }
216 break;
217 }
218 }
219 }
220 }
221
222#ifndef SQLITE_OMIT_TRIGGER
223 /* If we have not already resolved the name, then maybe
224 ** it is a new.* or old.* trigger argument reference
225 */
dan165921a2009-08-28 18:53:45 +0000226 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000227 Table *pTab = 0;
drhb27b7f52008-12-10 18:03:45 +0000228 u32 *piColMask = 0;
dan165921a2009-08-28 18:53:45 +0000229 if( pParse->triggerOp!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
230 pExpr->iTable = 1;
231 pTab = pParse->pTriggerTab;
232 piColMask = &(pParse->newmask);
233 }else if( pParse->triggerOp!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
234 pExpr->iTable = 0;
235 pTab = pParse->pTriggerTab;
236 piColMask = &(pParse->oldmask);
drh7d10d5a2008-08-20 16:35:10 +0000237 }
238
239 if( pTab ){
240 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000241 pSchema = pTab->pSchema;
242 cntTab++;
dan165921a2009-08-28 18:53:45 +0000243 isTrigger = 1;
244 for(iCol=0; iCol<pTab->nCol; iCol++){
245 Column *pCol = &pTab->aCol[iCol];
drh7d10d5a2008-08-20 16:35:10 +0000246 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
247 cnt++;
shanecf697392009-06-01 16:53:09 +0000248 pExpr->iColumn = iCol==pTab->iPKey ? -1 : (i16)iCol;
drh73c0fdc2009-06-15 18:32:36 +0000249 testcase( iCol==31 );
250 testcase( iCol==32 );
251 if( iCol>=32 ){
252 *piColMask = 0xffffffff;
253 }else{
254 *piColMask |= ((u32)1)<<iCol;
drh7d10d5a2008-08-20 16:35:10 +0000255 }
256 break;
257 }
258 }
259 }
260 }
261#endif /* !defined(SQLITE_OMIT_TRIGGER) */
262
263 /*
264 ** Perhaps the name is a reference to the ROWID
265 */
266 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
267 cnt = 1;
268 pExpr->iColumn = -1;
269 pExpr->affinity = SQLITE_AFF_INTEGER;
270 }
271
272 /*
273 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
274 ** might refer to an result-set alias. This happens, for example, when
275 ** we are resolving names in the WHERE clause of the following command:
276 **
277 ** SELECT a+b AS x FROM table WHERE x<10;
278 **
279 ** In cases like this, replace pExpr with a copy of the expression that
280 ** forms the result set entry ("a+b" in the example) and return immediately.
281 ** Note that the expression in the result set should have already been
282 ** resolved by the time the WHERE clause is resolved.
283 */
284 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
285 for(j=0; j<pEList->nExpr; j++){
286 char *zAs = pEList->a[j].zName;
287 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000288 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000289 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000290 assert( pExpr->x.pList==0 );
291 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000292 pOrig = pEList->a[j].pExpr;
293 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
294 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000295 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000296 }
drh8b213892008-08-29 02:14:02 +0000297 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000298 cnt = 1;
299 pMatch = 0;
300 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000301 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000302 }
303 }
304 }
305
306 /* Advance to the next name context. The loop will exit when either
307 ** we have a match (cnt>0) or when we run out of name contexts.
308 */
309 if( cnt==0 ){
310 pNC = pNC->pNext;
311 }
312 }
313
314 /*
315 ** If X and Y are NULL (in other words if only the column name Z is
316 ** supplied) and the value of Z is enclosed in double-quotes, then
317 ** Z is a string literal if it doesn't match any column names. In that
318 ** case, we need to return right away and not make any changes to
319 ** pExpr.
320 **
321 ** Because no reference was made to outer contexts, the pNC->nRef
322 ** fields are not changed in any context.
323 */
drh24fb6272009-05-01 21:13:36 +0000324 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000325 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000326 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000327 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000328 }
329
330 /*
331 ** cnt==0 means there was not match. cnt>1 means there were two or
332 ** more matches. Either way, we have an error.
333 */
334 if( cnt!=1 ){
335 const char *zErr;
336 zErr = cnt==0 ? "no such column" : "ambiguous column name";
337 if( zDb ){
338 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
339 }else if( zTab ){
340 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
341 }else{
342 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
343 }
344 pTopNC->nErr++;
345 }
346
347 /* If a column from a table in pSrcList is referenced, then record
348 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
349 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
350 ** column number is greater than the number of bits in the bitmask
351 ** then set the high-order bit of the bitmask.
352 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000353 if( pExpr->iColumn>=0 && pMatch!=0 ){
354 int n = pExpr->iColumn;
355 testcase( n==BMS-1 );
356 if( n>=BMS ){
357 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000358 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000359 assert( pMatch->iCursor==pExpr->iTable );
360 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000361 }
362
drh7d10d5a2008-08-20 16:35:10 +0000363 /* Clean up and return
364 */
drh7d10d5a2008-08-20 16:35:10 +0000365 sqlite3ExprDelete(db, pExpr->pLeft);
366 pExpr->pLeft = 0;
367 sqlite3ExprDelete(db, pExpr->pRight);
368 pExpr->pRight = 0;
369 pExpr->op = TK_COLUMN;
drhb7916a72009-05-27 10:31:29 +0000370lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000371 if( cnt==1 ){
372 assert( pNC!=0 );
373 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
374 /* Increment the nRef value on all name contexts from TopNC up to
375 ** the point where the name matched. */
376 for(;;){
377 assert( pTopNC!=0 );
378 pTopNC->nRef++;
379 if( pTopNC==pNC ) break;
380 pTopNC = pTopNC->pNext;
381 }
dan165921a2009-08-28 18:53:45 +0000382 if( isTrigger ){
383 pExpr->pTab = pParse->pTriggerTab;
384 pExpr->op = TK_TRIGGER;
385 }
drhf7828b52009-06-15 23:15:59 +0000386 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000387 } else {
drhf7828b52009-06-15 23:15:59 +0000388 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000389 }
390}
391
392/*
393** This routine is callback for sqlite3WalkExpr().
394**
395** Resolve symbolic names into TK_COLUMN operators for the current
396** node in the expression tree. Return 0 to continue the search down
397** the tree or 2 to abort the tree walk.
398**
399** This routine also does error checking and name resolution for
400** function names. The operator for aggregate functions is changed
401** to TK_AGG_FUNCTION.
402*/
403static int resolveExprStep(Walker *pWalker, Expr *pExpr){
404 NameContext *pNC;
405 Parse *pParse;
406
drh7d10d5a2008-08-20 16:35:10 +0000407 pNC = pWalker->u.pNC;
408 assert( pNC!=0 );
409 pParse = pNC->pParse;
410 assert( pParse==pWalker->pParse );
411
412 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
413 ExprSetProperty(pExpr, EP_Resolved);
414#ifndef NDEBUG
415 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
416 SrcList *pSrcList = pNC->pSrcList;
417 int i;
418 for(i=0; i<pNC->pSrcList->nSrc; i++){
419 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
420 }
421 }
422#endif
423 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000424
shane273f6192008-10-10 04:34:16 +0000425#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000426 /* The special operator TK_ROW means use the rowid for the first
427 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
428 ** clause processing on UPDATE and DELETE statements.
429 */
430 case TK_ROW: {
431 SrcList *pSrcList = pNC->pSrcList;
432 struct SrcList_item *pItem;
433 assert( pSrcList && pSrcList->nSrc==1 );
434 pItem = pSrcList->a;
435 pExpr->op = TK_COLUMN;
436 pExpr->pTab = pItem->pTab;
437 pExpr->iTable = pItem->iCursor;
438 pExpr->iColumn = -1;
439 pExpr->affinity = SQLITE_AFF_INTEGER;
440 break;
441 }
shane273f6192008-10-10 04:34:16 +0000442#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000443
drh7d10d5a2008-08-20 16:35:10 +0000444 /* A lone identifier is the name of a column.
445 */
446 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000447 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000448 }
449
450 /* A table name and column name: ID.ID
451 ** Or a database, table and column: ID.ID.ID
452 */
453 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000454 const char *zColumn;
455 const char *zTable;
456 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000457 Expr *pRight;
458
459 /* if( pSrcList==0 ) break; */
460 pRight = pExpr->pRight;
461 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000462 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000463 zTable = pExpr->pLeft->u.zToken;
464 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000465 }else{
466 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000467 zDb = pExpr->pLeft->u.zToken;
468 zTable = pRight->pLeft->u.zToken;
469 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000470 }
drhf7828b52009-06-15 23:15:59 +0000471 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000472 }
473
474 /* Resolve function names
475 */
476 case TK_CONST_FUNC:
477 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000478 ExprList *pList = pExpr->x.pList; /* The argument list */
479 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000480 int no_such_func = 0; /* True if no such function exists */
481 int wrong_num_args = 0; /* True if wrong number of arguments */
482 int is_agg = 0; /* True if is an aggregate function */
483 int auth; /* Authorization to use the function */
484 int nId; /* Number of characters in function name */
485 const char *zId; /* The function name. */
486 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000487 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000488
drh73c0fdc2009-06-15 18:32:36 +0000489 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000490 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000491 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000492 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000493 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
494 if( pDef==0 ){
495 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
496 if( pDef==0 ){
497 no_such_func = 1;
498 }else{
499 wrong_num_args = 1;
500 }
501 }else{
502 is_agg = pDef->xFunc==0;
503 }
504#ifndef SQLITE_OMIT_AUTHORIZATION
505 if( pDef ){
506 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
507 if( auth!=SQLITE_OK ){
508 if( auth==SQLITE_DENY ){
509 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
510 pDef->zName);
511 pNC->nErr++;
512 }
513 pExpr->op = TK_NULL;
514 return WRC_Prune;
515 }
516 }
517#endif
518 if( is_agg && !pNC->allowAgg ){
519 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
520 pNC->nErr++;
521 is_agg = 0;
522 }else if( no_such_func ){
523 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
524 pNC->nErr++;
525 }else if( wrong_num_args ){
526 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
527 nId, zId);
528 pNC->nErr++;
529 }
530 if( is_agg ){
531 pExpr->op = TK_AGG_FUNCTION;
532 pNC->hasAgg = 1;
533 }
534 if( is_agg ) pNC->allowAgg = 0;
535 sqlite3WalkExprList(pWalker, pList);
536 if( is_agg ) pNC->allowAgg = 1;
537 /* FIX ME: Compute pExpr->affinity based on the expected return
538 ** type of the function
539 */
540 return WRC_Prune;
541 }
542#ifndef SQLITE_OMIT_SUBQUERY
543 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000544 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000545#endif
546 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000547 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000548 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000549 int nRef = pNC->nRef;
550#ifndef SQLITE_OMIT_CHECK
551 if( pNC->isCheck ){
552 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
553 }
554#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000555 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000556 assert( pNC->nRef>=nRef );
557 if( nRef!=pNC->nRef ){
558 ExprSetProperty(pExpr, EP_VarSelect);
559 }
560 }
561 break;
562 }
563#ifndef SQLITE_OMIT_CHECK
564 case TK_VARIABLE: {
565 if( pNC->isCheck ){
566 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
567 }
568 break;
569 }
570#endif
571 }
572 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
573}
574
575/*
576** pEList is a list of expressions which are really the result set of the
577** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
578** This routine checks to see if pE is a simple identifier which corresponds
579** to the AS-name of one of the terms of the expression list. If it is,
580** this routine return an integer between 1 and N where N is the number of
581** elements in pEList, corresponding to the matching entry. If there is
582** no match, or if pE is not a simple identifier, then this routine
583** return 0.
584**
585** pEList has been resolved. pE has not.
586*/
587static int resolveAsName(
588 Parse *pParse, /* Parsing context for error messages */
589 ExprList *pEList, /* List of expressions to scan */
590 Expr *pE /* Expression we are trying to match */
591){
592 int i; /* Loop counter */
593
shanecf697392009-06-01 16:53:09 +0000594 UNUSED_PARAMETER(pParse);
595
drh73c0fdc2009-06-15 18:32:36 +0000596 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000597 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000598 for(i=0; i<pEList->nExpr; i++){
599 char *zAs = pEList->a[i].zName;
600 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000601 return i+1;
602 }
603 }
drh7d10d5a2008-08-20 16:35:10 +0000604 }
605 return 0;
606}
607
608/*
609** pE is a pointer to an expression which is a single term in the
610** ORDER BY of a compound SELECT. The expression has not been
611** name resolved.
612**
613** At the point this routine is called, we already know that the
614** ORDER BY term is not an integer index into the result set. That
615** case is handled by the calling routine.
616**
617** Attempt to match pE against result set columns in the left-most
618** SELECT statement. Return the index i of the matching column,
619** as an indication to the caller that it should sort by the i-th column.
620** The left-most column is 1. In other words, the value returned is the
621** same integer value that would be used in the SQL statement to indicate
622** the column.
623**
624** If there is no match, return 0. Return -1 if an error occurs.
625*/
626static int resolveOrderByTermToExprList(
627 Parse *pParse, /* Parsing context for error messages */
628 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
629 Expr *pE /* The specific ORDER BY term */
630){
631 int i; /* Loop counter */
632 ExprList *pEList; /* The columns of the result set */
633 NameContext nc; /* Name context for resolving pE */
634
635 assert( sqlite3ExprIsInteger(pE, &i)==0 );
636 pEList = pSelect->pEList;
637
638 /* Resolve all names in the ORDER BY term expression
639 */
640 memset(&nc, 0, sizeof(nc));
641 nc.pParse = pParse;
642 nc.pSrcList = pSelect->pSrc;
643 nc.pEList = pEList;
644 nc.allowAgg = 1;
645 nc.nErr = 0;
646 if( sqlite3ResolveExprNames(&nc, pE) ){
647 sqlite3ErrorClear(pParse);
648 return 0;
649 }
650
651 /* Try to match the ORDER BY expression against an expression
652 ** in the result set. Return an 1-based index of the matching
653 ** result-set entry.
654 */
655 for(i=0; i<pEList->nExpr; i++){
656 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
657 return i+1;
658 }
659 }
660
661 /* If no match, return 0. */
662 return 0;
663}
664
665/*
666** Generate an ORDER BY or GROUP BY term out-of-range error.
667*/
668static void resolveOutOfRangeError(
669 Parse *pParse, /* The error context into which to write the error */
670 const char *zType, /* "ORDER" or "GROUP" */
671 int i, /* The index (1-based) of the term out of range */
672 int mx /* Largest permissible value of i */
673){
674 sqlite3ErrorMsg(pParse,
675 "%r %s BY term out of range - should be "
676 "between 1 and %d", i, zType, mx);
677}
678
679/*
680** Analyze the ORDER BY clause in a compound SELECT statement. Modify
681** each term of the ORDER BY clause is a constant integer between 1
682** and N where N is the number of columns in the compound SELECT.
683**
684** ORDER BY terms that are already an integer between 1 and N are
685** unmodified. ORDER BY terms that are integers outside the range of
686** 1 through N generate an error. ORDER BY terms that are expressions
687** are matched against result set expressions of compound SELECT
688** beginning with the left-most SELECT and working toward the right.
689** At the first match, the ORDER BY expression is transformed into
690** the integer column number.
691**
692** Return the number of errors seen.
693*/
694static int resolveCompoundOrderBy(
695 Parse *pParse, /* Parsing context. Leave error messages here */
696 Select *pSelect /* The SELECT statement containing the ORDER BY */
697){
698 int i;
699 ExprList *pOrderBy;
700 ExprList *pEList;
701 sqlite3 *db;
702 int moreToDo = 1;
703
704 pOrderBy = pSelect->pOrderBy;
705 if( pOrderBy==0 ) return 0;
706 db = pParse->db;
707#if SQLITE_MAX_COLUMN
708 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
709 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
710 return 1;
711 }
712#endif
713 for(i=0; i<pOrderBy->nExpr; i++){
714 pOrderBy->a[i].done = 0;
715 }
716 pSelect->pNext = 0;
717 while( pSelect->pPrior ){
718 pSelect->pPrior->pNext = pSelect;
719 pSelect = pSelect->pPrior;
720 }
721 while( pSelect && moreToDo ){
722 struct ExprList_item *pItem;
723 moreToDo = 0;
724 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000725 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000726 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
727 int iCol = -1;
728 Expr *pE, *pDup;
729 if( pItem->done ) continue;
730 pE = pItem->pExpr;
731 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000732 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000733 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
734 return 1;
735 }
736 }else{
737 iCol = resolveAsName(pParse, pEList, pE);
738 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000739 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000740 if( !db->mallocFailed ){
741 assert(pDup);
742 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
743 }
744 sqlite3ExprDelete(db, pDup);
745 }
drh7d10d5a2008-08-20 16:35:10 +0000746 }
747 if( iCol>0 ){
748 CollSeq *pColl = pE->pColl;
749 int flags = pE->flags & EP_ExpCollate;
750 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000751 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000752 if( pE==0 ) return 1;
753 pE->pColl = pColl;
754 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000755 pE->u.iValue = iCol;
drhea678832008-12-10 19:26:22 +0000756 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000757 pItem->done = 1;
758 }else{
759 moreToDo = 1;
760 }
761 }
762 pSelect = pSelect->pNext;
763 }
764 for(i=0; i<pOrderBy->nExpr; i++){
765 if( pOrderBy->a[i].done==0 ){
766 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
767 "column in the result set", i+1);
768 return 1;
769 }
770 }
771 return 0;
772}
773
774/*
775** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
776** the SELECT statement pSelect. If any term is reference to a
777** result set expression (as determined by the ExprList.a.iCol field)
778** then convert that term into a copy of the corresponding result set
779** column.
780**
781** If any errors are detected, add an error message to pParse and
782** return non-zero. Return zero if no errors are seen.
783*/
784int sqlite3ResolveOrderGroupBy(
785 Parse *pParse, /* Parsing context. Leave error messages here */
786 Select *pSelect, /* The SELECT statement containing the clause */
787 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
788 const char *zType /* "ORDER" or "GROUP" */
789){
790 int i;
791 sqlite3 *db = pParse->db;
792 ExprList *pEList;
793 struct ExprList_item *pItem;
794
795 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
796#if SQLITE_MAX_COLUMN
797 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
798 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
799 return 1;
800 }
801#endif
802 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000803 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000804 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
805 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000806 if( pItem->iCol>pEList->nExpr ){
807 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
808 return 1;
809 }
drh8b213892008-08-29 02:14:02 +0000810 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000811 }
812 }
813 return 0;
814}
815
816/*
817** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
818** The Name context of the SELECT statement is pNC. zType is either
819** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
820**
821** This routine resolves each term of the clause into an expression.
822** If the order-by term is an integer I between 1 and N (where N is the
823** number of columns in the result set of the SELECT) then the expression
824** in the resolution is a copy of the I-th result-set expression. If
825** the order-by term is an identify that corresponds to the AS-name of
826** a result-set expression, then the term resolves to a copy of the
827** result-set expression. Otherwise, the expression is resolved in
828** the usual way - using sqlite3ResolveExprNames().
829**
830** This routine returns the number of errors. If errors occur, then
831** an appropriate error message might be left in pParse. (OOM errors
832** excepted.)
833*/
834static int resolveOrderGroupBy(
835 NameContext *pNC, /* The name context of the SELECT statement */
836 Select *pSelect, /* The SELECT statement holding pOrderBy */
837 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
838 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
839){
840 int i; /* Loop counter */
841 int iCol; /* Column number */
842 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
843 Parse *pParse; /* Parsing context */
844 int nResult; /* Number of terms in the result set */
845
846 if( pOrderBy==0 ) return 0;
847 nResult = pSelect->pEList->nExpr;
848 pParse = pNC->pParse;
849 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
850 Expr *pE = pItem->pExpr;
851 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000852 if( iCol>0 ){
853 /* If an AS-name match is found, mark this ORDER BY column as being
854 ** a copy of the iCol-th result-set column. The subsequent call to
855 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
856 ** copy of the iCol-th result-set expression. */
drhea678832008-12-10 19:26:22 +0000857 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000858 continue;
859 }
860 if( sqlite3ExprIsInteger(pE, &iCol) ){
861 /* The ORDER BY term is an integer constant. Again, set the column
862 ** number so that sqlite3ResolveOrderGroupBy() will convert the
863 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000864 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000865 resolveOutOfRangeError(pParse, zType, i+1, nResult);
866 return 1;
867 }
drhea678832008-12-10 19:26:22 +0000868 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000869 continue;
870 }
871
872 /* Otherwise, treat the ORDER BY term as an ordinary expression */
873 pItem->iCol = 0;
874 if( sqlite3ResolveExprNames(pNC, pE) ){
875 return 1;
876 }
877 }
878 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
879}
880
881/*
882** Resolve names in the SELECT statement p and all of its descendents.
883*/
884static int resolveSelectStep(Walker *pWalker, Select *p){
885 NameContext *pOuterNC; /* Context that contains this SELECT */
886 NameContext sNC; /* Name context of this SELECT */
887 int isCompound; /* True if p is a compound select */
888 int nCompound; /* Number of compound terms processed so far */
889 Parse *pParse; /* Parsing context */
890 ExprList *pEList; /* Result set expression list */
891 int i; /* Loop counter */
892 ExprList *pGroupBy; /* The GROUP BY clause */
893 Select *pLeftmost; /* Left-most of SELECT of a compound */
894 sqlite3 *db; /* Database connection */
895
896
drh0a846f92008-08-25 17:23:29 +0000897 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000898 if( p->selFlags & SF_Resolved ){
899 return WRC_Prune;
900 }
901 pOuterNC = pWalker->u.pNC;
902 pParse = pWalker->pParse;
903 db = pParse->db;
904
905 /* Normally sqlite3SelectExpand() will be called first and will have
906 ** already expanded this SELECT. However, if this is a subquery within
907 ** an expression, sqlite3ResolveExprNames() will be called without a
908 ** prior call to sqlite3SelectExpand(). When that happens, let
909 ** sqlite3SelectPrep() do all of the processing for this SELECT.
910 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
911 ** this routine in the correct order.
912 */
913 if( (p->selFlags & SF_Expanded)==0 ){
914 sqlite3SelectPrep(pParse, p, pOuterNC);
915 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
916 }
917
918 isCompound = p->pPrior!=0;
919 nCompound = 0;
920 pLeftmost = p;
921 while( p ){
922 assert( (p->selFlags & SF_Expanded)!=0 );
923 assert( (p->selFlags & SF_Resolved)==0 );
924 p->selFlags |= SF_Resolved;
925
926 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
927 ** are not allowed to refer to any names, so pass an empty NameContext.
928 */
929 memset(&sNC, 0, sizeof(sNC));
930 sNC.pParse = pParse;
931 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
932 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
933 return WRC_Abort;
934 }
935
936 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
937 ** resolve the result-set expression list.
938 */
939 sNC.allowAgg = 1;
940 sNC.pSrcList = p->pSrc;
941 sNC.pNext = pOuterNC;
942
943 /* Resolve names in the result set. */
944 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000945 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000946 for(i=0; i<pEList->nExpr; i++){
947 Expr *pX = pEList->a[i].pExpr;
948 if( sqlite3ResolveExprNames(&sNC, pX) ){
949 return WRC_Abort;
950 }
951 }
952
953 /* Recursively resolve names in all subqueries
954 */
955 for(i=0; i<p->pSrc->nSrc; i++){
956 struct SrcList_item *pItem = &p->pSrc->a[i];
957 if( pItem->pSelect ){
958 const char *zSavedContext = pParse->zAuthContext;
959 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +0000960 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +0000961 pParse->zAuthContext = zSavedContext;
962 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
963 }
964 }
965
966 /* If there are no aggregate functions in the result-set, and no GROUP BY
967 ** expression, do not allow aggregates in any of the other expressions.
968 */
969 assert( (p->selFlags & SF_Aggregate)==0 );
970 pGroupBy = p->pGroupBy;
971 if( pGroupBy || sNC.hasAgg ){
972 p->selFlags |= SF_Aggregate;
973 }else{
974 sNC.allowAgg = 0;
975 }
976
977 /* If a HAVING clause is present, then there must be a GROUP BY clause.
978 */
979 if( p->pHaving && !pGroupBy ){
980 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
981 return WRC_Abort;
982 }
983
984 /* Add the expression list to the name-context before parsing the
985 ** other expressions in the SELECT statement. This is so that
986 ** expressions in the WHERE clause (etc.) can refer to expressions by
987 ** aliases in the result set.
988 **
989 ** Minor point: If this is the case, then the expression will be
990 ** re-evaluated for each reference to it.
991 */
992 sNC.pEList = p->pEList;
993 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
994 sqlite3ResolveExprNames(&sNC, p->pHaving)
995 ){
996 return WRC_Abort;
997 }
998
999 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1000 ** outer queries
1001 */
1002 sNC.pNext = 0;
1003 sNC.allowAgg = 1;
1004
1005 /* Process the ORDER BY clause for singleton SELECT statements.
1006 ** The ORDER BY clause for compounds SELECT statements is handled
1007 ** below, after all of the result-sets for all of the elements of
1008 ** the compound have been resolved.
1009 */
1010 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1011 return WRC_Abort;
1012 }
1013 if( db->mallocFailed ){
1014 return WRC_Abort;
1015 }
1016
1017 /* Resolve the GROUP BY clause. At the same time, make sure
1018 ** the GROUP BY clause does not contain aggregate functions.
1019 */
1020 if( pGroupBy ){
1021 struct ExprList_item *pItem;
1022
1023 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1024 return WRC_Abort;
1025 }
1026 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1027 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1028 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1029 "the GROUP BY clause");
1030 return WRC_Abort;
1031 }
1032 }
1033 }
1034
1035 /* Advance to the next term of the compound
1036 */
1037 p = p->pPrior;
1038 nCompound++;
1039 }
1040
1041 /* Resolve the ORDER BY on a compound SELECT after all terms of
1042 ** the compound have been resolved.
1043 */
1044 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1045 return WRC_Abort;
1046 }
1047
1048 return WRC_Prune;
1049}
1050
1051/*
1052** This routine walks an expression tree and resolves references to
1053** table columns and result-set columns. At the same time, do error
1054** checking on function usage and set a flag if any aggregate functions
1055** are seen.
1056**
1057** To resolve table columns references we look for nodes (or subtrees) of the
1058** form X.Y.Z or Y.Z or just Z where
1059**
1060** X: The name of a database. Ex: "main" or "temp" or
1061** the symbolic name assigned to an ATTACH-ed database.
1062**
1063** Y: The name of a table in a FROM clause. Or in a trigger
1064** one of the special names "old" or "new".
1065**
1066** Z: The name of a column in table Y.
1067**
1068** The node at the root of the subtree is modified as follows:
1069**
1070** Expr.op Changed to TK_COLUMN
1071** Expr.pTab Points to the Table object for X.Y
1072** Expr.iColumn The column index in X.Y. -1 for the rowid.
1073** Expr.iTable The VDBE cursor number for X.Y
1074**
1075**
1076** To resolve result-set references, look for expression nodes of the
1077** form Z (with no X and Y prefix) where the Z matches the right-hand
1078** size of an AS clause in the result-set of a SELECT. The Z expression
1079** is replaced by a copy of the left-hand side of the result-set expression.
1080** Table-name and function resolution occurs on the substituted expression
1081** tree. For example, in:
1082**
1083** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1084**
1085** The "x" term of the order by is replaced by "a+b" to render:
1086**
1087** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1088**
1089** Function calls are checked to make sure that the function is
1090** defined and that the correct number of arguments are specified.
1091** If the function is an aggregate function, then the pNC->hasAgg is
1092** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1093** If an expression contains aggregate functions then the EP_Agg
1094** property on the expression is set.
1095**
1096** An error message is left in pParse if anything is amiss. The number
1097** if errors is returned.
1098*/
1099int sqlite3ResolveExprNames(
1100 NameContext *pNC, /* Namespace to resolve expressions in. */
1101 Expr *pExpr /* The expression to be analyzed. */
1102){
1103 int savedHasAgg;
1104 Walker w;
1105
1106 if( pExpr==0 ) return 0;
1107#if SQLITE_MAX_EXPR_DEPTH>0
1108 {
1109 Parse *pParse = pNC->pParse;
1110 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1111 return 1;
1112 }
1113 pParse->nHeight += pExpr->nHeight;
1114 }
1115#endif
1116 savedHasAgg = pNC->hasAgg;
1117 pNC->hasAgg = 0;
1118 w.xExprCallback = resolveExprStep;
1119 w.xSelectCallback = resolveSelectStep;
1120 w.pParse = pNC->pParse;
1121 w.u.pNC = pNC;
1122 sqlite3WalkExpr(&w, pExpr);
1123#if SQLITE_MAX_EXPR_DEPTH>0
1124 pNC->pParse->nHeight -= pExpr->nHeight;
1125#endif
drhfd773cf2009-05-29 14:39:07 +00001126 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001127 ExprSetProperty(pExpr, EP_Error);
1128 }
1129 if( pNC->hasAgg ){
1130 ExprSetProperty(pExpr, EP_Agg);
1131 }else if( savedHasAgg ){
1132 pNC->hasAgg = 1;
1133 }
1134 return ExprHasProperty(pExpr, EP_Error);
1135}
drh7d10d5a2008-08-20 16:35:10 +00001136
1137
1138/*
1139** Resolve all names in all expressions of a SELECT and in all
1140** decendents of the SELECT, including compounds off of p->pPrior,
1141** subqueries in expressions, and subqueries used as FROM clause
1142** terms.
1143**
1144** See sqlite3ResolveExprNames() for a description of the kinds of
1145** transformations that occur.
1146**
1147** All SELECT statements should have been expanded using
1148** sqlite3SelectExpand() prior to invoking this routine.
1149*/
1150void sqlite3ResolveSelectNames(
1151 Parse *pParse, /* The parser context */
1152 Select *p, /* The SELECT statement being coded. */
1153 NameContext *pOuterNC /* Name context for parent SELECT statement */
1154){
1155 Walker w;
1156
drh0a846f92008-08-25 17:23:29 +00001157 assert( p!=0 );
1158 w.xExprCallback = resolveExprStep;
1159 w.xSelectCallback = resolveSelectStep;
1160 w.pParse = pParse;
1161 w.u.pNC = pOuterNC;
1162 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001163}