blob: b87d231ac2eb57dec51b3c7142efd0a7455b688e [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 }
117 if( pExpr->flags & EP_ExpCollate ){
118 pDup->pColl = pExpr->pColl;
119 pDup->flags |= EP_ExpCollate;
120 }
danf6963f92009-11-23 14:39:14 +0000121
122 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
123 ** prevents ExprDelete() from deleting the Expr structure itself,
124 ** allowing it to be repopulated by the memcpy() on the following line.
125 */
126 ExprSetProperty(pExpr, EP_Static);
127 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +0000128 memcpy(pExpr, pDup, sizeof(*pExpr));
129 sqlite3DbFree(db, pDup);
130}
131
drhe802c5d2011-10-18 18:10:40 +0000132
133/*
134** Return TRUE if the name zCol occurs anywhere in the USING clause.
135**
136** Return FALSE if the USING clause is NULL or if it does not contain
137** zCol.
138*/
139static int nameInUsingClause(IdList *pUsing, const char *zCol){
140 if( pUsing ){
141 int k;
142 for(k=0; k<pUsing->nId; k++){
143 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
144 }
145 }
146 return 0;
147}
148
149
drh8b213892008-08-29 02:14:02 +0000150/*
drh7d10d5a2008-08-20 16:35:10 +0000151** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
152** that name in the set of source tables in pSrcList and make the pExpr
153** expression node refer back to that source column. The following changes
154** are made to pExpr:
155**
156** pExpr->iDb Set the index in db->aDb[] of the database X
157** (even if X is implied).
158** pExpr->iTable Set to the cursor number for the table obtained
159** from pSrcList.
160** pExpr->pTab Points to the Table structure of X.Y (even if
161** X and/or Y are implied.)
162** pExpr->iColumn Set to the column number within the table.
163** pExpr->op Set to TK_COLUMN.
164** pExpr->pLeft Any expression this points to is deleted
165** pExpr->pRight Any expression this points to is deleted.
166**
drhb7916a72009-05-27 10:31:29 +0000167** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000168** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000169** can be used. The zTable variable is the name of the table (the "Y"). This
170** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000171** means that the form of the name is Z and that columns from any table
172** can be used.
173**
174** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000175** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000176*/
177static int lookupName(
178 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000179 const char *zDb, /* Name of the database containing table, or NULL */
180 const char *zTab, /* Name of table containing column, or NULL */
181 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000182 NameContext *pNC, /* The name context used to resolve the name */
183 Expr *pExpr /* Make this EXPR node point to the selected column */
184){
drhed551b92012-08-23 19:46:11 +0000185 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000186 int cnt = 0; /* Number of matching column names */
187 int cntTab = 0; /* Number of matching table names */
drhed551b92012-08-23 19:46:11 +0000188 int nSubquery = 0; /* How many levels of subquery */
drh7d10d5a2008-08-20 16:35:10 +0000189 sqlite3 *db = pParse->db; /* The database connection */
190 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
191 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
192 NameContext *pTopNC = pNC; /* First namecontext in the list */
193 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000194 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000195
drhb7916a72009-05-27 10:31:29 +0000196 assert( pNC ); /* the name context cannot be NULL. */
197 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh33e619f2009-05-28 01:00:55 +0000198 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000199
200 /* Initialize the node to no-match */
201 pExpr->iTable = -1;
202 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000203 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000204
205 /* Start at the inner-most context and move outward until a match is found */
206 while( pNC && cnt==0 ){
207 ExprList *pEList;
208 SrcList *pSrcList = pNC->pSrcList;
209
210 if( pSrcList ){
211 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
212 Table *pTab;
213 int iDb;
214 Column *pCol;
215
216 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000217 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000218 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
219 assert( pTab->nCol>0 );
220 if( zTab ){
221 if( pItem->zAlias ){
222 char *zTabName = pItem->zAlias;
223 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
224 }else{
225 char *zTabName = pTab->zName;
drh73c0fdc2009-06-15 18:32:36 +0000226 if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
227 continue;
228 }
drh7d10d5a2008-08-20 16:35:10 +0000229 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
230 continue;
231 }
232 }
233 }
234 if( 0==(cntTab++) ){
235 pExpr->iTable = pItem->iCursor;
236 pExpr->pTab = pTab;
237 pSchema = pTab->pSchema;
238 pMatch = pItem;
239 }
240 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
241 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
drhe802c5d2011-10-18 18:10:40 +0000242 /* If there has been exactly one prior match and this match
243 ** is for the right-hand table of a NATURAL JOIN or is in a
244 ** USING clause, then skip this match.
245 */
246 if( cnt==1 ){
247 if( pItem->jointype & JT_NATURAL ) continue;
248 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
249 }
drh7d10d5a2008-08-20 16:35:10 +0000250 cnt++;
251 pExpr->iTable = pItem->iCursor;
252 pExpr->pTab = pTab;
253 pMatch = pItem;
254 pSchema = pTab->pSchema;
255 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000256 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000257 break;
258 }
259 }
260 }
261 }
262
263#ifndef SQLITE_OMIT_TRIGGER
264 /* If we have not already resolved the name, then maybe
265 ** it is a new.* or old.* trigger argument reference
266 */
dan165921a2009-08-28 18:53:45 +0000267 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000268 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000269 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000270 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
271 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000272 pExpr->iTable = 1;
273 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000274 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000275 pExpr->iTable = 0;
276 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000277 }
278
279 if( pTab ){
280 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000281 pSchema = pTab->pSchema;
282 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000283 for(iCol=0; iCol<pTab->nCol; iCol++){
284 Column *pCol = &pTab->aCol[iCol];
285 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
286 if( iCol==pTab->iPKey ){
287 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000288 }
drh25e978d2009-12-29 23:39:04 +0000289 break;
drh7d10d5a2008-08-20 16:35:10 +0000290 }
291 }
drh25e978d2009-12-29 23:39:04 +0000292 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000293 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000294 }
dan2bd93512009-08-31 08:22:46 +0000295 if( iCol<pTab->nCol ){
296 cnt++;
297 if( iCol<0 ){
298 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000299 }else if( pExpr->iTable==0 ){
300 testcase( iCol==31 );
301 testcase( iCol==32 );
302 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000303 }else{
304 testcase( iCol==31 );
305 testcase( iCol==32 );
306 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000307 }
shanecea72b22009-09-07 04:38:36 +0000308 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000309 pExpr->pTab = pTab;
310 isTrigger = 1;
311 }
drh7d10d5a2008-08-20 16:35:10 +0000312 }
313 }
314#endif /* !defined(SQLITE_OMIT_TRIGGER) */
315
316 /*
317 ** Perhaps the name is a reference to the ROWID
318 */
319 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
320 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000321 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000322 pExpr->affinity = SQLITE_AFF_INTEGER;
323 }
324
325 /*
326 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
327 ** might refer to an result-set alias. This happens, for example, when
328 ** we are resolving names in the WHERE clause of the following command:
329 **
330 ** SELECT a+b AS x FROM table WHERE x<10;
331 **
332 ** In cases like this, replace pExpr with a copy of the expression that
333 ** forms the result set entry ("a+b" in the example) and return immediately.
334 ** Note that the expression in the result set should have already been
335 ** resolved by the time the WHERE clause is resolved.
336 */
337 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
338 for(j=0; j<pEList->nExpr; j++){
339 char *zAs = pEList->a[j].zName;
340 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000341 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000342 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000343 assert( pExpr->x.pList==0 );
344 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000345 pOrig = pEList->a[j].pExpr;
drha51009b2012-05-21 19:11:25 +0000346 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10 +0000347 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000348 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000349 }
drhed551b92012-08-23 19:46:11 +0000350 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
drh7d10d5a2008-08-20 16:35:10 +0000351 cnt = 1;
352 pMatch = 0;
353 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000354 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000355 }
356 }
357 }
358
359 /* Advance to the next name context. The loop will exit when either
360 ** we have a match (cnt>0) or when we run out of name contexts.
361 */
362 if( cnt==0 ){
363 pNC = pNC->pNext;
drhed551b92012-08-23 19:46:11 +0000364 nSubquery++;
drh7d10d5a2008-08-20 16:35:10 +0000365 }
366 }
367
368 /*
369 ** If X and Y are NULL (in other words if only the column name Z is
370 ** supplied) and the value of Z is enclosed in double-quotes, then
371 ** Z is a string literal if it doesn't match any column names. In that
372 ** case, we need to return right away and not make any changes to
373 ** pExpr.
374 **
375 ** Because no reference was made to outer contexts, the pNC->nRef
376 ** fields are not changed in any context.
377 */
drh24fb6272009-05-01 21:13:36 +0000378 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000379 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000380 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000381 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000382 }
383
384 /*
385 ** cnt==0 means there was not match. cnt>1 means there were two or
386 ** more matches. Either way, we have an error.
387 */
388 if( cnt!=1 ){
389 const char *zErr;
390 zErr = cnt==0 ? "no such column" : "ambiguous column name";
391 if( zDb ){
392 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
393 }else if( zTab ){
394 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
395 }else{
396 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
397 }
dan1db95102010-06-28 10:15:19 +0000398 pParse->checkSchema = 1;
drh7d10d5a2008-08-20 16:35:10 +0000399 pTopNC->nErr++;
400 }
401
402 /* If a column from a table in pSrcList is referenced, then record
403 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
404 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
405 ** column number is greater than the number of bits in the bitmask
406 ** then set the high-order bit of the bitmask.
407 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000408 if( pExpr->iColumn>=0 && pMatch!=0 ){
409 int n = pExpr->iColumn;
410 testcase( n==BMS-1 );
411 if( n>=BMS ){
412 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000413 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000414 assert( pMatch->iCursor==pExpr->iTable );
415 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000416 }
417
drh7d10d5a2008-08-20 16:35:10 +0000418 /* Clean up and return
419 */
drh7d10d5a2008-08-20 16:35:10 +0000420 sqlite3ExprDelete(db, pExpr->pLeft);
421 pExpr->pLeft = 0;
422 sqlite3ExprDelete(db, pExpr->pRight);
423 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000424 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000425lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000426 if( cnt==1 ){
427 assert( pNC!=0 );
428 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
429 /* Increment the nRef value on all name contexts from TopNC up to
430 ** the point where the name matched. */
431 for(;;){
432 assert( pTopNC!=0 );
433 pTopNC->nRef++;
434 if( pTopNC==pNC ) break;
435 pTopNC = pTopNC->pNext;
436 }
drhf7828b52009-06-15 23:15:59 +0000437 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000438 } else {
drhf7828b52009-06-15 23:15:59 +0000439 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000440 }
441}
442
443/*
danf7b0b0a2009-10-19 15:52:32 +0000444** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34 +0000445** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32 +0000446*/
447Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
448 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
449 if( p ){
450 struct SrcList_item *pItem = &pSrc->a[iSrc];
451 p->pTab = pItem->pTab;
452 p->iTable = pItem->iCursor;
453 if( p->pTab->iPKey==iCol ){
454 p->iColumn = -1;
455 }else{
drh8677d302009-11-04 13:17:14 +0000456 p->iColumn = (ynVar)iCol;
drh7caba662010-04-08 15:01:44 +0000457 testcase( iCol==BMS );
458 testcase( iCol==BMS-1 );
danf7b0b0a2009-10-19 15:52:32 +0000459 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
460 }
461 ExprSetProperty(p, EP_Resolved);
462 }
463 return p;
464}
465
466/*
drh7d10d5a2008-08-20 16:35:10 +0000467** This routine is callback for sqlite3WalkExpr().
468**
469** Resolve symbolic names into TK_COLUMN operators for the current
470** node in the expression tree. Return 0 to continue the search down
471** the tree or 2 to abort the tree walk.
472**
473** This routine also does error checking and name resolution for
474** function names. The operator for aggregate functions is changed
475** to TK_AGG_FUNCTION.
476*/
477static int resolveExprStep(Walker *pWalker, Expr *pExpr){
478 NameContext *pNC;
479 Parse *pParse;
480
drh7d10d5a2008-08-20 16:35:10 +0000481 pNC = pWalker->u.pNC;
482 assert( pNC!=0 );
483 pParse = pNC->pParse;
484 assert( pParse==pWalker->pParse );
485
486 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
487 ExprSetProperty(pExpr, EP_Resolved);
488#ifndef NDEBUG
489 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
490 SrcList *pSrcList = pNC->pSrcList;
491 int i;
492 for(i=0; i<pNC->pSrcList->nSrc; i++){
493 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
494 }
495 }
496#endif
497 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000498
shane273f6192008-10-10 04:34:16 +0000499#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000500 /* The special operator TK_ROW means use the rowid for the first
501 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
502 ** clause processing on UPDATE and DELETE statements.
503 */
504 case TK_ROW: {
505 SrcList *pSrcList = pNC->pSrcList;
506 struct SrcList_item *pItem;
507 assert( pSrcList && pSrcList->nSrc==1 );
508 pItem = pSrcList->a;
509 pExpr->op = TK_COLUMN;
510 pExpr->pTab = pItem->pTab;
511 pExpr->iTable = pItem->iCursor;
512 pExpr->iColumn = -1;
513 pExpr->affinity = SQLITE_AFF_INTEGER;
514 break;
515 }
shane273f6192008-10-10 04:34:16 +0000516#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000517
drh7d10d5a2008-08-20 16:35:10 +0000518 /* A lone identifier is the name of a column.
519 */
520 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000521 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000522 }
523
524 /* A table name and column name: ID.ID
525 ** Or a database, table and column: ID.ID.ID
526 */
527 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000528 const char *zColumn;
529 const char *zTable;
530 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000531 Expr *pRight;
532
533 /* if( pSrcList==0 ) break; */
534 pRight = pExpr->pRight;
535 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000536 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000537 zTable = pExpr->pLeft->u.zToken;
538 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000539 }else{
540 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000541 zDb = pExpr->pLeft->u.zToken;
542 zTable = pRight->pLeft->u.zToken;
543 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000544 }
drhf7828b52009-06-15 23:15:59 +0000545 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000546 }
547
548 /* Resolve function names
549 */
550 case TK_CONST_FUNC:
551 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000552 ExprList *pList = pExpr->x.pList; /* The argument list */
553 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000554 int no_such_func = 0; /* True if no such function exists */
555 int wrong_num_args = 0; /* True if wrong number of arguments */
556 int is_agg = 0; /* True if is an aggregate function */
557 int auth; /* Authorization to use the function */
558 int nId; /* Number of characters in function name */
559 const char *zId; /* The function name. */
560 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000561 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000562
drh73c0fdc2009-06-15 18:32:36 +0000563 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000564 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000565 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000566 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000567 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
568 if( pDef==0 ){
drh89d5d6a2012-04-07 00:09:21 +0000569 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:10 +0000570 if( pDef==0 ){
571 no_such_func = 1;
572 }else{
573 wrong_num_args = 1;
574 }
575 }else{
576 is_agg = pDef->xFunc==0;
577 }
578#ifndef SQLITE_OMIT_AUTHORIZATION
579 if( pDef ){
580 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
581 if( auth!=SQLITE_OK ){
582 if( auth==SQLITE_DENY ){
583 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
584 pDef->zName);
585 pNC->nErr++;
586 }
587 pExpr->op = TK_NULL;
588 return WRC_Prune;
589 }
590 }
591#endif
drha51009b2012-05-21 19:11:25 +0000592 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000593 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
594 pNC->nErr++;
595 is_agg = 0;
596 }else if( no_such_func ){
597 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
598 pNC->nErr++;
599 }else if( wrong_num_args ){
600 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
601 nId, zId);
602 pNC->nErr++;
603 }
drha51009b2012-05-21 19:11:25 +0000604 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000605 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:10 +0000606 if( is_agg ){
607 NameContext *pNC2 = pNC;
608 pExpr->op = TK_AGG_FUNCTION;
609 pExpr->op2 = 0;
610 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
611 pExpr->op2++;
612 pNC2 = pNC2->pNext;
613 }
614 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
615 pNC->ncFlags |= NC_AllowAgg;
616 }
drh7d10d5a2008-08-20 16:35:10 +0000617 /* FIX ME: Compute pExpr->affinity based on the expected return
618 ** type of the function
619 */
620 return WRC_Prune;
621 }
622#ifndef SQLITE_OMIT_SUBQUERY
623 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000624 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000625#endif
626 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000627 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000628 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000629 int nRef = pNC->nRef;
630#ifndef SQLITE_OMIT_CHECK
drha51009b2012-05-21 19:11:25 +0000631 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000632 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
633 }
634#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000635 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000636 assert( pNC->nRef>=nRef );
637 if( nRef!=pNC->nRef ){
638 ExprSetProperty(pExpr, EP_VarSelect);
639 }
640 }
641 break;
642 }
643#ifndef SQLITE_OMIT_CHECK
644 case TK_VARIABLE: {
drha51009b2012-05-21 19:11:25 +0000645 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +0000646 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
647 }
648 break;
649 }
650#endif
651 }
652 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
653}
654
655/*
656** pEList is a list of expressions which are really the result set of the
657** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
658** This routine checks to see if pE is a simple identifier which corresponds
659** to the AS-name of one of the terms of the expression list. If it is,
660** this routine return an integer between 1 and N where N is the number of
661** elements in pEList, corresponding to the matching entry. If there is
662** no match, or if pE is not a simple identifier, then this routine
663** return 0.
664**
665** pEList has been resolved. pE has not.
666*/
667static int resolveAsName(
668 Parse *pParse, /* Parsing context for error messages */
669 ExprList *pEList, /* List of expressions to scan */
670 Expr *pE /* Expression we are trying to match */
671){
672 int i; /* Loop counter */
673
shanecf697392009-06-01 16:53:09 +0000674 UNUSED_PARAMETER(pParse);
675
drh73c0fdc2009-06-15 18:32:36 +0000676 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000677 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000678 for(i=0; i<pEList->nExpr; i++){
679 char *zAs = pEList->a[i].zName;
680 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000681 return i+1;
682 }
683 }
drh7d10d5a2008-08-20 16:35:10 +0000684 }
685 return 0;
686}
687
688/*
689** pE is a pointer to an expression which is a single term in the
690** ORDER BY of a compound SELECT. The expression has not been
691** name resolved.
692**
693** At the point this routine is called, we already know that the
694** ORDER BY term is not an integer index into the result set. That
695** case is handled by the calling routine.
696**
697** Attempt to match pE against result set columns in the left-most
698** SELECT statement. Return the index i of the matching column,
699** as an indication to the caller that it should sort by the i-th column.
700** The left-most column is 1. In other words, the value returned is the
701** same integer value that would be used in the SQL statement to indicate
702** the column.
703**
704** If there is no match, return 0. Return -1 if an error occurs.
705*/
706static int resolveOrderByTermToExprList(
707 Parse *pParse, /* Parsing context for error messages */
708 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
709 Expr *pE /* The specific ORDER BY term */
710){
711 int i; /* Loop counter */
712 ExprList *pEList; /* The columns of the result set */
713 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000714 sqlite3 *db; /* Database connection */
715 int rc; /* Return code from subprocedures */
716 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000717
718 assert( sqlite3ExprIsInteger(pE, &i)==0 );
719 pEList = pSelect->pEList;
720
721 /* Resolve all names in the ORDER BY term expression
722 */
723 memset(&nc, 0, sizeof(nc));
724 nc.pParse = pParse;
725 nc.pSrcList = pSelect->pSrc;
726 nc.pEList = pEList;
drha51009b2012-05-21 19:11:25 +0000727 nc.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000728 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000729 db = pParse->db;
730 savedSuppErr = db->suppressErr;
731 db->suppressErr = 1;
732 rc = sqlite3ResolveExprNames(&nc, pE);
733 db->suppressErr = savedSuppErr;
734 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000735
736 /* Try to match the ORDER BY expression against an expression
737 ** in the result set. Return an 1-based index of the matching
738 ** result-set entry.
739 */
740 for(i=0; i<pEList->nExpr; i++){
drh1d9da702010-01-07 15:17:02 +0000741 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000742 return i+1;
743 }
744 }
745
746 /* If no match, return 0. */
747 return 0;
748}
749
750/*
751** Generate an ORDER BY or GROUP BY term out-of-range error.
752*/
753static void resolveOutOfRangeError(
754 Parse *pParse, /* The error context into which to write the error */
755 const char *zType, /* "ORDER" or "GROUP" */
756 int i, /* The index (1-based) of the term out of range */
757 int mx /* Largest permissible value of i */
758){
759 sqlite3ErrorMsg(pParse,
760 "%r %s BY term out of range - should be "
761 "between 1 and %d", i, zType, mx);
762}
763
764/*
765** Analyze the ORDER BY clause in a compound SELECT statement. Modify
766** each term of the ORDER BY clause is a constant integer between 1
767** and N where N is the number of columns in the compound SELECT.
768**
769** ORDER BY terms that are already an integer between 1 and N are
770** unmodified. ORDER BY terms that are integers outside the range of
771** 1 through N generate an error. ORDER BY terms that are expressions
772** are matched against result set expressions of compound SELECT
773** beginning with the left-most SELECT and working toward the right.
774** At the first match, the ORDER BY expression is transformed into
775** the integer column number.
776**
777** Return the number of errors seen.
778*/
779static int resolveCompoundOrderBy(
780 Parse *pParse, /* Parsing context. Leave error messages here */
781 Select *pSelect /* The SELECT statement containing the ORDER BY */
782){
783 int i;
784 ExprList *pOrderBy;
785 ExprList *pEList;
786 sqlite3 *db;
787 int moreToDo = 1;
788
789 pOrderBy = pSelect->pOrderBy;
790 if( pOrderBy==0 ) return 0;
791 db = pParse->db;
792#if SQLITE_MAX_COLUMN
793 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
794 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
795 return 1;
796 }
797#endif
798 for(i=0; i<pOrderBy->nExpr; i++){
799 pOrderBy->a[i].done = 0;
800 }
801 pSelect->pNext = 0;
802 while( pSelect->pPrior ){
803 pSelect->pPrior->pNext = pSelect;
804 pSelect = pSelect->pPrior;
805 }
806 while( pSelect && moreToDo ){
807 struct ExprList_item *pItem;
808 moreToDo = 0;
809 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000810 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000811 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
812 int iCol = -1;
813 Expr *pE, *pDup;
814 if( pItem->done ) continue;
815 pE = pItem->pExpr;
816 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000817 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000818 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
819 return 1;
820 }
821 }else{
822 iCol = resolveAsName(pParse, pEList, pE);
823 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000824 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000825 if( !db->mallocFailed ){
826 assert(pDup);
827 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
828 }
829 sqlite3ExprDelete(db, pDup);
830 }
drh7d10d5a2008-08-20 16:35:10 +0000831 }
832 if( iCol>0 ){
833 CollSeq *pColl = pE->pColl;
834 int flags = pE->flags & EP_ExpCollate;
835 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000836 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000837 if( pE==0 ) return 1;
838 pE->pColl = pColl;
839 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000840 pE->u.iValue = iCol;
drh4b3ac732011-12-10 23:18:32 +0000841 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000842 pItem->done = 1;
843 }else{
844 moreToDo = 1;
845 }
846 }
847 pSelect = pSelect->pNext;
848 }
849 for(i=0; i<pOrderBy->nExpr; i++){
850 if( pOrderBy->a[i].done==0 ){
851 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
852 "column in the result set", i+1);
853 return 1;
854 }
855 }
856 return 0;
857}
858
859/*
860** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
861** the SELECT statement pSelect. If any term is reference to a
862** result set expression (as determined by the ExprList.a.iCol field)
863** then convert that term into a copy of the corresponding result set
864** column.
865**
866** If any errors are detected, add an error message to pParse and
867** return non-zero. Return zero if no errors are seen.
868*/
869int sqlite3ResolveOrderGroupBy(
870 Parse *pParse, /* Parsing context. Leave error messages here */
871 Select *pSelect, /* The SELECT statement containing the clause */
872 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
873 const char *zType /* "ORDER" or "GROUP" */
874){
875 int i;
876 sqlite3 *db = pParse->db;
877 ExprList *pEList;
878 struct ExprList_item *pItem;
879
880 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
881#if SQLITE_MAX_COLUMN
882 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
883 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
884 return 1;
885 }
886#endif
887 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000888 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000889 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +0000890 if( pItem->iOrderByCol ){
891 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000892 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
893 return 1;
894 }
drhed551b92012-08-23 19:46:11 +0000895 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
drh7d10d5a2008-08-20 16:35:10 +0000896 }
897 }
898 return 0;
899}
900
901/*
902** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
903** The Name context of the SELECT statement is pNC. zType is either
904** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
905**
906** This routine resolves each term of the clause into an expression.
907** If the order-by term is an integer I between 1 and N (where N is the
908** number of columns in the result set of the SELECT) then the expression
909** in the resolution is a copy of the I-th result-set expression. If
910** the order-by term is an identify that corresponds to the AS-name of
911** a result-set expression, then the term resolves to a copy of the
912** result-set expression. Otherwise, the expression is resolved in
913** the usual way - using sqlite3ResolveExprNames().
914**
915** This routine returns the number of errors. If errors occur, then
916** an appropriate error message might be left in pParse. (OOM errors
917** excepted.)
918*/
919static int resolveOrderGroupBy(
920 NameContext *pNC, /* The name context of the SELECT statement */
921 Select *pSelect, /* The SELECT statement holding pOrderBy */
922 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
923 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
924){
drh70331cd2012-04-27 01:09:06 +0000925 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000926 int iCol; /* Column number */
927 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
928 Parse *pParse; /* Parsing context */
929 int nResult; /* Number of terms in the result set */
930
931 if( pOrderBy==0 ) return 0;
932 nResult = pSelect->pEList->nExpr;
933 pParse = pNC->pParse;
934 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
935 Expr *pE = pItem->pExpr;
936 iCol = resolveAsName(pParse, pSelect->pEList, pE);
drh7d10d5a2008-08-20 16:35:10 +0000937 if( iCol>0 ){
938 /* If an AS-name match is found, mark this ORDER BY column as being
939 ** a copy of the iCol-th result-set column. The subsequent call to
940 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
941 ** copy of the iCol-th result-set expression. */
drh4b3ac732011-12-10 23:18:32 +0000942 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000943 continue;
944 }
945 if( sqlite3ExprIsInteger(pE, &iCol) ){
946 /* The ORDER BY term is an integer constant. Again, set the column
947 ** number so that sqlite3ResolveOrderGroupBy() will convert the
948 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000949 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000950 resolveOutOfRangeError(pParse, zType, i+1, nResult);
951 return 1;
952 }
drh4b3ac732011-12-10 23:18:32 +0000953 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000954 continue;
955 }
956
957 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +0000958 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +0000959 if( sqlite3ResolveExprNames(pNC, pE) ){
960 return 1;
961 }
drh70331cd2012-04-27 01:09:06 +0000962 for(j=0; j<pSelect->pEList->nExpr; j++){
963 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
964 pItem->iOrderByCol = j+1;
965 }
966 }
drh7d10d5a2008-08-20 16:35:10 +0000967 }
968 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
969}
970
971/*
972** Resolve names in the SELECT statement p and all of its descendents.
973*/
974static int resolveSelectStep(Walker *pWalker, Select *p){
975 NameContext *pOuterNC; /* Context that contains this SELECT */
976 NameContext sNC; /* Name context of this SELECT */
977 int isCompound; /* True if p is a compound select */
978 int nCompound; /* Number of compound terms processed so far */
979 Parse *pParse; /* Parsing context */
980 ExprList *pEList; /* Result set expression list */
981 int i; /* Loop counter */
982 ExprList *pGroupBy; /* The GROUP BY clause */
983 Select *pLeftmost; /* Left-most of SELECT of a compound */
984 sqlite3 *db; /* Database connection */
985
986
drh0a846f92008-08-25 17:23:29 +0000987 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000988 if( p->selFlags & SF_Resolved ){
989 return WRC_Prune;
990 }
991 pOuterNC = pWalker->u.pNC;
992 pParse = pWalker->pParse;
993 db = pParse->db;
994
995 /* Normally sqlite3SelectExpand() will be called first and will have
996 ** already expanded this SELECT. However, if this is a subquery within
997 ** an expression, sqlite3ResolveExprNames() will be called without a
998 ** prior call to sqlite3SelectExpand(). When that happens, let
999 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1000 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1001 ** this routine in the correct order.
1002 */
1003 if( (p->selFlags & SF_Expanded)==0 ){
1004 sqlite3SelectPrep(pParse, p, pOuterNC);
1005 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1006 }
1007
1008 isCompound = p->pPrior!=0;
1009 nCompound = 0;
1010 pLeftmost = p;
1011 while( p ){
1012 assert( (p->selFlags & SF_Expanded)!=0 );
1013 assert( (p->selFlags & SF_Resolved)==0 );
1014 p->selFlags |= SF_Resolved;
1015
1016 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1017 ** are not allowed to refer to any names, so pass an empty NameContext.
1018 */
1019 memset(&sNC, 0, sizeof(sNC));
1020 sNC.pParse = pParse;
1021 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1022 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1023 return WRC_Abort;
1024 }
1025
1026 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1027 ** resolve the result-set expression list.
1028 */
drha51009b2012-05-21 19:11:25 +00001029 sNC.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001030 sNC.pSrcList = p->pSrc;
1031 sNC.pNext = pOuterNC;
1032
1033 /* Resolve names in the result set. */
1034 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +00001035 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001036 for(i=0; i<pEList->nExpr; i++){
1037 Expr *pX = pEList->a[i].pExpr;
1038 if( sqlite3ResolveExprNames(&sNC, pX) ){
1039 return WRC_Abort;
1040 }
1041 }
1042
1043 /* Recursively resolve names in all subqueries
1044 */
1045 for(i=0; i<p->pSrc->nSrc; i++){
1046 struct SrcList_item *pItem = &p->pSrc->a[i];
1047 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001048 NameContext *pNC; /* Used to iterate name contexts */
1049 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001050 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001051
1052 /* Count the total number of references to pOuterNC and all of its
1053 ** parent contexts. After resolving references to expressions in
1054 ** pItem->pSelect, check if this value has changed. If so, then
1055 ** SELECT statement pItem->pSelect must be correlated. Set the
1056 ** pItem->isCorrelated flag if this is the case. */
1057 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1058
drh7d10d5a2008-08-20 16:35:10 +00001059 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001060 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001061 pParse->zAuthContext = zSavedContext;
1062 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001063
1064 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1065 assert( pItem->isCorrelated==0 && nRef<=0 );
1066 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001067 }
1068 }
1069
1070 /* If there are no aggregate functions in the result-set, and no GROUP BY
1071 ** expression, do not allow aggregates in any of the other expressions.
1072 */
1073 assert( (p->selFlags & SF_Aggregate)==0 );
1074 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:25 +00001075 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +00001076 p->selFlags |= SF_Aggregate;
1077 }else{
drha51009b2012-05-21 19:11:25 +00001078 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001079 }
1080
1081 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1082 */
1083 if( p->pHaving && !pGroupBy ){
1084 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1085 return WRC_Abort;
1086 }
1087
1088 /* Add the expression list to the name-context before parsing the
1089 ** other expressions in the SELECT statement. This is so that
1090 ** expressions in the WHERE clause (etc.) can refer to expressions by
1091 ** aliases in the result set.
1092 **
1093 ** Minor point: If this is the case, then the expression will be
1094 ** re-evaluated for each reference to it.
1095 */
1096 sNC.pEList = p->pEList;
1097 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
1098 sqlite3ResolveExprNames(&sNC, p->pHaving)
1099 ){
1100 return WRC_Abort;
1101 }
1102
1103 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1104 ** outer queries
1105 */
1106 sNC.pNext = 0;
drha51009b2012-05-21 19:11:25 +00001107 sNC.ncFlags |= NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001108
1109 /* Process the ORDER BY clause for singleton SELECT statements.
1110 ** The ORDER BY clause for compounds SELECT statements is handled
1111 ** below, after all of the result-sets for all of the elements of
1112 ** the compound have been resolved.
1113 */
1114 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1115 return WRC_Abort;
1116 }
1117 if( db->mallocFailed ){
1118 return WRC_Abort;
1119 }
1120
1121 /* Resolve the GROUP BY clause. At the same time, make sure
1122 ** the GROUP BY clause does not contain aggregate functions.
1123 */
1124 if( pGroupBy ){
1125 struct ExprList_item *pItem;
1126
1127 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1128 return WRC_Abort;
1129 }
1130 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1131 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1132 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1133 "the GROUP BY clause");
1134 return WRC_Abort;
1135 }
1136 }
1137 }
1138
1139 /* Advance to the next term of the compound
1140 */
1141 p = p->pPrior;
1142 nCompound++;
1143 }
1144
1145 /* Resolve the ORDER BY on a compound SELECT after all terms of
1146 ** the compound have been resolved.
1147 */
1148 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1149 return WRC_Abort;
1150 }
1151
1152 return WRC_Prune;
1153}
1154
1155/*
1156** This routine walks an expression tree and resolves references to
1157** table columns and result-set columns. At the same time, do error
1158** checking on function usage and set a flag if any aggregate functions
1159** are seen.
1160**
1161** To resolve table columns references we look for nodes (or subtrees) of the
1162** form X.Y.Z or Y.Z or just Z where
1163**
1164** X: The name of a database. Ex: "main" or "temp" or
1165** the symbolic name assigned to an ATTACH-ed database.
1166**
1167** Y: The name of a table in a FROM clause. Or in a trigger
1168** one of the special names "old" or "new".
1169**
1170** Z: The name of a column in table Y.
1171**
1172** The node at the root of the subtree is modified as follows:
1173**
1174** Expr.op Changed to TK_COLUMN
1175** Expr.pTab Points to the Table object for X.Y
1176** Expr.iColumn The column index in X.Y. -1 for the rowid.
1177** Expr.iTable The VDBE cursor number for X.Y
1178**
1179**
1180** To resolve result-set references, look for expression nodes of the
1181** form Z (with no X and Y prefix) where the Z matches the right-hand
1182** size of an AS clause in the result-set of a SELECT. The Z expression
1183** is replaced by a copy of the left-hand side of the result-set expression.
1184** Table-name and function resolution occurs on the substituted expression
1185** tree. For example, in:
1186**
1187** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1188**
1189** The "x" term of the order by is replaced by "a+b" to render:
1190**
1191** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1192**
1193** Function calls are checked to make sure that the function is
1194** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:25 +00001195** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:10 +00001196** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1197** If an expression contains aggregate functions then the EP_Agg
1198** property on the expression is set.
1199**
1200** An error message is left in pParse if anything is amiss. The number
1201** if errors is returned.
1202*/
1203int sqlite3ResolveExprNames(
1204 NameContext *pNC, /* Namespace to resolve expressions in. */
1205 Expr *pExpr /* The expression to be analyzed. */
1206){
drha51009b2012-05-21 19:11:25 +00001207 u8 savedHasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001208 Walker w;
1209
1210 if( pExpr==0 ) return 0;
1211#if SQLITE_MAX_EXPR_DEPTH>0
1212 {
1213 Parse *pParse = pNC->pParse;
1214 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1215 return 1;
1216 }
1217 pParse->nHeight += pExpr->nHeight;
1218 }
1219#endif
drha51009b2012-05-21 19:11:25 +00001220 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1221 pNC->ncFlags &= ~NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001222 w.xExprCallback = resolveExprStep;
1223 w.xSelectCallback = resolveSelectStep;
1224 w.pParse = pNC->pParse;
1225 w.u.pNC = pNC;
1226 sqlite3WalkExpr(&w, pExpr);
1227#if SQLITE_MAX_EXPR_DEPTH>0
1228 pNC->pParse->nHeight -= pExpr->nHeight;
1229#endif
drhfd773cf2009-05-29 14:39:07 +00001230 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001231 ExprSetProperty(pExpr, EP_Error);
1232 }
drha51009b2012-05-21 19:11:25 +00001233 if( pNC->ncFlags & NC_HasAgg ){
drh7d10d5a2008-08-20 16:35:10 +00001234 ExprSetProperty(pExpr, EP_Agg);
1235 }else if( savedHasAgg ){
drha51009b2012-05-21 19:11:25 +00001236 pNC->ncFlags |= NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001237 }
1238 return ExprHasProperty(pExpr, EP_Error);
1239}
drh7d10d5a2008-08-20 16:35:10 +00001240
1241
1242/*
1243** Resolve all names in all expressions of a SELECT and in all
1244** decendents of the SELECT, including compounds off of p->pPrior,
1245** subqueries in expressions, and subqueries used as FROM clause
1246** terms.
1247**
1248** See sqlite3ResolveExprNames() for a description of the kinds of
1249** transformations that occur.
1250**
1251** All SELECT statements should have been expanded using
1252** sqlite3SelectExpand() prior to invoking this routine.
1253*/
1254void sqlite3ResolveSelectNames(
1255 Parse *pParse, /* The parser context */
1256 Select *p, /* The SELECT statement being coded. */
1257 NameContext *pOuterNC /* Name context for parent SELECT statement */
1258){
1259 Walker w;
1260
drh0a846f92008-08-25 17:23:29 +00001261 assert( p!=0 );
1262 w.xExprCallback = resolveExprStep;
1263 w.xSelectCallback = resolveSelectStep;
1264 w.pParse = pParse;
1265 w.u.pNC = pOuterNC;
1266 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001267}