blob: b9c7face322a2f99fe214dd285e1de7cd9a961c2 [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**
drhb7916a72009-05-27 10:31:29 +000017** $Id: resolve.c,v 1.23 2009/05/27 10:31:29 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;
drhb7916a72009-05-27 10:31:29 +000074 }else{
75 char *zToken = pOrig->zToken;
76 pOrig->zToken = 0;
77 pDup = sqlite3ExprDup(db, pOrig, 0);
78 pOrig->zToken = zToken;
79 if( pDup==0 ) return;
80 if( zToken ){
81 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
82 pDup->flags2 |= EP2_FreeToken;
83 pDup->zToken = sqlite3DbStrDup(db, zToken);
84 }
drh8b213892008-08-29 02:14:02 +000085 }
86 if( pExpr->flags & EP_ExpCollate ){
87 pDup->pColl = pExpr->pColl;
88 pDup->flags |= EP_ExpCollate;
89 }
drh10fe8402008-10-11 16:47:35 +000090 sqlite3ExprClear(db, pExpr);
drh8b213892008-08-29 02:14:02 +000091 memcpy(pExpr, pDup, sizeof(*pExpr));
92 sqlite3DbFree(db, pDup);
93}
94
95/*
drh7d10d5a2008-08-20 16:35:10 +000096** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
97** that name in the set of source tables in pSrcList and make the pExpr
98** expression node refer back to that source column. The following changes
99** are made to pExpr:
100**
101** pExpr->iDb Set the index in db->aDb[] of the database X
102** (even if X is implied).
103** pExpr->iTable Set to the cursor number for the table obtained
104** from pSrcList.
105** pExpr->pTab Points to the Table structure of X.Y (even if
106** X and/or Y are implied.)
107** pExpr->iColumn Set to the column number within the table.
108** pExpr->op Set to TK_COLUMN.
109** pExpr->pLeft Any expression this points to is deleted
110** pExpr->pRight Any expression this points to is deleted.
111**
drhb7916a72009-05-27 10:31:29 +0000112** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000113** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000114** can be used. The zTable variable is the name of the table (the "Y"). This
115** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000116** means that the form of the name is Z and that columns from any table
117** can be used.
118**
119** If the name cannot be resolved unambiguously, leave an error message
120** in pParse and return non-zero. Return zero on success.
121*/
122static int lookupName(
123 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000124 const char *zDb, /* Name of the database containing table, or NULL */
125 const char *zTab, /* Name of table containing column, or NULL */
126 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000127 NameContext *pNC, /* The name context used to resolve the name */
128 Expr *pExpr /* Make this EXPR node point to the selected column */
129){
drh7d10d5a2008-08-20 16:35:10 +0000130 int i, j; /* Loop counters */
131 int cnt = 0; /* Number of matching column names */
132 int cntTab = 0; /* Number of matching table names */
133 sqlite3 *db = pParse->db; /* The database connection */
134 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
135 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
136 NameContext *pTopNC = pNC; /* First namecontext in the list */
137 Schema *pSchema = 0; /* Schema of the expression */
138
drhb7916a72009-05-27 10:31:29 +0000139 assert( pNC ); /* the name context cannot be NULL. */
140 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh7d10d5a2008-08-20 16:35:10 +0000141
142 /* Initialize the node to no-match */
143 pExpr->iTable = -1;
144 pExpr->pTab = 0;
145
146 /* Start at the inner-most context and move outward until a match is found */
147 while( pNC && cnt==0 ){
148 ExprList *pEList;
149 SrcList *pSrcList = pNC->pSrcList;
150
151 if( pSrcList ){
152 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
153 Table *pTab;
154 int iDb;
155 Column *pCol;
156
157 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000158 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000159 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
160 assert( pTab->nCol>0 );
161 if( zTab ){
162 if( pItem->zAlias ){
163 char *zTabName = pItem->zAlias;
164 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
165 }else{
166 char *zTabName = pTab->zName;
167 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
168 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
169 continue;
170 }
171 }
172 }
173 if( 0==(cntTab++) ){
174 pExpr->iTable = pItem->iCursor;
175 pExpr->pTab = pTab;
176 pSchema = pTab->pSchema;
177 pMatch = pItem;
178 }
179 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
180 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
181 IdList *pUsing;
182 cnt++;
183 pExpr->iTable = pItem->iCursor;
184 pExpr->pTab = pTab;
185 pMatch = pItem;
186 pSchema = pTab->pSchema;
187 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
188 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
189 if( i<pSrcList->nSrc-1 ){
190 if( pItem[1].jointype & JT_NATURAL ){
191 /* If this match occurred in the left table of a natural join,
192 ** then skip the right table to avoid a duplicate match */
193 pItem++;
194 i++;
195 }else if( (pUsing = pItem[1].pUsing)!=0 ){
196 /* If this match occurs on a column that is in the USING clause
197 ** of a join, skip the search of the right table of the join
198 ** to avoid a duplicate match there. */
199 int k;
200 for(k=0; k<pUsing->nId; k++){
201 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
202 pItem++;
203 i++;
204 break;
205 }
206 }
207 }
208 }
209 break;
210 }
211 }
212 }
213 }
214
215#ifndef SQLITE_OMIT_TRIGGER
216 /* If we have not already resolved the name, then maybe
217 ** it is a new.* or old.* trigger argument reference
218 */
219 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
220 TriggerStack *pTriggerStack = pParse->trigStack;
221 Table *pTab = 0;
drhb27b7f52008-12-10 18:03:45 +0000222 u32 *piColMask = 0;
drh7d10d5a2008-08-20 16:35:10 +0000223 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
224 pExpr->iTable = pTriggerStack->newIdx;
225 assert( pTriggerStack->pTab );
226 pTab = pTriggerStack->pTab;
227 piColMask = &(pTriggerStack->newColMask);
228 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
229 pExpr->iTable = pTriggerStack->oldIdx;
230 assert( pTriggerStack->pTab );
231 pTab = pTriggerStack->pTab;
232 piColMask = &(pTriggerStack->oldColMask);
233 }
234
235 if( pTab ){
236 int iCol;
237 Column *pCol = pTab->aCol;
238
239 pSchema = pTab->pSchema;
240 cntTab++;
241 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
242 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
243 cnt++;
244 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
245 pExpr->pTab = pTab;
246 if( iCol>=0 ){
247 testcase( iCol==31 );
248 testcase( iCol==32 );
drh3500ed62009-05-05 15:46:43 +0000249 if( iCol>=32 ){
250 *piColMask = 0xffffffff;
251 }else{
252 *piColMask |= ((u32)1)<<iCol;
253 }
drh7d10d5a2008-08-20 16:35:10 +0000254 }
255 break;
256 }
257 }
258 }
259 }
260#endif /* !defined(SQLITE_OMIT_TRIGGER) */
261
262 /*
263 ** Perhaps the name is a reference to the ROWID
264 */
265 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
266 cnt = 1;
267 pExpr->iColumn = -1;
268 pExpr->affinity = SQLITE_AFF_INTEGER;
269 }
270
271 /*
272 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
273 ** might refer to an result-set alias. This happens, for example, when
274 ** we are resolving names in the WHERE clause of the following command:
275 **
276 ** SELECT a+b AS x FROM table WHERE x<10;
277 **
278 ** In cases like this, replace pExpr with a copy of the expression that
279 ** forms the result set entry ("a+b" in the example) and return immediately.
280 ** Note that the expression in the result set should have already been
281 ** resolved by the time the WHERE clause is resolved.
282 */
283 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
284 for(j=0; j<pEList->nExpr; j++){
285 char *zAs = pEList->a[j].zName;
286 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000287 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000288 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000289 assert( pExpr->x.pList==0 );
290 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000291 pOrig = pEList->a[j].pExpr;
292 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
293 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drh7d10d5a2008-08-20 16:35:10 +0000294 return 2;
295 }
drh8b213892008-08-29 02:14:02 +0000296 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000297 cnt = 1;
298 pMatch = 0;
299 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000300 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000301 }
302 }
303 }
304
305 /* Advance to the next name context. The loop will exit when either
306 ** we have a match (cnt>0) or when we run out of name contexts.
307 */
308 if( cnt==0 ){
309 pNC = pNC->pNext;
310 }
311 }
312
313 /*
314 ** If X and Y are NULL (in other words if only the column name Z is
315 ** supplied) and the value of Z is enclosed in double-quotes, then
316 ** Z is a string literal if it doesn't match any column names. In that
317 ** case, we need to return right away and not make any changes to
318 ** pExpr.
319 **
320 ** Because no reference was made to outer contexts, the pNC->nRef
321 ** fields are not changed in any context.
322 */
drh24fb6272009-05-01 21:13:36 +0000323 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000324 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000325 pExpr->pTab = 0;
drh7d10d5a2008-08-20 16:35:10 +0000326 return 0;
327 }
328
329 /*
330 ** cnt==0 means there was not match. cnt>1 means there were two or
331 ** more matches. Either way, we have an error.
332 */
333 if( cnt!=1 ){
334 const char *zErr;
335 zErr = cnt==0 ? "no such column" : "ambiguous column name";
336 if( zDb ){
337 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
338 }else if( zTab ){
339 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
340 }else{
341 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
342 }
343 pTopNC->nErr++;
344 }
345
346 /* If a column from a table in pSrcList is referenced, then record
347 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
348 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
349 ** column number is greater than the number of bits in the bitmask
350 ** then set the high-order bit of the bitmask.
351 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000352 if( pExpr->iColumn>=0 && pMatch!=0 ){
353 int n = pExpr->iColumn;
354 testcase( n==BMS-1 );
355 if( n>=BMS ){
356 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000357 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000358 assert( pMatch->iCursor==pExpr->iTable );
359 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000360 }
361
drh7d10d5a2008-08-20 16:35:10 +0000362 /* Clean up and return
363 */
drh7d10d5a2008-08-20 16:35:10 +0000364 sqlite3ExprDelete(db, pExpr->pLeft);
365 pExpr->pLeft = 0;
366 sqlite3ExprDelete(db, pExpr->pRight);
367 pExpr->pRight = 0;
368 pExpr->op = TK_COLUMN;
drhb7916a72009-05-27 10:31:29 +0000369lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000370 if( cnt==1 ){
371 assert( pNC!=0 );
372 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
373 /* Increment the nRef value on all name contexts from TopNC up to
374 ** the point where the name matched. */
375 for(;;){
376 assert( pTopNC!=0 );
377 pTopNC->nRef++;
378 if( pTopNC==pNC ) break;
379 pTopNC = pTopNC->pNext;
380 }
381 return 0;
382 } else {
383 return 1;
384 }
385}
386
387/*
388** This routine is callback for sqlite3WalkExpr().
389**
390** Resolve symbolic names into TK_COLUMN operators for the current
391** node in the expression tree. Return 0 to continue the search down
392** the tree or 2 to abort the tree walk.
393**
394** This routine also does error checking and name resolution for
395** function names. The operator for aggregate functions is changed
396** to TK_AGG_FUNCTION.
397*/
398static int resolveExprStep(Walker *pWalker, Expr *pExpr){
399 NameContext *pNC;
400 Parse *pParse;
401
drh7d10d5a2008-08-20 16:35:10 +0000402 pNC = pWalker->u.pNC;
403 assert( pNC!=0 );
404 pParse = pNC->pParse;
405 assert( pParse==pWalker->pParse );
406
407 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
408 ExprSetProperty(pExpr, EP_Resolved);
409#ifndef NDEBUG
410 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
411 SrcList *pSrcList = pNC->pSrcList;
412 int i;
413 for(i=0; i<pNC->pSrcList->nSrc; i++){
414 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
415 }
416 }
417#endif
418 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000419
shane273f6192008-10-10 04:34:16 +0000420#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000421 /* The special operator TK_ROW means use the rowid for the first
422 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
423 ** clause processing on UPDATE and DELETE statements.
424 */
425 case TK_ROW: {
426 SrcList *pSrcList = pNC->pSrcList;
427 struct SrcList_item *pItem;
428 assert( pSrcList && pSrcList->nSrc==1 );
429 pItem = pSrcList->a;
430 pExpr->op = TK_COLUMN;
431 pExpr->pTab = pItem->pTab;
432 pExpr->iTable = pItem->iCursor;
433 pExpr->iColumn = -1;
434 pExpr->affinity = SQLITE_AFF_INTEGER;
435 break;
436 }
shane273f6192008-10-10 04:34:16 +0000437#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000438
drh7d10d5a2008-08-20 16:35:10 +0000439 /* A lone identifier is the name of a column.
440 */
441 case TK_ID: {
drhb7916a72009-05-27 10:31:29 +0000442 lookupName(pParse, 0, 0, pExpr->zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000443 return WRC_Prune;
444 }
445
446 /* A table name and column name: ID.ID
447 ** Or a database, table and column: ID.ID.ID
448 */
449 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000450 const char *zColumn;
451 const char *zTable;
452 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000453 Expr *pRight;
454
455 /* if( pSrcList==0 ) break; */
456 pRight = pExpr->pRight;
457 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000458 zDb = 0;
459 zTable = pExpr->pLeft->zToken;
460 zColumn = pRight->zToken;
drh7d10d5a2008-08-20 16:35:10 +0000461 }else{
462 assert( pRight->op==TK_DOT );
drhb7916a72009-05-27 10:31:29 +0000463 zDb = pExpr->pLeft->zToken;
464 zTable = pRight->pLeft->zToken;
465 zColumn = pRight->pRight->zToken;
drh7d10d5a2008-08-20 16:35:10 +0000466 }
drhb7916a72009-05-27 10:31:29 +0000467 lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000468 return WRC_Prune;
469 }
470
471 /* Resolve function names
472 */
473 case TK_CONST_FUNC:
474 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000475 ExprList *pList = pExpr->x.pList; /* The argument list */
476 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000477 int no_such_func = 0; /* True if no such function exists */
478 int wrong_num_args = 0; /* True if wrong number of arguments */
479 int is_agg = 0; /* True if is an aggregate function */
480 int auth; /* Authorization to use the function */
481 int nId; /* Number of characters in function name */
482 const char *zId; /* The function name. */
483 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000484 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000485
danielk19776ab3a2e2009-02-19 14:39:25 +0000486 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhb7916a72009-05-27 10:31:29 +0000487 zId = pExpr->zToken;
488 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000489 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
490 if( pDef==0 ){
491 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
492 if( pDef==0 ){
493 no_such_func = 1;
494 }else{
495 wrong_num_args = 1;
496 }
497 }else{
498 is_agg = pDef->xFunc==0;
499 }
500#ifndef SQLITE_OMIT_AUTHORIZATION
501 if( pDef ){
502 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
503 if( auth!=SQLITE_OK ){
504 if( auth==SQLITE_DENY ){
505 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
506 pDef->zName);
507 pNC->nErr++;
508 }
509 pExpr->op = TK_NULL;
510 return WRC_Prune;
511 }
512 }
513#endif
514 if( is_agg && !pNC->allowAgg ){
515 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
516 pNC->nErr++;
517 is_agg = 0;
518 }else if( no_such_func ){
519 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
520 pNC->nErr++;
521 }else if( wrong_num_args ){
522 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
523 nId, zId);
524 pNC->nErr++;
525 }
526 if( is_agg ){
527 pExpr->op = TK_AGG_FUNCTION;
528 pNC->hasAgg = 1;
529 }
530 if( is_agg ) pNC->allowAgg = 0;
531 sqlite3WalkExprList(pWalker, pList);
532 if( is_agg ) pNC->allowAgg = 1;
533 /* FIX ME: Compute pExpr->affinity based on the expected return
534 ** type of the function
535 */
536 return WRC_Prune;
537 }
538#ifndef SQLITE_OMIT_SUBQUERY
539 case TK_SELECT:
540 case TK_EXISTS:
541#endif
542 case TK_IN: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000543 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000544 int nRef = pNC->nRef;
545#ifndef SQLITE_OMIT_CHECK
546 if( pNC->isCheck ){
547 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
548 }
549#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000550 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000551 assert( pNC->nRef>=nRef );
552 if( nRef!=pNC->nRef ){
553 ExprSetProperty(pExpr, EP_VarSelect);
554 }
555 }
556 break;
557 }
558#ifndef SQLITE_OMIT_CHECK
559 case TK_VARIABLE: {
560 if( pNC->isCheck ){
561 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
562 }
563 break;
564 }
565#endif
566 }
567 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
568}
569
570/*
571** pEList is a list of expressions which are really the result set of the
572** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
573** This routine checks to see if pE is a simple identifier which corresponds
574** to the AS-name of one of the terms of the expression list. If it is,
575** this routine return an integer between 1 and N where N is the number of
576** elements in pEList, corresponding to the matching entry. If there is
577** no match, or if pE is not a simple identifier, then this routine
578** return 0.
579**
580** pEList has been resolved. pE has not.
581*/
582static int resolveAsName(
583 Parse *pParse, /* Parsing context for error messages */
584 ExprList *pEList, /* List of expressions to scan */
585 Expr *pE /* Expression we are trying to match */
586){
587 int i; /* Loop counter */
588
drhb7916a72009-05-27 10:31:29 +0000589 if( pE->op==TK_ID || (pE->op==TK_STRING && pE->zToken[0]!='\'') ){
590 char *zCol = pE->zToken;
drh7d10d5a2008-08-20 16:35:10 +0000591 for(i=0; i<pEList->nExpr; i++){
592 char *zAs = pEList->a[i].zName;
593 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000594 return i+1;
595 }
596 }
drh7d10d5a2008-08-20 16:35:10 +0000597 }
598 return 0;
599}
600
601/*
602** pE is a pointer to an expression which is a single term in the
603** ORDER BY of a compound SELECT. The expression has not been
604** name resolved.
605**
606** At the point this routine is called, we already know that the
607** ORDER BY term is not an integer index into the result set. That
608** case is handled by the calling routine.
609**
610** Attempt to match pE against result set columns in the left-most
611** SELECT statement. Return the index i of the matching column,
612** as an indication to the caller that it should sort by the i-th column.
613** The left-most column is 1. In other words, the value returned is the
614** same integer value that would be used in the SQL statement to indicate
615** the column.
616**
617** If there is no match, return 0. Return -1 if an error occurs.
618*/
619static int resolveOrderByTermToExprList(
620 Parse *pParse, /* Parsing context for error messages */
621 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
622 Expr *pE /* The specific ORDER BY term */
623){
624 int i; /* Loop counter */
625 ExprList *pEList; /* The columns of the result set */
626 NameContext nc; /* Name context for resolving pE */
627
628 assert( sqlite3ExprIsInteger(pE, &i)==0 );
629 pEList = pSelect->pEList;
630
631 /* Resolve all names in the ORDER BY term expression
632 */
633 memset(&nc, 0, sizeof(nc));
634 nc.pParse = pParse;
635 nc.pSrcList = pSelect->pSrc;
636 nc.pEList = pEList;
637 nc.allowAgg = 1;
638 nc.nErr = 0;
639 if( sqlite3ResolveExprNames(&nc, pE) ){
640 sqlite3ErrorClear(pParse);
641 return 0;
642 }
643
644 /* Try to match the ORDER BY expression against an expression
645 ** in the result set. Return an 1-based index of the matching
646 ** result-set entry.
647 */
648 for(i=0; i<pEList->nExpr; i++){
649 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
650 return i+1;
651 }
652 }
653
654 /* If no match, return 0. */
655 return 0;
656}
657
658/*
659** Generate an ORDER BY or GROUP BY term out-of-range error.
660*/
661static void resolveOutOfRangeError(
662 Parse *pParse, /* The error context into which to write the error */
663 const char *zType, /* "ORDER" or "GROUP" */
664 int i, /* The index (1-based) of the term out of range */
665 int mx /* Largest permissible value of i */
666){
667 sqlite3ErrorMsg(pParse,
668 "%r %s BY term out of range - should be "
669 "between 1 and %d", i, zType, mx);
670}
671
672/*
673** Analyze the ORDER BY clause in a compound SELECT statement. Modify
674** each term of the ORDER BY clause is a constant integer between 1
675** and N where N is the number of columns in the compound SELECT.
676**
677** ORDER BY terms that are already an integer between 1 and N are
678** unmodified. ORDER BY terms that are integers outside the range of
679** 1 through N generate an error. ORDER BY terms that are expressions
680** are matched against result set expressions of compound SELECT
681** beginning with the left-most SELECT and working toward the right.
682** At the first match, the ORDER BY expression is transformed into
683** the integer column number.
684**
685** Return the number of errors seen.
686*/
687static int resolveCompoundOrderBy(
688 Parse *pParse, /* Parsing context. Leave error messages here */
689 Select *pSelect /* The SELECT statement containing the ORDER BY */
690){
691 int i;
692 ExprList *pOrderBy;
693 ExprList *pEList;
694 sqlite3 *db;
695 int moreToDo = 1;
696
697 pOrderBy = pSelect->pOrderBy;
698 if( pOrderBy==0 ) return 0;
699 db = pParse->db;
700#if SQLITE_MAX_COLUMN
701 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
702 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
703 return 1;
704 }
705#endif
706 for(i=0; i<pOrderBy->nExpr; i++){
707 pOrderBy->a[i].done = 0;
708 }
709 pSelect->pNext = 0;
710 while( pSelect->pPrior ){
711 pSelect->pPrior->pNext = pSelect;
712 pSelect = pSelect->pPrior;
713 }
714 while( pSelect && moreToDo ){
715 struct ExprList_item *pItem;
716 moreToDo = 0;
717 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000718 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000719 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
720 int iCol = -1;
721 Expr *pE, *pDup;
722 if( pItem->done ) continue;
723 pE = pItem->pExpr;
724 if( sqlite3ExprIsInteger(pE, &iCol) ){
725 if( iCol<0 || iCol>pEList->nExpr ){
726 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
727 return 1;
728 }
729 }else{
730 iCol = resolveAsName(pParse, pEList, pE);
731 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000732 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000733 if( !db->mallocFailed ){
734 assert(pDup);
735 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
736 }
737 sqlite3ExprDelete(db, pDup);
738 }
739 if( iCol<0 ){
740 return 1;
741 }
742 }
743 if( iCol>0 ){
744 CollSeq *pColl = pE->pColl;
745 int flags = pE->flags & EP_ExpCollate;
746 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000747 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000748 if( pE==0 ) return 1;
749 pE->pColl = pColl;
750 pE->flags |= EP_IntValue | flags;
751 pE->iTable = iCol;
drhea678832008-12-10 19:26:22 +0000752 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000753 pItem->done = 1;
754 }else{
755 moreToDo = 1;
756 }
757 }
758 pSelect = pSelect->pNext;
759 }
760 for(i=0; i<pOrderBy->nExpr; i++){
761 if( pOrderBy->a[i].done==0 ){
762 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
763 "column in the result set", i+1);
764 return 1;
765 }
766 }
767 return 0;
768}
769
770/*
771** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
772** the SELECT statement pSelect. If any term is reference to a
773** result set expression (as determined by the ExprList.a.iCol field)
774** then convert that term into a copy of the corresponding result set
775** column.
776**
777** If any errors are detected, add an error message to pParse and
778** return non-zero. Return zero if no errors are seen.
779*/
780int sqlite3ResolveOrderGroupBy(
781 Parse *pParse, /* Parsing context. Leave error messages here */
782 Select *pSelect, /* The SELECT statement containing the clause */
783 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
784 const char *zType /* "ORDER" or "GROUP" */
785){
786 int i;
787 sqlite3 *db = pParse->db;
788 ExprList *pEList;
789 struct ExprList_item *pItem;
790
791 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
792#if SQLITE_MAX_COLUMN
793 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
794 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
795 return 1;
796 }
797#endif
798 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000799 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000800 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
801 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000802 if( pItem->iCol>pEList->nExpr ){
803 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
804 return 1;
805 }
drh8b213892008-08-29 02:14:02 +0000806 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000807 }
808 }
809 return 0;
810}
811
812/*
813** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
814** The Name context of the SELECT statement is pNC. zType is either
815** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
816**
817** This routine resolves each term of the clause into an expression.
818** If the order-by term is an integer I between 1 and N (where N is the
819** number of columns in the result set of the SELECT) then the expression
820** in the resolution is a copy of the I-th result-set expression. If
821** the order-by term is an identify that corresponds to the AS-name of
822** a result-set expression, then the term resolves to a copy of the
823** result-set expression. Otherwise, the expression is resolved in
824** the usual way - using sqlite3ResolveExprNames().
825**
826** This routine returns the number of errors. If errors occur, then
827** an appropriate error message might be left in pParse. (OOM errors
828** excepted.)
829*/
830static int resolveOrderGroupBy(
831 NameContext *pNC, /* The name context of the SELECT statement */
832 Select *pSelect, /* The SELECT statement holding pOrderBy */
833 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
834 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
835){
836 int i; /* Loop counter */
837 int iCol; /* Column number */
838 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
839 Parse *pParse; /* Parsing context */
840 int nResult; /* Number of terms in the result set */
841
842 if( pOrderBy==0 ) return 0;
843 nResult = pSelect->pEList->nExpr;
844 pParse = pNC->pParse;
845 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
846 Expr *pE = pItem->pExpr;
847 iCol = resolveAsName(pParse, pSelect->pEList, pE);
848 if( iCol<0 ){
849 return 1; /* OOM error */
850 }
851 if( iCol>0 ){
852 /* If an AS-name match is found, mark this ORDER BY column as being
853 ** a copy of the iCol-th result-set column. The subsequent call to
854 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
855 ** copy of the iCol-th result-set expression. */
drhea678832008-12-10 19:26:22 +0000856 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000857 continue;
858 }
859 if( sqlite3ExprIsInteger(pE, &iCol) ){
860 /* The ORDER BY term is an integer constant. Again, set the column
861 ** number so that sqlite3ResolveOrderGroupBy() will convert the
862 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000863 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000864 resolveOutOfRangeError(pParse, zType, i+1, nResult);
865 return 1;
866 }
drhea678832008-12-10 19:26:22 +0000867 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000868 continue;
869 }
870
871 /* Otherwise, treat the ORDER BY term as an ordinary expression */
872 pItem->iCol = 0;
873 if( sqlite3ResolveExprNames(pNC, pE) ){
874 return 1;
875 }
876 }
877 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
878}
879
880/*
881** Resolve names in the SELECT statement p and all of its descendents.
882*/
883static int resolveSelectStep(Walker *pWalker, Select *p){
884 NameContext *pOuterNC; /* Context that contains this SELECT */
885 NameContext sNC; /* Name context of this SELECT */
886 int isCompound; /* True if p is a compound select */
887 int nCompound; /* Number of compound terms processed so far */
888 Parse *pParse; /* Parsing context */
889 ExprList *pEList; /* Result set expression list */
890 int i; /* Loop counter */
891 ExprList *pGroupBy; /* The GROUP BY clause */
892 Select *pLeftmost; /* Left-most of SELECT of a compound */
893 sqlite3 *db; /* Database connection */
894
895
drh0a846f92008-08-25 17:23:29 +0000896 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000897 if( p->selFlags & SF_Resolved ){
898 return WRC_Prune;
899 }
900 pOuterNC = pWalker->u.pNC;
901 pParse = pWalker->pParse;
902 db = pParse->db;
903
904 /* Normally sqlite3SelectExpand() will be called first and will have
905 ** already expanded this SELECT. However, if this is a subquery within
906 ** an expression, sqlite3ResolveExprNames() will be called without a
907 ** prior call to sqlite3SelectExpand(). When that happens, let
908 ** sqlite3SelectPrep() do all of the processing for this SELECT.
909 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
910 ** this routine in the correct order.
911 */
912 if( (p->selFlags & SF_Expanded)==0 ){
913 sqlite3SelectPrep(pParse, p, pOuterNC);
914 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
915 }
916
917 isCompound = p->pPrior!=0;
918 nCompound = 0;
919 pLeftmost = p;
920 while( p ){
921 assert( (p->selFlags & SF_Expanded)!=0 );
922 assert( (p->selFlags & SF_Resolved)==0 );
923 p->selFlags |= SF_Resolved;
924
925 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
926 ** are not allowed to refer to any names, so pass an empty NameContext.
927 */
928 memset(&sNC, 0, sizeof(sNC));
929 sNC.pParse = pParse;
930 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
931 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
932 return WRC_Abort;
933 }
934
935 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
936 ** resolve the result-set expression list.
937 */
938 sNC.allowAgg = 1;
939 sNC.pSrcList = p->pSrc;
940 sNC.pNext = pOuterNC;
941
942 /* Resolve names in the result set. */
943 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000944 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000945 for(i=0; i<pEList->nExpr; i++){
946 Expr *pX = pEList->a[i].pExpr;
947 if( sqlite3ResolveExprNames(&sNC, pX) ){
948 return WRC_Abort;
949 }
950 }
951
952 /* Recursively resolve names in all subqueries
953 */
954 for(i=0; i<p->pSrc->nSrc; i++){
955 struct SrcList_item *pItem = &p->pSrc->a[i];
956 if( pItem->pSelect ){
957 const char *zSavedContext = pParse->zAuthContext;
958 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +0000959 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +0000960 pParse->zAuthContext = zSavedContext;
961 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
962 }
963 }
964
965 /* If there are no aggregate functions in the result-set, and no GROUP BY
966 ** expression, do not allow aggregates in any of the other expressions.
967 */
968 assert( (p->selFlags & SF_Aggregate)==0 );
969 pGroupBy = p->pGroupBy;
970 if( pGroupBy || sNC.hasAgg ){
971 p->selFlags |= SF_Aggregate;
972 }else{
973 sNC.allowAgg = 0;
974 }
975
976 /* If a HAVING clause is present, then there must be a GROUP BY clause.
977 */
978 if( p->pHaving && !pGroupBy ){
979 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
980 return WRC_Abort;
981 }
982
983 /* Add the expression list to the name-context before parsing the
984 ** other expressions in the SELECT statement. This is so that
985 ** expressions in the WHERE clause (etc.) can refer to expressions by
986 ** aliases in the result set.
987 **
988 ** Minor point: If this is the case, then the expression will be
989 ** re-evaluated for each reference to it.
990 */
991 sNC.pEList = p->pEList;
992 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
993 sqlite3ResolveExprNames(&sNC, p->pHaving)
994 ){
995 return WRC_Abort;
996 }
997
998 /* The ORDER BY and GROUP BY clauses may not refer to terms in
999 ** outer queries
1000 */
1001 sNC.pNext = 0;
1002 sNC.allowAgg = 1;
1003
1004 /* Process the ORDER BY clause for singleton SELECT statements.
1005 ** The ORDER BY clause for compounds SELECT statements is handled
1006 ** below, after all of the result-sets for all of the elements of
1007 ** the compound have been resolved.
1008 */
1009 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1010 return WRC_Abort;
1011 }
1012 if( db->mallocFailed ){
1013 return WRC_Abort;
1014 }
1015
1016 /* Resolve the GROUP BY clause. At the same time, make sure
1017 ** the GROUP BY clause does not contain aggregate functions.
1018 */
1019 if( pGroupBy ){
1020 struct ExprList_item *pItem;
1021
1022 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1023 return WRC_Abort;
1024 }
1025 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1026 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1027 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1028 "the GROUP BY clause");
1029 return WRC_Abort;
1030 }
1031 }
1032 }
1033
1034 /* Advance to the next term of the compound
1035 */
1036 p = p->pPrior;
1037 nCompound++;
1038 }
1039
1040 /* Resolve the ORDER BY on a compound SELECT after all terms of
1041 ** the compound have been resolved.
1042 */
1043 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1044 return WRC_Abort;
1045 }
1046
1047 return WRC_Prune;
1048}
1049
1050/*
1051** This routine walks an expression tree and resolves references to
1052** table columns and result-set columns. At the same time, do error
1053** checking on function usage and set a flag if any aggregate functions
1054** are seen.
1055**
1056** To resolve table columns references we look for nodes (or subtrees) of the
1057** form X.Y.Z or Y.Z or just Z where
1058**
1059** X: The name of a database. Ex: "main" or "temp" or
1060** the symbolic name assigned to an ATTACH-ed database.
1061**
1062** Y: The name of a table in a FROM clause. Or in a trigger
1063** one of the special names "old" or "new".
1064**
1065** Z: The name of a column in table Y.
1066**
1067** The node at the root of the subtree is modified as follows:
1068**
1069** Expr.op Changed to TK_COLUMN
1070** Expr.pTab Points to the Table object for X.Y
1071** Expr.iColumn The column index in X.Y. -1 for the rowid.
1072** Expr.iTable The VDBE cursor number for X.Y
1073**
1074**
1075** To resolve result-set references, look for expression nodes of the
1076** form Z (with no X and Y prefix) where the Z matches the right-hand
1077** size of an AS clause in the result-set of a SELECT. The Z expression
1078** is replaced by a copy of the left-hand side of the result-set expression.
1079** Table-name and function resolution occurs on the substituted expression
1080** tree. For example, in:
1081**
1082** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1083**
1084** The "x" term of the order by is replaced by "a+b" to render:
1085**
1086** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1087**
1088** Function calls are checked to make sure that the function is
1089** defined and that the correct number of arguments are specified.
1090** If the function is an aggregate function, then the pNC->hasAgg is
1091** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1092** If an expression contains aggregate functions then the EP_Agg
1093** property on the expression is set.
1094**
1095** An error message is left in pParse if anything is amiss. The number
1096** if errors is returned.
1097*/
1098int sqlite3ResolveExprNames(
1099 NameContext *pNC, /* Namespace to resolve expressions in. */
1100 Expr *pExpr /* The expression to be analyzed. */
1101){
1102 int savedHasAgg;
1103 Walker w;
1104
1105 if( pExpr==0 ) return 0;
1106#if SQLITE_MAX_EXPR_DEPTH>0
1107 {
1108 Parse *pParse = pNC->pParse;
1109 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1110 return 1;
1111 }
1112 pParse->nHeight += pExpr->nHeight;
1113 }
1114#endif
1115 savedHasAgg = pNC->hasAgg;
1116 pNC->hasAgg = 0;
1117 w.xExprCallback = resolveExprStep;
1118 w.xSelectCallback = resolveSelectStep;
1119 w.pParse = pNC->pParse;
1120 w.u.pNC = pNC;
1121 sqlite3WalkExpr(&w, pExpr);
1122#if SQLITE_MAX_EXPR_DEPTH>0
1123 pNC->pParse->nHeight -= pExpr->nHeight;
1124#endif
1125 if( pNC->nErr>0 ){
1126 ExprSetProperty(pExpr, EP_Error);
1127 }
1128 if( pNC->hasAgg ){
1129 ExprSetProperty(pExpr, EP_Agg);
1130 }else if( savedHasAgg ){
1131 pNC->hasAgg = 1;
1132 }
1133 return ExprHasProperty(pExpr, EP_Error);
1134}
drh7d10d5a2008-08-20 16:35:10 +00001135
1136
1137/*
1138** Resolve all names in all expressions of a SELECT and in all
1139** decendents of the SELECT, including compounds off of p->pPrior,
1140** subqueries in expressions, and subqueries used as FROM clause
1141** terms.
1142**
1143** See sqlite3ResolveExprNames() for a description of the kinds of
1144** transformations that occur.
1145**
1146** All SELECT statements should have been expanded using
1147** sqlite3SelectExpand() prior to invoking this routine.
1148*/
1149void sqlite3ResolveSelectNames(
1150 Parse *pParse, /* The parser context */
1151 Select *p, /* The SELECT statement being coded. */
1152 NameContext *pOuterNC /* Name context for parent SELECT statement */
1153){
1154 Walker w;
1155
drh0a846f92008-08-25 17:23:29 +00001156 assert( p!=0 );
1157 w.xExprCallback = resolveExprStep;
1158 w.xSelectCallback = resolveSelectStep;
1159 w.pParse = pParse;
1160 w.u.pNC = pOuterNC;
1161 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001162}