blob: c2b0523f0852cce52c0c7ebaebfb82ac1bcac055 [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/*
drhed551b92012-08-23 19:46:11 +000022** Walk the expression tree pExpr and increase the aggregate function
23** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
24** This needs to occur when copying a TK_AGG_FUNCTION node from an
25** outer query into an inner subquery.
26**
27** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
28** is a helper function - a callback for the tree walker.
29*/
30static int incrAggDepth(Walker *pWalker, Expr *pExpr){
31 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
32 return WRC_Continue;
33}
34static void incrAggFunctionDepth(Expr *pExpr, int N){
35 if( N>0 ){
36 Walker w;
37 memset(&w, 0, sizeof(w));
38 w.xExprCallback = incrAggDepth;
39 w.u.i = N;
40 sqlite3WalkExpr(&w, pExpr);
41 }
42}
43
44/*
drh8b213892008-08-29 02:14:02 +000045** Turn the pExpr expression into an alias for the iCol-th column of the
46** result set in pEList.
47**
48** If the result set column is a simple column reference, then this routine
49** makes an exact copy. But for any other kind of expression, this
50** routine make a copy of the result set column as the argument to the
51** TK_AS operator. The TK_AS operator causes the expression to be
52** evaluated just once and then reused for each alias.
53**
54** The reason for suppressing the TK_AS term when the expression is a simple
55** column reference is so that the column reference will be recognized as
56** usable by indices within the WHERE clause processing logic.
57**
58** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
59** that in a GROUP BY clause, the expression is evaluated twice. Hence:
60**
61** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
62**
63** Is equivalent to:
64**
65** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
66**
67** The result of random()%5 in the GROUP BY clause is probably different
68** from the result in the result-set. We might fix this someday. Or
69** then again, we might not...
drhed551b92012-08-23 19:46:11 +000070**
71** The nSubquery parameter specifies how many levels of subquery the
72** alias is removed from the original expression. The usually value is
73** zero but it might be more if the alias is contained within a subquery
74** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
75** structures must be increased by the nSubquery amount.
drh8b213892008-08-29 02:14:02 +000076*/
77static void resolveAlias(
78 Parse *pParse, /* Parsing context */
79 ExprList *pEList, /* A result set */
80 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
81 Expr *pExpr, /* Transform this into an alias to the result set */
drhed551b92012-08-23 19:46:11 +000082 const char *zType, /* "GROUP" or "ORDER" or "" */
83 int nSubquery /* Number of subqueries that the label is moving */
drh8b213892008-08-29 02:14:02 +000084){
85 Expr *pOrig; /* The iCol-th column of the result set */
86 Expr *pDup; /* Copy of pOrig */
87 sqlite3 *db; /* The database connection */
88
89 assert( iCol>=0 && iCol<pEList->nExpr );
90 pOrig = pEList->a[iCol].pExpr;
91 assert( pOrig!=0 );
92 assert( pOrig->flags & EP_Resolved );
93 db = pParse->db;
drhb7916a72009-05-27 10:31:29 +000094 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
95 pDup = sqlite3ExprDup(db, pOrig, 0);
drhed551b92012-08-23 19:46:11 +000096 incrAggFunctionDepth(pDup, nSubquery);
drh8b213892008-08-29 02:14:02 +000097 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
98 if( pDup==0 ) return;
99 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +0000100 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +0000101 }
102 pDup->iTable = pEList->a[iCol].iAlias;
drh0b0745a2009-05-28 12:49:53 +0000103 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
104 pDup = sqlite3ExprDup(db, pOrig, 0);
drh2c220452009-05-28 14:34:49 +0000105 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +0000106 }else{
drh33e619f2009-05-28 01:00:55 +0000107 char *zToken = pOrig->u.zToken;
drh73c0fdc2009-06-15 18:32:36 +0000108 assert( zToken!=0 );
drh33e619f2009-05-28 01:00:55 +0000109 pOrig->u.zToken = 0;
drhb7916a72009-05-27 10:31:29 +0000110 pDup = sqlite3ExprDup(db, pOrig, 0);
drh33e619f2009-05-28 01:00:55 +0000111 pOrig->u.zToken = zToken;
drhb7916a72009-05-27 10:31:29 +0000112 if( pDup==0 ) return;
drh73c0fdc2009-06-15 18:32:36 +0000113 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
114 pDup->flags2 |= EP2_MallocedToken;
115 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
drh8b213892008-08-29 02:14:02 +0000116 }
danf6963f92009-11-23 14:39:14 +0000117
118 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
119 ** prevents ExprDelete() from deleting the Expr structure itself,
120 ** allowing it to be repopulated by the memcpy() on the following line.
121 */
122 ExprSetProperty(pExpr, EP_Static);
123 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +0000124 memcpy(pExpr, pDup, sizeof(*pExpr));
125 sqlite3DbFree(db, pDup);
126}
127
drhe802c5d2011-10-18 18:10:40 +0000128
129/*
130** Return TRUE if the name zCol occurs anywhere in the USING clause.
131**
132** Return FALSE if the USING clause is NULL or if it does not contain
133** zCol.
134*/
135static int nameInUsingClause(IdList *pUsing, const char *zCol){
136 if( pUsing ){
137 int k;
138 for(k=0; k<pUsing->nId; k++){
139 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
140 }
141 }
142 return 0;
143}
144
145
drh8b213892008-08-29 02:14:02 +0000146/*
drh7d10d5a2008-08-20 16:35:10 +0000147** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
148** that name in the set of source tables in pSrcList and make the pExpr
149** expression node refer back to that source column. The following changes
150** are made to pExpr:
151**
152** pExpr->iDb Set the index in db->aDb[] of the database X
153** (even if X is implied).
154** pExpr->iTable Set to the cursor number for the table obtained
155** from pSrcList.
156** pExpr->pTab Points to the Table structure of X.Y (even if
157** X and/or Y are implied.)
158** pExpr->iColumn Set to the column number within the table.
159** pExpr->op Set to TK_COLUMN.
160** pExpr->pLeft Any expression this points to is deleted
161** pExpr->pRight Any expression this points to is deleted.
162**
drhb7916a72009-05-27 10:31:29 +0000163** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000164** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000165** can be used. The zTable variable is the name of the table (the "Y"). This
166** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000167** means that the form of the name is Z and that columns from any table
168** can be used.
169**
170** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000171** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000172*/
173static int lookupName(
174 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000175 const char *zDb, /* Name of the database containing table, or NULL */
176 const char *zTab, /* Name of table containing column, or NULL */
177 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000178 NameContext *pNC, /* The name context used to resolve the name */
179 Expr *pExpr /* Make this EXPR node point to the selected column */
180){
drhed551b92012-08-23 19:46:11 +0000181 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000182 int cnt = 0; /* Number of matching column names */
183 int cntTab = 0; /* Number of matching table names */
drhed551b92012-08-23 19:46:11 +0000184 int nSubquery = 0; /* How many levels of subquery */
drh7d10d5a2008-08-20 16:35:10 +0000185 sqlite3 *db = pParse->db; /* The database connection */
186 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
187 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
188 NameContext *pTopNC = pNC; /* First namecontext in the list */
189 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000190 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000191
drhb7916a72009-05-27 10:31:29 +0000192 assert( pNC ); /* the name context cannot be NULL. */
193 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh5a05be12012-10-09 18:51:44 +0000194 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000195
196 /* Initialize the node to no-match */
197 pExpr->iTable = -1;
198 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000199 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000200
201 /* Start at the inner-most context and move outward until a match is found */
202 while( pNC && cnt==0 ){
203 ExprList *pEList;
204 SrcList *pSrcList = pNC->pSrcList;
205
206 if( pSrcList ){
207 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
208 Table *pTab;
209 int iDb;
210 Column *pCol;
211
212 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000213 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000214 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
215 assert( pTab->nCol>0 );
216 if( zTab ){
217 if( pItem->zAlias ){
218 char *zTabName = pItem->zAlias;
219 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
220 }else{
221 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000222 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
223 continue;
224 }
drh7d10d5a2008-08-20 16:35:10 +0000225 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
226 continue;
227 }
228 }
229 }
230 if( 0==(cntTab++) ){
231 pExpr->iTable = pItem->iCursor;
232 pExpr->pTab = pTab;
233 pSchema = pTab->pSchema;
234 pMatch = pItem;
235 }
236 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
237 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
drhe802c5d2011-10-18 18:10:40 +0000238 /* If there has been exactly one prior match and this match
239 ** is for the right-hand table of a NATURAL JOIN or is in a
240 ** USING clause, then skip this match.
241 */
242 if( cnt==1 ){
243 if( pItem->jointype & JT_NATURAL ) continue;
244 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
245 }
drh7d10d5a2008-08-20 16:35:10 +0000246 cnt++;
247 pExpr->iTable = pItem->iCursor;
248 pExpr->pTab = pTab;
249 pMatch = pItem;
250 pSchema = pTab->pSchema;
251 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000252 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000253 break;
254 }
255 }
256 }
257 }
258
259#ifndef SQLITE_OMIT_TRIGGER
260 /* If we have not already resolved the name, then maybe
261 ** it is a new.* or old.* trigger argument reference
262 */
dan165921a2009-08-28 18:53:45 +0000263 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000264 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000265 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000266 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
267 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000268 pExpr->iTable = 1;
269 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000270 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000271 pExpr->iTable = 0;
272 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000273 }
274
275 if( pTab ){
276 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000277 pSchema = pTab->pSchema;
278 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000279 for(iCol=0; iCol<pTab->nCol; iCol++){
280 Column *pCol = &pTab->aCol[iCol];
281 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
282 if( iCol==pTab->iPKey ){
283 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000284 }
drh25e978d2009-12-29 23:39:04 +0000285 break;
drh7d10d5a2008-08-20 16:35:10 +0000286 }
287 }
drh25e978d2009-12-29 23:39:04 +0000288 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000289 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000290 }
dan2bd93512009-08-31 08:22:46 +0000291 if( iCol<pTab->nCol ){
292 cnt++;
293 if( iCol<0 ){
294 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000295 }else if( pExpr->iTable==0 ){
296 testcase( iCol==31 );
297 testcase( iCol==32 );
298 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000299 }else{
300 testcase( iCol==31 );
301 testcase( iCol==32 );
302 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000303 }
shanecea72b22009-09-07 04:38:36 +0000304 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000305 pExpr->pTab = pTab;
306 isTrigger = 1;
307 }
drh7d10d5a2008-08-20 16:35:10 +0000308 }
309 }
310#endif /* !defined(SQLITE_OMIT_TRIGGER) */
311
312 /*
313 ** Perhaps the name is a reference to the ROWID
314 */
315 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
316 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000317 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000318 pExpr->affinity = SQLITE_AFF_INTEGER;
319 }
320
321 /*
322 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
323 ** might refer to an result-set alias. This happens, for example, when
324 ** we are resolving names in the WHERE clause of the following command:
325 **
326 ** SELECT a+b AS x FROM table WHERE x<10;
327 **
328 ** In cases like this, replace pExpr with a copy of the expression that
329 ** forms the result set entry ("a+b" in the example) and return immediately.
330 ** Note that the expression in the result set should have already been
331 ** resolved by the time the WHERE clause is resolved.
332 */
333 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
334 for(j=0; j<pEList->nExpr; j++){
335 char *zAs = pEList->a[j].zName;
336 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000337 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000338 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000339 assert( pExpr->x.pList==0 );
340 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000341 pOrig = pEList->a[j].pExpr;
drha51009b2012-05-21 19:11:25 +0000342 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10 +0000343 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000344 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000345 }
drhed551b92012-08-23 19:46:11 +0000346 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
drh7d10d5a2008-08-20 16:35:10 +0000347 cnt = 1;
348 pMatch = 0;
349 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000350 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000351 }
352 }
353 }
354
355 /* Advance to the next name context. The loop will exit when either
356 ** we have a match (cnt>0) or when we run out of name contexts.
357 */
358 if( cnt==0 ){
359 pNC = pNC->pNext;
drhed551b92012-08-23 19:46:11 +0000360 nSubquery++;
drh7d10d5a2008-08-20 16:35:10 +0000361 }
362 }
363
364 /*
365 ** If X and Y are NULL (in other words if only the column name Z is
366 ** supplied) and the value of Z is enclosed in double-quotes, then
367 ** Z is a string literal if it doesn't match any column names. In that
368 ** case, we need to return right away and not make any changes to
369 ** pExpr.
370 **
371 ** Because no reference was made to outer contexts, the pNC->nRef
372 ** fields are not changed in any context.
373 */
drh24fb6272009-05-01 21:13:36 +0000374 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000375 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000376 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000377 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000378 }
379
380 /*
381 ** cnt==0 means there was not match. cnt>1 means there were two or
382 ** more matches. Either way, we have an error.
383 */
384 if( cnt!=1 ){
385 const char *zErr;
386 zErr = cnt==0 ? "no such column" : "ambiguous column name";
387 if( zDb ){
388 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
389 }else if( zTab ){
390 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
391 }else{
392 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
393 }
dan1db95102010-06-28 10:15:19 +0000394 pParse->checkSchema = 1;
drh7d10d5a2008-08-20 16:35:10 +0000395 pTopNC->nErr++;
396 }
397
398 /* If a column from a table in pSrcList is referenced, then record
399 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
400 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
401 ** column number is greater than the number of bits in the bitmask
402 ** then set the high-order bit of the bitmask.
403 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000404 if( pExpr->iColumn>=0 && pMatch!=0 ){
405 int n = pExpr->iColumn;
406 testcase( n==BMS-1 );
407 if( n>=BMS ){
408 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000409 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000410 assert( pMatch->iCursor==pExpr->iTable );
411 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000412 }
413
drh7d10d5a2008-08-20 16:35:10 +0000414 /* Clean up and return
415 */
drh7d10d5a2008-08-20 16:35:10 +0000416 sqlite3ExprDelete(db, pExpr->pLeft);
417 pExpr->pLeft = 0;
418 sqlite3ExprDelete(db, pExpr->pRight);
419 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000420 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000421lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000422 if( cnt==1 ){
423 assert( pNC!=0 );
424 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
425 /* Increment the nRef value on all name contexts from TopNC up to
426 ** the point where the name matched. */
427 for(;;){
428 assert( pTopNC!=0 );
429 pTopNC->nRef++;
430 if( pTopNC==pNC ) break;
431 pTopNC = pTopNC->pNext;
432 }
drhf7828b52009-06-15 23:15:59 +0000433 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000434 } else {
drhf7828b52009-06-15 23:15:59 +0000435 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000436 }
437}
438
439/*
danf7b0b0a2009-10-19 15:52:32 +0000440** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34 +0000441** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32 +0000442*/
443Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
444 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
445 if( p ){
446 struct SrcList_item *pItem = &pSrc->a[iSrc];
447 p->pTab = pItem->pTab;
448 p->iTable = pItem->iCursor;
449 if( p->pTab->iPKey==iCol ){
450 p->iColumn = -1;
451 }else{
drh8677d302009-11-04 13:17:14 +0000452 p->iColumn = (ynVar)iCol;
drh7caba662010-04-08 15:01:44 +0000453 testcase( iCol==BMS );
454 testcase( iCol==BMS-1 );
danf7b0b0a2009-10-19 15:52:32 +0000455 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
456 }
457 ExprSetProperty(p, EP_Resolved);
458 }
459 return p;
460}
461
462/*
drh7d10d5a2008-08-20 16:35:10 +0000463** This routine is callback for sqlite3WalkExpr().
464**
465** Resolve symbolic names into TK_COLUMN operators for the current
466** node in the expression tree. Return 0 to continue the search down
467** the tree or 2 to abort the tree walk.
468**
469** This routine also does error checking and name resolution for
470** function names. The operator for aggregate functions is changed
471** to TK_AGG_FUNCTION.
472*/
473static int resolveExprStep(Walker *pWalker, Expr *pExpr){
474 NameContext *pNC;
475 Parse *pParse;
476
drh7d10d5a2008-08-20 16:35:10 +0000477 pNC = pWalker->u.pNC;
478 assert( pNC!=0 );
479 pParse = pNC->pParse;
480 assert( pParse==pWalker->pParse );
481
482 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
483 ExprSetProperty(pExpr, EP_Resolved);
484#ifndef NDEBUG
485 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
486 SrcList *pSrcList = pNC->pSrcList;
487 int i;
488 for(i=0; i<pNC->pSrcList->nSrc; i++){
489 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
490 }
491 }
492#endif
493 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000494
shane273f6192008-10-10 04:34:16 +0000495#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000496 /* The special operator TK_ROW means use the rowid for the first
497 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
498 ** clause processing on UPDATE and DELETE statements.
499 */
500 case TK_ROW: {
501 SrcList *pSrcList = pNC->pSrcList;
502 struct SrcList_item *pItem;
503 assert( pSrcList && pSrcList->nSrc==1 );
504 pItem = pSrcList->a;
505 pExpr->op = TK_COLUMN;
506 pExpr->pTab = pItem->pTab;
507 pExpr->iTable = pItem->iCursor;
508 pExpr->iColumn = -1;
509 pExpr->affinity = SQLITE_AFF_INTEGER;
510 break;
511 }
shane273f6192008-10-10 04:34:16 +0000512#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000513
drh7d10d5a2008-08-20 16:35:10 +0000514 /* A lone identifier is the name of a column.
515 */
516 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000517 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000518 }
519
520 /* A table name and column name: ID.ID
521 ** Or a database, table and column: ID.ID.ID
522 */
523 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000524 const char *zColumn;
525 const char *zTable;
526 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000527 Expr *pRight;
528
529 /* if( pSrcList==0 ) break; */
530 pRight = pExpr->pRight;
531 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000532 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000533 zTable = pExpr->pLeft->u.zToken;
534 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000535 }else{
536 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000537 zDb = pExpr->pLeft->u.zToken;
538 zTable = pRight->pLeft->u.zToken;
539 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000540 }
drhf7828b52009-06-15 23:15:59 +0000541 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000542 }
543
544 /* Resolve function names
545 */
546 case TK_CONST_FUNC:
547 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000548 ExprList *pList = pExpr->x.pList; /* The argument list */
549 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000550 int no_such_func = 0; /* True if no such function exists */
551 int wrong_num_args = 0; /* True if wrong number of arguments */
552 int is_agg = 0; /* True if is an aggregate function */
553 int auth; /* Authorization to use the function */
554 int nId; /* Number of characters in function name */
555 const char *zId; /* The function name. */
556 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000557 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000558
drh73c0fdc2009-06-15 18:32:36 +0000559 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000560 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000561 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000562 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000563 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
564 if( pDef==0 ){
drh89d5d6a2012-04-07 00:09:21 +0000565 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:10 +0000566 if( pDef==0 ){
567 no_such_func = 1;
568 }else{
569 wrong_num_args = 1;
570 }
571 }else{
572 is_agg = pDef->xFunc==0;
573 }
574#ifndef SQLITE_OMIT_AUTHORIZATION
575 if( pDef ){
576 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
577 if( auth!=SQLITE_OK ){
578 if( auth==SQLITE_DENY ){
579 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
580 pDef->zName);
581 pNC->nErr++;
582 }
583 pExpr->op = TK_NULL;
584 return WRC_Prune;
585 }
586 }
587#endif
drha51009b2012-05-21 19:11:25 +0000588 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000589 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
590 pNC->nErr++;
591 is_agg = 0;
592 }else if( no_such_func ){
593 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
594 pNC->nErr++;
595 }else if( wrong_num_args ){
596 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
597 nId, zId);
598 pNC->nErr++;
599 }
drha51009b2012-05-21 19:11:25 +0000600 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000601 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:10 +0000602 if( is_agg ){
603 NameContext *pNC2 = pNC;
604 pExpr->op = TK_AGG_FUNCTION;
605 pExpr->op2 = 0;
606 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
607 pExpr->op2++;
608 pNC2 = pNC2->pNext;
609 }
610 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
611 pNC->ncFlags |= NC_AllowAgg;
612 }
drh7d10d5a2008-08-20 16:35:10 +0000613 /* FIX ME: Compute pExpr->affinity based on the expected return
614 ** type of the function
615 */
616 return WRC_Prune;
617 }
618#ifndef SQLITE_OMIT_SUBQUERY
619 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000620 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000621#endif
622 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000623 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000624 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000625 int nRef = pNC->nRef;
626#ifndef SQLITE_OMIT_CHECK
drha51009b2012-05-21 19:11:25 +0000627 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000628 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
629 }
630#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000631 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000632 assert( pNC->nRef>=nRef );
633 if( nRef!=pNC->nRef ){
634 ExprSetProperty(pExpr, EP_VarSelect);
635 }
636 }
637 break;
638 }
639#ifndef SQLITE_OMIT_CHECK
640 case TK_VARIABLE: {
drha51009b2012-05-21 19:11:25 +0000641 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000642 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
643 }
644 break;
645 }
646#endif
647 }
648 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
649}
650
651/*
652** pEList is a list of expressions which are really the result set of the
653** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
654** This routine checks to see if pE is a simple identifier which corresponds
655** to the AS-name of one of the terms of the expression list. If it is,
656** this routine return an integer between 1 and N where N is the number of
657** elements in pEList, corresponding to the matching entry. If there is
658** no match, or if pE is not a simple identifier, then this routine
659** return 0.
660**
661** pEList has been resolved. pE has not.
662*/
663static int resolveAsName(
664 Parse *pParse, /* Parsing context for error messages */
665 ExprList *pEList, /* List of expressions to scan */
666 Expr *pE /* Expression we are trying to match */
667){
668 int i; /* Loop counter */
669
shanecf697392009-06-01 16:53:09 +0000670 UNUSED_PARAMETER(pParse);
671
drh73c0fdc2009-06-15 18:32:36 +0000672 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000673 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000674 for(i=0; i<pEList->nExpr; i++){
675 char *zAs = pEList->a[i].zName;
676 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000677 return i+1;
678 }
679 }
drh7d10d5a2008-08-20 16:35:10 +0000680 }
681 return 0;
682}
683
684/*
685** pE is a pointer to an expression which is a single term in the
686** ORDER BY of a compound SELECT. The expression has not been
687** name resolved.
688**
689** At the point this routine is called, we already know that the
690** ORDER BY term is not an integer index into the result set. That
691** case is handled by the calling routine.
692**
693** Attempt to match pE against result set columns in the left-most
694** SELECT statement. Return the index i of the matching column,
695** as an indication to the caller that it should sort by the i-th column.
696** The left-most column is 1. In other words, the value returned is the
697** same integer value that would be used in the SQL statement to indicate
698** the column.
699**
700** If there is no match, return 0. Return -1 if an error occurs.
701*/
702static int resolveOrderByTermToExprList(
703 Parse *pParse, /* Parsing context for error messages */
704 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
705 Expr *pE /* The specific ORDER BY term */
706){
707 int i; /* Loop counter */
708 ExprList *pEList; /* The columns of the result set */
709 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000710 sqlite3 *db; /* Database connection */
711 int rc; /* Return code from subprocedures */
712 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000713
714 assert( sqlite3ExprIsInteger(pE, &i)==0 );
715 pEList = pSelect->pEList;
716
717 /* Resolve all names in the ORDER BY term expression
718 */
719 memset(&nc, 0, sizeof(nc));
720 nc.pParse = pParse;
721 nc.pSrcList = pSelect->pSrc;
722 nc.pEList = pEList;
drha51009b2012-05-21 19:11:25 +0000723 nc.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000724 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000725 db = pParse->db;
726 savedSuppErr = db->suppressErr;
727 db->suppressErr = 1;
728 rc = sqlite3ResolveExprNames(&nc, pE);
729 db->suppressErr = savedSuppErr;
730 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000731
732 /* Try to match the ORDER BY expression against an expression
733 ** in the result set. Return an 1-based index of the matching
734 ** result-set entry.
735 */
736 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000737 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000738 return i+1;
739 }
740 }
741
742 /* If no match, return 0. */
743 return 0;
744}
745
746/*
747** Generate an ORDER BY or GROUP BY term out-of-range error.
748*/
749static void resolveOutOfRangeError(
750 Parse *pParse, /* The error context into which to write the error */
751 const char *zType, /* "ORDER" or "GROUP" */
752 int i, /* The index (1-based) of the term out of range */
753 int mx /* Largest permissible value of i */
754){
755 sqlite3ErrorMsg(pParse,
756 "%r %s BY term out of range - should be "
757 "between 1 and %d", i, zType, mx);
758}
759
760/*
761** Analyze the ORDER BY clause in a compound SELECT statement. Modify
762** each term of the ORDER BY clause is a constant integer between 1
763** and N where N is the number of columns in the compound SELECT.
764**
765** ORDER BY terms that are already an integer between 1 and N are
766** unmodified. ORDER BY terms that are integers outside the range of
767** 1 through N generate an error. ORDER BY terms that are expressions
768** are matched against result set expressions of compound SELECT
769** beginning with the left-most SELECT and working toward the right.
770** At the first match, the ORDER BY expression is transformed into
771** the integer column number.
772**
773** Return the number of errors seen.
774*/
775static int resolveCompoundOrderBy(
776 Parse *pParse, /* Parsing context. Leave error messages here */
777 Select *pSelect /* The SELECT statement containing the ORDER BY */
778){
779 int i;
780 ExprList *pOrderBy;
781 ExprList *pEList;
782 sqlite3 *db;
783 int moreToDo = 1;
784
785 pOrderBy = pSelect->pOrderBy;
786 if( pOrderBy==0 ) return 0;
787 db = pParse->db;
788#if SQLITE_MAX_COLUMN
789 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
790 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
791 return 1;
792 }
793#endif
794 for(i=0; i<pOrderBy->nExpr; i++){
795 pOrderBy->a[i].done = 0;
796 }
797 pSelect->pNext = 0;
798 while( pSelect->pPrior ){
799 pSelect->pPrior->pNext = pSelect;
800 pSelect = pSelect->pPrior;
801 }
802 while( pSelect && moreToDo ){
803 struct ExprList_item *pItem;
804 moreToDo = 0;
805 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000806 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000807 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
808 int iCol = -1;
809 Expr *pE, *pDup;
810 if( pItem->done ) continue;
811 pE = pItem->pExpr;
812 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000813 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000814 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
815 return 1;
816 }
817 }else{
818 iCol = resolveAsName(pParse, pEList, pE);
819 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000820 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000821 if( !db->mallocFailed ){
822 assert(pDup);
823 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
824 }
825 sqlite3ExprDelete(db, pDup);
826 }
drh7d10d5a2008-08-20 16:35:10 +0000827 }
828 if( iCol>0 ){
drh7d10d5a2008-08-20 16:35:10 +0000829 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000830 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000831 if( pE==0 ) return 1;
drhae80dde2012-12-06 21:16:43 +0000832 pE->flags |= EP_IntValue;
drh33e619f2009-05-28 01:00:55 +0000833 pE->u.iValue = iCol;
drh4b3ac732011-12-10 23:18:32 +0000834 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000835 pItem->done = 1;
836 }else{
837 moreToDo = 1;
838 }
839 }
840 pSelect = pSelect->pNext;
841 }
842 for(i=0; i<pOrderBy->nExpr; i++){
843 if( pOrderBy->a[i].done==0 ){
844 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
845 "column in the result set", i+1);
846 return 1;
847 }
848 }
849 return 0;
850}
851
852/*
853** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
854** the SELECT statement pSelect. If any term is reference to a
855** result set expression (as determined by the ExprList.a.iCol field)
856** then convert that term into a copy of the corresponding result set
857** column.
858**
859** If any errors are detected, add an error message to pParse and
860** return non-zero. Return zero if no errors are seen.
861*/
862int sqlite3ResolveOrderGroupBy(
863 Parse *pParse, /* Parsing context. Leave error messages here */
864 Select *pSelect, /* The SELECT statement containing the clause */
865 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
866 const char *zType /* "ORDER" or "GROUP" */
867){
868 int i;
869 sqlite3 *db = pParse->db;
870 ExprList *pEList;
871 struct ExprList_item *pItem;
872
873 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
874#if SQLITE_MAX_COLUMN
875 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
876 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
877 return 1;
878 }
879#endif
880 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000881 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000882 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +0000883 if( pItem->iOrderByCol ){
884 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000885 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
886 return 1;
887 }
drhed551b92012-08-23 19:46:11 +0000888 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
drh7d10d5a2008-08-20 16:35:10 +0000889 }
890 }
891 return 0;
892}
893
894/*
895** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
896** The Name context of the SELECT statement is pNC. zType is either
897** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
898**
899** This routine resolves each term of the clause into an expression.
900** If the order-by term is an integer I between 1 and N (where N is the
901** number of columns in the result set of the SELECT) then the expression
902** in the resolution is a copy of the I-th result-set expression. If
903** the order-by term is an identify that corresponds to the AS-name of
904** a result-set expression, then the term resolves to a copy of the
905** result-set expression. Otherwise, the expression is resolved in
906** the usual way - using sqlite3ResolveExprNames().
907**
908** This routine returns the number of errors. If errors occur, then
909** an appropriate error message might be left in pParse. (OOM errors
910** excepted.)
911*/
912static int resolveOrderGroupBy(
913 NameContext *pNC, /* The name context of the SELECT statement */
914 Select *pSelect, /* The SELECT statement holding pOrderBy */
915 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
916 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
917){
drh70331cd2012-04-27 01:09:06 +0000918 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000919 int iCol; /* Column number */
920 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
921 Parse *pParse; /* Parsing context */
922 int nResult; /* Number of terms in the result set */
923
924 if( pOrderBy==0 ) return 0;
925 nResult = pSelect->pEList->nExpr;
926 pParse = pNC->pParse;
927 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
928 Expr *pE = pItem->pExpr;
929 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000930 if( iCol>0 ){
931 /* If an AS-name match is found, mark this ORDER BY column as being
932 ** a copy of the iCol-th result-set column. The subsequent call to
933 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
934 ** copy of the iCol-th result-set expression. */
drh4b3ac732011-12-10 23:18:32 +0000935 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000936 continue;
937 }
938 if( sqlite3ExprIsInteger(pE, &iCol) ){
939 /* The ORDER BY term is an integer constant. Again, set the column
940 ** number so that sqlite3ResolveOrderGroupBy() will convert the
941 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000942 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000943 resolveOutOfRangeError(pParse, zType, i+1, nResult);
944 return 1;
945 }
drh4b3ac732011-12-10 23:18:32 +0000946 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000947 continue;
948 }
949
950 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +0000951 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +0000952 if( sqlite3ResolveExprNames(pNC, pE) ){
953 return 1;
954 }
drh70331cd2012-04-27 01:09:06 +0000955 for(j=0; j<pSelect->pEList->nExpr; j++){
956 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
957 pItem->iOrderByCol = j+1;
958 }
959 }
drh7d10d5a2008-08-20 16:35:10 +0000960 }
961 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
962}
963
964/*
965** Resolve names in the SELECT statement p and all of its descendents.
966*/
967static int resolveSelectStep(Walker *pWalker, Select *p){
968 NameContext *pOuterNC; /* Context that contains this SELECT */
969 NameContext sNC; /* Name context of this SELECT */
970 int isCompound; /* True if p is a compound select */
971 int nCompound; /* Number of compound terms processed so far */
972 Parse *pParse; /* Parsing context */
973 ExprList *pEList; /* Result set expression list */
974 int i; /* Loop counter */
975 ExprList *pGroupBy; /* The GROUP BY clause */
976 Select *pLeftmost; /* Left-most of SELECT of a compound */
977 sqlite3 *db; /* Database connection */
978
979
drh0a846f92008-08-25 17:23:29 +0000980 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000981 if( p->selFlags & SF_Resolved ){
982 return WRC_Prune;
983 }
984 pOuterNC = pWalker->u.pNC;
985 pParse = pWalker->pParse;
986 db = pParse->db;
987
988 /* Normally sqlite3SelectExpand() will be called first and will have
989 ** already expanded this SELECT. However, if this is a subquery within
990 ** an expression, sqlite3ResolveExprNames() will be called without a
991 ** prior call to sqlite3SelectExpand(). When that happens, let
992 ** sqlite3SelectPrep() do all of the processing for this SELECT.
993 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
994 ** this routine in the correct order.
995 */
996 if( (p->selFlags & SF_Expanded)==0 ){
997 sqlite3SelectPrep(pParse, p, pOuterNC);
998 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
999 }
1000
1001 isCompound = p->pPrior!=0;
1002 nCompound = 0;
1003 pLeftmost = p;
1004 while( p ){
1005 assert( (p->selFlags & SF_Expanded)!=0 );
1006 assert( (p->selFlags & SF_Resolved)==0 );
1007 p->selFlags |= SF_Resolved;
1008
1009 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1010 ** are not allowed to refer to any names, so pass an empty NameContext.
1011 */
1012 memset(&sNC, 0, sizeof(sNC));
1013 sNC.pParse = pParse;
1014 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1015 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1016 return WRC_Abort;
1017 }
1018
1019 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1020 ** resolve the result-set expression list.
1021 */
drha51009b2012-05-21 19:11:25 +00001022 sNC.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001023 sNC.pSrcList = p->pSrc;
1024 sNC.pNext = pOuterNC;
1025
1026 /* Resolve names in the result set. */
1027 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +00001028 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001029 for(i=0; i<pEList->nExpr; i++){
1030 Expr *pX = pEList->a[i].pExpr;
1031 if( sqlite3ResolveExprNames(&sNC, pX) ){
1032 return WRC_Abort;
1033 }
1034 }
1035
1036 /* Recursively resolve names in all subqueries
1037 */
1038 for(i=0; i<p->pSrc->nSrc; i++){
1039 struct SrcList_item *pItem = &p->pSrc->a[i];
1040 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001041 NameContext *pNC; /* Used to iterate name contexts */
1042 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001043 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001044
1045 /* Count the total number of references to pOuterNC and all of its
1046 ** parent contexts. After resolving references to expressions in
1047 ** pItem->pSelect, check if this value has changed. If so, then
1048 ** SELECT statement pItem->pSelect must be correlated. Set the
1049 ** pItem->isCorrelated flag if this is the case. */
1050 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1051
drh7d10d5a2008-08-20 16:35:10 +00001052 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001053 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001054 pParse->zAuthContext = zSavedContext;
1055 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001056
1057 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1058 assert( pItem->isCorrelated==0 && nRef<=0 );
1059 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001060 }
1061 }
1062
1063 /* If there are no aggregate functions in the result-set, and no GROUP BY
1064 ** expression, do not allow aggregates in any of the other expressions.
1065 */
1066 assert( (p->selFlags & SF_Aggregate)==0 );
1067 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:25 +00001068 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +00001069 p->selFlags |= SF_Aggregate;
1070 }else{
drha51009b2012-05-21 19:11:25 +00001071 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001072 }
1073
1074 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1075 */
1076 if( p->pHaving && !pGroupBy ){
1077 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1078 return WRC_Abort;
1079 }
1080
1081 /* Add the expression list to the name-context before parsing the
1082 ** other expressions in the SELECT statement. This is so that
1083 ** expressions in the WHERE clause (etc.) can refer to expressions by
1084 ** aliases in the result set.
1085 **
1086 ** Minor point: If this is the case, then the expression will be
1087 ** re-evaluated for each reference to it.
1088 */
1089 sNC.pEList = p->pEList;
1090 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1091 sqlite3ResolveExprNames(&sNC, p->pHaving)
1092 ){
1093 return WRC_Abort;
1094 }
1095
1096 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1097 ** outer queries
1098 */
1099 sNC.pNext = 0;
drha51009b2012-05-21 19:11:25 +00001100 sNC.ncFlags |= NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001101
1102 /* Process the ORDER BY clause for singleton SELECT statements.
1103 ** The ORDER BY clause for compounds SELECT statements is handled
1104 ** below, after all of the result-sets for all of the elements of
1105 ** the compound have been resolved.
1106 */
1107 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1108 return WRC_Abort;
1109 }
1110 if( db->mallocFailed ){
1111 return WRC_Abort;
1112 }
1113
1114 /* Resolve the GROUP BY clause. At the same time, make sure
1115 ** the GROUP BY clause does not contain aggregate functions.
1116 */
1117 if( pGroupBy ){
1118 struct ExprList_item *pItem;
1119
1120 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1121 return WRC_Abort;
1122 }
1123 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1124 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1125 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1126 "the GROUP BY clause");
1127 return WRC_Abort;
1128 }
1129 }
1130 }
1131
1132 /* Advance to the next term of the compound
1133 */
1134 p = p->pPrior;
1135 nCompound++;
1136 }
1137
1138 /* Resolve the ORDER BY on a compound SELECT after all terms of
1139 ** the compound have been resolved.
1140 */
1141 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1142 return WRC_Abort;
1143 }
1144
1145 return WRC_Prune;
1146}
1147
1148/*
1149** This routine walks an expression tree and resolves references to
1150** table columns and result-set columns. At the same time, do error
1151** checking on function usage and set a flag if any aggregate functions
1152** are seen.
1153**
1154** To resolve table columns references we look for nodes (or subtrees) of the
1155** form X.Y.Z or Y.Z or just Z where
1156**
1157** X: The name of a database. Ex: "main" or "temp" or
1158** the symbolic name assigned to an ATTACH-ed database.
1159**
1160** Y: The name of a table in a FROM clause. Or in a trigger
1161** one of the special names "old" or "new".
1162**
1163** Z: The name of a column in table Y.
1164**
1165** The node at the root of the subtree is modified as follows:
1166**
1167** Expr.op Changed to TK_COLUMN
1168** Expr.pTab Points to the Table object for X.Y
1169** Expr.iColumn The column index in X.Y. -1 for the rowid.
1170** Expr.iTable The VDBE cursor number for X.Y
1171**
1172**
1173** To resolve result-set references, look for expression nodes of the
1174** form Z (with no X and Y prefix) where the Z matches the right-hand
1175** size of an AS clause in the result-set of a SELECT. The Z expression
1176** is replaced by a copy of the left-hand side of the result-set expression.
1177** Table-name and function resolution occurs on the substituted expression
1178** tree. For example, in:
1179**
1180** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1181**
1182** The "x" term of the order by is replaced by "a+b" to render:
1183**
1184** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1185**
1186** Function calls are checked to make sure that the function is
1187** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:25 +00001188** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:10 +00001189** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1190** If an expression contains aggregate functions then the EP_Agg
1191** property on the expression is set.
1192**
1193** An error message is left in pParse if anything is amiss. The number
1194** if errors is returned.
1195*/
1196int sqlite3ResolveExprNames(
1197 NameContext *pNC, /* Namespace to resolve expressions in. */
1198 Expr *pExpr /* The expression to be analyzed. */
1199){
drha51009b2012-05-21 19:11:25 +00001200 u8 savedHasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001201 Walker w;
1202
1203 if( pExpr==0 ) return 0;
1204#if SQLITE_MAX_EXPR_DEPTH>0
1205 {
1206 Parse *pParse = pNC->pParse;
1207 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1208 return 1;
1209 }
1210 pParse->nHeight += pExpr->nHeight;
1211 }
1212#endif
drha51009b2012-05-21 19:11:25 +00001213 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1214 pNC->ncFlags &= ~NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001215 w.xExprCallback = resolveExprStep;
1216 w.xSelectCallback = resolveSelectStep;
1217 w.pParse = pNC->pParse;
1218 w.u.pNC = pNC;
1219 sqlite3WalkExpr(&w, pExpr);
1220#if SQLITE_MAX_EXPR_DEPTH>0
1221 pNC->pParse->nHeight -= pExpr->nHeight;
1222#endif
drhfd773cf2009-05-29 14:39:07 +00001223 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001224 ExprSetProperty(pExpr, EP_Error);
1225 }
drha51009b2012-05-21 19:11:25 +00001226 if( pNC->ncFlags & NC_HasAgg ){
drh7d10d5a2008-08-20 16:35:10 +00001227 ExprSetProperty(pExpr, EP_Agg);
1228 }else if( savedHasAgg ){
drha51009b2012-05-21 19:11:25 +00001229 pNC->ncFlags |= NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001230 }
1231 return ExprHasProperty(pExpr, EP_Error);
1232}
drh7d10d5a2008-08-20 16:35:10 +00001233
1234
1235/*
1236** Resolve all names in all expressions of a SELECT and in all
1237** decendents of the SELECT, including compounds off of p->pPrior,
1238** subqueries in expressions, and subqueries used as FROM clause
1239** terms.
1240**
1241** See sqlite3ResolveExprNames() for a description of the kinds of
1242** transformations that occur.
1243**
1244** All SELECT statements should have been expanded using
1245** sqlite3SelectExpand() prior to invoking this routine.
1246*/
1247void sqlite3ResolveSelectNames(
1248 Parse *pParse, /* The parser context */
1249 Select *p, /* The SELECT statement being coded. */
1250 NameContext *pOuterNC /* Name context for parent SELECT statement */
1251){
1252 Walker w;
1253
drh0a846f92008-08-25 17:23:29 +00001254 assert( p!=0 );
1255 w.xExprCallback = resolveExprStep;
1256 w.xSelectCallback = resolveSelectStep;
1257 w.pParse = pParse;
1258 w.u.pNC = pOuterNC;
1259 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001260}