blob: 3f3ac939f6e306b3e05952bdf7600fc0d8d507a9 [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.
16**
drh10fe8402008-10-11 16:47:35 +000017** $Id: resolve.c,v 1.9 2008/10/11 16:47:36 drh Exp $
drh7d10d5a2008-08-20 16:35:10 +000018*/
19#include "sqliteInt.h"
20#include <stdlib.h>
21#include <string.h>
22
23/*
drh8b213892008-08-29 02:14:02 +000024** Turn the pExpr expression into an alias for the iCol-th column of the
25** result set in pEList.
26**
27** If the result set column is a simple column reference, then this routine
28** makes an exact copy. But for any other kind of expression, this
29** routine make a copy of the result set column as the argument to the
30** TK_AS operator. The TK_AS operator causes the expression to be
31** evaluated just once and then reused for each alias.
32**
33** The reason for suppressing the TK_AS term when the expression is a simple
34** column reference is so that the column reference will be recognized as
35** usable by indices within the WHERE clause processing logic.
36**
37** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
38** that in a GROUP BY clause, the expression is evaluated twice. Hence:
39**
40** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
41**
42** Is equivalent to:
43**
44** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
45**
46** The result of random()%5 in the GROUP BY clause is probably different
47** from the result in the result-set. We might fix this someday. Or
48** then again, we might not...
49*/
50static void resolveAlias(
51 Parse *pParse, /* Parsing context */
52 ExprList *pEList, /* A result set */
53 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
54 Expr *pExpr, /* Transform this into an alias to the result set */
55 const char *zType /* "GROUP" or "ORDER" or "" */
56){
57 Expr *pOrig; /* The iCol-th column of the result set */
58 Expr *pDup; /* Copy of pOrig */
59 sqlite3 *db; /* The database connection */
60
61 assert( iCol>=0 && iCol<pEList->nExpr );
62 pOrig = pEList->a[iCol].pExpr;
63 assert( pOrig!=0 );
64 assert( pOrig->flags & EP_Resolved );
65 db = pParse->db;
66 pDup = sqlite3ExprDup(db, pOrig);
67 if( pDup==0 ) return;
68 if( pDup->op!=TK_COLUMN && zType[0]!='G' ){
69 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
70 if( pDup==0 ) return;
71 if( pEList->a[iCol].iAlias==0 ){
72 pEList->a[iCol].iAlias = ++pParse->nAlias;
73 }
74 pDup->iTable = pEList->a[iCol].iAlias;
75 }
76 if( pExpr->flags & EP_ExpCollate ){
77 pDup->pColl = pExpr->pColl;
78 pDup->flags |= EP_ExpCollate;
79 }
drh10fe8402008-10-11 16:47:35 +000080 sqlite3ExprClear(db, pExpr);
drh8b213892008-08-29 02:14:02 +000081 memcpy(pExpr, pDup, sizeof(*pExpr));
82 sqlite3DbFree(db, pDup);
83}
84
85/*
drh7d10d5a2008-08-20 16:35:10 +000086** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
87** that name in the set of source tables in pSrcList and make the pExpr
88** expression node refer back to that source column. The following changes
89** are made to pExpr:
90**
91** pExpr->iDb Set the index in db->aDb[] of the database X
92** (even if X is implied).
93** pExpr->iTable Set to the cursor number for the table obtained
94** from pSrcList.
95** pExpr->pTab Points to the Table structure of X.Y (even if
96** X and/or Y are implied.)
97** pExpr->iColumn Set to the column number within the table.
98** pExpr->op Set to TK_COLUMN.
99** pExpr->pLeft Any expression this points to is deleted
100** pExpr->pRight Any expression this points to is deleted.
101**
102** The pDbToken is the name of the database (the "X"). This value may be
103** NULL meaning that name is of the form Y.Z or Z. Any available database
104** can be used. The pTableToken is the name of the table (the "Y"). This
105** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
106** means that the form of the name is Z and that columns from any table
107** can be used.
108**
109** If the name cannot be resolved unambiguously, leave an error message
110** in pParse and return non-zero. Return zero on success.
111*/
112static int lookupName(
113 Parse *pParse, /* The parsing context */
114 Token *pDbToken, /* Name of the database containing table, or NULL */
115 Token *pTableToken, /* Name of table containing column, or NULL */
116 Token *pColumnToken, /* Name of the column. */
117 NameContext *pNC, /* The name context used to resolve the name */
118 Expr *pExpr /* Make this EXPR node point to the selected column */
119){
120 char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
121 char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
122 char *zCol = 0; /* Name of the column. The "Z" */
123 int i, j; /* Loop counters */
124 int cnt = 0; /* Number of matching column names */
125 int cntTab = 0; /* Number of matching table names */
126 sqlite3 *db = pParse->db; /* The database connection */
127 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
128 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
129 NameContext *pTopNC = pNC; /* First namecontext in the list */
130 Schema *pSchema = 0; /* Schema of the expression */
131
132 assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
133
134 /* Dequote and zero-terminate the names */
135 zDb = sqlite3NameFromToken(db, pDbToken);
136 zTab = sqlite3NameFromToken(db, pTableToken);
137 zCol = sqlite3NameFromToken(db, pColumnToken);
138 if( db->mallocFailed ){
139 goto lookupname_end;
140 }
141
142 /* Initialize the node to no-match */
143 pExpr->iTable = -1;
144 pExpr->pTab = 0;
145
146 /* Start at the inner-most context and move outward until a match is found */
147 while( pNC && cnt==0 ){
148 ExprList *pEList;
149 SrcList *pSrcList = pNC->pSrcList;
150
151 if( pSrcList ){
152 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
153 Table *pTab;
154 int iDb;
155 Column *pCol;
156
157 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000158 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000159 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
160 assert( pTab->nCol>0 );
161 if( zTab ){
162 if( pItem->zAlias ){
163 char *zTabName = pItem->zAlias;
164 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
165 }else{
166 char *zTabName = pTab->zName;
167 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
168 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
169 continue;
170 }
171 }
172 }
173 if( 0==(cntTab++) ){
174 pExpr->iTable = pItem->iCursor;
175 pExpr->pTab = pTab;
176 pSchema = pTab->pSchema;
177 pMatch = pItem;
178 }
179 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
180 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
181 IdList *pUsing;
182 cnt++;
183 pExpr->iTable = pItem->iCursor;
184 pExpr->pTab = pTab;
185 pMatch = pItem;
186 pSchema = pTab->pSchema;
187 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
188 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
189 if( i<pSrcList->nSrc-1 ){
190 if( pItem[1].jointype & JT_NATURAL ){
191 /* If this match occurred in the left table of a natural join,
192 ** then skip the right table to avoid a duplicate match */
193 pItem++;
194 i++;
195 }else if( (pUsing = pItem[1].pUsing)!=0 ){
196 /* If this match occurs on a column that is in the USING clause
197 ** of a join, skip the search of the right table of the join
198 ** to avoid a duplicate match there. */
199 int k;
200 for(k=0; k<pUsing->nId; k++){
201 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
202 pItem++;
203 i++;
204 break;
205 }
206 }
207 }
208 }
209 break;
210 }
211 }
212 }
213 }
214
215#ifndef SQLITE_OMIT_TRIGGER
216 /* If we have not already resolved the name, then maybe
217 ** it is a new.* or old.* trigger argument reference
218 */
219 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
220 TriggerStack *pTriggerStack = pParse->trigStack;
221 Table *pTab = 0;
222 u32 *piColMask;
223 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
224 pExpr->iTable = pTriggerStack->newIdx;
225 assert( pTriggerStack->pTab );
226 pTab = pTriggerStack->pTab;
227 piColMask = &(pTriggerStack->newColMask);
228 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
229 pExpr->iTable = pTriggerStack->oldIdx;
230 assert( pTriggerStack->pTab );
231 pTab = pTriggerStack->pTab;
232 piColMask = &(pTriggerStack->oldColMask);
233 }
234
235 if( pTab ){
236 int iCol;
237 Column *pCol = pTab->aCol;
238
239 pSchema = pTab->pSchema;
240 cntTab++;
241 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
242 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
243 cnt++;
244 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
245 pExpr->pTab = pTab;
246 if( iCol>=0 ){
247 testcase( iCol==31 );
248 testcase( iCol==32 );
249 *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
250 }
251 break;
252 }
253 }
254 }
255 }
256#endif /* !defined(SQLITE_OMIT_TRIGGER) */
257
258 /*
259 ** Perhaps the name is a reference to the ROWID
260 */
261 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
262 cnt = 1;
263 pExpr->iColumn = -1;
264 pExpr->affinity = SQLITE_AFF_INTEGER;
265 }
266
267 /*
268 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
269 ** might refer to an result-set alias. This happens, for example, when
270 ** we are resolving names in the WHERE clause of the following command:
271 **
272 ** SELECT a+b AS x FROM table WHERE x<10;
273 **
274 ** In cases like this, replace pExpr with a copy of the expression that
275 ** forms the result set entry ("a+b" in the example) and return immediately.
276 ** Note that the expression in the result set should have already been
277 ** resolved by the time the WHERE clause is resolved.
278 */
279 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
280 for(j=0; j<pEList->nExpr; j++){
281 char *zAs = pEList->a[j].zName;
282 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000283 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000284 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
285 assert( pExpr->pList==0 );
286 assert( pExpr->pSelect==0 );
287 pOrig = pEList->a[j].pExpr;
288 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
289 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
290 sqlite3DbFree(db, zCol);
291 return 2;
292 }
drh8b213892008-08-29 02:14:02 +0000293 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000294 cnt = 1;
295 pMatch = 0;
296 assert( zTab==0 && zDb==0 );
297 goto lookupname_end_2;
298 }
299 }
300 }
301
302 /* Advance to the next name context. The loop will exit when either
303 ** we have a match (cnt>0) or when we run out of name contexts.
304 */
305 if( cnt==0 ){
306 pNC = pNC->pNext;
307 }
308 }
309
310 /*
311 ** If X and Y are NULL (in other words if only the column name Z is
312 ** supplied) and the value of Z is enclosed in double-quotes, then
313 ** Z is a string literal if it doesn't match any column names. In that
314 ** case, we need to return right away and not make any changes to
315 ** pExpr.
316 **
317 ** Because no reference was made to outer contexts, the pNC->nRef
318 ** fields are not changed in any context.
319 */
320 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
321 sqlite3DbFree(db, zCol);
322 pExpr->op = TK_STRING;
323 return 0;
324 }
325
326 /*
327 ** cnt==0 means there was not match. cnt>1 means there were two or
328 ** more matches. Either way, we have an error.
329 */
330 if( cnt!=1 ){
331 const char *zErr;
332 zErr = cnt==0 ? "no such column" : "ambiguous column name";
333 if( zDb ){
334 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
335 }else if( zTab ){
336 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
337 }else{
338 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
339 }
340 pTopNC->nErr++;
341 }
342
343 /* If a column from a table in pSrcList is referenced, then record
344 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
345 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
346 ** column number is greater than the number of bits in the bitmask
347 ** then set the high-order bit of the bitmask.
348 */
349 if( pExpr->iColumn>=0 && pMatch!=0 ){
350 int n = pExpr->iColumn;
351 testcase( n==sizeof(Bitmask)*8-1 );
352 if( n>=sizeof(Bitmask)*8 ){
353 n = sizeof(Bitmask)*8-1;
354 }
355 assert( pMatch->iCursor==pExpr->iTable );
356 pMatch->colUsed |= ((Bitmask)1)<<n;
357 }
358
359lookupname_end:
360 /* Clean up and return
361 */
362 sqlite3DbFree(db, zDb);
363 sqlite3DbFree(db, zTab);
364 sqlite3ExprDelete(db, pExpr->pLeft);
365 pExpr->pLeft = 0;
366 sqlite3ExprDelete(db, pExpr->pRight);
367 pExpr->pRight = 0;
368 pExpr->op = TK_COLUMN;
369lookupname_end_2:
370 sqlite3DbFree(db, zCol);
371 if( cnt==1 ){
372 assert( pNC!=0 );
373 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
374 /* Increment the nRef value on all name contexts from TopNC up to
375 ** the point where the name matched. */
376 for(;;){
377 assert( pTopNC!=0 );
378 pTopNC->nRef++;
379 if( pTopNC==pNC ) break;
380 pTopNC = pTopNC->pNext;
381 }
382 return 0;
383 } else {
384 return 1;
385 }
386}
387
388/*
389** This routine is callback for sqlite3WalkExpr().
390**
391** Resolve symbolic names into TK_COLUMN operators for the current
392** node in the expression tree. Return 0 to continue the search down
393** the tree or 2 to abort the tree walk.
394**
395** This routine also does error checking and name resolution for
396** function names. The operator for aggregate functions is changed
397** to TK_AGG_FUNCTION.
398*/
399static int resolveExprStep(Walker *pWalker, Expr *pExpr){
400 NameContext *pNC;
401 Parse *pParse;
402
drh7d10d5a2008-08-20 16:35:10 +0000403 pNC = pWalker->u.pNC;
404 assert( pNC!=0 );
405 pParse = pNC->pParse;
406 assert( pParse==pWalker->pParse );
407
408 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
409 ExprSetProperty(pExpr, EP_Resolved);
410#ifndef NDEBUG
411 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
412 SrcList *pSrcList = pNC->pSrcList;
413 int i;
414 for(i=0; i<pNC->pSrcList->nSrc; i++){
415 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
416 }
417 }
418#endif
419 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000420
shane273f6192008-10-10 04:34:16 +0000421#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000422 /* The special operator TK_ROW means use the rowid for the first
423 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
424 ** clause processing on UPDATE and DELETE statements.
425 */
426 case TK_ROW: {
427 SrcList *pSrcList = pNC->pSrcList;
428 struct SrcList_item *pItem;
429 assert( pSrcList && pSrcList->nSrc==1 );
430 pItem = pSrcList->a;
431 pExpr->op = TK_COLUMN;
432 pExpr->pTab = pItem->pTab;
433 pExpr->iTable = pItem->iCursor;
434 pExpr->iColumn = -1;
435 pExpr->affinity = SQLITE_AFF_INTEGER;
436 break;
437 }
shane273f6192008-10-10 04:34:16 +0000438#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000439
drh7d10d5a2008-08-20 16:35:10 +0000440 /* A lone identifier is the name of a column.
441 */
442 case TK_ID: {
443 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
444 return WRC_Prune;
445 }
446
447 /* A table name and column name: ID.ID
448 ** Or a database, table and column: ID.ID.ID
449 */
450 case TK_DOT: {
451 Token *pColumn;
452 Token *pTable;
453 Token *pDb;
454 Expr *pRight;
455
456 /* if( pSrcList==0 ) break; */
457 pRight = pExpr->pRight;
458 if( pRight->op==TK_ID ){
459 pDb = 0;
460 pTable = &pExpr->pLeft->token;
461 pColumn = &pRight->token;
462 }else{
463 assert( pRight->op==TK_DOT );
464 pDb = &pExpr->pLeft->token;
465 pTable = &pRight->pLeft->token;
466 pColumn = &pRight->pRight->token;
467 }
468 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
469 return WRC_Prune;
470 }
471
472 /* Resolve function names
473 */
474 case TK_CONST_FUNC:
475 case TK_FUNCTION: {
476 ExprList *pList = pExpr->pList; /* The argument list */
477 int n = pList ? pList->nExpr : 0; /* Number of arguments */
478 int no_such_func = 0; /* True if no such function exists */
479 int wrong_num_args = 0; /* True if wrong number of arguments */
480 int is_agg = 0; /* True if is an aggregate function */
481 int auth; /* Authorization to use the function */
482 int nId; /* Number of characters in function name */
483 const char *zId; /* The function name. */
484 FuncDef *pDef; /* Information about the function */
485 int enc = ENC(pParse->db); /* The database encoding */
486
487 zId = (char*)pExpr->token.z;
488 nId = pExpr->token.n;
489 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
490 if( pDef==0 ){
491 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
492 if( pDef==0 ){
493 no_such_func = 1;
494 }else{
495 wrong_num_args = 1;
496 }
497 }else{
498 is_agg = pDef->xFunc==0;
499 }
500#ifndef SQLITE_OMIT_AUTHORIZATION
501 if( pDef ){
502 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
503 if( auth!=SQLITE_OK ){
504 if( auth==SQLITE_DENY ){
505 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
506 pDef->zName);
507 pNC->nErr++;
508 }
509 pExpr->op = TK_NULL;
510 return WRC_Prune;
511 }
512 }
513#endif
514 if( is_agg && !pNC->allowAgg ){
515 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
516 pNC->nErr++;
517 is_agg = 0;
518 }else if( no_such_func ){
519 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
520 pNC->nErr++;
521 }else if( wrong_num_args ){
522 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
523 nId, zId);
524 pNC->nErr++;
525 }
526 if( is_agg ){
527 pExpr->op = TK_AGG_FUNCTION;
528 pNC->hasAgg = 1;
529 }
530 if( is_agg ) pNC->allowAgg = 0;
531 sqlite3WalkExprList(pWalker, pList);
532 if( is_agg ) pNC->allowAgg = 1;
533 /* FIX ME: Compute pExpr->affinity based on the expected return
534 ** type of the function
535 */
536 return WRC_Prune;
537 }
538#ifndef SQLITE_OMIT_SUBQUERY
539 case TK_SELECT:
540 case TK_EXISTS:
541#endif
542 case TK_IN: {
543 if( pExpr->pSelect ){
544 int nRef = pNC->nRef;
545#ifndef SQLITE_OMIT_CHECK
546 if( pNC->isCheck ){
547 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
548 }
549#endif
550 sqlite3WalkSelect(pWalker, pExpr->pSelect);
551 assert( pNC->nRef>=nRef );
552 if( nRef!=pNC->nRef ){
553 ExprSetProperty(pExpr, EP_VarSelect);
554 }
555 }
556 break;
557 }
558#ifndef SQLITE_OMIT_CHECK
559 case TK_VARIABLE: {
560 if( pNC->isCheck ){
561 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
562 }
563 break;
564 }
565#endif
566 }
567 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
568}
569
570/*
571** pEList is a list of expressions which are really the result set of the
572** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
573** This routine checks to see if pE is a simple identifier which corresponds
574** to the AS-name of one of the terms of the expression list. If it is,
575** this routine return an integer between 1 and N where N is the number of
576** elements in pEList, corresponding to the matching entry. If there is
577** no match, or if pE is not a simple identifier, then this routine
578** return 0.
579**
580** pEList has been resolved. pE has not.
581*/
582static int resolveAsName(
583 Parse *pParse, /* Parsing context for error messages */
584 ExprList *pEList, /* List of expressions to scan */
585 Expr *pE /* Expression we are trying to match */
586){
587 int i; /* Loop counter */
588
589 if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
590 sqlite3 *db = pParse->db;
591 char *zCol = sqlite3NameFromToken(db, &pE->token);
592 if( zCol==0 ){
593 return -1;
594 }
595 for(i=0; i<pEList->nExpr; i++){
596 char *zAs = pEList->a[i].zName;
597 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
598 sqlite3DbFree(db, zCol);
599 return i+1;
600 }
601 }
602 sqlite3DbFree(db, zCol);
603 }
604 return 0;
605}
606
607/*
608** pE is a pointer to an expression which is a single term in the
609** ORDER BY of a compound SELECT. The expression has not been
610** name resolved.
611**
612** At the point this routine is called, we already know that the
613** ORDER BY term is not an integer index into the result set. That
614** case is handled by the calling routine.
615**
616** Attempt to match pE against result set columns in the left-most
617** SELECT statement. Return the index i of the matching column,
618** as an indication to the caller that it should sort by the i-th column.
619** The left-most column is 1. In other words, the value returned is the
620** same integer value that would be used in the SQL statement to indicate
621** the column.
622**
623** If there is no match, return 0. Return -1 if an error occurs.
624*/
625static int resolveOrderByTermToExprList(
626 Parse *pParse, /* Parsing context for error messages */
627 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
628 Expr *pE /* The specific ORDER BY term */
629){
630 int i; /* Loop counter */
631 ExprList *pEList; /* The columns of the result set */
632 NameContext nc; /* Name context for resolving pE */
633
634 assert( sqlite3ExprIsInteger(pE, &i)==0 );
635 pEList = pSelect->pEList;
636
637 /* Resolve all names in the ORDER BY term expression
638 */
639 memset(&nc, 0, sizeof(nc));
640 nc.pParse = pParse;
641 nc.pSrcList = pSelect->pSrc;
642 nc.pEList = pEList;
643 nc.allowAgg = 1;
644 nc.nErr = 0;
645 if( sqlite3ResolveExprNames(&nc, pE) ){
646 sqlite3ErrorClear(pParse);
647 return 0;
648 }
649
650 /* Try to match the ORDER BY expression against an expression
651 ** in the result set. Return an 1-based index of the matching
652 ** result-set entry.
653 */
654 for(i=0; i<pEList->nExpr; i++){
655 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
656 return i+1;
657 }
658 }
659
660 /* If no match, return 0. */
661 return 0;
662}
663
664/*
665** Generate an ORDER BY or GROUP BY term out-of-range error.
666*/
667static void resolveOutOfRangeError(
668 Parse *pParse, /* The error context into which to write the error */
669 const char *zType, /* "ORDER" or "GROUP" */
670 int i, /* The index (1-based) of the term out of range */
671 int mx /* Largest permissible value of i */
672){
673 sqlite3ErrorMsg(pParse,
674 "%r %s BY term out of range - should be "
675 "between 1 and %d", i, zType, mx);
676}
677
678/*
679** Analyze the ORDER BY clause in a compound SELECT statement. Modify
680** each term of the ORDER BY clause is a constant integer between 1
681** and N where N is the number of columns in the compound SELECT.
682**
683** ORDER BY terms that are already an integer between 1 and N are
684** unmodified. ORDER BY terms that are integers outside the range of
685** 1 through N generate an error. ORDER BY terms that are expressions
686** are matched against result set expressions of compound SELECT
687** beginning with the left-most SELECT and working toward the right.
688** At the first match, the ORDER BY expression is transformed into
689** the integer column number.
690**
691** Return the number of errors seen.
692*/
693static int resolveCompoundOrderBy(
694 Parse *pParse, /* Parsing context. Leave error messages here */
695 Select *pSelect /* The SELECT statement containing the ORDER BY */
696){
697 int i;
698 ExprList *pOrderBy;
699 ExprList *pEList;
700 sqlite3 *db;
701 int moreToDo = 1;
702
703 pOrderBy = pSelect->pOrderBy;
704 if( pOrderBy==0 ) return 0;
705 db = pParse->db;
706#if SQLITE_MAX_COLUMN
707 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
708 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
709 return 1;
710 }
711#endif
712 for(i=0; i<pOrderBy->nExpr; i++){
713 pOrderBy->a[i].done = 0;
714 }
715 pSelect->pNext = 0;
716 while( pSelect->pPrior ){
717 pSelect->pPrior->pNext = pSelect;
718 pSelect = pSelect->pPrior;
719 }
720 while( pSelect && moreToDo ){
721 struct ExprList_item *pItem;
722 moreToDo = 0;
723 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000724 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000725 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
726 int iCol = -1;
727 Expr *pE, *pDup;
728 if( pItem->done ) continue;
729 pE = pItem->pExpr;
730 if( sqlite3ExprIsInteger(pE, &iCol) ){
731 if( iCol<0 || iCol>pEList->nExpr ){
732 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
733 return 1;
734 }
735 }else{
736 iCol = resolveAsName(pParse, pEList, pE);
737 if( iCol==0 ){
738 pDup = sqlite3ExprDup(db, pE);
739 if( !db->mallocFailed ){
740 assert(pDup);
741 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
742 }
743 sqlite3ExprDelete(db, pDup);
744 }
745 if( iCol<0 ){
746 return 1;
747 }
748 }
749 if( iCol>0 ){
750 CollSeq *pColl = pE->pColl;
751 int flags = pE->flags & EP_ExpCollate;
752 sqlite3ExprDelete(db, pE);
753 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
754 if( pE==0 ) return 1;
755 pE->pColl = pColl;
756 pE->flags |= EP_IntValue | flags;
757 pE->iTable = iCol;
758 pItem->iCol = iCol;
759 pItem->done = 1;
760 }else{
761 moreToDo = 1;
762 }
763 }
764 pSelect = pSelect->pNext;
765 }
766 for(i=0; i<pOrderBy->nExpr; i++){
767 if( pOrderBy->a[i].done==0 ){
768 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
769 "column in the result set", i+1);
770 return 1;
771 }
772 }
773 return 0;
774}
775
776/*
777** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
778** the SELECT statement pSelect. If any term is reference to a
779** result set expression (as determined by the ExprList.a.iCol field)
780** then convert that term into a copy of the corresponding result set
781** column.
782**
783** If any errors are detected, add an error message to pParse and
784** return non-zero. Return zero if no errors are seen.
785*/
786int sqlite3ResolveOrderGroupBy(
787 Parse *pParse, /* Parsing context. Leave error messages here */
788 Select *pSelect, /* The SELECT statement containing the clause */
789 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
790 const char *zType /* "ORDER" or "GROUP" */
791){
792 int i;
793 sqlite3 *db = pParse->db;
794 ExprList *pEList;
795 struct ExprList_item *pItem;
796
797 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
798#if SQLITE_MAX_COLUMN
799 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
800 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
801 return 1;
802 }
803#endif
804 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000805 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000806 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
807 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000808 if( pItem->iCol>pEList->nExpr ){
809 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
810 return 1;
811 }
drh8b213892008-08-29 02:14:02 +0000812 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000813 }
814 }
815 return 0;
816}
817
818/*
819** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
820** The Name context of the SELECT statement is pNC. zType is either
821** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
822**
823** This routine resolves each term of the clause into an expression.
824** If the order-by term is an integer I between 1 and N (where N is the
825** number of columns in the result set of the SELECT) then the expression
826** in the resolution is a copy of the I-th result-set expression. If
827** the order-by term is an identify that corresponds to the AS-name of
828** a result-set expression, then the term resolves to a copy of the
829** result-set expression. Otherwise, the expression is resolved in
830** the usual way - using sqlite3ResolveExprNames().
831**
832** This routine returns the number of errors. If errors occur, then
833** an appropriate error message might be left in pParse. (OOM errors
834** excepted.)
835*/
836static int resolveOrderGroupBy(
837 NameContext *pNC, /* The name context of the SELECT statement */
838 Select *pSelect, /* The SELECT statement holding pOrderBy */
839 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
840 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
841){
842 int i; /* Loop counter */
843 int iCol; /* Column number */
844 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
845 Parse *pParse; /* Parsing context */
846 int nResult; /* Number of terms in the result set */
847
848 if( pOrderBy==0 ) return 0;
849 nResult = pSelect->pEList->nExpr;
850 pParse = pNC->pParse;
851 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
852 Expr *pE = pItem->pExpr;
853 iCol = resolveAsName(pParse, pSelect->pEList, pE);
854 if( iCol<0 ){
855 return 1; /* OOM error */
856 }
857 if( iCol>0 ){
858 /* If an AS-name match is found, mark this ORDER BY column as being
859 ** a copy of the iCol-th result-set column. The subsequent call to
860 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
861 ** copy of the iCol-th result-set expression. */
862 pItem->iCol = iCol;
863 continue;
864 }
865 if( sqlite3ExprIsInteger(pE, &iCol) ){
866 /* The ORDER BY term is an integer constant. Again, set the column
867 ** number so that sqlite3ResolveOrderGroupBy() will convert the
868 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000869 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000870 resolveOutOfRangeError(pParse, zType, i+1, nResult);
871 return 1;
872 }
873 pItem->iCol = iCol;
874 continue;
875 }
876
877 /* Otherwise, treat the ORDER BY term as an ordinary expression */
878 pItem->iCol = 0;
879 if( sqlite3ResolveExprNames(pNC, pE) ){
880 return 1;
881 }
882 }
883 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
884}
885
886/*
887** Resolve names in the SELECT statement p and all of its descendents.
888*/
889static int resolveSelectStep(Walker *pWalker, Select *p){
890 NameContext *pOuterNC; /* Context that contains this SELECT */
891 NameContext sNC; /* Name context of this SELECT */
892 int isCompound; /* True if p is a compound select */
893 int nCompound; /* Number of compound terms processed so far */
894 Parse *pParse; /* Parsing context */
895 ExprList *pEList; /* Result set expression list */
896 int i; /* Loop counter */
897 ExprList *pGroupBy; /* The GROUP BY clause */
898 Select *pLeftmost; /* Left-most of SELECT of a compound */
899 sqlite3 *db; /* Database connection */
900
901
drh0a846f92008-08-25 17:23:29 +0000902 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000903 if( p->selFlags & SF_Resolved ){
904 return WRC_Prune;
905 }
906 pOuterNC = pWalker->u.pNC;
907 pParse = pWalker->pParse;
908 db = pParse->db;
909
910 /* Normally sqlite3SelectExpand() will be called first and will have
911 ** already expanded this SELECT. However, if this is a subquery within
912 ** an expression, sqlite3ResolveExprNames() will be called without a
913 ** prior call to sqlite3SelectExpand(). When that happens, let
914 ** sqlite3SelectPrep() do all of the processing for this SELECT.
915 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
916 ** this routine in the correct order.
917 */
918 if( (p->selFlags & SF_Expanded)==0 ){
919 sqlite3SelectPrep(pParse, p, pOuterNC);
920 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
921 }
922
923 isCompound = p->pPrior!=0;
924 nCompound = 0;
925 pLeftmost = p;
926 while( p ){
927 assert( (p->selFlags & SF_Expanded)!=0 );
928 assert( (p->selFlags & SF_Resolved)==0 );
929 p->selFlags |= SF_Resolved;
930
931 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
932 ** are not allowed to refer to any names, so pass an empty NameContext.
933 */
934 memset(&sNC, 0, sizeof(sNC));
935 sNC.pParse = pParse;
936 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
937 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
938 return WRC_Abort;
939 }
940
941 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
942 ** resolve the result-set expression list.
943 */
944 sNC.allowAgg = 1;
945 sNC.pSrcList = p->pSrc;
946 sNC.pNext = pOuterNC;
947
948 /* Resolve names in the result set. */
949 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000950 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000951 for(i=0; i<pEList->nExpr; i++){
952 Expr *pX = pEList->a[i].pExpr;
953 if( sqlite3ResolveExprNames(&sNC, pX) ){
954 return WRC_Abort;
955 }
956 }
957
958 /* Recursively resolve names in all subqueries
959 */
960 for(i=0; i<p->pSrc->nSrc; i++){
961 struct SrcList_item *pItem = &p->pSrc->a[i];
962 if( pItem->pSelect ){
963 const char *zSavedContext = pParse->zAuthContext;
964 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
965 sqlite3ResolveSelectNames(pParse, pItem->pSelect, &sNC);
966 pParse->zAuthContext = zSavedContext;
967 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
968 }
969 }
970
971 /* If there are no aggregate functions in the result-set, and no GROUP BY
972 ** expression, do not allow aggregates in any of the other expressions.
973 */
974 assert( (p->selFlags & SF_Aggregate)==0 );
975 pGroupBy = p->pGroupBy;
976 if( pGroupBy || sNC.hasAgg ){
977 p->selFlags |= SF_Aggregate;
978 }else{
979 sNC.allowAgg = 0;
980 }
981
982 /* If a HAVING clause is present, then there must be a GROUP BY clause.
983 */
984 if( p->pHaving && !pGroupBy ){
985 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
986 return WRC_Abort;
987 }
988
989 /* Add the expression list to the name-context before parsing the
990 ** other expressions in the SELECT statement. This is so that
991 ** expressions in the WHERE clause (etc.) can refer to expressions by
992 ** aliases in the result set.
993 **
994 ** Minor point: If this is the case, then the expression will be
995 ** re-evaluated for each reference to it.
996 */
997 sNC.pEList = p->pEList;
998 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
999 sqlite3ResolveExprNames(&sNC, p->pHaving)
1000 ){
1001 return WRC_Abort;
1002 }
1003
1004 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1005 ** outer queries
1006 */
1007 sNC.pNext = 0;
1008 sNC.allowAgg = 1;
1009
1010 /* Process the ORDER BY clause for singleton SELECT statements.
1011 ** The ORDER BY clause for compounds SELECT statements is handled
1012 ** below, after all of the result-sets for all of the elements of
1013 ** the compound have been resolved.
1014 */
1015 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1016 return WRC_Abort;
1017 }
1018 if( db->mallocFailed ){
1019 return WRC_Abort;
1020 }
1021
1022 /* Resolve the GROUP BY clause. At the same time, make sure
1023 ** the GROUP BY clause does not contain aggregate functions.
1024 */
1025 if( pGroupBy ){
1026 struct ExprList_item *pItem;
1027
1028 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1029 return WRC_Abort;
1030 }
1031 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1032 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1033 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1034 "the GROUP BY clause");
1035 return WRC_Abort;
1036 }
1037 }
1038 }
1039
1040 /* Advance to the next term of the compound
1041 */
1042 p = p->pPrior;
1043 nCompound++;
1044 }
1045
1046 /* Resolve the ORDER BY on a compound SELECT after all terms of
1047 ** the compound have been resolved.
1048 */
1049 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1050 return WRC_Abort;
1051 }
1052
1053 return WRC_Prune;
1054}
1055
1056/*
1057** This routine walks an expression tree and resolves references to
1058** table columns and result-set columns. At the same time, do error
1059** checking on function usage and set a flag if any aggregate functions
1060** are seen.
1061**
1062** To resolve table columns references we look for nodes (or subtrees) of the
1063** form X.Y.Z or Y.Z or just Z where
1064**
1065** X: The name of a database. Ex: "main" or "temp" or
1066** the symbolic name assigned to an ATTACH-ed database.
1067**
1068** Y: The name of a table in a FROM clause. Or in a trigger
1069** one of the special names "old" or "new".
1070**
1071** Z: The name of a column in table Y.
1072**
1073** The node at the root of the subtree is modified as follows:
1074**
1075** Expr.op Changed to TK_COLUMN
1076** Expr.pTab Points to the Table object for X.Y
1077** Expr.iColumn The column index in X.Y. -1 for the rowid.
1078** Expr.iTable The VDBE cursor number for X.Y
1079**
1080**
1081** To resolve result-set references, look for expression nodes of the
1082** form Z (with no X and Y prefix) where the Z matches the right-hand
1083** size of an AS clause in the result-set of a SELECT. The Z expression
1084** is replaced by a copy of the left-hand side of the result-set expression.
1085** Table-name and function resolution occurs on the substituted expression
1086** tree. For example, in:
1087**
1088** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1089**
1090** The "x" term of the order by is replaced by "a+b" to render:
1091**
1092** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1093**
1094** Function calls are checked to make sure that the function is
1095** defined and that the correct number of arguments are specified.
1096** If the function is an aggregate function, then the pNC->hasAgg is
1097** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1098** If an expression contains aggregate functions then the EP_Agg
1099** property on the expression is set.
1100**
1101** An error message is left in pParse if anything is amiss. The number
1102** if errors is returned.
1103*/
1104int sqlite3ResolveExprNames(
1105 NameContext *pNC, /* Namespace to resolve expressions in. */
1106 Expr *pExpr /* The expression to be analyzed. */
1107){
1108 int savedHasAgg;
1109 Walker w;
1110
1111 if( pExpr==0 ) return 0;
1112#if SQLITE_MAX_EXPR_DEPTH>0
1113 {
1114 Parse *pParse = pNC->pParse;
1115 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1116 return 1;
1117 }
1118 pParse->nHeight += pExpr->nHeight;
1119 }
1120#endif
1121 savedHasAgg = pNC->hasAgg;
1122 pNC->hasAgg = 0;
1123 w.xExprCallback = resolveExprStep;
1124 w.xSelectCallback = resolveSelectStep;
1125 w.pParse = pNC->pParse;
1126 w.u.pNC = pNC;
1127 sqlite3WalkExpr(&w, pExpr);
1128#if SQLITE_MAX_EXPR_DEPTH>0
1129 pNC->pParse->nHeight -= pExpr->nHeight;
1130#endif
1131 if( pNC->nErr>0 ){
1132 ExprSetProperty(pExpr, EP_Error);
1133 }
1134 if( pNC->hasAgg ){
1135 ExprSetProperty(pExpr, EP_Agg);
1136 }else if( savedHasAgg ){
1137 pNC->hasAgg = 1;
1138 }
1139 return ExprHasProperty(pExpr, EP_Error);
1140}
drh7d10d5a2008-08-20 16:35:10 +00001141
1142
1143/*
1144** Resolve all names in all expressions of a SELECT and in all
1145** decendents of the SELECT, including compounds off of p->pPrior,
1146** subqueries in expressions, and subqueries used as FROM clause
1147** terms.
1148**
1149** See sqlite3ResolveExprNames() for a description of the kinds of
1150** transformations that occur.
1151**
1152** All SELECT statements should have been expanded using
1153** sqlite3SelectExpand() prior to invoking this routine.
1154*/
1155void sqlite3ResolveSelectNames(
1156 Parse *pParse, /* The parser context */
1157 Select *p, /* The SELECT statement being coded. */
1158 NameContext *pOuterNC /* Name context for parent SELECT statement */
1159){
1160 Walker w;
1161
drh0a846f92008-08-25 17:23:29 +00001162 assert( p!=0 );
1163 w.xExprCallback = resolveExprStep;
1164 w.xSelectCallback = resolveSelectStep;
1165 w.pParse = pParse;
1166 w.u.pNC = pOuterNC;
1167 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001168}