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