blob: 3a44aef6235b28fe57c2ec9da08fa9eb83712f64 [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 }
danf6963f92009-11-23 14:39:14 +000090
91 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
92 ** prevents ExprDelete() from deleting the Expr structure itself,
93 ** allowing it to be repopulated by the memcpy() on the following line.
94 */
95 ExprSetProperty(pExpr, EP_Static);
96 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +000097 memcpy(pExpr, pDup, sizeof(*pExpr));
98 sqlite3DbFree(db, pDup);
99}
100
101/*
drh7d10d5a2008-08-20 16:35:10 +0000102** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
103** that name in the set of source tables in pSrcList and make the pExpr
104** expression node refer back to that source column. The following changes
105** are made to pExpr:
106**
107** pExpr->iDb Set the index in db->aDb[] of the database X
108** (even if X is implied).
109** pExpr->iTable Set to the cursor number for the table obtained
110** from pSrcList.
111** pExpr->pTab Points to the Table structure of X.Y (even if
112** X and/or Y are implied.)
113** pExpr->iColumn Set to the column number within the table.
114** pExpr->op Set to TK_COLUMN.
115** pExpr->pLeft Any expression this points to is deleted
116** pExpr->pRight Any expression this points to is deleted.
117**
drhb7916a72009-05-27 10:31:29 +0000118** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000119** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000120** can be used. The zTable variable is the name of the table (the "Y"). This
121** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000122** means that the form of the name is Z and that columns from any table
123** can be used.
124**
125** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000126** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000127*/
128static int lookupName(
129 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000130 const char *zDb, /* Name of the database containing table, or NULL */
131 const char *zTab, /* Name of table containing column, or NULL */
132 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000133 NameContext *pNC, /* The name context used to resolve the name */
134 Expr *pExpr /* Make this EXPR node point to the selected column */
135){
drh7d10d5a2008-08-20 16:35:10 +0000136 int i, j; /* Loop counters */
137 int cnt = 0; /* Number of matching column names */
138 int cntTab = 0; /* Number of matching table names */
139 sqlite3 *db = pParse->db; /* The database connection */
140 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
141 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
142 NameContext *pTopNC = pNC; /* First namecontext in the list */
143 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000144 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000145
drhb7916a72009-05-27 10:31:29 +0000146 assert( pNC ); /* the name context cannot be NULL. */
147 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh33e619f2009-05-28 01:00:55 +0000148 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000149
150 /* Initialize the node to no-match */
151 pExpr->iTable = -1;
152 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000153 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000154
155 /* Start at the inner-most context and move outward until a match is found */
156 while( pNC && cnt==0 ){
157 ExprList *pEList;
158 SrcList *pSrcList = pNC->pSrcList;
159
160 if( pSrcList ){
161 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
162 Table *pTab;
163 int iDb;
164 Column *pCol;
165
166 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000167 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000168 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
169 assert( pTab->nCol>0 );
170 if( zTab ){
171 if( pItem->zAlias ){
172 char *zTabName = pItem->zAlias;
173 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
174 }else{
175 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000176 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
177 continue;
178 }
drh7d10d5a2008-08-20 16:35:10 +0000179 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
180 continue;
181 }
182 }
183 }
184 if( 0==(cntTab++) ){
185 pExpr->iTable = pItem->iCursor;
186 pExpr->pTab = pTab;
187 pSchema = pTab->pSchema;
188 pMatch = pItem;
189 }
190 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
191 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
192 IdList *pUsing;
193 cnt++;
194 pExpr->iTable = pItem->iCursor;
195 pExpr->pTab = pTab;
196 pMatch = pItem;
197 pSchema = pTab->pSchema;
198 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000199 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000200 if( i<pSrcList->nSrc-1 ){
201 if( pItem[1].jointype & JT_NATURAL ){
202 /* If this match occurred in the left table of a natural join,
203 ** then skip the right table to avoid a duplicate match */
204 pItem++;
205 i++;
206 }else if( (pUsing = pItem[1].pUsing)!=0 ){
207 /* If this match occurs on a column that is in the USING clause
208 ** of a join, skip the search of the right table of the join
209 ** to avoid a duplicate match there. */
210 int k;
211 for(k=0; k<pUsing->nId; k++){
212 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
213 pItem++;
214 i++;
215 break;
216 }
217 }
218 }
219 }
220 break;
221 }
222 }
223 }
224 }
225
226#ifndef SQLITE_OMIT_TRIGGER
227 /* If we have not already resolved the name, then maybe
228 ** it is a new.* or old.* trigger argument reference
229 */
dan165921a2009-08-28 18:53:45 +0000230 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000231 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000232 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000233 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
234 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000235 pExpr->iTable = 1;
236 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000237 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000238 pExpr->iTable = 0;
239 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000240 }
241
242 if( pTab ){
243 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000244 pSchema = pTab->pSchema;
245 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000246 for(iCol=0; iCol<pTab->nCol; iCol++){
247 Column *pCol = &pTab->aCol[iCol];
248 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
249 if( iCol==pTab->iPKey ){
250 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000251 }
drh25e978d2009-12-29 23:39:04 +0000252 break;
drh7d10d5a2008-08-20 16:35:10 +0000253 }
254 }
drh25e978d2009-12-29 23:39:04 +0000255 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000256 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000257 }
dan2bd93512009-08-31 08:22:46 +0000258 if( iCol<pTab->nCol ){
259 cnt++;
260 if( iCol<0 ){
261 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000262 }else if( pExpr->iTable==0 ){
263 testcase( iCol==31 );
264 testcase( iCol==32 );
265 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000266 }else{
267 testcase( iCol==31 );
268 testcase( iCol==32 );
269 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000270 }
shanecea72b22009-09-07 04:38:36 +0000271 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000272 pExpr->pTab = pTab;
273 isTrigger = 1;
274 }
drh7d10d5a2008-08-20 16:35:10 +0000275 }
276 }
277#endif /* !defined(SQLITE_OMIT_TRIGGER) */
278
279 /*
280 ** Perhaps the name is a reference to the ROWID
281 */
282 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
283 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000284 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000285 pExpr->affinity = SQLITE_AFF_INTEGER;
286 }
287
288 /*
289 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
290 ** might refer to an result-set alias. This happens, for example, when
291 ** we are resolving names in the WHERE clause of the following command:
292 **
293 ** SELECT a+b AS x FROM table WHERE x<10;
294 **
295 ** In cases like this, replace pExpr with a copy of the expression that
296 ** forms the result set entry ("a+b" in the example) and return immediately.
297 ** Note that the expression in the result set should have already been
298 ** resolved by the time the WHERE clause is resolved.
299 */
300 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
301 for(j=0; j<pEList->nExpr; j++){
302 char *zAs = pEList->a[j].zName;
303 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000304 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000305 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000306 assert( pExpr->x.pList==0 );
307 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000308 pOrig = pEList->a[j].pExpr;
309 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
310 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000311 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000312 }
drh8b213892008-08-29 02:14:02 +0000313 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000314 cnt = 1;
315 pMatch = 0;
316 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000317 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000318 }
319 }
320 }
321
322 /* Advance to the next name context. The loop will exit when either
323 ** we have a match (cnt>0) or when we run out of name contexts.
324 */
325 if( cnt==0 ){
326 pNC = pNC->pNext;
327 }
328 }
329
330 /*
331 ** If X and Y are NULL (in other words if only the column name Z is
332 ** supplied) and the value of Z is enclosed in double-quotes, then
333 ** Z is a string literal if it doesn't match any column names. In that
334 ** case, we need to return right away and not make any changes to
335 ** pExpr.
336 **
337 ** Because no reference was made to outer contexts, the pNC->nRef
338 ** fields are not changed in any context.
339 */
drh24fb6272009-05-01 21:13:36 +0000340 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000341 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000342 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000343 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000344 }
345
346 /*
347 ** cnt==0 means there was not match. cnt>1 means there were two or
348 ** more matches. Either way, we have an error.
349 */
350 if( cnt!=1 ){
351 const char *zErr;
352 zErr = cnt==0 ? "no such column" : "ambiguous column name";
353 if( zDb ){
354 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
355 }else if( zTab ){
356 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
357 }else{
358 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
359 }
360 pTopNC->nErr++;
361 }
362
363 /* If a column from a table in pSrcList is referenced, then record
364 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
365 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
366 ** column number is greater than the number of bits in the bitmask
367 ** then set the high-order bit of the bitmask.
368 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000369 if( pExpr->iColumn>=0 && pMatch!=0 ){
370 int n = pExpr->iColumn;
371 testcase( n==BMS-1 );
372 if( n>=BMS ){
373 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000374 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000375 assert( pMatch->iCursor==pExpr->iTable );
376 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000377 }
378
drh7d10d5a2008-08-20 16:35:10 +0000379 /* Clean up and return
380 */
drh7d10d5a2008-08-20 16:35:10 +0000381 sqlite3ExprDelete(db, pExpr->pLeft);
382 pExpr->pLeft = 0;
383 sqlite3ExprDelete(db, pExpr->pRight);
384 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000385 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000386lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000387 if( cnt==1 ){
388 assert( pNC!=0 );
389 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
390 /* Increment the nRef value on all name contexts from TopNC up to
391 ** the point where the name matched. */
392 for(;;){
393 assert( pTopNC!=0 );
394 pTopNC->nRef++;
395 if( pTopNC==pNC ) break;
396 pTopNC = pTopNC->pNext;
397 }
drhf7828b52009-06-15 23:15:59 +0000398 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000399 } else {
drhf7828b52009-06-15 23:15:59 +0000400 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000401 }
402}
403
404/*
danf7b0b0a2009-10-19 15:52:32 +0000405** Allocate and return a pointer to an expression to load the column iCol
406** from datasource iSrc datasource in SrcList pSrc.
407*/
408Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
409 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
410 if( p ){
411 struct SrcList_item *pItem = &pSrc->a[iSrc];
412 p->pTab = pItem->pTab;
413 p->iTable = pItem->iCursor;
414 if( p->pTab->iPKey==iCol ){
415 p->iColumn = -1;
416 }else{
drh8677d302009-11-04 13:17:14 +0000417 p->iColumn = (ynVar)iCol;
danf7b0b0a2009-10-19 15:52:32 +0000418 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
419 }
420 ExprSetProperty(p, EP_Resolved);
421 }
422 return p;
423}
424
425/*
drh7d10d5a2008-08-20 16:35:10 +0000426** This routine is callback for sqlite3WalkExpr().
427**
428** Resolve symbolic names into TK_COLUMN operators for the current
429** node in the expression tree. Return 0 to continue the search down
430** the tree or 2 to abort the tree walk.
431**
432** This routine also does error checking and name resolution for
433** function names. The operator for aggregate functions is changed
434** to TK_AGG_FUNCTION.
435*/
436static int resolveExprStep(Walker *pWalker, Expr *pExpr){
437 NameContext *pNC;
438 Parse *pParse;
439
drh7d10d5a2008-08-20 16:35:10 +0000440 pNC = pWalker->u.pNC;
441 assert( pNC!=0 );
442 pParse = pNC->pParse;
443 assert( pParse==pWalker->pParse );
444
445 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
446 ExprSetProperty(pExpr, EP_Resolved);
447#ifndef NDEBUG
448 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
449 SrcList *pSrcList = pNC->pSrcList;
450 int i;
451 for(i=0; i<pNC->pSrcList->nSrc; i++){
452 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
453 }
454 }
455#endif
456 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000457
shane273f6192008-10-10 04:34:16 +0000458#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000459 /* The special operator TK_ROW means use the rowid for the first
460 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
461 ** clause processing on UPDATE and DELETE statements.
462 */
463 case TK_ROW: {
464 SrcList *pSrcList = pNC->pSrcList;
465 struct SrcList_item *pItem;
466 assert( pSrcList && pSrcList->nSrc==1 );
467 pItem = pSrcList->a;
468 pExpr->op = TK_COLUMN;
469 pExpr->pTab = pItem->pTab;
470 pExpr->iTable = pItem->iCursor;
471 pExpr->iColumn = -1;
472 pExpr->affinity = SQLITE_AFF_INTEGER;
473 break;
474 }
shane273f6192008-10-10 04:34:16 +0000475#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000476
drh7d10d5a2008-08-20 16:35:10 +0000477 /* A lone identifier is the name of a column.
478 */
479 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000480 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000481 }
482
483 /* A table name and column name: ID.ID
484 ** Or a database, table and column: ID.ID.ID
485 */
486 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000487 const char *zColumn;
488 const char *zTable;
489 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000490 Expr *pRight;
491
492 /* if( pSrcList==0 ) break; */
493 pRight = pExpr->pRight;
494 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000495 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000496 zTable = pExpr->pLeft->u.zToken;
497 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000498 }else{
499 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000500 zDb = pExpr->pLeft->u.zToken;
501 zTable = pRight->pLeft->u.zToken;
502 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000503 }
drhf7828b52009-06-15 23:15:59 +0000504 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000505 }
506
507 /* Resolve function names
508 */
509 case TK_CONST_FUNC:
510 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000511 ExprList *pList = pExpr->x.pList; /* The argument list */
512 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000513 int no_such_func = 0; /* True if no such function exists */
514 int wrong_num_args = 0; /* True if wrong number of arguments */
515 int is_agg = 0; /* True if is an aggregate function */
516 int auth; /* Authorization to use the function */
517 int nId; /* Number of characters in function name */
518 const char *zId; /* The function name. */
519 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000520 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000521
drh73c0fdc2009-06-15 18:32:36 +0000522 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000523 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000524 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000525 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000526 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
527 if( pDef==0 ){
528 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
529 if( pDef==0 ){
530 no_such_func = 1;
531 }else{
532 wrong_num_args = 1;
533 }
534 }else{
535 is_agg = pDef->xFunc==0;
536 }
537#ifndef SQLITE_OMIT_AUTHORIZATION
538 if( pDef ){
539 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
540 if( auth!=SQLITE_OK ){
541 if( auth==SQLITE_DENY ){
542 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
543 pDef->zName);
544 pNC->nErr++;
545 }
546 pExpr->op = TK_NULL;
547 return WRC_Prune;
548 }
549 }
550#endif
551 if( is_agg && !pNC->allowAgg ){
552 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
553 pNC->nErr++;
554 is_agg = 0;
555 }else if( no_such_func ){
556 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
557 pNC->nErr++;
558 }else if( wrong_num_args ){
559 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
560 nId, zId);
561 pNC->nErr++;
562 }
563 if( is_agg ){
564 pExpr->op = TK_AGG_FUNCTION;
565 pNC->hasAgg = 1;
566 }
567 if( is_agg ) pNC->allowAgg = 0;
568 sqlite3WalkExprList(pWalker, pList);
569 if( is_agg ) pNC->allowAgg = 1;
570 /* FIX ME: Compute pExpr->affinity based on the expected return
571 ** type of the function
572 */
573 return WRC_Prune;
574 }
575#ifndef SQLITE_OMIT_SUBQUERY
576 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000577 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000578#endif
579 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000580 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000581 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000582 int nRef = pNC->nRef;
583#ifndef SQLITE_OMIT_CHECK
584 if( pNC->isCheck ){
585 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
586 }
587#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000588 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000589 assert( pNC->nRef>=nRef );
590 if( nRef!=pNC->nRef ){
591 ExprSetProperty(pExpr, EP_VarSelect);
592 }
593 }
594 break;
595 }
596#ifndef SQLITE_OMIT_CHECK
597 case TK_VARIABLE: {
598 if( pNC->isCheck ){
599 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
600 }
601 break;
602 }
603#endif
604 }
605 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
606}
607
608/*
609** pEList is a list of expressions which are really the result set of the
610** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
611** This routine checks to see if pE is a simple identifier which corresponds
612** to the AS-name of one of the terms of the expression list. If it is,
613** this routine return an integer between 1 and N where N is the number of
614** elements in pEList, corresponding to the matching entry. If there is
615** no match, or if pE is not a simple identifier, then this routine
616** return 0.
617**
618** pEList has been resolved. pE has not.
619*/
620static int resolveAsName(
621 Parse *pParse, /* Parsing context for error messages */
622 ExprList *pEList, /* List of expressions to scan */
623 Expr *pE /* Expression we are trying to match */
624){
625 int i; /* Loop counter */
626
shanecf697392009-06-01 16:53:09 +0000627 UNUSED_PARAMETER(pParse);
628
drh73c0fdc2009-06-15 18:32:36 +0000629 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000630 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000631 for(i=0; i<pEList->nExpr; i++){
632 char *zAs = pEList->a[i].zName;
633 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000634 return i+1;
635 }
636 }
drh7d10d5a2008-08-20 16:35:10 +0000637 }
638 return 0;
639}
640
641/*
642** pE is a pointer to an expression which is a single term in the
643** ORDER BY of a compound SELECT. The expression has not been
644** name resolved.
645**
646** At the point this routine is called, we already know that the
647** ORDER BY term is not an integer index into the result set. That
648** case is handled by the calling routine.
649**
650** Attempt to match pE against result set columns in the left-most
651** SELECT statement. Return the index i of the matching column,
652** as an indication to the caller that it should sort by the i-th column.
653** The left-most column is 1. In other words, the value returned is the
654** same integer value that would be used in the SQL statement to indicate
655** the column.
656**
657** If there is no match, return 0. Return -1 if an error occurs.
658*/
659static int resolveOrderByTermToExprList(
660 Parse *pParse, /* Parsing context for error messages */
661 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
662 Expr *pE /* The specific ORDER BY term */
663){
664 int i; /* Loop counter */
665 ExprList *pEList; /* The columns of the result set */
666 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000667 sqlite3 *db; /* Database connection */
668 int rc; /* Return code from subprocedures */
669 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000670
671 assert( sqlite3ExprIsInteger(pE, &i)==0 );
672 pEList = pSelect->pEList;
673
674 /* Resolve all names in the ORDER BY term expression
675 */
676 memset(&nc, 0, sizeof(nc));
677 nc.pParse = pParse;
678 nc.pSrcList = pSelect->pSrc;
679 nc.pEList = pEList;
680 nc.allowAgg = 1;
681 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000682 db = pParse->db;
683 savedSuppErr = db->suppressErr;
684 db->suppressErr = 1;
685 rc = sqlite3ResolveExprNames(&nc, pE);
686 db->suppressErr = savedSuppErr;
687 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000688
689 /* Try to match the ORDER BY expression against an expression
690 ** in the result set. Return an 1-based index of the matching
691 ** result-set entry.
692 */
693 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000694 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000695 return i+1;
696 }
697 }
698
699 /* If no match, return 0. */
700 return 0;
701}
702
703/*
704** Generate an ORDER BY or GROUP BY term out-of-range error.
705*/
706static void resolveOutOfRangeError(
707 Parse *pParse, /* The error context into which to write the error */
708 const char *zType, /* "ORDER" or "GROUP" */
709 int i, /* The index (1-based) of the term out of range */
710 int mx /* Largest permissible value of i */
711){
712 sqlite3ErrorMsg(pParse,
713 "%r %s BY term out of range - should be "
714 "between 1 and %d", i, zType, mx);
715}
716
717/*
718** Analyze the ORDER BY clause in a compound SELECT statement. Modify
719** each term of the ORDER BY clause is a constant integer between 1
720** and N where N is the number of columns in the compound SELECT.
721**
722** ORDER BY terms that are already an integer between 1 and N are
723** unmodified. ORDER BY terms that are integers outside the range of
724** 1 through N generate an error. ORDER BY terms that are expressions
725** are matched against result set expressions of compound SELECT
726** beginning with the left-most SELECT and working toward the right.
727** At the first match, the ORDER BY expression is transformed into
728** the integer column number.
729**
730** Return the number of errors seen.
731*/
732static int resolveCompoundOrderBy(
733 Parse *pParse, /* Parsing context. Leave error messages here */
734 Select *pSelect /* The SELECT statement containing the ORDER BY */
735){
736 int i;
737 ExprList *pOrderBy;
738 ExprList *pEList;
739 sqlite3 *db;
740 int moreToDo = 1;
741
742 pOrderBy = pSelect->pOrderBy;
743 if( pOrderBy==0 ) return 0;
744 db = pParse->db;
745#if SQLITE_MAX_COLUMN
746 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
747 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
748 return 1;
749 }
750#endif
751 for(i=0; i<pOrderBy->nExpr; i++){
752 pOrderBy->a[i].done = 0;
753 }
754 pSelect->pNext = 0;
755 while( pSelect->pPrior ){
756 pSelect->pPrior->pNext = pSelect;
757 pSelect = pSelect->pPrior;
758 }
759 while( pSelect && moreToDo ){
760 struct ExprList_item *pItem;
761 moreToDo = 0;
762 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000763 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000764 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
765 int iCol = -1;
766 Expr *pE, *pDup;
767 if( pItem->done ) continue;
768 pE = pItem->pExpr;
769 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000770 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000771 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
772 return 1;
773 }
774 }else{
775 iCol = resolveAsName(pParse, pEList, pE);
776 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000777 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000778 if( !db->mallocFailed ){
779 assert(pDup);
780 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
781 }
782 sqlite3ExprDelete(db, pDup);
783 }
drh7d10d5a2008-08-20 16:35:10 +0000784 }
785 if( iCol>0 ){
786 CollSeq *pColl = pE->pColl;
787 int flags = pE->flags & EP_ExpCollate;
788 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000789 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000790 if( pE==0 ) return 1;
791 pE->pColl = pColl;
792 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000793 pE->u.iValue = iCol;
drhea678832008-12-10 19:26:22 +0000794 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000795 pItem->done = 1;
796 }else{
797 moreToDo = 1;
798 }
799 }
800 pSelect = pSelect->pNext;
801 }
802 for(i=0; i<pOrderBy->nExpr; i++){
803 if( pOrderBy->a[i].done==0 ){
804 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
805 "column in the result set", i+1);
806 return 1;
807 }
808 }
809 return 0;
810}
811
812/*
813** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
814** the SELECT statement pSelect. If any term is reference to a
815** result set expression (as determined by the ExprList.a.iCol field)
816** then convert that term into a copy of the corresponding result set
817** column.
818**
819** If any errors are detected, add an error message to pParse and
820** return non-zero. Return zero if no errors are seen.
821*/
822int sqlite3ResolveOrderGroupBy(
823 Parse *pParse, /* Parsing context. Leave error messages here */
824 Select *pSelect, /* The SELECT statement containing the clause */
825 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
826 const char *zType /* "ORDER" or "GROUP" */
827){
828 int i;
829 sqlite3 *db = pParse->db;
830 ExprList *pEList;
831 struct ExprList_item *pItem;
832
833 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
834#if SQLITE_MAX_COLUMN
835 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
836 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
837 return 1;
838 }
839#endif
840 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000841 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000842 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
843 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000844 if( pItem->iCol>pEList->nExpr ){
845 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
846 return 1;
847 }
drh8b213892008-08-29 02:14:02 +0000848 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000849 }
850 }
851 return 0;
852}
853
854/*
855** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
856** The Name context of the SELECT statement is pNC. zType is either
857** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
858**
859** This routine resolves each term of the clause into an expression.
860** If the order-by term is an integer I between 1 and N (where N is the
861** number of columns in the result set of the SELECT) then the expression
862** in the resolution is a copy of the I-th result-set expression. If
863** the order-by term is an identify that corresponds to the AS-name of
864** a result-set expression, then the term resolves to a copy of the
865** result-set expression. Otherwise, the expression is resolved in
866** the usual way - using sqlite3ResolveExprNames().
867**
868** This routine returns the number of errors. If errors occur, then
869** an appropriate error message might be left in pParse. (OOM errors
870** excepted.)
871*/
872static int resolveOrderGroupBy(
873 NameContext *pNC, /* The name context of the SELECT statement */
874 Select *pSelect, /* The SELECT statement holding pOrderBy */
875 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
876 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
877){
878 int i; /* Loop counter */
879 int iCol; /* Column number */
880 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
881 Parse *pParse; /* Parsing context */
882 int nResult; /* Number of terms in the result set */
883
884 if( pOrderBy==0 ) return 0;
885 nResult = pSelect->pEList->nExpr;
886 pParse = pNC->pParse;
887 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
888 Expr *pE = pItem->pExpr;
889 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000890 if( iCol>0 ){
891 /* If an AS-name match is found, mark this ORDER BY column as being
892 ** a copy of the iCol-th result-set column. The subsequent call to
893 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
894 ** copy of the iCol-th result-set expression. */
drhea678832008-12-10 19:26:22 +0000895 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000896 continue;
897 }
898 if( sqlite3ExprIsInteger(pE, &iCol) ){
899 /* The ORDER BY term is an integer constant. Again, set the column
900 ** number so that sqlite3ResolveOrderGroupBy() will convert the
901 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000902 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000903 resolveOutOfRangeError(pParse, zType, i+1, nResult);
904 return 1;
905 }
drhea678832008-12-10 19:26:22 +0000906 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000907 continue;
908 }
909
910 /* Otherwise, treat the ORDER BY term as an ordinary expression */
911 pItem->iCol = 0;
912 if( sqlite3ResolveExprNames(pNC, pE) ){
913 return 1;
914 }
915 }
916 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
917}
918
919/*
920** Resolve names in the SELECT statement p and all of its descendents.
921*/
922static int resolveSelectStep(Walker *pWalker, Select *p){
923 NameContext *pOuterNC; /* Context that contains this SELECT */
924 NameContext sNC; /* Name context of this SELECT */
925 int isCompound; /* True if p is a compound select */
926 int nCompound; /* Number of compound terms processed so far */
927 Parse *pParse; /* Parsing context */
928 ExprList *pEList; /* Result set expression list */
929 int i; /* Loop counter */
930 ExprList *pGroupBy; /* The GROUP BY clause */
931 Select *pLeftmost; /* Left-most of SELECT of a compound */
932 sqlite3 *db; /* Database connection */
933
934
drh0a846f92008-08-25 17:23:29 +0000935 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000936 if( p->selFlags & SF_Resolved ){
937 return WRC_Prune;
938 }
939 pOuterNC = pWalker->u.pNC;
940 pParse = pWalker->pParse;
941 db = pParse->db;
942
943 /* Normally sqlite3SelectExpand() will be called first and will have
944 ** already expanded this SELECT. However, if this is a subquery within
945 ** an expression, sqlite3ResolveExprNames() will be called without a
946 ** prior call to sqlite3SelectExpand(). When that happens, let
947 ** sqlite3SelectPrep() do all of the processing for this SELECT.
948 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
949 ** this routine in the correct order.
950 */
951 if( (p->selFlags & SF_Expanded)==0 ){
952 sqlite3SelectPrep(pParse, p, pOuterNC);
953 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
954 }
955
956 isCompound = p->pPrior!=0;
957 nCompound = 0;
958 pLeftmost = p;
959 while( p ){
960 assert( (p->selFlags & SF_Expanded)!=0 );
961 assert( (p->selFlags & SF_Resolved)==0 );
962 p->selFlags |= SF_Resolved;
963
964 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
965 ** are not allowed to refer to any names, so pass an empty NameContext.
966 */
967 memset(&sNC, 0, sizeof(sNC));
968 sNC.pParse = pParse;
969 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
970 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
971 return WRC_Abort;
972 }
973
974 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
975 ** resolve the result-set expression list.
976 */
977 sNC.allowAgg = 1;
978 sNC.pSrcList = p->pSrc;
979 sNC.pNext = pOuterNC;
980
981 /* Resolve names in the result set. */
982 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000983 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000984 for(i=0; i<pEList->nExpr; i++){
985 Expr *pX = pEList->a[i].pExpr;
986 if( sqlite3ResolveExprNames(&sNC, pX) ){
987 return WRC_Abort;
988 }
989 }
990
991 /* Recursively resolve names in all subqueries
992 */
993 for(i=0; i<p->pSrc->nSrc; i++){
994 struct SrcList_item *pItem = &p->pSrc->a[i];
995 if( pItem->pSelect ){
996 const char *zSavedContext = pParse->zAuthContext;
997 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +0000998 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +0000999 pParse->zAuthContext = zSavedContext;
1000 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
1001 }
1002 }
1003
1004 /* If there are no aggregate functions in the result-set, and no GROUP BY
1005 ** expression, do not allow aggregates in any of the other expressions.
1006 */
1007 assert( (p->selFlags & SF_Aggregate)==0 );
1008 pGroupBy = p->pGroupBy;
1009 if( pGroupBy || sNC.hasAgg ){
1010 p->selFlags |= SF_Aggregate;
1011 }else{
1012 sNC.allowAgg = 0;
1013 }
1014
1015 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1016 */
1017 if( p->pHaving && !pGroupBy ){
1018 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1019 return WRC_Abort;
1020 }
1021
1022 /* Add the expression list to the name-context before parsing the
1023 ** other expressions in the SELECT statement. This is so that
1024 ** expressions in the WHERE clause (etc.) can refer to expressions by
1025 ** aliases in the result set.
1026 **
1027 ** Minor point: If this is the case, then the expression will be
1028 ** re-evaluated for each reference to it.
1029 */
1030 sNC.pEList = p->pEList;
1031 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1032 sqlite3ResolveExprNames(&sNC, p->pHaving)
1033 ){
1034 return WRC_Abort;
1035 }
1036
1037 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1038 ** outer queries
1039 */
1040 sNC.pNext = 0;
1041 sNC.allowAgg = 1;
1042
1043 /* Process the ORDER BY clause for singleton SELECT statements.
1044 ** The ORDER BY clause for compounds SELECT statements is handled
1045 ** below, after all of the result-sets for all of the elements of
1046 ** the compound have been resolved.
1047 */
1048 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1049 return WRC_Abort;
1050 }
1051 if( db->mallocFailed ){
1052 return WRC_Abort;
1053 }
1054
1055 /* Resolve the GROUP BY clause. At the same time, make sure
1056 ** the GROUP BY clause does not contain aggregate functions.
1057 */
1058 if( pGroupBy ){
1059 struct ExprList_item *pItem;
1060
1061 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1062 return WRC_Abort;
1063 }
1064 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1065 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1066 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1067 "the GROUP BY clause");
1068 return WRC_Abort;
1069 }
1070 }
1071 }
1072
1073 /* Advance to the next term of the compound
1074 */
1075 p = p->pPrior;
1076 nCompound++;
1077 }
1078
1079 /* Resolve the ORDER BY on a compound SELECT after all terms of
1080 ** the compound have been resolved.
1081 */
1082 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1083 return WRC_Abort;
1084 }
1085
1086 return WRC_Prune;
1087}
1088
1089/*
1090** This routine walks an expression tree and resolves references to
1091** table columns and result-set columns. At the same time, do error
1092** checking on function usage and set a flag if any aggregate functions
1093** are seen.
1094**
1095** To resolve table columns references we look for nodes (or subtrees) of the
1096** form X.Y.Z or Y.Z or just Z where
1097**
1098** X: The name of a database. Ex: "main" or "temp" or
1099** the symbolic name assigned to an ATTACH-ed database.
1100**
1101** Y: The name of a table in a FROM clause. Or in a trigger
1102** one of the special names "old" or "new".
1103**
1104** Z: The name of a column in table Y.
1105**
1106** The node at the root of the subtree is modified as follows:
1107**
1108** Expr.op Changed to TK_COLUMN
1109** Expr.pTab Points to the Table object for X.Y
1110** Expr.iColumn The column index in X.Y. -1 for the rowid.
1111** Expr.iTable The VDBE cursor number for X.Y
1112**
1113**
1114** To resolve result-set references, look for expression nodes of the
1115** form Z (with no X and Y prefix) where the Z matches the right-hand
1116** size of an AS clause in the result-set of a SELECT. The Z expression
1117** is replaced by a copy of the left-hand side of the result-set expression.
1118** Table-name and function resolution occurs on the substituted expression
1119** tree. For example, in:
1120**
1121** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1122**
1123** The "x" term of the order by is replaced by "a+b" to render:
1124**
1125** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1126**
1127** Function calls are checked to make sure that the function is
1128** defined and that the correct number of arguments are specified.
1129** If the function is an aggregate function, then the pNC->hasAgg is
1130** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1131** If an expression contains aggregate functions then the EP_Agg
1132** property on the expression is set.
1133**
1134** An error message is left in pParse if anything is amiss. The number
1135** if errors is returned.
1136*/
1137int sqlite3ResolveExprNames(
1138 NameContext *pNC, /* Namespace to resolve expressions in. */
1139 Expr *pExpr /* The expression to be analyzed. */
1140){
1141 int savedHasAgg;
1142 Walker w;
1143
1144 if( pExpr==0 ) return 0;
1145#if SQLITE_MAX_EXPR_DEPTH>0
1146 {
1147 Parse *pParse = pNC->pParse;
1148 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1149 return 1;
1150 }
1151 pParse->nHeight += pExpr->nHeight;
1152 }
1153#endif
1154 savedHasAgg = pNC->hasAgg;
1155 pNC->hasAgg = 0;
1156 w.xExprCallback = resolveExprStep;
1157 w.xSelectCallback = resolveSelectStep;
1158 w.pParse = pNC->pParse;
1159 w.u.pNC = pNC;
1160 sqlite3WalkExpr(&w, pExpr);
1161#if SQLITE_MAX_EXPR_DEPTH>0
1162 pNC->pParse->nHeight -= pExpr->nHeight;
1163#endif
drhfd773cf2009-05-29 14:39:07 +00001164 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001165 ExprSetProperty(pExpr, EP_Error);
1166 }
1167 if( pNC->hasAgg ){
1168 ExprSetProperty(pExpr, EP_Agg);
1169 }else if( savedHasAgg ){
1170 pNC->hasAgg = 1;
1171 }
1172 return ExprHasProperty(pExpr, EP_Error);
1173}
drh7d10d5a2008-08-20 16:35:10 +00001174
1175
1176/*
1177** Resolve all names in all expressions of a SELECT and in all
1178** decendents of the SELECT, including compounds off of p->pPrior,
1179** subqueries in expressions, and subqueries used as FROM clause
1180** terms.
1181**
1182** See sqlite3ResolveExprNames() for a description of the kinds of
1183** transformations that occur.
1184**
1185** All SELECT statements should have been expanded using
1186** sqlite3SelectExpand() prior to invoking this routine.
1187*/
1188void sqlite3ResolveSelectNames(
1189 Parse *pParse, /* The parser context */
1190 Select *p, /* The SELECT statement being coded. */
1191 NameContext *pOuterNC /* Name context for parent SELECT statement */
1192){
1193 Walker w;
1194
drh0a846f92008-08-25 17:23:29 +00001195 assert( p!=0 );
1196 w.xExprCallback = resolveExprStep;
1197 w.xSelectCallback = resolveSelectStep;
1198 w.pParse = pParse;
1199 w.u.pNC = pOuterNC;
1200 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001201}