blob: 2c4d4f2ed00f1232c6d703f5d3dcc1b8be935517 [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 */
dan2bd93512009-08-31 08:22:46 +0000140 int isTrigger = 0;
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++;
dan2bd93512009-08-31 08:22:46 +0000243 if( sqlite3IsRowid(zCol) ){
244 iCol = -1;
245 }else{
246 for(iCol=0; iCol<pTab->nCol; iCol++){
247 Column *pCol = &pTab->aCol[iCol];
248 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
249 testcase( iCol==31 );
250 testcase( iCol==32 );
251 if( iCol>=32 ){
252 *piColMask = 0xffffffff;
253 }else{
254 *piColMask |= ((u32)1)<<iCol;
255 }
256 if( iCol==pTab->iPKey ){
257 iCol = -1;
258 }
259 break;
drh7d10d5a2008-08-20 16:35:10 +0000260 }
drh7d10d5a2008-08-20 16:35:10 +0000261 }
262 }
dan2bd93512009-08-31 08:22:46 +0000263 if( iCol<pTab->nCol ){
264 cnt++;
265 if( iCol<0 ){
266 pExpr->affinity = SQLITE_AFF_INTEGER;
267 }
268 pExpr->iColumn = iCol;
269 pExpr->pTab = pTab;
270 isTrigger = 1;
271 }
drh7d10d5a2008-08-20 16:35:10 +0000272 }
273 }
274#endif /* !defined(SQLITE_OMIT_TRIGGER) */
275
276 /*
277 ** Perhaps the name is a reference to the ROWID
278 */
279 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
280 cnt = 1;
281 pExpr->iColumn = -1;
282 pExpr->affinity = SQLITE_AFF_INTEGER;
283 }
284
285 /*
286 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
287 ** might refer to an result-set alias. This happens, for example, when
288 ** we are resolving names in the WHERE clause of the following command:
289 **
290 ** SELECT a+b AS x FROM table WHERE x<10;
291 **
292 ** In cases like this, replace pExpr with a copy of the expression that
293 ** forms the result set entry ("a+b" in the example) and return immediately.
294 ** Note that the expression in the result set should have already been
295 ** resolved by the time the WHERE clause is resolved.
296 */
297 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
298 for(j=0; j<pEList->nExpr; j++){
299 char *zAs = pEList->a[j].zName;
300 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000301 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000302 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000303 assert( pExpr->x.pList==0 );
304 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000305 pOrig = pEList->a[j].pExpr;
306 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
307 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000308 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000309 }
drh8b213892008-08-29 02:14:02 +0000310 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000311 cnt = 1;
312 pMatch = 0;
313 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000314 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000315 }
316 }
317 }
318
319 /* Advance to the next name context. The loop will exit when either
320 ** we have a match (cnt>0) or when we run out of name contexts.
321 */
322 if( cnt==0 ){
323 pNC = pNC->pNext;
324 }
325 }
326
327 /*
328 ** If X and Y are NULL (in other words if only the column name Z is
329 ** supplied) and the value of Z is enclosed in double-quotes, then
330 ** Z is a string literal if it doesn't match any column names. In that
331 ** case, we need to return right away and not make any changes to
332 ** pExpr.
333 **
334 ** Because no reference was made to outer contexts, the pNC->nRef
335 ** fields are not changed in any context.
336 */
drh24fb6272009-05-01 21:13:36 +0000337 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000338 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000339 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000340 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000341 }
342
343 /*
344 ** cnt==0 means there was not match. cnt>1 means there were two or
345 ** more matches. Either way, we have an error.
346 */
347 if( cnt!=1 ){
348 const char *zErr;
349 zErr = cnt==0 ? "no such column" : "ambiguous column name";
350 if( zDb ){
351 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
352 }else if( zTab ){
353 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
354 }else{
355 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
356 }
357 pTopNC->nErr++;
358 }
359
360 /* If a column from a table in pSrcList is referenced, then record
361 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
362 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
363 ** column number is greater than the number of bits in the bitmask
364 ** then set the high-order bit of the bitmask.
365 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000366 if( pExpr->iColumn>=0 && pMatch!=0 ){
367 int n = pExpr->iColumn;
368 testcase( n==BMS-1 );
369 if( n>=BMS ){
370 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000371 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000372 assert( pMatch->iCursor==pExpr->iTable );
373 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000374 }
375
drh7d10d5a2008-08-20 16:35:10 +0000376 /* Clean up and return
377 */
drh7d10d5a2008-08-20 16:35:10 +0000378 sqlite3ExprDelete(db, pExpr->pLeft);
379 pExpr->pLeft = 0;
380 sqlite3ExprDelete(db, pExpr->pRight);
381 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000382 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000383lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000384 if( cnt==1 ){
385 assert( pNC!=0 );
386 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
387 /* Increment the nRef value on all name contexts from TopNC up to
388 ** the point where the name matched. */
389 for(;;){
390 assert( pTopNC!=0 );
391 pTopNC->nRef++;
392 if( pTopNC==pNC ) break;
393 pTopNC = pTopNC->pNext;
394 }
drhf7828b52009-06-15 23:15:59 +0000395 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000396 } else {
drhf7828b52009-06-15 23:15:59 +0000397 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000398 }
399}
400
401/*
402** This routine is callback for sqlite3WalkExpr().
403**
404** Resolve symbolic names into TK_COLUMN operators for the current
405** node in the expression tree. Return 0 to continue the search down
406** the tree or 2 to abort the tree walk.
407**
408** This routine also does error checking and name resolution for
409** function names. The operator for aggregate functions is changed
410** to TK_AGG_FUNCTION.
411*/
412static int resolveExprStep(Walker *pWalker, Expr *pExpr){
413 NameContext *pNC;
414 Parse *pParse;
415
drh7d10d5a2008-08-20 16:35:10 +0000416 pNC = pWalker->u.pNC;
417 assert( pNC!=0 );
418 pParse = pNC->pParse;
419 assert( pParse==pWalker->pParse );
420
421 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
422 ExprSetProperty(pExpr, EP_Resolved);
423#ifndef NDEBUG
424 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
425 SrcList *pSrcList = pNC->pSrcList;
426 int i;
427 for(i=0; i<pNC->pSrcList->nSrc; i++){
428 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
429 }
430 }
431#endif
432 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000433
shane273f6192008-10-10 04:34:16 +0000434#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000435 /* The special operator TK_ROW means use the rowid for the first
436 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
437 ** clause processing on UPDATE and DELETE statements.
438 */
439 case TK_ROW: {
440 SrcList *pSrcList = pNC->pSrcList;
441 struct SrcList_item *pItem;
442 assert( pSrcList && pSrcList->nSrc==1 );
443 pItem = pSrcList->a;
444 pExpr->op = TK_COLUMN;
445 pExpr->pTab = pItem->pTab;
446 pExpr->iTable = pItem->iCursor;
447 pExpr->iColumn = -1;
448 pExpr->affinity = SQLITE_AFF_INTEGER;
449 break;
450 }
shane273f6192008-10-10 04:34:16 +0000451#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000452
drh7d10d5a2008-08-20 16:35:10 +0000453 /* A lone identifier is the name of a column.
454 */
455 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000456 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000457 }
458
459 /* A table name and column name: ID.ID
460 ** Or a database, table and column: ID.ID.ID
461 */
462 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000463 const char *zColumn;
464 const char *zTable;
465 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000466 Expr *pRight;
467
468 /* if( pSrcList==0 ) break; */
469 pRight = pExpr->pRight;
470 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000471 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000472 zTable = pExpr->pLeft->u.zToken;
473 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000474 }else{
475 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000476 zDb = pExpr->pLeft->u.zToken;
477 zTable = pRight->pLeft->u.zToken;
478 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000479 }
drhf7828b52009-06-15 23:15:59 +0000480 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000481 }
482
483 /* Resolve function names
484 */
485 case TK_CONST_FUNC:
486 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000487 ExprList *pList = pExpr->x.pList; /* The argument list */
488 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000489 int no_such_func = 0; /* True if no such function exists */
490 int wrong_num_args = 0; /* True if wrong number of arguments */
491 int is_agg = 0; /* True if is an aggregate function */
492 int auth; /* Authorization to use the function */
493 int nId; /* Number of characters in function name */
494 const char *zId; /* The function name. */
495 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000496 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000497
drh73c0fdc2009-06-15 18:32:36 +0000498 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000499 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000500 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000501 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000502 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
503 if( pDef==0 ){
504 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
505 if( pDef==0 ){
506 no_such_func = 1;
507 }else{
508 wrong_num_args = 1;
509 }
510 }else{
511 is_agg = pDef->xFunc==0;
512 }
513#ifndef SQLITE_OMIT_AUTHORIZATION
514 if( pDef ){
515 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
516 if( auth!=SQLITE_OK ){
517 if( auth==SQLITE_DENY ){
518 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
519 pDef->zName);
520 pNC->nErr++;
521 }
522 pExpr->op = TK_NULL;
523 return WRC_Prune;
524 }
525 }
526#endif
527 if( is_agg && !pNC->allowAgg ){
528 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
529 pNC->nErr++;
530 is_agg = 0;
531 }else if( no_such_func ){
532 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
533 pNC->nErr++;
534 }else if( wrong_num_args ){
535 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
536 nId, zId);
537 pNC->nErr++;
538 }
539 if( is_agg ){
540 pExpr->op = TK_AGG_FUNCTION;
541 pNC->hasAgg = 1;
542 }
543 if( is_agg ) pNC->allowAgg = 0;
544 sqlite3WalkExprList(pWalker, pList);
545 if( is_agg ) pNC->allowAgg = 1;
546 /* FIX ME: Compute pExpr->affinity based on the expected return
547 ** type of the function
548 */
549 return WRC_Prune;
550 }
551#ifndef SQLITE_OMIT_SUBQUERY
552 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000553 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000554#endif
555 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000556 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000557 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000558 int nRef = pNC->nRef;
559#ifndef SQLITE_OMIT_CHECK
560 if( pNC->isCheck ){
561 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
562 }
563#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000564 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000565 assert( pNC->nRef>=nRef );
566 if( nRef!=pNC->nRef ){
567 ExprSetProperty(pExpr, EP_VarSelect);
568 }
569 }
570 break;
571 }
572#ifndef SQLITE_OMIT_CHECK
573 case TK_VARIABLE: {
574 if( pNC->isCheck ){
575 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
576 }
577 break;
578 }
579#endif
580 }
581 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
582}
583
584/*
585** pEList is a list of expressions which are really the result set of the
586** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
587** This routine checks to see if pE is a simple identifier which corresponds
588** to the AS-name of one of the terms of the expression list. If it is,
589** this routine return an integer between 1 and N where N is the number of
590** elements in pEList, corresponding to the matching entry. If there is
591** no match, or if pE is not a simple identifier, then this routine
592** return 0.
593**
594** pEList has been resolved. pE has not.
595*/
596static int resolveAsName(
597 Parse *pParse, /* Parsing context for error messages */
598 ExprList *pEList, /* List of expressions to scan */
599 Expr *pE /* Expression we are trying to match */
600){
601 int i; /* Loop counter */
602
shanecf697392009-06-01 16:53:09 +0000603 UNUSED_PARAMETER(pParse);
604
drh73c0fdc2009-06-15 18:32:36 +0000605 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000606 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000607 for(i=0; i<pEList->nExpr; i++){
608 char *zAs = pEList->a[i].zName;
609 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000610 return i+1;
611 }
612 }
drh7d10d5a2008-08-20 16:35:10 +0000613 }
614 return 0;
615}
616
617/*
618** pE is a pointer to an expression which is a single term in the
619** ORDER BY of a compound SELECT. The expression has not been
620** name resolved.
621**
622** At the point this routine is called, we already know that the
623** ORDER BY term is not an integer index into the result set. That
624** case is handled by the calling routine.
625**
626** Attempt to match pE against result set columns in the left-most
627** SELECT statement. Return the index i of the matching column,
628** as an indication to the caller that it should sort by the i-th column.
629** The left-most column is 1. In other words, the value returned is the
630** same integer value that would be used in the SQL statement to indicate
631** the column.
632**
633** If there is no match, return 0. Return -1 if an error occurs.
634*/
635static int resolveOrderByTermToExprList(
636 Parse *pParse, /* Parsing context for error messages */
637 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
638 Expr *pE /* The specific ORDER BY term */
639){
640 int i; /* Loop counter */
641 ExprList *pEList; /* The columns of the result set */
642 NameContext nc; /* Name context for resolving pE */
643
644 assert( sqlite3ExprIsInteger(pE, &i)==0 );
645 pEList = pSelect->pEList;
646
647 /* Resolve all names in the ORDER BY term expression
648 */
649 memset(&nc, 0, sizeof(nc));
650 nc.pParse = pParse;
651 nc.pSrcList = pSelect->pSrc;
652 nc.pEList = pEList;
653 nc.allowAgg = 1;
654 nc.nErr = 0;
655 if( sqlite3ResolveExprNames(&nc, pE) ){
656 sqlite3ErrorClear(pParse);
657 return 0;
658 }
659
660 /* Try to match the ORDER BY expression against an expression
661 ** in the result set. Return an 1-based index of the matching
662 ** result-set entry.
663 */
664 for(i=0; i<pEList->nExpr; i++){
665 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
666 return i+1;
667 }
668 }
669
670 /* If no match, return 0. */
671 return 0;
672}
673
674/*
675** Generate an ORDER BY or GROUP BY term out-of-range error.
676*/
677static void resolveOutOfRangeError(
678 Parse *pParse, /* The error context into which to write the error */
679 const char *zType, /* "ORDER" or "GROUP" */
680 int i, /* The index (1-based) of the term out of range */
681 int mx /* Largest permissible value of i */
682){
683 sqlite3ErrorMsg(pParse,
684 "%r %s BY term out of range - should be "
685 "between 1 and %d", i, zType, mx);
686}
687
688/*
689** Analyze the ORDER BY clause in a compound SELECT statement. Modify
690** each term of the ORDER BY clause is a constant integer between 1
691** and N where N is the number of columns in the compound SELECT.
692**
693** ORDER BY terms that are already an integer between 1 and N are
694** unmodified. ORDER BY terms that are integers outside the range of
695** 1 through N generate an error. ORDER BY terms that are expressions
696** are matched against result set expressions of compound SELECT
697** beginning with the left-most SELECT and working toward the right.
698** At the first match, the ORDER BY expression is transformed into
699** the integer column number.
700**
701** Return the number of errors seen.
702*/
703static int resolveCompoundOrderBy(
704 Parse *pParse, /* Parsing context. Leave error messages here */
705 Select *pSelect /* The SELECT statement containing the ORDER BY */
706){
707 int i;
708 ExprList *pOrderBy;
709 ExprList *pEList;
710 sqlite3 *db;
711 int moreToDo = 1;
712
713 pOrderBy = pSelect->pOrderBy;
714 if( pOrderBy==0 ) return 0;
715 db = pParse->db;
716#if SQLITE_MAX_COLUMN
717 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
718 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
719 return 1;
720 }
721#endif
722 for(i=0; i<pOrderBy->nExpr; i++){
723 pOrderBy->a[i].done = 0;
724 }
725 pSelect->pNext = 0;
726 while( pSelect->pPrior ){
727 pSelect->pPrior->pNext = pSelect;
728 pSelect = pSelect->pPrior;
729 }
730 while( pSelect && moreToDo ){
731 struct ExprList_item *pItem;
732 moreToDo = 0;
733 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000734 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000735 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
736 int iCol = -1;
737 Expr *pE, *pDup;
738 if( pItem->done ) continue;
739 pE = pItem->pExpr;
740 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000741 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000742 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
743 return 1;
744 }
745 }else{
746 iCol = resolveAsName(pParse, pEList, pE);
747 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000748 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000749 if( !db->mallocFailed ){
750 assert(pDup);
751 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
752 }
753 sqlite3ExprDelete(db, pDup);
754 }
drh7d10d5a2008-08-20 16:35:10 +0000755 }
756 if( iCol>0 ){
757 CollSeq *pColl = pE->pColl;
758 int flags = pE->flags & EP_ExpCollate;
759 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000760 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000761 if( pE==0 ) return 1;
762 pE->pColl = pColl;
763 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000764 pE->u.iValue = iCol;
drhea678832008-12-10 19:26:22 +0000765 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000766 pItem->done = 1;
767 }else{
768 moreToDo = 1;
769 }
770 }
771 pSelect = pSelect->pNext;
772 }
773 for(i=0; i<pOrderBy->nExpr; i++){
774 if( pOrderBy->a[i].done==0 ){
775 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
776 "column in the result set", i+1);
777 return 1;
778 }
779 }
780 return 0;
781}
782
783/*
784** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
785** the SELECT statement pSelect. If any term is reference to a
786** result set expression (as determined by the ExprList.a.iCol field)
787** then convert that term into a copy of the corresponding result set
788** column.
789**
790** If any errors are detected, add an error message to pParse and
791** return non-zero. Return zero if no errors are seen.
792*/
793int sqlite3ResolveOrderGroupBy(
794 Parse *pParse, /* Parsing context. Leave error messages here */
795 Select *pSelect, /* The SELECT statement containing the clause */
796 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
797 const char *zType /* "ORDER" or "GROUP" */
798){
799 int i;
800 sqlite3 *db = pParse->db;
801 ExprList *pEList;
802 struct ExprList_item *pItem;
803
804 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
805#if SQLITE_MAX_COLUMN
806 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
807 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
808 return 1;
809 }
810#endif
811 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000812 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000813 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
814 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000815 if( pItem->iCol>pEList->nExpr ){
816 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
817 return 1;
818 }
drh8b213892008-08-29 02:14:02 +0000819 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000820 }
821 }
822 return 0;
823}
824
825/*
826** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
827** The Name context of the SELECT statement is pNC. zType is either
828** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
829**
830** This routine resolves each term of the clause into an expression.
831** If the order-by term is an integer I between 1 and N (where N is the
832** number of columns in the result set of the SELECT) then the expression
833** in the resolution is a copy of the I-th result-set expression. If
834** the order-by term is an identify that corresponds to the AS-name of
835** a result-set expression, then the term resolves to a copy of the
836** result-set expression. Otherwise, the expression is resolved in
837** the usual way - using sqlite3ResolveExprNames().
838**
839** This routine returns the number of errors. If errors occur, then
840** an appropriate error message might be left in pParse. (OOM errors
841** excepted.)
842*/
843static int resolveOrderGroupBy(
844 NameContext *pNC, /* The name context of the SELECT statement */
845 Select *pSelect, /* The SELECT statement holding pOrderBy */
846 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
847 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
848){
849 int i; /* Loop counter */
850 int iCol; /* Column number */
851 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
852 Parse *pParse; /* Parsing context */
853 int nResult; /* Number of terms in the result set */
854
855 if( pOrderBy==0 ) return 0;
856 nResult = pSelect->pEList->nExpr;
857 pParse = pNC->pParse;
858 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
859 Expr *pE = pItem->pExpr;
860 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000861 if( iCol>0 ){
862 /* If an AS-name match is found, mark this ORDER BY column as being
863 ** a copy of the iCol-th result-set column. The subsequent call to
864 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
865 ** copy of the iCol-th result-set expression. */
drhea678832008-12-10 19:26:22 +0000866 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000867 continue;
868 }
869 if( sqlite3ExprIsInteger(pE, &iCol) ){
870 /* The ORDER BY term is an integer constant. Again, set the column
871 ** number so that sqlite3ResolveOrderGroupBy() will convert the
872 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000873 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000874 resolveOutOfRangeError(pParse, zType, i+1, nResult);
875 return 1;
876 }
drhea678832008-12-10 19:26:22 +0000877 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000878 continue;
879 }
880
881 /* Otherwise, treat the ORDER BY term as an ordinary expression */
882 pItem->iCol = 0;
883 if( sqlite3ResolveExprNames(pNC, pE) ){
884 return 1;
885 }
886 }
887 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
888}
889
890/*
891** Resolve names in the SELECT statement p and all of its descendents.
892*/
893static int resolveSelectStep(Walker *pWalker, Select *p){
894 NameContext *pOuterNC; /* Context that contains this SELECT */
895 NameContext sNC; /* Name context of this SELECT */
896 int isCompound; /* True if p is a compound select */
897 int nCompound; /* Number of compound terms processed so far */
898 Parse *pParse; /* Parsing context */
899 ExprList *pEList; /* Result set expression list */
900 int i; /* Loop counter */
901 ExprList *pGroupBy; /* The GROUP BY clause */
902 Select *pLeftmost; /* Left-most of SELECT of a compound */
903 sqlite3 *db; /* Database connection */
904
905
drh0a846f92008-08-25 17:23:29 +0000906 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000907 if( p->selFlags & SF_Resolved ){
908 return WRC_Prune;
909 }
910 pOuterNC = pWalker->u.pNC;
911 pParse = pWalker->pParse;
912 db = pParse->db;
913
914 /* Normally sqlite3SelectExpand() will be called first and will have
915 ** already expanded this SELECT. However, if this is a subquery within
916 ** an expression, sqlite3ResolveExprNames() will be called without a
917 ** prior call to sqlite3SelectExpand(). When that happens, let
918 ** sqlite3SelectPrep() do all of the processing for this SELECT.
919 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
920 ** this routine in the correct order.
921 */
922 if( (p->selFlags & SF_Expanded)==0 ){
923 sqlite3SelectPrep(pParse, p, pOuterNC);
924 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
925 }
926
927 isCompound = p->pPrior!=0;
928 nCompound = 0;
929 pLeftmost = p;
930 while( p ){
931 assert( (p->selFlags & SF_Expanded)!=0 );
932 assert( (p->selFlags & SF_Resolved)==0 );
933 p->selFlags |= SF_Resolved;
934
935 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
936 ** are not allowed to refer to any names, so pass an empty NameContext.
937 */
938 memset(&sNC, 0, sizeof(sNC));
939 sNC.pParse = pParse;
940 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
941 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
942 return WRC_Abort;
943 }
944
945 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
946 ** resolve the result-set expression list.
947 */
948 sNC.allowAgg = 1;
949 sNC.pSrcList = p->pSrc;
950 sNC.pNext = pOuterNC;
951
952 /* Resolve names in the result set. */
953 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000954 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000955 for(i=0; i<pEList->nExpr; i++){
956 Expr *pX = pEList->a[i].pExpr;
957 if( sqlite3ResolveExprNames(&sNC, pX) ){
958 return WRC_Abort;
959 }
960 }
961
962 /* Recursively resolve names in all subqueries
963 */
964 for(i=0; i<p->pSrc->nSrc; i++){
965 struct SrcList_item *pItem = &p->pSrc->a[i];
966 if( pItem->pSelect ){
967 const char *zSavedContext = pParse->zAuthContext;
968 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +0000969 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +0000970 pParse->zAuthContext = zSavedContext;
971 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
972 }
973 }
974
975 /* If there are no aggregate functions in the result-set, and no GROUP BY
976 ** expression, do not allow aggregates in any of the other expressions.
977 */
978 assert( (p->selFlags & SF_Aggregate)==0 );
979 pGroupBy = p->pGroupBy;
980 if( pGroupBy || sNC.hasAgg ){
981 p->selFlags |= SF_Aggregate;
982 }else{
983 sNC.allowAgg = 0;
984 }
985
986 /* If a HAVING clause is present, then there must be a GROUP BY clause.
987 */
988 if( p->pHaving && !pGroupBy ){
989 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
990 return WRC_Abort;
991 }
992
993 /* Add the expression list to the name-context before parsing the
994 ** other expressions in the SELECT statement. This is so that
995 ** expressions in the WHERE clause (etc.) can refer to expressions by
996 ** aliases in the result set.
997 **
998 ** Minor point: If this is the case, then the expression will be
999 ** re-evaluated for each reference to it.
1000 */
1001 sNC.pEList = p->pEList;
1002 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1003 sqlite3ResolveExprNames(&sNC, p->pHaving)
1004 ){
1005 return WRC_Abort;
1006 }
1007
1008 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1009 ** outer queries
1010 */
1011 sNC.pNext = 0;
1012 sNC.allowAgg = 1;
1013
1014 /* Process the ORDER BY clause for singleton SELECT statements.
1015 ** The ORDER BY clause for compounds SELECT statements is handled
1016 ** below, after all of the result-sets for all of the elements of
1017 ** the compound have been resolved.
1018 */
1019 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1020 return WRC_Abort;
1021 }
1022 if( db->mallocFailed ){
1023 return WRC_Abort;
1024 }
1025
1026 /* Resolve the GROUP BY clause. At the same time, make sure
1027 ** the GROUP BY clause does not contain aggregate functions.
1028 */
1029 if( pGroupBy ){
1030 struct ExprList_item *pItem;
1031
1032 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1033 return WRC_Abort;
1034 }
1035 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1036 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1037 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1038 "the GROUP BY clause");
1039 return WRC_Abort;
1040 }
1041 }
1042 }
1043
1044 /* Advance to the next term of the compound
1045 */
1046 p = p->pPrior;
1047 nCompound++;
1048 }
1049
1050 /* Resolve the ORDER BY on a compound SELECT after all terms of
1051 ** the compound have been resolved.
1052 */
1053 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1054 return WRC_Abort;
1055 }
1056
1057 return WRC_Prune;
1058}
1059
1060/*
1061** This routine walks an expression tree and resolves references to
1062** table columns and result-set columns. At the same time, do error
1063** checking on function usage and set a flag if any aggregate functions
1064** are seen.
1065**
1066** To resolve table columns references we look for nodes (or subtrees) of the
1067** form X.Y.Z or Y.Z or just Z where
1068**
1069** X: The name of a database. Ex: "main" or "temp" or
1070** the symbolic name assigned to an ATTACH-ed database.
1071**
1072** Y: The name of a table in a FROM clause. Or in a trigger
1073** one of the special names "old" or "new".
1074**
1075** Z: The name of a column in table Y.
1076**
1077** The node at the root of the subtree is modified as follows:
1078**
1079** Expr.op Changed to TK_COLUMN
1080** Expr.pTab Points to the Table object for X.Y
1081** Expr.iColumn The column index in X.Y. -1 for the rowid.
1082** Expr.iTable The VDBE cursor number for X.Y
1083**
1084**
1085** To resolve result-set references, look for expression nodes of the
1086** form Z (with no X and Y prefix) where the Z matches the right-hand
1087** size of an AS clause in the result-set of a SELECT. The Z expression
1088** is replaced by a copy of the left-hand side of the result-set expression.
1089** Table-name and function resolution occurs on the substituted expression
1090** tree. For example, in:
1091**
1092** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1093**
1094** The "x" term of the order by is replaced by "a+b" to render:
1095**
1096** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1097**
1098** Function calls are checked to make sure that the function is
1099** defined and that the correct number of arguments are specified.
1100** If the function is an aggregate function, then the pNC->hasAgg is
1101** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1102** If an expression contains aggregate functions then the EP_Agg
1103** property on the expression is set.
1104**
1105** An error message is left in pParse if anything is amiss. The number
1106** if errors is returned.
1107*/
1108int sqlite3ResolveExprNames(
1109 NameContext *pNC, /* Namespace to resolve expressions in. */
1110 Expr *pExpr /* The expression to be analyzed. */
1111){
1112 int savedHasAgg;
1113 Walker w;
1114
1115 if( pExpr==0 ) return 0;
1116#if SQLITE_MAX_EXPR_DEPTH>0
1117 {
1118 Parse *pParse = pNC->pParse;
1119 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1120 return 1;
1121 }
1122 pParse->nHeight += pExpr->nHeight;
1123 }
1124#endif
1125 savedHasAgg = pNC->hasAgg;
1126 pNC->hasAgg = 0;
1127 w.xExprCallback = resolveExprStep;
1128 w.xSelectCallback = resolveSelectStep;
1129 w.pParse = pNC->pParse;
1130 w.u.pNC = pNC;
1131 sqlite3WalkExpr(&w, pExpr);
1132#if SQLITE_MAX_EXPR_DEPTH>0
1133 pNC->pParse->nHeight -= pExpr->nHeight;
1134#endif
drhfd773cf2009-05-29 14:39:07 +00001135 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001136 ExprSetProperty(pExpr, EP_Error);
1137 }
1138 if( pNC->hasAgg ){
1139 ExprSetProperty(pExpr, EP_Agg);
1140 }else if( savedHasAgg ){
1141 pNC->hasAgg = 1;
1142 }
1143 return ExprHasProperty(pExpr, EP_Error);
1144}
drh7d10d5a2008-08-20 16:35:10 +00001145
1146
1147/*
1148** Resolve all names in all expressions of a SELECT and in all
1149** decendents of the SELECT, including compounds off of p->pPrior,
1150** subqueries in expressions, and subqueries used as FROM clause
1151** terms.
1152**
1153** See sqlite3ResolveExprNames() for a description of the kinds of
1154** transformations that occur.
1155**
1156** All SELECT statements should have been expanded using
1157** sqlite3SelectExpand() prior to invoking this routine.
1158*/
1159void sqlite3ResolveSelectNames(
1160 Parse *pParse, /* The parser context */
1161 Select *p, /* The SELECT statement being coded. */
1162 NameContext *pOuterNC /* Name context for parent SELECT statement */
1163){
1164 Walker w;
1165
drh0a846f92008-08-25 17:23:29 +00001166 assert( p!=0 );
1167 w.xExprCallback = resolveExprStep;
1168 w.xSelectCallback = resolveSelectStep;
1169 w.pParse = pParse;
1170 w.u.pNC = pOuterNC;
1171 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001172}