blob: 09f547c942e746ec1892053f94b2020b5113565a [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 ){
dan65a7cd12009-09-01 12:16:01 +0000227 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000228 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000229 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
230 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000231 pExpr->iTable = 1;
232 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000233 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000234 pExpr->iTable = 0;
235 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000236 }
237
238 if( pTab ){
239 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000240 pSchema = pTab->pSchema;
241 cntTab++;
dan2bd93512009-08-31 08:22:46 +0000242 if( sqlite3IsRowid(zCol) ){
243 iCol = -1;
244 }else{
245 for(iCol=0; iCol<pTab->nCol; iCol++){
246 Column *pCol = &pTab->aCol[iCol];
247 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
dan2bd93512009-08-31 08:22:46 +0000248 if( iCol==pTab->iPKey ){
249 iCol = -1;
250 }
251 break;
drh7d10d5a2008-08-20 16:35:10 +0000252 }
drh7d10d5a2008-08-20 16:35:10 +0000253 }
254 }
dan2bd93512009-08-31 08:22:46 +0000255 if( iCol<pTab->nCol ){
256 cnt++;
257 if( iCol<0 ){
258 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000259 }else if( pExpr->iTable==0 ){
260 testcase( iCol==31 );
261 testcase( iCol==32 );
262 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000263 }
shanecea72b22009-09-07 04:38:36 +0000264 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000265 pExpr->pTab = pTab;
266 isTrigger = 1;
267 }
drh7d10d5a2008-08-20 16:35:10 +0000268 }
269 }
270#endif /* !defined(SQLITE_OMIT_TRIGGER) */
271
272 /*
273 ** Perhaps the name is a reference to the ROWID
274 */
275 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
276 cnt = 1;
277 pExpr->iColumn = -1;
278 pExpr->affinity = SQLITE_AFF_INTEGER;
279 }
280
281 /*
282 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
283 ** might refer to an result-set alias. This happens, for example, when
284 ** we are resolving names in the WHERE clause of the following command:
285 **
286 ** SELECT a+b AS x FROM table WHERE x<10;
287 **
288 ** In cases like this, replace pExpr with a copy of the expression that
289 ** forms the result set entry ("a+b" in the example) and return immediately.
290 ** Note that the expression in the result set should have already been
291 ** resolved by the time the WHERE clause is resolved.
292 */
293 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
294 for(j=0; j<pEList->nExpr; j++){
295 char *zAs = pEList->a[j].zName;
296 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000297 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000298 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000299 assert( pExpr->x.pList==0 );
300 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000301 pOrig = pEList->a[j].pExpr;
302 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
303 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000304 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000305 }
drh8b213892008-08-29 02:14:02 +0000306 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000307 cnt = 1;
308 pMatch = 0;
309 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000310 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000311 }
312 }
313 }
314
315 /* Advance to the next name context. The loop will exit when either
316 ** we have a match (cnt>0) or when we run out of name contexts.
317 */
318 if( cnt==0 ){
319 pNC = pNC->pNext;
320 }
321 }
322
323 /*
324 ** If X and Y are NULL (in other words if only the column name Z is
325 ** supplied) and the value of Z is enclosed in double-quotes, then
326 ** Z is a string literal if it doesn't match any column names. In that
327 ** case, we need to return right away and not make any changes to
328 ** pExpr.
329 **
330 ** Because no reference was made to outer contexts, the pNC->nRef
331 ** fields are not changed in any context.
332 */
drh24fb6272009-05-01 21:13:36 +0000333 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000334 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000335 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000336 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000337 }
338
339 /*
340 ** cnt==0 means there was not match. cnt>1 means there were two or
341 ** more matches. Either way, we have an error.
342 */
343 if( cnt!=1 ){
344 const char *zErr;
345 zErr = cnt==0 ? "no such column" : "ambiguous column name";
346 if( zDb ){
347 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
348 }else if( zTab ){
349 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
350 }else{
351 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
352 }
353 pTopNC->nErr++;
354 }
355
356 /* If a column from a table in pSrcList is referenced, then record
357 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
358 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
359 ** column number is greater than the number of bits in the bitmask
360 ** then set the high-order bit of the bitmask.
361 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000362 if( pExpr->iColumn>=0 && pMatch!=0 ){
363 int n = pExpr->iColumn;
364 testcase( n==BMS-1 );
365 if( n>=BMS ){
366 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000367 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000368 assert( pMatch->iCursor==pExpr->iTable );
369 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000370 }
371
drh7d10d5a2008-08-20 16:35:10 +0000372 /* Clean up and return
373 */
drh7d10d5a2008-08-20 16:35:10 +0000374 sqlite3ExprDelete(db, pExpr->pLeft);
375 pExpr->pLeft = 0;
376 sqlite3ExprDelete(db, pExpr->pRight);
377 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000378 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000379lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000380 if( cnt==1 ){
381 assert( pNC!=0 );
382 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
383 /* Increment the nRef value on all name contexts from TopNC up to
384 ** the point where the name matched. */
385 for(;;){
386 assert( pTopNC!=0 );
387 pTopNC->nRef++;
388 if( pTopNC==pNC ) break;
389 pTopNC = pTopNC->pNext;
390 }
drhf7828b52009-06-15 23:15:59 +0000391 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000392 } else {
drhf7828b52009-06-15 23:15:59 +0000393 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000394 }
395}
396
397/*
danf7b0b0a2009-10-19 15:52:32 +0000398** Allocate and return a pointer to an expression to load the column iCol
399** from datasource iSrc datasource in SrcList pSrc.
400*/
401Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
402 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
403 if( p ){
404 struct SrcList_item *pItem = &pSrc->a[iSrc];
405 p->pTab = pItem->pTab;
406 p->iTable = pItem->iCursor;
407 if( p->pTab->iPKey==iCol ){
408 p->iColumn = -1;
409 }else{
shanef639c402009-11-03 19:42:30 +0000410#if SQLITE_MAX_VARIABLE_NUMBER<=32767
411 p->iColumn = (i16)iCol;
412#else
danf7b0b0a2009-10-19 15:52:32 +0000413 p->iColumn = iCol;
shanef639c402009-11-03 19:42:30 +0000414#endif
danf7b0b0a2009-10-19 15:52:32 +0000415 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
416 }
417 ExprSetProperty(p, EP_Resolved);
418 }
419 return p;
420}
421
422/*
drh7d10d5a2008-08-20 16:35:10 +0000423** This routine is callback for sqlite3WalkExpr().
424**
425** Resolve symbolic names into TK_COLUMN operators for the current
426** node in the expression tree. Return 0 to continue the search down
427** the tree or 2 to abort the tree walk.
428**
429** This routine also does error checking and name resolution for
430** function names. The operator for aggregate functions is changed
431** to TK_AGG_FUNCTION.
432*/
433static int resolveExprStep(Walker *pWalker, Expr *pExpr){
434 NameContext *pNC;
435 Parse *pParse;
436
drh7d10d5a2008-08-20 16:35:10 +0000437 pNC = pWalker->u.pNC;
438 assert( pNC!=0 );
439 pParse = pNC->pParse;
440 assert( pParse==pWalker->pParse );
441
442 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
443 ExprSetProperty(pExpr, EP_Resolved);
444#ifndef NDEBUG
445 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
446 SrcList *pSrcList = pNC->pSrcList;
447 int i;
448 for(i=0; i<pNC->pSrcList->nSrc; i++){
449 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
450 }
451 }
452#endif
453 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000454
shane273f6192008-10-10 04:34:16 +0000455#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000456 /* The special operator TK_ROW means use the rowid for the first
457 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
458 ** clause processing on UPDATE and DELETE statements.
459 */
460 case TK_ROW: {
461 SrcList *pSrcList = pNC->pSrcList;
462 struct SrcList_item *pItem;
463 assert( pSrcList && pSrcList->nSrc==1 );
464 pItem = pSrcList->a;
465 pExpr->op = TK_COLUMN;
466 pExpr->pTab = pItem->pTab;
467 pExpr->iTable = pItem->iCursor;
468 pExpr->iColumn = -1;
469 pExpr->affinity = SQLITE_AFF_INTEGER;
470 break;
471 }
shane273f6192008-10-10 04:34:16 +0000472#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000473
drh7d10d5a2008-08-20 16:35:10 +0000474 /* A lone identifier is the name of a column.
475 */
476 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000477 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000478 }
479
480 /* A table name and column name: ID.ID
481 ** Or a database, table and column: ID.ID.ID
482 */
483 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000484 const char *zColumn;
485 const char *zTable;
486 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000487 Expr *pRight;
488
489 /* if( pSrcList==0 ) break; */
490 pRight = pExpr->pRight;
491 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000492 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000493 zTable = pExpr->pLeft->u.zToken;
494 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000495 }else{
496 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000497 zDb = pExpr->pLeft->u.zToken;
498 zTable = pRight->pLeft->u.zToken;
499 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000500 }
drhf7828b52009-06-15 23:15:59 +0000501 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000502 }
503
504 /* Resolve function names
505 */
506 case TK_CONST_FUNC:
507 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000508 ExprList *pList = pExpr->x.pList; /* The argument list */
509 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000510 int no_such_func = 0; /* True if no such function exists */
511 int wrong_num_args = 0; /* True if wrong number of arguments */
512 int is_agg = 0; /* True if is an aggregate function */
513 int auth; /* Authorization to use the function */
514 int nId; /* Number of characters in function name */
515 const char *zId; /* The function name. */
516 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000517 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000518
drh73c0fdc2009-06-15 18:32:36 +0000519 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000520 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000521 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000522 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000523 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
524 if( pDef==0 ){
525 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
526 if( pDef==0 ){
527 no_such_func = 1;
528 }else{
529 wrong_num_args = 1;
530 }
531 }else{
532 is_agg = pDef->xFunc==0;
533 }
534#ifndef SQLITE_OMIT_AUTHORIZATION
535 if( pDef ){
536 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
537 if( auth!=SQLITE_OK ){
538 if( auth==SQLITE_DENY ){
539 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
540 pDef->zName);
541 pNC->nErr++;
542 }
543 pExpr->op = TK_NULL;
544 return WRC_Prune;
545 }
546 }
547#endif
548 if( is_agg && !pNC->allowAgg ){
549 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
550 pNC->nErr++;
551 is_agg = 0;
552 }else if( no_such_func ){
553 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
554 pNC->nErr++;
555 }else if( wrong_num_args ){
556 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
557 nId, zId);
558 pNC->nErr++;
559 }
560 if( is_agg ){
561 pExpr->op = TK_AGG_FUNCTION;
562 pNC->hasAgg = 1;
563 }
564 if( is_agg ) pNC->allowAgg = 0;
565 sqlite3WalkExprList(pWalker, pList);
566 if( is_agg ) pNC->allowAgg = 1;
567 /* FIX ME: Compute pExpr->affinity based on the expected return
568 ** type of the function
569 */
570 return WRC_Prune;
571 }
572#ifndef SQLITE_OMIT_SUBQUERY
573 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000574 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000575#endif
576 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000577 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000578 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000579 int nRef = pNC->nRef;
580#ifndef SQLITE_OMIT_CHECK
581 if( pNC->isCheck ){
582 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
583 }
584#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000585 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000586 assert( pNC->nRef>=nRef );
587 if( nRef!=pNC->nRef ){
588 ExprSetProperty(pExpr, EP_VarSelect);
589 }
590 }
591 break;
592 }
593#ifndef SQLITE_OMIT_CHECK
594 case TK_VARIABLE: {
595 if( pNC->isCheck ){
596 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
597 }
598 break;
599 }
600#endif
601 }
602 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
603}
604
605/*
606** pEList is a list of expressions which are really the result set of the
607** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
608** This routine checks to see if pE is a simple identifier which corresponds
609** to the AS-name of one of the terms of the expression list. If it is,
610** this routine return an integer between 1 and N where N is the number of
611** elements in pEList, corresponding to the matching entry. If there is
612** no match, or if pE is not a simple identifier, then this routine
613** return 0.
614**
615** pEList has been resolved. pE has not.
616*/
617static int resolveAsName(
618 Parse *pParse, /* Parsing context for error messages */
619 ExprList *pEList, /* List of expressions to scan */
620 Expr *pE /* Expression we are trying to match */
621){
622 int i; /* Loop counter */
623
shanecf697392009-06-01 16:53:09 +0000624 UNUSED_PARAMETER(pParse);
625
drh73c0fdc2009-06-15 18:32:36 +0000626 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000627 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000628 for(i=0; i<pEList->nExpr; i++){
629 char *zAs = pEList->a[i].zName;
630 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000631 return i+1;
632 }
633 }
drh7d10d5a2008-08-20 16:35:10 +0000634 }
635 return 0;
636}
637
638/*
639** pE is a pointer to an expression which is a single term in the
640** ORDER BY of a compound SELECT. The expression has not been
641** name resolved.
642**
643** At the point this routine is called, we already know that the
644** ORDER BY term is not an integer index into the result set. That
645** case is handled by the calling routine.
646**
647** Attempt to match pE against result set columns in the left-most
648** SELECT statement. Return the index i of the matching column,
649** as an indication to the caller that it should sort by the i-th column.
650** The left-most column is 1. In other words, the value returned is the
651** same integer value that would be used in the SQL statement to indicate
652** the column.
653**
654** If there is no match, return 0. Return -1 if an error occurs.
655*/
656static int resolveOrderByTermToExprList(
657 Parse *pParse, /* Parsing context for error messages */
658 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
659 Expr *pE /* The specific ORDER BY term */
660){
661 int i; /* Loop counter */
662 ExprList *pEList; /* The columns of the result set */
663 NameContext nc; /* Name context for resolving pE */
664
665 assert( sqlite3ExprIsInteger(pE, &i)==0 );
666 pEList = pSelect->pEList;
667
668 /* Resolve all names in the ORDER BY term expression
669 */
670 memset(&nc, 0, sizeof(nc));
671 nc.pParse = pParse;
672 nc.pSrcList = pSelect->pSrc;
673 nc.pEList = pEList;
674 nc.allowAgg = 1;
675 nc.nErr = 0;
676 if( sqlite3ResolveExprNames(&nc, pE) ){
677 sqlite3ErrorClear(pParse);
678 return 0;
679 }
680
681 /* Try to match the ORDER BY expression against an expression
682 ** in the result set. Return an 1-based index of the matching
683 ** result-set entry.
684 */
685 for(i=0; i<pEList->nExpr; i++){
686 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
687 return i+1;
688 }
689 }
690
691 /* If no match, return 0. */
692 return 0;
693}
694
695/*
696** Generate an ORDER BY or GROUP BY term out-of-range error.
697*/
698static void resolveOutOfRangeError(
699 Parse *pParse, /* The error context into which to write the error */
700 const char *zType, /* "ORDER" or "GROUP" */
701 int i, /* The index (1-based) of the term out of range */
702 int mx /* Largest permissible value of i */
703){
704 sqlite3ErrorMsg(pParse,
705 "%r %s BY term out of range - should be "
706 "between 1 and %d", i, zType, mx);
707}
708
709/*
710** Analyze the ORDER BY clause in a compound SELECT statement. Modify
711** each term of the ORDER BY clause is a constant integer between 1
712** and N where N is the number of columns in the compound SELECT.
713**
714** ORDER BY terms that are already an integer between 1 and N are
715** unmodified. ORDER BY terms that are integers outside the range of
716** 1 through N generate an error. ORDER BY terms that are expressions
717** are matched against result set expressions of compound SELECT
718** beginning with the left-most SELECT and working toward the right.
719** At the first match, the ORDER BY expression is transformed into
720** the integer column number.
721**
722** Return the number of errors seen.
723*/
724static int resolveCompoundOrderBy(
725 Parse *pParse, /* Parsing context. Leave error messages here */
726 Select *pSelect /* The SELECT statement containing the ORDER BY */
727){
728 int i;
729 ExprList *pOrderBy;
730 ExprList *pEList;
731 sqlite3 *db;
732 int moreToDo = 1;
733
734 pOrderBy = pSelect->pOrderBy;
735 if( pOrderBy==0 ) return 0;
736 db = pParse->db;
737#if SQLITE_MAX_COLUMN
738 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
739 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
740 return 1;
741 }
742#endif
743 for(i=0; i<pOrderBy->nExpr; i++){
744 pOrderBy->a[i].done = 0;
745 }
746 pSelect->pNext = 0;
747 while( pSelect->pPrior ){
748 pSelect->pPrior->pNext = pSelect;
749 pSelect = pSelect->pPrior;
750 }
751 while( pSelect && moreToDo ){
752 struct ExprList_item *pItem;
753 moreToDo = 0;
754 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000755 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000756 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
757 int iCol = -1;
758 Expr *pE, *pDup;
759 if( pItem->done ) continue;
760 pE = pItem->pExpr;
761 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000762 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000763 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
764 return 1;
765 }
766 }else{
767 iCol = resolveAsName(pParse, pEList, pE);
768 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000769 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000770 if( !db->mallocFailed ){
771 assert(pDup);
772 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
773 }
774 sqlite3ExprDelete(db, pDup);
775 }
drh7d10d5a2008-08-20 16:35:10 +0000776 }
777 if( iCol>0 ){
778 CollSeq *pColl = pE->pColl;
779 int flags = pE->flags & EP_ExpCollate;
780 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000781 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000782 if( pE==0 ) return 1;
783 pE->pColl = pColl;
784 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000785 pE->u.iValue = iCol;
drhea678832008-12-10 19:26:22 +0000786 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000787 pItem->done = 1;
788 }else{
789 moreToDo = 1;
790 }
791 }
792 pSelect = pSelect->pNext;
793 }
794 for(i=0; i<pOrderBy->nExpr; i++){
795 if( pOrderBy->a[i].done==0 ){
796 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
797 "column in the result set", i+1);
798 return 1;
799 }
800 }
801 return 0;
802}
803
804/*
805** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
806** the SELECT statement pSelect. If any term is reference to a
807** result set expression (as determined by the ExprList.a.iCol field)
808** then convert that term into a copy of the corresponding result set
809** column.
810**
811** If any errors are detected, add an error message to pParse and
812** return non-zero. Return zero if no errors are seen.
813*/
814int sqlite3ResolveOrderGroupBy(
815 Parse *pParse, /* Parsing context. Leave error messages here */
816 Select *pSelect, /* The SELECT statement containing the clause */
817 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
818 const char *zType /* "ORDER" or "GROUP" */
819){
820 int i;
821 sqlite3 *db = pParse->db;
822 ExprList *pEList;
823 struct ExprList_item *pItem;
824
825 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
826#if SQLITE_MAX_COLUMN
827 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
828 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
829 return 1;
830 }
831#endif
832 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000833 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000834 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
835 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000836 if( pItem->iCol>pEList->nExpr ){
837 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
838 return 1;
839 }
drh8b213892008-08-29 02:14:02 +0000840 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000841 }
842 }
843 return 0;
844}
845
846/*
847** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
848** The Name context of the SELECT statement is pNC. zType is either
849** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
850**
851** This routine resolves each term of the clause into an expression.
852** If the order-by term is an integer I between 1 and N (where N is the
853** number of columns in the result set of the SELECT) then the expression
854** in the resolution is a copy of the I-th result-set expression. If
855** the order-by term is an identify that corresponds to the AS-name of
856** a result-set expression, then the term resolves to a copy of the
857** result-set expression. Otherwise, the expression is resolved in
858** the usual way - using sqlite3ResolveExprNames().
859**
860** This routine returns the number of errors. If errors occur, then
861** an appropriate error message might be left in pParse. (OOM errors
862** excepted.)
863*/
864static int resolveOrderGroupBy(
865 NameContext *pNC, /* The name context of the SELECT statement */
866 Select *pSelect, /* The SELECT statement holding pOrderBy */
867 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
868 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
869){
870 int i; /* Loop counter */
871 int iCol; /* Column number */
872 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
873 Parse *pParse; /* Parsing context */
874 int nResult; /* Number of terms in the result set */
875
876 if( pOrderBy==0 ) return 0;
877 nResult = pSelect->pEList->nExpr;
878 pParse = pNC->pParse;
879 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
880 Expr *pE = pItem->pExpr;
881 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000882 if( iCol>0 ){
883 /* If an AS-name match is found, mark this ORDER BY column as being
884 ** a copy of the iCol-th result-set column. The subsequent call to
885 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
886 ** copy of the iCol-th result-set expression. */
drhea678832008-12-10 19:26:22 +0000887 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000888 continue;
889 }
890 if( sqlite3ExprIsInteger(pE, &iCol) ){
891 /* The ORDER BY term is an integer constant. Again, set the column
892 ** number so that sqlite3ResolveOrderGroupBy() will convert the
893 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000894 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000895 resolveOutOfRangeError(pParse, zType, i+1, nResult);
896 return 1;
897 }
drhea678832008-12-10 19:26:22 +0000898 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000899 continue;
900 }
901
902 /* Otherwise, treat the ORDER BY term as an ordinary expression */
903 pItem->iCol = 0;
904 if( sqlite3ResolveExprNames(pNC, pE) ){
905 return 1;
906 }
907 }
908 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
909}
910
911/*
912** Resolve names in the SELECT statement p and all of its descendents.
913*/
914static int resolveSelectStep(Walker *pWalker, Select *p){
915 NameContext *pOuterNC; /* Context that contains this SELECT */
916 NameContext sNC; /* Name context of this SELECT */
917 int isCompound; /* True if p is a compound select */
918 int nCompound; /* Number of compound terms processed so far */
919 Parse *pParse; /* Parsing context */
920 ExprList *pEList; /* Result set expression list */
921 int i; /* Loop counter */
922 ExprList *pGroupBy; /* The GROUP BY clause */
923 Select *pLeftmost; /* Left-most of SELECT of a compound */
924 sqlite3 *db; /* Database connection */
925
926
drh0a846f92008-08-25 17:23:29 +0000927 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000928 if( p->selFlags & SF_Resolved ){
929 return WRC_Prune;
930 }
931 pOuterNC = pWalker->u.pNC;
932 pParse = pWalker->pParse;
933 db = pParse->db;
934
935 /* Normally sqlite3SelectExpand() will be called first and will have
936 ** already expanded this SELECT. However, if this is a subquery within
937 ** an expression, sqlite3ResolveExprNames() will be called without a
938 ** prior call to sqlite3SelectExpand(). When that happens, let
939 ** sqlite3SelectPrep() do all of the processing for this SELECT.
940 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
941 ** this routine in the correct order.
942 */
943 if( (p->selFlags & SF_Expanded)==0 ){
944 sqlite3SelectPrep(pParse, p, pOuterNC);
945 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
946 }
947
948 isCompound = p->pPrior!=0;
949 nCompound = 0;
950 pLeftmost = p;
951 while( p ){
952 assert( (p->selFlags & SF_Expanded)!=0 );
953 assert( (p->selFlags & SF_Resolved)==0 );
954 p->selFlags |= SF_Resolved;
955
956 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
957 ** are not allowed to refer to any names, so pass an empty NameContext.
958 */
959 memset(&sNC, 0, sizeof(sNC));
960 sNC.pParse = pParse;
961 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
962 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
963 return WRC_Abort;
964 }
965
966 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
967 ** resolve the result-set expression list.
968 */
969 sNC.allowAgg = 1;
970 sNC.pSrcList = p->pSrc;
971 sNC.pNext = pOuterNC;
972
973 /* Resolve names in the result set. */
974 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000975 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000976 for(i=0; i<pEList->nExpr; i++){
977 Expr *pX = pEList->a[i].pExpr;
978 if( sqlite3ResolveExprNames(&sNC, pX) ){
979 return WRC_Abort;
980 }
981 }
982
983 /* Recursively resolve names in all subqueries
984 */
985 for(i=0; i<p->pSrc->nSrc; i++){
986 struct SrcList_item *pItem = &p->pSrc->a[i];
987 if( pItem->pSelect ){
988 const char *zSavedContext = pParse->zAuthContext;
989 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +0000990 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +0000991 pParse->zAuthContext = zSavedContext;
992 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
993 }
994 }
995
996 /* If there are no aggregate functions in the result-set, and no GROUP BY
997 ** expression, do not allow aggregates in any of the other expressions.
998 */
999 assert( (p->selFlags & SF_Aggregate)==0 );
1000 pGroupBy = p->pGroupBy;
1001 if( pGroupBy || sNC.hasAgg ){
1002 p->selFlags |= SF_Aggregate;
1003 }else{
1004 sNC.allowAgg = 0;
1005 }
1006
1007 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1008 */
1009 if( p->pHaving && !pGroupBy ){
1010 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1011 return WRC_Abort;
1012 }
1013
1014 /* Add the expression list to the name-context before parsing the
1015 ** other expressions in the SELECT statement. This is so that
1016 ** expressions in the WHERE clause (etc.) can refer to expressions by
1017 ** aliases in the result set.
1018 **
1019 ** Minor point: If this is the case, then the expression will be
1020 ** re-evaluated for each reference to it.
1021 */
1022 sNC.pEList = p->pEList;
1023 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1024 sqlite3ResolveExprNames(&sNC, p->pHaving)
1025 ){
1026 return WRC_Abort;
1027 }
1028
1029 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1030 ** outer queries
1031 */
1032 sNC.pNext = 0;
1033 sNC.allowAgg = 1;
1034
1035 /* Process the ORDER BY clause for singleton SELECT statements.
1036 ** The ORDER BY clause for compounds SELECT statements is handled
1037 ** below, after all of the result-sets for all of the elements of
1038 ** the compound have been resolved.
1039 */
1040 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1041 return WRC_Abort;
1042 }
1043 if( db->mallocFailed ){
1044 return WRC_Abort;
1045 }
1046
1047 /* Resolve the GROUP BY clause. At the same time, make sure
1048 ** the GROUP BY clause does not contain aggregate functions.
1049 */
1050 if( pGroupBy ){
1051 struct ExprList_item *pItem;
1052
1053 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1054 return WRC_Abort;
1055 }
1056 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1057 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1058 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1059 "the GROUP BY clause");
1060 return WRC_Abort;
1061 }
1062 }
1063 }
1064
1065 /* Advance to the next term of the compound
1066 */
1067 p = p->pPrior;
1068 nCompound++;
1069 }
1070
1071 /* Resolve the ORDER BY on a compound SELECT after all terms of
1072 ** the compound have been resolved.
1073 */
1074 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1075 return WRC_Abort;
1076 }
1077
1078 return WRC_Prune;
1079}
1080
1081/*
1082** This routine walks an expression tree and resolves references to
1083** table columns and result-set columns. At the same time, do error
1084** checking on function usage and set a flag if any aggregate functions
1085** are seen.
1086**
1087** To resolve table columns references we look for nodes (or subtrees) of the
1088** form X.Y.Z or Y.Z or just Z where
1089**
1090** X: The name of a database. Ex: "main" or "temp" or
1091** the symbolic name assigned to an ATTACH-ed database.
1092**
1093** Y: The name of a table in a FROM clause. Or in a trigger
1094** one of the special names "old" or "new".
1095**
1096** Z: The name of a column in table Y.
1097**
1098** The node at the root of the subtree is modified as follows:
1099**
1100** Expr.op Changed to TK_COLUMN
1101** Expr.pTab Points to the Table object for X.Y
1102** Expr.iColumn The column index in X.Y. -1 for the rowid.
1103** Expr.iTable The VDBE cursor number for X.Y
1104**
1105**
1106** To resolve result-set references, look for expression nodes of the
1107** form Z (with no X and Y prefix) where the Z matches the right-hand
1108** size of an AS clause in the result-set of a SELECT. The Z expression
1109** is replaced by a copy of the left-hand side of the result-set expression.
1110** Table-name and function resolution occurs on the substituted expression
1111** tree. For example, in:
1112**
1113** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1114**
1115** The "x" term of the order by is replaced by "a+b" to render:
1116**
1117** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1118**
1119** Function calls are checked to make sure that the function is
1120** defined and that the correct number of arguments are specified.
1121** If the function is an aggregate function, then the pNC->hasAgg is
1122** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1123** If an expression contains aggregate functions then the EP_Agg
1124** property on the expression is set.
1125**
1126** An error message is left in pParse if anything is amiss. The number
1127** if errors is returned.
1128*/
1129int sqlite3ResolveExprNames(
1130 NameContext *pNC, /* Namespace to resolve expressions in. */
1131 Expr *pExpr /* The expression to be analyzed. */
1132){
1133 int savedHasAgg;
1134 Walker w;
1135
1136 if( pExpr==0 ) return 0;
1137#if SQLITE_MAX_EXPR_DEPTH>0
1138 {
1139 Parse *pParse = pNC->pParse;
1140 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1141 return 1;
1142 }
1143 pParse->nHeight += pExpr->nHeight;
1144 }
1145#endif
1146 savedHasAgg = pNC->hasAgg;
1147 pNC->hasAgg = 0;
1148 w.xExprCallback = resolveExprStep;
1149 w.xSelectCallback = resolveSelectStep;
1150 w.pParse = pNC->pParse;
1151 w.u.pNC = pNC;
1152 sqlite3WalkExpr(&w, pExpr);
1153#if SQLITE_MAX_EXPR_DEPTH>0
1154 pNC->pParse->nHeight -= pExpr->nHeight;
1155#endif
drhfd773cf2009-05-29 14:39:07 +00001156 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001157 ExprSetProperty(pExpr, EP_Error);
1158 }
1159 if( pNC->hasAgg ){
1160 ExprSetProperty(pExpr, EP_Agg);
1161 }else if( savedHasAgg ){
1162 pNC->hasAgg = 1;
1163 }
1164 return ExprHasProperty(pExpr, EP_Error);
1165}
drh7d10d5a2008-08-20 16:35:10 +00001166
1167
1168/*
1169** Resolve all names in all expressions of a SELECT and in all
1170** decendents of the SELECT, including compounds off of p->pPrior,
1171** subqueries in expressions, and subqueries used as FROM clause
1172** terms.
1173**
1174** See sqlite3ResolveExprNames() for a description of the kinds of
1175** transformations that occur.
1176**
1177** All SELECT statements should have been expanded using
1178** sqlite3SelectExpand() prior to invoking this routine.
1179*/
1180void sqlite3ResolveSelectNames(
1181 Parse *pParse, /* The parser context */
1182 Select *p, /* The SELECT statement being coded. */
1183 NameContext *pOuterNC /* Name context for parent SELECT statement */
1184){
1185 Walker w;
1186
drh0a846f92008-08-25 17:23:29 +00001187 assert( p!=0 );
1188 w.xExprCallback = resolveExprStep;
1189 w.xSelectCallback = resolveSelectStep;
1190 w.pParse = pParse;
1191 w.u.pNC = pOuterNC;
1192 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001193}