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