blob: 8ae170ab4278d9606b0b1a2759dbc883d01b0aa1 [file] [log] [blame]
drh7d10d5a2008-08-20 16:35:10 +00001/*
2** 2008 August 18
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12**
13** This file contains routines used for walking the parser tree and
14** resolve all identifiers by associating them with a particular
15** table and column.
drh7d10d5a2008-08-20 16:35:10 +000016*/
17#include "sqliteInt.h"
18#include <stdlib.h>
19#include <string.h>
20
21/*
drhed551b92012-08-23 19:46:11 +000022** Walk the expression tree pExpr and increase the aggregate function
23** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
24** This needs to occur when copying a TK_AGG_FUNCTION node from an
25** outer query into an inner subquery.
26**
27** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
28** is a helper function - a callback for the tree walker.
29*/
30static int incrAggDepth(Walker *pWalker, Expr *pExpr){
31 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
32 return WRC_Continue;
33}
34static void incrAggFunctionDepth(Expr *pExpr, int N){
35 if( N>0 ){
36 Walker w;
37 memset(&w, 0, sizeof(w));
38 w.xExprCallback = incrAggDepth;
39 w.u.i = N;
40 sqlite3WalkExpr(&w, pExpr);
41 }
42}
43
44/*
drh8b213892008-08-29 02:14:02 +000045** Turn the pExpr expression into an alias for the iCol-th column of the
46** result set in pEList.
47**
48** If the result set column is a simple column reference, then this routine
49** makes an exact copy. But for any other kind of expression, this
50** routine make a copy of the result set column as the argument to the
51** TK_AS operator. The TK_AS operator causes the expression to be
52** evaluated just once and then reused for each alias.
53**
54** The reason for suppressing the TK_AS term when the expression is a simple
55** column reference is so that the column reference will be recognized as
56** usable by indices within the WHERE clause processing logic.
57**
58** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
59** that in a GROUP BY clause, the expression is evaluated twice. Hence:
60**
61** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
62**
63** Is equivalent to:
64**
65** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
66**
67** The result of random()%5 in the GROUP BY clause is probably different
68** from the result in the result-set. We might fix this someday. Or
69** then again, we might not...
drhed551b92012-08-23 19:46:11 +000070**
71** The nSubquery parameter specifies how many levels of subquery the
72** alias is removed from the original expression. The usually value is
73** zero but it might be more if the alias is contained within a subquery
74** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
75** structures must be increased by the nSubquery amount.
drh8b213892008-08-29 02:14:02 +000076*/
77static void resolveAlias(
78 Parse *pParse, /* Parsing context */
79 ExprList *pEList, /* A result set */
80 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
81 Expr *pExpr, /* Transform this into an alias to the result set */
drhed551b92012-08-23 19:46:11 +000082 const char *zType, /* "GROUP" or "ORDER" or "" */
83 int nSubquery /* Number of subqueries that the label is moving */
drh8b213892008-08-29 02:14:02 +000084){
85 Expr *pOrig; /* The iCol-th column of the result set */
86 Expr *pDup; /* Copy of pOrig */
87 sqlite3 *db; /* The database connection */
88
89 assert( iCol>=0 && iCol<pEList->nExpr );
90 pOrig = pEList->a[iCol].pExpr;
91 assert( pOrig!=0 );
92 assert( pOrig->flags & EP_Resolved );
93 db = pParse->db;
drhb7916a72009-05-27 10:31:29 +000094 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
95 pDup = sqlite3ExprDup(db, pOrig, 0);
drhed551b92012-08-23 19:46:11 +000096 incrAggFunctionDepth(pDup, nSubquery);
drh8b213892008-08-29 02:14:02 +000097 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
98 if( pDup==0 ) return;
99 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +0000100 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +0000101 }
102 pDup->iTable = pEList->a[iCol].iAlias;
drh0b0745a2009-05-28 12:49:53 +0000103 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
104 pDup = sqlite3ExprDup(db, pOrig, 0);
drh2c220452009-05-28 14:34:49 +0000105 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +0000106 }else{
drh33e619f2009-05-28 01:00:55 +0000107 char *zToken = pOrig->u.zToken;
drh73c0fdc2009-06-15 18:32:36 +0000108 assert( zToken!=0 );
drh33e619f2009-05-28 01:00:55 +0000109 pOrig->u.zToken = 0;
drhb7916a72009-05-27 10:31:29 +0000110 pDup = sqlite3ExprDup(db, pOrig, 0);
drh33e619f2009-05-28 01:00:55 +0000111 pOrig->u.zToken = zToken;
drhb7916a72009-05-27 10:31:29 +0000112 if( pDup==0 ) return;
drh73c0fdc2009-06-15 18:32:36 +0000113 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
114 pDup->flags2 |= EP2_MallocedToken;
115 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
drh8b213892008-08-29 02:14:02 +0000116 }
drh4b17cf52012-12-07 14:02:14 +0000117 pDup->flags |= EP_Collate & pExpr->flags;
danf6963f92009-11-23 14:39:14 +0000118
119 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
120 ** prevents ExprDelete() from deleting the Expr structure itself,
121 ** allowing it to be repopulated by the memcpy() on the following line.
122 */
123 ExprSetProperty(pExpr, EP_Static);
124 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +0000125 memcpy(pExpr, pDup, sizeof(*pExpr));
126 sqlite3DbFree(db, pDup);
127}
128
drhe802c5d2011-10-18 18:10:40 +0000129
130/*
131** Return TRUE if the name zCol occurs anywhere in the USING clause.
132**
133** Return FALSE if the USING clause is NULL or if it does not contain
134** zCol.
135*/
136static int nameInUsingClause(IdList *pUsing, const char *zCol){
137 if( pUsing ){
138 int k;
139 for(k=0; k<pUsing->nId; k++){
140 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
141 }
142 }
143 return 0;
144}
145
146
drh8b213892008-08-29 02:14:02 +0000147/*
drh7d10d5a2008-08-20 16:35:10 +0000148** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
149** that name in the set of source tables in pSrcList and make the pExpr
150** expression node refer back to that source column. The following changes
151** are made to pExpr:
152**
153** pExpr->iDb Set the index in db->aDb[] of the database X
154** (even if X is implied).
155** pExpr->iTable Set to the cursor number for the table obtained
156** from pSrcList.
157** pExpr->pTab Points to the Table structure of X.Y (even if
158** X and/or Y are implied.)
159** pExpr->iColumn Set to the column number within the table.
160** pExpr->op Set to TK_COLUMN.
161** pExpr->pLeft Any expression this points to is deleted
162** pExpr->pRight Any expression this points to is deleted.
163**
drhb7916a72009-05-27 10:31:29 +0000164** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000165** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000166** can be used. The zTable variable is the name of the table (the "Y"). This
167** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000168** means that the form of the name is Z and that columns from any table
169** can be used.
170**
171** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000172** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000173*/
174static int lookupName(
175 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000176 const char *zDb, /* Name of the database containing table, or NULL */
177 const char *zTab, /* Name of table containing column, or NULL */
178 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000179 NameContext *pNC, /* The name context used to resolve the name */
180 Expr *pExpr /* Make this EXPR node point to the selected column */
181){
drhed551b92012-08-23 19:46:11 +0000182 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000183 int cnt = 0; /* Number of matching column names */
184 int cntTab = 0; /* Number of matching table names */
drhed551b92012-08-23 19:46:11 +0000185 int nSubquery = 0; /* How many levels of subquery */
drh7d10d5a2008-08-20 16:35:10 +0000186 sqlite3 *db = pParse->db; /* The database connection */
187 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
188 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
189 NameContext *pTopNC = pNC; /* First namecontext in the list */
190 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000191 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000192
drhb7916a72009-05-27 10:31:29 +0000193 assert( pNC ); /* the name context cannot be NULL. */
194 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh5a05be12012-10-09 18:51:44 +0000195 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000196
197 /* Initialize the node to no-match */
198 pExpr->iTable = -1;
199 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000200 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000201
202 /* Start at the inner-most context and move outward until a match is found */
203 while( pNC && cnt==0 ){
204 ExprList *pEList;
205 SrcList *pSrcList = pNC->pSrcList;
206
207 if( pSrcList ){
208 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
209 Table *pTab;
210 int iDb;
211 Column *pCol;
212
213 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000214 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000215 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
216 assert( pTab->nCol>0 );
217 if( zTab ){
218 if( pItem->zAlias ){
219 char *zTabName = pItem->zAlias;
220 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
221 }else{
222 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000223 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
224 continue;
225 }
drh7d10d5a2008-08-20 16:35:10 +0000226 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
227 continue;
228 }
229 }
230 }
231 if( 0==(cntTab++) ){
232 pExpr->iTable = pItem->iCursor;
233 pExpr->pTab = pTab;
234 pSchema = pTab->pSchema;
235 pMatch = pItem;
236 }
237 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
238 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
drhe802c5d2011-10-18 18:10:40 +0000239 /* If there has been exactly one prior match and this match
240 ** is for the right-hand table of a NATURAL JOIN or is in a
241 ** USING clause, then skip this match.
242 */
243 if( cnt==1 ){
244 if( pItem->jointype & JT_NATURAL ) continue;
245 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
246 }
drh7d10d5a2008-08-20 16:35:10 +0000247 cnt++;
248 pExpr->iTable = pItem->iCursor;
249 pExpr->pTab = pTab;
250 pMatch = pItem;
251 pSchema = pTab->pSchema;
252 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000253 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000254 break;
255 }
256 }
257 }
258 }
259
260#ifndef SQLITE_OMIT_TRIGGER
261 /* If we have not already resolved the name, then maybe
262 ** it is a new.* or old.* trigger argument reference
263 */
dan165921a2009-08-28 18:53:45 +0000264 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000265 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000266 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000267 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
268 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000269 pExpr->iTable = 1;
270 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000271 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000272 pExpr->iTable = 0;
273 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000274 }
275
276 if( pTab ){
277 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000278 pSchema = pTab->pSchema;
279 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000280 for(iCol=0; iCol<pTab->nCol; iCol++){
281 Column *pCol = &pTab->aCol[iCol];
282 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
283 if( iCol==pTab->iPKey ){
284 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000285 }
drh25e978d2009-12-29 23:39:04 +0000286 break;
drh7d10d5a2008-08-20 16:35:10 +0000287 }
288 }
drh25e978d2009-12-29 23:39:04 +0000289 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000290 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000291 }
dan2bd93512009-08-31 08:22:46 +0000292 if( iCol<pTab->nCol ){
293 cnt++;
294 if( iCol<0 ){
295 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000296 }else if( pExpr->iTable==0 ){
297 testcase( iCol==31 );
298 testcase( iCol==32 );
299 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000300 }else{
301 testcase( iCol==31 );
302 testcase( iCol==32 );
303 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000304 }
shanecea72b22009-09-07 04:38:36 +0000305 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000306 pExpr->pTab = pTab;
307 isTrigger = 1;
308 }
drh7d10d5a2008-08-20 16:35:10 +0000309 }
310 }
311#endif /* !defined(SQLITE_OMIT_TRIGGER) */
312
313 /*
314 ** Perhaps the name is a reference to the ROWID
315 */
316 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
317 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000318 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000319 pExpr->affinity = SQLITE_AFF_INTEGER;
320 }
321
322 /*
323 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
324 ** might refer to an result-set alias. This happens, for example, when
325 ** we are resolving names in the WHERE clause of the following command:
326 **
327 ** SELECT a+b AS x FROM table WHERE x<10;
328 **
329 ** In cases like this, replace pExpr with a copy of the expression that
330 ** forms the result set entry ("a+b" in the example) and return immediately.
331 ** Note that the expression in the result set should have already been
332 ** resolved by the time the WHERE clause is resolved.
333 */
334 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
335 for(j=0; j<pEList->nExpr; j++){
336 char *zAs = pEList->a[j].zName;
337 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000338 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000339 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000340 assert( pExpr->x.pList==0 );
341 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000342 pOrig = pEList->a[j].pExpr;
drha51009b2012-05-21 19:11:25 +0000343 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10 +0000344 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000345 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000346 }
drhed551b92012-08-23 19:46:11 +0000347 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
drh7d10d5a2008-08-20 16:35:10 +0000348 cnt = 1;
349 pMatch = 0;
350 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000351 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000352 }
353 }
354 }
355
356 /* Advance to the next name context. The loop will exit when either
357 ** we have a match (cnt>0) or when we run out of name contexts.
358 */
359 if( cnt==0 ){
360 pNC = pNC->pNext;
drhed551b92012-08-23 19:46:11 +0000361 nSubquery++;
drh7d10d5a2008-08-20 16:35:10 +0000362 }
363 }
364
365 /*
366 ** If X and Y are NULL (in other words if only the column name Z is
367 ** supplied) and the value of Z is enclosed in double-quotes, then
368 ** Z is a string literal if it doesn't match any column names. In that
369 ** case, we need to return right away and not make any changes to
370 ** pExpr.
371 **
372 ** Because no reference was made to outer contexts, the pNC->nRef
373 ** fields are not changed in any context.
374 */
drh24fb6272009-05-01 21:13:36 +0000375 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000376 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000377 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000378 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000379 }
380
381 /*
382 ** cnt==0 means there was not match. cnt>1 means there were two or
383 ** more matches. Either way, we have an error.
384 */
385 if( cnt!=1 ){
386 const char *zErr;
387 zErr = cnt==0 ? "no such column" : "ambiguous column name";
388 if( zDb ){
389 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
390 }else if( zTab ){
391 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
392 }else{
393 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
394 }
dan1db95102010-06-28 10:15:19 +0000395 pParse->checkSchema = 1;
drh7d10d5a2008-08-20 16:35:10 +0000396 pTopNC->nErr++;
397 }
398
399 /* If a column from a table in pSrcList is referenced, then record
400 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
401 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
402 ** column number is greater than the number of bits in the bitmask
403 ** then set the high-order bit of the bitmask.
404 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000405 if( pExpr->iColumn>=0 && pMatch!=0 ){
406 int n = pExpr->iColumn;
407 testcase( n==BMS-1 );
408 if( n>=BMS ){
409 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000410 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000411 assert( pMatch->iCursor==pExpr->iTable );
412 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000413 }
414
drh7d10d5a2008-08-20 16:35:10 +0000415 /* Clean up and return
416 */
drh7d10d5a2008-08-20 16:35:10 +0000417 sqlite3ExprDelete(db, pExpr->pLeft);
418 pExpr->pLeft = 0;
419 sqlite3ExprDelete(db, pExpr->pRight);
420 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000421 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000422lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000423 if( cnt==1 ){
424 assert( pNC!=0 );
425 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
426 /* Increment the nRef value on all name contexts from TopNC up to
427 ** the point where the name matched. */
428 for(;;){
429 assert( pTopNC!=0 );
430 pTopNC->nRef++;
431 if( pTopNC==pNC ) break;
432 pTopNC = pTopNC->pNext;
433 }
drhf7828b52009-06-15 23:15:59 +0000434 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000435 } else {
drhf7828b52009-06-15 23:15:59 +0000436 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000437 }
438}
439
440/*
danf7b0b0a2009-10-19 15:52:32 +0000441** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34 +0000442** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32 +0000443*/
444Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
445 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
446 if( p ){
447 struct SrcList_item *pItem = &pSrc->a[iSrc];
448 p->pTab = pItem->pTab;
449 p->iTable = pItem->iCursor;
450 if( p->pTab->iPKey==iCol ){
451 p->iColumn = -1;
452 }else{
drh8677d302009-11-04 13:17:14 +0000453 p->iColumn = (ynVar)iCol;
drh7caba662010-04-08 15:01:44 +0000454 testcase( iCol==BMS );
455 testcase( iCol==BMS-1 );
danf7b0b0a2009-10-19 15:52:32 +0000456 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
457 }
458 ExprSetProperty(p, EP_Resolved);
459 }
460 return p;
461}
462
463/*
drh7d10d5a2008-08-20 16:35:10 +0000464** This routine is callback for sqlite3WalkExpr().
465**
466** Resolve symbolic names into TK_COLUMN operators for the current
467** node in the expression tree. Return 0 to continue the search down
468** the tree or 2 to abort the tree walk.
469**
470** This routine also does error checking and name resolution for
471** function names. The operator for aggregate functions is changed
472** to TK_AGG_FUNCTION.
473*/
474static int resolveExprStep(Walker *pWalker, Expr *pExpr){
475 NameContext *pNC;
476 Parse *pParse;
477
drh7d10d5a2008-08-20 16:35:10 +0000478 pNC = pWalker->u.pNC;
479 assert( pNC!=0 );
480 pParse = pNC->pParse;
481 assert( pParse==pWalker->pParse );
482
483 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
484 ExprSetProperty(pExpr, EP_Resolved);
485#ifndef NDEBUG
486 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
487 SrcList *pSrcList = pNC->pSrcList;
488 int i;
489 for(i=0; i<pNC->pSrcList->nSrc; i++){
490 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
491 }
492 }
493#endif
494 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000495
shane273f6192008-10-10 04:34:16 +0000496#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000497 /* The special operator TK_ROW means use the rowid for the first
498 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
499 ** clause processing on UPDATE and DELETE statements.
500 */
501 case TK_ROW: {
502 SrcList *pSrcList = pNC->pSrcList;
503 struct SrcList_item *pItem;
504 assert( pSrcList && pSrcList->nSrc==1 );
505 pItem = pSrcList->a;
506 pExpr->op = TK_COLUMN;
507 pExpr->pTab = pItem->pTab;
508 pExpr->iTable = pItem->iCursor;
509 pExpr->iColumn = -1;
510 pExpr->affinity = SQLITE_AFF_INTEGER;
511 break;
512 }
shane273f6192008-10-10 04:34:16 +0000513#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000514
drh7d10d5a2008-08-20 16:35:10 +0000515 /* A lone identifier is the name of a column.
516 */
517 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000518 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000519 }
520
521 /* A table name and column name: ID.ID
522 ** Or a database, table and column: ID.ID.ID
523 */
524 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000525 const char *zColumn;
526 const char *zTable;
527 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000528 Expr *pRight;
529
530 /* if( pSrcList==0 ) break; */
531 pRight = pExpr->pRight;
532 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000533 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000534 zTable = pExpr->pLeft->u.zToken;
535 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000536 }else{
537 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000538 zDb = pExpr->pLeft->u.zToken;
539 zTable = pRight->pLeft->u.zToken;
540 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000541 }
drhf7828b52009-06-15 23:15:59 +0000542 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000543 }
544
545 /* Resolve function names
546 */
547 case TK_CONST_FUNC:
548 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000549 ExprList *pList = pExpr->x.pList; /* The argument list */
550 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000551 int no_such_func = 0; /* True if no such function exists */
552 int wrong_num_args = 0; /* True if wrong number of arguments */
553 int is_agg = 0; /* True if is an aggregate function */
554 int auth; /* Authorization to use the function */
555 int nId; /* Number of characters in function name */
556 const char *zId; /* The function name. */
557 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000558 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000559
drh73c0fdc2009-06-15 18:32:36 +0000560 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000561 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000562 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000563 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000564 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
565 if( pDef==0 ){
drh89d5d6a2012-04-07 00:09:21 +0000566 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:10 +0000567 if( pDef==0 ){
568 no_such_func = 1;
569 }else{
570 wrong_num_args = 1;
571 }
572 }else{
573 is_agg = pDef->xFunc==0;
574 }
575#ifndef SQLITE_OMIT_AUTHORIZATION
576 if( pDef ){
577 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
578 if( auth!=SQLITE_OK ){
579 if( auth==SQLITE_DENY ){
580 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
581 pDef->zName);
582 pNC->nErr++;
583 }
584 pExpr->op = TK_NULL;
585 return WRC_Prune;
586 }
587 }
588#endif
drha51009b2012-05-21 19:11:25 +0000589 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000590 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
591 pNC->nErr++;
592 is_agg = 0;
593 }else if( no_such_func ){
594 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
595 pNC->nErr++;
596 }else if( wrong_num_args ){
597 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
598 nId, zId);
599 pNC->nErr++;
600 }
drha51009b2012-05-21 19:11:25 +0000601 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000602 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:10 +0000603 if( is_agg ){
604 NameContext *pNC2 = pNC;
605 pExpr->op = TK_AGG_FUNCTION;
606 pExpr->op2 = 0;
607 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
608 pExpr->op2++;
609 pNC2 = pNC2->pNext;
610 }
611 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
612 pNC->ncFlags |= NC_AllowAgg;
613 }
drh7d10d5a2008-08-20 16:35:10 +0000614 /* FIX ME: Compute pExpr->affinity based on the expected return
615 ** type of the function
616 */
617 return WRC_Prune;
618 }
619#ifndef SQLITE_OMIT_SUBQUERY
620 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000621 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000622#endif
623 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000624 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000625 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000626 int nRef = pNC->nRef;
627#ifndef SQLITE_OMIT_CHECK
drha51009b2012-05-21 19:11:25 +0000628 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000629 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
630 }
631#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000632 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000633 assert( pNC->nRef>=nRef );
634 if( nRef!=pNC->nRef ){
635 ExprSetProperty(pExpr, EP_VarSelect);
636 }
637 }
638 break;
639 }
640#ifndef SQLITE_OMIT_CHECK
641 case TK_VARIABLE: {
drha51009b2012-05-21 19:11:25 +0000642 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000643 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
644 }
645 break;
646 }
647#endif
648 }
649 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
650}
651
652/*
653** pEList is a list of expressions which are really the result set of the
654** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
655** This routine checks to see if pE is a simple identifier which corresponds
656** to the AS-name of one of the terms of the expression list. If it is,
657** this routine return an integer between 1 and N where N is the number of
658** elements in pEList, corresponding to the matching entry. If there is
659** no match, or if pE is not a simple identifier, then this routine
660** return 0.
661**
662** pEList has been resolved. pE has not.
663*/
664static int resolveAsName(
665 Parse *pParse, /* Parsing context for error messages */
666 ExprList *pEList, /* List of expressions to scan */
667 Expr *pE /* Expression we are trying to match */
668){
669 int i; /* Loop counter */
670
shanecf697392009-06-01 16:53:09 +0000671 UNUSED_PARAMETER(pParse);
672
drh73c0fdc2009-06-15 18:32:36 +0000673 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000674 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000675 for(i=0; i<pEList->nExpr; i++){
676 char *zAs = pEList->a[i].zName;
677 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000678 return i+1;
679 }
680 }
drh7d10d5a2008-08-20 16:35:10 +0000681 }
682 return 0;
683}
684
685/*
686** pE is a pointer to an expression which is a single term in the
687** ORDER BY of a compound SELECT. The expression has not been
688** name resolved.
689**
690** At the point this routine is called, we already know that the
691** ORDER BY term is not an integer index into the result set. That
692** case is handled by the calling routine.
693**
694** Attempt to match pE against result set columns in the left-most
695** SELECT statement. Return the index i of the matching column,
696** as an indication to the caller that it should sort by the i-th column.
697** The left-most column is 1. In other words, the value returned is the
698** same integer value that would be used in the SQL statement to indicate
699** the column.
700**
701** If there is no match, return 0. Return -1 if an error occurs.
702*/
703static int resolveOrderByTermToExprList(
704 Parse *pParse, /* Parsing context for error messages */
705 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
706 Expr *pE /* The specific ORDER BY term */
707){
708 int i; /* Loop counter */
709 ExprList *pEList; /* The columns of the result set */
710 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000711 sqlite3 *db; /* Database connection */
712 int rc; /* Return code from subprocedures */
713 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000714
715 assert( sqlite3ExprIsInteger(pE, &i)==0 );
716 pEList = pSelect->pEList;
717
718 /* Resolve all names in the ORDER BY term expression
719 */
720 memset(&nc, 0, sizeof(nc));
721 nc.pParse = pParse;
722 nc.pSrcList = pSelect->pSrc;
723 nc.pEList = pEList;
drha51009b2012-05-21 19:11:25 +0000724 nc.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000725 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000726 db = pParse->db;
727 savedSuppErr = db->suppressErr;
728 db->suppressErr = 1;
729 rc = sqlite3ResolveExprNames(&nc, pE);
730 db->suppressErr = savedSuppErr;
731 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000732
733 /* Try to match the ORDER BY expression against an expression
734 ** in the result set. Return an 1-based index of the matching
735 ** result-set entry.
736 */
737 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000738 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000739 return i+1;
740 }
741 }
742
743 /* If no match, return 0. */
744 return 0;
745}
746
747/*
748** Generate an ORDER BY or GROUP BY term out-of-range error.
749*/
750static void resolveOutOfRangeError(
751 Parse *pParse, /* The error context into which to write the error */
752 const char *zType, /* "ORDER" or "GROUP" */
753 int i, /* The index (1-based) of the term out of range */
754 int mx /* Largest permissible value of i */
755){
756 sqlite3ErrorMsg(pParse,
757 "%r %s BY term out of range - should be "
758 "between 1 and %d", i, zType, mx);
759}
760
761/*
762** Analyze the ORDER BY clause in a compound SELECT statement. Modify
763** each term of the ORDER BY clause is a constant integer between 1
764** and N where N is the number of columns in the compound SELECT.
765**
766** ORDER BY terms that are already an integer between 1 and N are
767** unmodified. ORDER BY terms that are integers outside the range of
768** 1 through N generate an error. ORDER BY terms that are expressions
769** are matched against result set expressions of compound SELECT
770** beginning with the left-most SELECT and working toward the right.
771** At the first match, the ORDER BY expression is transformed into
772** the integer column number.
773**
774** Return the number of errors seen.
775*/
776static int resolveCompoundOrderBy(
777 Parse *pParse, /* Parsing context. Leave error messages here */
778 Select *pSelect /* The SELECT statement containing the ORDER BY */
779){
780 int i;
781 ExprList *pOrderBy;
782 ExprList *pEList;
783 sqlite3 *db;
784 int moreToDo = 1;
785
786 pOrderBy = pSelect->pOrderBy;
787 if( pOrderBy==0 ) return 0;
788 db = pParse->db;
789#if SQLITE_MAX_COLUMN
790 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
791 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
792 return 1;
793 }
794#endif
795 for(i=0; i<pOrderBy->nExpr; i++){
796 pOrderBy->a[i].done = 0;
797 }
798 pSelect->pNext = 0;
799 while( pSelect->pPrior ){
800 pSelect->pPrior->pNext = pSelect;
801 pSelect = pSelect->pPrior;
802 }
803 while( pSelect && moreToDo ){
804 struct ExprList_item *pItem;
805 moreToDo = 0;
806 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000807 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000808 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
809 int iCol = -1;
810 Expr *pE, *pDup;
811 if( pItem->done ) continue;
812 pE = pItem->pExpr;
813 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000814 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000815 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
816 return 1;
817 }
818 }else{
819 iCol = resolveAsName(pParse, pEList, pE);
820 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000821 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000822 if( !db->mallocFailed ){
823 assert(pDup);
824 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
825 }
826 sqlite3ExprDelete(db, pDup);
827 }
drh7d10d5a2008-08-20 16:35:10 +0000828 }
829 if( iCol>0 ){
drh7d10d5a2008-08-20 16:35:10 +0000830 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000831 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000832 if( pE==0 ) return 1;
drhae80dde2012-12-06 21:16:43 +0000833 pE->flags |= EP_IntValue;
drh33e619f2009-05-28 01:00:55 +0000834 pE->u.iValue = iCol;
drh4b3ac732011-12-10 23:18:32 +0000835 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000836 pItem->done = 1;
837 }else{
838 moreToDo = 1;
839 }
840 }
841 pSelect = pSelect->pNext;
842 }
843 for(i=0; i<pOrderBy->nExpr; i++){
844 if( pOrderBy->a[i].done==0 ){
845 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
846 "column in the result set", i+1);
847 return 1;
848 }
849 }
850 return 0;
851}
852
853/*
854** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
855** the SELECT statement pSelect. If any term is reference to a
856** result set expression (as determined by the ExprList.a.iCol field)
857** then convert that term into a copy of the corresponding result set
858** column.
859**
860** If any errors are detected, add an error message to pParse and
861** return non-zero. Return zero if no errors are seen.
862*/
863int sqlite3ResolveOrderGroupBy(
864 Parse *pParse, /* Parsing context. Leave error messages here */
865 Select *pSelect, /* The SELECT statement containing the clause */
866 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
867 const char *zType /* "ORDER" or "GROUP" */
868){
869 int i;
870 sqlite3 *db = pParse->db;
871 ExprList *pEList;
872 struct ExprList_item *pItem;
873
874 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
875#if SQLITE_MAX_COLUMN
876 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
877 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
878 return 1;
879 }
880#endif
881 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000882 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000883 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +0000884 if( pItem->iOrderByCol ){
885 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000886 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
887 return 1;
888 }
drhed551b92012-08-23 19:46:11 +0000889 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
drh7d10d5a2008-08-20 16:35:10 +0000890 }
891 }
892 return 0;
893}
894
895/*
896** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
897** The Name context of the SELECT statement is pNC. zType is either
898** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
899**
900** This routine resolves each term of the clause into an expression.
901** If the order-by term is an integer I between 1 and N (where N is the
902** number of columns in the result set of the SELECT) then the expression
903** in the resolution is a copy of the I-th result-set expression. If
904** the order-by term is an identify that corresponds to the AS-name of
905** a result-set expression, then the term resolves to a copy of the
906** result-set expression. Otherwise, the expression is resolved in
907** the usual way - using sqlite3ResolveExprNames().
908**
909** This routine returns the number of errors. If errors occur, then
910** an appropriate error message might be left in pParse. (OOM errors
911** excepted.)
912*/
913static int resolveOrderGroupBy(
914 NameContext *pNC, /* The name context of the SELECT statement */
915 Select *pSelect, /* The SELECT statement holding pOrderBy */
916 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
917 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
918){
drh70331cd2012-04-27 01:09:06 +0000919 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000920 int iCol; /* Column number */
921 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
922 Parse *pParse; /* Parsing context */
923 int nResult; /* Number of terms in the result set */
924
925 if( pOrderBy==0 ) return 0;
926 nResult = pSelect->pEList->nExpr;
927 pParse = pNC->pParse;
928 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
929 Expr *pE = pItem->pExpr;
930 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000931 if( iCol>0 ){
932 /* If an AS-name match is found, mark this ORDER BY column as being
933 ** a copy of the iCol-th result-set column. The subsequent call to
934 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
935 ** copy of the iCol-th result-set expression. */
drh4b3ac732011-12-10 23:18:32 +0000936 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000937 continue;
938 }
939 if( sqlite3ExprIsInteger(pE, &iCol) ){
940 /* The ORDER BY term is an integer constant. Again, set the column
941 ** number so that sqlite3ResolveOrderGroupBy() will convert the
942 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000943 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000944 resolveOutOfRangeError(pParse, zType, i+1, nResult);
945 return 1;
946 }
drh4b3ac732011-12-10 23:18:32 +0000947 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000948 continue;
949 }
950
951 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +0000952 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +0000953 if( sqlite3ResolveExprNames(pNC, pE) ){
954 return 1;
955 }
drh70331cd2012-04-27 01:09:06 +0000956 for(j=0; j<pSelect->pEList->nExpr; j++){
957 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
958 pItem->iOrderByCol = j+1;
959 }
960 }
drh7d10d5a2008-08-20 16:35:10 +0000961 }
962 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
963}
964
965/*
966** Resolve names in the SELECT statement p and all of its descendents.
967*/
968static int resolveSelectStep(Walker *pWalker, Select *p){
969 NameContext *pOuterNC; /* Context that contains this SELECT */
970 NameContext sNC; /* Name context of this SELECT */
971 int isCompound; /* True if p is a compound select */
972 int nCompound; /* Number of compound terms processed so far */
973 Parse *pParse; /* Parsing context */
974 ExprList *pEList; /* Result set expression list */
975 int i; /* Loop counter */
976 ExprList *pGroupBy; /* The GROUP BY clause */
977 Select *pLeftmost; /* Left-most of SELECT of a compound */
978 sqlite3 *db; /* Database connection */
979
980
drh0a846f92008-08-25 17:23:29 +0000981 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000982 if( p->selFlags & SF_Resolved ){
983 return WRC_Prune;
984 }
985 pOuterNC = pWalker->u.pNC;
986 pParse = pWalker->pParse;
987 db = pParse->db;
988
989 /* Normally sqlite3SelectExpand() will be called first and will have
990 ** already expanded this SELECT. However, if this is a subquery within
991 ** an expression, sqlite3ResolveExprNames() will be called without a
992 ** prior call to sqlite3SelectExpand(). When that happens, let
993 ** sqlite3SelectPrep() do all of the processing for this SELECT.
994 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
995 ** this routine in the correct order.
996 */
997 if( (p->selFlags & SF_Expanded)==0 ){
998 sqlite3SelectPrep(pParse, p, pOuterNC);
999 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1000 }
1001
1002 isCompound = p->pPrior!=0;
1003 nCompound = 0;
1004 pLeftmost = p;
1005 while( p ){
1006 assert( (p->selFlags & SF_Expanded)!=0 );
1007 assert( (p->selFlags & SF_Resolved)==0 );
1008 p->selFlags |= SF_Resolved;
1009
1010 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1011 ** are not allowed to refer to any names, so pass an empty NameContext.
1012 */
1013 memset(&sNC, 0, sizeof(sNC));
1014 sNC.pParse = pParse;
1015 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1016 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1017 return WRC_Abort;
1018 }
1019
1020 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1021 ** resolve the result-set expression list.
1022 */
drha51009b2012-05-21 19:11:25 +00001023 sNC.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001024 sNC.pSrcList = p->pSrc;
1025 sNC.pNext = pOuterNC;
1026
1027 /* Resolve names in the result set. */
1028 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +00001029 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001030 for(i=0; i<pEList->nExpr; i++){
1031 Expr *pX = pEList->a[i].pExpr;
1032 if( sqlite3ResolveExprNames(&sNC, pX) ){
1033 return WRC_Abort;
1034 }
1035 }
1036
1037 /* Recursively resolve names in all subqueries
1038 */
1039 for(i=0; i<p->pSrc->nSrc; i++){
1040 struct SrcList_item *pItem = &p->pSrc->a[i];
1041 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001042 NameContext *pNC; /* Used to iterate name contexts */
1043 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001044 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001045
1046 /* Count the total number of references to pOuterNC and all of its
1047 ** parent contexts. After resolving references to expressions in
1048 ** pItem->pSelect, check if this value has changed. If so, then
1049 ** SELECT statement pItem->pSelect must be correlated. Set the
1050 ** pItem->isCorrelated flag if this is the case. */
1051 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1052
drh7d10d5a2008-08-20 16:35:10 +00001053 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001054 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001055 pParse->zAuthContext = zSavedContext;
1056 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001057
1058 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1059 assert( pItem->isCorrelated==0 && nRef<=0 );
1060 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001061 }
1062 }
1063
1064 /* If there are no aggregate functions in the result-set, and no GROUP BY
1065 ** expression, do not allow aggregates in any of the other expressions.
1066 */
1067 assert( (p->selFlags & SF_Aggregate)==0 );
1068 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:25 +00001069 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +00001070 p->selFlags |= SF_Aggregate;
1071 }else{
drha51009b2012-05-21 19:11:25 +00001072 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001073 }
1074
1075 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1076 */
1077 if( p->pHaving && !pGroupBy ){
1078 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1079 return WRC_Abort;
1080 }
1081
1082 /* Add the expression list to the name-context before parsing the
1083 ** other expressions in the SELECT statement. This is so that
1084 ** expressions in the WHERE clause (etc.) can refer to expressions by
1085 ** aliases in the result set.
1086 **
1087 ** Minor point: If this is the case, then the expression will be
1088 ** re-evaluated for each reference to it.
1089 */
1090 sNC.pEList = p->pEList;
1091 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1092 sqlite3ResolveExprNames(&sNC, p->pHaving)
1093 ){
1094 return WRC_Abort;
1095 }
1096
1097 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1098 ** outer queries
1099 */
1100 sNC.pNext = 0;
drha51009b2012-05-21 19:11:25 +00001101 sNC.ncFlags |= NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001102
1103 /* Process the ORDER BY clause for singleton SELECT statements.
1104 ** The ORDER BY clause for compounds SELECT statements is handled
1105 ** below, after all of the result-sets for all of the elements of
1106 ** the compound have been resolved.
1107 */
1108 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1109 return WRC_Abort;
1110 }
1111 if( db->mallocFailed ){
1112 return WRC_Abort;
1113 }
1114
1115 /* Resolve the GROUP BY clause. At the same time, make sure
1116 ** the GROUP BY clause does not contain aggregate functions.
1117 */
1118 if( pGroupBy ){
1119 struct ExprList_item *pItem;
1120
1121 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1122 return WRC_Abort;
1123 }
1124 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1125 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1126 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1127 "the GROUP BY clause");
1128 return WRC_Abort;
1129 }
1130 }
1131 }
1132
1133 /* Advance to the next term of the compound
1134 */
1135 p = p->pPrior;
1136 nCompound++;
1137 }
1138
1139 /* Resolve the ORDER BY on a compound SELECT after all terms of
1140 ** the compound have been resolved.
1141 */
1142 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1143 return WRC_Abort;
1144 }
1145
1146 return WRC_Prune;
1147}
1148
1149/*
1150** This routine walks an expression tree and resolves references to
1151** table columns and result-set columns. At the same time, do error
1152** checking on function usage and set a flag if any aggregate functions
1153** are seen.
1154**
1155** To resolve table columns references we look for nodes (or subtrees) of the
1156** form X.Y.Z or Y.Z or just Z where
1157**
1158** X: The name of a database. Ex: "main" or "temp" or
1159** the symbolic name assigned to an ATTACH-ed database.
1160**
1161** Y: The name of a table in a FROM clause. Or in a trigger
1162** one of the special names "old" or "new".
1163**
1164** Z: The name of a column in table Y.
1165**
1166** The node at the root of the subtree is modified as follows:
1167**
1168** Expr.op Changed to TK_COLUMN
1169** Expr.pTab Points to the Table object for X.Y
1170** Expr.iColumn The column index in X.Y. -1 for the rowid.
1171** Expr.iTable The VDBE cursor number for X.Y
1172**
1173**
1174** To resolve result-set references, look for expression nodes of the
1175** form Z (with no X and Y prefix) where the Z matches the right-hand
1176** size of an AS clause in the result-set of a SELECT. The Z expression
1177** is replaced by a copy of the left-hand side of the result-set expression.
1178** Table-name and function resolution occurs on the substituted expression
1179** tree. For example, in:
1180**
1181** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1182**
1183** The "x" term of the order by is replaced by "a+b" to render:
1184**
1185** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1186**
1187** Function calls are checked to make sure that the function is
1188** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:25 +00001189** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:10 +00001190** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1191** If an expression contains aggregate functions then the EP_Agg
1192** property on the expression is set.
1193**
1194** An error message is left in pParse if anything is amiss. The number
1195** if errors is returned.
1196*/
1197int sqlite3ResolveExprNames(
1198 NameContext *pNC, /* Namespace to resolve expressions in. */
1199 Expr *pExpr /* The expression to be analyzed. */
1200){
drha51009b2012-05-21 19:11:25 +00001201 u8 savedHasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001202 Walker w;
1203
1204 if( pExpr==0 ) return 0;
1205#if SQLITE_MAX_EXPR_DEPTH>0
1206 {
1207 Parse *pParse = pNC->pParse;
1208 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1209 return 1;
1210 }
1211 pParse->nHeight += pExpr->nHeight;
1212 }
1213#endif
drha51009b2012-05-21 19:11:25 +00001214 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1215 pNC->ncFlags &= ~NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001216 w.xExprCallback = resolveExprStep;
1217 w.xSelectCallback = resolveSelectStep;
1218 w.pParse = pNC->pParse;
1219 w.u.pNC = pNC;
1220 sqlite3WalkExpr(&w, pExpr);
1221#if SQLITE_MAX_EXPR_DEPTH>0
1222 pNC->pParse->nHeight -= pExpr->nHeight;
1223#endif
drhfd773cf2009-05-29 14:39:07 +00001224 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001225 ExprSetProperty(pExpr, EP_Error);
1226 }
drha51009b2012-05-21 19:11:25 +00001227 if( pNC->ncFlags & NC_HasAgg ){
drh7d10d5a2008-08-20 16:35:10 +00001228 ExprSetProperty(pExpr, EP_Agg);
1229 }else if( savedHasAgg ){
drha51009b2012-05-21 19:11:25 +00001230 pNC->ncFlags |= NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001231 }
1232 return ExprHasProperty(pExpr, EP_Error);
1233}
drh7d10d5a2008-08-20 16:35:10 +00001234
1235
1236/*
1237** Resolve all names in all expressions of a SELECT and in all
1238** decendents of the SELECT, including compounds off of p->pPrior,
1239** subqueries in expressions, and subqueries used as FROM clause
1240** terms.
1241**
1242** See sqlite3ResolveExprNames() for a description of the kinds of
1243** transformations that occur.
1244**
1245** All SELECT statements should have been expanded using
1246** sqlite3SelectExpand() prior to invoking this routine.
1247*/
1248void sqlite3ResolveSelectNames(
1249 Parse *pParse, /* The parser context */
1250 Select *p, /* The SELECT statement being coded. */
1251 NameContext *pOuterNC /* Name context for parent SELECT statement */
1252){
1253 Walker w;
1254
drh0a846f92008-08-25 17:23:29 +00001255 assert( p!=0 );
1256 w.xExprCallback = resolveExprStep;
1257 w.xSelectCallback = resolveSelectStep;
1258 w.pParse = pParse;
1259 w.u.pNC = pOuterNC;
1260 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001261}