000001  /*
000002  ** 2008 August 18
000003  **
000004  ** The author disclaims copyright to this source code.  In place of
000005  ** a legal notice, here is a blessing:
000006  **
000007  **    May you do good and not evil.
000008  **    May you find forgiveness for yourself and forgive others.
000009  **    May you share freely, never taking more than you give.
000010  **
000011  *************************************************************************
000012  **
000013  ** This file contains routines used for walking the parser tree and
000014  ** resolve all identifiers by associating them with a particular
000015  ** table and column.
000016  */
000017  #include "sqliteInt.h"
000018  
000019  /*
000020  ** Magic table number to mean the EXCLUDED table in an UPSERT statement.
000021  */
000022  #define EXCLUDED_TABLE_NUMBER  2
000023  
000024  /*
000025  ** Walk the expression tree pExpr and increase the aggregate function
000026  ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
000027  ** This needs to occur when copying a TK_AGG_FUNCTION node from an
000028  ** outer query into an inner subquery.
000029  **
000030  ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
000031  ** is a helper function - a callback for the tree walker.
000032  **
000033  ** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
000034  */
000035  static int incrAggDepth(Walker *pWalker, Expr *pExpr){
000036    if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
000037    return WRC_Continue;
000038  }
000039  static void incrAggFunctionDepth(Expr *pExpr, int N){
000040    if( N>0 ){
000041      Walker w;
000042      memset(&w, 0, sizeof(w));
000043      w.xExprCallback = incrAggDepth;
000044      w.u.n = N;
000045      sqlite3WalkExpr(&w, pExpr);
000046    }
000047  }
000048  
000049  /*
000050  ** Turn the pExpr expression into an alias for the iCol-th column of the
000051  ** result set in pEList.
000052  **
000053  ** If the reference is followed by a COLLATE operator, then make sure
000054  ** the COLLATE operator is preserved.  For example:
000055  **
000056  **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
000057  **
000058  ** Should be transformed into:
000059  **
000060  **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
000061  **
000062  ** The nSubquery parameter specifies how many levels of subquery the
000063  ** alias is removed from the original expression.  The usual value is
000064  ** zero but it might be more if the alias is contained within a subquery
000065  ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
000066  ** structures must be increased by the nSubquery amount.
000067  */
000068  static void resolveAlias(
000069    Parse *pParse,         /* Parsing context */
000070    ExprList *pEList,      /* A result set */
000071    int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
000072    Expr *pExpr,           /* Transform this into an alias to the result set */
000073    int nSubquery          /* Number of subqueries that the label is moving */
000074  ){
000075    Expr *pOrig;           /* The iCol-th column of the result set */
000076    Expr *pDup;            /* Copy of pOrig */
000077    sqlite3 *db;           /* The database connection */
000078  
000079    assert( iCol>=0 && iCol<pEList->nExpr );
000080    pOrig = pEList->a[iCol].pExpr;
000081    assert( pOrig!=0 );
000082    db = pParse->db;
000083    pDup = sqlite3ExprDup(db, pOrig, 0);
000084    if( db->mallocFailed ){
000085      sqlite3ExprDelete(db, pDup);
000086      pDup = 0;
000087    }else{
000088      Expr temp;
000089      incrAggFunctionDepth(pDup, nSubquery);
000090      if( pExpr->op==TK_COLLATE ){
000091        assert( !ExprHasProperty(pExpr, EP_IntValue) );
000092        pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
000093      }
000094      memcpy(&temp, pDup, sizeof(Expr));
000095      memcpy(pDup, pExpr, sizeof(Expr));
000096      memcpy(pExpr, &temp, sizeof(Expr));
000097      if( ExprHasProperty(pExpr, EP_WinFunc) ){
000098        if( ALWAYS(pExpr->y.pWin!=0) ){
000099          pExpr->y.pWin->pOwner = pExpr;
000100        }
000101      }
000102      sqlite3ExprDeferredDelete(pParse, pDup);
000103    }
000104  }
000105  
000106  /*
000107  ** Subqueries stores the original database, table and column names for their
000108  ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
000109  ** Check to see if the zSpan given to this routine matches the zDb, zTab,
000110  ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
000111  ** match anything.
000112  */
000113  int sqlite3MatchEName(
000114    const struct ExprList_item *pItem,
000115    const char *zCol,
000116    const char *zTab,
000117    const char *zDb
000118  ){
000119    int n;
000120    const char *zSpan;
000121    if( pItem->fg.eEName!=ENAME_TAB ) return 0;
000122    zSpan = pItem->zEName;
000123    for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
000124    if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
000125      return 0;
000126    }
000127    zSpan += n+1;
000128    for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
000129    if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
000130      return 0;
000131    }
000132    zSpan += n+1;
000133    if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
000134      return 0;
000135    }
000136    return 1;
000137  }
000138  
000139  /*
000140  ** Return TRUE if the double-quoted string  mis-feature should be supported.
000141  */
000142  static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
000143    if( db->init.busy ) return 1;  /* Always support for legacy schemas */
000144    if( pTopNC->ncFlags & NC_IsDDL ){
000145      /* Currently parsing a DDL statement */
000146      if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
000147        return 1;
000148      }
000149      return (db->flags & SQLITE_DqsDDL)!=0;
000150    }else{
000151      /* Currently parsing a DML statement */
000152      return (db->flags & SQLITE_DqsDML)!=0;
000153    }
000154  }
000155  
000156  /*
000157  ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
000158  ** return the appropriate colUsed mask.
000159  */
000160  Bitmask sqlite3ExprColUsed(Expr *pExpr){
000161    int n;
000162    Table *pExTab;
000163  
000164    n = pExpr->iColumn;
000165    assert( ExprUseYTab(pExpr) );
000166    pExTab = pExpr->y.pTab;
000167    assert( pExTab!=0 );
000168    if( (pExTab->tabFlags & TF_HasGenerated)!=0
000169     && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
000170    ){
000171      testcase( pExTab->nCol==BMS-1 );
000172      testcase( pExTab->nCol==BMS );
000173      return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
000174    }else{
000175      testcase( n==BMS-1 );
000176      testcase( n==BMS );
000177      if( n>=BMS ) n = BMS-1;
000178      return ((Bitmask)1)<<n;
000179    }
000180  }
000181  
000182  /*
000183  ** Create a new expression term for the column specified by pMatch and
000184  ** iColumn.  Append this new expression term to the FULL JOIN Match set
000185  ** in *ppList.  Create a new *ppList if this is the first term in the
000186  ** set.
000187  */
000188  static void extendFJMatch(
000189    Parse *pParse,          /* Parsing context */
000190    ExprList **ppList,      /* ExprList to extend */
000191    SrcItem *pMatch,        /* Source table containing the column */
000192    i16 iColumn             /* The column number */
000193  ){
000194    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
000195    if( pNew ){
000196      pNew->iTable = pMatch->iCursor;
000197      pNew->iColumn = iColumn;
000198      pNew->y.pTab = pMatch->pTab;
000199      assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
000200      ExprSetProperty(pNew, EP_CanBeNull);
000201      *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew);
000202    }
000203  }
000204  
000205  /*
000206  ** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
000207  */
000208  static SQLITE_NOINLINE int isValidSchemaTableName(
000209    const char *zTab,         /* Name as it appears in the SQL */
000210    Table *pTab,              /* The schema table we are trying to match */
000211    Schema *pSchema           /* non-NULL if a database qualifier is present */
000212  ){
000213    const char *zLegacy;
000214    assert( pTab!=0 );
000215    assert( pTab->tnum==1 );
000216    if( sqlite3StrNICmp(zTab, "sqlite_", 7)!=0 ) return 0;
000217    zLegacy = pTab->zName;
000218    if( strcmp(zLegacy+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
000219      if( sqlite3StrICmp(zTab+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
000220        return 1;
000221      }
000222      if( pSchema==0 ) return 0;
000223      if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1;
000224      if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
000225    }else{
000226      if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
000227    }
000228    return 0;
000229  }
000230  
000231  /*
000232  ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
000233  ** that name in the set of source tables in pSrcList and make the pExpr
000234  ** expression node refer back to that source column.  The following changes
000235  ** are made to pExpr:
000236  **
000237  **    pExpr->iDb           Set the index in db->aDb[] of the database X
000238  **                         (even if X is implied).
000239  **    pExpr->iTable        Set to the cursor number for the table obtained
000240  **                         from pSrcList.
000241  **    pExpr->y.pTab        Points to the Table structure of X.Y (even if
000242  **                         X and/or Y are implied.)
000243  **    pExpr->iColumn       Set to the column number within the table.
000244  **    pExpr->op            Set to TK_COLUMN.
000245  **    pExpr->pLeft         Any expression this points to is deleted
000246  **    pExpr->pRight        Any expression this points to is deleted.
000247  **
000248  ** The zDb variable is the name of the database (the "X").  This value may be
000249  ** NULL meaning that name is of the form Y.Z or Z.  Any available database
000250  ** can be used.  The zTable variable is the name of the table (the "Y").  This
000251  ** value can be NULL if zDb is also NULL.  If zTable is NULL it
000252  ** means that the form of the name is Z and that columns from any table
000253  ** can be used.
000254  **
000255  ** If the name cannot be resolved unambiguously, leave an error message
000256  ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
000257  */
000258  static int lookupName(
000259    Parse *pParse,       /* The parsing context */
000260    const char *zDb,     /* Name of the database containing table, or NULL */
000261    const char *zTab,    /* Name of table containing column, or NULL */
000262    const char *zCol,    /* Name of the column. */
000263    NameContext *pNC,    /* The name context used to resolve the name */
000264    Expr *pExpr          /* Make this EXPR node point to the selected column */
000265  ){
000266    int i, j;                         /* Loop counters */
000267    int cnt = 0;                      /* Number of matching column names */
000268    int cntTab = 0;                   /* Number of matching table names */
000269    int nSubquery = 0;                /* How many levels of subquery */
000270    sqlite3 *db = pParse->db;         /* The database connection */
000271    SrcItem *pItem;                   /* Use for looping over pSrcList items */
000272    SrcItem *pMatch = 0;              /* The matching pSrcList item */
000273    NameContext *pTopNC = pNC;        /* First namecontext in the list */
000274    Schema *pSchema = 0;              /* Schema of the expression */
000275    int eNewExprOp = TK_COLUMN;       /* New value for pExpr->op on success */
000276    Table *pTab = 0;                  /* Table holding the row */
000277    Column *pCol;                     /* A column of pTab */
000278    ExprList *pFJMatch = 0;           /* Matches for FULL JOIN .. USING */
000279  
000280    assert( pNC );     /* the name context cannot be NULL. */
000281    assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
000282    assert( zDb==0 || zTab!=0 );
000283    assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
000284  
000285    /* Initialize the node to no-match */
000286    pExpr->iTable = -1;
000287    ExprSetVVAProperty(pExpr, EP_NoReduce);
000288  
000289    /* Translate the schema name in zDb into a pointer to the corresponding
000290    ** schema.  If not found, pSchema will remain NULL and nothing will match
000291    ** resulting in an appropriate error message toward the end of this routine
000292    */
000293    if( zDb ){
000294      testcase( pNC->ncFlags & NC_PartIdx );
000295      testcase( pNC->ncFlags & NC_IsCheck );
000296      if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
000297        /* Silently ignore database qualifiers inside CHECK constraints and
000298        ** partial indices.  Do not raise errors because that might break
000299        ** legacy and because it does not hurt anything to just ignore the
000300        ** database name. */
000301        zDb = 0;
000302      }else{
000303        for(i=0; i<db->nDb; i++){
000304          assert( db->aDb[i].zDbSName );
000305          if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
000306            pSchema = db->aDb[i].pSchema;
000307            break;
000308          }
000309        }
000310        if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
000311          /* This branch is taken when the main database has been renamed
000312          ** using SQLITE_DBCONFIG_MAINDBNAME. */
000313          pSchema = db->aDb[0].pSchema;
000314          zDb = db->aDb[0].zDbSName;
000315        }
000316      }
000317    }
000318  
000319    /* Start at the inner-most context and move outward until a match is found */
000320    assert( pNC && cnt==0 );
000321    do{
000322      ExprList *pEList;
000323      SrcList *pSrcList = pNC->pSrcList;
000324  
000325      if( pSrcList ){
000326        for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
000327          u8 hCol;
000328          pTab = pItem->pTab;
000329          assert( pTab!=0 && pTab->zName!=0 );
000330          assert( pTab->nCol>0 || pParse->nErr );
000331          assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
000332          if( pItem->fg.isNestedFrom ){
000333            /* In this case, pItem is a subquery that has been formed from a
000334            ** parenthesized subset of the FROM clause terms.  Example:
000335            **   .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
000336            **                          \_________________________/
000337            **             This pItem -------------^
000338            */
000339            int hit = 0;
000340            assert( pItem->pSelect!=0 );
000341            pEList = pItem->pSelect->pEList;
000342            assert( pEList!=0 );
000343            assert( pEList->nExpr==pTab->nCol );
000344            for(j=0; j<pEList->nExpr; j++){
000345              if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
000346                continue;
000347              }
000348              if( cnt>0 ){
000349                if( pItem->fg.isUsing==0
000350                 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
000351                ){
000352                  /* Two or more tables have the same column name which is
000353                  ** not joined by USING.  This is an error.  Signal as much
000354                  ** by clearing pFJMatch and letting cnt go above 1. */
000355                  sqlite3ExprListDelete(db, pFJMatch);
000356                  pFJMatch = 0;
000357                }else
000358                if( (pItem->fg.jointype & JT_RIGHT)==0 ){
000359                  /* An INNER or LEFT JOIN.  Use the left-most table */
000360                  continue;
000361                }else
000362                if( (pItem->fg.jointype & JT_LEFT)==0 ){
000363                  /* A RIGHT JOIN.  Use the right-most table */
000364                  cnt = 0;
000365                  sqlite3ExprListDelete(db, pFJMatch);
000366                  pFJMatch = 0;
000367                }else{
000368                  /* For a FULL JOIN, we must construct a coalesce() func */
000369                  extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
000370                }
000371              }
000372              cnt++;
000373              cntTab = 2;
000374              pMatch = pItem;
000375              pExpr->iColumn = j;
000376              pEList->a[j].fg.bUsed = 1;
000377              hit = 1;
000378              if( pEList->a[j].fg.bUsingTerm ) break;
000379            }
000380            if( hit || zTab==0 ) continue;
000381          }
000382          assert( zDb==0 || zTab!=0 );
000383          if( zTab ){
000384            if( zDb ){
000385              if( pTab->pSchema!=pSchema ) continue;
000386              if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
000387            }
000388            if( pItem->zAlias!=0 ){
000389              if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
000390                continue;
000391              }
000392            }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
000393              if( pTab->tnum!=1 ) continue;
000394              if( !isValidSchemaTableName(zTab, pTab, pSchema) ) continue;
000395            }
000396            assert( ExprUseYTab(pExpr) );
000397            if( IN_RENAME_OBJECT && pItem->zAlias ){
000398              sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
000399            }
000400          }
000401          hCol = sqlite3StrIHash(zCol);
000402          for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
000403            if( pCol->hName==hCol
000404             && sqlite3StrICmp(pCol->zCnName, zCol)==0
000405            ){
000406              if( cnt>0 ){
000407                if( pItem->fg.isUsing==0
000408                 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
000409                ){
000410                  /* Two or more tables have the same column name which is
000411                  ** not joined by USING.  This is an error.  Signal as much
000412                  ** by clearing pFJMatch and letting cnt go above 1. */
000413                  sqlite3ExprListDelete(db, pFJMatch);
000414                  pFJMatch = 0;
000415                }else
000416                if( (pItem->fg.jointype & JT_RIGHT)==0 ){
000417                  /* An INNER or LEFT JOIN.  Use the left-most table */
000418                  continue;
000419                }else
000420                if( (pItem->fg.jointype & JT_LEFT)==0 ){
000421                  /* A RIGHT JOIN.  Use the right-most table */
000422                  cnt = 0;
000423                  sqlite3ExprListDelete(db, pFJMatch);
000424                  pFJMatch = 0;
000425                }else{
000426                  /* For a FULL JOIN, we must construct a coalesce() func */
000427                  extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
000428                }
000429              }
000430              cnt++;
000431              pMatch = pItem;
000432              /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
000433              pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
000434              if( pItem->fg.isNestedFrom ){
000435                sqlite3SrcItemColumnUsed(pItem, j);
000436              }
000437              break;
000438            }
000439          }
000440          if( 0==cnt && VisibleRowid(pTab) ){
000441            cntTab++;
000442            pMatch = pItem;
000443          }
000444        }
000445        if( pMatch ){
000446          pExpr->iTable = pMatch->iCursor;
000447          assert( ExprUseYTab(pExpr) );
000448          pExpr->y.pTab = pMatch->pTab;
000449          if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
000450            ExprSetProperty(pExpr, EP_CanBeNull);
000451          }
000452          pSchema = pExpr->y.pTab->pSchema;
000453        }
000454      } /* if( pSrcList ) */
000455  
000456  #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
000457      /* If we have not already resolved the name, then maybe
000458      ** it is a new.* or old.* trigger argument reference.  Or
000459      ** maybe it is an excluded.* from an upsert.  Or maybe it is
000460      ** a reference in the RETURNING clause to a table being modified.
000461      */
000462      if( cnt==0 && zDb==0 ){
000463        pTab = 0;
000464  #ifndef SQLITE_OMIT_TRIGGER
000465        if( pParse->pTriggerTab!=0 ){
000466          int op = pParse->eTriggerOp;
000467          assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
000468          if( pParse->bReturning ){
000469            if( (pNC->ncFlags & NC_UBaseReg)!=0
000470             && ALWAYS(zTab==0
000471                       || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0)
000472            ){
000473              pExpr->iTable = op!=TK_DELETE;
000474              pTab = pParse->pTriggerTab;
000475            }
000476          }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
000477            pExpr->iTable = 1;
000478            pTab = pParse->pTriggerTab;
000479          }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
000480            pExpr->iTable = 0;
000481            pTab = pParse->pTriggerTab;
000482          }
000483        }
000484  #endif /* SQLITE_OMIT_TRIGGER */
000485  #ifndef SQLITE_OMIT_UPSERT
000486        if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
000487          Upsert *pUpsert = pNC->uNC.pUpsert;
000488          if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
000489            pTab = pUpsert->pUpsertSrc->a[0].pTab;
000490            pExpr->iTable = EXCLUDED_TABLE_NUMBER;
000491          }
000492        }
000493  #endif /* SQLITE_OMIT_UPSERT */
000494  
000495        if( pTab ){
000496          int iCol;
000497          u8 hCol = sqlite3StrIHash(zCol);
000498          pSchema = pTab->pSchema;
000499          cntTab++;
000500          for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
000501            if( pCol->hName==hCol
000502             && sqlite3StrICmp(pCol->zCnName, zCol)==0
000503            ){
000504              if( iCol==pTab->iPKey ){
000505                iCol = -1;
000506              }
000507              break;
000508            }
000509          }
000510          if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
000511            /* IMP: R-51414-32910 */
000512            iCol = -1;
000513          }
000514          if( iCol<pTab->nCol ){
000515            cnt++;
000516            pMatch = 0;
000517  #ifndef SQLITE_OMIT_UPSERT
000518            if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
000519              testcase( iCol==(-1) );
000520              assert( ExprUseYTab(pExpr) );
000521              if( IN_RENAME_OBJECT ){
000522                pExpr->iColumn = iCol;
000523                pExpr->y.pTab = pTab;
000524                eNewExprOp = TK_COLUMN;
000525              }else{
000526                pExpr->iTable = pNC->uNC.pUpsert->regData +
000527                   sqlite3TableColumnToStorage(pTab, iCol);
000528                eNewExprOp = TK_REGISTER;
000529              }
000530            }else
000531  #endif /* SQLITE_OMIT_UPSERT */
000532            {
000533              assert( ExprUseYTab(pExpr) );
000534              pExpr->y.pTab = pTab;
000535              if( pParse->bReturning ){
000536                eNewExprOp = TK_REGISTER;
000537                pExpr->op2 = TK_COLUMN;
000538                pExpr->iColumn = iCol;
000539                pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
000540                   sqlite3TableColumnToStorage(pTab, iCol) + 1;
000541              }else{
000542                pExpr->iColumn = (i16)iCol;
000543                eNewExprOp = TK_TRIGGER;
000544  #ifndef SQLITE_OMIT_TRIGGER
000545                if( iCol<0 ){
000546                  pExpr->affExpr = SQLITE_AFF_INTEGER;
000547                }else if( pExpr->iTable==0 ){
000548                  testcase( iCol==31 );
000549                  testcase( iCol==32 );
000550                  pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
000551                }else{
000552                  testcase( iCol==31 );
000553                  testcase( iCol==32 );
000554                  pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
000555                }
000556  #endif /* SQLITE_OMIT_TRIGGER */
000557              }
000558            }
000559          }
000560        }
000561      }
000562  #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
000563  
000564      /*
000565      ** Perhaps the name is a reference to the ROWID
000566      */
000567      if( cnt==0
000568       && cntTab==1
000569       && pMatch
000570       && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
000571       && sqlite3IsRowid(zCol)
000572       && ALWAYS(VisibleRowid(pMatch->pTab))
000573      ){
000574        cnt = 1;
000575        pExpr->iColumn = -1;
000576        pExpr->affExpr = SQLITE_AFF_INTEGER;
000577      }
000578  
000579      /*
000580      ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
000581      ** might refer to an result-set alias.  This happens, for example, when
000582      ** we are resolving names in the WHERE clause of the following command:
000583      **
000584      **     SELECT a+b AS x FROM table WHERE x<10;
000585      **
000586      ** In cases like this, replace pExpr with a copy of the expression that
000587      ** forms the result set entry ("a+b" in the example) and return immediately.
000588      ** Note that the expression in the result set should have already been
000589      ** resolved by the time the WHERE clause is resolved.
000590      **
000591      ** The ability to use an output result-set column in the WHERE, GROUP BY,
000592      ** or HAVING clauses, or as part of a larger expression in the ORDER BY
000593      ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
000594      ** is supported for backwards compatibility only. Hence, we issue a warning
000595      ** on sqlite3_log() whenever the capability is used.
000596      */
000597      if( cnt==0
000598       && (pNC->ncFlags & NC_UEList)!=0
000599       && zTab==0
000600      ){
000601        pEList = pNC->uNC.pEList;
000602        assert( pEList!=0 );
000603        for(j=0; j<pEList->nExpr; j++){
000604          char *zAs = pEList->a[j].zEName;
000605          if( pEList->a[j].fg.eEName==ENAME_NAME
000606           && sqlite3_stricmp(zAs, zCol)==0
000607          ){
000608            Expr *pOrig;
000609            assert( pExpr->pLeft==0 && pExpr->pRight==0 );
000610            assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
000611            assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
000612            pOrig = pEList->a[j].pExpr;
000613            if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
000614              sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
000615              return WRC_Abort;
000616            }
000617            if( ExprHasProperty(pOrig, EP_Win)
000618             && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
000619            ){
000620              sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
000621              return WRC_Abort;
000622            }
000623            if( sqlite3ExprVectorSize(pOrig)!=1 ){
000624              sqlite3ErrorMsg(pParse, "row value misused");
000625              return WRC_Abort;
000626            }
000627            resolveAlias(pParse, pEList, j, pExpr, nSubquery);
000628            cnt = 1;
000629            pMatch = 0;
000630            assert( zTab==0 && zDb==0 );
000631            if( IN_RENAME_OBJECT ){
000632              sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
000633            }
000634            goto lookupname_end;
000635          }
000636        }
000637      }
000638  
000639      /* Advance to the next name context.  The loop will exit when either
000640      ** we have a match (cnt>0) or when we run out of name contexts.
000641      */
000642      if( cnt ) break;
000643      pNC = pNC->pNext;
000644      nSubquery++;
000645    }while( pNC );
000646  
000647  
000648    /*
000649    ** If X and Y are NULL (in other words if only the column name Z is
000650    ** supplied) and the value of Z is enclosed in double-quotes, then
000651    ** Z is a string literal if it doesn't match any column names.  In that
000652    ** case, we need to return right away and not make any changes to
000653    ** pExpr.
000654    **
000655    ** Because no reference was made to outer contexts, the pNC->nRef
000656    ** fields are not changed in any context.
000657    */
000658    if( cnt==0 && zTab==0 ){
000659      assert( pExpr->op==TK_ID );
000660      if( ExprHasProperty(pExpr,EP_DblQuoted)
000661       && areDoubleQuotedStringsEnabled(db, pTopNC)
000662      ){
000663        /* If a double-quoted identifier does not match any known column name,
000664        ** then treat it as a string.
000665        **
000666        ** This hack was added in the early days of SQLite in a misguided attempt
000667        ** to be compatible with MySQL 3.x, which used double-quotes for strings.
000668        ** I now sorely regret putting in this hack. The effect of this hack is
000669        ** that misspelled identifier names are silently converted into strings
000670        ** rather than causing an error, to the frustration of countless
000671        ** programmers. To all those frustrated programmers, my apologies.
000672        **
000673        ** Someday, I hope to get rid of this hack. Unfortunately there is
000674        ** a huge amount of legacy SQL that uses it. So for now, we just
000675        ** issue a warning.
000676        */
000677        sqlite3_log(SQLITE_WARNING,
000678          "double-quoted string literal: \"%w\"", zCol);
000679  #ifdef SQLITE_ENABLE_NORMALIZE
000680        sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
000681  #endif
000682        pExpr->op = TK_STRING;
000683        memset(&pExpr->y, 0, sizeof(pExpr->y));
000684        return WRC_Prune;
000685      }
000686      if( sqlite3ExprIdToTrueFalse(pExpr) ){
000687        return WRC_Prune;
000688      }
000689    }
000690  
000691    /*
000692    ** cnt==0 means there was not match.
000693    ** cnt>1 means there were two or more matches.
000694    **
000695    ** cnt==0 is always an error.  cnt>1 is often an error, but might
000696    ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
000697    */
000698    assert( pFJMatch==0 || cnt>0 );
000699    assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
000700    if( cnt!=1 ){
000701      const char *zErr;
000702      if( pFJMatch ){
000703        if( pFJMatch->nExpr==cnt-1 ){
000704          if( ExprHasProperty(pExpr,EP_Leaf) ){
000705            ExprClearProperty(pExpr,EP_Leaf);
000706          }else{
000707            sqlite3ExprDelete(db, pExpr->pLeft);
000708            pExpr->pLeft = 0;
000709            sqlite3ExprDelete(db, pExpr->pRight);
000710            pExpr->pRight = 0;
000711          }
000712          extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
000713          pExpr->op = TK_FUNCTION;
000714          pExpr->u.zToken = "coalesce";
000715          pExpr->x.pList = pFJMatch;
000716          cnt = 1;
000717          goto lookupname_end;
000718        }else{
000719          sqlite3ExprListDelete(db, pFJMatch);
000720          pFJMatch = 0;
000721        }
000722      }
000723      zErr = cnt==0 ? "no such column" : "ambiguous column name";
000724      if( zDb ){
000725        sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
000726      }else if( zTab ){
000727        sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
000728      }else{
000729        sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
000730      }
000731      sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
000732      pParse->checkSchema = 1;
000733      pTopNC->nNcErr++;
000734    }
000735    assert( pFJMatch==0 );
000736  
000737    /* Remove all substructure from pExpr */
000738    if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
000739      sqlite3ExprDelete(db, pExpr->pLeft);
000740      pExpr->pLeft = 0;
000741      sqlite3ExprDelete(db, pExpr->pRight);
000742      pExpr->pRight = 0;
000743      ExprSetProperty(pExpr, EP_Leaf);
000744    }
000745  
000746    /* If a column from a table in pSrcList is referenced, then record
000747    ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
000748    ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  Bit 63 is
000749    ** set if the 63rd or any subsequent column is used.
000750    **
000751    ** The colUsed mask is an optimization used to help determine if an
000752    ** index is a covering index.  The correct answer is still obtained
000753    ** if the mask contains extra set bits.  However, it is important to
000754    ** avoid setting bits beyond the maximum column number of the table.
000755    ** (See ticket [b92e5e8ec2cdbaa1]).
000756    **
000757    ** If a generated column is referenced, set bits for every column
000758    ** of the table.
000759    */
000760    if( pExpr->iColumn>=0 && pMatch!=0 ){
000761      pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
000762    }
000763  
000764    pExpr->op = eNewExprOp;
000765  lookupname_end:
000766    if( cnt==1 ){
000767      assert( pNC!=0 );
000768  #ifndef SQLITE_OMIT_AUTHORIZATION
000769      if( pParse->db->xAuth
000770       && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
000771      ){
000772        sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
000773      }
000774  #endif
000775      /* Increment the nRef value on all name contexts from TopNC up to
000776      ** the point where the name matched. */
000777      for(;;){
000778        assert( pTopNC!=0 );
000779        pTopNC->nRef++;
000780        if( pTopNC==pNC ) break;
000781        pTopNC = pTopNC->pNext;
000782      }
000783      return WRC_Prune;
000784    } else {
000785      return WRC_Abort;
000786    }
000787  }
000788  
000789  /*
000790  ** Allocate and return a pointer to an expression to load the column iCol
000791  ** from datasource iSrc in SrcList pSrc.
000792  */
000793  Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
000794    Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
000795    if( p ){
000796      SrcItem *pItem = &pSrc->a[iSrc];
000797      Table *pTab;
000798      assert( ExprUseYTab(p) );
000799      pTab = p->y.pTab = pItem->pTab;
000800      p->iTable = pItem->iCursor;
000801      if( p->y.pTab->iPKey==iCol ){
000802        p->iColumn = -1;
000803      }else{
000804        p->iColumn = (ynVar)iCol;
000805        if( (pTab->tabFlags & TF_HasGenerated)!=0
000806         && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
000807        ){
000808          testcase( pTab->nCol==63 );
000809          testcase( pTab->nCol==64 );
000810          pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
000811        }else{
000812          testcase( iCol==BMS );
000813          testcase( iCol==BMS-1 );
000814          pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
000815        }
000816      }
000817    }
000818    return p;
000819  }
000820  
000821  /*
000822  ** Report an error that an expression is not valid for some set of
000823  ** pNC->ncFlags values determined by validMask.
000824  **
000825  ** static void notValid(
000826  **   Parse *pParse,       // Leave error message here
000827  **   NameContext *pNC,    // The name context
000828  **   const char *zMsg,    // Type of error
000829  **   int validMask,       // Set of contexts for which prohibited
000830  **   Expr *pExpr          // Invalidate this expression on error
000831  ** ){...}
000832  **
000833  ** As an optimization, since the conditional is almost always false
000834  ** (because errors are rare), the conditional is moved outside of the
000835  ** function call using a macro.
000836  */
000837  static void notValidImpl(
000838     Parse *pParse,       /* Leave error message here */
000839     NameContext *pNC,    /* The name context */
000840     const char *zMsg,    /* Type of error */
000841     Expr *pExpr,         /* Invalidate this expression on error */
000842     Expr *pError         /* Associate error with this expression */
000843  ){
000844    const char *zIn = "partial index WHERE clauses";
000845    if( pNC->ncFlags & NC_IdxExpr )      zIn = "index expressions";
000846  #ifndef SQLITE_OMIT_CHECK
000847    else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
000848  #endif
000849  #ifndef SQLITE_OMIT_GENERATED_COLUMNS
000850    else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
000851  #endif
000852    sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
000853    if( pExpr ) pExpr->op = TK_NULL;
000854    sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
000855  }
000856  #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
000857    assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
000858    if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
000859  
000860  /*
000861  ** Expression p should encode a floating point value between 1.0 and 0.0.
000862  ** Return 1024 times this value.  Or return -1 if p is not a floating point
000863  ** value between 1.0 and 0.0.
000864  */
000865  static int exprProbability(Expr *p){
000866    double r = -1.0;
000867    if( p->op!=TK_FLOAT ) return -1;
000868    assert( !ExprHasProperty(p, EP_IntValue) );
000869    sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
000870    assert( r>=0.0 );
000871    if( r>1.0 ) return -1;
000872    return (int)(r*134217728.0);
000873  }
000874  
000875  /*
000876  ** This routine is callback for sqlite3WalkExpr().
000877  **
000878  ** Resolve symbolic names into TK_COLUMN operators for the current
000879  ** node in the expression tree.  Return 0 to continue the search down
000880  ** the tree or 2 to abort the tree walk.
000881  **
000882  ** This routine also does error checking and name resolution for
000883  ** function names.  The operator for aggregate functions is changed
000884  ** to TK_AGG_FUNCTION.
000885  */
000886  static int resolveExprStep(Walker *pWalker, Expr *pExpr){
000887    NameContext *pNC;
000888    Parse *pParse;
000889  
000890    pNC = pWalker->u.pNC;
000891    assert( pNC!=0 );
000892    pParse = pNC->pParse;
000893    assert( pParse==pWalker->pParse );
000894  
000895  #ifndef NDEBUG
000896    if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
000897      SrcList *pSrcList = pNC->pSrcList;
000898      int i;
000899      for(i=0; i<pNC->pSrcList->nSrc; i++){
000900        assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
000901      }
000902    }
000903  #endif
000904    switch( pExpr->op ){
000905  
000906      /* The special operator TK_ROW means use the rowid for the first
000907      ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
000908      ** clause processing on UPDATE and DELETE statements, and by
000909      ** UPDATE ... FROM statement processing.
000910      */
000911      case TK_ROW: {
000912        SrcList *pSrcList = pNC->pSrcList;
000913        SrcItem *pItem;
000914        assert( pSrcList && pSrcList->nSrc>=1 );
000915        pItem = pSrcList->a;
000916        pExpr->op = TK_COLUMN;
000917        assert( ExprUseYTab(pExpr) );
000918        pExpr->y.pTab = pItem->pTab;
000919        pExpr->iTable = pItem->iCursor;
000920        pExpr->iColumn--;
000921        pExpr->affExpr = SQLITE_AFF_INTEGER;
000922        break;
000923      }
000924  
000925      /* An optimization:  Attempt to convert
000926      **
000927      **      "expr IS NOT NULL"  -->  "TRUE"
000928      **      "expr IS NULL"      -->  "FALSE"
000929      **
000930      ** if we can prove that "expr" is never NULL.  Call this the
000931      ** "NOT NULL strength reduction optimization".
000932      **
000933      ** If this optimization occurs, also restore the NameContext ref-counts
000934      ** to the state they where in before the "column" LHS expression was
000935      ** resolved.  This prevents "column" from being counted as having been
000936      ** referenced, which might prevent a SELECT from being erroneously
000937      ** marked as correlated.
000938      */
000939      case TK_NOTNULL:
000940      case TK_ISNULL: {
000941        int anRef[8];
000942        NameContext *p;
000943        int i;
000944        for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
000945          anRef[i] = p->nRef;
000946        }
000947        sqlite3WalkExpr(pWalker, pExpr->pLeft);
000948        if( 0==sqlite3ExprCanBeNull(pExpr->pLeft) && !IN_RENAME_OBJECT ){
000949          testcase( ExprHasProperty(pExpr, EP_OuterON) );
000950          assert( !ExprHasProperty(pExpr, EP_IntValue) );
000951          pExpr->u.iValue = (pExpr->op==TK_NOTNULL);
000952          pExpr->flags |= EP_IntValue;
000953          pExpr->op = TK_INTEGER;
000954  
000955          for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
000956            p->nRef = anRef[i];
000957          }
000958          sqlite3ExprDelete(pParse->db, pExpr->pLeft);
000959          pExpr->pLeft = 0;
000960        }
000961        return WRC_Prune;
000962      }
000963  
000964      /* A column name:                    ID
000965      ** Or table name and column name:    ID.ID
000966      ** Or a database, table and column:  ID.ID.ID
000967      **
000968      ** The TK_ID and TK_OUT cases are combined so that there will only
000969      ** be one call to lookupName().  Then the compiler will in-line
000970      ** lookupName() for a size reduction and performance increase.
000971      */
000972      case TK_ID:
000973      case TK_DOT: {
000974        const char *zColumn;
000975        const char *zTable;
000976        const char *zDb;
000977        Expr *pRight;
000978  
000979        if( pExpr->op==TK_ID ){
000980          zDb = 0;
000981          zTable = 0;
000982          assert( !ExprHasProperty(pExpr, EP_IntValue) );
000983          zColumn = pExpr->u.zToken;
000984        }else{
000985          Expr *pLeft = pExpr->pLeft;
000986          testcase( pNC->ncFlags & NC_IdxExpr );
000987          testcase( pNC->ncFlags & NC_GenCol );
000988          sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
000989                                 NC_IdxExpr|NC_GenCol, 0, pExpr);
000990          pRight = pExpr->pRight;
000991          if( pRight->op==TK_ID ){
000992            zDb = 0;
000993          }else{
000994            assert( pRight->op==TK_DOT );
000995            assert( !ExprHasProperty(pRight, EP_IntValue) );
000996            zDb = pLeft->u.zToken;
000997            pLeft = pRight->pLeft;
000998            pRight = pRight->pRight;
000999          }
001000          assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
001001          zTable = pLeft->u.zToken;
001002          zColumn = pRight->u.zToken;
001003          assert( ExprUseYTab(pExpr) );
001004          if( IN_RENAME_OBJECT ){
001005            sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
001006            sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
001007          }
001008        }
001009        return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
001010      }
001011  
001012      /* Resolve function names
001013      */
001014      case TK_FUNCTION: {
001015        ExprList *pList = pExpr->x.pList;    /* The argument list */
001016        int n = pList ? pList->nExpr : 0;    /* Number of arguments */
001017        int no_such_func = 0;       /* True if no such function exists */
001018        int wrong_num_args = 0;     /* True if wrong number of arguments */
001019        int is_agg = 0;             /* True if is an aggregate function */
001020        const char *zId;            /* The function name. */
001021        FuncDef *pDef;              /* Information about the function */
001022        u8 enc = ENC(pParse->db);   /* The database encoding */
001023        int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
001024  #ifndef SQLITE_OMIT_WINDOWFUNC
001025        Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
001026  #endif
001027        assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
001028        zId = pExpr->u.zToken;
001029        pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
001030        if( pDef==0 ){
001031          pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
001032          if( pDef==0 ){
001033            no_such_func = 1;
001034          }else{
001035            wrong_num_args = 1;
001036          }
001037        }else{
001038          is_agg = pDef->xFinalize!=0;
001039          if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
001040            ExprSetProperty(pExpr, EP_Unlikely);
001041            if( n==2 ){
001042              pExpr->iTable = exprProbability(pList->a[1].pExpr);
001043              if( pExpr->iTable<0 ){
001044                sqlite3ErrorMsg(pParse,
001045                  "second argument to %#T() must be a "
001046                  "constant between 0.0 and 1.0", pExpr);
001047                pNC->nNcErr++;
001048              }
001049            }else{
001050              /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
001051              ** equivalent to likelihood(X, 0.0625).
001052              ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
001053              ** short-hand for likelihood(X,0.0625).
001054              ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
001055              ** for likelihood(X,0.9375).
001056              ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
001057              ** to likelihood(X,0.9375). */
001058              /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
001059              pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
001060            }            
001061          }
001062  #ifndef SQLITE_OMIT_AUTHORIZATION
001063          {
001064            int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
001065            if( auth!=SQLITE_OK ){
001066              if( auth==SQLITE_DENY ){
001067                sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
001068                                        pExpr);
001069                pNC->nNcErr++;
001070              }
001071              pExpr->op = TK_NULL;
001072              return WRC_Prune;
001073            }
001074          }
001075  #endif
001076          if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
001077            /* For the purposes of the EP_ConstFunc flag, date and time
001078            ** functions and other functions that change slowly are considered
001079            ** constant because they are constant for the duration of one query.
001080            ** This allows them to be factored out of inner loops. */
001081            ExprSetProperty(pExpr,EP_ConstFunc);
001082          }
001083          if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
001084            /* Clearly non-deterministic functions like random(), but also
001085            ** date/time functions that use 'now', and other functions like
001086            ** sqlite_version() that might change over time cannot be used
001087            ** in an index or generated column.  Curiously, they can be used
001088            ** in a CHECK constraint.  SQLServer, MySQL, and PostgreSQL all
001089            ** all this. */
001090            sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
001091                                   NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
001092          }else{
001093            assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
001094            pExpr->op2 = pNC->ncFlags & NC_SelfRef;
001095            if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
001096          }
001097          if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
001098           && pParse->nested==0
001099           && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
001100          ){
001101            /* Internal-use-only functions are disallowed unless the
001102            ** SQL is being compiled using sqlite3NestedParse() or
001103            ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
001104            ** used to activate internal functions for testing purposes */
001105            no_such_func = 1;
001106            pDef = 0;
001107          }else
001108          if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
001109           && !IN_RENAME_OBJECT
001110          ){
001111            sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
001112          }
001113        }
001114  
001115        if( 0==IN_RENAME_OBJECT ){
001116  #ifndef SQLITE_OMIT_WINDOWFUNC
001117          assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
001118            || (pDef->xValue==0 && pDef->xInverse==0)
001119            || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
001120          );
001121          if( pDef && pDef->xValue==0 && pWin ){
001122            sqlite3ErrorMsg(pParse,
001123                "%#T() may not be used as a window function", pExpr
001124            );
001125            pNC->nNcErr++;
001126          }else if(
001127                (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
001128             || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
001129             || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
001130          ){
001131            const char *zType;
001132            if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
001133              zType = "window";
001134            }else{
001135              zType = "aggregate";
001136            }
001137            sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
001138            pNC->nNcErr++;
001139            is_agg = 0;
001140          }
001141  #else
001142          if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
001143            sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
001144            pNC->nNcErr++;
001145            is_agg = 0;
001146          }
001147  #endif
001148          else if( no_such_func && pParse->db->init.busy==0
001149  #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
001150                    && pParse->explain==0
001151  #endif
001152          ){
001153            sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
001154            pNC->nNcErr++;
001155          }else if( wrong_num_args ){
001156            sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
001157                 pExpr);
001158            pNC->nNcErr++;
001159          }
001160  #ifndef SQLITE_OMIT_WINDOWFUNC
001161          else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
001162            sqlite3ErrorMsg(pParse,
001163                "FILTER may not be used with non-aggregate %#T()",
001164                pExpr
001165            );
001166            pNC->nNcErr++;
001167          }
001168  #endif
001169          if( is_agg ){
001170            /* Window functions may not be arguments of aggregate functions.
001171            ** Or arguments of other window functions. But aggregate functions
001172            ** may be arguments for window functions.  */
001173  #ifndef SQLITE_OMIT_WINDOWFUNC
001174            pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
001175  #else
001176            pNC->ncFlags &= ~NC_AllowAgg;
001177  #endif
001178          }
001179        }
001180  #ifndef SQLITE_OMIT_WINDOWFUNC
001181        else if( ExprHasProperty(pExpr, EP_WinFunc) ){
001182          is_agg = 1;
001183        }
001184  #endif
001185        sqlite3WalkExprList(pWalker, pList);
001186        if( is_agg ){
001187  #ifndef SQLITE_OMIT_WINDOWFUNC
001188          if( pWin ){
001189            Select *pSel = pNC->pWinSelect;
001190            assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
001191            if( IN_RENAME_OBJECT==0 ){
001192              sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
001193              if( pParse->db->mallocFailed ) break;
001194            }
001195            sqlite3WalkExprList(pWalker, pWin->pPartition);
001196            sqlite3WalkExprList(pWalker, pWin->pOrderBy);
001197            sqlite3WalkExpr(pWalker, pWin->pFilter);
001198            sqlite3WindowLink(pSel, pWin);
001199            pNC->ncFlags |= NC_HasWin;
001200          }else
001201  #endif /* SQLITE_OMIT_WINDOWFUNC */
001202          {
001203            NameContext *pNC2;          /* For looping up thru outer contexts */
001204            pExpr->op = TK_AGG_FUNCTION;
001205            pExpr->op2 = 0;
001206  #ifndef SQLITE_OMIT_WINDOWFUNC
001207            if( ExprHasProperty(pExpr, EP_WinFunc) ){
001208              sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
001209            }
001210  #endif
001211            pNC2 = pNC;
001212            while( pNC2
001213                && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
001214            ){
001215              pExpr->op2++;
001216              pNC2 = pNC2->pNext;
001217            }
001218            assert( pDef!=0 || IN_RENAME_OBJECT );
001219            if( pNC2 && pDef ){
001220              assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
001221              assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
001222              testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
001223              testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
001224              pNC2->ncFlags |= NC_HasAgg
001225                | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
001226                    & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
001227            }
001228          }
001229          pNC->ncFlags |= savedAllowFlags;
001230        }
001231        /* FIX ME:  Compute pExpr->affinity based on the expected return
001232        ** type of the function
001233        */
001234        return WRC_Prune;
001235      }
001236  #ifndef SQLITE_OMIT_SUBQUERY
001237      case TK_SELECT:
001238      case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
001239  #endif
001240      case TK_IN: {
001241        testcase( pExpr->op==TK_IN );
001242        if( ExprUseXSelect(pExpr) ){
001243          int nRef = pNC->nRef;
001244          testcase( pNC->ncFlags & NC_IsCheck );
001245          testcase( pNC->ncFlags & NC_PartIdx );
001246          testcase( pNC->ncFlags & NC_IdxExpr );
001247          testcase( pNC->ncFlags & NC_GenCol );
001248          if( pNC->ncFlags & NC_SelfRef ){
001249            notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
001250          }else{
001251            sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
001252          }
001253          assert( pNC->nRef>=nRef );
001254          if( nRef!=pNC->nRef ){
001255            ExprSetProperty(pExpr, EP_VarSelect);
001256          }
001257          pNC->ncFlags |= NC_Subquery;
001258        }
001259        break;
001260      }
001261      case TK_VARIABLE: {
001262        testcase( pNC->ncFlags & NC_IsCheck );
001263        testcase( pNC->ncFlags & NC_PartIdx );
001264        testcase( pNC->ncFlags & NC_IdxExpr );
001265        testcase( pNC->ncFlags & NC_GenCol );
001266        sqlite3ResolveNotValid(pParse, pNC, "parameters",
001267                 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
001268        break;
001269      }
001270      case TK_IS:
001271      case TK_ISNOT: {
001272        Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
001273        assert( !ExprHasProperty(pExpr, EP_Reduced) );
001274        /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
001275        ** and "x IS NOT FALSE". */
001276        if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
001277          int rc = resolveExprStep(pWalker, pRight);
001278          if( rc==WRC_Abort ) return WRC_Abort;
001279          if( pRight->op==TK_TRUEFALSE ){
001280            pExpr->op2 = pExpr->op;
001281            pExpr->op = TK_TRUTH;
001282            return WRC_Continue;
001283          }
001284        }
001285        /* no break */ deliberate_fall_through
001286      }
001287      case TK_BETWEEN:
001288      case TK_EQ:
001289      case TK_NE:
001290      case TK_LT:
001291      case TK_LE:
001292      case TK_GT:
001293      case TK_GE: {
001294        int nLeft, nRight;
001295        if( pParse->db->mallocFailed ) break;
001296        assert( pExpr->pLeft!=0 );
001297        nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
001298        if( pExpr->op==TK_BETWEEN ){
001299          assert( ExprUseXList(pExpr) );
001300          nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
001301          if( nRight==nLeft ){
001302            nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
001303          }
001304        }else{
001305          assert( pExpr->pRight!=0 );
001306          nRight = sqlite3ExprVectorSize(pExpr->pRight);
001307        }
001308        if( nLeft!=nRight ){
001309          testcase( pExpr->op==TK_EQ );
001310          testcase( pExpr->op==TK_NE );
001311          testcase( pExpr->op==TK_LT );
001312          testcase( pExpr->op==TK_LE );
001313          testcase( pExpr->op==TK_GT );
001314          testcase( pExpr->op==TK_GE );
001315          testcase( pExpr->op==TK_IS );
001316          testcase( pExpr->op==TK_ISNOT );
001317          testcase( pExpr->op==TK_BETWEEN );
001318          sqlite3ErrorMsg(pParse, "row value misused");
001319          sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
001320        }
001321        break;
001322      }
001323    }
001324    assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
001325    return pParse->nErr ? WRC_Abort : WRC_Continue;
001326  }
001327  
001328  /*
001329  ** pEList is a list of expressions which are really the result set of the
001330  ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
001331  ** This routine checks to see if pE is a simple identifier which corresponds
001332  ** to the AS-name of one of the terms of the expression list.  If it is,
001333  ** this routine return an integer between 1 and N where N is the number of
001334  ** elements in pEList, corresponding to the matching entry.  If there is
001335  ** no match, or if pE is not a simple identifier, then this routine
001336  ** return 0.
001337  **
001338  ** pEList has been resolved.  pE has not.
001339  */
001340  static int resolveAsName(
001341    Parse *pParse,     /* Parsing context for error messages */
001342    ExprList *pEList,  /* List of expressions to scan */
001343    Expr *pE           /* Expression we are trying to match */
001344  ){
001345    int i;             /* Loop counter */
001346  
001347    UNUSED_PARAMETER(pParse);
001348  
001349    if( pE->op==TK_ID ){
001350      const char *zCol;
001351      assert( !ExprHasProperty(pE, EP_IntValue) );
001352      zCol = pE->u.zToken;
001353      for(i=0; i<pEList->nExpr; i++){
001354        if( pEList->a[i].fg.eEName==ENAME_NAME
001355         && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
001356        ){
001357          return i+1;
001358        }
001359      }
001360    }
001361    return 0;
001362  }
001363  
001364  /*
001365  ** pE is a pointer to an expression which is a single term in the
001366  ** ORDER BY of a compound SELECT.  The expression has not been
001367  ** name resolved.
001368  **
001369  ** At the point this routine is called, we already know that the
001370  ** ORDER BY term is not an integer index into the result set.  That
001371  ** case is handled by the calling routine.
001372  **
001373  ** Attempt to match pE against result set columns in the left-most
001374  ** SELECT statement.  Return the index i of the matching column,
001375  ** as an indication to the caller that it should sort by the i-th column.
001376  ** The left-most column is 1.  In other words, the value returned is the
001377  ** same integer value that would be used in the SQL statement to indicate
001378  ** the column.
001379  **
001380  ** If there is no match, return 0.  Return -1 if an error occurs.
001381  */
001382  static int resolveOrderByTermToExprList(
001383    Parse *pParse,     /* Parsing context for error messages */
001384    Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
001385    Expr *pE           /* The specific ORDER BY term */
001386  ){
001387    int i;             /* Loop counter */
001388    ExprList *pEList;  /* The columns of the result set */
001389    NameContext nc;    /* Name context for resolving pE */
001390    sqlite3 *db;       /* Database connection */
001391    int rc;            /* Return code from subprocedures */
001392    u8 savedSuppErr;   /* Saved value of db->suppressErr */
001393  
001394    assert( sqlite3ExprIsInteger(pE, &i)==0 );
001395    pEList = pSelect->pEList;
001396  
001397    /* Resolve all names in the ORDER BY term expression
001398    */
001399    memset(&nc, 0, sizeof(nc));
001400    nc.pParse = pParse;
001401    nc.pSrcList = pSelect->pSrc;
001402    nc.uNC.pEList = pEList;
001403    nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
001404    nc.nNcErr = 0;
001405    db = pParse->db;
001406    savedSuppErr = db->suppressErr;
001407    db->suppressErr = 1;
001408    rc = sqlite3ResolveExprNames(&nc, pE);
001409    db->suppressErr = savedSuppErr;
001410    if( rc ) return 0;
001411  
001412    /* Try to match the ORDER BY expression against an expression
001413    ** in the result set.  Return an 1-based index of the matching
001414    ** result-set entry.
001415    */
001416    for(i=0; i<pEList->nExpr; i++){
001417      if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
001418        return i+1;
001419      }
001420    }
001421  
001422    /* If no match, return 0. */
001423    return 0;
001424  }
001425  
001426  /*
001427  ** Generate an ORDER BY or GROUP BY term out-of-range error.
001428  */
001429  static void resolveOutOfRangeError(
001430    Parse *pParse,         /* The error context into which to write the error */
001431    const char *zType,     /* "ORDER" or "GROUP" */
001432    int i,                 /* The index (1-based) of the term out of range */
001433    int mx,                /* Largest permissible value of i */
001434    Expr *pError           /* Associate the error with the expression */
001435  ){
001436    sqlite3ErrorMsg(pParse,
001437      "%r %s BY term out of range - should be "
001438      "between 1 and %d", i, zType, mx);
001439    sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
001440  }
001441  
001442  /*
001443  ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
001444  ** each term of the ORDER BY clause is a constant integer between 1
001445  ** and N where N is the number of columns in the compound SELECT.
001446  **
001447  ** ORDER BY terms that are already an integer between 1 and N are
001448  ** unmodified.  ORDER BY terms that are integers outside the range of
001449  ** 1 through N generate an error.  ORDER BY terms that are expressions
001450  ** are matched against result set expressions of compound SELECT
001451  ** beginning with the left-most SELECT and working toward the right.
001452  ** At the first match, the ORDER BY expression is transformed into
001453  ** the integer column number.
001454  **
001455  ** Return the number of errors seen.
001456  */
001457  static int resolveCompoundOrderBy(
001458    Parse *pParse,        /* Parsing context.  Leave error messages here */
001459    Select *pSelect       /* The SELECT statement containing the ORDER BY */
001460  ){
001461    int i;
001462    ExprList *pOrderBy;
001463    ExprList *pEList;
001464    sqlite3 *db;
001465    int moreToDo = 1;
001466  
001467    pOrderBy = pSelect->pOrderBy;
001468    if( pOrderBy==0 ) return 0;
001469    db = pParse->db;
001470    if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
001471      sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
001472      return 1;
001473    }
001474    for(i=0; i<pOrderBy->nExpr; i++){
001475      pOrderBy->a[i].fg.done = 0;
001476    }
001477    pSelect->pNext = 0;
001478    while( pSelect->pPrior ){
001479      pSelect->pPrior->pNext = pSelect;
001480      pSelect = pSelect->pPrior;
001481    }
001482    while( pSelect && moreToDo ){
001483      struct ExprList_item *pItem;
001484      moreToDo = 0;
001485      pEList = pSelect->pEList;
001486      assert( pEList!=0 );
001487      for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
001488        int iCol = -1;
001489        Expr *pE, *pDup;
001490        if( pItem->fg.done ) continue;
001491        pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
001492        if( NEVER(pE==0) ) continue;
001493        if( sqlite3ExprIsInteger(pE, &iCol) ){
001494          if( iCol<=0 || iCol>pEList->nExpr ){
001495            resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
001496            return 1;
001497          }
001498        }else{
001499          iCol = resolveAsName(pParse, pEList, pE);
001500          if( iCol==0 ){
001501            /* Now test if expression pE matches one of the values returned
001502            ** by pSelect. In the usual case this is done by duplicating the
001503            ** expression, resolving any symbols in it, and then comparing
001504            ** it against each expression returned by the SELECT statement.
001505            ** Once the comparisons are finished, the duplicate expression
001506            ** is deleted.
001507            **
001508            ** If this is running as part of an ALTER TABLE operation and
001509            ** the symbols resolve successfully, also resolve the symbols in the
001510            ** actual expression. This allows the code in alter.c to modify
001511            ** column references within the ORDER BY expression as required.  */
001512            pDup = sqlite3ExprDup(db, pE, 0);
001513            if( !db->mallocFailed ){
001514              assert(pDup);
001515              iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
001516              if( IN_RENAME_OBJECT && iCol>0 ){
001517                resolveOrderByTermToExprList(pParse, pSelect, pE);
001518              }
001519            }
001520            sqlite3ExprDelete(db, pDup);
001521          }
001522        }
001523        if( iCol>0 ){
001524          /* Convert the ORDER BY term into an integer column number iCol,
001525          ** taking care to preserve the COLLATE clause if it exists. */
001526          if( !IN_RENAME_OBJECT ){
001527            Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
001528            if( pNew==0 ) return 1;
001529            pNew->flags |= EP_IntValue;
001530            pNew->u.iValue = iCol;
001531            if( pItem->pExpr==pE ){
001532              pItem->pExpr = pNew;
001533            }else{
001534              Expr *pParent = pItem->pExpr;
001535              assert( pParent->op==TK_COLLATE );
001536              while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
001537              assert( pParent->pLeft==pE );
001538              pParent->pLeft = pNew;
001539            }
001540            sqlite3ExprDelete(db, pE);
001541            pItem->u.x.iOrderByCol = (u16)iCol;
001542          }
001543          pItem->fg.done = 1;
001544        }else{
001545          moreToDo = 1;
001546        }
001547      }
001548      pSelect = pSelect->pNext;
001549    }
001550    for(i=0; i<pOrderBy->nExpr; i++){
001551      if( pOrderBy->a[i].fg.done==0 ){
001552        sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
001553              "column in the result set", i+1);
001554        return 1;
001555      }
001556    }
001557    return 0;
001558  }
001559  
001560  /*
001561  ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
001562  ** the SELECT statement pSelect.  If any term is reference to a
001563  ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
001564  ** field) then convert that term into a copy of the corresponding result set
001565  ** column.
001566  **
001567  ** If any errors are detected, add an error message to pParse and
001568  ** return non-zero.  Return zero if no errors are seen.
001569  */
001570  int sqlite3ResolveOrderGroupBy(
001571    Parse *pParse,        /* Parsing context.  Leave error messages here */
001572    Select *pSelect,      /* The SELECT statement containing the clause */
001573    ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
001574    const char *zType     /* "ORDER" or "GROUP" */
001575  ){
001576    int i;
001577    sqlite3 *db = pParse->db;
001578    ExprList *pEList;
001579    struct ExprList_item *pItem;
001580  
001581    if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
001582    if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
001583      sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
001584      return 1;
001585    }
001586    pEList = pSelect->pEList;
001587    assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
001588    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
001589      if( pItem->u.x.iOrderByCol ){
001590        if( pItem->u.x.iOrderByCol>pEList->nExpr ){
001591          resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
001592          return 1;
001593        }
001594        resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
001595      }
001596    }
001597    return 0;
001598  }
001599  
001600  #ifndef SQLITE_OMIT_WINDOWFUNC
001601  /*
001602  ** Walker callback for windowRemoveExprFromSelect().
001603  */
001604  static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
001605    UNUSED_PARAMETER(pWalker);
001606    if( ExprHasProperty(pExpr, EP_WinFunc) ){
001607      Window *pWin = pExpr->y.pWin;
001608      sqlite3WindowUnlinkFromSelect(pWin);
001609    }
001610    return WRC_Continue;
001611  }
001612  
001613  /*
001614  ** Remove any Window objects owned by the expression pExpr from the
001615  ** Select.pWin list of Select object pSelect.
001616  */
001617  static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
001618    if( pSelect->pWin ){
001619      Walker sWalker;
001620      memset(&sWalker, 0, sizeof(Walker));
001621      sWalker.xExprCallback = resolveRemoveWindowsCb;
001622      sWalker.u.pSelect = pSelect;
001623      sqlite3WalkExpr(&sWalker, pExpr);
001624    }
001625  }
001626  #else
001627  # define windowRemoveExprFromSelect(a, b)
001628  #endif /* SQLITE_OMIT_WINDOWFUNC */
001629  
001630  /*
001631  ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
001632  ** The Name context of the SELECT statement is pNC.  zType is either
001633  ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
001634  **
001635  ** This routine resolves each term of the clause into an expression.
001636  ** If the order-by term is an integer I between 1 and N (where N is the
001637  ** number of columns in the result set of the SELECT) then the expression
001638  ** in the resolution is a copy of the I-th result-set expression.  If
001639  ** the order-by term is an identifier that corresponds to the AS-name of
001640  ** a result-set expression, then the term resolves to a copy of the
001641  ** result-set expression.  Otherwise, the expression is resolved in
001642  ** the usual way - using sqlite3ResolveExprNames().
001643  **
001644  ** This routine returns the number of errors.  If errors occur, then
001645  ** an appropriate error message might be left in pParse.  (OOM errors
001646  ** excepted.)
001647  */
001648  static int resolveOrderGroupBy(
001649    NameContext *pNC,     /* The name context of the SELECT statement */
001650    Select *pSelect,      /* The SELECT statement holding pOrderBy */
001651    ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
001652    const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
001653  ){
001654    int i, j;                      /* Loop counters */
001655    int iCol;                      /* Column number */
001656    struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
001657    Parse *pParse;                 /* Parsing context */
001658    int nResult;                   /* Number of terms in the result set */
001659  
001660    assert( pOrderBy!=0 );
001661    nResult = pSelect->pEList->nExpr;
001662    pParse = pNC->pParse;
001663    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
001664      Expr *pE = pItem->pExpr;
001665      Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
001666      if( NEVER(pE2==0) ) continue;
001667      if( zType[0]!='G' ){
001668        iCol = resolveAsName(pParse, pSelect->pEList, pE2);
001669        if( iCol>0 ){
001670          /* If an AS-name match is found, mark this ORDER BY column as being
001671          ** a copy of the iCol-th result-set column.  The subsequent call to
001672          ** sqlite3ResolveOrderGroupBy() will convert the expression to a
001673          ** copy of the iCol-th result-set expression. */
001674          pItem->u.x.iOrderByCol = (u16)iCol;
001675          continue;
001676        }
001677      }
001678      if( sqlite3ExprIsInteger(pE2, &iCol) ){
001679        /* The ORDER BY term is an integer constant.  Again, set the column
001680        ** number so that sqlite3ResolveOrderGroupBy() will convert the
001681        ** order-by term to a copy of the result-set expression */
001682        if( iCol<1 || iCol>0xffff ){
001683          resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
001684          return 1;
001685        }
001686        pItem->u.x.iOrderByCol = (u16)iCol;
001687        continue;
001688      }
001689  
001690      /* Otherwise, treat the ORDER BY term as an ordinary expression */
001691      pItem->u.x.iOrderByCol = 0;
001692      if( sqlite3ResolveExprNames(pNC, pE) ){
001693        return 1;
001694      }
001695      for(j=0; j<pSelect->pEList->nExpr; j++){
001696        if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
001697          /* Since this expression is being changed into a reference
001698          ** to an identical expression in the result set, remove all Window
001699          ** objects belonging to the expression from the Select.pWin list. */
001700          windowRemoveExprFromSelect(pSelect, pE);
001701          pItem->u.x.iOrderByCol = j+1;
001702        }
001703      }
001704    }
001705    return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
001706  }
001707  
001708  /*
001709  ** Resolve names in the SELECT statement p and all of its descendants.
001710  */
001711  static int resolveSelectStep(Walker *pWalker, Select *p){
001712    NameContext *pOuterNC;  /* Context that contains this SELECT */
001713    NameContext sNC;        /* Name context of this SELECT */
001714    int isCompound;         /* True if p is a compound select */
001715    int nCompound;          /* Number of compound terms processed so far */
001716    Parse *pParse;          /* Parsing context */
001717    int i;                  /* Loop counter */
001718    ExprList *pGroupBy;     /* The GROUP BY clause */
001719    Select *pLeftmost;      /* Left-most of SELECT of a compound */
001720    sqlite3 *db;            /* Database connection */
001721   
001722  
001723    assert( p!=0 );
001724    if( p->selFlags & SF_Resolved ){
001725      return WRC_Prune;
001726    }
001727    pOuterNC = pWalker->u.pNC;
001728    pParse = pWalker->pParse;
001729    db = pParse->db;
001730  
001731    /* Normally sqlite3SelectExpand() will be called first and will have
001732    ** already expanded this SELECT.  However, if this is a subquery within
001733    ** an expression, sqlite3ResolveExprNames() will be called without a
001734    ** prior call to sqlite3SelectExpand().  When that happens, let
001735    ** sqlite3SelectPrep() do all of the processing for this SELECT.
001736    ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
001737    ** this routine in the correct order.
001738    */
001739    if( (p->selFlags & SF_Expanded)==0 ){
001740      sqlite3SelectPrep(pParse, p, pOuterNC);
001741      return pParse->nErr ? WRC_Abort : WRC_Prune;
001742    }
001743  
001744    isCompound = p->pPrior!=0;
001745    nCompound = 0;
001746    pLeftmost = p;
001747    while( p ){
001748      assert( (p->selFlags & SF_Expanded)!=0 );
001749      assert( (p->selFlags & SF_Resolved)==0 );
001750      assert( db->suppressErr==0 ); /* SF_Resolved not set if errors suppressed */
001751      p->selFlags |= SF_Resolved;
001752  
001753  
001754      /* Resolve the expressions in the LIMIT and OFFSET clauses. These
001755      ** are not allowed to refer to any names, so pass an empty NameContext.
001756      */
001757      memset(&sNC, 0, sizeof(sNC));
001758      sNC.pParse = pParse;
001759      sNC.pWinSelect = p;
001760      if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
001761        return WRC_Abort;
001762      }
001763  
001764      /* If the SF_Converted flags is set, then this Select object was
001765      ** was created by the convertCompoundSelectToSubquery() function.
001766      ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
001767      ** as if it were part of the sub-query, not the parent. This block
001768      ** moves the pOrderBy down to the sub-query. It will be moved back
001769      ** after the names have been resolved.  */
001770      if( p->selFlags & SF_Converted ){
001771        Select *pSub = p->pSrc->a[0].pSelect;
001772        assert( p->pSrc->nSrc==1 && p->pOrderBy );
001773        assert( pSub->pPrior && pSub->pOrderBy==0 );
001774        pSub->pOrderBy = p->pOrderBy;
001775        p->pOrderBy = 0;
001776      }
001777   
001778      /* Recursively resolve names in all subqueries in the FROM clause
001779      */
001780      for(i=0; i<p->pSrc->nSrc; i++){
001781        SrcItem *pItem = &p->pSrc->a[i];
001782        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
001783          int nRef = pOuterNC ? pOuterNC->nRef : 0;
001784          const char *zSavedContext = pParse->zAuthContext;
001785  
001786          if( pItem->zName ) pParse->zAuthContext = pItem->zName;
001787          sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
001788          pParse->zAuthContext = zSavedContext;
001789          if( pParse->nErr ) return WRC_Abort;
001790          assert( db->mallocFailed==0 );
001791  
001792          /* If the number of references to the outer context changed when
001793          ** expressions in the sub-select were resolved, the sub-select
001794          ** is correlated. It is not required to check the refcount on any
001795          ** but the innermost outer context object, as lookupName() increments
001796          ** the refcount on all contexts between the current one and the
001797          ** context containing the column when it resolves a name. */
001798          if( pOuterNC ){
001799            assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
001800            pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
001801          }
001802        }
001803      }
001804   
001805      /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
001806      ** resolve the result-set expression list.
001807      */
001808      sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
001809      sNC.pSrcList = p->pSrc;
001810      sNC.pNext = pOuterNC;
001811   
001812      /* Resolve names in the result set. */
001813      if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
001814      sNC.ncFlags &= ~NC_AllowWin;
001815   
001816      /* If there are no aggregate functions in the result-set, and no GROUP BY
001817      ** expression, do not allow aggregates in any of the other expressions.
001818      */
001819      assert( (p->selFlags & SF_Aggregate)==0 );
001820      pGroupBy = p->pGroupBy;
001821      if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
001822        assert( NC_MinMaxAgg==SF_MinMaxAgg );
001823        assert( NC_OrderAgg==SF_OrderByReqd );
001824        p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
001825      }else{
001826        sNC.ncFlags &= ~NC_AllowAgg;
001827      }
001828   
001829      /* Add the output column list to the name-context before parsing the
001830      ** other expressions in the SELECT statement. This is so that
001831      ** expressions in the WHERE clause (etc.) can refer to expressions by
001832      ** aliases in the result set.
001833      **
001834      ** Minor point: If this is the case, then the expression will be
001835      ** re-evaluated for each reference to it.
001836      */
001837      assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
001838      sNC.uNC.pEList = p->pEList;
001839      sNC.ncFlags |= NC_UEList;
001840      if( p->pHaving ){
001841        if( (p->selFlags & SF_Aggregate)==0 ){
001842          sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
001843          return WRC_Abort;
001844        }
001845        if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
001846      }
001847      if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
001848  
001849      /* Resolve names in table-valued-function arguments */
001850      for(i=0; i<p->pSrc->nSrc; i++){
001851        SrcItem *pItem = &p->pSrc->a[i];
001852        if( pItem->fg.isTabFunc
001853         && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
001854        ){
001855          return WRC_Abort;
001856        }
001857      }
001858  
001859  #ifndef SQLITE_OMIT_WINDOWFUNC
001860      if( IN_RENAME_OBJECT ){
001861        Window *pWin;
001862        for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
001863          if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
001864           || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
001865          ){
001866            return WRC_Abort;
001867          }
001868        }
001869      }
001870  #endif
001871  
001872      /* The ORDER BY and GROUP BY clauses may not refer to terms in
001873      ** outer queries
001874      */
001875      sNC.pNext = 0;
001876      sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
001877  
001878      /* If this is a converted compound query, move the ORDER BY clause from
001879      ** the sub-query back to the parent query. At this point each term
001880      ** within the ORDER BY clause has been transformed to an integer value.
001881      ** These integers will be replaced by copies of the corresponding result
001882      ** set expressions by the call to resolveOrderGroupBy() below.  */
001883      if( p->selFlags & SF_Converted ){
001884        Select *pSub = p->pSrc->a[0].pSelect;
001885        p->pOrderBy = pSub->pOrderBy;
001886        pSub->pOrderBy = 0;
001887      }
001888  
001889      /* Process the ORDER BY clause for singleton SELECT statements.
001890      ** The ORDER BY clause for compounds SELECT statements is handled
001891      ** below, after all of the result-sets for all of the elements of
001892      ** the compound have been resolved.
001893      **
001894      ** If there is an ORDER BY clause on a term of a compound-select other
001895      ** than the right-most term, then that is a syntax error.  But the error
001896      ** is not detected until much later, and so we need to go ahead and
001897      ** resolve those symbols on the incorrect ORDER BY for consistency.
001898      */
001899      if( p->pOrderBy!=0
001900       && isCompound<=nCompound  /* Defer right-most ORDER BY of a compound */
001901       && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
001902      ){
001903        return WRC_Abort;
001904      }
001905      if( db->mallocFailed ){
001906        return WRC_Abort;
001907      }
001908      sNC.ncFlags &= ~NC_AllowWin;
001909   
001910      /* Resolve the GROUP BY clause.  At the same time, make sure
001911      ** the GROUP BY clause does not contain aggregate functions.
001912      */
001913      if( pGroupBy ){
001914        struct ExprList_item *pItem;
001915     
001916        if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
001917          return WRC_Abort;
001918        }
001919        for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
001920          if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
001921            sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
001922                "the GROUP BY clause");
001923            return WRC_Abort;
001924          }
001925        }
001926      }
001927  
001928      /* If this is part of a compound SELECT, check that it has the right
001929      ** number of expressions in the select list. */
001930      if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
001931        sqlite3SelectWrongNumTermsError(pParse, p->pNext);
001932        return WRC_Abort;
001933      }
001934  
001935      /* Advance to the next term of the compound
001936      */
001937      p = p->pPrior;
001938      nCompound++;
001939    }
001940  
001941    /* Resolve the ORDER BY on a compound SELECT after all terms of
001942    ** the compound have been resolved.
001943    */
001944    if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
001945      return WRC_Abort;
001946    }
001947  
001948    return WRC_Prune;
001949  }
001950  
001951  /*
001952  ** This routine walks an expression tree and resolves references to
001953  ** table columns and result-set columns.  At the same time, do error
001954  ** checking on function usage and set a flag if any aggregate functions
001955  ** are seen.
001956  **
001957  ** To resolve table columns references we look for nodes (or subtrees) of the
001958  ** form X.Y.Z or Y.Z or just Z where
001959  **
001960  **      X:   The name of a database.  Ex:  "main" or "temp" or
001961  **           the symbolic name assigned to an ATTACH-ed database.
001962  **
001963  **      Y:   The name of a table in a FROM clause.  Or in a trigger
001964  **           one of the special names "old" or "new".
001965  **
001966  **      Z:   The name of a column in table Y.
001967  **
001968  ** The node at the root of the subtree is modified as follows:
001969  **
001970  **    Expr.op        Changed to TK_COLUMN
001971  **    Expr.pTab      Points to the Table object for X.Y
001972  **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
001973  **    Expr.iTable    The VDBE cursor number for X.Y
001974  **
001975  **
001976  ** To resolve result-set references, look for expression nodes of the
001977  ** form Z (with no X and Y prefix) where the Z matches the right-hand
001978  ** size of an AS clause in the result-set of a SELECT.  The Z expression
001979  ** is replaced by a copy of the left-hand side of the result-set expression.
001980  ** Table-name and function resolution occurs on the substituted expression
001981  ** tree.  For example, in:
001982  **
001983  **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
001984  **
001985  ** The "x" term of the order by is replaced by "a+b" to render:
001986  **
001987  **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
001988  **
001989  ** Function calls are checked to make sure that the function is
001990  ** defined and that the correct number of arguments are specified.
001991  ** If the function is an aggregate function, then the NC_HasAgg flag is
001992  ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
001993  ** If an expression contains aggregate functions then the EP_Agg
001994  ** property on the expression is set.
001995  **
001996  ** An error message is left in pParse if anything is amiss.  The number
001997  ** if errors is returned.
001998  */
001999  int sqlite3ResolveExprNames(
002000    NameContext *pNC,       /* Namespace to resolve expressions in. */
002001    Expr *pExpr             /* The expression to be analyzed. */
002002  ){
002003    int savedHasAgg;
002004    Walker w;
002005  
002006    if( pExpr==0 ) return SQLITE_OK;
002007    savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
002008    pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
002009    w.pParse = pNC->pParse;
002010    w.xExprCallback = resolveExprStep;
002011    w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
002012    w.xSelectCallback2 = 0;
002013    w.u.pNC = pNC;
002014  #if SQLITE_MAX_EXPR_DEPTH>0
002015    w.pParse->nHeight += pExpr->nHeight;
002016    if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
002017      return SQLITE_ERROR;
002018    }
002019  #endif
002020    assert( pExpr!=0 );
002021    sqlite3WalkExprNN(&w, pExpr);
002022  #if SQLITE_MAX_EXPR_DEPTH>0
002023    w.pParse->nHeight -= pExpr->nHeight;
002024  #endif
002025    assert( EP_Agg==NC_HasAgg );
002026    assert( EP_Win==NC_HasWin );
002027    testcase( pNC->ncFlags & NC_HasAgg );
002028    testcase( pNC->ncFlags & NC_HasWin );
002029    ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
002030    pNC->ncFlags |= savedHasAgg;
002031    return pNC->nNcErr>0 || w.pParse->nErr>0;
002032  }
002033  
002034  /*
002035  ** Resolve all names for all expression in an expression list.  This is
002036  ** just like sqlite3ResolveExprNames() except that it works for an expression
002037  ** list rather than a single expression.
002038  */
002039  int sqlite3ResolveExprListNames(
002040    NameContext *pNC,       /* Namespace to resolve expressions in. */
002041    ExprList *pList         /* The expression list to be analyzed. */
002042  ){
002043    int i;
002044    int savedHasAgg = 0;
002045    Walker w;
002046    if( pList==0 ) return WRC_Continue;
002047    w.pParse = pNC->pParse;
002048    w.xExprCallback = resolveExprStep;
002049    w.xSelectCallback = resolveSelectStep;
002050    w.xSelectCallback2 = 0;
002051    w.u.pNC = pNC;
002052    savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
002053    pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
002054    for(i=0; i<pList->nExpr; i++){
002055      Expr *pExpr = pList->a[i].pExpr;
002056      if( pExpr==0 ) continue;
002057  #if SQLITE_MAX_EXPR_DEPTH>0
002058      w.pParse->nHeight += pExpr->nHeight;
002059      if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
002060        return WRC_Abort;
002061      }
002062  #endif
002063      sqlite3WalkExprNN(&w, pExpr);
002064  #if SQLITE_MAX_EXPR_DEPTH>0
002065      w.pParse->nHeight -= pExpr->nHeight;
002066  #endif
002067      assert( EP_Agg==NC_HasAgg );
002068      assert( EP_Win==NC_HasWin );
002069      testcase( pNC->ncFlags & NC_HasAgg );
002070      testcase( pNC->ncFlags & NC_HasWin );
002071      if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
002072        ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
002073        savedHasAgg |= pNC->ncFlags &
002074                            (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
002075        pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
002076      }
002077      if( w.pParse->nErr>0 ) return WRC_Abort;
002078    }
002079    pNC->ncFlags |= savedHasAgg;
002080    return WRC_Continue;
002081  }
002082  
002083  /*
002084  ** Resolve all names in all expressions of a SELECT and in all
002085  ** descendants of the SELECT, including compounds off of p->pPrior,
002086  ** subqueries in expressions, and subqueries used as FROM clause
002087  ** terms.
002088  **
002089  ** See sqlite3ResolveExprNames() for a description of the kinds of
002090  ** transformations that occur.
002091  **
002092  ** All SELECT statements should have been expanded using
002093  ** sqlite3SelectExpand() prior to invoking this routine.
002094  */
002095  void sqlite3ResolveSelectNames(
002096    Parse *pParse,         /* The parser context */
002097    Select *p,             /* The SELECT statement being coded. */
002098    NameContext *pOuterNC  /* Name context for parent SELECT statement */
002099  ){
002100    Walker w;
002101  
002102    assert( p!=0 );
002103    w.xExprCallback = resolveExprStep;
002104    w.xSelectCallback = resolveSelectStep;
002105    w.xSelectCallback2 = 0;
002106    w.pParse = pParse;
002107    w.u.pNC = pOuterNC;
002108    sqlite3WalkSelect(&w, p);
002109  }
002110  
002111  /*
002112  ** Resolve names in expressions that can only reference a single table
002113  ** or which cannot reference any tables at all.  Examples:
002114  **
002115  **                                                    "type" flag
002116  **                                                    ------------
002117  **    (1)   CHECK constraints                         NC_IsCheck
002118  **    (2)   WHERE clauses on partial indices          NC_PartIdx
002119  **    (3)   Expressions in indexes on expressions     NC_IdxExpr
002120  **    (4)   Expression arguments to VACUUM INTO.      0
002121  **    (5)   GENERATED ALWAYS as expressions           NC_GenCol
002122  **
002123  ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
002124  ** nodes of the expression is set to -1 and the Expr.iColumn value is
002125  ** set to the column number.  In case (4), TK_COLUMN nodes cause an error.
002126  **
002127  ** Any errors cause an error message to be set in pParse.
002128  */
002129  int sqlite3ResolveSelfReference(
002130    Parse *pParse,   /* Parsing context */
002131    Table *pTab,     /* The table being referenced, or NULL */
002132    int type,        /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
002133    Expr *pExpr,     /* Expression to resolve.  May be NULL. */
002134    ExprList *pList  /* Expression list to resolve.  May be NULL. */
002135  ){
002136    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
002137    NameContext sNC;                /* Name context for pParse->pNewTable */
002138    int rc;
002139  
002140    assert( type==0 || pTab!=0 );
002141    assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
002142            || type==NC_GenCol || pTab==0 );
002143    memset(&sNC, 0, sizeof(sNC));
002144    memset(&sSrc, 0, sizeof(sSrc));
002145    if( pTab ){
002146      sSrc.nSrc = 1;
002147      sSrc.a[0].zName = pTab->zName;
002148      sSrc.a[0].pTab = pTab;
002149      sSrc.a[0].iCursor = -1;
002150      if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
002151        /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
002152        ** schema elements */
002153        type |= NC_FromDDL;
002154      }
002155    }
002156    sNC.pParse = pParse;
002157    sNC.pSrcList = &sSrc;
002158    sNC.ncFlags = type | NC_IsDDL;
002159    if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
002160    if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
002161    return rc;
002162  }