blob: 4d33c1a69faaf17a98dde4059379e18ac46bfb3b [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**
drhee76c612008-08-22 17:34:45 +000017** $Id: resolve.c,v 1.2 2008/08/22 17:34:45 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;
96 assert( pTab!=0 );
97 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
349 if( pExpr==0 ) return WRC_Continue;
350 pNC = pWalker->u.pNC;
351 assert( pNC!=0 );
352 pParse = pNC->pParse;
353 assert( pParse==pWalker->pParse );
354
355 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
356 ExprSetProperty(pExpr, EP_Resolved);
357#ifndef NDEBUG
358 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
359 SrcList *pSrcList = pNC->pSrcList;
360 int i;
361 for(i=0; i<pNC->pSrcList->nSrc; i++){
362 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
363 }
364 }
365#endif
366 switch( pExpr->op ){
367 /* A lone identifier is the name of a column.
368 */
369 case TK_ID: {
370 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
371 return WRC_Prune;
372 }
373
374 /* A table name and column name: ID.ID
375 ** Or a database, table and column: ID.ID.ID
376 */
377 case TK_DOT: {
378 Token *pColumn;
379 Token *pTable;
380 Token *pDb;
381 Expr *pRight;
382
383 /* if( pSrcList==0 ) break; */
384 pRight = pExpr->pRight;
385 if( pRight->op==TK_ID ){
386 pDb = 0;
387 pTable = &pExpr->pLeft->token;
388 pColumn = &pRight->token;
389 }else{
390 assert( pRight->op==TK_DOT );
391 pDb = &pExpr->pLeft->token;
392 pTable = &pRight->pLeft->token;
393 pColumn = &pRight->pRight->token;
394 }
395 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
396 return WRC_Prune;
397 }
398
399 /* Resolve function names
400 */
401 case TK_CONST_FUNC:
402 case TK_FUNCTION: {
403 ExprList *pList = pExpr->pList; /* The argument list */
404 int n = pList ? pList->nExpr : 0; /* Number of arguments */
405 int no_such_func = 0; /* True if no such function exists */
406 int wrong_num_args = 0; /* True if wrong number of arguments */
407 int is_agg = 0; /* True if is an aggregate function */
408 int auth; /* Authorization to use the function */
409 int nId; /* Number of characters in function name */
410 const char *zId; /* The function name. */
411 FuncDef *pDef; /* Information about the function */
412 int enc = ENC(pParse->db); /* The database encoding */
413
414 zId = (char*)pExpr->token.z;
415 nId = pExpr->token.n;
416 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
417 if( pDef==0 ){
418 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
419 if( pDef==0 ){
420 no_such_func = 1;
421 }else{
422 wrong_num_args = 1;
423 }
424 }else{
425 is_agg = pDef->xFunc==0;
426 }
427#ifndef SQLITE_OMIT_AUTHORIZATION
428 if( pDef ){
429 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
430 if( auth!=SQLITE_OK ){
431 if( auth==SQLITE_DENY ){
432 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
433 pDef->zName);
434 pNC->nErr++;
435 }
436 pExpr->op = TK_NULL;
437 return WRC_Prune;
438 }
439 }
440#endif
441 if( is_agg && !pNC->allowAgg ){
442 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
443 pNC->nErr++;
444 is_agg = 0;
445 }else if( no_such_func ){
446 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
447 pNC->nErr++;
448 }else if( wrong_num_args ){
449 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
450 nId, zId);
451 pNC->nErr++;
452 }
453 if( is_agg ){
454 pExpr->op = TK_AGG_FUNCTION;
455 pNC->hasAgg = 1;
456 }
457 if( is_agg ) pNC->allowAgg = 0;
458 sqlite3WalkExprList(pWalker, pList);
459 if( is_agg ) pNC->allowAgg = 1;
460 /* FIX ME: Compute pExpr->affinity based on the expected return
461 ** type of the function
462 */
463 return WRC_Prune;
464 }
465#ifndef SQLITE_OMIT_SUBQUERY
466 case TK_SELECT:
467 case TK_EXISTS:
468#endif
469 case TK_IN: {
470 if( pExpr->pSelect ){
471 int nRef = pNC->nRef;
472#ifndef SQLITE_OMIT_CHECK
473 if( pNC->isCheck ){
474 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
475 }
476#endif
477 sqlite3WalkSelect(pWalker, pExpr->pSelect);
478 assert( pNC->nRef>=nRef );
479 if( nRef!=pNC->nRef ){
480 ExprSetProperty(pExpr, EP_VarSelect);
481 }
482 }
483 break;
484 }
485#ifndef SQLITE_OMIT_CHECK
486 case TK_VARIABLE: {
487 if( pNC->isCheck ){
488 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
489 }
490 break;
491 }
492#endif
493 }
494 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
495}
496
497/*
498** pEList is a list of expressions which are really the result set of the
499** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
500** This routine checks to see if pE is a simple identifier which corresponds
501** to the AS-name of one of the terms of the expression list. If it is,
502** this routine return an integer between 1 and N where N is the number of
503** elements in pEList, corresponding to the matching entry. If there is
504** no match, or if pE is not a simple identifier, then this routine
505** return 0.
506**
507** pEList has been resolved. pE has not.
508*/
509static int resolveAsName(
510 Parse *pParse, /* Parsing context for error messages */
511 ExprList *pEList, /* List of expressions to scan */
512 Expr *pE /* Expression we are trying to match */
513){
514 int i; /* Loop counter */
515
516 if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){
517 sqlite3 *db = pParse->db;
518 char *zCol = sqlite3NameFromToken(db, &pE->token);
519 if( zCol==0 ){
520 return -1;
521 }
522 for(i=0; i<pEList->nExpr; i++){
523 char *zAs = pEList->a[i].zName;
524 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
525 sqlite3DbFree(db, zCol);
526 return i+1;
527 }
528 }
529 sqlite3DbFree(db, zCol);
530 }
531 return 0;
532}
533
534/*
535** pE is a pointer to an expression which is a single term in the
536** ORDER BY of a compound SELECT. The expression has not been
537** name resolved.
538**
539** At the point this routine is called, we already know that the
540** ORDER BY term is not an integer index into the result set. That
541** case is handled by the calling routine.
542**
543** Attempt to match pE against result set columns in the left-most
544** SELECT statement. Return the index i of the matching column,
545** as an indication to the caller that it should sort by the i-th column.
546** The left-most column is 1. In other words, the value returned is the
547** same integer value that would be used in the SQL statement to indicate
548** the column.
549**
550** If there is no match, return 0. Return -1 if an error occurs.
551*/
552static int resolveOrderByTermToExprList(
553 Parse *pParse, /* Parsing context for error messages */
554 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
555 Expr *pE /* The specific ORDER BY term */
556){
557 int i; /* Loop counter */
558 ExprList *pEList; /* The columns of the result set */
559 NameContext nc; /* Name context for resolving pE */
560
561 assert( sqlite3ExprIsInteger(pE, &i)==0 );
562 pEList = pSelect->pEList;
563
564 /* Resolve all names in the ORDER BY term expression
565 */
566 memset(&nc, 0, sizeof(nc));
567 nc.pParse = pParse;
568 nc.pSrcList = pSelect->pSrc;
569 nc.pEList = pEList;
570 nc.allowAgg = 1;
571 nc.nErr = 0;
572 if( sqlite3ResolveExprNames(&nc, pE) ){
573 sqlite3ErrorClear(pParse);
574 return 0;
575 }
576
577 /* Try to match the ORDER BY expression against an expression
578 ** in the result set. Return an 1-based index of the matching
579 ** result-set entry.
580 */
581 for(i=0; i<pEList->nExpr; i++){
582 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
583 return i+1;
584 }
585 }
586
587 /* If no match, return 0. */
588 return 0;
589}
590
591/*
592** Generate an ORDER BY or GROUP BY term out-of-range error.
593*/
594static void resolveOutOfRangeError(
595 Parse *pParse, /* The error context into which to write the error */
596 const char *zType, /* "ORDER" or "GROUP" */
597 int i, /* The index (1-based) of the term out of range */
598 int mx /* Largest permissible value of i */
599){
600 sqlite3ErrorMsg(pParse,
601 "%r %s BY term out of range - should be "
602 "between 1 and %d", i, zType, mx);
603}
604
605/*
606** Analyze the ORDER BY clause in a compound SELECT statement. Modify
607** each term of the ORDER BY clause is a constant integer between 1
608** and N where N is the number of columns in the compound SELECT.
609**
610** ORDER BY terms that are already an integer between 1 and N are
611** unmodified. ORDER BY terms that are integers outside the range of
612** 1 through N generate an error. ORDER BY terms that are expressions
613** are matched against result set expressions of compound SELECT
614** beginning with the left-most SELECT and working toward the right.
615** At the first match, the ORDER BY expression is transformed into
616** the integer column number.
617**
618** Return the number of errors seen.
619*/
620static int resolveCompoundOrderBy(
621 Parse *pParse, /* Parsing context. Leave error messages here */
622 Select *pSelect /* The SELECT statement containing the ORDER BY */
623){
624 int i;
625 ExprList *pOrderBy;
626 ExprList *pEList;
627 sqlite3 *db;
628 int moreToDo = 1;
629
630 pOrderBy = pSelect->pOrderBy;
631 if( pOrderBy==0 ) return 0;
632 db = pParse->db;
633#if SQLITE_MAX_COLUMN
634 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
635 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
636 return 1;
637 }
638#endif
639 for(i=0; i<pOrderBy->nExpr; i++){
640 pOrderBy->a[i].done = 0;
641 }
642 pSelect->pNext = 0;
643 while( pSelect->pPrior ){
644 pSelect->pPrior->pNext = pSelect;
645 pSelect = pSelect->pPrior;
646 }
647 while( pSelect && moreToDo ){
648 struct ExprList_item *pItem;
649 moreToDo = 0;
650 pEList = pSelect->pEList;
651 if( pEList==0 ){
652 return 1;
653 }
654 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
655 int iCol = -1;
656 Expr *pE, *pDup;
657 if( pItem->done ) continue;
658 pE = pItem->pExpr;
659 if( sqlite3ExprIsInteger(pE, &iCol) ){
660 if( iCol<0 || iCol>pEList->nExpr ){
661 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
662 return 1;
663 }
664 }else{
665 iCol = resolveAsName(pParse, pEList, pE);
666 if( iCol==0 ){
667 pDup = sqlite3ExprDup(db, pE);
668 if( !db->mallocFailed ){
669 assert(pDup);
670 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
671 }
672 sqlite3ExprDelete(db, pDup);
673 }
674 if( iCol<0 ){
675 return 1;
676 }
677 }
678 if( iCol>0 ){
679 CollSeq *pColl = pE->pColl;
680 int flags = pE->flags & EP_ExpCollate;
681 sqlite3ExprDelete(db, pE);
682 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0, 0, 0);
683 if( pE==0 ) return 1;
684 pE->pColl = pColl;
685 pE->flags |= EP_IntValue | flags;
686 pE->iTable = iCol;
687 pItem->iCol = iCol;
688 pItem->done = 1;
689 }else{
690 moreToDo = 1;
691 }
692 }
693 pSelect = pSelect->pNext;
694 }
695 for(i=0; i<pOrderBy->nExpr; i++){
696 if( pOrderBy->a[i].done==0 ){
697 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
698 "column in the result set", i+1);
699 return 1;
700 }
701 }
702 return 0;
703}
704
705/*
706** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
707** the SELECT statement pSelect. If any term is reference to a
708** result set expression (as determined by the ExprList.a.iCol field)
709** then convert that term into a copy of the corresponding result set
710** column.
711**
712** If any errors are detected, add an error message to pParse and
713** return non-zero. Return zero if no errors are seen.
714*/
715int sqlite3ResolveOrderGroupBy(
716 Parse *pParse, /* Parsing context. Leave error messages here */
717 Select *pSelect, /* The SELECT statement containing the clause */
718 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
719 const char *zType /* "ORDER" or "GROUP" */
720){
721 int i;
722 sqlite3 *db = pParse->db;
723 ExprList *pEList;
724 struct ExprList_item *pItem;
725
726 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
727#if SQLITE_MAX_COLUMN
728 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
729 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
730 return 1;
731 }
732#endif
733 pEList = pSelect->pEList;
734 if( pEList==0 ){
735 return 0;
736 }
737 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
738 if( pItem->iCol ){
739 Expr *pE;
740 CollSeq *pColl;
741 int flags;
742
743 if( pItem->iCol>pEList->nExpr ){
744 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
745 return 1;
746 }
747 pE = pItem->pExpr;
748 pColl = pE->pColl;
749 flags = pE->flags & EP_ExpCollate;
750 sqlite3ExprDelete(db, pE);
751 pE = sqlite3ExprDup(db, pEList->a[pItem->iCol-1].pExpr);
752 pItem->pExpr = pE;
753 if( pE && pColl && flags ){
754 pE->pColl = pColl;
755 pE->flags |= flags;
756 }
757 }
758 }
759 return 0;
760}
761
762/*
763** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
764** The Name context of the SELECT statement is pNC. zType is either
765** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
766**
767** This routine resolves each term of the clause into an expression.
768** If the order-by term is an integer I between 1 and N (where N is the
769** number of columns in the result set of the SELECT) then the expression
770** in the resolution is a copy of the I-th result-set expression. If
771** the order-by term is an identify that corresponds to the AS-name of
772** a result-set expression, then the term resolves to a copy of the
773** result-set expression. Otherwise, the expression is resolved in
774** the usual way - using sqlite3ResolveExprNames().
775**
776** This routine returns the number of errors. If errors occur, then
777** an appropriate error message might be left in pParse. (OOM errors
778** excepted.)
779*/
780static int resolveOrderGroupBy(
781 NameContext *pNC, /* The name context of the SELECT statement */
782 Select *pSelect, /* The SELECT statement holding pOrderBy */
783 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
784 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
785){
786 int i; /* Loop counter */
787 int iCol; /* Column number */
788 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
789 Parse *pParse; /* Parsing context */
790 int nResult; /* Number of terms in the result set */
791
792 if( pOrderBy==0 ) return 0;
793 nResult = pSelect->pEList->nExpr;
794 pParse = pNC->pParse;
795 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
796 Expr *pE = pItem->pExpr;
797 iCol = resolveAsName(pParse, pSelect->pEList, pE);
798 if( iCol<0 ){
799 return 1; /* OOM error */
800 }
801 if( iCol>0 ){
802 /* If an AS-name match is found, mark this ORDER BY column as being
803 ** a copy of the iCol-th result-set column. The subsequent call to
804 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
805 ** copy of the iCol-th result-set expression. */
806 pItem->iCol = iCol;
807 continue;
808 }
809 if( sqlite3ExprIsInteger(pE, &iCol) ){
810 /* The ORDER BY term is an integer constant. Again, set the column
811 ** number so that sqlite3ResolveOrderGroupBy() will convert the
812 ** order-by term to a copy of the result-set expression */
813 if( iCol<1 || iCol>nResult ){
814 resolveOutOfRangeError(pParse, zType, i+1, nResult);
815 return 1;
816 }
817 pItem->iCol = iCol;
818 continue;
819 }
820
821 /* Otherwise, treat the ORDER BY term as an ordinary expression */
822 pItem->iCol = 0;
823 if( sqlite3ResolveExprNames(pNC, pE) ){
824 return 1;
825 }
826 }
827 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
828}
829
830/*
831** Resolve names in the SELECT statement p and all of its descendents.
832*/
833static int resolveSelectStep(Walker *pWalker, Select *p){
834 NameContext *pOuterNC; /* Context that contains this SELECT */
835 NameContext sNC; /* Name context of this SELECT */
836 int isCompound; /* True if p is a compound select */
837 int nCompound; /* Number of compound terms processed so far */
838 Parse *pParse; /* Parsing context */
839 ExprList *pEList; /* Result set expression list */
840 int i; /* Loop counter */
841 ExprList *pGroupBy; /* The GROUP BY clause */
842 Select *pLeftmost; /* Left-most of SELECT of a compound */
843 sqlite3 *db; /* Database connection */
844
845
846 if( p==0 ) return WRC_Continue;
847 if( p->selFlags & SF_Resolved ){
848 return WRC_Prune;
849 }
850 pOuterNC = pWalker->u.pNC;
851 pParse = pWalker->pParse;
852 db = pParse->db;
853
854 /* Normally sqlite3SelectExpand() will be called first and will have
855 ** already expanded this SELECT. However, if this is a subquery within
856 ** an expression, sqlite3ResolveExprNames() will be called without a
857 ** prior call to sqlite3SelectExpand(). When that happens, let
858 ** sqlite3SelectPrep() do all of the processing for this SELECT.
859 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
860 ** this routine in the correct order.
861 */
862 if( (p->selFlags & SF_Expanded)==0 ){
863 sqlite3SelectPrep(pParse, p, pOuterNC);
864 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
865 }
866
867 isCompound = p->pPrior!=0;
868 nCompound = 0;
869 pLeftmost = p;
870 while( p ){
871 assert( (p->selFlags & SF_Expanded)!=0 );
872 assert( (p->selFlags & SF_Resolved)==0 );
873 p->selFlags |= SF_Resolved;
874
875 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
876 ** are not allowed to refer to any names, so pass an empty NameContext.
877 */
878 memset(&sNC, 0, sizeof(sNC));
879 sNC.pParse = pParse;
880 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
881 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
882 return WRC_Abort;
883 }
884
885 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
886 ** resolve the result-set expression list.
887 */
888 sNC.allowAgg = 1;
889 sNC.pSrcList = p->pSrc;
890 sNC.pNext = pOuterNC;
891
892 /* Resolve names in the result set. */
893 pEList = p->pEList;
894 if( !pEList ) return WRC_Abort;
895 for(i=0; i<pEList->nExpr; i++){
896 Expr *pX = pEList->a[i].pExpr;
897 if( sqlite3ResolveExprNames(&sNC, pX) ){
898 return WRC_Abort;
899 }
900 }
901
902 /* Recursively resolve names in all subqueries
903 */
904 for(i=0; i<p->pSrc->nSrc; i++){
905 struct SrcList_item *pItem = &p->pSrc->a[i];
906 if( pItem->pSelect ){
907 const char *zSavedContext = pParse->zAuthContext;
908 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
909 sqlite3ResolveSelectNames(pParse, pItem->pSelect, &sNC);
910 pParse->zAuthContext = zSavedContext;
911 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
912 }
913 }
914
915 /* If there are no aggregate functions in the result-set, and no GROUP BY
916 ** expression, do not allow aggregates in any of the other expressions.
917 */
918 assert( (p->selFlags & SF_Aggregate)==0 );
919 pGroupBy = p->pGroupBy;
920 if( pGroupBy || sNC.hasAgg ){
921 p->selFlags |= SF_Aggregate;
922 }else{
923 sNC.allowAgg = 0;
924 }
925
926 /* If a HAVING clause is present, then there must be a GROUP BY clause.
927 */
928 if( p->pHaving && !pGroupBy ){
929 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
930 return WRC_Abort;
931 }
932
933 /* Add the expression list to the name-context before parsing the
934 ** other expressions in the SELECT statement. This is so that
935 ** expressions in the WHERE clause (etc.) can refer to expressions by
936 ** aliases in the result set.
937 **
938 ** Minor point: If this is the case, then the expression will be
939 ** re-evaluated for each reference to it.
940 */
941 sNC.pEList = p->pEList;
942 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
943 sqlite3ResolveExprNames(&sNC, p->pHaving)
944 ){
945 return WRC_Abort;
946 }
947
948 /* The ORDER BY and GROUP BY clauses may not refer to terms in
949 ** outer queries
950 */
951 sNC.pNext = 0;
952 sNC.allowAgg = 1;
953
954 /* Process the ORDER BY clause for singleton SELECT statements.
955 ** The ORDER BY clause for compounds SELECT statements is handled
956 ** below, after all of the result-sets for all of the elements of
957 ** the compound have been resolved.
958 */
959 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
960 return WRC_Abort;
961 }
962 if( db->mallocFailed ){
963 return WRC_Abort;
964 }
965
966 /* Resolve the GROUP BY clause. At the same time, make sure
967 ** the GROUP BY clause does not contain aggregate functions.
968 */
969 if( pGroupBy ){
970 struct ExprList_item *pItem;
971
972 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
973 return WRC_Abort;
974 }
975 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
976 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
977 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
978 "the GROUP BY clause");
979 return WRC_Abort;
980 }
981 }
982 }
983
984 /* Advance to the next term of the compound
985 */
986 p = p->pPrior;
987 nCompound++;
988 }
989
990 /* Resolve the ORDER BY on a compound SELECT after all terms of
991 ** the compound have been resolved.
992 */
993 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
994 return WRC_Abort;
995 }
996
997 return WRC_Prune;
998}
999
1000/*
1001** This routine walks an expression tree and resolves references to
1002** table columns and result-set columns. At the same time, do error
1003** checking on function usage and set a flag if any aggregate functions
1004** are seen.
1005**
1006** To resolve table columns references we look for nodes (or subtrees) of the
1007** form X.Y.Z or Y.Z or just Z where
1008**
1009** X: The name of a database. Ex: "main" or "temp" or
1010** the symbolic name assigned to an ATTACH-ed database.
1011**
1012** Y: The name of a table in a FROM clause. Or in a trigger
1013** one of the special names "old" or "new".
1014**
1015** Z: The name of a column in table Y.
1016**
1017** The node at the root of the subtree is modified as follows:
1018**
1019** Expr.op Changed to TK_COLUMN
1020** Expr.pTab Points to the Table object for X.Y
1021** Expr.iColumn The column index in X.Y. -1 for the rowid.
1022** Expr.iTable The VDBE cursor number for X.Y
1023**
1024**
1025** To resolve result-set references, look for expression nodes of the
1026** form Z (with no X and Y prefix) where the Z matches the right-hand
1027** size of an AS clause in the result-set of a SELECT. The Z expression
1028** is replaced by a copy of the left-hand side of the result-set expression.
1029** Table-name and function resolution occurs on the substituted expression
1030** tree. For example, in:
1031**
1032** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1033**
1034** The "x" term of the order by is replaced by "a+b" to render:
1035**
1036** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1037**
1038** Function calls are checked to make sure that the function is
1039** defined and that the correct number of arguments are specified.
1040** If the function is an aggregate function, then the pNC->hasAgg is
1041** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1042** If an expression contains aggregate functions then the EP_Agg
1043** property on the expression is set.
1044**
1045** An error message is left in pParse if anything is amiss. The number
1046** if errors is returned.
1047*/
1048int sqlite3ResolveExprNames(
1049 NameContext *pNC, /* Namespace to resolve expressions in. */
1050 Expr *pExpr /* The expression to be analyzed. */
1051){
1052 int savedHasAgg;
1053 Walker w;
1054
1055 if( pExpr==0 ) return 0;
1056#if SQLITE_MAX_EXPR_DEPTH>0
1057 {
1058 Parse *pParse = pNC->pParse;
1059 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1060 return 1;
1061 }
1062 pParse->nHeight += pExpr->nHeight;
1063 }
1064#endif
1065 savedHasAgg = pNC->hasAgg;
1066 pNC->hasAgg = 0;
1067 w.xExprCallback = resolveExprStep;
1068 w.xSelectCallback = resolveSelectStep;
1069 w.pParse = pNC->pParse;
1070 w.u.pNC = pNC;
1071 sqlite3WalkExpr(&w, pExpr);
1072#if SQLITE_MAX_EXPR_DEPTH>0
1073 pNC->pParse->nHeight -= pExpr->nHeight;
1074#endif
1075 if( pNC->nErr>0 ){
1076 ExprSetProperty(pExpr, EP_Error);
1077 }
1078 if( pNC->hasAgg ){
1079 ExprSetProperty(pExpr, EP_Agg);
1080 }else if( savedHasAgg ){
1081 pNC->hasAgg = 1;
1082 }
1083 return ExprHasProperty(pExpr, EP_Error);
1084}
drh7d10d5a2008-08-20 16:35:10 +00001085
1086
1087/*
1088** Resolve all names in all expressions of a SELECT and in all
1089** decendents of the SELECT, including compounds off of p->pPrior,
1090** subqueries in expressions, and subqueries used as FROM clause
1091** terms.
1092**
1093** See sqlite3ResolveExprNames() for a description of the kinds of
1094** transformations that occur.
1095**
1096** All SELECT statements should have been expanded using
1097** sqlite3SelectExpand() prior to invoking this routine.
1098*/
1099void sqlite3ResolveSelectNames(
1100 Parse *pParse, /* The parser context */
1101 Select *p, /* The SELECT statement being coded. */
1102 NameContext *pOuterNC /* Name context for parent SELECT statement */
1103){
1104 Walker w;
1105
1106 if( p ){
1107 w.xExprCallback = resolveExprStep;
1108 w.xSelectCallback = resolveSelectStep;
1109 w.pParse = pParse;
1110 w.u.pNC = pOuterNC;
1111 sqlite3WalkSelect(&w, p);
1112 }
1113}