blob: b763a809fad5620886e0dcd24101f7829e36e54e [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.
drh7d10d5a2008-08-20 16:35:10 +000016*/
17#include "sqliteInt.h"
18#include <stdlib.h>
19#include <string.h>
20
21/*
drh8b213892008-08-29 02:14:02 +000022** Turn the pExpr expression into an alias for the iCol-th column of the
23** result set in pEList.
24**
25** If the result set column is a simple column reference, then this routine
26** makes an exact copy. But for any other kind of expression, this
27** routine make a copy of the result set column as the argument to the
28** TK_AS operator. The TK_AS operator causes the expression to be
29** evaluated just once and then reused for each alias.
30**
31** The reason for suppressing the TK_AS term when the expression is a simple
32** column reference is so that the column reference will be recognized as
33** usable by indices within the WHERE clause processing logic.
34**
35** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
36** that in a GROUP BY clause, the expression is evaluated twice. Hence:
37**
38** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
39**
40** Is equivalent to:
41**
42** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
43**
44** The result of random()%5 in the GROUP BY clause is probably different
45** from the result in the result-set. We might fix this someday. Or
46** then again, we might not...
47*/
48static void resolveAlias(
49 Parse *pParse, /* Parsing context */
50 ExprList *pEList, /* A result set */
51 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
52 Expr *pExpr, /* Transform this into an alias to the result set */
53 const char *zType /* "GROUP" or "ORDER" or "" */
54){
55 Expr *pOrig; /* The iCol-th column of the result set */
56 Expr *pDup; /* Copy of pOrig */
57 sqlite3 *db; /* The database connection */
58
59 assert( iCol>=0 && iCol<pEList->nExpr );
60 pOrig = pEList->a[iCol].pExpr;
61 assert( pOrig!=0 );
62 assert( pOrig->flags & EP_Resolved );
63 db = pParse->db;
drhb7916a72009-05-27 10:31:29 +000064 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
65 pDup = sqlite3ExprDup(db, pOrig, 0);
drh8b213892008-08-29 02:14:02 +000066 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
67 if( pDup==0 ) return;
68 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +000069 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +000070 }
71 pDup->iTable = pEList->a[iCol].iAlias;
drh0b0745a2009-05-28 12:49:53 +000072 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
73 pDup = sqlite3ExprDup(db, pOrig, 0);
drh2c220452009-05-28 14:34:49 +000074 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +000075 }else{
drh33e619f2009-05-28 01:00:55 +000076 char *zToken = pOrig->u.zToken;
drh73c0fdc2009-06-15 18:32:36 +000077 assert( zToken!=0 );
drh33e619f2009-05-28 01:00:55 +000078 pOrig->u.zToken = 0;
drhb7916a72009-05-27 10:31:29 +000079 pDup = sqlite3ExprDup(db, pOrig, 0);
drh33e619f2009-05-28 01:00:55 +000080 pOrig->u.zToken = zToken;
drhb7916a72009-05-27 10:31:29 +000081 if( pDup==0 ) return;
drh73c0fdc2009-06-15 18:32:36 +000082 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
83 pDup->flags2 |= EP2_MallocedToken;
84 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
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
drhf7828b52009-06-15 23:15:59 +0000120** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000121*/
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 */
dan2bd93512009-08-31 08:22:46 +0000138 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000139
drhb7916a72009-05-27 10:31:29 +0000140 assert( pNC ); /* the name context cannot be NULL. */
141 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh33e619f2009-05-28 01:00:55 +0000142 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000143
144 /* Initialize the node to no-match */
145 pExpr->iTable = -1;
146 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000147 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000148
149 /* Start at the inner-most context and move outward until a match is found */
150 while( pNC && cnt==0 ){
151 ExprList *pEList;
152 SrcList *pSrcList = pNC->pSrcList;
153
154 if( pSrcList ){
155 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
156 Table *pTab;
157 int iDb;
158 Column *pCol;
159
160 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000161 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000162 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
163 assert( pTab->nCol>0 );
164 if( zTab ){
165 if( pItem->zAlias ){
166 char *zTabName = pItem->zAlias;
167 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
168 }else{
169 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000170 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
171 continue;
172 }
drh7d10d5a2008-08-20 16:35:10 +0000173 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
174 continue;
175 }
176 }
177 }
178 if( 0==(cntTab++) ){
179 pExpr->iTable = pItem->iCursor;
180 pExpr->pTab = pTab;
181 pSchema = pTab->pSchema;
182 pMatch = pItem;
183 }
184 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
185 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
186 IdList *pUsing;
187 cnt++;
188 pExpr->iTable = pItem->iCursor;
189 pExpr->pTab = pTab;
190 pMatch = pItem;
191 pSchema = pTab->pSchema;
192 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000193 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000194 if( i<pSrcList->nSrc-1 ){
195 if( pItem[1].jointype & JT_NATURAL ){
196 /* If this match occurred in the left table of a natural join,
197 ** then skip the right table to avoid a duplicate match */
198 pItem++;
199 i++;
200 }else if( (pUsing = pItem[1].pUsing)!=0 ){
201 /* If this match occurs on a column that is in the USING clause
202 ** of a join, skip the search of the right table of the join
203 ** to avoid a duplicate match there. */
204 int k;
205 for(k=0; k<pUsing->nId; k++){
206 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
207 pItem++;
208 i++;
209 break;
210 }
211 }
212 }
213 }
214 break;
215 }
216 }
217 }
218 }
219
220#ifndef SQLITE_OMIT_TRIGGER
221 /* If we have not already resolved the name, then maybe
222 ** it is a new.* or old.* trigger argument reference
223 */
dan165921a2009-08-28 18:53:45 +0000224 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000225 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000226 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000227 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
228 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000229 pExpr->iTable = 1;
230 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000231 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000232 pExpr->iTable = 0;
233 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000234 }
235
236 if( pTab ){
237 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000238 pSchema = pTab->pSchema;
239 cntTab++;
dan2bd93512009-08-31 08:22:46 +0000240 if( sqlite3IsRowid(zCol) ){
241 iCol = -1;
242 }else{
243 for(iCol=0; iCol<pTab->nCol; iCol++){
244 Column *pCol = &pTab->aCol[iCol];
245 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
dan2bd93512009-08-31 08:22:46 +0000246 if( iCol==pTab->iPKey ){
247 iCol = -1;
248 }
249 break;
drh7d10d5a2008-08-20 16:35:10 +0000250 }
drh7d10d5a2008-08-20 16:35:10 +0000251 }
252 }
dan2bd93512009-08-31 08:22:46 +0000253 if( iCol<pTab->nCol ){
254 cnt++;
255 if( iCol<0 ){
256 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000257 }else if( pExpr->iTable==0 ){
258 testcase( iCol==31 );
259 testcase( iCol==32 );
260 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000261 }
shanecea72b22009-09-07 04:38:36 +0000262 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000263 pExpr->pTab = pTab;
264 isTrigger = 1;
265 }
drh7d10d5a2008-08-20 16:35:10 +0000266 }
267 }
268#endif /* !defined(SQLITE_OMIT_TRIGGER) */
269
270 /*
271 ** Perhaps the name is a reference to the ROWID
272 */
273 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
274 cnt = 1;
275 pExpr->iColumn = -1;
276 pExpr->affinity = SQLITE_AFF_INTEGER;
277 }
278
279 /*
280 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
281 ** might refer to an result-set alias. This happens, for example, when
282 ** we are resolving names in the WHERE clause of the following command:
283 **
284 ** SELECT a+b AS x FROM table WHERE x<10;
285 **
286 ** In cases like this, replace pExpr with a copy of the expression that
287 ** forms the result set entry ("a+b" in the example) and return immediately.
288 ** Note that the expression in the result set should have already been
289 ** resolved by the time the WHERE clause is resolved.
290 */
291 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
292 for(j=0; j<pEList->nExpr; j++){
293 char *zAs = pEList->a[j].zName;
294 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000295 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000296 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000297 assert( pExpr->x.pList==0 );
298 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000299 pOrig = pEList->a[j].pExpr;
300 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
301 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000302 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000303 }
drh8b213892008-08-29 02:14:02 +0000304 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000305 cnt = 1;
306 pMatch = 0;
307 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000308 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000309 }
310 }
311 }
312
313 /* Advance to the next name context. The loop will exit when either
314 ** we have a match (cnt>0) or when we run out of name contexts.
315 */
316 if( cnt==0 ){
317 pNC = pNC->pNext;
318 }
319 }
320
321 /*
322 ** If X and Y are NULL (in other words if only the column name Z is
323 ** supplied) and the value of Z is enclosed in double-quotes, then
324 ** Z is a string literal if it doesn't match any column names. In that
325 ** case, we need to return right away and not make any changes to
326 ** pExpr.
327 **
328 ** Because no reference was made to outer contexts, the pNC->nRef
329 ** fields are not changed in any context.
330 */
drh24fb6272009-05-01 21:13:36 +0000331 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000332 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000333 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000334 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000335 }
336
337 /*
338 ** cnt==0 means there was not match. cnt>1 means there were two or
339 ** more matches. Either way, we have an error.
340 */
341 if( cnt!=1 ){
342 const char *zErr;
343 zErr = cnt==0 ? "no such column" : "ambiguous column name";
344 if( zDb ){
345 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
346 }else if( zTab ){
347 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
348 }else{
349 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
350 }
351 pTopNC->nErr++;
352 }
353
354 /* If a column from a table in pSrcList is referenced, then record
355 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
356 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
357 ** column number is greater than the number of bits in the bitmask
358 ** then set the high-order bit of the bitmask.
359 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000360 if( pExpr->iColumn>=0 && pMatch!=0 ){
361 int n = pExpr->iColumn;
362 testcase( n==BMS-1 );
363 if( n>=BMS ){
364 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000365 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000366 assert( pMatch->iCursor==pExpr->iTable );
367 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000368 }
369
drh7d10d5a2008-08-20 16:35:10 +0000370 /* Clean up and return
371 */
drh7d10d5a2008-08-20 16:35:10 +0000372 sqlite3ExprDelete(db, pExpr->pLeft);
373 pExpr->pLeft = 0;
374 sqlite3ExprDelete(db, pExpr->pRight);
375 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000376 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000377lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000378 if( cnt==1 ){
379 assert( pNC!=0 );
380 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
381 /* Increment the nRef value on all name contexts from TopNC up to
382 ** the point where the name matched. */
383 for(;;){
384 assert( pTopNC!=0 );
385 pTopNC->nRef++;
386 if( pTopNC==pNC ) break;
387 pTopNC = pTopNC->pNext;
388 }
drhf7828b52009-06-15 23:15:59 +0000389 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000390 } else {
drhf7828b52009-06-15 23:15:59 +0000391 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000392 }
393}
394
395/*
danf7b0b0a2009-10-19 15:52:32 +0000396** Allocate and return a pointer to an expression to load the column iCol
397** from datasource iSrc datasource in SrcList pSrc.
398*/
399Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
400 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
401 if( p ){
402 struct SrcList_item *pItem = &pSrc->a[iSrc];
403 p->pTab = pItem->pTab;
404 p->iTable = pItem->iCursor;
405 if( p->pTab->iPKey==iCol ){
406 p->iColumn = -1;
407 }else{
drh8677d302009-11-04 13:17:14 +0000408 p->iColumn = (ynVar)iCol;
danf7b0b0a2009-10-19 15:52:32 +0000409 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
410 }
411 ExprSetProperty(p, EP_Resolved);
412 }
413 return p;
414}
415
416/*
drh7d10d5a2008-08-20 16:35:10 +0000417** This routine is callback for sqlite3WalkExpr().
418**
419** Resolve symbolic names into TK_COLUMN operators for the current
420** node in the expression tree. Return 0 to continue the search down
421** the tree or 2 to abort the tree walk.
422**
423** This routine also does error checking and name resolution for
424** function names. The operator for aggregate functions is changed
425** to TK_AGG_FUNCTION.
426*/
427static int resolveExprStep(Walker *pWalker, Expr *pExpr){
428 NameContext *pNC;
429 Parse *pParse;
430
drh7d10d5a2008-08-20 16:35:10 +0000431 pNC = pWalker->u.pNC;
432 assert( pNC!=0 );
433 pParse = pNC->pParse;
434 assert( pParse==pWalker->pParse );
435
436 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
437 ExprSetProperty(pExpr, EP_Resolved);
438#ifndef NDEBUG
439 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
440 SrcList *pSrcList = pNC->pSrcList;
441 int i;
442 for(i=0; i<pNC->pSrcList->nSrc; i++){
443 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
444 }
445 }
446#endif
447 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000448
shane273f6192008-10-10 04:34:16 +0000449#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000450 /* The special operator TK_ROW means use the rowid for the first
451 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
452 ** clause processing on UPDATE and DELETE statements.
453 */
454 case TK_ROW: {
455 SrcList *pSrcList = pNC->pSrcList;
456 struct SrcList_item *pItem;
457 assert( pSrcList && pSrcList->nSrc==1 );
458 pItem = pSrcList->a;
459 pExpr->op = TK_COLUMN;
460 pExpr->pTab = pItem->pTab;
461 pExpr->iTable = pItem->iCursor;
462 pExpr->iColumn = -1;
463 pExpr->affinity = SQLITE_AFF_INTEGER;
464 break;
465 }
shane273f6192008-10-10 04:34:16 +0000466#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000467
drh7d10d5a2008-08-20 16:35:10 +0000468 /* A lone identifier is the name of a column.
469 */
470 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000471 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000472 }
473
474 /* A table name and column name: ID.ID
475 ** Or a database, table and column: ID.ID.ID
476 */
477 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000478 const char *zColumn;
479 const char *zTable;
480 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000481 Expr *pRight;
482
483 /* if( pSrcList==0 ) break; */
484 pRight = pExpr->pRight;
485 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000486 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000487 zTable = pExpr->pLeft->u.zToken;
488 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000489 }else{
490 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000491 zDb = pExpr->pLeft->u.zToken;
492 zTable = pRight->pLeft->u.zToken;
493 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000494 }
drhf7828b52009-06-15 23:15:59 +0000495 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000496 }
497
498 /* Resolve function names
499 */
500 case TK_CONST_FUNC:
501 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000502 ExprList *pList = pExpr->x.pList; /* The argument list */
503 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000504 int no_such_func = 0; /* True if no such function exists */
505 int wrong_num_args = 0; /* True if wrong number of arguments */
506 int is_agg = 0; /* True if is an aggregate function */
507 int auth; /* Authorization to use the function */
508 int nId; /* Number of characters in function name */
509 const char *zId; /* The function name. */
510 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000511 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000512
drh73c0fdc2009-06-15 18:32:36 +0000513 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000514 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000515 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000516 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000517 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
518 if( pDef==0 ){
519 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
520 if( pDef==0 ){
521 no_such_func = 1;
522 }else{
523 wrong_num_args = 1;
524 }
525 }else{
526 is_agg = pDef->xFunc==0;
527 }
528#ifndef SQLITE_OMIT_AUTHORIZATION
529 if( pDef ){
530 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
531 if( auth!=SQLITE_OK ){
532 if( auth==SQLITE_DENY ){
533 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
534 pDef->zName);
535 pNC->nErr++;
536 }
537 pExpr->op = TK_NULL;
538 return WRC_Prune;
539 }
540 }
541#endif
542 if( is_agg && !pNC->allowAgg ){
543 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
544 pNC->nErr++;
545 is_agg = 0;
546 }else if( no_such_func ){
547 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
548 pNC->nErr++;
549 }else if( wrong_num_args ){
550 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
551 nId, zId);
552 pNC->nErr++;
553 }
554 if( is_agg ){
555 pExpr->op = TK_AGG_FUNCTION;
556 pNC->hasAgg = 1;
557 }
558 if( is_agg ) pNC->allowAgg = 0;
559 sqlite3WalkExprList(pWalker, pList);
560 if( is_agg ) pNC->allowAgg = 1;
561 /* FIX ME: Compute pExpr->affinity based on the expected return
562 ** type of the function
563 */
564 return WRC_Prune;
565 }
566#ifndef SQLITE_OMIT_SUBQUERY
567 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000568 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000569#endif
570 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000571 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000572 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000573 int nRef = pNC->nRef;
574#ifndef SQLITE_OMIT_CHECK
575 if( pNC->isCheck ){
576 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
577 }
578#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000579 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000580 assert( pNC->nRef>=nRef );
581 if( nRef!=pNC->nRef ){
582 ExprSetProperty(pExpr, EP_VarSelect);
583 }
584 }
585 break;
586 }
587#ifndef SQLITE_OMIT_CHECK
588 case TK_VARIABLE: {
589 if( pNC->isCheck ){
590 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
591 }
592 break;
593 }
594#endif
595 }
596 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
597}
598
599/*
600** pEList is a list of expressions which are really the result set of the
601** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
602** This routine checks to see if pE is a simple identifier which corresponds
603** to the AS-name of one of the terms of the expression list. If it is,
604** this routine return an integer between 1 and N where N is the number of
605** elements in pEList, corresponding to the matching entry. If there is
606** no match, or if pE is not a simple identifier, then this routine
607** return 0.
608**
609** pEList has been resolved. pE has not.
610*/
611static int resolveAsName(
612 Parse *pParse, /* Parsing context for error messages */
613 ExprList *pEList, /* List of expressions to scan */
614 Expr *pE /* Expression we are trying to match */
615){
616 int i; /* Loop counter */
617
shanecf697392009-06-01 16:53:09 +0000618 UNUSED_PARAMETER(pParse);
619
drh73c0fdc2009-06-15 18:32:36 +0000620 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000621 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000622 for(i=0; i<pEList->nExpr; i++){
623 char *zAs = pEList->a[i].zName;
624 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000625 return i+1;
626 }
627 }
drh7d10d5a2008-08-20 16:35:10 +0000628 }
629 return 0;
630}
631
632/*
633** pE is a pointer to an expression which is a single term in the
634** ORDER BY of a compound SELECT. The expression has not been
635** name resolved.
636**
637** At the point this routine is called, we already know that the
638** ORDER BY term is not an integer index into the result set. That
639** case is handled by the calling routine.
640**
641** Attempt to match pE against result set columns in the left-most
642** SELECT statement. Return the index i of the matching column,
643** as an indication to the caller that it should sort by the i-th column.
644** The left-most column is 1. In other words, the value returned is the
645** same integer value that would be used in the SQL statement to indicate
646** the column.
647**
648** If there is no match, return 0. Return -1 if an error occurs.
649*/
650static int resolveOrderByTermToExprList(
651 Parse *pParse, /* Parsing context for error messages */
652 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
653 Expr *pE /* The specific ORDER BY term */
654){
655 int i; /* Loop counter */
656 ExprList *pEList; /* The columns of the result set */
657 NameContext nc; /* Name context for resolving pE */
658
659 assert( sqlite3ExprIsInteger(pE, &i)==0 );
660 pEList = pSelect->pEList;
661
662 /* Resolve all names in the ORDER BY term expression
663 */
664 memset(&nc, 0, sizeof(nc));
665 nc.pParse = pParse;
666 nc.pSrcList = pSelect->pSrc;
667 nc.pEList = pEList;
668 nc.allowAgg = 1;
669 nc.nErr = 0;
670 if( sqlite3ResolveExprNames(&nc, pE) ){
671 sqlite3ErrorClear(pParse);
672 return 0;
673 }
674
675 /* Try to match the ORDER BY expression against an expression
676 ** in the result set. Return an 1-based index of the matching
677 ** result-set entry.
678 */
679 for(i=0; i<pEList->nExpr; i++){
680 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
681 return i+1;
682 }
683 }
684
685 /* If no match, return 0. */
686 return 0;
687}
688
689/*
690** Generate an ORDER BY or GROUP BY term out-of-range error.
691*/
692static void resolveOutOfRangeError(
693 Parse *pParse, /* The error context into which to write the error */
694 const char *zType, /* "ORDER" or "GROUP" */
695 int i, /* The index (1-based) of the term out of range */
696 int mx /* Largest permissible value of i */
697){
698 sqlite3ErrorMsg(pParse,
699 "%r %s BY term out of range - should be "
700 "between 1 and %d", i, zType, mx);
701}
702
703/*
704** Analyze the ORDER BY clause in a compound SELECT statement. Modify
705** each term of the ORDER BY clause is a constant integer between 1
706** and N where N is the number of columns in the compound SELECT.
707**
708** ORDER BY terms that are already an integer between 1 and N are
709** unmodified. ORDER BY terms that are integers outside the range of
710** 1 through N generate an error. ORDER BY terms that are expressions
711** are matched against result set expressions of compound SELECT
712** beginning with the left-most SELECT and working toward the right.
713** At the first match, the ORDER BY expression is transformed into
714** the integer column number.
715**
716** Return the number of errors seen.
717*/
718static int resolveCompoundOrderBy(
719 Parse *pParse, /* Parsing context. Leave error messages here */
720 Select *pSelect /* The SELECT statement containing the ORDER BY */
721){
722 int i;
723 ExprList *pOrderBy;
724 ExprList *pEList;
725 sqlite3 *db;
726 int moreToDo = 1;
727
728 pOrderBy = pSelect->pOrderBy;
729 if( pOrderBy==0 ) return 0;
730 db = pParse->db;
731#if SQLITE_MAX_COLUMN
732 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
733 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
734 return 1;
735 }
736#endif
737 for(i=0; i<pOrderBy->nExpr; i++){
738 pOrderBy->a[i].done = 0;
739 }
740 pSelect->pNext = 0;
741 while( pSelect->pPrior ){
742 pSelect->pPrior->pNext = pSelect;
743 pSelect = pSelect->pPrior;
744 }
745 while( pSelect && moreToDo ){
746 struct ExprList_item *pItem;
747 moreToDo = 0;
748 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000749 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000750 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
751 int iCol = -1;
752 Expr *pE, *pDup;
753 if( pItem->done ) continue;
754 pE = pItem->pExpr;
755 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000756 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000757 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
758 return 1;
759 }
760 }else{
761 iCol = resolveAsName(pParse, pEList, pE);
762 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000763 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000764 if( !db->mallocFailed ){
765 assert(pDup);
766 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
767 }
768 sqlite3ExprDelete(db, pDup);
769 }
drh7d10d5a2008-08-20 16:35:10 +0000770 }
771 if( iCol>0 ){
772 CollSeq *pColl = pE->pColl;
773 int flags = pE->flags & EP_ExpCollate;
774 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000775 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000776 if( pE==0 ) return 1;
777 pE->pColl = pColl;
778 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000779 pE->u.iValue = iCol;
drhea678832008-12-10 19:26:22 +0000780 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000781 pItem->done = 1;
782 }else{
783 moreToDo = 1;
784 }
785 }
786 pSelect = pSelect->pNext;
787 }
788 for(i=0; i<pOrderBy->nExpr; i++){
789 if( pOrderBy->a[i].done==0 ){
790 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
791 "column in the result set", i+1);
792 return 1;
793 }
794 }
795 return 0;
796}
797
798/*
799** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
800** the SELECT statement pSelect. If any term is reference to a
801** result set expression (as determined by the ExprList.a.iCol field)
802** then convert that term into a copy of the corresponding result set
803** column.
804**
805** If any errors are detected, add an error message to pParse and
806** return non-zero. Return zero if no errors are seen.
807*/
808int sqlite3ResolveOrderGroupBy(
809 Parse *pParse, /* Parsing context. Leave error messages here */
810 Select *pSelect, /* The SELECT statement containing the clause */
811 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
812 const char *zType /* "ORDER" or "GROUP" */
813){
814 int i;
815 sqlite3 *db = pParse->db;
816 ExprList *pEList;
817 struct ExprList_item *pItem;
818
819 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
820#if SQLITE_MAX_COLUMN
821 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
822 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
823 return 1;
824 }
825#endif
826 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000827 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000828 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
829 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000830 if( pItem->iCol>pEList->nExpr ){
831 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
832 return 1;
833 }
drh8b213892008-08-29 02:14:02 +0000834 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000835 }
836 }
837 return 0;
838}
839
840/*
841** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
842** The Name context of the SELECT statement is pNC. zType is either
843** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
844**
845** This routine resolves each term of the clause into an expression.
846** If the order-by term is an integer I between 1 and N (where N is the
847** number of columns in the result set of the SELECT) then the expression
848** in the resolution is a copy of the I-th result-set expression. If
849** the order-by term is an identify that corresponds to the AS-name of
850** a result-set expression, then the term resolves to a copy of the
851** result-set expression. Otherwise, the expression is resolved in
852** the usual way - using sqlite3ResolveExprNames().
853**
854** This routine returns the number of errors. If errors occur, then
855** an appropriate error message might be left in pParse. (OOM errors
856** excepted.)
857*/
858static int resolveOrderGroupBy(
859 NameContext *pNC, /* The name context of the SELECT statement */
860 Select *pSelect, /* The SELECT statement holding pOrderBy */
861 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
862 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
863){
864 int i; /* Loop counter */
865 int iCol; /* Column number */
866 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
867 Parse *pParse; /* Parsing context */
868 int nResult; /* Number of terms in the result set */
869
870 if( pOrderBy==0 ) return 0;
871 nResult = pSelect->pEList->nExpr;
872 pParse = pNC->pParse;
873 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
874 Expr *pE = pItem->pExpr;
875 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000876 if( iCol>0 ){
877 /* If an AS-name match is found, mark this ORDER BY column as being
878 ** a copy of the iCol-th result-set column. The subsequent call to
879 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
880 ** copy of the iCol-th result-set expression. */
drhea678832008-12-10 19:26:22 +0000881 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000882 continue;
883 }
884 if( sqlite3ExprIsInteger(pE, &iCol) ){
885 /* The ORDER BY term is an integer constant. Again, set the column
886 ** number so that sqlite3ResolveOrderGroupBy() will convert the
887 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000888 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000889 resolveOutOfRangeError(pParse, zType, i+1, nResult);
890 return 1;
891 }
drhea678832008-12-10 19:26:22 +0000892 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000893 continue;
894 }
895
896 /* Otherwise, treat the ORDER BY term as an ordinary expression */
897 pItem->iCol = 0;
898 if( sqlite3ResolveExprNames(pNC, pE) ){
899 return 1;
900 }
901 }
902 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
903}
904
905/*
906** Resolve names in the SELECT statement p and all of its descendents.
907*/
908static int resolveSelectStep(Walker *pWalker, Select *p){
909 NameContext *pOuterNC; /* Context that contains this SELECT */
910 NameContext sNC; /* Name context of this SELECT */
911 int isCompound; /* True if p is a compound select */
912 int nCompound; /* Number of compound terms processed so far */
913 Parse *pParse; /* Parsing context */
914 ExprList *pEList; /* Result set expression list */
915 int i; /* Loop counter */
916 ExprList *pGroupBy; /* The GROUP BY clause */
917 Select *pLeftmost; /* Left-most of SELECT of a compound */
918 sqlite3 *db; /* Database connection */
919
920
drh0a846f92008-08-25 17:23:29 +0000921 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000922 if( p->selFlags & SF_Resolved ){
923 return WRC_Prune;
924 }
925 pOuterNC = pWalker->u.pNC;
926 pParse = pWalker->pParse;
927 db = pParse->db;
928
929 /* Normally sqlite3SelectExpand() will be called first and will have
930 ** already expanded this SELECT. However, if this is a subquery within
931 ** an expression, sqlite3ResolveExprNames() will be called without a
932 ** prior call to sqlite3SelectExpand(). When that happens, let
933 ** sqlite3SelectPrep() do all of the processing for this SELECT.
934 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
935 ** this routine in the correct order.
936 */
937 if( (p->selFlags & SF_Expanded)==0 ){
938 sqlite3SelectPrep(pParse, p, pOuterNC);
939 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
940 }
941
942 isCompound = p->pPrior!=0;
943 nCompound = 0;
944 pLeftmost = p;
945 while( p ){
946 assert( (p->selFlags & SF_Expanded)!=0 );
947 assert( (p->selFlags & SF_Resolved)==0 );
948 p->selFlags |= SF_Resolved;
949
950 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
951 ** are not allowed to refer to any names, so pass an empty NameContext.
952 */
953 memset(&sNC, 0, sizeof(sNC));
954 sNC.pParse = pParse;
955 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
956 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
957 return WRC_Abort;
958 }
959
960 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
961 ** resolve the result-set expression list.
962 */
963 sNC.allowAgg = 1;
964 sNC.pSrcList = p->pSrc;
965 sNC.pNext = pOuterNC;
966
967 /* Resolve names in the result set. */
968 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000969 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000970 for(i=0; i<pEList->nExpr; i++){
971 Expr *pX = pEList->a[i].pExpr;
972 if( sqlite3ResolveExprNames(&sNC, pX) ){
973 return WRC_Abort;
974 }
975 }
976
977 /* Recursively resolve names in all subqueries
978 */
979 for(i=0; i<p->pSrc->nSrc; i++){
980 struct SrcList_item *pItem = &p->pSrc->a[i];
981 if( pItem->pSelect ){
982 const char *zSavedContext = pParse->zAuthContext;
983 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +0000984 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +0000985 pParse->zAuthContext = zSavedContext;
986 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
987 }
988 }
989
990 /* If there are no aggregate functions in the result-set, and no GROUP BY
991 ** expression, do not allow aggregates in any of the other expressions.
992 */
993 assert( (p->selFlags & SF_Aggregate)==0 );
994 pGroupBy = p->pGroupBy;
995 if( pGroupBy || sNC.hasAgg ){
996 p->selFlags |= SF_Aggregate;
997 }else{
998 sNC.allowAgg = 0;
999 }
1000
1001 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1002 */
1003 if( p->pHaving && !pGroupBy ){
1004 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1005 return WRC_Abort;
1006 }
1007
1008 /* Add the expression list to the name-context before parsing the
1009 ** other expressions in the SELECT statement. This is so that
1010 ** expressions in the WHERE clause (etc.) can refer to expressions by
1011 ** aliases in the result set.
1012 **
1013 ** Minor point: If this is the case, then the expression will be
1014 ** re-evaluated for each reference to it.
1015 */
1016 sNC.pEList = p->pEList;
1017 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1018 sqlite3ResolveExprNames(&sNC, p->pHaving)
1019 ){
1020 return WRC_Abort;
1021 }
1022
1023 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1024 ** outer queries
1025 */
1026 sNC.pNext = 0;
1027 sNC.allowAgg = 1;
1028
1029 /* Process the ORDER BY clause for singleton SELECT statements.
1030 ** The ORDER BY clause for compounds SELECT statements is handled
1031 ** below, after all of the result-sets for all of the elements of
1032 ** the compound have been resolved.
1033 */
1034 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1035 return WRC_Abort;
1036 }
1037 if( db->mallocFailed ){
1038 return WRC_Abort;
1039 }
1040
1041 /* Resolve the GROUP BY clause. At the same time, make sure
1042 ** the GROUP BY clause does not contain aggregate functions.
1043 */
1044 if( pGroupBy ){
1045 struct ExprList_item *pItem;
1046
1047 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1048 return WRC_Abort;
1049 }
1050 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1051 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1052 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1053 "the GROUP BY clause");
1054 return WRC_Abort;
1055 }
1056 }
1057 }
1058
1059 /* Advance to the next term of the compound
1060 */
1061 p = p->pPrior;
1062 nCompound++;
1063 }
1064
1065 /* Resolve the ORDER BY on a compound SELECT after all terms of
1066 ** the compound have been resolved.
1067 */
1068 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1069 return WRC_Abort;
1070 }
1071
1072 return WRC_Prune;
1073}
1074
1075/*
1076** This routine walks an expression tree and resolves references to
1077** table columns and result-set columns. At the same time, do error
1078** checking on function usage and set a flag if any aggregate functions
1079** are seen.
1080**
1081** To resolve table columns references we look for nodes (or subtrees) of the
1082** form X.Y.Z or Y.Z or just Z where
1083**
1084** X: The name of a database. Ex: "main" or "temp" or
1085** the symbolic name assigned to an ATTACH-ed database.
1086**
1087** Y: The name of a table in a FROM clause. Or in a trigger
1088** one of the special names "old" or "new".
1089**
1090** Z: The name of a column in table Y.
1091**
1092** The node at the root of the subtree is modified as follows:
1093**
1094** Expr.op Changed to TK_COLUMN
1095** Expr.pTab Points to the Table object for X.Y
1096** Expr.iColumn The column index in X.Y. -1 for the rowid.
1097** Expr.iTable The VDBE cursor number for X.Y
1098**
1099**
1100** To resolve result-set references, look for expression nodes of the
1101** form Z (with no X and Y prefix) where the Z matches the right-hand
1102** size of an AS clause in the result-set of a SELECT. The Z expression
1103** is replaced by a copy of the left-hand side of the result-set expression.
1104** Table-name and function resolution occurs on the substituted expression
1105** tree. For example, in:
1106**
1107** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1108**
1109** The "x" term of the order by is replaced by "a+b" to render:
1110**
1111** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1112**
1113** Function calls are checked to make sure that the function is
1114** defined and that the correct number of arguments are specified.
1115** If the function is an aggregate function, then the pNC->hasAgg is
1116** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1117** If an expression contains aggregate functions then the EP_Agg
1118** property on the expression is set.
1119**
1120** An error message is left in pParse if anything is amiss. The number
1121** if errors is returned.
1122*/
1123int sqlite3ResolveExprNames(
1124 NameContext *pNC, /* Namespace to resolve expressions in. */
1125 Expr *pExpr /* The expression to be analyzed. */
1126){
1127 int savedHasAgg;
1128 Walker w;
1129
1130 if( pExpr==0 ) return 0;
1131#if SQLITE_MAX_EXPR_DEPTH>0
1132 {
1133 Parse *pParse = pNC->pParse;
1134 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1135 return 1;
1136 }
1137 pParse->nHeight += pExpr->nHeight;
1138 }
1139#endif
1140 savedHasAgg = pNC->hasAgg;
1141 pNC->hasAgg = 0;
1142 w.xExprCallback = resolveExprStep;
1143 w.xSelectCallback = resolveSelectStep;
1144 w.pParse = pNC->pParse;
1145 w.u.pNC = pNC;
1146 sqlite3WalkExpr(&w, pExpr);
1147#if SQLITE_MAX_EXPR_DEPTH>0
1148 pNC->pParse->nHeight -= pExpr->nHeight;
1149#endif
drhfd773cf2009-05-29 14:39:07 +00001150 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001151 ExprSetProperty(pExpr, EP_Error);
1152 }
1153 if( pNC->hasAgg ){
1154 ExprSetProperty(pExpr, EP_Agg);
1155 }else if( savedHasAgg ){
1156 pNC->hasAgg = 1;
1157 }
1158 return ExprHasProperty(pExpr, EP_Error);
1159}
drh7d10d5a2008-08-20 16:35:10 +00001160
1161
1162/*
1163** Resolve all names in all expressions of a SELECT and in all
1164** decendents of the SELECT, including compounds off of p->pPrior,
1165** subqueries in expressions, and subqueries used as FROM clause
1166** terms.
1167**
1168** See sqlite3ResolveExprNames() for a description of the kinds of
1169** transformations that occur.
1170**
1171** All SELECT statements should have been expanded using
1172** sqlite3SelectExpand() prior to invoking this routine.
1173*/
1174void sqlite3ResolveSelectNames(
1175 Parse *pParse, /* The parser context */
1176 Select *p, /* The SELECT statement being coded. */
1177 NameContext *pOuterNC /* Name context for parent SELECT statement */
1178){
1179 Walker w;
1180
drh0a846f92008-08-25 17:23:29 +00001181 assert( p!=0 );
1182 w.xExprCallback = resolveExprStep;
1183 w.xSelectCallback = resolveSelectStep;
1184 w.pParse = pParse;
1185 w.u.pNC = pOuterNC;
1186 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001187}