blob: 6e5e2e7a9a1ed0763042c15eeb87bf066a1027cb [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.
132 */
133 ExprSetProperty(pExpr, EP_Static);
134 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +0000135 memcpy(pExpr, pDup, sizeof(*pExpr));
drh0a8a4062012-12-07 18:38:16 +0000136 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
137 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
138 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
139 pExpr->flags2 |= EP2_MallocedToken;
140 }
drh8b213892008-08-29 02:14:02 +0000141 sqlite3DbFree(db, pDup);
142}
143
drhe802c5d2011-10-18 18:10:40 +0000144
145/*
146** Return TRUE if the name zCol occurs anywhere in the USING clause.
147**
148** Return FALSE if the USING clause is NULL or if it does not contain
149** zCol.
150*/
151static int nameInUsingClause(IdList *pUsing, const char *zCol){
152 if( pUsing ){
153 int k;
154 for(k=0; k<pUsing->nId; k++){
155 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
156 }
157 }
158 return 0;
159}
160
161
drh8b213892008-08-29 02:14:02 +0000162/*
drh7d10d5a2008-08-20 16:35:10 +0000163** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
164** that name in the set of source tables in pSrcList and make the pExpr
165** expression node refer back to that source column. The following changes
166** are made to pExpr:
167**
168** pExpr->iDb Set the index in db->aDb[] of the database X
169** (even if X is implied).
170** pExpr->iTable Set to the cursor number for the table obtained
171** from pSrcList.
172** pExpr->pTab Points to the Table structure of X.Y (even if
173** X and/or Y are implied.)
174** pExpr->iColumn Set to the column number within the table.
175** pExpr->op Set to TK_COLUMN.
176** pExpr->pLeft Any expression this points to is deleted
177** pExpr->pRight Any expression this points to is deleted.
178**
drhb7916a72009-05-27 10:31:29 +0000179** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000180** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000181** can be used. The zTable variable is the name of the table (the "Y"). This
182** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000183** means that the form of the name is Z and that columns from any table
184** can be used.
185**
186** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000187** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000188*/
189static int lookupName(
190 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000191 const char *zDb, /* Name of the database containing table, or NULL */
192 const char *zTab, /* Name of table containing column, or NULL */
193 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000194 NameContext *pNC, /* The name context used to resolve the name */
195 Expr *pExpr /* Make this EXPR node point to the selected column */
196){
drhed551b92012-08-23 19:46:11 +0000197 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000198 int cnt = 0; /* Number of matching column names */
199 int cntTab = 0; /* Number of matching table names */
drhed551b92012-08-23 19:46:11 +0000200 int nSubquery = 0; /* How many levels of subquery */
drh7d10d5a2008-08-20 16:35:10 +0000201 sqlite3 *db = pParse->db; /* The database connection */
202 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
203 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
204 NameContext *pTopNC = pNC; /* First namecontext in the list */
205 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000206 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000207
drhb7916a72009-05-27 10:31:29 +0000208 assert( pNC ); /* the name context cannot be NULL. */
209 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh5a05be12012-10-09 18:51:44 +0000210 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000211
212 /* Initialize the node to no-match */
213 pExpr->iTable = -1;
214 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000215 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000216
217 /* Start at the inner-most context and move outward until a match is found */
218 while( pNC && cnt==0 ){
219 ExprList *pEList;
220 SrcList *pSrcList = pNC->pSrcList;
221
222 if( pSrcList ){
223 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
224 Table *pTab;
225 int iDb;
226 Column *pCol;
227
228 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000229 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000230 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
231 assert( pTab->nCol>0 );
232 if( zTab ){
233 if( pItem->zAlias ){
234 char *zTabName = pItem->zAlias;
235 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
236 }else{
237 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000238 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
239 continue;
240 }
drh7d10d5a2008-08-20 16:35:10 +0000241 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
242 continue;
243 }
244 }
245 }
246 if( 0==(cntTab++) ){
247 pExpr->iTable = pItem->iCursor;
248 pExpr->pTab = pTab;
249 pSchema = pTab->pSchema;
250 pMatch = pItem;
251 }
252 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
253 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
drhe802c5d2011-10-18 18:10:40 +0000254 /* If there has been exactly one prior match and this match
255 ** is for the right-hand table of a NATURAL JOIN or is in a
256 ** USING clause, then skip this match.
257 */
258 if( cnt==1 ){
259 if( pItem->jointype & JT_NATURAL ) continue;
260 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
261 }
drh7d10d5a2008-08-20 16:35:10 +0000262 cnt++;
263 pExpr->iTable = pItem->iCursor;
264 pExpr->pTab = pTab;
265 pMatch = pItem;
266 pSchema = pTab->pSchema;
267 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000268 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000269 break;
270 }
271 }
272 }
273 }
274
275#ifndef SQLITE_OMIT_TRIGGER
276 /* If we have not already resolved the name, then maybe
277 ** it is a new.* or old.* trigger argument reference
278 */
dan165921a2009-08-28 18:53:45 +0000279 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000280 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000281 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000282 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
283 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000284 pExpr->iTable = 1;
285 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000286 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000287 pExpr->iTable = 0;
288 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000289 }
290
291 if( pTab ){
292 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000293 pSchema = pTab->pSchema;
294 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000295 for(iCol=0; iCol<pTab->nCol; iCol++){
296 Column *pCol = &pTab->aCol[iCol];
297 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
298 if( iCol==pTab->iPKey ){
299 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000300 }
drh25e978d2009-12-29 23:39:04 +0000301 break;
drh7d10d5a2008-08-20 16:35:10 +0000302 }
303 }
drh25e978d2009-12-29 23:39:04 +0000304 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000305 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000306 }
dan2bd93512009-08-31 08:22:46 +0000307 if( iCol<pTab->nCol ){
308 cnt++;
309 if( iCol<0 ){
310 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000311 }else if( pExpr->iTable==0 ){
312 testcase( iCol==31 );
313 testcase( iCol==32 );
314 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000315 }else{
316 testcase( iCol==31 );
317 testcase( iCol==32 );
318 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000319 }
shanecea72b22009-09-07 04:38:36 +0000320 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000321 pExpr->pTab = pTab;
322 isTrigger = 1;
323 }
drh7d10d5a2008-08-20 16:35:10 +0000324 }
325 }
326#endif /* !defined(SQLITE_OMIT_TRIGGER) */
327
328 /*
329 ** Perhaps the name is a reference to the ROWID
330 */
331 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
332 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000333 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000334 pExpr->affinity = SQLITE_AFF_INTEGER;
335 }
336
337 /*
338 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
339 ** might refer to an result-set alias. This happens, for example, when
340 ** we are resolving names in the WHERE clause of the following command:
341 **
342 ** SELECT a+b AS x FROM table WHERE x<10;
343 **
344 ** In cases like this, replace pExpr with a copy of the expression that
345 ** forms the result set entry ("a+b" in the example) and return immediately.
346 ** Note that the expression in the result set should have already been
347 ** resolved by the time the WHERE clause is resolved.
348 */
349 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
350 for(j=0; j<pEList->nExpr; j++){
351 char *zAs = pEList->a[j].zName;
352 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000353 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000354 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000355 assert( pExpr->x.pList==0 );
356 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000357 pOrig = pEList->a[j].pExpr;
drha51009b2012-05-21 19:11:25 +0000358 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10 +0000359 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000360 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000361 }
drhed551b92012-08-23 19:46:11 +0000362 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
drh7d10d5a2008-08-20 16:35:10 +0000363 cnt = 1;
364 pMatch = 0;
365 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000366 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000367 }
368 }
369 }
370
371 /* Advance to the next name context. The loop will exit when either
372 ** we have a match (cnt>0) or when we run out of name contexts.
373 */
374 if( cnt==0 ){
375 pNC = pNC->pNext;
drhed551b92012-08-23 19:46:11 +0000376 nSubquery++;
drh7d10d5a2008-08-20 16:35:10 +0000377 }
378 }
379
380 /*
381 ** If X and Y are NULL (in other words if only the column name Z is
382 ** supplied) and the value of Z is enclosed in double-quotes, then
383 ** Z is a string literal if it doesn't match any column names. In that
384 ** case, we need to return right away and not make any changes to
385 ** pExpr.
386 **
387 ** Because no reference was made to outer contexts, the pNC->nRef
388 ** fields are not changed in any context.
389 */
drh24fb6272009-05-01 21:13:36 +0000390 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000391 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000392 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000393 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000394 }
395
396 /*
397 ** cnt==0 means there was not match. cnt>1 means there were two or
398 ** more matches. Either way, we have an error.
399 */
400 if( cnt!=1 ){
401 const char *zErr;
402 zErr = cnt==0 ? "no such column" : "ambiguous column name";
403 if( zDb ){
404 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
405 }else if( zTab ){
406 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
407 }else{
408 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
409 }
dan1db95102010-06-28 10:15:19 +0000410 pParse->checkSchema = 1;
drh7d10d5a2008-08-20 16:35:10 +0000411 pTopNC->nErr++;
412 }
413
414 /* If a column from a table in pSrcList is referenced, then record
415 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
416 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
417 ** column number is greater than the number of bits in the bitmask
418 ** then set the high-order bit of the bitmask.
419 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000420 if( pExpr->iColumn>=0 && pMatch!=0 ){
421 int n = pExpr->iColumn;
422 testcase( n==BMS-1 );
423 if( n>=BMS ){
424 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000425 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000426 assert( pMatch->iCursor==pExpr->iTable );
427 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000428 }
429
drh7d10d5a2008-08-20 16:35:10 +0000430 /* Clean up and return
431 */
drh7d10d5a2008-08-20 16:35:10 +0000432 sqlite3ExprDelete(db, pExpr->pLeft);
433 pExpr->pLeft = 0;
434 sqlite3ExprDelete(db, pExpr->pRight);
435 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000436 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000437lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000438 if( cnt==1 ){
439 assert( pNC!=0 );
440 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
441 /* Increment the nRef value on all name contexts from TopNC up to
442 ** the point where the name matched. */
443 for(;;){
444 assert( pTopNC!=0 );
445 pTopNC->nRef++;
446 if( pTopNC==pNC ) break;
447 pTopNC = pTopNC->pNext;
448 }
drhf7828b52009-06-15 23:15:59 +0000449 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000450 } else {
drhf7828b52009-06-15 23:15:59 +0000451 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000452 }
453}
454
455/*
danf7b0b0a2009-10-19 15:52:32 +0000456** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34 +0000457** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32 +0000458*/
459Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
460 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
461 if( p ){
462 struct SrcList_item *pItem = &pSrc->a[iSrc];
463 p->pTab = pItem->pTab;
464 p->iTable = pItem->iCursor;
465 if( p->pTab->iPKey==iCol ){
466 p->iColumn = -1;
467 }else{
drh8677d302009-11-04 13:17:14 +0000468 p->iColumn = (ynVar)iCol;
drh7caba662010-04-08 15:01:44 +0000469 testcase( iCol==BMS );
470 testcase( iCol==BMS-1 );
danf7b0b0a2009-10-19 15:52:32 +0000471 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
472 }
473 ExprSetProperty(p, EP_Resolved);
474 }
475 return p;
476}
477
478/*
drh7d10d5a2008-08-20 16:35:10 +0000479** This routine is callback for sqlite3WalkExpr().
480**
481** Resolve symbolic names into TK_COLUMN operators for the current
482** node in the expression tree. Return 0 to continue the search down
483** the tree or 2 to abort the tree walk.
484**
485** This routine also does error checking and name resolution for
486** function names. The operator for aggregate functions is changed
487** to TK_AGG_FUNCTION.
488*/
489static int resolveExprStep(Walker *pWalker, Expr *pExpr){
490 NameContext *pNC;
491 Parse *pParse;
492
drh7d10d5a2008-08-20 16:35:10 +0000493 pNC = pWalker->u.pNC;
494 assert( pNC!=0 );
495 pParse = pNC->pParse;
496 assert( pParse==pWalker->pParse );
497
498 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
499 ExprSetProperty(pExpr, EP_Resolved);
500#ifndef NDEBUG
501 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
502 SrcList *pSrcList = pNC->pSrcList;
503 int i;
504 for(i=0; i<pNC->pSrcList->nSrc; i++){
505 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
506 }
507 }
508#endif
509 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000510
shane273f6192008-10-10 04:34:16 +0000511#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000512 /* The special operator TK_ROW means use the rowid for the first
513 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
514 ** clause processing on UPDATE and DELETE statements.
515 */
516 case TK_ROW: {
517 SrcList *pSrcList = pNC->pSrcList;
518 struct SrcList_item *pItem;
519 assert( pSrcList && pSrcList->nSrc==1 );
520 pItem = pSrcList->a;
521 pExpr->op = TK_COLUMN;
522 pExpr->pTab = pItem->pTab;
523 pExpr->iTable = pItem->iCursor;
524 pExpr->iColumn = -1;
525 pExpr->affinity = SQLITE_AFF_INTEGER;
526 break;
527 }
shane273f6192008-10-10 04:34:16 +0000528#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000529
drh7d10d5a2008-08-20 16:35:10 +0000530 /* A lone identifier is the name of a column.
531 */
532 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000533 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000534 }
535
536 /* A table name and column name: ID.ID
537 ** Or a database, table and column: ID.ID.ID
538 */
539 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000540 const char *zColumn;
541 const char *zTable;
542 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000543 Expr *pRight;
544
545 /* if( pSrcList==0 ) break; */
546 pRight = pExpr->pRight;
547 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000548 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000549 zTable = pExpr->pLeft->u.zToken;
550 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000551 }else{
552 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000553 zDb = pExpr->pLeft->u.zToken;
554 zTable = pRight->pLeft->u.zToken;
555 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000556 }
drhf7828b52009-06-15 23:15:59 +0000557 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000558 }
559
560 /* Resolve function names
561 */
562 case TK_CONST_FUNC:
563 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000564 ExprList *pList = pExpr->x.pList; /* The argument list */
565 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000566 int no_such_func = 0; /* True if no such function exists */
567 int wrong_num_args = 0; /* True if wrong number of arguments */
568 int is_agg = 0; /* True if is an aggregate function */
569 int auth; /* Authorization to use the function */
570 int nId; /* Number of characters in function name */
571 const char *zId; /* The function name. */
572 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000573 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000574
drh73c0fdc2009-06-15 18:32:36 +0000575 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000576 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000577 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000578 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000579 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
580 if( pDef==0 ){
drh89d5d6a2012-04-07 00:09:21 +0000581 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:10 +0000582 if( pDef==0 ){
583 no_such_func = 1;
584 }else{
585 wrong_num_args = 1;
586 }
587 }else{
588 is_agg = pDef->xFunc==0;
589 }
590#ifndef SQLITE_OMIT_AUTHORIZATION
591 if( pDef ){
592 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
593 if( auth!=SQLITE_OK ){
594 if( auth==SQLITE_DENY ){
595 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
596 pDef->zName);
597 pNC->nErr++;
598 }
599 pExpr->op = TK_NULL;
600 return WRC_Prune;
601 }
602 }
603#endif
drha51009b2012-05-21 19:11:25 +0000604 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000605 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
606 pNC->nErr++;
607 is_agg = 0;
608 }else if( no_such_func ){
609 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
610 pNC->nErr++;
611 }else if( wrong_num_args ){
612 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
613 nId, zId);
614 pNC->nErr++;
615 }
drha51009b2012-05-21 19:11:25 +0000616 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000617 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:10 +0000618 if( is_agg ){
619 NameContext *pNC2 = pNC;
620 pExpr->op = TK_AGG_FUNCTION;
621 pExpr->op2 = 0;
622 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
623 pExpr->op2++;
624 pNC2 = pNC2->pNext;
625 }
626 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
627 pNC->ncFlags |= NC_AllowAgg;
628 }
drh7d10d5a2008-08-20 16:35:10 +0000629 /* FIX ME: Compute pExpr->affinity based on the expected return
630 ** type of the function
631 */
632 return WRC_Prune;
633 }
634#ifndef SQLITE_OMIT_SUBQUERY
635 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000636 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000637#endif
638 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000639 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000640 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000641 int nRef = pNC->nRef;
642#ifndef SQLITE_OMIT_CHECK
drha51009b2012-05-21 19:11:25 +0000643 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000644 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
645 }
646#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000647 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000648 assert( pNC->nRef>=nRef );
649 if( nRef!=pNC->nRef ){
650 ExprSetProperty(pExpr, EP_VarSelect);
651 }
652 }
653 break;
654 }
655#ifndef SQLITE_OMIT_CHECK
656 case TK_VARIABLE: {
drha51009b2012-05-21 19:11:25 +0000657 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000658 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
659 }
660 break;
661 }
662#endif
663 }
664 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
665}
666
667/*
668** pEList is a list of expressions which are really the result set of the
669** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
670** This routine checks to see if pE is a simple identifier which corresponds
671** to the AS-name of one of the terms of the expression list. If it is,
672** this routine return an integer between 1 and N where N is the number of
673** elements in pEList, corresponding to the matching entry. If there is
674** no match, or if pE is not a simple identifier, then this routine
675** return 0.
676**
677** pEList has been resolved. pE has not.
678*/
679static int resolveAsName(
680 Parse *pParse, /* Parsing context for error messages */
681 ExprList *pEList, /* List of expressions to scan */
682 Expr *pE /* Expression we are trying to match */
683){
684 int i; /* Loop counter */
685
shanecf697392009-06-01 16:53:09 +0000686 UNUSED_PARAMETER(pParse);
687
drh73c0fdc2009-06-15 18:32:36 +0000688 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000689 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000690 for(i=0; i<pEList->nExpr; i++){
691 char *zAs = pEList->a[i].zName;
692 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000693 return i+1;
694 }
695 }
drh7d10d5a2008-08-20 16:35:10 +0000696 }
697 return 0;
698}
699
700/*
701** pE is a pointer to an expression which is a single term in the
702** ORDER BY of a compound SELECT. The expression has not been
703** name resolved.
704**
705** At the point this routine is called, we already know that the
706** ORDER BY term is not an integer index into the result set. That
707** case is handled by the calling routine.
708**
709** Attempt to match pE against result set columns in the left-most
710** SELECT statement. Return the index i of the matching column,
711** as an indication to the caller that it should sort by the i-th column.
712** The left-most column is 1. In other words, the value returned is the
713** same integer value that would be used in the SQL statement to indicate
714** the column.
715**
716** If there is no match, return 0. Return -1 if an error occurs.
717*/
718static int resolveOrderByTermToExprList(
719 Parse *pParse, /* Parsing context for error messages */
720 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
721 Expr *pE /* The specific ORDER BY term */
722){
723 int i; /* Loop counter */
724 ExprList *pEList; /* The columns of the result set */
725 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000726 sqlite3 *db; /* Database connection */
727 int rc; /* Return code from subprocedures */
728 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000729
730 assert( sqlite3ExprIsInteger(pE, &i)==0 );
731 pEList = pSelect->pEList;
732
733 /* Resolve all names in the ORDER BY term expression
734 */
735 memset(&nc, 0, sizeof(nc));
736 nc.pParse = pParse;
737 nc.pSrcList = pSelect->pSrc;
738 nc.pEList = pEList;
drha51009b2012-05-21 19:11:25 +0000739 nc.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000740 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000741 db = pParse->db;
742 savedSuppErr = db->suppressErr;
743 db->suppressErr = 1;
744 rc = sqlite3ResolveExprNames(&nc, pE);
745 db->suppressErr = savedSuppErr;
746 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000747
748 /* Try to match the ORDER BY expression against an expression
749 ** in the result set. Return an 1-based index of the matching
750 ** result-set entry.
751 */
752 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000753 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000754 return i+1;
755 }
756 }
757
758 /* If no match, return 0. */
759 return 0;
760}
761
762/*
763** Generate an ORDER BY or GROUP BY term out-of-range error.
764*/
765static void resolveOutOfRangeError(
766 Parse *pParse, /* The error context into which to write the error */
767 const char *zType, /* "ORDER" or "GROUP" */
768 int i, /* The index (1-based) of the term out of range */
769 int mx /* Largest permissible value of i */
770){
771 sqlite3ErrorMsg(pParse,
772 "%r %s BY term out of range - should be "
773 "between 1 and %d", i, zType, mx);
774}
775
776/*
777** Analyze the ORDER BY clause in a compound SELECT statement. Modify
778** each term of the ORDER BY clause is a constant integer between 1
779** and N where N is the number of columns in the compound SELECT.
780**
781** ORDER BY terms that are already an integer between 1 and N are
782** unmodified. ORDER BY terms that are integers outside the range of
783** 1 through N generate an error. ORDER BY terms that are expressions
784** are matched against result set expressions of compound SELECT
785** beginning with the left-most SELECT and working toward the right.
786** At the first match, the ORDER BY expression is transformed into
787** the integer column number.
788**
789** Return the number of errors seen.
790*/
791static int resolveCompoundOrderBy(
792 Parse *pParse, /* Parsing context. Leave error messages here */
793 Select *pSelect /* The SELECT statement containing the ORDER BY */
794){
795 int i;
796 ExprList *pOrderBy;
797 ExprList *pEList;
798 sqlite3 *db;
799 int moreToDo = 1;
800
801 pOrderBy = pSelect->pOrderBy;
802 if( pOrderBy==0 ) return 0;
803 db = pParse->db;
804#if SQLITE_MAX_COLUMN
805 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
806 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
807 return 1;
808 }
809#endif
810 for(i=0; i<pOrderBy->nExpr; i++){
811 pOrderBy->a[i].done = 0;
812 }
813 pSelect->pNext = 0;
814 while( pSelect->pPrior ){
815 pSelect->pPrior->pNext = pSelect;
816 pSelect = pSelect->pPrior;
817 }
818 while( pSelect && moreToDo ){
819 struct ExprList_item *pItem;
820 moreToDo = 0;
821 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000822 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000823 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
824 int iCol = -1;
825 Expr *pE, *pDup;
826 if( pItem->done ) continue;
827 pE = pItem->pExpr;
828 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000829 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000830 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
831 return 1;
832 }
833 }else{
834 iCol = resolveAsName(pParse, pEList, pE);
835 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000836 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000837 if( !db->mallocFailed ){
838 assert(pDup);
839 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
840 }
841 sqlite3ExprDelete(db, pDup);
842 }
drh7d10d5a2008-08-20 16:35:10 +0000843 }
844 if( iCol>0 ){
drh7d10d5a2008-08-20 16:35:10 +0000845 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000846 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000847 if( pE==0 ) return 1;
drhae80dde2012-12-06 21:16:43 +0000848 pE->flags |= EP_IntValue;
drh33e619f2009-05-28 01:00:55 +0000849 pE->u.iValue = iCol;
drh4b3ac732011-12-10 23:18:32 +0000850 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000851 pItem->done = 1;
852 }else{
853 moreToDo = 1;
854 }
855 }
856 pSelect = pSelect->pNext;
857 }
858 for(i=0; i<pOrderBy->nExpr; i++){
859 if( pOrderBy->a[i].done==0 ){
860 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
861 "column in the result set", i+1);
862 return 1;
863 }
864 }
865 return 0;
866}
867
868/*
869** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
870** the SELECT statement pSelect. If any term is reference to a
871** result set expression (as determined by the ExprList.a.iCol field)
872** then convert that term into a copy of the corresponding result set
873** column.
874**
875** If any errors are detected, add an error message to pParse and
876** return non-zero. Return zero if no errors are seen.
877*/
878int sqlite3ResolveOrderGroupBy(
879 Parse *pParse, /* Parsing context. Leave error messages here */
880 Select *pSelect, /* The SELECT statement containing the clause */
881 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
882 const char *zType /* "ORDER" or "GROUP" */
883){
884 int i;
885 sqlite3 *db = pParse->db;
886 ExprList *pEList;
887 struct ExprList_item *pItem;
888
889 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
890#if SQLITE_MAX_COLUMN
891 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
892 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
893 return 1;
894 }
895#endif
896 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000897 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000898 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +0000899 if( pItem->iOrderByCol ){
900 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000901 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
902 return 1;
903 }
drhed551b92012-08-23 19:46:11 +0000904 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
drh7d10d5a2008-08-20 16:35:10 +0000905 }
906 }
907 return 0;
908}
909
910/*
911** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
912** The Name context of the SELECT statement is pNC. zType is either
913** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
914**
915** This routine resolves each term of the clause into an expression.
916** If the order-by term is an integer I between 1 and N (where N is the
917** number of columns in the result set of the SELECT) then the expression
918** in the resolution is a copy of the I-th result-set expression. If
919** the order-by term is an identify that corresponds to the AS-name of
920** a result-set expression, then the term resolves to a copy of the
921** result-set expression. Otherwise, the expression is resolved in
922** the usual way - using sqlite3ResolveExprNames().
923**
924** This routine returns the number of errors. If errors occur, then
925** an appropriate error message might be left in pParse. (OOM errors
926** excepted.)
927*/
928static int resolveOrderGroupBy(
929 NameContext *pNC, /* The name context of the SELECT statement */
930 Select *pSelect, /* The SELECT statement holding pOrderBy */
931 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
932 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
933){
drh70331cd2012-04-27 01:09:06 +0000934 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000935 int iCol; /* Column number */
936 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
937 Parse *pParse; /* Parsing context */
938 int nResult; /* Number of terms in the result set */
939
940 if( pOrderBy==0 ) return 0;
941 nResult = pSelect->pEList->nExpr;
942 pParse = pNC->pParse;
943 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
944 Expr *pE = pItem->pExpr;
945 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000946 if( iCol>0 ){
947 /* If an AS-name match is found, mark this ORDER BY column as being
948 ** a copy of the iCol-th result-set column. The subsequent call to
949 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
950 ** copy of the iCol-th result-set expression. */
drh4b3ac732011-12-10 23:18:32 +0000951 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000952 continue;
953 }
drh0a8a4062012-12-07 18:38:16 +0000954 if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
drh7d10d5a2008-08-20 16:35:10 +0000955 /* The ORDER BY term is an integer constant. Again, set the column
956 ** number so that sqlite3ResolveOrderGroupBy() will convert the
957 ** order-by term to a copy of the result-set expression */
drh0a8a4062012-12-07 18:38:16 +0000958 if( (iCol & ~0xffff)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000959 resolveOutOfRangeError(pParse, zType, i+1, nResult);
960 return 1;
961 }
drh4b3ac732011-12-10 23:18:32 +0000962 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000963 continue;
964 }
965
966 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +0000967 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +0000968 if( sqlite3ResolveExprNames(pNC, pE) ){
969 return 1;
970 }
drh70331cd2012-04-27 01:09:06 +0000971 for(j=0; j<pSelect->pEList->nExpr; j++){
972 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
973 pItem->iOrderByCol = j+1;
974 }
975 }
drh7d10d5a2008-08-20 16:35:10 +0000976 }
977 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
978}
979
980/*
981** Resolve names in the SELECT statement p and all of its descendents.
982*/
983static int resolveSelectStep(Walker *pWalker, Select *p){
984 NameContext *pOuterNC; /* Context that contains this SELECT */
985 NameContext sNC; /* Name context of this SELECT */
986 int isCompound; /* True if p is a compound select */
987 int nCompound; /* Number of compound terms processed so far */
988 Parse *pParse; /* Parsing context */
989 ExprList *pEList; /* Result set expression list */
990 int i; /* Loop counter */
991 ExprList *pGroupBy; /* The GROUP BY clause */
992 Select *pLeftmost; /* Left-most of SELECT of a compound */
993 sqlite3 *db; /* Database connection */
994
995
drh0a846f92008-08-25 17:23:29 +0000996 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000997 if( p->selFlags & SF_Resolved ){
998 return WRC_Prune;
999 }
1000 pOuterNC = pWalker->u.pNC;
1001 pParse = pWalker->pParse;
1002 db = pParse->db;
1003
1004 /* Normally sqlite3SelectExpand() will be called first and will have
1005 ** already expanded this SELECT. However, if this is a subquery within
1006 ** an expression, sqlite3ResolveExprNames() will be called without a
1007 ** prior call to sqlite3SelectExpand(). When that happens, let
1008 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1009 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1010 ** this routine in the correct order.
1011 */
1012 if( (p->selFlags & SF_Expanded)==0 ){
1013 sqlite3SelectPrep(pParse, p, pOuterNC);
1014 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1015 }
1016
1017 isCompound = p->pPrior!=0;
1018 nCompound = 0;
1019 pLeftmost = p;
1020 while( p ){
1021 assert( (p->selFlags & SF_Expanded)!=0 );
1022 assert( (p->selFlags & SF_Resolved)==0 );
1023 p->selFlags |= SF_Resolved;
1024
1025 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1026 ** are not allowed to refer to any names, so pass an empty NameContext.
1027 */
1028 memset(&sNC, 0, sizeof(sNC));
1029 sNC.pParse = pParse;
1030 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1031 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1032 return WRC_Abort;
1033 }
1034
1035 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1036 ** resolve the result-set expression list.
1037 */
drha51009b2012-05-21 19:11:25 +00001038 sNC.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001039 sNC.pSrcList = p->pSrc;
1040 sNC.pNext = pOuterNC;
1041
1042 /* Resolve names in the result set. */
1043 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +00001044 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001045 for(i=0; i<pEList->nExpr; i++){
1046 Expr *pX = pEList->a[i].pExpr;
1047 if( sqlite3ResolveExprNames(&sNC, pX) ){
1048 return WRC_Abort;
1049 }
1050 }
1051
1052 /* Recursively resolve names in all subqueries
1053 */
1054 for(i=0; i<p->pSrc->nSrc; i++){
1055 struct SrcList_item *pItem = &p->pSrc->a[i];
1056 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001057 NameContext *pNC; /* Used to iterate name contexts */
1058 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001059 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001060
1061 /* Count the total number of references to pOuterNC and all of its
1062 ** parent contexts. After resolving references to expressions in
1063 ** pItem->pSelect, check if this value has changed. If so, then
1064 ** SELECT statement pItem->pSelect must be correlated. Set the
1065 ** pItem->isCorrelated flag if this is the case. */
1066 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1067
drh7d10d5a2008-08-20 16:35:10 +00001068 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001069 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001070 pParse->zAuthContext = zSavedContext;
1071 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001072
1073 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1074 assert( pItem->isCorrelated==0 && nRef<=0 );
1075 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001076 }
1077 }
1078
1079 /* If there are no aggregate functions in the result-set, and no GROUP BY
1080 ** expression, do not allow aggregates in any of the other expressions.
1081 */
1082 assert( (p->selFlags & SF_Aggregate)==0 );
1083 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:25 +00001084 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +00001085 p->selFlags |= SF_Aggregate;
1086 }else{
drha51009b2012-05-21 19:11:25 +00001087 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001088 }
1089
1090 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1091 */
1092 if( p->pHaving && !pGroupBy ){
1093 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1094 return WRC_Abort;
1095 }
1096
1097 /* Add the expression list to the name-context before parsing the
1098 ** other expressions in the SELECT statement. This is so that
1099 ** expressions in the WHERE clause (etc.) can refer to expressions by
1100 ** aliases in the result set.
1101 **
1102 ** Minor point: If this is the case, then the expression will be
1103 ** re-evaluated for each reference to it.
1104 */
1105 sNC.pEList = p->pEList;
1106 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1107 sqlite3ResolveExprNames(&sNC, p->pHaving)
1108 ){
1109 return WRC_Abort;
1110 }
1111
1112 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1113 ** outer queries
1114 */
1115 sNC.pNext = 0;
drha51009b2012-05-21 19:11:25 +00001116 sNC.ncFlags |= NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001117
1118 /* Process the ORDER BY clause for singleton SELECT statements.
1119 ** The ORDER BY clause for compounds SELECT statements is handled
1120 ** below, after all of the result-sets for all of the elements of
1121 ** the compound have been resolved.
1122 */
1123 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1124 return WRC_Abort;
1125 }
1126 if( db->mallocFailed ){
1127 return WRC_Abort;
1128 }
1129
1130 /* Resolve the GROUP BY clause. At the same time, make sure
1131 ** the GROUP BY clause does not contain aggregate functions.
1132 */
1133 if( pGroupBy ){
1134 struct ExprList_item *pItem;
1135
1136 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1137 return WRC_Abort;
1138 }
1139 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1140 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1141 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1142 "the GROUP BY clause");
1143 return WRC_Abort;
1144 }
1145 }
1146 }
1147
1148 /* Advance to the next term of the compound
1149 */
1150 p = p->pPrior;
1151 nCompound++;
1152 }
1153
1154 /* Resolve the ORDER BY on a compound SELECT after all terms of
1155 ** the compound have been resolved.
1156 */
1157 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1158 return WRC_Abort;
1159 }
1160
1161 return WRC_Prune;
1162}
1163
1164/*
1165** This routine walks an expression tree and resolves references to
1166** table columns and result-set columns. At the same time, do error
1167** checking on function usage and set a flag if any aggregate functions
1168** are seen.
1169**
1170** To resolve table columns references we look for nodes (or subtrees) of the
1171** form X.Y.Z or Y.Z or just Z where
1172**
1173** X: The name of a database. Ex: "main" or "temp" or
1174** the symbolic name assigned to an ATTACH-ed database.
1175**
1176** Y: The name of a table in a FROM clause. Or in a trigger
1177** one of the special names "old" or "new".
1178**
1179** Z: The name of a column in table Y.
1180**
1181** The node at the root of the subtree is modified as follows:
1182**
1183** Expr.op Changed to TK_COLUMN
1184** Expr.pTab Points to the Table object for X.Y
1185** Expr.iColumn The column index in X.Y. -1 for the rowid.
1186** Expr.iTable The VDBE cursor number for X.Y
1187**
1188**
1189** To resolve result-set references, look for expression nodes of the
1190** form Z (with no X and Y prefix) where the Z matches the right-hand
1191** size of an AS clause in the result-set of a SELECT. The Z expression
1192** is replaced by a copy of the left-hand side of the result-set expression.
1193** Table-name and function resolution occurs on the substituted expression
1194** tree. For example, in:
1195**
1196** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1197**
1198** The "x" term of the order by is replaced by "a+b" to render:
1199**
1200** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1201**
1202** Function calls are checked to make sure that the function is
1203** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:25 +00001204** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:10 +00001205** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1206** If an expression contains aggregate functions then the EP_Agg
1207** property on the expression is set.
1208**
1209** An error message is left in pParse if anything is amiss. The number
1210** if errors is returned.
1211*/
1212int sqlite3ResolveExprNames(
1213 NameContext *pNC, /* Namespace to resolve expressions in. */
1214 Expr *pExpr /* The expression to be analyzed. */
1215){
drha51009b2012-05-21 19:11:25 +00001216 u8 savedHasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001217 Walker w;
1218
1219 if( pExpr==0 ) return 0;
1220#if SQLITE_MAX_EXPR_DEPTH>0
1221 {
1222 Parse *pParse = pNC->pParse;
1223 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1224 return 1;
1225 }
1226 pParse->nHeight += pExpr->nHeight;
1227 }
1228#endif
drha51009b2012-05-21 19:11:25 +00001229 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1230 pNC->ncFlags &= ~NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001231 w.xExprCallback = resolveExprStep;
1232 w.xSelectCallback = resolveSelectStep;
1233 w.pParse = pNC->pParse;
1234 w.u.pNC = pNC;
1235 sqlite3WalkExpr(&w, pExpr);
1236#if SQLITE_MAX_EXPR_DEPTH>0
1237 pNC->pParse->nHeight -= pExpr->nHeight;
1238#endif
drhfd773cf2009-05-29 14:39:07 +00001239 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001240 ExprSetProperty(pExpr, EP_Error);
1241 }
drha51009b2012-05-21 19:11:25 +00001242 if( pNC->ncFlags & NC_HasAgg ){
drh7d10d5a2008-08-20 16:35:10 +00001243 ExprSetProperty(pExpr, EP_Agg);
1244 }else if( savedHasAgg ){
drha51009b2012-05-21 19:11:25 +00001245 pNC->ncFlags |= NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001246 }
1247 return ExprHasProperty(pExpr, EP_Error);
1248}
drh7d10d5a2008-08-20 16:35:10 +00001249
1250
1251/*
1252** Resolve all names in all expressions of a SELECT and in all
1253** decendents of the SELECT, including compounds off of p->pPrior,
1254** subqueries in expressions, and subqueries used as FROM clause
1255** terms.
1256**
1257** See sqlite3ResolveExprNames() for a description of the kinds of
1258** transformations that occur.
1259**
1260** All SELECT statements should have been expanded using
1261** sqlite3SelectExpand() prior to invoking this routine.
1262*/
1263void sqlite3ResolveSelectNames(
1264 Parse *pParse, /* The parser context */
1265 Select *p, /* The SELECT statement being coded. */
1266 NameContext *pOuterNC /* Name context for parent SELECT statement */
1267){
1268 Walker w;
1269
drh0a846f92008-08-25 17:23:29 +00001270 assert( p!=0 );
1271 w.xExprCallback = resolveExprStep;
1272 w.xSelectCallback = resolveSelectStep;
1273 w.pParse = pParse;
1274 w.u.pNC = pOuterNC;
1275 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001276}