blob: 4b9d8fa1450535ffd82069d6a8c6bc3e004bbba9 [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**
drh0a8a4062012-12-07 18:38:16 +000071** If the reference is followed by a COLLATE operator, then make sure
72** the COLLATE operator is preserved. For example:
73**
74** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
75**
76** Should be transformed into:
77**
78** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
79**
drhed551b92012-08-23 19:46:11 +000080** The nSubquery parameter specifies how many levels of subquery the
81** alias is removed from the original expression. The usually value is
82** zero but it might be more if the alias is contained within a subquery
83** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
84** structures must be increased by the nSubquery amount.
drh8b213892008-08-29 02:14:02 +000085*/
86static void resolveAlias(
87 Parse *pParse, /* Parsing context */
88 ExprList *pEList, /* A result set */
89 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
90 Expr *pExpr, /* Transform this into an alias to the result set */
drhed551b92012-08-23 19:46:11 +000091 const char *zType, /* "GROUP" or "ORDER" or "" */
92 int nSubquery /* Number of subqueries that the label is moving */
drh8b213892008-08-29 02:14:02 +000093){
94 Expr *pOrig; /* The iCol-th column of the result set */
95 Expr *pDup; /* Copy of pOrig */
96 sqlite3 *db; /* The database connection */
97
98 assert( iCol>=0 && iCol<pEList->nExpr );
99 pOrig = pEList->a[iCol].pExpr;
100 assert( pOrig!=0 );
101 assert( pOrig->flags & EP_Resolved );
102 db = pParse->db;
drh0a8a4062012-12-07 18:38:16 +0000103 pDup = sqlite3ExprDup(db, pOrig, 0);
104 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +0000105 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
drhed551b92012-08-23 19:46:11 +0000106 incrAggFunctionDepth(pDup, nSubquery);
drh8b213892008-08-29 02:14:02 +0000107 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
108 if( pDup==0 ) return;
109 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +0000110 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +0000111 }
112 pDup->iTable = pEList->a[iCol].iAlias;
113 }
drh0a8a4062012-12-07 18:38:16 +0000114#if 1 /* FIXME */
115 if( pExpr->flags & EP_Collate ){
116 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
117 if( pColl ){
118 pDup = sqlite3ExprAddCollateString(pParse, pDup, pColl->zName);
119 }
120 pDup->flags |= EP_Collate;
121 }
122#else
123 /* Should be this: */
124 if( pExpr->op==TK_COLLATE ){
125 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
126 }
127#endif
danf6963f92009-11-23 14:39:14 +0000128
129 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
130 ** prevents ExprDelete() from deleting the Expr structure itself,
131 ** allowing it to be repopulated by the memcpy() on the following line.
drhbd13d342012-12-07 21:02:47 +0000132 ** The pExpr->u.zToken might point into memory that will be freed by the
133 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
134 ** make a copy of the token before doing the sqlite3DbFree().
danf6963f92009-11-23 14:39:14 +0000135 */
136 ExprSetProperty(pExpr, EP_Static);
137 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +0000138 memcpy(pExpr, pDup, sizeof(*pExpr));
drh0a8a4062012-12-07 18:38:16 +0000139 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
140 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
141 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
142 pExpr->flags2 |= EP2_MallocedToken;
143 }
drh8b213892008-08-29 02:14:02 +0000144 sqlite3DbFree(db, pDup);
145}
146
drhe802c5d2011-10-18 18:10:40 +0000147
148/*
149** Return TRUE if the name zCol occurs anywhere in the USING clause.
150**
151** Return FALSE if the USING clause is NULL or if it does not contain
152** zCol.
153*/
154static int nameInUsingClause(IdList *pUsing, const char *zCol){
155 if( pUsing ){
156 int k;
157 for(k=0; k<pUsing->nId; k++){
158 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
159 }
160 }
161 return 0;
162}
163
164
drh8b213892008-08-29 02:14:02 +0000165/*
drh7d10d5a2008-08-20 16:35:10 +0000166** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
167** that name in the set of source tables in pSrcList and make the pExpr
168** expression node refer back to that source column. The following changes
169** are made to pExpr:
170**
171** pExpr->iDb Set the index in db->aDb[] of the database X
172** (even if X is implied).
173** pExpr->iTable Set to the cursor number for the table obtained
174** from pSrcList.
175** pExpr->pTab Points to the Table structure of X.Y (even if
176** X and/or Y are implied.)
177** pExpr->iColumn Set to the column number within the table.
178** pExpr->op Set to TK_COLUMN.
179** pExpr->pLeft Any expression this points to is deleted
180** pExpr->pRight Any expression this points to is deleted.
181**
drhb7916a72009-05-27 10:31:29 +0000182** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000183** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000184** can be used. The zTable variable is the name of the table (the "Y"). This
185** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000186** means that the form of the name is Z and that columns from any table
187** can be used.
188**
189** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000190** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000191*/
192static int lookupName(
193 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000194 const char *zDb, /* Name of the database containing table, or NULL */
195 const char *zTab, /* Name of table containing column, or NULL */
196 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000197 NameContext *pNC, /* The name context used to resolve the name */
198 Expr *pExpr /* Make this EXPR node point to the selected column */
199){
drhed551b92012-08-23 19:46:11 +0000200 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000201 int cnt = 0; /* Number of matching column names */
202 int cntTab = 0; /* Number of matching table names */
drhed551b92012-08-23 19:46:11 +0000203 int nSubquery = 0; /* How many levels of subquery */
drh7d10d5a2008-08-20 16:35:10 +0000204 sqlite3 *db = pParse->db; /* The database connection */
205 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
206 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
207 NameContext *pTopNC = pNC; /* First namecontext in the list */
208 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000209 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000210
drhb7916a72009-05-27 10:31:29 +0000211 assert( pNC ); /* the name context cannot be NULL. */
212 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh5a05be12012-10-09 18:51:44 +0000213 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000214
215 /* Initialize the node to no-match */
216 pExpr->iTable = -1;
217 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000218 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000219
220 /* Start at the inner-most context and move outward until a match is found */
221 while( pNC && cnt==0 ){
222 ExprList *pEList;
223 SrcList *pSrcList = pNC->pSrcList;
224
225 if( pSrcList ){
226 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
227 Table *pTab;
228 int iDb;
229 Column *pCol;
230
231 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000232 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000233 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
234 assert( pTab->nCol>0 );
235 if( zTab ){
236 if( pItem->zAlias ){
237 char *zTabName = pItem->zAlias;
238 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
239 }else{
240 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000241 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
242 continue;
243 }
drh7d10d5a2008-08-20 16:35:10 +0000244 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
245 continue;
246 }
247 }
248 }
249 if( 0==(cntTab++) ){
250 pExpr->iTable = pItem->iCursor;
251 pExpr->pTab = pTab;
252 pSchema = pTab->pSchema;
253 pMatch = pItem;
254 }
255 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
256 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
drhe802c5d2011-10-18 18:10:40 +0000257 /* If there has been exactly one prior match and this match
258 ** is for the right-hand table of a NATURAL JOIN or is in a
259 ** USING clause, then skip this match.
260 */
261 if( cnt==1 ){
262 if( pItem->jointype & JT_NATURAL ) continue;
263 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
264 }
drh7d10d5a2008-08-20 16:35:10 +0000265 cnt++;
266 pExpr->iTable = pItem->iCursor;
267 pExpr->pTab = pTab;
268 pMatch = pItem;
269 pSchema = pTab->pSchema;
270 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000271 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000272 break;
273 }
274 }
275 }
276 }
277
278#ifndef SQLITE_OMIT_TRIGGER
279 /* If we have not already resolved the name, then maybe
280 ** it is a new.* or old.* trigger argument reference
281 */
dan165921a2009-08-28 18:53:45 +0000282 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000283 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000284 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000285 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
286 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000287 pExpr->iTable = 1;
288 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000289 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000290 pExpr->iTable = 0;
291 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000292 }
293
294 if( pTab ){
295 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000296 pSchema = pTab->pSchema;
297 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000298 for(iCol=0; iCol<pTab->nCol; iCol++){
299 Column *pCol = &pTab->aCol[iCol];
300 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
301 if( iCol==pTab->iPKey ){
302 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000303 }
drh25e978d2009-12-29 23:39:04 +0000304 break;
drh7d10d5a2008-08-20 16:35:10 +0000305 }
306 }
drh25e978d2009-12-29 23:39:04 +0000307 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000308 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000309 }
dan2bd93512009-08-31 08:22:46 +0000310 if( iCol<pTab->nCol ){
311 cnt++;
312 if( iCol<0 ){
313 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000314 }else if( pExpr->iTable==0 ){
315 testcase( iCol==31 );
316 testcase( iCol==32 );
317 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000318 }else{
319 testcase( iCol==31 );
320 testcase( iCol==32 );
321 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000322 }
shanecea72b22009-09-07 04:38:36 +0000323 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000324 pExpr->pTab = pTab;
325 isTrigger = 1;
326 }
drh7d10d5a2008-08-20 16:35:10 +0000327 }
328 }
329#endif /* !defined(SQLITE_OMIT_TRIGGER) */
330
331 /*
332 ** Perhaps the name is a reference to the ROWID
333 */
334 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
335 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000336 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000337 pExpr->affinity = SQLITE_AFF_INTEGER;
338 }
339
340 /*
341 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
342 ** might refer to an result-set alias. This happens, for example, when
343 ** we are resolving names in the WHERE clause of the following command:
344 **
345 ** SELECT a+b AS x FROM table WHERE x<10;
346 **
347 ** In cases like this, replace pExpr with a copy of the expression that
348 ** forms the result set entry ("a+b" in the example) and return immediately.
349 ** Note that the expression in the result set should have already been
350 ** resolved by the time the WHERE clause is resolved.
351 */
352 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
353 for(j=0; j<pEList->nExpr; j++){
354 char *zAs = pEList->a[j].zName;
355 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000356 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000357 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000358 assert( pExpr->x.pList==0 );
359 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000360 pOrig = pEList->a[j].pExpr;
drha51009b2012-05-21 19:11:25 +0000361 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10 +0000362 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000363 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000364 }
drhed551b92012-08-23 19:46:11 +0000365 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
drh7d10d5a2008-08-20 16:35:10 +0000366 cnt = 1;
367 pMatch = 0;
368 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000369 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000370 }
371 }
372 }
373
374 /* Advance to the next name context. The loop will exit when either
375 ** we have a match (cnt>0) or when we run out of name contexts.
376 */
377 if( cnt==0 ){
378 pNC = pNC->pNext;
drhed551b92012-08-23 19:46:11 +0000379 nSubquery++;
drh7d10d5a2008-08-20 16:35:10 +0000380 }
381 }
382
383 /*
384 ** If X and Y are NULL (in other words if only the column name Z is
385 ** supplied) and the value of Z is enclosed in double-quotes, then
386 ** Z is a string literal if it doesn't match any column names. In that
387 ** case, we need to return right away and not make any changes to
388 ** pExpr.
389 **
390 ** Because no reference was made to outer contexts, the pNC->nRef
391 ** fields are not changed in any context.
392 */
drh24fb6272009-05-01 21:13:36 +0000393 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000394 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000395 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000396 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000397 }
398
399 /*
400 ** cnt==0 means there was not match. cnt>1 means there were two or
401 ** more matches. Either way, we have an error.
402 */
403 if( cnt!=1 ){
404 const char *zErr;
405 zErr = cnt==0 ? "no such column" : "ambiguous column name";
406 if( zDb ){
407 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
408 }else if( zTab ){
409 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
410 }else{
411 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
412 }
dan1db95102010-06-28 10:15:19 +0000413 pParse->checkSchema = 1;
drh7d10d5a2008-08-20 16:35:10 +0000414 pTopNC->nErr++;
415 }
416
417 /* If a column from a table in pSrcList is referenced, then record
418 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
419 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
420 ** column number is greater than the number of bits in the bitmask
421 ** then set the high-order bit of the bitmask.
422 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000423 if( pExpr->iColumn>=0 && pMatch!=0 ){
424 int n = pExpr->iColumn;
425 testcase( n==BMS-1 );
426 if( n>=BMS ){
427 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000428 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000429 assert( pMatch->iCursor==pExpr->iTable );
430 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000431 }
432
drh7d10d5a2008-08-20 16:35:10 +0000433 /* Clean up and return
434 */
drh7d10d5a2008-08-20 16:35:10 +0000435 sqlite3ExprDelete(db, pExpr->pLeft);
436 pExpr->pLeft = 0;
437 sqlite3ExprDelete(db, pExpr->pRight);
438 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000439 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000440lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000441 if( cnt==1 ){
442 assert( pNC!=0 );
443 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
444 /* Increment the nRef value on all name contexts from TopNC up to
445 ** the point where the name matched. */
446 for(;;){
447 assert( pTopNC!=0 );
448 pTopNC->nRef++;
449 if( pTopNC==pNC ) break;
450 pTopNC = pTopNC->pNext;
451 }
drhf7828b52009-06-15 23:15:59 +0000452 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000453 } else {
drhf7828b52009-06-15 23:15:59 +0000454 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000455 }
456}
457
458/*
danf7b0b0a2009-10-19 15:52:32 +0000459** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34 +0000460** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32 +0000461*/
462Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
463 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
464 if( p ){
465 struct SrcList_item *pItem = &pSrc->a[iSrc];
466 p->pTab = pItem->pTab;
467 p->iTable = pItem->iCursor;
468 if( p->pTab->iPKey==iCol ){
469 p->iColumn = -1;
470 }else{
drh8677d302009-11-04 13:17:14 +0000471 p->iColumn = (ynVar)iCol;
drh7caba662010-04-08 15:01:44 +0000472 testcase( iCol==BMS );
473 testcase( iCol==BMS-1 );
danf7b0b0a2009-10-19 15:52:32 +0000474 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
475 }
476 ExprSetProperty(p, EP_Resolved);
477 }
478 return p;
479}
480
481/*
drh7d10d5a2008-08-20 16:35:10 +0000482** This routine is callback for sqlite3WalkExpr().
483**
484** Resolve symbolic names into TK_COLUMN operators for the current
485** node in the expression tree. Return 0 to continue the search down
486** the tree or 2 to abort the tree walk.
487**
488** This routine also does error checking and name resolution for
489** function names. The operator for aggregate functions is changed
490** to TK_AGG_FUNCTION.
491*/
492static int resolveExprStep(Walker *pWalker, Expr *pExpr){
493 NameContext *pNC;
494 Parse *pParse;
495
drh7d10d5a2008-08-20 16:35:10 +0000496 pNC = pWalker->u.pNC;
497 assert( pNC!=0 );
498 pParse = pNC->pParse;
499 assert( pParse==pWalker->pParse );
500
501 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
502 ExprSetProperty(pExpr, EP_Resolved);
503#ifndef NDEBUG
504 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
505 SrcList *pSrcList = pNC->pSrcList;
506 int i;
507 for(i=0; i<pNC->pSrcList->nSrc; i++){
508 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
509 }
510 }
511#endif
512 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000513
shane273f6192008-10-10 04:34:16 +0000514#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000515 /* The special operator TK_ROW means use the rowid for the first
516 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
517 ** clause processing on UPDATE and DELETE statements.
518 */
519 case TK_ROW: {
520 SrcList *pSrcList = pNC->pSrcList;
521 struct SrcList_item *pItem;
522 assert( pSrcList && pSrcList->nSrc==1 );
523 pItem = pSrcList->a;
524 pExpr->op = TK_COLUMN;
525 pExpr->pTab = pItem->pTab;
526 pExpr->iTable = pItem->iCursor;
527 pExpr->iColumn = -1;
528 pExpr->affinity = SQLITE_AFF_INTEGER;
529 break;
530 }
shane273f6192008-10-10 04:34:16 +0000531#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000532
drh7d10d5a2008-08-20 16:35:10 +0000533 /* A lone identifier is the name of a column.
534 */
535 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000536 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000537 }
538
539 /* A table name and column name: ID.ID
540 ** Or a database, table and column: ID.ID.ID
541 */
542 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000543 const char *zColumn;
544 const char *zTable;
545 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000546 Expr *pRight;
547
548 /* if( pSrcList==0 ) break; */
549 pRight = pExpr->pRight;
550 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000551 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000552 zTable = pExpr->pLeft->u.zToken;
553 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000554 }else{
555 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000556 zDb = pExpr->pLeft->u.zToken;
557 zTable = pRight->pLeft->u.zToken;
558 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000559 }
drhf7828b52009-06-15 23:15:59 +0000560 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000561 }
562
563 /* Resolve function names
564 */
565 case TK_CONST_FUNC:
566 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000567 ExprList *pList = pExpr->x.pList; /* The argument list */
568 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000569 int no_such_func = 0; /* True if no such function exists */
570 int wrong_num_args = 0; /* True if wrong number of arguments */
571 int is_agg = 0; /* True if is an aggregate function */
572 int auth; /* Authorization to use the function */
573 int nId; /* Number of characters in function name */
574 const char *zId; /* The function name. */
575 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000576 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000577
drh73c0fdc2009-06-15 18:32:36 +0000578 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000579 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000580 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000581 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000582 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
583 if( pDef==0 ){
drh89d5d6a2012-04-07 00:09:21 +0000584 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:10 +0000585 if( pDef==0 ){
586 no_such_func = 1;
587 }else{
588 wrong_num_args = 1;
589 }
590 }else{
591 is_agg = pDef->xFunc==0;
592 }
593#ifndef SQLITE_OMIT_AUTHORIZATION
594 if( pDef ){
595 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
596 if( auth!=SQLITE_OK ){
597 if( auth==SQLITE_DENY ){
598 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
599 pDef->zName);
600 pNC->nErr++;
601 }
602 pExpr->op = TK_NULL;
603 return WRC_Prune;
604 }
605 }
606#endif
drha51009b2012-05-21 19:11:25 +0000607 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000608 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
609 pNC->nErr++;
610 is_agg = 0;
611 }else if( no_such_func ){
612 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
613 pNC->nErr++;
614 }else if( wrong_num_args ){
615 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
616 nId, zId);
617 pNC->nErr++;
618 }
drha51009b2012-05-21 19:11:25 +0000619 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000620 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:10 +0000621 if( is_agg ){
622 NameContext *pNC2 = pNC;
623 pExpr->op = TK_AGG_FUNCTION;
624 pExpr->op2 = 0;
625 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
626 pExpr->op2++;
627 pNC2 = pNC2->pNext;
628 }
629 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
630 pNC->ncFlags |= NC_AllowAgg;
631 }
drh7d10d5a2008-08-20 16:35:10 +0000632 /* FIX ME: Compute pExpr->affinity based on the expected return
633 ** type of the function
634 */
635 return WRC_Prune;
636 }
637#ifndef SQLITE_OMIT_SUBQUERY
638 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000639 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000640#endif
641 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000642 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000643 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000644 int nRef = pNC->nRef;
645#ifndef SQLITE_OMIT_CHECK
drha51009b2012-05-21 19:11:25 +0000646 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000647 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
648 }
649#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000650 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000651 assert( pNC->nRef>=nRef );
652 if( nRef!=pNC->nRef ){
653 ExprSetProperty(pExpr, EP_VarSelect);
654 }
655 }
656 break;
657 }
658#ifndef SQLITE_OMIT_CHECK
659 case TK_VARIABLE: {
drha51009b2012-05-21 19:11:25 +0000660 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000661 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
662 }
663 break;
664 }
665#endif
666 }
667 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
668}
669
670/*
671** pEList is a list of expressions which are really the result set of the
672** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
673** This routine checks to see if pE is a simple identifier which corresponds
674** to the AS-name of one of the terms of the expression list. If it is,
675** this routine return an integer between 1 and N where N is the number of
676** elements in pEList, corresponding to the matching entry. If there is
677** no match, or if pE is not a simple identifier, then this routine
678** return 0.
679**
680** pEList has been resolved. pE has not.
681*/
682static int resolveAsName(
683 Parse *pParse, /* Parsing context for error messages */
684 ExprList *pEList, /* List of expressions to scan */
685 Expr *pE /* Expression we are trying to match */
686){
687 int i; /* Loop counter */
688
shanecf697392009-06-01 16:53:09 +0000689 UNUSED_PARAMETER(pParse);
690
drh73c0fdc2009-06-15 18:32:36 +0000691 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000692 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000693 for(i=0; i<pEList->nExpr; i++){
694 char *zAs = pEList->a[i].zName;
695 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000696 return i+1;
697 }
698 }
drh7d10d5a2008-08-20 16:35:10 +0000699 }
700 return 0;
701}
702
703/*
704** pE is a pointer to an expression which is a single term in the
705** ORDER BY of a compound SELECT. The expression has not been
706** name resolved.
707**
708** At the point this routine is called, we already know that the
709** ORDER BY term is not an integer index into the result set. That
710** case is handled by the calling routine.
711**
712** Attempt to match pE against result set columns in the left-most
713** SELECT statement. Return the index i of the matching column,
714** as an indication to the caller that it should sort by the i-th column.
715** The left-most column is 1. In other words, the value returned is the
716** same integer value that would be used in the SQL statement to indicate
717** the column.
718**
719** If there is no match, return 0. Return -1 if an error occurs.
720*/
721static int resolveOrderByTermToExprList(
722 Parse *pParse, /* Parsing context for error messages */
723 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
724 Expr *pE /* The specific ORDER BY term */
725){
726 int i; /* Loop counter */
727 ExprList *pEList; /* The columns of the result set */
728 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000729 sqlite3 *db; /* Database connection */
730 int rc; /* Return code from subprocedures */
731 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000732
733 assert( sqlite3ExprIsInteger(pE, &i)==0 );
734 pEList = pSelect->pEList;
735
736 /* Resolve all names in the ORDER BY term expression
737 */
738 memset(&nc, 0, sizeof(nc));
739 nc.pParse = pParse;
740 nc.pSrcList = pSelect->pSrc;
741 nc.pEList = pEList;
drha51009b2012-05-21 19:11:25 +0000742 nc.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000743 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000744 db = pParse->db;
745 savedSuppErr = db->suppressErr;
746 db->suppressErr = 1;
747 rc = sqlite3ResolveExprNames(&nc, pE);
748 db->suppressErr = savedSuppErr;
749 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000750
751 /* Try to match the ORDER BY expression against an expression
752 ** in the result set. Return an 1-based index of the matching
753 ** result-set entry.
754 */
755 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000756 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000757 return i+1;
758 }
759 }
760
761 /* If no match, return 0. */
762 return 0;
763}
764
765/*
766** Generate an ORDER BY or GROUP BY term out-of-range error.
767*/
768static void resolveOutOfRangeError(
769 Parse *pParse, /* The error context into which to write the error */
770 const char *zType, /* "ORDER" or "GROUP" */
771 int i, /* The index (1-based) of the term out of range */
772 int mx /* Largest permissible value of i */
773){
774 sqlite3ErrorMsg(pParse,
775 "%r %s BY term out of range - should be "
776 "between 1 and %d", i, zType, mx);
777}
778
779/*
780** Analyze the ORDER BY clause in a compound SELECT statement. Modify
781** each term of the ORDER BY clause is a constant integer between 1
782** and N where N is the number of columns in the compound SELECT.
783**
784** ORDER BY terms that are already an integer between 1 and N are
785** unmodified. ORDER BY terms that are integers outside the range of
786** 1 through N generate an error. ORDER BY terms that are expressions
787** are matched against result set expressions of compound SELECT
788** beginning with the left-most SELECT and working toward the right.
789** At the first match, the ORDER BY expression is transformed into
790** the integer column number.
791**
792** Return the number of errors seen.
793*/
794static int resolveCompoundOrderBy(
795 Parse *pParse, /* Parsing context. Leave error messages here */
796 Select *pSelect /* The SELECT statement containing the ORDER BY */
797){
798 int i;
799 ExprList *pOrderBy;
800 ExprList *pEList;
801 sqlite3 *db;
802 int moreToDo = 1;
803
804 pOrderBy = pSelect->pOrderBy;
805 if( pOrderBy==0 ) return 0;
806 db = pParse->db;
807#if SQLITE_MAX_COLUMN
808 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
809 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
810 return 1;
811 }
812#endif
813 for(i=0; i<pOrderBy->nExpr; i++){
814 pOrderBy->a[i].done = 0;
815 }
816 pSelect->pNext = 0;
817 while( pSelect->pPrior ){
818 pSelect->pPrior->pNext = pSelect;
819 pSelect = pSelect->pPrior;
820 }
821 while( pSelect && moreToDo ){
822 struct ExprList_item *pItem;
823 moreToDo = 0;
824 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000825 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000826 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
827 int iCol = -1;
828 Expr *pE, *pDup;
829 if( pItem->done ) continue;
drhbd13d342012-12-07 21:02:47 +0000830 pE = sqlite3ExprSkipCollate(pItem->pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000831 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000832 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000833 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
834 return 1;
835 }
836 }else{
837 iCol = resolveAsName(pParse, pEList, pE);
838 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000839 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000840 if( !db->mallocFailed ){
841 assert(pDup);
842 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
843 }
844 sqlite3ExprDelete(db, pDup);
845 }
drh7d10d5a2008-08-20 16:35:10 +0000846 }
847 if( iCol>0 ){
drhbd13d342012-12-07 21:02:47 +0000848 /* Convert the ORDER BY term into an integer column number iCol,
849 ** taking care to preserve the COLLATE clause if it exists */
850 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
851 if( pNew==0 ) return 1;
852 pNew->flags |= EP_IntValue;
853 pNew->u.iValue = iCol;
854 if( pItem->pExpr==pE ){
855 pItem->pExpr = pNew;
856 }else{
857 assert( pItem->pExpr->op==TK_COLLATE );
858 assert( pItem->pExpr->pLeft==pE );
859 pItem->pExpr->pLeft = pNew;
860 }
drh7d10d5a2008-08-20 16:35:10 +0000861 sqlite3ExprDelete(db, pE);
drh4b3ac732011-12-10 23:18:32 +0000862 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000863 pItem->done = 1;
864 }else{
865 moreToDo = 1;
866 }
867 }
868 pSelect = pSelect->pNext;
869 }
870 for(i=0; i<pOrderBy->nExpr; i++){
871 if( pOrderBy->a[i].done==0 ){
872 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
873 "column in the result set", i+1);
874 return 1;
875 }
876 }
877 return 0;
878}
879
880/*
881** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
882** the SELECT statement pSelect. If any term is reference to a
883** result set expression (as determined by the ExprList.a.iCol field)
884** then convert that term into a copy of the corresponding result set
885** column.
886**
887** If any errors are detected, add an error message to pParse and
888** return non-zero. Return zero if no errors are seen.
889*/
890int sqlite3ResolveOrderGroupBy(
891 Parse *pParse, /* Parsing context. Leave error messages here */
892 Select *pSelect, /* The SELECT statement containing the clause */
893 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
894 const char *zType /* "ORDER" or "GROUP" */
895){
896 int i;
897 sqlite3 *db = pParse->db;
898 ExprList *pEList;
899 struct ExprList_item *pItem;
900
901 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
902#if SQLITE_MAX_COLUMN
903 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
904 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
905 return 1;
906 }
907#endif
908 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000909 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000910 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +0000911 if( pItem->iOrderByCol ){
912 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000913 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
914 return 1;
915 }
drhed551b92012-08-23 19:46:11 +0000916 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
drh7d10d5a2008-08-20 16:35:10 +0000917 }
918 }
919 return 0;
920}
921
922/*
923** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
924** The Name context of the SELECT statement is pNC. zType is either
925** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
926**
927** This routine resolves each term of the clause into an expression.
928** If the order-by term is an integer I between 1 and N (where N is the
929** number of columns in the result set of the SELECT) then the expression
930** in the resolution is a copy of the I-th result-set expression. If
931** the order-by term is an identify that corresponds to the AS-name of
932** a result-set expression, then the term resolves to a copy of the
933** result-set expression. Otherwise, the expression is resolved in
934** the usual way - using sqlite3ResolveExprNames().
935**
936** This routine returns the number of errors. If errors occur, then
937** an appropriate error message might be left in pParse. (OOM errors
938** excepted.)
939*/
940static int resolveOrderGroupBy(
941 NameContext *pNC, /* The name context of the SELECT statement */
942 Select *pSelect, /* The SELECT statement holding pOrderBy */
943 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
944 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
945){
drh70331cd2012-04-27 01:09:06 +0000946 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000947 int iCol; /* Column number */
948 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
949 Parse *pParse; /* Parsing context */
950 int nResult; /* Number of terms in the result set */
951
952 if( pOrderBy==0 ) return 0;
953 nResult = pSelect->pEList->nExpr;
954 pParse = pNC->pParse;
955 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
956 Expr *pE = pItem->pExpr;
957 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000958 if( iCol>0 ){
959 /* If an AS-name match is found, mark this ORDER BY column as being
960 ** a copy of the iCol-th result-set column. The subsequent call to
961 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
962 ** copy of the iCol-th result-set expression. */
drh4b3ac732011-12-10 23:18:32 +0000963 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000964 continue;
965 }
drh0a8a4062012-12-07 18:38:16 +0000966 if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
drh7d10d5a2008-08-20 16:35:10 +0000967 /* The ORDER BY term is an integer constant. Again, set the column
968 ** number so that sqlite3ResolveOrderGroupBy() will convert the
969 ** order-by term to a copy of the result-set expression */
drh0a8a4062012-12-07 18:38:16 +0000970 if( (iCol & ~0xffff)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000971 resolveOutOfRangeError(pParse, zType, i+1, nResult);
972 return 1;
973 }
drh4b3ac732011-12-10 23:18:32 +0000974 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000975 continue;
976 }
977
978 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +0000979 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +0000980 if( sqlite3ResolveExprNames(pNC, pE) ){
981 return 1;
982 }
drh70331cd2012-04-27 01:09:06 +0000983 for(j=0; j<pSelect->pEList->nExpr; j++){
984 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
985 pItem->iOrderByCol = j+1;
986 }
987 }
drh7d10d5a2008-08-20 16:35:10 +0000988 }
989 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
990}
991
992/*
993** Resolve names in the SELECT statement p and all of its descendents.
994*/
995static int resolveSelectStep(Walker *pWalker, Select *p){
996 NameContext *pOuterNC; /* Context that contains this SELECT */
997 NameContext sNC; /* Name context of this SELECT */
998 int isCompound; /* True if p is a compound select */
999 int nCompound; /* Number of compound terms processed so far */
1000 Parse *pParse; /* Parsing context */
1001 ExprList *pEList; /* Result set expression list */
1002 int i; /* Loop counter */
1003 ExprList *pGroupBy; /* The GROUP BY clause */
1004 Select *pLeftmost; /* Left-most of SELECT of a compound */
1005 sqlite3 *db; /* Database connection */
1006
1007
drh0a846f92008-08-25 17:23:29 +00001008 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001009 if( p->selFlags & SF_Resolved ){
1010 return WRC_Prune;
1011 }
1012 pOuterNC = pWalker->u.pNC;
1013 pParse = pWalker->pParse;
1014 db = pParse->db;
1015
1016 /* Normally sqlite3SelectExpand() will be called first and will have
1017 ** already expanded this SELECT. However, if this is a subquery within
1018 ** an expression, sqlite3ResolveExprNames() will be called without a
1019 ** prior call to sqlite3SelectExpand(). When that happens, let
1020 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1021 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1022 ** this routine in the correct order.
1023 */
1024 if( (p->selFlags & SF_Expanded)==0 ){
1025 sqlite3SelectPrep(pParse, p, pOuterNC);
1026 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1027 }
1028
1029 isCompound = p->pPrior!=0;
1030 nCompound = 0;
1031 pLeftmost = p;
1032 while( p ){
1033 assert( (p->selFlags & SF_Expanded)!=0 );
1034 assert( (p->selFlags & SF_Resolved)==0 );
1035 p->selFlags |= SF_Resolved;
1036
1037 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1038 ** are not allowed to refer to any names, so pass an empty NameContext.
1039 */
1040 memset(&sNC, 0, sizeof(sNC));
1041 sNC.pParse = pParse;
1042 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1043 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1044 return WRC_Abort;
1045 }
1046
1047 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1048 ** resolve the result-set expression list.
1049 */
drha51009b2012-05-21 19:11:25 +00001050 sNC.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001051 sNC.pSrcList = p->pSrc;
1052 sNC.pNext = pOuterNC;
1053
1054 /* Resolve names in the result set. */
1055 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +00001056 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001057 for(i=0; i<pEList->nExpr; i++){
1058 Expr *pX = pEList->a[i].pExpr;
1059 if( sqlite3ResolveExprNames(&sNC, pX) ){
1060 return WRC_Abort;
1061 }
1062 }
1063
1064 /* Recursively resolve names in all subqueries
1065 */
1066 for(i=0; i<p->pSrc->nSrc; i++){
1067 struct SrcList_item *pItem = &p->pSrc->a[i];
1068 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001069 NameContext *pNC; /* Used to iterate name contexts */
1070 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001071 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001072
1073 /* Count the total number of references to pOuterNC and all of its
1074 ** parent contexts. After resolving references to expressions in
1075 ** pItem->pSelect, check if this value has changed. If so, then
1076 ** SELECT statement pItem->pSelect must be correlated. Set the
1077 ** pItem->isCorrelated flag if this is the case. */
1078 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1079
drh7d10d5a2008-08-20 16:35:10 +00001080 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001081 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001082 pParse->zAuthContext = zSavedContext;
1083 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001084
1085 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1086 assert( pItem->isCorrelated==0 && nRef<=0 );
1087 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001088 }
1089 }
1090
1091 /* If there are no aggregate functions in the result-set, and no GROUP BY
1092 ** expression, do not allow aggregates in any of the other expressions.
1093 */
1094 assert( (p->selFlags & SF_Aggregate)==0 );
1095 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:25 +00001096 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +00001097 p->selFlags |= SF_Aggregate;
1098 }else{
drha51009b2012-05-21 19:11:25 +00001099 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001100 }
1101
1102 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1103 */
1104 if( p->pHaving && !pGroupBy ){
1105 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1106 return WRC_Abort;
1107 }
1108
1109 /* Add the expression list to the name-context before parsing the
1110 ** other expressions in the SELECT statement. This is so that
1111 ** expressions in the WHERE clause (etc.) can refer to expressions by
1112 ** aliases in the result set.
1113 **
1114 ** Minor point: If this is the case, then the expression will be
1115 ** re-evaluated for each reference to it.
1116 */
1117 sNC.pEList = p->pEList;
1118 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1119 sqlite3ResolveExprNames(&sNC, p->pHaving)
1120 ){
1121 return WRC_Abort;
1122 }
1123
1124 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1125 ** outer queries
1126 */
1127 sNC.pNext = 0;
drha51009b2012-05-21 19:11:25 +00001128 sNC.ncFlags |= NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001129
1130 /* Process the ORDER BY clause for singleton SELECT statements.
1131 ** The ORDER BY clause for compounds SELECT statements is handled
1132 ** below, after all of the result-sets for all of the elements of
1133 ** the compound have been resolved.
1134 */
1135 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1136 return WRC_Abort;
1137 }
1138 if( db->mallocFailed ){
1139 return WRC_Abort;
1140 }
1141
1142 /* Resolve the GROUP BY clause. At the same time, make sure
1143 ** the GROUP BY clause does not contain aggregate functions.
1144 */
1145 if( pGroupBy ){
1146 struct ExprList_item *pItem;
1147
1148 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1149 return WRC_Abort;
1150 }
1151 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1152 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1153 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1154 "the GROUP BY clause");
1155 return WRC_Abort;
1156 }
1157 }
1158 }
1159
1160 /* Advance to the next term of the compound
1161 */
1162 p = p->pPrior;
1163 nCompound++;
1164 }
1165
1166 /* Resolve the ORDER BY on a compound SELECT after all terms of
1167 ** the compound have been resolved.
1168 */
1169 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1170 return WRC_Abort;
1171 }
1172
1173 return WRC_Prune;
1174}
1175
1176/*
1177** This routine walks an expression tree and resolves references to
1178** table columns and result-set columns. At the same time, do error
1179** checking on function usage and set a flag if any aggregate functions
1180** are seen.
1181**
1182** To resolve table columns references we look for nodes (or subtrees) of the
1183** form X.Y.Z or Y.Z or just Z where
1184**
1185** X: The name of a database. Ex: "main" or "temp" or
1186** the symbolic name assigned to an ATTACH-ed database.
1187**
1188** Y: The name of a table in a FROM clause. Or in a trigger
1189** one of the special names "old" or "new".
1190**
1191** Z: The name of a column in table Y.
1192**
1193** The node at the root of the subtree is modified as follows:
1194**
1195** Expr.op Changed to TK_COLUMN
1196** Expr.pTab Points to the Table object for X.Y
1197** Expr.iColumn The column index in X.Y. -1 for the rowid.
1198** Expr.iTable The VDBE cursor number for X.Y
1199**
1200**
1201** To resolve result-set references, look for expression nodes of the
1202** form Z (with no X and Y prefix) where the Z matches the right-hand
1203** size of an AS clause in the result-set of a SELECT. The Z expression
1204** is replaced by a copy of the left-hand side of the result-set expression.
1205** Table-name and function resolution occurs on the substituted expression
1206** tree. For example, in:
1207**
1208** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1209**
1210** The "x" term of the order by is replaced by "a+b" to render:
1211**
1212** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1213**
1214** Function calls are checked to make sure that the function is
1215** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:25 +00001216** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:10 +00001217** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1218** If an expression contains aggregate functions then the EP_Agg
1219** property on the expression is set.
1220**
1221** An error message is left in pParse if anything is amiss. The number
1222** if errors is returned.
1223*/
1224int sqlite3ResolveExprNames(
1225 NameContext *pNC, /* Namespace to resolve expressions in. */
1226 Expr *pExpr /* The expression to be analyzed. */
1227){
drha51009b2012-05-21 19:11:25 +00001228 u8 savedHasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001229 Walker w;
1230
1231 if( pExpr==0 ) return 0;
1232#if SQLITE_MAX_EXPR_DEPTH>0
1233 {
1234 Parse *pParse = pNC->pParse;
1235 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1236 return 1;
1237 }
1238 pParse->nHeight += pExpr->nHeight;
1239 }
1240#endif
drha51009b2012-05-21 19:11:25 +00001241 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1242 pNC->ncFlags &= ~NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001243 w.xExprCallback = resolveExprStep;
1244 w.xSelectCallback = resolveSelectStep;
1245 w.pParse = pNC->pParse;
1246 w.u.pNC = pNC;
1247 sqlite3WalkExpr(&w, pExpr);
1248#if SQLITE_MAX_EXPR_DEPTH>0
1249 pNC->pParse->nHeight -= pExpr->nHeight;
1250#endif
drhfd773cf2009-05-29 14:39:07 +00001251 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001252 ExprSetProperty(pExpr, EP_Error);
1253 }
drha51009b2012-05-21 19:11:25 +00001254 if( pNC->ncFlags & NC_HasAgg ){
drh7d10d5a2008-08-20 16:35:10 +00001255 ExprSetProperty(pExpr, EP_Agg);
1256 }else if( savedHasAgg ){
drha51009b2012-05-21 19:11:25 +00001257 pNC->ncFlags |= NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001258 }
1259 return ExprHasProperty(pExpr, EP_Error);
1260}
drh7d10d5a2008-08-20 16:35:10 +00001261
1262
1263/*
1264** Resolve all names in all expressions of a SELECT and in all
1265** decendents of the SELECT, including compounds off of p->pPrior,
1266** subqueries in expressions, and subqueries used as FROM clause
1267** terms.
1268**
1269** See sqlite3ResolveExprNames() for a description of the kinds of
1270** transformations that occur.
1271**
1272** All SELECT statements should have been expanded using
1273** sqlite3SelectExpand() prior to invoking this routine.
1274*/
1275void sqlite3ResolveSelectNames(
1276 Parse *pParse, /* The parser context */
1277 Select *p, /* The SELECT statement being coded. */
1278 NameContext *pOuterNC /* Name context for parent SELECT statement */
1279){
1280 Walker w;
1281
drh0a846f92008-08-25 17:23:29 +00001282 assert( p!=0 );
1283 w.xExprCallback = resolveExprStep;
1284 w.xSelectCallback = resolveSelectStep;
1285 w.pParse = pParse;
1286 w.u.pNC = pOuterNC;
1287 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001288}