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