extensions/sqlite/sqlite-source/select.c
changeset 1952 b7aa2b626807
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/extensions/sqlite/sqlite-source/select.c	Sun Mar 30 07:00:22 2008 +0000
     1.3 @@ -0,0 +1,3539 @@
     1.4 +/*
     1.5 +** 2001 September 15
     1.6 +**
     1.7 +** The author disclaims copyright to this source code.  In place of
     1.8 +** a legal notice, here is a blessing:
     1.9 +**
    1.10 +**    May you do good and not evil.
    1.11 +**    May you find forgiveness for yourself and forgive others.
    1.12 +**    May you share freely, never taking more than you give.
    1.13 +**
    1.14 +*************************************************************************
    1.15 +** This file contains C code routines that are called by the parser
    1.16 +** to handle SELECT statements in SQLite.
    1.17 +**
    1.18 +** $Id$
    1.19 +*/
    1.20 +#include "sqliteInt.h"
    1.21 +
    1.22 +
    1.23 +/*
    1.24 +** Delete all the content of a Select structure but do not deallocate
    1.25 +** the select structure itself.
    1.26 +*/
    1.27 +static void clearSelect(Select *p){
    1.28 +  sqlite3ExprListDelete(p->pEList);
    1.29 +  sqlite3SrcListDelete(p->pSrc);
    1.30 +  sqlite3ExprDelete(p->pWhere);
    1.31 +  sqlite3ExprListDelete(p->pGroupBy);
    1.32 +  sqlite3ExprDelete(p->pHaving);
    1.33 +  sqlite3ExprListDelete(p->pOrderBy);
    1.34 +  sqlite3SelectDelete(p->pPrior);
    1.35 +  sqlite3ExprDelete(p->pLimit);
    1.36 +  sqlite3ExprDelete(p->pOffset);
    1.37 +}
    1.38 +
    1.39 +
    1.40 +/*
    1.41 +** Allocate a new Select structure and return a pointer to that
    1.42 +** structure.
    1.43 +*/
    1.44 +Select *sqlite3SelectNew(
    1.45 +  Parse *pParse,        /* Parsing context */
    1.46 +  ExprList *pEList,     /* which columns to include in the result */
    1.47 +  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
    1.48 +  Expr *pWhere,         /* the WHERE clause */
    1.49 +  ExprList *pGroupBy,   /* the GROUP BY clause */
    1.50 +  Expr *pHaving,        /* the HAVING clause */
    1.51 +  ExprList *pOrderBy,   /* the ORDER BY clause */
    1.52 +  int isDistinct,       /* true if the DISTINCT keyword is present */
    1.53 +  Expr *pLimit,         /* LIMIT value.  NULL means not used */
    1.54 +  Expr *pOffset         /* OFFSET value.  NULL means no offset */
    1.55 +){
    1.56 +  Select *pNew;
    1.57 +  Select standin;
    1.58 +  sqlite3 *db = pParse->db;
    1.59 +  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
    1.60 +  assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
    1.61 +  if( pNew==0 ){
    1.62 +    pNew = &standin;
    1.63 +    memset(pNew, 0, sizeof(*pNew));
    1.64 +  }
    1.65 +  if( pEList==0 ){
    1.66 +    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
    1.67 +  }
    1.68 +  pNew->pEList = pEList;
    1.69 +  pNew->pSrc = pSrc;
    1.70 +  pNew->pWhere = pWhere;
    1.71 +  pNew->pGroupBy = pGroupBy;
    1.72 +  pNew->pHaving = pHaving;
    1.73 +  pNew->pOrderBy = pOrderBy;
    1.74 +  pNew->isDistinct = isDistinct;
    1.75 +  pNew->op = TK_SELECT;
    1.76 +  assert( pOffset==0 || pLimit!=0 );
    1.77 +  pNew->pLimit = pLimit;
    1.78 +  pNew->pOffset = pOffset;
    1.79 +  pNew->iLimit = -1;
    1.80 +  pNew->iOffset = -1;
    1.81 +  pNew->addrOpenEphm[0] = -1;
    1.82 +  pNew->addrOpenEphm[1] = -1;
    1.83 +  pNew->addrOpenEphm[2] = -1;
    1.84 +  if( pNew==&standin) {
    1.85 +    clearSelect(pNew);
    1.86 +    pNew = 0;
    1.87 +  }
    1.88 +  return pNew;
    1.89 +}
    1.90 +
    1.91 +/*
    1.92 +** Delete the given Select structure and all of its substructures.
    1.93 +*/
    1.94 +void sqlite3SelectDelete(Select *p){
    1.95 +  if( p ){
    1.96 +    clearSelect(p);
    1.97 +    sqlite3_free(p);
    1.98 +  }
    1.99 +}
   1.100 +
   1.101 +/*
   1.102 +** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
   1.103 +** type of join.  Return an integer constant that expresses that type
   1.104 +** in terms of the following bit values:
   1.105 +**
   1.106 +**     JT_INNER
   1.107 +**     JT_CROSS
   1.108 +**     JT_OUTER
   1.109 +**     JT_NATURAL
   1.110 +**     JT_LEFT
   1.111 +**     JT_RIGHT
   1.112 +**
   1.113 +** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   1.114 +**
   1.115 +** If an illegal or unsupported join type is seen, then still return
   1.116 +** a join type, but put an error in the pParse structure.
   1.117 +*/
   1.118 +int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   1.119 +  int jointype = 0;
   1.120 +  Token *apAll[3];
   1.121 +  Token *p;
   1.122 +  static const struct {
   1.123 +    const char zKeyword[8];
   1.124 +    u8 nChar;
   1.125 +    u8 code;
   1.126 +  } keywords[] = {
   1.127 +    { "natural", 7, JT_NATURAL },
   1.128 +    { "left",    4, JT_LEFT|JT_OUTER },
   1.129 +    { "right",   5, JT_RIGHT|JT_OUTER },
   1.130 +    { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
   1.131 +    { "outer",   5, JT_OUTER },
   1.132 +    { "inner",   5, JT_INNER },
   1.133 +    { "cross",   5, JT_INNER|JT_CROSS },
   1.134 +  };
   1.135 +  int i, j;
   1.136 +  apAll[0] = pA;
   1.137 +  apAll[1] = pB;
   1.138 +  apAll[2] = pC;
   1.139 +  for(i=0; i<3 && apAll[i]; i++){
   1.140 +    p = apAll[i];
   1.141 +    for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
   1.142 +      if( p->n==keywords[j].nChar 
   1.143 +          && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
   1.144 +        jointype |= keywords[j].code;
   1.145 +        break;
   1.146 +      }
   1.147 +    }
   1.148 +    if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
   1.149 +      jointype |= JT_ERROR;
   1.150 +      break;
   1.151 +    }
   1.152 +  }
   1.153 +  if(
   1.154 +     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   1.155 +     (jointype & JT_ERROR)!=0
   1.156 +  ){
   1.157 +    const char *zSp1 = " ";
   1.158 +    const char *zSp2 = " ";
   1.159 +    if( pB==0 ){ zSp1++; }
   1.160 +    if( pC==0 ){ zSp2++; }
   1.161 +    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   1.162 +       "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
   1.163 +    jointype = JT_INNER;
   1.164 +  }else if( jointype & JT_RIGHT ){
   1.165 +    sqlite3ErrorMsg(pParse, 
   1.166 +      "RIGHT and FULL OUTER JOINs are not currently supported");
   1.167 +    jointype = JT_INNER;
   1.168 +  }
   1.169 +  return jointype;
   1.170 +}
   1.171 +
   1.172 +/*
   1.173 +** Return the index of a column in a table.  Return -1 if the column
   1.174 +** is not contained in the table.
   1.175 +*/
   1.176 +static int columnIndex(Table *pTab, const char *zCol){
   1.177 +  int i;
   1.178 +  for(i=0; i<pTab->nCol; i++){
   1.179 +    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   1.180 +  }
   1.181 +  return -1;
   1.182 +}
   1.183 +
   1.184 +/*
   1.185 +** Set the value of a token to a '\000'-terminated string.
   1.186 +*/
   1.187 +static void setToken(Token *p, const char *z){
   1.188 +  p->z = (u8*)z;
   1.189 +  p->n = z ? strlen(z) : 0;
   1.190 +  p->dyn = 0;
   1.191 +}
   1.192 +
   1.193 +/*
   1.194 +** Set the token to the double-quoted and escaped version of the string pointed
   1.195 +** to by z. For example;
   1.196 +**
   1.197 +**    {a"bc}  ->  {"a""bc"}
   1.198 +*/
   1.199 +static void setQuotedToken(Parse *pParse, Token *p, const char *z){
   1.200 +  p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z);
   1.201 +  p->dyn = 1;
   1.202 +  if( p->z ){
   1.203 +    p->n = strlen((char *)p->z);
   1.204 +  }else{
   1.205 +    pParse->db->mallocFailed = 1;
   1.206 +  }
   1.207 +}
   1.208 +
   1.209 +/*
   1.210 +** Create an expression node for an identifier with the name of zName
   1.211 +*/
   1.212 +Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
   1.213 +  Token dummy;
   1.214 +  setToken(&dummy, zName);
   1.215 +  return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
   1.216 +}
   1.217 +
   1.218 +
   1.219 +/*
   1.220 +** Add a term to the WHERE expression in *ppExpr that requires the
   1.221 +** zCol column to be equal in the two tables pTab1 and pTab2.
   1.222 +*/
   1.223 +static void addWhereTerm(
   1.224 +  Parse *pParse,           /* Parsing context */
   1.225 +  const char *zCol,        /* Name of the column */
   1.226 +  const Table *pTab1,      /* First table */
   1.227 +  const char *zAlias1,     /* Alias for first table.  May be NULL */
   1.228 +  const Table *pTab2,      /* Second table */
   1.229 +  const char *zAlias2,     /* Alias for second table.  May be NULL */
   1.230 +  int iRightJoinTable,     /* VDBE cursor for the right table */
   1.231 +  Expr **ppExpr            /* Add the equality term to this expression */
   1.232 +){
   1.233 +  Expr *pE1a, *pE1b, *pE1c;
   1.234 +  Expr *pE2a, *pE2b, *pE2c;
   1.235 +  Expr *pE;
   1.236 +
   1.237 +  pE1a = sqlite3CreateIdExpr(pParse, zCol);
   1.238 +  pE2a = sqlite3CreateIdExpr(pParse, zCol);
   1.239 +  if( zAlias1==0 ){
   1.240 +    zAlias1 = pTab1->zName;
   1.241 +  }
   1.242 +  pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
   1.243 +  if( zAlias2==0 ){
   1.244 +    zAlias2 = pTab2->zName;
   1.245 +  }
   1.246 +  pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
   1.247 +  pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
   1.248 +  pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
   1.249 +  pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
   1.250 +  if( pE ){
   1.251 +    ExprSetProperty(pE, EP_FromJoin);
   1.252 +    pE->iRightJoinTable = iRightJoinTable;
   1.253 +  }
   1.254 +  pE = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
   1.255 +  if( pE ){
   1.256 +    *ppExpr = pE;
   1.257 +  }
   1.258 +}
   1.259 +
   1.260 +/*
   1.261 +** Set the EP_FromJoin property on all terms of the given expression.
   1.262 +** And set the Expr.iRightJoinTable to iTable for every term in the
   1.263 +** expression.
   1.264 +**
   1.265 +** The EP_FromJoin property is used on terms of an expression to tell
   1.266 +** the LEFT OUTER JOIN processing logic that this term is part of the
   1.267 +** join restriction specified in the ON or USING clause and not a part
   1.268 +** of the more general WHERE clause.  These terms are moved over to the
   1.269 +** WHERE clause during join processing but we need to remember that they
   1.270 +** originated in the ON or USING clause.
   1.271 +**
   1.272 +** The Expr.iRightJoinTable tells the WHERE clause processing that the
   1.273 +** expression depends on table iRightJoinTable even if that table is not
   1.274 +** explicitly mentioned in the expression.  That information is needed
   1.275 +** for cases like this:
   1.276 +**
   1.277 +**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   1.278 +**
   1.279 +** The where clause needs to defer the handling of the t1.x=5
   1.280 +** term until after the t2 loop of the join.  In that way, a
   1.281 +** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   1.282 +** defer the handling of t1.x=5, it will be processed immediately
   1.283 +** after the t1 loop and rows with t1.x!=5 will never appear in
   1.284 +** the output, which is incorrect.
   1.285 +*/
   1.286 +static void setJoinExpr(Expr *p, int iTable){
   1.287 +  while( p ){
   1.288 +    ExprSetProperty(p, EP_FromJoin);
   1.289 +    p->iRightJoinTable = iTable;
   1.290 +    setJoinExpr(p->pLeft, iTable);
   1.291 +    p = p->pRight;
   1.292 +  } 
   1.293 +}
   1.294 +
   1.295 +/*
   1.296 +** This routine processes the join information for a SELECT statement.
   1.297 +** ON and USING clauses are converted into extra terms of the WHERE clause.
   1.298 +** NATURAL joins also create extra WHERE clause terms.
   1.299 +**
   1.300 +** The terms of a FROM clause are contained in the Select.pSrc structure.
   1.301 +** The left most table is the first entry in Select.pSrc.  The right-most
   1.302 +** table is the last entry.  The join operator is held in the entry to
   1.303 +** the left.  Thus entry 0 contains the join operator for the join between
   1.304 +** entries 0 and 1.  Any ON or USING clauses associated with the join are
   1.305 +** also attached to the left entry.
   1.306 +**
   1.307 +** This routine returns the number of errors encountered.
   1.308 +*/
   1.309 +static int sqliteProcessJoin(Parse *pParse, Select *p){
   1.310 +  SrcList *pSrc;                  /* All tables in the FROM clause */
   1.311 +  int i, j;                       /* Loop counters */
   1.312 +  struct SrcList_item *pLeft;     /* Left table being joined */
   1.313 +  struct SrcList_item *pRight;    /* Right table being joined */
   1.314 +
   1.315 +  pSrc = p->pSrc;
   1.316 +  pLeft = &pSrc->a[0];
   1.317 +  pRight = &pLeft[1];
   1.318 +  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   1.319 +    Table *pLeftTab = pLeft->pTab;
   1.320 +    Table *pRightTab = pRight->pTab;
   1.321 +
   1.322 +    if( pLeftTab==0 || pRightTab==0 ) continue;
   1.323 +
   1.324 +    /* When the NATURAL keyword is present, add WHERE clause terms for
   1.325 +    ** every column that the two tables have in common.
   1.326 +    */
   1.327 +    if( pRight->jointype & JT_NATURAL ){
   1.328 +      if( pRight->pOn || pRight->pUsing ){
   1.329 +        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   1.330 +           "an ON or USING clause", 0);
   1.331 +        return 1;
   1.332 +      }
   1.333 +      for(j=0; j<pLeftTab->nCol; j++){
   1.334 +        char *zName = pLeftTab->aCol[j].zName;
   1.335 +        if( columnIndex(pRightTab, zName)>=0 ){
   1.336 +          addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
   1.337 +                              pRightTab, pRight->zAlias,
   1.338 +                              pRight->iCursor, &p->pWhere);
   1.339 +          
   1.340 +        }
   1.341 +      }
   1.342 +    }
   1.343 +
   1.344 +    /* Disallow both ON and USING clauses in the same join
   1.345 +    */
   1.346 +    if( pRight->pOn && pRight->pUsing ){
   1.347 +      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   1.348 +        "clauses in the same join");
   1.349 +      return 1;
   1.350 +    }
   1.351 +
   1.352 +    /* Add the ON clause to the end of the WHERE clause, connected by
   1.353 +    ** an AND operator.
   1.354 +    */
   1.355 +    if( pRight->pOn ){
   1.356 +      setJoinExpr(pRight->pOn, pRight->iCursor);
   1.357 +      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   1.358 +      pRight->pOn = 0;
   1.359 +    }
   1.360 +
   1.361 +    /* Create extra terms on the WHERE clause for each column named
   1.362 +    ** in the USING clause.  Example: If the two tables to be joined are 
   1.363 +    ** A and B and the USING clause names X, Y, and Z, then add this
   1.364 +    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   1.365 +    ** Report an error if any column mentioned in the USING clause is
   1.366 +    ** not contained in both tables to be joined.
   1.367 +    */
   1.368 +    if( pRight->pUsing ){
   1.369 +      IdList *pList = pRight->pUsing;
   1.370 +      for(j=0; j<pList->nId; j++){
   1.371 +        char *zName = pList->a[j].zName;
   1.372 +        if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
   1.373 +          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   1.374 +            "not present in both tables", zName);
   1.375 +          return 1;
   1.376 +        }
   1.377 +        addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
   1.378 +                            pRightTab, pRight->zAlias,
   1.379 +                            pRight->iCursor, &p->pWhere);
   1.380 +      }
   1.381 +    }
   1.382 +  }
   1.383 +  return 0;
   1.384 +}
   1.385 +
   1.386 +/*
   1.387 +** Insert code into "v" that will push the record on the top of the
   1.388 +** stack into the sorter.
   1.389 +*/
   1.390 +static void pushOntoSorter(
   1.391 +  Parse *pParse,         /* Parser context */
   1.392 +  ExprList *pOrderBy,    /* The ORDER BY clause */
   1.393 +  Select *pSelect        /* The whole SELECT statement */
   1.394 +){
   1.395 +  Vdbe *v = pParse->pVdbe;
   1.396 +  sqlite3ExprCodeExprList(pParse, pOrderBy);
   1.397 +  sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0);
   1.398 +  sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0);
   1.399 +  sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0);
   1.400 +  sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0);
   1.401 +  if( pSelect->iLimit>=0 ){
   1.402 +    int addr1, addr2;
   1.403 +    addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0);
   1.404 +    sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1);
   1.405 +    addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
   1.406 +    sqlite3VdbeJumpHere(v, addr1);
   1.407 +    sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0);
   1.408 +    sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0);
   1.409 +    sqlite3VdbeJumpHere(v, addr2);
   1.410 +    pSelect->iLimit = -1;
   1.411 +  }
   1.412 +}
   1.413 +
   1.414 +/*
   1.415 +** Add code to implement the OFFSET
   1.416 +*/
   1.417 +static void codeOffset(
   1.418 +  Vdbe *v,          /* Generate code into this VM */
   1.419 +  Select *p,        /* The SELECT statement being coded */
   1.420 +  int iContinue,    /* Jump here to skip the current record */
   1.421 +  int nPop          /* Number of times to pop stack when jumping */
   1.422 +){
   1.423 +  if( p->iOffset>=0 && iContinue!=0 ){
   1.424 +    int addr;
   1.425 +    sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset);
   1.426 +    addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0);
   1.427 +    if( nPop>0 ){
   1.428 +      sqlite3VdbeAddOp(v, OP_Pop, nPop, 0);
   1.429 +    }
   1.430 +    sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue);
   1.431 +    VdbeComment((v, "# skip OFFSET records"));
   1.432 +    sqlite3VdbeJumpHere(v, addr);
   1.433 +  }
   1.434 +}
   1.435 +
   1.436 +/*
   1.437 +** Add code that will check to make sure the top N elements of the
   1.438 +** stack are distinct.  iTab is a sorting index that holds previously
   1.439 +** seen combinations of the N values.  A new entry is made in iTab
   1.440 +** if the current N values are new.
   1.441 +**
   1.442 +** A jump to addrRepeat is made and the N+1 values are popped from the
   1.443 +** stack if the top N elements are not distinct.
   1.444 +*/
   1.445 +static void codeDistinct(
   1.446 +  Vdbe *v,           /* Generate code into this VM */
   1.447 +  int iTab,          /* A sorting index used to test for distinctness */
   1.448 +  int addrRepeat,    /* Jump to here if not distinct */
   1.449 +  int N              /* The top N elements of the stack must be distinct */
   1.450 +){
   1.451 +  sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0);
   1.452 +  sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3);
   1.453 +  sqlite3VdbeAddOp(v, OP_Pop, N+1, 0);
   1.454 +  sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat);
   1.455 +  VdbeComment((v, "# skip indistinct records"));
   1.456 +  sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0);
   1.457 +}
   1.458 +
   1.459 +/*
   1.460 +** Generate an error message when a SELECT is used within a subexpression
   1.461 +** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   1.462 +** column.  We do this in a subroutine because the error occurs in multiple
   1.463 +** places.
   1.464 +*/
   1.465 +static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){
   1.466 +  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   1.467 +    sqlite3ErrorMsg(pParse, "only a single result allowed for "
   1.468 +       "a SELECT that is part of an expression");
   1.469 +    return 1;
   1.470 +  }else{
   1.471 +    return 0;
   1.472 +  }
   1.473 +}
   1.474 +
   1.475 +/*
   1.476 +** This routine generates the code for the inside of the inner loop
   1.477 +** of a SELECT.
   1.478 +**
   1.479 +** If srcTab and nColumn are both zero, then the pEList expressions
   1.480 +** are evaluated in order to get the data for this row.  If nColumn>0
   1.481 +** then data is pulled from srcTab and pEList is used only to get the
   1.482 +** datatypes for each column.
   1.483 +*/
   1.484 +static int selectInnerLoop(
   1.485 +  Parse *pParse,          /* The parser context */
   1.486 +  Select *p,              /* The complete select statement being coded */
   1.487 +  ExprList *pEList,       /* List of values being extracted */
   1.488 +  int srcTab,             /* Pull data from this table */
   1.489 +  int nColumn,            /* Number of columns in the source table */
   1.490 +  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
   1.491 +  int distinct,           /* If >=0, make sure results are distinct */
   1.492 +  int eDest,              /* How to dispose of the results */
   1.493 +  int iParm,              /* An argument to the disposal method */
   1.494 +  int iContinue,          /* Jump here to continue with next row */
   1.495 +  int iBreak,             /* Jump here to break out of the inner loop */
   1.496 +  char *aff               /* affinity string if eDest is SRT_Union */
   1.497 +){
   1.498 +  Vdbe *v = pParse->pVdbe;
   1.499 +  int i;
   1.500 +  int hasDistinct;        /* True if the DISTINCT keyword is present */
   1.501 +
   1.502 +  if( v==0 ) return 0;
   1.503 +  assert( pEList!=0 );
   1.504 +
   1.505 +  /* If there was a LIMIT clause on the SELECT statement, then do the check
   1.506 +  ** to see if this row should be output.
   1.507 +  */
   1.508 +  hasDistinct = distinct>=0 && pEList->nExpr>0;
   1.509 +  if( pOrderBy==0 && !hasDistinct ){
   1.510 +    codeOffset(v, p, iContinue, 0);
   1.511 +  }
   1.512 +
   1.513 +  /* Pull the requested columns.
   1.514 +  */
   1.515 +  if( nColumn>0 ){
   1.516 +    for(i=0; i<nColumn; i++){
   1.517 +      sqlite3VdbeAddOp(v, OP_Column, srcTab, i);
   1.518 +    }
   1.519 +  }else{
   1.520 +    nColumn = pEList->nExpr;
   1.521 +    sqlite3ExprCodeExprList(pParse, pEList);
   1.522 +  }
   1.523 +
   1.524 +  /* If the DISTINCT keyword was present on the SELECT statement
   1.525 +  ** and this row has been seen before, then do not make this row
   1.526 +  ** part of the result.
   1.527 +  */
   1.528 +  if( hasDistinct ){
   1.529 +    assert( pEList!=0 );
   1.530 +    assert( pEList->nExpr==nColumn );
   1.531 +    codeDistinct(v, distinct, iContinue, nColumn);
   1.532 +    if( pOrderBy==0 ){
   1.533 +      codeOffset(v, p, iContinue, nColumn);
   1.534 +    }
   1.535 +  }
   1.536 +
   1.537 +  if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
   1.538 +    return 0;
   1.539 +  }
   1.540 +
   1.541 +  switch( eDest ){
   1.542 +    /* In this mode, write each query result to the key of the temporary
   1.543 +    ** table iParm.
   1.544 +    */
   1.545 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
   1.546 +    case SRT_Union: {
   1.547 +      sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
   1.548 +      if( aff ){
   1.549 +        sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
   1.550 +      }
   1.551 +      sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0);
   1.552 +      break;
   1.553 +    }
   1.554 +
   1.555 +    /* Construct a record from the query result, but instead of
   1.556 +    ** saving that record, use it as a key to delete elements from
   1.557 +    ** the temporary table iParm.
   1.558 +    */
   1.559 +    case SRT_Except: {
   1.560 +      int addr;
   1.561 +      addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
   1.562 +      sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC);
   1.563 +      sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3);
   1.564 +      sqlite3VdbeAddOp(v, OP_Delete, iParm, 0);
   1.565 +      break;
   1.566 +    }
   1.567 +#endif
   1.568 +
   1.569 +    /* Store the result as data using a unique key.
   1.570 +    */
   1.571 +    case SRT_Table:
   1.572 +    case SRT_EphemTab: {
   1.573 +      sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
   1.574 +      if( pOrderBy ){
   1.575 +        pushOntoSorter(pParse, pOrderBy, p);
   1.576 +      }else{
   1.577 +        sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
   1.578 +        sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
   1.579 +        sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
   1.580 +      }
   1.581 +      break;
   1.582 +    }
   1.583 +
   1.584 +#ifndef SQLITE_OMIT_SUBQUERY
   1.585 +    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   1.586 +    ** then there should be a single item on the stack.  Write this
   1.587 +    ** item into the set table with bogus data.
   1.588 +    */
   1.589 +    case SRT_Set: {
   1.590 +      int addr1 = sqlite3VdbeCurrentAddr(v);
   1.591 +      int addr2;
   1.592 +
   1.593 +      assert( nColumn==1 );
   1.594 +      sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3);
   1.595 +      sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
   1.596 +      addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
   1.597 +      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff);
   1.598 +      if( pOrderBy ){
   1.599 +        /* At first glance you would think we could optimize out the
   1.600 +        ** ORDER BY in this case since the order of entries in the set
   1.601 +        ** does not matter.  But there might be a LIMIT clause, in which
   1.602 +        ** case the order does matter */
   1.603 +        pushOntoSorter(pParse, pOrderBy, p);
   1.604 +      }else{
   1.605 +        sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
   1.606 +        sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
   1.607 +      }
   1.608 +      sqlite3VdbeJumpHere(v, addr2);
   1.609 +      break;
   1.610 +    }
   1.611 +
   1.612 +    /* If any row exist in the result set, record that fact and abort.
   1.613 +    */
   1.614 +    case SRT_Exists: {
   1.615 +      sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm);
   1.616 +      sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
   1.617 +      /* The LIMIT clause will terminate the loop for us */
   1.618 +      break;
   1.619 +    }
   1.620 +
   1.621 +    /* If this is a scalar select that is part of an expression, then
   1.622 +    ** store the results in the appropriate memory cell and break out
   1.623 +    ** of the scan loop.
   1.624 +    */
   1.625 +    case SRT_Mem: {
   1.626 +      assert( nColumn==1 );
   1.627 +      if( pOrderBy ){
   1.628 +        pushOntoSorter(pParse, pOrderBy, p);
   1.629 +      }else{
   1.630 +        sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
   1.631 +        /* The LIMIT clause will jump out of the loop for us */
   1.632 +      }
   1.633 +      break;
   1.634 +    }
   1.635 +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   1.636 +
   1.637 +    /* Send the data to the callback function or to a subroutine.  In the
   1.638 +    ** case of a subroutine, the subroutine itself is responsible for
   1.639 +    ** popping the data from the stack.
   1.640 +    */
   1.641 +    case SRT_Subroutine:
   1.642 +    case SRT_Callback: {
   1.643 +      if( pOrderBy ){
   1.644 +        sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0);
   1.645 +        pushOntoSorter(pParse, pOrderBy, p);
   1.646 +      }else if( eDest==SRT_Subroutine ){
   1.647 +        sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
   1.648 +      }else{
   1.649 +        sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
   1.650 +      }
   1.651 +      break;
   1.652 +    }
   1.653 +
   1.654 +#if !defined(SQLITE_OMIT_TRIGGER)
   1.655 +    /* Discard the results.  This is used for SELECT statements inside
   1.656 +    ** the body of a TRIGGER.  The purpose of such selects is to call
   1.657 +    ** user-defined functions that have side effects.  We do not care
   1.658 +    ** about the actual results of the select.
   1.659 +    */
   1.660 +    default: {
   1.661 +      assert( eDest==SRT_Discard );
   1.662 +      sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0);
   1.663 +      break;
   1.664 +    }
   1.665 +#endif
   1.666 +  }
   1.667 +
   1.668 +  /* Jump to the end of the loop if the LIMIT is reached.
   1.669 +  */
   1.670 +  if( p->iLimit>=0 && pOrderBy==0 ){
   1.671 +    sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
   1.672 +    sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak);
   1.673 +  }
   1.674 +  return 0;
   1.675 +}
   1.676 +
   1.677 +/*
   1.678 +** Given an expression list, generate a KeyInfo structure that records
   1.679 +** the collating sequence for each expression in that expression list.
   1.680 +**
   1.681 +** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   1.682 +** KeyInfo structure is appropriate for initializing a virtual index to
   1.683 +** implement that clause.  If the ExprList is the result set of a SELECT
   1.684 +** then the KeyInfo structure is appropriate for initializing a virtual
   1.685 +** index to implement a DISTINCT test.
   1.686 +**
   1.687 +** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   1.688 +** function is responsible for seeing that this structure is eventually
   1.689 +** freed.  Add the KeyInfo structure to the P3 field of an opcode using
   1.690 +** P3_KEYINFO_HANDOFF is the usual way of dealing with this.
   1.691 +*/
   1.692 +static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
   1.693 +  sqlite3 *db = pParse->db;
   1.694 +  int nExpr;
   1.695 +  KeyInfo *pInfo;
   1.696 +  struct ExprList_item *pItem;
   1.697 +  int i;
   1.698 +
   1.699 +  nExpr = pList->nExpr;
   1.700 +  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
   1.701 +  if( pInfo ){
   1.702 +    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
   1.703 +    pInfo->nField = nExpr;
   1.704 +    pInfo->enc = ENC(db);
   1.705 +    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
   1.706 +      CollSeq *pColl;
   1.707 +      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   1.708 +      if( !pColl ){
   1.709 +        pColl = db->pDfltColl;
   1.710 +      }
   1.711 +      pInfo->aColl[i] = pColl;
   1.712 +      pInfo->aSortOrder[i] = pItem->sortOrder;
   1.713 +    }
   1.714 +  }
   1.715 +  return pInfo;
   1.716 +}
   1.717 +
   1.718 +
   1.719 +/*
   1.720 +** If the inner loop was generated using a non-null pOrderBy argument,
   1.721 +** then the results were placed in a sorter.  After the loop is terminated
   1.722 +** we need to run the sorter and output the results.  The following
   1.723 +** routine generates the code needed to do that.
   1.724 +*/
   1.725 +static void generateSortTail(
   1.726 +  Parse *pParse,   /* Parsing context */
   1.727 +  Select *p,       /* The SELECT statement */
   1.728 +  Vdbe *v,         /* Generate code into this VDBE */
   1.729 +  int nColumn,     /* Number of columns of data */
   1.730 +  int eDest,       /* Write the sorted results here */
   1.731 +  int iParm        /* Optional parameter associated with eDest */
   1.732 +){
   1.733 +  int brk = sqlite3VdbeMakeLabel(v);
   1.734 +  int cont = sqlite3VdbeMakeLabel(v);
   1.735 +  int addr;
   1.736 +  int iTab;
   1.737 +  int pseudoTab = 0;
   1.738 +  ExprList *pOrderBy = p->pOrderBy;
   1.739 +
   1.740 +  iTab = pOrderBy->iECursor;
   1.741 +  if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
   1.742 +    pseudoTab = pParse->nTab++;
   1.743 +    sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0);
   1.744 +    sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn);
   1.745 +  }
   1.746 +  addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk);
   1.747 +  codeOffset(v, p, cont, 0);
   1.748 +  if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
   1.749 +    sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
   1.750 +  }
   1.751 +  sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1);
   1.752 +  switch( eDest ){
   1.753 +    case SRT_Table:
   1.754 +    case SRT_EphemTab: {
   1.755 +      sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0);
   1.756 +      sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
   1.757 +      sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND);
   1.758 +      break;
   1.759 +    }
   1.760 +#ifndef SQLITE_OMIT_SUBQUERY
   1.761 +    case SRT_Set: {
   1.762 +      assert( nColumn==1 );
   1.763 +      sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
   1.764 +      sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
   1.765 +      sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
   1.766 +      sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1);
   1.767 +      sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0);
   1.768 +      break;
   1.769 +    }
   1.770 +    case SRT_Mem: {
   1.771 +      assert( nColumn==1 );
   1.772 +      sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1);
   1.773 +      /* The LIMIT clause will terminate the loop for us */
   1.774 +      break;
   1.775 +    }
   1.776 +#endif
   1.777 +    case SRT_Callback:
   1.778 +    case SRT_Subroutine: {
   1.779 +      int i;
   1.780 +      sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0);
   1.781 +      for(i=0; i<nColumn; i++){
   1.782 +        sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i);
   1.783 +      }
   1.784 +      if( eDest==SRT_Callback ){
   1.785 +        sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0);
   1.786 +      }else{
   1.787 +        sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm);
   1.788 +      }
   1.789 +      break;
   1.790 +    }
   1.791 +    default: {
   1.792 +      /* Do nothing */
   1.793 +      break;
   1.794 +    }
   1.795 +  }
   1.796 +
   1.797 +  /* Jump to the end of the loop when the LIMIT is reached
   1.798 +  */
   1.799 +  if( p->iLimit>=0 ){
   1.800 +    sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit);
   1.801 +    sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk);
   1.802 +  }
   1.803 +
   1.804 +  /* The bottom of the loop
   1.805 +  */
   1.806 +  sqlite3VdbeResolveLabel(v, cont);
   1.807 +  sqlite3VdbeAddOp(v, OP_Next, iTab, addr);
   1.808 +  sqlite3VdbeResolveLabel(v, brk);
   1.809 +  if( eDest==SRT_Callback || eDest==SRT_Subroutine ){
   1.810 +    sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0);
   1.811 +  }
   1.812 +
   1.813 +}
   1.814 +
   1.815 +/*
   1.816 +** Return a pointer to a string containing the 'declaration type' of the
   1.817 +** expression pExpr. The string may be treated as static by the caller.
   1.818 +**
   1.819 +** The declaration type is the exact datatype definition extracted from the
   1.820 +** original CREATE TABLE statement if the expression is a column. The
   1.821 +** declaration type for a ROWID field is INTEGER. Exactly when an expression
   1.822 +** is considered a column can be complex in the presence of subqueries. The
   1.823 +** result-set expression in all of the following SELECT statements is 
   1.824 +** considered a column by this function.
   1.825 +**
   1.826 +**   SELECT col FROM tbl;
   1.827 +**   SELECT (SELECT col FROM tbl;
   1.828 +**   SELECT (SELECT col FROM tbl);
   1.829 +**   SELECT abc FROM (SELECT col AS abc FROM tbl);
   1.830 +** 
   1.831 +** The declaration type for any expression other than a column is NULL.
   1.832 +*/
   1.833 +static const char *columnType(
   1.834 +  NameContext *pNC, 
   1.835 +  Expr *pExpr,
   1.836 +  const char **pzOriginDb,
   1.837 +  const char **pzOriginTab,
   1.838 +  const char **pzOriginCol
   1.839 +){
   1.840 +  char const *zType = 0;
   1.841 +  char const *zOriginDb = 0;
   1.842 +  char const *zOriginTab = 0;
   1.843 +  char const *zOriginCol = 0;
   1.844 +  int j;
   1.845 +  if( pExpr==0 || pNC->pSrcList==0 ) return 0;
   1.846 +
   1.847 +  switch( pExpr->op ){
   1.848 +    case TK_AGG_COLUMN:
   1.849 +    case TK_COLUMN: {
   1.850 +      /* The expression is a column. Locate the table the column is being
   1.851 +      ** extracted from in NameContext.pSrcList. This table may be real
   1.852 +      ** database table or a subquery.
   1.853 +      */
   1.854 +      Table *pTab = 0;            /* Table structure column is extracted from */
   1.855 +      Select *pS = 0;             /* Select the column is extracted from */
   1.856 +      int iCol = pExpr->iColumn;  /* Index of column in pTab */
   1.857 +      while( pNC && !pTab ){
   1.858 +        SrcList *pTabList = pNC->pSrcList;
   1.859 +        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   1.860 +        if( j<pTabList->nSrc ){
   1.861 +          pTab = pTabList->a[j].pTab;
   1.862 +          pS = pTabList->a[j].pSelect;
   1.863 +        }else{
   1.864 +          pNC = pNC->pNext;
   1.865 +        }
   1.866 +      }
   1.867 +
   1.868 +      if( pTab==0 ){
   1.869 +        /* FIX ME:
   1.870 +        ** This can occurs if you have something like "SELECT new.x;" inside
   1.871 +        ** a trigger.  In other words, if you reference the special "new"
   1.872 +        ** table in the result set of a select.  We do not have a good way
   1.873 +        ** to find the actual table type, so call it "TEXT".  This is really
   1.874 +        ** something of a bug, but I do not know how to fix it.
   1.875 +        **
   1.876 +        ** This code does not produce the correct answer - it just prevents
   1.877 +        ** a segfault.  See ticket #1229.
   1.878 +        */
   1.879 +        zType = "TEXT";
   1.880 +        break;
   1.881 +      }
   1.882 +
   1.883 +      assert( pTab );
   1.884 +      if( pS ){
   1.885 +        /* The "table" is actually a sub-select or a view in the FROM clause
   1.886 +        ** of the SELECT statement. Return the declaration type and origin
   1.887 +        ** data for the result-set column of the sub-select.
   1.888 +        */
   1.889 +        if( iCol>=0 && iCol<pS->pEList->nExpr ){
   1.890 +          /* If iCol is less than zero, then the expression requests the
   1.891 +          ** rowid of the sub-select or view. This expression is legal (see 
   1.892 +          ** test case misc2.2.2) - it always evaluates to NULL.
   1.893 +          */
   1.894 +          NameContext sNC;
   1.895 +          Expr *p = pS->pEList->a[iCol].pExpr;
   1.896 +          sNC.pSrcList = pS->pSrc;
   1.897 +          sNC.pNext = 0;
   1.898 +          sNC.pParse = pNC->pParse;
   1.899 +          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
   1.900 +        }
   1.901 +      }else if( pTab->pSchema ){
   1.902 +        /* A real table */
   1.903 +        assert( !pS );
   1.904 +        if( iCol<0 ) iCol = pTab->iPKey;
   1.905 +        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   1.906 +        if( iCol<0 ){
   1.907 +          zType = "INTEGER";
   1.908 +          zOriginCol = "rowid";
   1.909 +        }else{
   1.910 +          zType = pTab->aCol[iCol].zType;
   1.911 +          zOriginCol = pTab->aCol[iCol].zName;
   1.912 +        }
   1.913 +        zOriginTab = pTab->zName;
   1.914 +        if( pNC->pParse ){
   1.915 +          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   1.916 +          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
   1.917 +        }
   1.918 +      }
   1.919 +      break;
   1.920 +    }
   1.921 +#ifndef SQLITE_OMIT_SUBQUERY
   1.922 +    case TK_SELECT: {
   1.923 +      /* The expression is a sub-select. Return the declaration type and
   1.924 +      ** origin info for the single column in the result set of the SELECT
   1.925 +      ** statement.
   1.926 +      */
   1.927 +      NameContext sNC;
   1.928 +      Select *pS = pExpr->pSelect;
   1.929 +      Expr *p = pS->pEList->a[0].pExpr;
   1.930 +      sNC.pSrcList = pS->pSrc;
   1.931 +      sNC.pNext = pNC;
   1.932 +      sNC.pParse = pNC->pParse;
   1.933 +      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
   1.934 +      break;
   1.935 +    }
   1.936 +#endif
   1.937 +  }
   1.938 +  
   1.939 +  if( pzOriginDb ){
   1.940 +    assert( pzOriginTab && pzOriginCol );
   1.941 +    *pzOriginDb = zOriginDb;
   1.942 +    *pzOriginTab = zOriginTab;
   1.943 +    *pzOriginCol = zOriginCol;
   1.944 +  }
   1.945 +  return zType;
   1.946 +}
   1.947 +
   1.948 +/*
   1.949 +** Generate code that will tell the VDBE the declaration types of columns
   1.950 +** in the result set.
   1.951 +*/
   1.952 +static void generateColumnTypes(
   1.953 +  Parse *pParse,      /* Parser context */
   1.954 +  SrcList *pTabList,  /* List of tables */
   1.955 +  ExprList *pEList    /* Expressions defining the result set */
   1.956 +){
   1.957 +  Vdbe *v = pParse->pVdbe;
   1.958 +  int i;
   1.959 +  NameContext sNC;
   1.960 +  sNC.pSrcList = pTabList;
   1.961 +  sNC.pParse = pParse;
   1.962 +  for(i=0; i<pEList->nExpr; i++){
   1.963 +    Expr *p = pEList->a[i].pExpr;
   1.964 +    const char *zOrigDb = 0;
   1.965 +    const char *zOrigTab = 0;
   1.966 +    const char *zOrigCol = 0;
   1.967 +    const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
   1.968 +
   1.969 +    /* The vdbe must make it's own copy of the column-type and other 
   1.970 +    ** column specific strings, in case the schema is reset before this
   1.971 +    ** virtual machine is deleted.
   1.972 +    */
   1.973 +    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT);
   1.974 +    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT);
   1.975 +    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT);
   1.976 +    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT);
   1.977 +  }
   1.978 +}
   1.979 +
   1.980 +/*
   1.981 +** Generate code that will tell the VDBE the names of columns
   1.982 +** in the result set.  This information is used to provide the
   1.983 +** azCol[] values in the callback.
   1.984 +*/
   1.985 +static void generateColumnNames(
   1.986 +  Parse *pParse,      /* Parser context */
   1.987 +  SrcList *pTabList,  /* List of tables */
   1.988 +  ExprList *pEList    /* Expressions defining the result set */
   1.989 +){
   1.990 +  Vdbe *v = pParse->pVdbe;
   1.991 +  int i, j;
   1.992 +  sqlite3 *db = pParse->db;
   1.993 +  int fullNames, shortNames;
   1.994 +
   1.995 +#ifndef SQLITE_OMIT_EXPLAIN
   1.996 +  /* If this is an EXPLAIN, skip this step */
   1.997 +  if( pParse->explain ){
   1.998 +    return;
   1.999 +  }
  1.1000 +#endif
  1.1001 +
  1.1002 +  assert( v!=0 );
  1.1003 +  if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
  1.1004 +  pParse->colNamesSet = 1;
  1.1005 +  fullNames = (db->flags & SQLITE_FullColNames)!=0;
  1.1006 +  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  1.1007 +  sqlite3VdbeSetNumCols(v, pEList->nExpr);
  1.1008 +  for(i=0; i<pEList->nExpr; i++){
  1.1009 +    Expr *p;
  1.1010 +    p = pEList->a[i].pExpr;
  1.1011 +    if( p==0 ) continue;
  1.1012 +    if( pEList->a[i].zName ){
  1.1013 +      char *zName = pEList->a[i].zName;
  1.1014 +      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
  1.1015 +      continue;
  1.1016 +    }
  1.1017 +    if( p->op==TK_COLUMN && pTabList ){
  1.1018 +      Table *pTab;
  1.1019 +      char *zCol;
  1.1020 +      int iCol = p->iColumn;
  1.1021 +      for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
  1.1022 +      assert( j<pTabList->nSrc );
  1.1023 +      pTab = pTabList->a[j].pTab;
  1.1024 +      if( iCol<0 ) iCol = pTab->iPKey;
  1.1025 +      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  1.1026 +      if( iCol<0 ){
  1.1027 +        zCol = "rowid";
  1.1028 +      }else{
  1.1029 +        zCol = pTab->aCol[iCol].zName;
  1.1030 +      }
  1.1031 +      if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
  1.1032 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
  1.1033 +      }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
  1.1034 +        char *zName = 0;
  1.1035 +        char *zTab;
  1.1036 + 
  1.1037 +        zTab = pTabList->a[j].zAlias;
  1.1038 +        if( fullNames || zTab==0 ) zTab = pTab->zName;
  1.1039 +        sqlite3SetString(&zName, zTab, ".", zCol, (char*)0);
  1.1040 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC);
  1.1041 +      }else{
  1.1042 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
  1.1043 +      }
  1.1044 +    }else if( p->span.z && p->span.z[0] ){
  1.1045 +      sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
  1.1046 +      /* sqlite3VdbeCompressSpace(v, addr); */
  1.1047 +    }else{
  1.1048 +      char zName[30];
  1.1049 +      assert( p->op!=TK_COLUMN || pTabList==0 );
  1.1050 +      sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1);
  1.1051 +      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0);
  1.1052 +    }
  1.1053 +  }
  1.1054 +  generateColumnTypes(pParse, pTabList, pEList);
  1.1055 +}
  1.1056 +
  1.1057 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.1058 +/*
  1.1059 +** Name of the connection operator, used for error messages.
  1.1060 +*/
  1.1061 +static const char *selectOpName(int id){
  1.1062 +  char *z;
  1.1063 +  switch( id ){
  1.1064 +    case TK_ALL:       z = "UNION ALL";   break;
  1.1065 +    case TK_INTERSECT: z = "INTERSECT";   break;
  1.1066 +    case TK_EXCEPT:    z = "EXCEPT";      break;
  1.1067 +    default:           z = "UNION";       break;
  1.1068 +  }
  1.1069 +  return z;
  1.1070 +}
  1.1071 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1.1072 +
  1.1073 +/*
  1.1074 +** Forward declaration
  1.1075 +*/
  1.1076 +static int prepSelectStmt(Parse*, Select*);
  1.1077 +
  1.1078 +/*
  1.1079 +** Given a SELECT statement, generate a Table structure that describes
  1.1080 +** the result set of that SELECT.
  1.1081 +*/
  1.1082 +Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
  1.1083 +  Table *pTab;
  1.1084 +  int i, j;
  1.1085 +  ExprList *pEList;
  1.1086 +  Column *aCol, *pCol;
  1.1087 +  sqlite3 *db = pParse->db;
  1.1088 +
  1.1089 +  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  1.1090 +  if( prepSelectStmt(pParse, pSelect) ){
  1.1091 +    return 0;
  1.1092 +  }
  1.1093 +  if( sqlite3SelectResolve(pParse, pSelect, 0) ){
  1.1094 +    return 0;
  1.1095 +  }
  1.1096 +  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  1.1097 +  if( pTab==0 ){
  1.1098 +    return 0;
  1.1099 +  }
  1.1100 +  pTab->nRef = 1;
  1.1101 +  pTab->zName = zTabName ? sqlite3DbStrDup(db, zTabName) : 0;
  1.1102 +  pEList = pSelect->pEList;
  1.1103 +  pTab->nCol = pEList->nExpr;
  1.1104 +  assert( pTab->nCol>0 );
  1.1105 +  pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol);
  1.1106 +  for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
  1.1107 +    Expr *p, *pR;
  1.1108 +    char *zType;
  1.1109 +    char *zName;
  1.1110 +    int nName;
  1.1111 +    CollSeq *pColl;
  1.1112 +    int cnt;
  1.1113 +    NameContext sNC;
  1.1114 +    
  1.1115 +    /* Get an appropriate name for the column
  1.1116 +    */
  1.1117 +    p = pEList->a[i].pExpr;
  1.1118 +    assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
  1.1119 +    if( (zName = pEList->a[i].zName)!=0 ){
  1.1120 +      /* If the column contains an "AS <name>" phrase, use <name> as the name */
  1.1121 +      zName = sqlite3DbStrDup(db, zName);
  1.1122 +    }else if( p->op==TK_DOT 
  1.1123 +              && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
  1.1124 +      /* For columns of the from A.B use B as the name */
  1.1125 +      zName = sqlite3MPrintf(db, "%T", &pR->token);
  1.1126 +    }else if( p->span.z && p->span.z[0] ){
  1.1127 +      /* Use the original text of the column expression as its name */
  1.1128 +      zName = sqlite3MPrintf(db, "%T", &p->span);
  1.1129 +    }else{
  1.1130 +      /* If all else fails, make up a name */
  1.1131 +      zName = sqlite3MPrintf(db, "column%d", i+1);
  1.1132 +    }
  1.1133 +    if( !zName || db->mallocFailed ){
  1.1134 +      db->mallocFailed = 1;
  1.1135 +      sqlite3_free(zName);
  1.1136 +      sqlite3DeleteTable(pTab);
  1.1137 +      return 0;
  1.1138 +    }
  1.1139 +    sqlite3Dequote(zName);
  1.1140 +
  1.1141 +    /* Make sure the column name is unique.  If the name is not unique,
  1.1142 +    ** append a integer to the name so that it becomes unique.
  1.1143 +    */
  1.1144 +    nName = strlen(zName);
  1.1145 +    for(j=cnt=0; j<i; j++){
  1.1146 +      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  1.1147 +        zName[nName] = 0;
  1.1148 +        zName = sqlite3MPrintf(db, "%z:%d", zName, ++cnt);
  1.1149 +        j = -1;
  1.1150 +        if( zName==0 ) break;
  1.1151 +      }
  1.1152 +    }
  1.1153 +    pCol->zName = zName;
  1.1154 +
  1.1155 +    /* Get the typename, type affinity, and collating sequence for the
  1.1156 +    ** column.
  1.1157 +    */
  1.1158 +    memset(&sNC, 0, sizeof(sNC));
  1.1159 +    sNC.pSrcList = pSelect->pSrc;
  1.1160 +    zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  1.1161 +    pCol->zType = zType;
  1.1162 +    pCol->affinity = sqlite3ExprAffinity(p);
  1.1163 +    pColl = sqlite3ExprCollSeq(pParse, p);
  1.1164 +    if( pColl ){
  1.1165 +      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  1.1166 +    }
  1.1167 +  }
  1.1168 +  pTab->iPKey = -1;
  1.1169 +  return pTab;
  1.1170 +}
  1.1171 +
  1.1172 +/*
  1.1173 +** Prepare a SELECT statement for processing by doing the following
  1.1174 +** things:
  1.1175 +**
  1.1176 +**    (1)  Make sure VDBE cursor numbers have been assigned to every
  1.1177 +**         element of the FROM clause.
  1.1178 +**
  1.1179 +**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
  1.1180 +**         defines FROM clause.  When views appear in the FROM clause,
  1.1181 +**         fill pTabList->a[].pSelect with a copy of the SELECT statement
  1.1182 +**         that implements the view.  A copy is made of the view's SELECT
  1.1183 +**         statement so that we can freely modify or delete that statement
  1.1184 +**         without worrying about messing up the presistent representation
  1.1185 +**         of the view.
  1.1186 +**
  1.1187 +**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
  1.1188 +**         on joins and the ON and USING clause of joins.
  1.1189 +**
  1.1190 +**    (4)  Scan the list of columns in the result set (pEList) looking
  1.1191 +**         for instances of the "*" operator or the TABLE.* operator.
  1.1192 +**         If found, expand each "*" to be every column in every table
  1.1193 +**         and TABLE.* to be every column in TABLE.
  1.1194 +**
  1.1195 +** Return 0 on success.  If there are problems, leave an error message
  1.1196 +** in pParse and return non-zero.
  1.1197 +*/
  1.1198 +static int prepSelectStmt(Parse *pParse, Select *p){
  1.1199 +  int i, j, k, rc;
  1.1200 +  SrcList *pTabList;
  1.1201 +  ExprList *pEList;
  1.1202 +  struct SrcList_item *pFrom;
  1.1203 +  sqlite3 *db = pParse->db;
  1.1204 +
  1.1205 +  if( p==0 || p->pSrc==0 || db->mallocFailed ){
  1.1206 +    return 1;
  1.1207 +  }
  1.1208 +  pTabList = p->pSrc;
  1.1209 +  pEList = p->pEList;
  1.1210 +
  1.1211 +  /* Make sure cursor numbers have been assigned to all entries in
  1.1212 +  ** the FROM clause of the SELECT statement.
  1.1213 +  */
  1.1214 +  sqlite3SrcListAssignCursors(pParse, p->pSrc);
  1.1215 +
  1.1216 +  /* Look up every table named in the FROM clause of the select.  If
  1.1217 +  ** an entry of the FROM clause is a subquery instead of a table or view,
  1.1218 +  ** then create a transient table structure to describe the subquery.
  1.1219 +  */
  1.1220 +  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  1.1221 +    Table *pTab;
  1.1222 +    if( pFrom->pTab!=0 ){
  1.1223 +      /* This statement has already been prepared.  There is no need
  1.1224 +      ** to go further. */
  1.1225 +      assert( i==0 );
  1.1226 +      return 0;
  1.1227 +    }
  1.1228 +    if( pFrom->zName==0 ){
  1.1229 +#ifndef SQLITE_OMIT_SUBQUERY
  1.1230 +      /* A sub-query in the FROM clause of a SELECT */
  1.1231 +      assert( pFrom->pSelect!=0 );
  1.1232 +      if( pFrom->zAlias==0 ){
  1.1233 +        pFrom->zAlias =
  1.1234 +          sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pFrom->pSelect);
  1.1235 +      }
  1.1236 +      assert( pFrom->pTab==0 );
  1.1237 +      pFrom->pTab = pTab = 
  1.1238 +        sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
  1.1239 +      if( pTab==0 ){
  1.1240 +        return 1;
  1.1241 +      }
  1.1242 +      /* The isEphem flag indicates that the Table structure has been
  1.1243 +      ** dynamically allocated and may be freed at any time.  In other words,
  1.1244 +      ** pTab is not pointing to a persistent table structure that defines
  1.1245 +      ** part of the schema. */
  1.1246 +      pTab->isEphem = 1;
  1.1247 +#endif
  1.1248 +    }else{
  1.1249 +      /* An ordinary table or view name in the FROM clause */
  1.1250 +      assert( pFrom->pTab==0 );
  1.1251 +      pFrom->pTab = pTab = 
  1.1252 +        sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase);
  1.1253 +      if( pTab==0 ){
  1.1254 +        return 1;
  1.1255 +      }
  1.1256 +      pTab->nRef++;
  1.1257 +#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  1.1258 +      if( pTab->pSelect || IsVirtual(pTab) ){
  1.1259 +        /* We reach here if the named table is a really a view */
  1.1260 +        if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  1.1261 +          return 1;
  1.1262 +        }
  1.1263 +        /* If pFrom->pSelect!=0 it means we are dealing with a
  1.1264 +        ** view within a view.  The SELECT structure has already been
  1.1265 +        ** copied by the outer view so we can skip the copy step here
  1.1266 +        ** in the inner view.
  1.1267 +        */
  1.1268 +        if( pFrom->pSelect==0 ){
  1.1269 +          pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
  1.1270 +        }
  1.1271 +      }
  1.1272 +#endif
  1.1273 +    }
  1.1274 +  }
  1.1275 +
  1.1276 +  /* Process NATURAL keywords, and ON and USING clauses of joins.
  1.1277 +  */
  1.1278 +  if( sqliteProcessJoin(pParse, p) ) return 1;
  1.1279 +
  1.1280 +  /* For every "*" that occurs in the column list, insert the names of
  1.1281 +  ** all columns in all tables.  And for every TABLE.* insert the names
  1.1282 +  ** of all columns in TABLE.  The parser inserted a special expression
  1.1283 +  ** with the TK_ALL operator for each "*" that it found in the column list.
  1.1284 +  ** The following code just has to locate the TK_ALL expressions and expand
  1.1285 +  ** each one to the list of all columns in all tables.
  1.1286 +  **
  1.1287 +  ** The first loop just checks to see if there are any "*" operators
  1.1288 +  ** that need expanding.
  1.1289 +  */
  1.1290 +  for(k=0; k<pEList->nExpr; k++){
  1.1291 +    Expr *pE = pEList->a[k].pExpr;
  1.1292 +    if( pE->op==TK_ALL ) break;
  1.1293 +    if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
  1.1294 +         && pE->pLeft && pE->pLeft->op==TK_ID ) break;
  1.1295 +  }
  1.1296 +  rc = 0;
  1.1297 +  if( k<pEList->nExpr ){
  1.1298 +    /*
  1.1299 +    ** If we get here it means the result set contains one or more "*"
  1.1300 +    ** operators that need to be expanded.  Loop through each expression
  1.1301 +    ** in the result set and expand them one by one.
  1.1302 +    */
  1.1303 +    struct ExprList_item *a = pEList->a;
  1.1304 +    ExprList *pNew = 0;
  1.1305 +    int flags = pParse->db->flags;
  1.1306 +    int longNames = (flags & SQLITE_FullColNames)!=0 &&
  1.1307 +                      (flags & SQLITE_ShortColNames)==0;
  1.1308 +
  1.1309 +    for(k=0; k<pEList->nExpr; k++){
  1.1310 +      Expr *pE = a[k].pExpr;
  1.1311 +      if( pE->op!=TK_ALL &&
  1.1312 +           (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
  1.1313 +        /* This particular expression does not need to be expanded.
  1.1314 +        */
  1.1315 +        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
  1.1316 +        if( pNew ){
  1.1317 +          pNew->a[pNew->nExpr-1].zName = a[k].zName;
  1.1318 +        }else{
  1.1319 +          rc = 1;
  1.1320 +        }
  1.1321 +        a[k].pExpr = 0;
  1.1322 +        a[k].zName = 0;
  1.1323 +      }else{
  1.1324 +        /* This expression is a "*" or a "TABLE.*" and needs to be
  1.1325 +        ** expanded. */
  1.1326 +        int tableSeen = 0;      /* Set to 1 when TABLE matches */
  1.1327 +        char *zTName;            /* text of name of TABLE */
  1.1328 +        if( pE->op==TK_DOT && pE->pLeft ){
  1.1329 +          zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
  1.1330 +        }else{
  1.1331 +          zTName = 0;
  1.1332 +        }
  1.1333 +        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  1.1334 +          Table *pTab = pFrom->pTab;
  1.1335 +          char *zTabName = pFrom->zAlias;
  1.1336 +          if( zTabName==0 || zTabName[0]==0 ){ 
  1.1337 +            zTabName = pTab->zName;
  1.1338 +          }
  1.1339 +          if( zTName && (zTabName==0 || zTabName[0]==0 || 
  1.1340 +                 sqlite3StrICmp(zTName, zTabName)!=0) ){
  1.1341 +            continue;
  1.1342 +          }
  1.1343 +          tableSeen = 1;
  1.1344 +          for(j=0; j<pTab->nCol; j++){
  1.1345 +            Expr *pExpr, *pRight;
  1.1346 +            char *zName = pTab->aCol[j].zName;
  1.1347 +
  1.1348 +            /* If a column is marked as 'hidden' (currently only possible
  1.1349 +            ** for virtual tables), do not include it in the expanded
  1.1350 +            ** result-set list.
  1.1351 +            */
  1.1352 +            if( IsHiddenColumn(&pTab->aCol[j]) ){
  1.1353 +              assert(IsVirtual(pTab));
  1.1354 +              continue;
  1.1355 +            }
  1.1356 +
  1.1357 +            if( i>0 ){
  1.1358 +              struct SrcList_item *pLeft = &pTabList->a[i-1];
  1.1359 +              if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
  1.1360 +                        columnIndex(pLeft->pTab, zName)>=0 ){
  1.1361 +                /* In a NATURAL join, omit the join columns from the 
  1.1362 +                ** table on the right */
  1.1363 +                continue;
  1.1364 +              }
  1.1365 +              if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
  1.1366 +                /* In a join with a USING clause, omit columns in the
  1.1367 +                ** using clause from the table on the right. */
  1.1368 +                continue;
  1.1369 +              }
  1.1370 +            }
  1.1371 +            pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  1.1372 +            if( pRight==0 ) break;
  1.1373 +            setQuotedToken(pParse, &pRight->token, zName);
  1.1374 +            if( zTabName && (longNames || pTabList->nSrc>1) ){
  1.1375 +              Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  1.1376 +              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  1.1377 +              if( pExpr==0 ) break;
  1.1378 +              setQuotedToken(pParse, &pLeft->token, zTabName);
  1.1379 +              setToken(&pExpr->span, 
  1.1380 +                  sqlite3MPrintf(db, "%s.%s", zTabName, zName));
  1.1381 +              pExpr->span.dyn = 1;
  1.1382 +              pExpr->token.z = 0;
  1.1383 +              pExpr->token.n = 0;
  1.1384 +              pExpr->token.dyn = 0;
  1.1385 +            }else{
  1.1386 +              pExpr = pRight;
  1.1387 +              pExpr->span = pExpr->token;
  1.1388 +              pExpr->span.dyn = 0;
  1.1389 +            }
  1.1390 +            if( longNames ){
  1.1391 +              pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
  1.1392 +            }else{
  1.1393 +              pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
  1.1394 +            }
  1.1395 +          }
  1.1396 +        }
  1.1397 +        if( !tableSeen ){
  1.1398 +          if( zTName ){
  1.1399 +            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  1.1400 +          }else{
  1.1401 +            sqlite3ErrorMsg(pParse, "no tables specified");
  1.1402 +          }
  1.1403 +          rc = 1;
  1.1404 +        }
  1.1405 +        sqlite3_free(zTName);
  1.1406 +      }
  1.1407 +    }
  1.1408 +    sqlite3ExprListDelete(pEList);
  1.1409 +    p->pEList = pNew;
  1.1410 +  }
  1.1411 +  if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
  1.1412 +    sqlite3ErrorMsg(pParse, "too many columns in result set");
  1.1413 +    rc = SQLITE_ERROR;
  1.1414 +  }
  1.1415 +  if( db->mallocFailed ){
  1.1416 +    rc = SQLITE_NOMEM;
  1.1417 +  }
  1.1418 +  return rc;
  1.1419 +}
  1.1420 +
  1.1421 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.1422 +/*
  1.1423 +** This routine associates entries in an ORDER BY expression list with
  1.1424 +** columns in a result.  For each ORDER BY expression, the opcode of
  1.1425 +** the top-level node is changed to TK_COLUMN and the iColumn value of
  1.1426 +** the top-level node is filled in with column number and the iTable
  1.1427 +** value of the top-level node is filled with iTable parameter.
  1.1428 +**
  1.1429 +** If there are prior SELECT clauses, they are processed first.  A match
  1.1430 +** in an earlier SELECT takes precedence over a later SELECT.
  1.1431 +**
  1.1432 +** Any entry that does not match is flagged as an error.  The number
  1.1433 +** of errors is returned.
  1.1434 +*/
  1.1435 +static int matchOrderbyToColumn(
  1.1436 +  Parse *pParse,          /* A place to leave error messages */
  1.1437 +  Select *pSelect,        /* Match to result columns of this SELECT */
  1.1438 +  ExprList *pOrderBy,     /* The ORDER BY values to match against columns */
  1.1439 +  int iTable,             /* Insert this value in iTable */
  1.1440 +  int mustComplete        /* If TRUE all ORDER BYs must match */
  1.1441 +){
  1.1442 +  int nErr = 0;
  1.1443 +  int i, j;
  1.1444 +  ExprList *pEList;
  1.1445 +  sqlite3 *db = pParse->db;
  1.1446 +
  1.1447 +  if( pSelect==0 || pOrderBy==0 ) return 1;
  1.1448 +  if( mustComplete ){
  1.1449 +    for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
  1.1450 +  }
  1.1451 +  if( prepSelectStmt(pParse, pSelect) ){
  1.1452 +    return 1;
  1.1453 +  }
  1.1454 +  if( pSelect->pPrior ){
  1.1455 +    if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
  1.1456 +      return 1;
  1.1457 +    }
  1.1458 +  }
  1.1459 +  pEList = pSelect->pEList;
  1.1460 +  for(i=0; i<pOrderBy->nExpr; i++){
  1.1461 +    struct ExprList_item *pItem;
  1.1462 +    Expr *pE = pOrderBy->a[i].pExpr;
  1.1463 +    int iCol = -1;
  1.1464 +    char *zLabel;
  1.1465 +
  1.1466 +    if( pOrderBy->a[i].done ) continue;
  1.1467 +    if( sqlite3ExprIsInteger(pE, &iCol) ){
  1.1468 +      if( iCol<=0 || iCol>pEList->nExpr ){
  1.1469 +        sqlite3ErrorMsg(pParse,
  1.1470 +          "ORDER BY position %d should be between 1 and %d",
  1.1471 +          iCol, pEList->nExpr);
  1.1472 +        nErr++;
  1.1473 +        break;
  1.1474 +      }
  1.1475 +      if( !mustComplete ) continue;
  1.1476 +      iCol--;
  1.1477 +    }
  1.1478 +    if( iCol<0 && (zLabel = sqlite3NameFromToken(db, &pE->token))!=0 ){
  1.1479 +      for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){
  1.1480 +        char *zName;
  1.1481 +        int isMatch;
  1.1482 +        if( pItem->zName ){
  1.1483 +          zName = sqlite3DbStrDup(db, pItem->zName);
  1.1484 +        }else{
  1.1485 +          zName = sqlite3NameFromToken(db, &pItem->pExpr->token);
  1.1486 +        }
  1.1487 +        isMatch = zName && sqlite3StrICmp(zName, zLabel)==0;
  1.1488 +        sqlite3_free(zName);
  1.1489 +        if( isMatch ){
  1.1490 +          iCol = j;
  1.1491 +          break;
  1.1492 +        }
  1.1493 +      }
  1.1494 +      sqlite3_free(zLabel);
  1.1495 +    }
  1.1496 +    if( iCol>=0 ){
  1.1497 +      pE->op = TK_COLUMN;
  1.1498 +      pE->iColumn = iCol;
  1.1499 +      pE->iTable = iTable;
  1.1500 +      pE->iAgg = -1;
  1.1501 +      pOrderBy->a[i].done = 1;
  1.1502 +    }else if( mustComplete ){
  1.1503 +      sqlite3ErrorMsg(pParse,
  1.1504 +        "ORDER BY term number %d does not match any result column", i+1);
  1.1505 +      nErr++;
  1.1506 +      break;
  1.1507 +    }
  1.1508 +  }
  1.1509 +  return nErr;  
  1.1510 +}
  1.1511 +#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */
  1.1512 +
  1.1513 +/*
  1.1514 +** Get a VDBE for the given parser context.  Create a new one if necessary.
  1.1515 +** If an error occurs, return NULL and leave a message in pParse.
  1.1516 +*/
  1.1517 +Vdbe *sqlite3GetVdbe(Parse *pParse){
  1.1518 +  Vdbe *v = pParse->pVdbe;
  1.1519 +  if( v==0 ){
  1.1520 +    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  1.1521 +  }
  1.1522 +  return v;
  1.1523 +}
  1.1524 +
  1.1525 +
  1.1526 +/*
  1.1527 +** Compute the iLimit and iOffset fields of the SELECT based on the
  1.1528 +** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
  1.1529 +** that appear in the original SQL statement after the LIMIT and OFFSET
  1.1530 +** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
  1.1531 +** are the integer memory register numbers for counters used to compute 
  1.1532 +** the limit and offset.  If there is no limit and/or offset, then 
  1.1533 +** iLimit and iOffset are negative.
  1.1534 +**
  1.1535 +** This routine changes the values of iLimit and iOffset only if
  1.1536 +** a limit or offset is defined by pLimit and pOffset.  iLimit and
  1.1537 +** iOffset should have been preset to appropriate default values
  1.1538 +** (usually but not always -1) prior to calling this routine.
  1.1539 +** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  1.1540 +** redefined.  The UNION ALL operator uses this property to force
  1.1541 +** the reuse of the same limit and offset registers across multiple
  1.1542 +** SELECT statements.
  1.1543 +*/
  1.1544 +static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  1.1545 +  Vdbe *v = 0;
  1.1546 +  int iLimit = 0;
  1.1547 +  int iOffset;
  1.1548 +  int addr1, addr2;
  1.1549 +
  1.1550 +  /* 
  1.1551 +  ** "LIMIT -1" always shows all rows.  There is some
  1.1552 +  ** contraversy about what the correct behavior should be.
  1.1553 +  ** The current implementation interprets "LIMIT 0" to mean
  1.1554 +  ** no rows.
  1.1555 +  */
  1.1556 +  if( p->pLimit ){
  1.1557 +    p->iLimit = iLimit = pParse->nMem;
  1.1558 +    pParse->nMem += 2;
  1.1559 +    v = sqlite3GetVdbe(pParse);
  1.1560 +    if( v==0 ) return;
  1.1561 +    sqlite3ExprCode(pParse, p->pLimit);
  1.1562 +    sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
  1.1563 +    sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1);
  1.1564 +    VdbeComment((v, "# LIMIT counter"));
  1.1565 +    sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak);
  1.1566 +    sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0);
  1.1567 +  }
  1.1568 +  if( p->pOffset ){
  1.1569 +    p->iOffset = iOffset = pParse->nMem++;
  1.1570 +    v = sqlite3GetVdbe(pParse);
  1.1571 +    if( v==0 ) return;
  1.1572 +    sqlite3ExprCode(pParse, p->pOffset);
  1.1573 +    sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
  1.1574 +    sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0);
  1.1575 +    VdbeComment((v, "# OFFSET counter"));
  1.1576 +    addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0);
  1.1577 +    sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  1.1578 +    sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
  1.1579 +    sqlite3VdbeJumpHere(v, addr1);
  1.1580 +    if( p->pLimit ){
  1.1581 +      sqlite3VdbeAddOp(v, OP_Add, 0, 0);
  1.1582 +    }
  1.1583 +  }
  1.1584 +  if( p->pLimit ){
  1.1585 +    addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0);
  1.1586 +    sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
  1.1587 +    sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1);
  1.1588 +    addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  1.1589 +    sqlite3VdbeJumpHere(v, addr1);
  1.1590 +    sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1);
  1.1591 +    VdbeComment((v, "# LIMIT+OFFSET"));
  1.1592 +    sqlite3VdbeJumpHere(v, addr2);
  1.1593 +  }
  1.1594 +}
  1.1595 +
  1.1596 +/*
  1.1597 +** Allocate a virtual index to use for sorting.
  1.1598 +*/
  1.1599 +static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){
  1.1600 +  if( pOrderBy ){
  1.1601 +    int addr;
  1.1602 +    assert( pOrderBy->iECursor==0 );
  1.1603 +    pOrderBy->iECursor = pParse->nTab++;
  1.1604 +    addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral,
  1.1605 +                            pOrderBy->iECursor, pOrderBy->nExpr+1);
  1.1606 +    assert( p->addrOpenEphm[2] == -1 );
  1.1607 +    p->addrOpenEphm[2] = addr;
  1.1608 +  }
  1.1609 +}
  1.1610 +
  1.1611 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.1612 +/*
  1.1613 +** Return the appropriate collating sequence for the iCol-th column of
  1.1614 +** the result set for the compound-select statement "p".  Return NULL if
  1.1615 +** the column has no default collating sequence.
  1.1616 +**
  1.1617 +** The collating sequence for the compound select is taken from the
  1.1618 +** left-most term of the select that has a collating sequence.
  1.1619 +*/
  1.1620 +static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  1.1621 +  CollSeq *pRet;
  1.1622 +  if( p->pPrior ){
  1.1623 +    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  1.1624 +  }else{
  1.1625 +    pRet = 0;
  1.1626 +  }
  1.1627 +  if( pRet==0 ){
  1.1628 +    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  1.1629 +  }
  1.1630 +  return pRet;
  1.1631 +}
  1.1632 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1.1633 +
  1.1634 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.1635 +/*
  1.1636 +** This routine is called to process a query that is really the union
  1.1637 +** or intersection of two or more separate queries.
  1.1638 +**
  1.1639 +** "p" points to the right-most of the two queries.  the query on the
  1.1640 +** left is p->pPrior.  The left query could also be a compound query
  1.1641 +** in which case this routine will be called recursively. 
  1.1642 +**
  1.1643 +** The results of the total query are to be written into a destination
  1.1644 +** of type eDest with parameter iParm.
  1.1645 +**
  1.1646 +** Example 1:  Consider a three-way compound SQL statement.
  1.1647 +**
  1.1648 +**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  1.1649 +**
  1.1650 +** This statement is parsed up as follows:
  1.1651 +**
  1.1652 +**     SELECT c FROM t3
  1.1653 +**      |
  1.1654 +**      `----->  SELECT b FROM t2
  1.1655 +**                |
  1.1656 +**                `------>  SELECT a FROM t1
  1.1657 +**
  1.1658 +** The arrows in the diagram above represent the Select.pPrior pointer.
  1.1659 +** So if this routine is called with p equal to the t3 query, then
  1.1660 +** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
  1.1661 +**
  1.1662 +** Notice that because of the way SQLite parses compound SELECTs, the
  1.1663 +** individual selects always group from left to right.
  1.1664 +*/
  1.1665 +static int multiSelect(
  1.1666 +  Parse *pParse,        /* Parsing context */
  1.1667 +  Select *p,            /* The right-most of SELECTs to be coded */
  1.1668 +  int eDest,            /* \___  Store query results as specified */
  1.1669 +  int iParm,            /* /     by these two parameters.         */
  1.1670 +  char *aff             /* If eDest is SRT_Union, the affinity string */
  1.1671 +){
  1.1672 +  int rc = SQLITE_OK;   /* Success code from a subroutine */
  1.1673 +  Select *pPrior;       /* Another SELECT immediately to our left */
  1.1674 +  Vdbe *v;              /* Generate code to this VDBE */
  1.1675 +  int nCol;             /* Number of columns in the result set */
  1.1676 +  ExprList *pOrderBy;   /* The ORDER BY clause on p */
  1.1677 +  int aSetP2[2];        /* Set P2 value of these op to number of columns */
  1.1678 +  int nSetP2 = 0;       /* Number of slots in aSetP2[] used */
  1.1679 +
  1.1680 +  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
  1.1681 +  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  1.1682 +  */
  1.1683 +  if( p==0 || p->pPrior==0 ){
  1.1684 +    rc = 1;
  1.1685 +    goto multi_select_end;
  1.1686 +  }
  1.1687 +  pPrior = p->pPrior;
  1.1688 +  assert( pPrior->pRightmost!=pPrior );
  1.1689 +  assert( pPrior->pRightmost==p->pRightmost );
  1.1690 +  if( pPrior->pOrderBy ){
  1.1691 +    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  1.1692 +      selectOpName(p->op));
  1.1693 +    rc = 1;
  1.1694 +    goto multi_select_end;
  1.1695 +  }
  1.1696 +  if( pPrior->pLimit ){
  1.1697 +    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  1.1698 +      selectOpName(p->op));
  1.1699 +    rc = 1;
  1.1700 +    goto multi_select_end;
  1.1701 +  }
  1.1702 +
  1.1703 +  /* Make sure we have a valid query engine.  If not, create a new one.
  1.1704 +  */
  1.1705 +  v = sqlite3GetVdbe(pParse);
  1.1706 +  if( v==0 ){
  1.1707 +    rc = 1;
  1.1708 +    goto multi_select_end;
  1.1709 +  }
  1.1710 +
  1.1711 +  /* Create the destination temporary table if necessary
  1.1712 +  */
  1.1713 +  if( eDest==SRT_EphemTab ){
  1.1714 +    assert( p->pEList );
  1.1715 +    assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
  1.1716 +    aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0);
  1.1717 +    eDest = SRT_Table;
  1.1718 +  }
  1.1719 +
  1.1720 +  /* Generate code for the left and right SELECT statements.
  1.1721 +  */
  1.1722 +  pOrderBy = p->pOrderBy;
  1.1723 +  switch( p->op ){
  1.1724 +    case TK_ALL: {
  1.1725 +      if( pOrderBy==0 ){
  1.1726 +        int addr = 0;
  1.1727 +        assert( !pPrior->pLimit );
  1.1728 +        pPrior->pLimit = p->pLimit;
  1.1729 +        pPrior->pOffset = p->pOffset;
  1.1730 +        rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
  1.1731 +        p->pLimit = 0;
  1.1732 +        p->pOffset = 0;
  1.1733 +        if( rc ){
  1.1734 +          goto multi_select_end;
  1.1735 +        }
  1.1736 +        p->pPrior = 0;
  1.1737 +        p->iLimit = pPrior->iLimit;
  1.1738 +        p->iOffset = pPrior->iOffset;
  1.1739 +        if( p->iLimit>=0 ){
  1.1740 +          addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0);
  1.1741 +          VdbeComment((v, "# Jump ahead if LIMIT reached"));
  1.1742 +        }
  1.1743 +        rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
  1.1744 +        p->pPrior = pPrior;
  1.1745 +        if( rc ){
  1.1746 +          goto multi_select_end;
  1.1747 +        }
  1.1748 +        if( addr ){
  1.1749 +          sqlite3VdbeJumpHere(v, addr);
  1.1750 +        }
  1.1751 +        break;
  1.1752 +      }
  1.1753 +      /* For UNION ALL ... ORDER BY fall through to the next case */
  1.1754 +    }
  1.1755 +    case TK_EXCEPT:
  1.1756 +    case TK_UNION: {
  1.1757 +      int unionTab;    /* Cursor number of the temporary table holding result */
  1.1758 +      int op = 0;      /* One of the SRT_ operations to apply to self */
  1.1759 +      int priorOp;     /* The SRT_ operation to apply to prior selects */
  1.1760 +      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  1.1761 +      int addr;
  1.1762 +
  1.1763 +      priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
  1.1764 +      if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){
  1.1765 +        /* We can reuse a temporary table generated by a SELECT to our
  1.1766 +        ** right.
  1.1767 +        */
  1.1768 +        unionTab = iParm;
  1.1769 +      }else{
  1.1770 +        /* We will need to create our own temporary table to hold the
  1.1771 +        ** intermediate results.
  1.1772 +        */
  1.1773 +        unionTab = pParse->nTab++;
  1.1774 +        if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){
  1.1775 +          rc = 1;
  1.1776 +          goto multi_select_end;
  1.1777 +        }
  1.1778 +        addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0);
  1.1779 +        if( priorOp==SRT_Table ){
  1.1780 +          assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) );
  1.1781 +          aSetP2[nSetP2++] = addr;
  1.1782 +        }else{
  1.1783 +          assert( p->addrOpenEphm[0] == -1 );
  1.1784 +          p->addrOpenEphm[0] = addr;
  1.1785 +          p->pRightmost->usesEphm = 1;
  1.1786 +        }
  1.1787 +        createSortingIndex(pParse, p, pOrderBy);
  1.1788 +        assert( p->pEList );
  1.1789 +      }
  1.1790 +
  1.1791 +      /* Code the SELECT statements to our left
  1.1792 +      */
  1.1793 +      assert( !pPrior->pOrderBy );
  1.1794 +      rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
  1.1795 +      if( rc ){
  1.1796 +        goto multi_select_end;
  1.1797 +      }
  1.1798 +
  1.1799 +      /* Code the current SELECT statement
  1.1800 +      */
  1.1801 +      switch( p->op ){
  1.1802 +         case TK_EXCEPT:  op = SRT_Except;   break;
  1.1803 +         case TK_UNION:   op = SRT_Union;    break;
  1.1804 +         case TK_ALL:     op = SRT_Table;    break;
  1.1805 +      }
  1.1806 +      p->pPrior = 0;
  1.1807 +      p->pOrderBy = 0;
  1.1808 +      p->disallowOrderBy = pOrderBy!=0;
  1.1809 +      pLimit = p->pLimit;
  1.1810 +      p->pLimit = 0;
  1.1811 +      pOffset = p->pOffset;
  1.1812 +      p->pOffset = 0;
  1.1813 +      rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
  1.1814 +      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  1.1815 +      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  1.1816 +      sqlite3ExprListDelete(p->pOrderBy);
  1.1817 +      p->pPrior = pPrior;
  1.1818 +      p->pOrderBy = pOrderBy;
  1.1819 +      sqlite3ExprDelete(p->pLimit);
  1.1820 +      p->pLimit = pLimit;
  1.1821 +      p->pOffset = pOffset;
  1.1822 +      p->iLimit = -1;
  1.1823 +      p->iOffset = -1;
  1.1824 +      if( rc ){
  1.1825 +        goto multi_select_end;
  1.1826 +      }
  1.1827 +
  1.1828 +
  1.1829 +      /* Convert the data in the temporary table into whatever form
  1.1830 +      ** it is that we currently need.
  1.1831 +      */      
  1.1832 +      if( eDest!=priorOp || unionTab!=iParm ){
  1.1833 +        int iCont, iBreak, iStart;
  1.1834 +        assert( p->pEList );
  1.1835 +        if( eDest==SRT_Callback ){
  1.1836 +          Select *pFirst = p;
  1.1837 +          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  1.1838 +          generateColumnNames(pParse, 0, pFirst->pEList);
  1.1839 +        }
  1.1840 +        iBreak = sqlite3VdbeMakeLabel(v);
  1.1841 +        iCont = sqlite3VdbeMakeLabel(v);
  1.1842 +        computeLimitRegisters(pParse, p, iBreak);
  1.1843 +        sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak);
  1.1844 +        iStart = sqlite3VdbeCurrentAddr(v);
  1.1845 +        rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  1.1846 +                             pOrderBy, -1, eDest, iParm, 
  1.1847 +                             iCont, iBreak, 0);
  1.1848 +        if( rc ){
  1.1849 +          rc = 1;
  1.1850 +          goto multi_select_end;
  1.1851 +        }
  1.1852 +        sqlite3VdbeResolveLabel(v, iCont);
  1.1853 +        sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart);
  1.1854 +        sqlite3VdbeResolveLabel(v, iBreak);
  1.1855 +        sqlite3VdbeAddOp(v, OP_Close, unionTab, 0);
  1.1856 +      }
  1.1857 +      break;
  1.1858 +    }
  1.1859 +    case TK_INTERSECT: {
  1.1860 +      int tab1, tab2;
  1.1861 +      int iCont, iBreak, iStart;
  1.1862 +      Expr *pLimit, *pOffset;
  1.1863 +      int addr;
  1.1864 +
  1.1865 +      /* INTERSECT is different from the others since it requires
  1.1866 +      ** two temporary tables.  Hence it has its own case.  Begin
  1.1867 +      ** by allocating the tables we will need.
  1.1868 +      */
  1.1869 +      tab1 = pParse->nTab++;
  1.1870 +      tab2 = pParse->nTab++;
  1.1871 +      if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){
  1.1872 +        rc = 1;
  1.1873 +        goto multi_select_end;
  1.1874 +      }
  1.1875 +      createSortingIndex(pParse, p, pOrderBy);
  1.1876 +
  1.1877 +      addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0);
  1.1878 +      assert( p->addrOpenEphm[0] == -1 );
  1.1879 +      p->addrOpenEphm[0] = addr;
  1.1880 +      p->pRightmost->usesEphm = 1;
  1.1881 +      assert( p->pEList );
  1.1882 +
  1.1883 +      /* Code the SELECTs to our left into temporary table "tab1".
  1.1884 +      */
  1.1885 +      rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
  1.1886 +      if( rc ){
  1.1887 +        goto multi_select_end;
  1.1888 +      }
  1.1889 +
  1.1890 +      /* Code the current SELECT into temporary table "tab2"
  1.1891 +      */
  1.1892 +      addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0);
  1.1893 +      assert( p->addrOpenEphm[1] == -1 );
  1.1894 +      p->addrOpenEphm[1] = addr;
  1.1895 +      p->pPrior = 0;
  1.1896 +      pLimit = p->pLimit;
  1.1897 +      p->pLimit = 0;
  1.1898 +      pOffset = p->pOffset;
  1.1899 +      p->pOffset = 0;
  1.1900 +      rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
  1.1901 +      p->pPrior = pPrior;
  1.1902 +      sqlite3ExprDelete(p->pLimit);
  1.1903 +      p->pLimit = pLimit;
  1.1904 +      p->pOffset = pOffset;
  1.1905 +      if( rc ){
  1.1906 +        goto multi_select_end;
  1.1907 +      }
  1.1908 +
  1.1909 +      /* Generate code to take the intersection of the two temporary
  1.1910 +      ** tables.
  1.1911 +      */
  1.1912 +      assert( p->pEList );
  1.1913 +      if( eDest==SRT_Callback ){
  1.1914 +        Select *pFirst = p;
  1.1915 +        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  1.1916 +        generateColumnNames(pParse, 0, pFirst->pEList);
  1.1917 +      }
  1.1918 +      iBreak = sqlite3VdbeMakeLabel(v);
  1.1919 +      iCont = sqlite3VdbeMakeLabel(v);
  1.1920 +      computeLimitRegisters(pParse, p, iBreak);
  1.1921 +      sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak);
  1.1922 +      iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0);
  1.1923 +      sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont);
  1.1924 +      rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  1.1925 +                             pOrderBy, -1, eDest, iParm, 
  1.1926 +                             iCont, iBreak, 0);
  1.1927 +      if( rc ){
  1.1928 +        rc = 1;
  1.1929 +        goto multi_select_end;
  1.1930 +      }
  1.1931 +      sqlite3VdbeResolveLabel(v, iCont);
  1.1932 +      sqlite3VdbeAddOp(v, OP_Next, tab1, iStart);
  1.1933 +      sqlite3VdbeResolveLabel(v, iBreak);
  1.1934 +      sqlite3VdbeAddOp(v, OP_Close, tab2, 0);
  1.1935 +      sqlite3VdbeAddOp(v, OP_Close, tab1, 0);
  1.1936 +      break;
  1.1937 +    }
  1.1938 +  }
  1.1939 +
  1.1940 +  /* Make sure all SELECTs in the statement have the same number of elements
  1.1941 +  ** in their result sets.
  1.1942 +  */
  1.1943 +  assert( p->pEList && pPrior->pEList );
  1.1944 +  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  1.1945 +    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  1.1946 +      " do not have the same number of result columns", selectOpName(p->op));
  1.1947 +    rc = 1;
  1.1948 +    goto multi_select_end;
  1.1949 +  }
  1.1950 +
  1.1951 +  /* Set the number of columns in temporary tables
  1.1952 +  */
  1.1953 +  nCol = p->pEList->nExpr;
  1.1954 +  while( nSetP2 ){
  1.1955 +    sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol);
  1.1956 +  }
  1.1957 +
  1.1958 +  /* Compute collating sequences used by either the ORDER BY clause or
  1.1959 +  ** by any temporary tables needed to implement the compound select.
  1.1960 +  ** Attach the KeyInfo structure to all temporary tables.  Invoke the
  1.1961 +  ** ORDER BY processing if there is an ORDER BY clause.
  1.1962 +  **
  1.1963 +  ** This section is run by the right-most SELECT statement only.
  1.1964 +  ** SELECT statements to the left always skip this part.  The right-most
  1.1965 +  ** SELECT might also skip this part if it has no ORDER BY clause and
  1.1966 +  ** no temp tables are required.
  1.1967 +  */
  1.1968 +  if( pOrderBy || p->usesEphm ){
  1.1969 +    int i;                        /* Loop counter */
  1.1970 +    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
  1.1971 +    Select *pLoop;                /* For looping through SELECT statements */
  1.1972 +    int nKeyCol;                  /* Number of entries in pKeyInfo->aCol[] */
  1.1973 +    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
  1.1974 +    CollSeq **aCopy;              /* A copy of pKeyInfo->aColl[] */
  1.1975 +
  1.1976 +    assert( p->pRightmost==p );
  1.1977 +    nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0);
  1.1978 +    pKeyInfo = sqlite3DbMallocZero(pParse->db,
  1.1979 +                       sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1));
  1.1980 +    if( !pKeyInfo ){
  1.1981 +      rc = SQLITE_NOMEM;
  1.1982 +      goto multi_select_end;
  1.1983 +    }
  1.1984 +
  1.1985 +    pKeyInfo->enc = ENC(pParse->db);
  1.1986 +    pKeyInfo->nField = nCol;
  1.1987 +
  1.1988 +    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  1.1989 +      *apColl = multiSelectCollSeq(pParse, p, i);
  1.1990 +      if( 0==*apColl ){
  1.1991 +        *apColl = pParse->db->pDfltColl;
  1.1992 +      }
  1.1993 +    }
  1.1994 +
  1.1995 +    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  1.1996 +      for(i=0; i<2; i++){
  1.1997 +        int addr = pLoop->addrOpenEphm[i];
  1.1998 +        if( addr<0 ){
  1.1999 +          /* If [0] is unused then [1] is also unused.  So we can
  1.2000 +          ** always safely abort as soon as the first unused slot is found */
  1.2001 +          assert( pLoop->addrOpenEphm[1]<0 );
  1.2002 +          break;
  1.2003 +        }
  1.2004 +        sqlite3VdbeChangeP2(v, addr, nCol);
  1.2005 +        sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO);
  1.2006 +        pLoop->addrOpenEphm[i] = -1;
  1.2007 +      }
  1.2008 +    }
  1.2009 +
  1.2010 +    if( pOrderBy ){
  1.2011 +      struct ExprList_item *pOTerm = pOrderBy->a;
  1.2012 +      int nOrderByExpr = pOrderBy->nExpr;
  1.2013 +      int addr;
  1.2014 +      u8 *pSortOrder;
  1.2015 +
  1.2016 +      /* Reuse the same pKeyInfo for the ORDER BY as was used above for
  1.2017 +      ** the compound select statements.  Except we have to change out the
  1.2018 +      ** pKeyInfo->aColl[] values.  Some of the aColl[] values will be
  1.2019 +      ** reused when constructing the pKeyInfo for the ORDER BY, so make
  1.2020 +      ** a copy.  Sufficient space to hold both the nCol entries for
  1.2021 +      ** the compound select and the nOrderbyExpr entries for the ORDER BY
  1.2022 +      ** was allocated above.  But we need to move the compound select
  1.2023 +      ** entries out of the way before constructing the ORDER BY entries.
  1.2024 +      ** Move the compound select entries into aCopy[] where they can be
  1.2025 +      ** accessed and reused when constructing the ORDER BY entries.
  1.2026 +      ** Because nCol might be greater than or less than nOrderByExpr
  1.2027 +      ** we have to use memmove() when doing the copy.
  1.2028 +      */
  1.2029 +      aCopy = &pKeyInfo->aColl[nOrderByExpr];
  1.2030 +      pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol];
  1.2031 +      memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*));
  1.2032 +
  1.2033 +      apColl = pKeyInfo->aColl;
  1.2034 +      for(i=0; i<nOrderByExpr; i++, pOTerm++, apColl++, pSortOrder++){
  1.2035 +        Expr *pExpr = pOTerm->pExpr;
  1.2036 +        if( (pExpr->flags & EP_ExpCollate) ){
  1.2037 +          assert( pExpr->pColl!=0 );
  1.2038 +          *apColl = pExpr->pColl;
  1.2039 +        }else{
  1.2040 +          *apColl = aCopy[pExpr->iColumn];
  1.2041 +        }
  1.2042 +        *pSortOrder = pOTerm->sortOrder;
  1.2043 +      }
  1.2044 +      assert( p->pRightmost==p );
  1.2045 +      assert( p->addrOpenEphm[2]>=0 );
  1.2046 +      addr = p->addrOpenEphm[2];
  1.2047 +      sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2);
  1.2048 +      pKeyInfo->nField = nOrderByExpr;
  1.2049 +      sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  1.2050 +      pKeyInfo = 0;
  1.2051 +      generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
  1.2052 +    }
  1.2053 +
  1.2054 +    sqlite3_free(pKeyInfo);
  1.2055 +  }
  1.2056 +
  1.2057 +multi_select_end:
  1.2058 +  return rc;
  1.2059 +}
  1.2060 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1.2061 +
  1.2062 +#ifndef SQLITE_OMIT_VIEW
  1.2063 +/* Forward Declarations */
  1.2064 +static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  1.2065 +static void substSelect(sqlite3*, Select *, int, ExprList *);
  1.2066 +
  1.2067 +/*
  1.2068 +** Scan through the expression pExpr.  Replace every reference to
  1.2069 +** a column in table number iTable with a copy of the iColumn-th
  1.2070 +** entry in pEList.  (But leave references to the ROWID column 
  1.2071 +** unchanged.)
  1.2072 +**
  1.2073 +** This routine is part of the flattening procedure.  A subquery
  1.2074 +** whose result set is defined by pEList appears as entry in the
  1.2075 +** FROM clause of a SELECT such that the VDBE cursor assigned to that
  1.2076 +** FORM clause entry is iTable.  This routine make the necessary 
  1.2077 +** changes to pExpr so that it refers directly to the source table
  1.2078 +** of the subquery rather the result set of the subquery.
  1.2079 +*/
  1.2080 +static void substExpr(
  1.2081 +  sqlite3 *db,        /* Report malloc errors to this connection */
  1.2082 +  Expr *pExpr,        /* Expr in which substitution occurs */
  1.2083 +  int iTable,         /* Table to be substituted */
  1.2084 +  ExprList *pEList    /* Substitute expressions */
  1.2085 +){
  1.2086 +  if( pExpr==0 ) return;
  1.2087 +  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  1.2088 +    if( pExpr->iColumn<0 ){
  1.2089 +      pExpr->op = TK_NULL;
  1.2090 +    }else{
  1.2091 +      Expr *pNew;
  1.2092 +      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  1.2093 +      assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
  1.2094 +      pNew = pEList->a[pExpr->iColumn].pExpr;
  1.2095 +      assert( pNew!=0 );
  1.2096 +      pExpr->op = pNew->op;
  1.2097 +      assert( pExpr->pLeft==0 );
  1.2098 +      pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
  1.2099 +      assert( pExpr->pRight==0 );
  1.2100 +      pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
  1.2101 +      assert( pExpr->pList==0 );
  1.2102 +      pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
  1.2103 +      pExpr->iTable = pNew->iTable;
  1.2104 +      pExpr->pTab = pNew->pTab;
  1.2105 +      pExpr->iColumn = pNew->iColumn;
  1.2106 +      pExpr->iAgg = pNew->iAgg;
  1.2107 +      sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
  1.2108 +      sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
  1.2109 +      pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
  1.2110 +      pExpr->flags = pNew->flags;
  1.2111 +    }
  1.2112 +  }else{
  1.2113 +    substExpr(db, pExpr->pLeft, iTable, pEList);
  1.2114 +    substExpr(db, pExpr->pRight, iTable, pEList);
  1.2115 +    substSelect(db, pExpr->pSelect, iTable, pEList);
  1.2116 +    substExprList(db, pExpr->pList, iTable, pEList);
  1.2117 +  }
  1.2118 +}
  1.2119 +static void substExprList(
  1.2120 +  sqlite3 *db,         /* Report malloc errors here */
  1.2121 +  ExprList *pList,     /* List to scan and in which to make substitutes */
  1.2122 +  int iTable,          /* Table to be substituted */
  1.2123 +  ExprList *pEList     /* Substitute values */
  1.2124 +){
  1.2125 +  int i;
  1.2126 +  if( pList==0 ) return;
  1.2127 +  for(i=0; i<pList->nExpr; i++){
  1.2128 +    substExpr(db, pList->a[i].pExpr, iTable, pEList);
  1.2129 +  }
  1.2130 +}
  1.2131 +static void substSelect(
  1.2132 +  sqlite3 *db,         /* Report malloc errors here */
  1.2133 +  Select *p,           /* SELECT statement in which to make substitutions */
  1.2134 +  int iTable,          /* Table to be replaced */
  1.2135 +  ExprList *pEList     /* Substitute values */
  1.2136 +){
  1.2137 +  if( !p ) return;
  1.2138 +  substExprList(db, p->pEList, iTable, pEList);
  1.2139 +  substExprList(db, p->pGroupBy, iTable, pEList);
  1.2140 +  substExprList(db, p->pOrderBy, iTable, pEList);
  1.2141 +  substExpr(db, p->pHaving, iTable, pEList);
  1.2142 +  substExpr(db, p->pWhere, iTable, pEList);
  1.2143 +  substSelect(db, p->pPrior, iTable, pEList);
  1.2144 +}
  1.2145 +#endif /* !defined(SQLITE_OMIT_VIEW) */
  1.2146 +
  1.2147 +#ifndef SQLITE_OMIT_VIEW
  1.2148 +/*
  1.2149 +** This routine attempts to flatten subqueries in order to speed
  1.2150 +** execution.  It returns 1 if it makes changes and 0 if no flattening
  1.2151 +** occurs.
  1.2152 +**
  1.2153 +** To understand the concept of flattening, consider the following
  1.2154 +** query:
  1.2155 +**
  1.2156 +**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  1.2157 +**
  1.2158 +** The default way of implementing this query is to execute the
  1.2159 +** subquery first and store the results in a temporary table, then
  1.2160 +** run the outer query on that temporary table.  This requires two
  1.2161 +** passes over the data.  Furthermore, because the temporary table
  1.2162 +** has no indices, the WHERE clause on the outer query cannot be
  1.2163 +** optimized.
  1.2164 +**
  1.2165 +** This routine attempts to rewrite queries such as the above into
  1.2166 +** a single flat select, like this:
  1.2167 +**
  1.2168 +**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  1.2169 +**
  1.2170 +** The code generated for this simpification gives the same result
  1.2171 +** but only has to scan the data once.  And because indices might 
  1.2172 +** exist on the table t1, a complete scan of the data might be
  1.2173 +** avoided.
  1.2174 +**
  1.2175 +** Flattening is only attempted if all of the following are true:
  1.2176 +**
  1.2177 +**   (1)  The subquery and the outer query do not both use aggregates.
  1.2178 +**
  1.2179 +**   (2)  The subquery is not an aggregate or the outer query is not a join.
  1.2180 +**
  1.2181 +**   (3)  The subquery is not the right operand of a left outer join, or
  1.2182 +**        the subquery is not itself a join.  (Ticket #306)
  1.2183 +**
  1.2184 +**   (4)  The subquery is not DISTINCT or the outer query is not a join.
  1.2185 +**
  1.2186 +**   (5)  The subquery is not DISTINCT or the outer query does not use
  1.2187 +**        aggregates.
  1.2188 +**
  1.2189 +**   (6)  The subquery does not use aggregates or the outer query is not
  1.2190 +**        DISTINCT.
  1.2191 +**
  1.2192 +**   (7)  The subquery has a FROM clause.
  1.2193 +**
  1.2194 +**   (8)  The subquery does not use LIMIT or the outer query is not a join.
  1.2195 +**
  1.2196 +**   (9)  The subquery does not use LIMIT or the outer query does not use
  1.2197 +**        aggregates.
  1.2198 +**
  1.2199 +**  (10)  The subquery does not use aggregates or the outer query does not
  1.2200 +**        use LIMIT.
  1.2201 +**
  1.2202 +**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
  1.2203 +**
  1.2204 +**  (12)  The subquery is not the right term of a LEFT OUTER JOIN or the
  1.2205 +**        subquery has no WHERE clause.  (added by ticket #350)
  1.2206 +**
  1.2207 +**  (13)  The subquery and outer query do not both use LIMIT
  1.2208 +**
  1.2209 +**  (14)  The subquery does not use OFFSET
  1.2210 +**
  1.2211 +**  (15)  The outer query is not part of a compound select or the
  1.2212 +**        subquery does not have both an ORDER BY and a LIMIT clause.
  1.2213 +**        (See ticket #2339)
  1.2214 +**
  1.2215 +** In this routine, the "p" parameter is a pointer to the outer query.
  1.2216 +** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
  1.2217 +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  1.2218 +**
  1.2219 +** If flattening is not attempted, this routine is a no-op and returns 0.
  1.2220 +** If flattening is attempted this routine returns 1.
  1.2221 +**
  1.2222 +** All of the expression analysis must occur on both the outer query and
  1.2223 +** the subquery before this routine runs.
  1.2224 +*/
  1.2225 +static int flattenSubquery(
  1.2226 +  sqlite3 *db,         /* Database connection */
  1.2227 +  Select *p,           /* The parent or outer SELECT statement */
  1.2228 +  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
  1.2229 +  int isAgg,           /* True if outer SELECT uses aggregate functions */
  1.2230 +  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
  1.2231 +){
  1.2232 +  Select *pSub;       /* The inner query or "subquery" */
  1.2233 +  SrcList *pSrc;      /* The FROM clause of the outer query */
  1.2234 +  SrcList *pSubSrc;   /* The FROM clause of the subquery */
  1.2235 +  ExprList *pList;    /* The result set of the outer query */
  1.2236 +  int iParent;        /* VDBE cursor number of the pSub result set temp table */
  1.2237 +  int i;              /* Loop counter */
  1.2238 +  Expr *pWhere;                    /* The WHERE clause */
  1.2239 +  struct SrcList_item *pSubitem;   /* The subquery */
  1.2240 +
  1.2241 +  /* Check to see if flattening is permitted.  Return 0 if not.
  1.2242 +  */
  1.2243 +  if( p==0 ) return 0;
  1.2244 +  pSrc = p->pSrc;
  1.2245 +  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  1.2246 +  pSubitem = &pSrc->a[iFrom];
  1.2247 +  pSub = pSubitem->pSelect;
  1.2248 +  assert( pSub!=0 );
  1.2249 +  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
  1.2250 +  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
  1.2251 +  pSubSrc = pSub->pSrc;
  1.2252 +  assert( pSubSrc );
  1.2253 +  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  1.2254 +  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  1.2255 +  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
  1.2256 +  ** became arbitrary expressions, we were forced to add restrictions (13)
  1.2257 +  ** and (14). */
  1.2258 +  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
  1.2259 +  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
  1.2260 +  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
  1.2261 +    return 0;                                            /* Restriction (15) */
  1.2262 +  }
  1.2263 +  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
  1.2264 +  if( (pSub->isDistinct || pSub->pLimit) 
  1.2265 +         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
  1.2266 +     return 0;       
  1.2267 +  }
  1.2268 +  if( p->isDistinct && subqueryIsAgg ) return 0;         /* Restriction (6)  */
  1.2269 +  if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){
  1.2270 +     return 0;                                           /* Restriction (11) */
  1.2271 +  }
  1.2272 +
  1.2273 +  /* Restriction 3:  If the subquery is a join, make sure the subquery is 
  1.2274 +  ** not used as the right operand of an outer join.  Examples of why this
  1.2275 +  ** is not allowed:
  1.2276 +  **
  1.2277 +  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
  1.2278 +  **
  1.2279 +  ** If we flatten the above, we would get
  1.2280 +  **
  1.2281 +  **         (t1 LEFT OUTER JOIN t2) JOIN t3
  1.2282 +  **
  1.2283 +  ** which is not at all the same thing.
  1.2284 +  */
  1.2285 +  if( pSubSrc->nSrc>1 && (pSubitem->jointype & JT_OUTER)!=0 ){
  1.2286 +    return 0;
  1.2287 +  }
  1.2288 +
  1.2289 +  /* Restriction 12:  If the subquery is the right operand of a left outer
  1.2290 +  ** join, make sure the subquery has no WHERE clause.
  1.2291 +  ** An examples of why this is not allowed:
  1.2292 +  **
  1.2293 +  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  1.2294 +  **
  1.2295 +  ** If we flatten the above, we would get
  1.2296 +  **
  1.2297 +  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  1.2298 +  **
  1.2299 +  ** But the t2.x>0 test will always fail on a NULL row of t2, which
  1.2300 +  ** effectively converts the OUTER JOIN into an INNER JOIN.
  1.2301 +  */
  1.2302 +  if( (pSubitem->jointype & JT_OUTER)!=0 && pSub->pWhere!=0 ){
  1.2303 +    return 0;
  1.2304 +  }
  1.2305 +
  1.2306 +  /* If we reach this point, it means flattening is permitted for the
  1.2307 +  ** iFrom-th entry of the FROM clause in the outer query.
  1.2308 +  */
  1.2309 +
  1.2310 +  /* Move all of the FROM elements of the subquery into the
  1.2311 +  ** the FROM clause of the outer query.  Before doing this, remember
  1.2312 +  ** the cursor number for the original outer query FROM element in
  1.2313 +  ** iParent.  The iParent cursor will never be used.  Subsequent code
  1.2314 +  ** will scan expressions looking for iParent references and replace
  1.2315 +  ** those references with expressions that resolve to the subquery FROM
  1.2316 +  ** elements we are now copying in.
  1.2317 +  */
  1.2318 +  iParent = pSubitem->iCursor;
  1.2319 +  {
  1.2320 +    int nSubSrc = pSubSrc->nSrc;
  1.2321 +    int jointype = pSubitem->jointype;
  1.2322 +
  1.2323 +    sqlite3DeleteTable(pSubitem->pTab);
  1.2324 +    sqlite3_free(pSubitem->zDatabase);
  1.2325 +    sqlite3_free(pSubitem->zName);
  1.2326 +    sqlite3_free(pSubitem->zAlias);
  1.2327 +    if( nSubSrc>1 ){
  1.2328 +      int extra = nSubSrc - 1;
  1.2329 +      for(i=1; i<nSubSrc; i++){
  1.2330 +        pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
  1.2331 +      }
  1.2332 +      p->pSrc = pSrc;
  1.2333 +      for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
  1.2334 +        pSrc->a[i] = pSrc->a[i-extra];
  1.2335 +      }
  1.2336 +    }
  1.2337 +    for(i=0; i<nSubSrc; i++){
  1.2338 +      pSrc->a[i+iFrom] = pSubSrc->a[i];
  1.2339 +      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  1.2340 +    }
  1.2341 +    pSrc->a[iFrom].jointype = jointype;
  1.2342 +  }
  1.2343 +
  1.2344 +  /* Now begin substituting subquery result set expressions for 
  1.2345 +  ** references to the iParent in the outer query.
  1.2346 +  ** 
  1.2347 +  ** Example:
  1.2348 +  **
  1.2349 +  **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  1.2350 +  **   \                     \_____________ subquery __________/          /
  1.2351 +  **    \_____________________ outer query ______________________________/
  1.2352 +  **
  1.2353 +  ** We look at every expression in the outer query and every place we see
  1.2354 +  ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  1.2355 +  */
  1.2356 +  pList = p->pEList;
  1.2357 +  for(i=0; i<pList->nExpr; i++){
  1.2358 +    Expr *pExpr;
  1.2359 +    if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
  1.2360 +      pList->a[i].zName = 
  1.2361 +             sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
  1.2362 +    }
  1.2363 +  }
  1.2364 +  substExprList(db, p->pEList, iParent, pSub->pEList);
  1.2365 +  if( isAgg ){
  1.2366 +    substExprList(db, p->pGroupBy, iParent, pSub->pEList);
  1.2367 +    substExpr(db, p->pHaving, iParent, pSub->pEList);
  1.2368 +  }
  1.2369 +  if( pSub->pOrderBy ){
  1.2370 +    assert( p->pOrderBy==0 );
  1.2371 +    p->pOrderBy = pSub->pOrderBy;
  1.2372 +    pSub->pOrderBy = 0;
  1.2373 +  }else if( p->pOrderBy ){
  1.2374 +    substExprList(db, p->pOrderBy, iParent, pSub->pEList);
  1.2375 +  }
  1.2376 +  if( pSub->pWhere ){
  1.2377 +    pWhere = sqlite3ExprDup(db, pSub->pWhere);
  1.2378 +  }else{
  1.2379 +    pWhere = 0;
  1.2380 +  }
  1.2381 +  if( subqueryIsAgg ){
  1.2382 +    assert( p->pHaving==0 );
  1.2383 +    p->pHaving = p->pWhere;
  1.2384 +    p->pWhere = pWhere;
  1.2385 +    substExpr(db, p->pHaving, iParent, pSub->pEList);
  1.2386 +    p->pHaving = sqlite3ExprAnd(db, p->pHaving, 
  1.2387 +                                sqlite3ExprDup(db, pSub->pHaving));
  1.2388 +    assert( p->pGroupBy==0 );
  1.2389 +    p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
  1.2390 +  }else{
  1.2391 +    substExpr(db, p->pWhere, iParent, pSub->pEList);
  1.2392 +    p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere);
  1.2393 +  }
  1.2394 +
  1.2395 +  /* The flattened query is distinct if either the inner or the
  1.2396 +  ** outer query is distinct. 
  1.2397 +  */
  1.2398 +  p->isDistinct = p->isDistinct || pSub->isDistinct;
  1.2399 +
  1.2400 +  /*
  1.2401 +  ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  1.2402 +  **
  1.2403 +  ** One is tempted to try to add a and b to combine the limits.  But this
  1.2404 +  ** does not work if either limit is negative.
  1.2405 +  */
  1.2406 +  if( pSub->pLimit ){
  1.2407 +    p->pLimit = pSub->pLimit;
  1.2408 +    pSub->pLimit = 0;
  1.2409 +  }
  1.2410 +
  1.2411 +  /* Finially, delete what is left of the subquery and return
  1.2412 +  ** success.
  1.2413 +  */
  1.2414 +  sqlite3SelectDelete(pSub);
  1.2415 +  return 1;
  1.2416 +}
  1.2417 +#endif /* SQLITE_OMIT_VIEW */
  1.2418 +
  1.2419 +/*
  1.2420 +** Analyze the SELECT statement passed in as an argument to see if it
  1.2421 +** is a simple min() or max() query.  If it is and this query can be
  1.2422 +** satisfied using a single seek to the beginning or end of an index,
  1.2423 +** then generate the code for this SELECT and return 1.  If this is not a 
  1.2424 +** simple min() or max() query, then return 0;
  1.2425 +**
  1.2426 +** A simply min() or max() query looks like this:
  1.2427 +**
  1.2428 +**    SELECT min(a) FROM table;
  1.2429 +**    SELECT max(a) FROM table;
  1.2430 +**
  1.2431 +** The query may have only a single table in its FROM argument.  There
  1.2432 +** can be no GROUP BY or HAVING or WHERE clauses.  The result set must
  1.2433 +** be the min() or max() of a single column of the table.  The column
  1.2434 +** in the min() or max() function must be indexed.
  1.2435 +**
  1.2436 +** The parameters to this routine are the same as for sqlite3Select().
  1.2437 +** See the header comment on that routine for additional information.
  1.2438 +*/
  1.2439 +static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
  1.2440 +  Expr *pExpr;
  1.2441 +  int iCol;
  1.2442 +  Table *pTab;
  1.2443 +  Index *pIdx;
  1.2444 +  int base;
  1.2445 +  Vdbe *v;
  1.2446 +  int seekOp;
  1.2447 +  ExprList *pEList, *pList, eList;
  1.2448 +  struct ExprList_item eListItem;
  1.2449 +  SrcList *pSrc;
  1.2450 +  int brk;
  1.2451 +  int iDb;
  1.2452 +
  1.2453 +  /* Check to see if this query is a simple min() or max() query.  Return
  1.2454 +  ** zero if it is  not.
  1.2455 +  */
  1.2456 +  if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
  1.2457 +  pSrc = p->pSrc;
  1.2458 +  if( pSrc->nSrc!=1 ) return 0;
  1.2459 +  pEList = p->pEList;
  1.2460 +  if( pEList->nExpr!=1 ) return 0;
  1.2461 +  pExpr = pEList->a[0].pExpr;
  1.2462 +  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  1.2463 +  pList = pExpr->pList;
  1.2464 +  if( pList==0 || pList->nExpr!=1 ) return 0;
  1.2465 +  if( pExpr->token.n!=3 ) return 0;
  1.2466 +  if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
  1.2467 +    seekOp = OP_Rewind;
  1.2468 +  }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
  1.2469 +    seekOp = OP_Last;
  1.2470 +  }else{
  1.2471 +    return 0;
  1.2472 +  }
  1.2473 +  pExpr = pList->a[0].pExpr;
  1.2474 +  if( pExpr->op!=TK_COLUMN ) return 0;
  1.2475 +  iCol = pExpr->iColumn;
  1.2476 +  pTab = pSrc->a[0].pTab;
  1.2477 +
  1.2478 +  /* This optimization cannot be used with virtual tables. */
  1.2479 +  if( IsVirtual(pTab) ) return 0;
  1.2480 +
  1.2481 +  /* If we get to here, it means the query is of the correct form.
  1.2482 +  ** Check to make sure we have an index and make pIdx point to the
  1.2483 +  ** appropriate index.  If the min() or max() is on an INTEGER PRIMARY
  1.2484 +  ** key column, no index is necessary so set pIdx to NULL.  If no
  1.2485 +  ** usable index is found, return 0.
  1.2486 +  */
  1.2487 +  if( iCol<0 ){
  1.2488 +    pIdx = 0;
  1.2489 +  }else{
  1.2490 +    CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr);
  1.2491 +    if( pColl==0 ) return 0;
  1.2492 +    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1.2493 +      assert( pIdx->nColumn>=1 );
  1.2494 +      if( pIdx->aiColumn[0]==iCol && 
  1.2495 +          0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){
  1.2496 +        break;
  1.2497 +      }
  1.2498 +    }
  1.2499 +    if( pIdx==0 ) return 0;
  1.2500 +  }
  1.2501 +
  1.2502 +  /* Identify column types if we will be using the callback.  This
  1.2503 +  ** step is skipped if the output is going to a table or a memory cell.
  1.2504 +  ** The column names have already been generated in the calling function.
  1.2505 +  */
  1.2506 +  v = sqlite3GetVdbe(pParse);
  1.2507 +  if( v==0 ) return 0;
  1.2508 +
  1.2509 +  /* If the output is destined for a temporary table, open that table.
  1.2510 +  */
  1.2511 +  if( eDest==SRT_EphemTab ){
  1.2512 +    sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1);
  1.2513 +  }
  1.2514 +
  1.2515 +  /* Generating code to find the min or the max.  Basically all we have
  1.2516 +  ** to do is find the first or the last entry in the chosen index.  If
  1.2517 +  ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
  1.2518 +  ** or last entry in the main table.
  1.2519 +  */
  1.2520 +  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  1.2521 +  assert( iDb>=0 || pTab->isEphem );
  1.2522 +  sqlite3CodeVerifySchema(pParse, iDb);
  1.2523 +  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  1.2524 +  base = pSrc->a[0].iCursor;
  1.2525 +  brk = sqlite3VdbeMakeLabel(v);
  1.2526 +  computeLimitRegisters(pParse, p, brk);
  1.2527 +  if( pSrc->a[0].pSelect==0 ){
  1.2528 +    sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead);
  1.2529 +  }
  1.2530 +  if( pIdx==0 ){
  1.2531 +    sqlite3VdbeAddOp(v, seekOp, base, 0);
  1.2532 +  }else{
  1.2533 +    /* Even though the cursor used to open the index here is closed
  1.2534 +    ** as soon as a single value has been read from it, allocate it
  1.2535 +    ** using (pParse->nTab++) to prevent the cursor id from being 
  1.2536 +    ** reused. This is important for statements of the form 
  1.2537 +    ** "INSERT INTO x SELECT max() FROM x".
  1.2538 +    */
  1.2539 +    int iIdx;
  1.2540 +    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  1.2541 +    iIdx = pParse->nTab++;
  1.2542 +    assert( pIdx->pSchema==pTab->pSchema );
  1.2543 +    sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  1.2544 +    sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 
  1.2545 +        (char*)pKey, P3_KEYINFO_HANDOFF);
  1.2546 +    if( seekOp==OP_Rewind ){
  1.2547 +      sqlite3VdbeAddOp(v, OP_Null, 0, 0);
  1.2548 +      sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
  1.2549 +      seekOp = OP_MoveGt;
  1.2550 +    }
  1.2551 +    if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
  1.2552 +      /* Ticket #2514: invert the seek operator if we are using
  1.2553 +      ** a descending index. */
  1.2554 +      if( seekOp==OP_Last ){
  1.2555 +        seekOp = OP_Rewind;
  1.2556 +      }else{
  1.2557 +        assert( seekOp==OP_MoveGt );
  1.2558 +        seekOp = OP_MoveLt;
  1.2559 +      }
  1.2560 +    }
  1.2561 +    sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
  1.2562 +    sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
  1.2563 +    sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
  1.2564 +    sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  1.2565 +  }
  1.2566 +  eList.nExpr = 1;
  1.2567 +  memset(&eListItem, 0, sizeof(eListItem));
  1.2568 +  eList.a = &eListItem;
  1.2569 +  eList.a[0].pExpr = pExpr;
  1.2570 +  selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0);
  1.2571 +  sqlite3VdbeResolveLabel(v, brk);
  1.2572 +  sqlite3VdbeAddOp(v, OP_Close, base, 0);
  1.2573 +  
  1.2574 +  return 1;
  1.2575 +}
  1.2576 +
  1.2577 +/*
  1.2578 +** Analyze and ORDER BY or GROUP BY clause in a SELECT statement.  Return
  1.2579 +** the number of errors seen.
  1.2580 +**
  1.2581 +** An ORDER BY or GROUP BY is a list of expressions.  If any expression
  1.2582 +** is an integer constant, then that expression is replaced by the
  1.2583 +** corresponding entry in the result set.
  1.2584 +*/
  1.2585 +static int processOrderGroupBy(
  1.2586 +  NameContext *pNC,     /* Name context of the SELECT statement. */
  1.2587 +  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
  1.2588 +  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
  1.2589 +){
  1.2590 +  int i;
  1.2591 +  ExprList *pEList = pNC->pEList;     /* The result set of the SELECT */
  1.2592 +  Parse *pParse = pNC->pParse;     /* The result set of the SELECT */
  1.2593 +  assert( pEList );
  1.2594 +
  1.2595 +  if( pOrderBy==0 ) return 0;
  1.2596 +  if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){
  1.2597 +    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  1.2598 +    return 1;
  1.2599 +  }
  1.2600 +  for(i=0; i<pOrderBy->nExpr; i++){
  1.2601 +    int iCol;
  1.2602 +    Expr *pE = pOrderBy->a[i].pExpr;
  1.2603 +    if( sqlite3ExprIsInteger(pE, &iCol) ){
  1.2604 +      if( iCol>0 && iCol<=pEList->nExpr ){
  1.2605 +        CollSeq *pColl = pE->pColl;
  1.2606 +        int flags = pE->flags & EP_ExpCollate;
  1.2607 +        sqlite3ExprDelete(pE);
  1.2608 +        pE = sqlite3ExprDup(pParse->db, pEList->a[iCol-1].pExpr);
  1.2609 +        pOrderBy->a[i].pExpr = pE;
  1.2610 +        if( pColl && flags ){
  1.2611 +          pE->pColl = pColl;
  1.2612 +          pE->flags |= flags;
  1.2613 +        }
  1.2614 +      }else{
  1.2615 +        sqlite3ErrorMsg(pParse, 
  1.2616 +           "%s BY column number %d out of range - should be "
  1.2617 +           "between 1 and %d", zType, iCol, pEList->nExpr);
  1.2618 +        return 1;
  1.2619 +      }
  1.2620 +    }
  1.2621 +    if( sqlite3ExprResolveNames(pNC, pE) ){
  1.2622 +      return 1;
  1.2623 +    }
  1.2624 +  }
  1.2625 +  return 0;
  1.2626 +}
  1.2627 +
  1.2628 +/*
  1.2629 +** This routine resolves any names used in the result set of the
  1.2630 +** supplied SELECT statement. If the SELECT statement being resolved
  1.2631 +** is a sub-select, then pOuterNC is a pointer to the NameContext 
  1.2632 +** of the parent SELECT.
  1.2633 +*/
  1.2634 +int sqlite3SelectResolve(
  1.2635 +  Parse *pParse,         /* The parser context */
  1.2636 +  Select *p,             /* The SELECT statement being coded. */
  1.2637 +  NameContext *pOuterNC  /* The outer name context. May be NULL. */
  1.2638 +){
  1.2639 +  ExprList *pEList;          /* Result set. */
  1.2640 +  int i;                     /* For-loop variable used in multiple places */
  1.2641 +  NameContext sNC;           /* Local name-context */
  1.2642 +  ExprList *pGroupBy;        /* The group by clause */
  1.2643 +
  1.2644 +  /* If this routine has run before, return immediately. */
  1.2645 +  if( p->isResolved ){
  1.2646 +    assert( !pOuterNC );
  1.2647 +    return SQLITE_OK;
  1.2648 +  }
  1.2649 +  p->isResolved = 1;
  1.2650 +
  1.2651 +  /* If there have already been errors, do nothing. */
  1.2652 +  if( pParse->nErr>0 ){
  1.2653 +    return SQLITE_ERROR;
  1.2654 +  }
  1.2655 +
  1.2656 +  /* Prepare the select statement. This call will allocate all cursors
  1.2657 +  ** required to handle the tables and subqueries in the FROM clause.
  1.2658 +  */
  1.2659 +  if( prepSelectStmt(pParse, p) ){
  1.2660 +    return SQLITE_ERROR;
  1.2661 +  }
  1.2662 +
  1.2663 +  /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  1.2664 +  ** are not allowed to refer to any names, so pass an empty NameContext.
  1.2665 +  */
  1.2666 +  memset(&sNC, 0, sizeof(sNC));
  1.2667 +  sNC.pParse = pParse;
  1.2668 +  if( sqlite3ExprResolveNames(&sNC, p->pLimit) ||
  1.2669 +      sqlite3ExprResolveNames(&sNC, p->pOffset) ){
  1.2670 +    return SQLITE_ERROR;
  1.2671 +  }
  1.2672 +
  1.2673 +  /* Set up the local name-context to pass to ExprResolveNames() to
  1.2674 +  ** resolve the expression-list.
  1.2675 +  */
  1.2676 +  sNC.allowAgg = 1;
  1.2677 +  sNC.pSrcList = p->pSrc;
  1.2678 +  sNC.pNext = pOuterNC;
  1.2679 +
  1.2680 +  /* Resolve names in the result set. */
  1.2681 +  pEList = p->pEList;
  1.2682 +  if( !pEList ) return SQLITE_ERROR;
  1.2683 +  for(i=0; i<pEList->nExpr; i++){
  1.2684 +    Expr *pX = pEList->a[i].pExpr;
  1.2685 +    if( sqlite3ExprResolveNames(&sNC, pX) ){
  1.2686 +      return SQLITE_ERROR;
  1.2687 +    }
  1.2688 +  }
  1.2689 +
  1.2690 +  /* If there are no aggregate functions in the result-set, and no GROUP BY 
  1.2691 +  ** expression, do not allow aggregates in any of the other expressions.
  1.2692 +  */
  1.2693 +  assert( !p->isAgg );
  1.2694 +  pGroupBy = p->pGroupBy;
  1.2695 +  if( pGroupBy || sNC.hasAgg ){
  1.2696 +    p->isAgg = 1;
  1.2697 +  }else{
  1.2698 +    sNC.allowAgg = 0;
  1.2699 +  }
  1.2700 +
  1.2701 +  /* If a HAVING clause is present, then there must be a GROUP BY clause.
  1.2702 +  */
  1.2703 +  if( p->pHaving && !pGroupBy ){
  1.2704 +    sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  1.2705 +    return SQLITE_ERROR;
  1.2706 +  }
  1.2707 +
  1.2708 +  /* Add the expression list to the name-context before parsing the
  1.2709 +  ** other expressions in the SELECT statement. This is so that
  1.2710 +  ** expressions in the WHERE clause (etc.) can refer to expressions by
  1.2711 +  ** aliases in the result set.
  1.2712 +  **
  1.2713 +  ** Minor point: If this is the case, then the expression will be
  1.2714 +  ** re-evaluated for each reference to it.
  1.2715 +  */
  1.2716 +  sNC.pEList = p->pEList;
  1.2717 +  if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
  1.2718 +     sqlite3ExprResolveNames(&sNC, p->pHaving) ){
  1.2719 +    return SQLITE_ERROR;
  1.2720 +  }
  1.2721 +  if( p->pPrior==0 ){
  1.2722 +    if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
  1.2723 +        processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){
  1.2724 +      return SQLITE_ERROR;
  1.2725 +    }
  1.2726 +  }
  1.2727 +
  1.2728 +  if( pParse->db->mallocFailed ){
  1.2729 +    return SQLITE_NOMEM;
  1.2730 +  }
  1.2731 +
  1.2732 +  /* Make sure the GROUP BY clause does not contain aggregate functions.
  1.2733 +  */
  1.2734 +  if( pGroupBy ){
  1.2735 +    struct ExprList_item *pItem;
  1.2736 +  
  1.2737 +    for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  1.2738 +      if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  1.2739 +        sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  1.2740 +            "the GROUP BY clause");
  1.2741 +        return SQLITE_ERROR;
  1.2742 +      }
  1.2743 +    }
  1.2744 +  }
  1.2745 +
  1.2746 +  /* If this is one SELECT of a compound, be sure to resolve names
  1.2747 +  ** in the other SELECTs.
  1.2748 +  */
  1.2749 +  if( p->pPrior ){
  1.2750 +    return sqlite3SelectResolve(pParse, p->pPrior, pOuterNC);
  1.2751 +  }else{
  1.2752 +    return SQLITE_OK;
  1.2753 +  }
  1.2754 +}
  1.2755 +
  1.2756 +/*
  1.2757 +** Reset the aggregate accumulator.
  1.2758 +**
  1.2759 +** The aggregate accumulator is a set of memory cells that hold
  1.2760 +** intermediate results while calculating an aggregate.  This
  1.2761 +** routine simply stores NULLs in all of those memory cells.
  1.2762 +*/
  1.2763 +static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  1.2764 +  Vdbe *v = pParse->pVdbe;
  1.2765 +  int i;
  1.2766 +  struct AggInfo_func *pFunc;
  1.2767 +  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  1.2768 +    return;
  1.2769 +  }
  1.2770 +  for(i=0; i<pAggInfo->nColumn; i++){
  1.2771 +    sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0);
  1.2772 +  }
  1.2773 +  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  1.2774 +    sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0);
  1.2775 +    if( pFunc->iDistinct>=0 ){
  1.2776 +      Expr *pE = pFunc->pExpr;
  1.2777 +      if( pE->pList==0 || pE->pList->nExpr!=1 ){
  1.2778 +        sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
  1.2779 +           "by an expression");
  1.2780 +        pFunc->iDistinct = -1;
  1.2781 +      }else{
  1.2782 +        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
  1.2783 +        sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 
  1.2784 +                          (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  1.2785 +      }
  1.2786 +    }
  1.2787 +  }
  1.2788 +}
  1.2789 +
  1.2790 +/*
  1.2791 +** Invoke the OP_AggFinalize opcode for every aggregate function
  1.2792 +** in the AggInfo structure.
  1.2793 +*/
  1.2794 +static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  1.2795 +  Vdbe *v = pParse->pVdbe;
  1.2796 +  int i;
  1.2797 +  struct AggInfo_func *pF;
  1.2798 +  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  1.2799 +    ExprList *pList = pF->pExpr->pList;
  1.2800 +    sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0,
  1.2801 +                      (void*)pF->pFunc, P3_FUNCDEF);
  1.2802 +  }
  1.2803 +}
  1.2804 +
  1.2805 +/*
  1.2806 +** Update the accumulator memory cells for an aggregate based on
  1.2807 +** the current cursor position.
  1.2808 +*/
  1.2809 +static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  1.2810 +  Vdbe *v = pParse->pVdbe;
  1.2811 +  int i;
  1.2812 +  struct AggInfo_func *pF;
  1.2813 +  struct AggInfo_col *pC;
  1.2814 +
  1.2815 +  pAggInfo->directMode = 1;
  1.2816 +  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  1.2817 +    int nArg;
  1.2818 +    int addrNext = 0;
  1.2819 +    ExprList *pList = pF->pExpr->pList;
  1.2820 +    if( pList ){
  1.2821 +      nArg = pList->nExpr;
  1.2822 +      sqlite3ExprCodeExprList(pParse, pList);
  1.2823 +    }else{
  1.2824 +      nArg = 0;
  1.2825 +    }
  1.2826 +    if( pF->iDistinct>=0 ){
  1.2827 +      addrNext = sqlite3VdbeMakeLabel(v);
  1.2828 +      assert( nArg==1 );
  1.2829 +      codeDistinct(v, pF->iDistinct, addrNext, 1);
  1.2830 +    }
  1.2831 +    if( pF->pFunc->needCollSeq ){
  1.2832 +      CollSeq *pColl = 0;
  1.2833 +      struct ExprList_item *pItem;
  1.2834 +      int j;
  1.2835 +      assert( pList!=0 );  /* pList!=0 if pF->pFunc->needCollSeq is true */
  1.2836 +      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  1.2837 +        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  1.2838 +      }
  1.2839 +      if( !pColl ){
  1.2840 +        pColl = pParse->db->pDfltColl;
  1.2841 +      }
  1.2842 +      sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
  1.2843 +    }
  1.2844 +    sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF);
  1.2845 +    if( addrNext ){
  1.2846 +      sqlite3VdbeResolveLabel(v, addrNext);
  1.2847 +    }
  1.2848 +  }
  1.2849 +  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  1.2850 +    sqlite3ExprCode(pParse, pC->pExpr);
  1.2851 +    sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1);
  1.2852 +  }
  1.2853 +  pAggInfo->directMode = 0;
  1.2854 +}
  1.2855 +
  1.2856 +
  1.2857 +/*
  1.2858 +** Generate code for the given SELECT statement.
  1.2859 +**
  1.2860 +** The results are distributed in various ways depending on the
  1.2861 +** value of eDest and iParm.
  1.2862 +**
  1.2863 +**     eDest Value       Result
  1.2864 +**     ------------    -------------------------------------------
  1.2865 +**     SRT_Callback    Invoke the callback for each row of the result.
  1.2866 +**
  1.2867 +**     SRT_Mem         Store first result in memory cell iParm
  1.2868 +**
  1.2869 +**     SRT_Set         Store results as keys of table iParm.
  1.2870 +**
  1.2871 +**     SRT_Union       Store results as a key in a temporary table iParm
  1.2872 +**
  1.2873 +**     SRT_Except      Remove results from the temporary table iParm.
  1.2874 +**
  1.2875 +**     SRT_Table       Store results in temporary table iParm
  1.2876 +**
  1.2877 +** The table above is incomplete.  Additional eDist value have be added
  1.2878 +** since this comment was written.  See the selectInnerLoop() function for
  1.2879 +** a complete listing of the allowed values of eDest and their meanings.
  1.2880 +**
  1.2881 +** This routine returns the number of errors.  If any errors are
  1.2882 +** encountered, then an appropriate error message is left in
  1.2883 +** pParse->zErrMsg.
  1.2884 +**
  1.2885 +** This routine does NOT free the Select structure passed in.  The
  1.2886 +** calling function needs to do that.
  1.2887 +**
  1.2888 +** The pParent, parentTab, and *pParentAgg fields are filled in if this
  1.2889 +** SELECT is a subquery.  This routine may try to combine this SELECT
  1.2890 +** with its parent to form a single flat query.  In so doing, it might
  1.2891 +** change the parent query from a non-aggregate to an aggregate query.
  1.2892 +** For that reason, the pParentAgg flag is passed as a pointer, so it
  1.2893 +** can be changed.
  1.2894 +**
  1.2895 +** Example 1:   The meaning of the pParent parameter.
  1.2896 +**
  1.2897 +**    SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
  1.2898 +**    \                      \_______ subquery _______/        /
  1.2899 +**     \                                                      /
  1.2900 +**      \____________________ outer query ___________________/
  1.2901 +**
  1.2902 +** This routine is called for the outer query first.   For that call,
  1.2903 +** pParent will be NULL.  During the processing of the outer query, this 
  1.2904 +** routine is called recursively to handle the subquery.  For the recursive
  1.2905 +** call, pParent will point to the outer query.  Because the subquery is
  1.2906 +** the second element in a three-way join, the parentTab parameter will
  1.2907 +** be 1 (the 2nd value of a 0-indexed array.)
  1.2908 +*/
  1.2909 +int sqlite3Select(
  1.2910 +  Parse *pParse,         /* The parser context */
  1.2911 +  Select *p,             /* The SELECT statement being coded. */
  1.2912 +  int eDest,             /* How to dispose of the results */
  1.2913 +  int iParm,             /* A parameter used by the eDest disposal method */
  1.2914 +  Select *pParent,       /* Another SELECT for which this is a sub-query */
  1.2915 +  int parentTab,         /* Index in pParent->pSrc of this query */
  1.2916 +  int *pParentAgg,       /* True if pParent uses aggregate functions */
  1.2917 +  char *aff              /* If eDest is SRT_Union, the affinity string */
  1.2918 +){
  1.2919 +  int i, j;              /* Loop counters */
  1.2920 +  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
  1.2921 +  Vdbe *v;               /* The virtual machine under construction */
  1.2922 +  int isAgg;             /* True for select lists like "count(*)" */
  1.2923 +  ExprList *pEList;      /* List of columns to extract. */
  1.2924 +  SrcList *pTabList;     /* List of tables to select from */
  1.2925 +  Expr *pWhere;          /* The WHERE clause.  May be NULL */
  1.2926 +  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
  1.2927 +  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
  1.2928 +  Expr *pHaving;         /* The HAVING clause.  May be NULL */
  1.2929 +  int isDistinct;        /* True if the DISTINCT keyword is present */
  1.2930 +  int distinct;          /* Table to use for the distinct set */
  1.2931 +  int rc = 1;            /* Value to return from this function */
  1.2932 +  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
  1.2933 +  AggInfo sAggInfo;      /* Information used by aggregate queries */
  1.2934 +  int iEnd;              /* Address of the end of the query */
  1.2935 +  sqlite3 *db;           /* The database connection */
  1.2936 +
  1.2937 +  db = pParse->db;
  1.2938 +  if( p==0 || db->mallocFailed || pParse->nErr ){
  1.2939 +    return 1;
  1.2940 +  }
  1.2941 +  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  1.2942 +  memset(&sAggInfo, 0, sizeof(sAggInfo));
  1.2943 +
  1.2944 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.2945 +  /* If there is are a sequence of queries, do the earlier ones first.
  1.2946 +  */
  1.2947 +  if( p->pPrior ){
  1.2948 +    if( p->pRightmost==0 ){
  1.2949 +      Select *pLoop;
  1.2950 +      int cnt = 0;
  1.2951 +      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  1.2952 +        pLoop->pRightmost = p;
  1.2953 +      }
  1.2954 +      if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){
  1.2955 +        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  1.2956 +        return 1;
  1.2957 +      }
  1.2958 +    }
  1.2959 +    return multiSelect(pParse, p, eDest, iParm, aff);
  1.2960 +  }
  1.2961 +#endif
  1.2962 +
  1.2963 +  pOrderBy = p->pOrderBy;
  1.2964 +  if( IgnorableOrderby(eDest) ){
  1.2965 +    p->pOrderBy = 0;
  1.2966 +  }
  1.2967 +  if( sqlite3SelectResolve(pParse, p, 0) ){
  1.2968 +    goto select_end;
  1.2969 +  }
  1.2970 +  p->pOrderBy = pOrderBy;
  1.2971 +
  1.2972 +  /* Make local copies of the parameters for this query.
  1.2973 +  */
  1.2974 +  pTabList = p->pSrc;
  1.2975 +  pWhere = p->pWhere;
  1.2976 +  pGroupBy = p->pGroupBy;
  1.2977 +  pHaving = p->pHaving;
  1.2978 +  isAgg = p->isAgg;
  1.2979 +  isDistinct = p->isDistinct;
  1.2980 +  pEList = p->pEList;
  1.2981 +  if( pEList==0 ) goto select_end;
  1.2982 +
  1.2983 +  /* 
  1.2984 +  ** Do not even attempt to generate any code if we have already seen
  1.2985 +  ** errors before this routine starts.
  1.2986 +  */
  1.2987 +  if( pParse->nErr>0 ) goto select_end;
  1.2988 +
  1.2989 +  /* If writing to memory or generating a set
  1.2990 +  ** only a single column may be output.
  1.2991 +  */
  1.2992 +#ifndef SQLITE_OMIT_SUBQUERY
  1.2993 +  if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){
  1.2994 +    goto select_end;
  1.2995 +  }
  1.2996 +#endif
  1.2997 +
  1.2998 +  /* ORDER BY is ignored for some destinations.
  1.2999 +  */
  1.3000 +  if( IgnorableOrderby(eDest) ){
  1.3001 +    pOrderBy = 0;
  1.3002 +  }
  1.3003 +
  1.3004 +  /* Begin generating code.
  1.3005 +  */
  1.3006 +  v = sqlite3GetVdbe(pParse);
  1.3007 +  if( v==0 ) goto select_end;
  1.3008 +
  1.3009 +  /* Generate code for all sub-queries in the FROM clause
  1.3010 +  */
  1.3011 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  1.3012 +  for(i=0; i<pTabList->nSrc; i++){
  1.3013 +    const char *zSavedAuthContext = 0;
  1.3014 +    int needRestoreContext;
  1.3015 +    struct SrcList_item *pItem = &pTabList->a[i];
  1.3016 +
  1.3017 +    if( pItem->pSelect==0 || pItem->isPopulated ) continue;
  1.3018 +    if( pItem->zName!=0 ){
  1.3019 +      zSavedAuthContext = pParse->zAuthContext;
  1.3020 +      pParse->zAuthContext = pItem->zName;
  1.3021 +      needRestoreContext = 1;
  1.3022 +    }else{
  1.3023 +      needRestoreContext = 0;
  1.3024 +    }
  1.3025 +#if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
  1.3026 +    /* Increment Parse.nHeight by the height of the largest expression
  1.3027 +    ** tree refered to by this, the parent select. The child select
  1.3028 +    ** may contain expression trees of at most
  1.3029 +    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  1.3030 +    ** more conservative than necessary, but much easier than enforcing
  1.3031 +    ** an exact limit.
  1.3032 +    */
  1.3033 +    pParse->nHeight += sqlite3SelectExprHeight(p);
  1.3034 +#endif
  1.3035 +    sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab, 
  1.3036 +                 pItem->iCursor, p, i, &isAgg, 0);
  1.3037 +#if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
  1.3038 +    pParse->nHeight -= sqlite3SelectExprHeight(p);
  1.3039 +#endif
  1.3040 +    if( needRestoreContext ){
  1.3041 +      pParse->zAuthContext = zSavedAuthContext;
  1.3042 +    }
  1.3043 +    pTabList = p->pSrc;
  1.3044 +    pWhere = p->pWhere;
  1.3045 +    if( !IgnorableOrderby(eDest) ){
  1.3046 +      pOrderBy = p->pOrderBy;
  1.3047 +    }
  1.3048 +    pGroupBy = p->pGroupBy;
  1.3049 +    pHaving = p->pHaving;
  1.3050 +    isDistinct = p->isDistinct;
  1.3051 +  }
  1.3052 +#endif
  1.3053 +
  1.3054 +  /* Check for the special case of a min() or max() function by itself
  1.3055 +  ** in the result set.
  1.3056 +  */
  1.3057 +  if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
  1.3058 +    rc = 0;
  1.3059 +    goto select_end;
  1.3060 +  }
  1.3061 +
  1.3062 +  /* Check to see if this is a subquery that can be "flattened" into its parent.
  1.3063 +  ** If flattening is a possiblity, do so and return immediately.  
  1.3064 +  */
  1.3065 +#ifndef SQLITE_OMIT_VIEW
  1.3066 +  if( pParent && pParentAgg &&
  1.3067 +      flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){
  1.3068 +    if( isAgg ) *pParentAgg = 1;
  1.3069 +    goto select_end;
  1.3070 +  }
  1.3071 +#endif
  1.3072 +
  1.3073 +  /* If there is an ORDER BY clause, then this sorting
  1.3074 +  ** index might end up being unused if the data can be 
  1.3075 +  ** extracted in pre-sorted order.  If that is the case, then the
  1.3076 +  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  1.3077 +  ** we figure out that the sorting index is not needed.  The addrSortIndex
  1.3078 +  ** variable is used to facilitate that change.
  1.3079 +  */
  1.3080 +  if( pOrderBy ){
  1.3081 +    KeyInfo *pKeyInfo;
  1.3082 +    if( pParse->nErr ){
  1.3083 +      goto select_end;
  1.3084 +    }
  1.3085 +    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  1.3086 +    pOrderBy->iECursor = pParse->nTab++;
  1.3087 +    p->addrOpenEphm[2] = addrSortIndex =
  1.3088 +      sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2,                     (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  1.3089 +  }else{
  1.3090 +    addrSortIndex = -1;
  1.3091 +  }
  1.3092 +
  1.3093 +  /* If the output is destined for a temporary table, open that table.
  1.3094 +  */
  1.3095 +  if( eDest==SRT_EphemTab ){
  1.3096 +    sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr);
  1.3097 +  }
  1.3098 +
  1.3099 +  /* Set the limiter.
  1.3100 +  */
  1.3101 +  iEnd = sqlite3VdbeMakeLabel(v);
  1.3102 +  computeLimitRegisters(pParse, p, iEnd);
  1.3103 +
  1.3104 +  /* Open a virtual index to use for the distinct set.
  1.3105 +  */
  1.3106 +  if( isDistinct ){
  1.3107 +    KeyInfo *pKeyInfo;
  1.3108 +    distinct = pParse->nTab++;
  1.3109 +    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
  1.3110 +    sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0, 
  1.3111 +                        (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  1.3112 +  }else{
  1.3113 +    distinct = -1;
  1.3114 +  }
  1.3115 +
  1.3116 +  /* Aggregate and non-aggregate queries are handled differently */
  1.3117 +  if( !isAgg && pGroupBy==0 ){
  1.3118 +    /* This case is for non-aggregate queries
  1.3119 +    ** Begin the database scan
  1.3120 +    */
  1.3121 +    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy);
  1.3122 +    if( pWInfo==0 ) goto select_end;
  1.3123 +
  1.3124 +    /* If sorting index that was created by a prior OP_OpenEphemeral 
  1.3125 +    ** instruction ended up not being needed, then change the OP_OpenEphemeral
  1.3126 +    ** into an OP_Noop.
  1.3127 +    */
  1.3128 +    if( addrSortIndex>=0 && pOrderBy==0 ){
  1.3129 +      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
  1.3130 +      p->addrOpenEphm[2] = -1;
  1.3131 +    }
  1.3132 +
  1.3133 +    /* Use the standard inner loop
  1.3134 +    */
  1.3135 +    if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
  1.3136 +                    iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){
  1.3137 +       goto select_end;
  1.3138 +    }
  1.3139 +
  1.3140 +    /* End the database scan loop.
  1.3141 +    */
  1.3142 +    sqlite3WhereEnd(pWInfo);
  1.3143 +  }else{
  1.3144 +    /* This is the processing for aggregate queries */
  1.3145 +    NameContext sNC;    /* Name context for processing aggregate information */
  1.3146 +    int iAMem;          /* First Mem address for storing current GROUP BY */
  1.3147 +    int iBMem;          /* First Mem address for previous GROUP BY */
  1.3148 +    int iUseFlag;       /* Mem address holding flag indicating that at least
  1.3149 +                        ** one row of the input to the aggregator has been
  1.3150 +                        ** processed */
  1.3151 +    int iAbortFlag;     /* Mem address which causes query abort if positive */
  1.3152 +    int groupBySort;    /* Rows come from source in GROUP BY order */
  1.3153 +
  1.3154 +
  1.3155 +    /* The following variables hold addresses or labels for parts of the
  1.3156 +    ** virtual machine program we are putting together */
  1.3157 +    int addrOutputRow;      /* Start of subroutine that outputs a result row */
  1.3158 +    int addrSetAbort;       /* Set the abort flag and return */
  1.3159 +    int addrInitializeLoop; /* Start of code that initializes the input loop */
  1.3160 +    int addrTopOfLoop;      /* Top of the input loop */
  1.3161 +    int addrGroupByChange;  /* Code that runs when any GROUP BY term changes */
  1.3162 +    int addrProcessRow;     /* Code to process a single input row */
  1.3163 +    int addrEnd;            /* End of all processing */
  1.3164 +    int addrSortingIdx;     /* The OP_OpenEphemeral for the sorting index */
  1.3165 +    int addrReset;          /* Subroutine for resetting the accumulator */
  1.3166 +
  1.3167 +    addrEnd = sqlite3VdbeMakeLabel(v);
  1.3168 +
  1.3169 +    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  1.3170 +    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  1.3171 +    ** SELECT statement.
  1.3172 +    */
  1.3173 +    memset(&sNC, 0, sizeof(sNC));
  1.3174 +    sNC.pParse = pParse;
  1.3175 +    sNC.pSrcList = pTabList;
  1.3176 +    sNC.pAggInfo = &sAggInfo;
  1.3177 +    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  1.3178 +    sAggInfo.pGroupBy = pGroupBy;
  1.3179 +    if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){
  1.3180 +      goto select_end;
  1.3181 +    }
  1.3182 +    if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){
  1.3183 +      goto select_end;
  1.3184 +    }
  1.3185 +    if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){
  1.3186 +      goto select_end;
  1.3187 +    }
  1.3188 +    sAggInfo.nAccumulator = sAggInfo.nColumn;
  1.3189 +    for(i=0; i<sAggInfo.nFunc; i++){
  1.3190 +      if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){
  1.3191 +        goto select_end;
  1.3192 +      }
  1.3193 +    }
  1.3194 +    if( db->mallocFailed ) goto select_end;
  1.3195 +
  1.3196 +    /* Processing for aggregates with GROUP BY is very different and
  1.3197 +    ** much more complex tha aggregates without a GROUP BY.
  1.3198 +    */
  1.3199 +    if( pGroupBy ){
  1.3200 +      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
  1.3201 +
  1.3202 +      /* Create labels that we will be needing
  1.3203 +      */
  1.3204 +     
  1.3205 +      addrInitializeLoop = sqlite3VdbeMakeLabel(v);
  1.3206 +      addrGroupByChange = sqlite3VdbeMakeLabel(v);
  1.3207 +      addrProcessRow = sqlite3VdbeMakeLabel(v);
  1.3208 +
  1.3209 +      /* If there is a GROUP BY clause we might need a sorting index to
  1.3210 +      ** implement it.  Allocate that sorting index now.  If it turns out
  1.3211 +      ** that we do not need it after all, the OpenEphemeral instruction
  1.3212 +      ** will be converted into a Noop.  
  1.3213 +      */
  1.3214 +      sAggInfo.sortingIdx = pParse->nTab++;
  1.3215 +      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  1.3216 +      addrSortingIdx =
  1.3217 +          sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx,
  1.3218 +                         sAggInfo.nSortingColumn,
  1.3219 +                         (char*)pKeyInfo, P3_KEYINFO_HANDOFF);
  1.3220 +
  1.3221 +      /* Initialize memory locations used by GROUP BY aggregate processing
  1.3222 +      */
  1.3223 +      iUseFlag = pParse->nMem++;
  1.3224 +      iAbortFlag = pParse->nMem++;
  1.3225 +      iAMem = pParse->nMem;
  1.3226 +      pParse->nMem += pGroupBy->nExpr;
  1.3227 +      iBMem = pParse->nMem;
  1.3228 +      pParse->nMem += pGroupBy->nExpr;
  1.3229 +      sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag);
  1.3230 +      VdbeComment((v, "# clear abort flag"));
  1.3231 +      sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag);
  1.3232 +      VdbeComment((v, "# indicate accumulator empty"));
  1.3233 +      sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop);
  1.3234 +
  1.3235 +      /* Generate a subroutine that outputs a single row of the result
  1.3236 +      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
  1.3237 +      ** is less than or equal to zero, the subroutine is a no-op.  If
  1.3238 +      ** the processing calls for the query to abort, this subroutine
  1.3239 +      ** increments the iAbortFlag memory location before returning in
  1.3240 +      ** order to signal the caller to abort.
  1.3241 +      */
  1.3242 +      addrSetAbort = sqlite3VdbeCurrentAddr(v);
  1.3243 +      sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag);
  1.3244 +      VdbeComment((v, "# set abort flag"));
  1.3245 +      sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  1.3246 +      addrOutputRow = sqlite3VdbeCurrentAddr(v);
  1.3247 +      sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2);
  1.3248 +      VdbeComment((v, "# Groupby result generator entry point"));
  1.3249 +      sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  1.3250 +      finalizeAggFunctions(pParse, &sAggInfo);
  1.3251 +      if( pHaving ){
  1.3252 +        sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1);
  1.3253 +      }
  1.3254 +      rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  1.3255 +                           distinct, eDest, iParm, 
  1.3256 +                           addrOutputRow+1, addrSetAbort, aff);
  1.3257 +      if( rc ){
  1.3258 +        goto select_end;
  1.3259 +      }
  1.3260 +      sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  1.3261 +      VdbeComment((v, "# end groupby result generator"));
  1.3262 +
  1.3263 +      /* Generate a subroutine that will reset the group-by accumulator
  1.3264 +      */
  1.3265 +      addrReset = sqlite3VdbeCurrentAddr(v);
  1.3266 +      resetAccumulator(pParse, &sAggInfo);
  1.3267 +      sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  1.3268 +
  1.3269 +      /* Begin a loop that will extract all source rows in GROUP BY order.
  1.3270 +      ** This might involve two separate loops with an OP_Sort in between, or
  1.3271 +      ** it might be a single loop that uses an index to extract information
  1.3272 +      ** in the right order to begin with.
  1.3273 +      */
  1.3274 +      sqlite3VdbeResolveLabel(v, addrInitializeLoop);
  1.3275 +      sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
  1.3276 +      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy);
  1.3277 +      if( pWInfo==0 ) goto select_end;
  1.3278 +      if( pGroupBy==0 ){
  1.3279 +        /* The optimizer is able to deliver rows in group by order so
  1.3280 +        ** we do not have to sort.  The OP_OpenEphemeral table will be
  1.3281 +        ** cancelled later because we still need to use the pKeyInfo
  1.3282 +        */
  1.3283 +        pGroupBy = p->pGroupBy;
  1.3284 +        groupBySort = 0;
  1.3285 +      }else{
  1.3286 +        /* Rows are coming out in undetermined order.  We have to push
  1.3287 +        ** each row into a sorting index, terminate the first loop,
  1.3288 +        ** then loop over the sorting index in order to get the output
  1.3289 +        ** in sorted order
  1.3290 +        */
  1.3291 +        groupBySort = 1;
  1.3292 +        sqlite3ExprCodeExprList(pParse, pGroupBy);
  1.3293 +        sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0);
  1.3294 +        j = pGroupBy->nExpr+1;
  1.3295 +        for(i=0; i<sAggInfo.nColumn; i++){
  1.3296 +          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  1.3297 +          if( pCol->iSorterColumn<j ) continue;
  1.3298 +          sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable);
  1.3299 +          j++;
  1.3300 +        }
  1.3301 +        sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0);
  1.3302 +        sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0);
  1.3303 +        sqlite3WhereEnd(pWInfo);
  1.3304 +        sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
  1.3305 +        VdbeComment((v, "# GROUP BY sort"));
  1.3306 +        sAggInfo.useSortingIdx = 1;
  1.3307 +      }
  1.3308 +
  1.3309 +      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  1.3310 +      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  1.3311 +      ** Then compare the current GROUP BY terms against the GROUP BY terms
  1.3312 +      ** from the previous row currently stored in a0, a1, a2...
  1.3313 +      */
  1.3314 +      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  1.3315 +      for(j=0; j<pGroupBy->nExpr; j++){
  1.3316 +        if( groupBySort ){
  1.3317 +          sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j);
  1.3318 +        }else{
  1.3319 +          sAggInfo.directMode = 1;
  1.3320 +          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr);
  1.3321 +        }
  1.3322 +        sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1);
  1.3323 +      }
  1.3324 +      for(j=pGroupBy->nExpr-1; j>=0; j--){
  1.3325 +        if( j<pGroupBy->nExpr-1 ){
  1.3326 +          sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0);
  1.3327 +        }
  1.3328 +        sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0);
  1.3329 +        if( j==0 ){
  1.3330 +          sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow);
  1.3331 +        }else{
  1.3332 +          sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange);
  1.3333 +        }
  1.3334 +        sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ);
  1.3335 +      }
  1.3336 +
  1.3337 +      /* Generate code that runs whenever the GROUP BY changes.
  1.3338 +      ** Change in the GROUP BY are detected by the previous code
  1.3339 +      ** block.  If there were no changes, this block is skipped.
  1.3340 +      **
  1.3341 +      ** This code copies current group by terms in b0,b1,b2,...
  1.3342 +      ** over to a0,a1,a2.  It then calls the output subroutine
  1.3343 +      ** and resets the aggregate accumulator registers in preparation
  1.3344 +      ** for the next GROUP BY batch.
  1.3345 +      */
  1.3346 +      sqlite3VdbeResolveLabel(v, addrGroupByChange);
  1.3347 +      for(j=0; j<pGroupBy->nExpr; j++){
  1.3348 +        sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j);
  1.3349 +      }
  1.3350 +      sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
  1.3351 +      VdbeComment((v, "# output one row"));
  1.3352 +      sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd);
  1.3353 +      VdbeComment((v, "# check abort flag"));
  1.3354 +      sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset);
  1.3355 +      VdbeComment((v, "# reset accumulator"));
  1.3356 +
  1.3357 +      /* Update the aggregate accumulators based on the content of
  1.3358 +      ** the current row
  1.3359 +      */
  1.3360 +      sqlite3VdbeResolveLabel(v, addrProcessRow);
  1.3361 +      updateAccumulator(pParse, &sAggInfo);
  1.3362 +      sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag);
  1.3363 +      VdbeComment((v, "# indicate data in accumulator"));
  1.3364 +
  1.3365 +      /* End of the loop
  1.3366 +      */
  1.3367 +      if( groupBySort ){
  1.3368 +        sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
  1.3369 +      }else{
  1.3370 +        sqlite3WhereEnd(pWInfo);
  1.3371 +        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
  1.3372 +      }
  1.3373 +
  1.3374 +      /* Output the final row of result
  1.3375 +      */
  1.3376 +      sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow);
  1.3377 +      VdbeComment((v, "# output final row"));
  1.3378 +      
  1.3379 +    } /* endif pGroupBy */
  1.3380 +    else {
  1.3381 +      /* This case runs if the aggregate has no GROUP BY clause.  The
  1.3382 +      ** processing is much simpler since there is only a single row
  1.3383 +      ** of output.
  1.3384 +      */
  1.3385 +      resetAccumulator(pParse, &sAggInfo);
  1.3386 +      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0);
  1.3387 +      if( pWInfo==0 ) goto select_end;
  1.3388 +      updateAccumulator(pParse, &sAggInfo);
  1.3389 +      sqlite3WhereEnd(pWInfo);
  1.3390 +      finalizeAggFunctions(pParse, &sAggInfo);
  1.3391 +      pOrderBy = 0;
  1.3392 +      if( pHaving ){
  1.3393 +        sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1);
  1.3394 +      }
  1.3395 +      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
  1.3396 +                      eDest, iParm, addrEnd, addrEnd, aff);
  1.3397 +    }
  1.3398 +    sqlite3VdbeResolveLabel(v, addrEnd);
  1.3399 +    
  1.3400 +  } /* endif aggregate query */
  1.3401 +
  1.3402 +  /* If there is an ORDER BY clause, then we need to sort the results
  1.3403 +  ** and send them to the callback one by one.
  1.3404 +  */
  1.3405 +  if( pOrderBy ){
  1.3406 +    generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm);
  1.3407 +  }
  1.3408 +
  1.3409 +#ifndef SQLITE_OMIT_SUBQUERY
  1.3410 +  /* If this was a subquery, we have now converted the subquery into a
  1.3411 +  ** temporary table.  So set the SrcList_item.isPopulated flag to prevent
  1.3412 +  ** this subquery from being evaluated again and to force the use of
  1.3413 +  ** the temporary table.
  1.3414 +  */
  1.3415 +  if( pParent ){
  1.3416 +    assert( pParent->pSrc->nSrc>parentTab );
  1.3417 +    assert( pParent->pSrc->a[parentTab].pSelect==p );
  1.3418 +    pParent->pSrc->a[parentTab].isPopulated = 1;
  1.3419 +  }
  1.3420 +#endif
  1.3421 +
  1.3422 +  /* Jump here to skip this query
  1.3423 +  */
  1.3424 +  sqlite3VdbeResolveLabel(v, iEnd);
  1.3425 +
  1.3426 +  /* The SELECT was successfully coded.   Set the return code to 0
  1.3427 +  ** to indicate no errors.
  1.3428 +  */
  1.3429 +  rc = 0;
  1.3430 +
  1.3431 +  /* Control jumps to here if an error is encountered above, or upon
  1.3432 +  ** successful coding of the SELECT.
  1.3433 +  */
  1.3434 +select_end:
  1.3435 +
  1.3436 +  /* Identify column names if we will be using them in a callback.  This
  1.3437 +  ** step is skipped if the output is going to some other destination.
  1.3438 +  */
  1.3439 +  if( rc==SQLITE_OK && eDest==SRT_Callback ){
  1.3440 +    generateColumnNames(pParse, pTabList, pEList);
  1.3441 +  }
  1.3442 +
  1.3443 +  sqlite3_free(sAggInfo.aCol);
  1.3444 +  sqlite3_free(sAggInfo.aFunc);
  1.3445 +  return rc;
  1.3446 +}
  1.3447 +
  1.3448 +#if defined(SQLITE_DEBUG)
  1.3449 +/*
  1.3450 +*******************************************************************************
  1.3451 +** The following code is used for testing and debugging only.  The code
  1.3452 +** that follows does not appear in normal builds.
  1.3453 +**
  1.3454 +** These routines are used to print out the content of all or part of a 
  1.3455 +** parse structures such as Select or Expr.  Such printouts are useful
  1.3456 +** for helping to understand what is happening inside the code generator
  1.3457 +** during the execution of complex SELECT statements.
  1.3458 +**
  1.3459 +** These routine are not called anywhere from within the normal
  1.3460 +** code base.  Then are intended to be called from within the debugger
  1.3461 +** or from temporary "printf" statements inserted for debugging.
  1.3462 +*/
  1.3463 +void sqlite3PrintExpr(Expr *p){
  1.3464 +  if( p->token.z && p->token.n>0 ){
  1.3465 +    sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
  1.3466 +  }else{
  1.3467 +    sqlite3DebugPrintf("(%d", p->op);
  1.3468 +  }
  1.3469 +  if( p->pLeft ){
  1.3470 +    sqlite3DebugPrintf(" ");
  1.3471 +    sqlite3PrintExpr(p->pLeft);
  1.3472 +  }
  1.3473 +  if( p->pRight ){
  1.3474 +    sqlite3DebugPrintf(" ");
  1.3475 +    sqlite3PrintExpr(p->pRight);
  1.3476 +  }
  1.3477 +  sqlite3DebugPrintf(")");
  1.3478 +}
  1.3479 +void sqlite3PrintExprList(ExprList *pList){
  1.3480 +  int i;
  1.3481 +  for(i=0; i<pList->nExpr; i++){
  1.3482 +    sqlite3PrintExpr(pList->a[i].pExpr);
  1.3483 +    if( i<pList->nExpr-1 ){
  1.3484 +      sqlite3DebugPrintf(", ");
  1.3485 +    }
  1.3486 +  }
  1.3487 +}
  1.3488 +void sqlite3PrintSelect(Select *p, int indent){
  1.3489 +  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  1.3490 +  sqlite3PrintExprList(p->pEList);
  1.3491 +  sqlite3DebugPrintf("\n");
  1.3492 +  if( p->pSrc ){
  1.3493 +    char *zPrefix;
  1.3494 +    int i;
  1.3495 +    zPrefix = "FROM";
  1.3496 +    for(i=0; i<p->pSrc->nSrc; i++){
  1.3497 +      struct SrcList_item *pItem = &p->pSrc->a[i];
  1.3498 +      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
  1.3499 +      zPrefix = "";
  1.3500 +      if( pItem->pSelect ){
  1.3501 +        sqlite3DebugPrintf("(\n");
  1.3502 +        sqlite3PrintSelect(pItem->pSelect, indent+10);
  1.3503 +        sqlite3DebugPrintf("%*s)", indent+8, "");
  1.3504 +      }else if( pItem->zName ){
  1.3505 +        sqlite3DebugPrintf("%s", pItem->zName);
  1.3506 +      }
  1.3507 +      if( pItem->pTab ){
  1.3508 +        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
  1.3509 +      }
  1.3510 +      if( pItem->zAlias ){
  1.3511 +        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
  1.3512 +      }
  1.3513 +      if( i<p->pSrc->nSrc-1 ){
  1.3514 +        sqlite3DebugPrintf(",");
  1.3515 +      }
  1.3516 +      sqlite3DebugPrintf("\n");
  1.3517 +    }
  1.3518 +  }
  1.3519 +  if( p->pWhere ){
  1.3520 +    sqlite3DebugPrintf("%*s WHERE ", indent, "");
  1.3521 +    sqlite3PrintExpr(p->pWhere);
  1.3522 +    sqlite3DebugPrintf("\n");
  1.3523 +  }
  1.3524 +  if( p->pGroupBy ){
  1.3525 +    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
  1.3526 +    sqlite3PrintExprList(p->pGroupBy);
  1.3527 +    sqlite3DebugPrintf("\n");
  1.3528 +  }
  1.3529 +  if( p->pHaving ){
  1.3530 +    sqlite3DebugPrintf("%*s HAVING ", indent, "");
  1.3531 +    sqlite3PrintExpr(p->pHaving);
  1.3532 +    sqlite3DebugPrintf("\n");
  1.3533 +  }
  1.3534 +  if( p->pOrderBy ){
  1.3535 +    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
  1.3536 +    sqlite3PrintExprList(p->pOrderBy);
  1.3537 +    sqlite3DebugPrintf("\n");
  1.3538 +  }
  1.3539 +}
  1.3540 +/* End of the structure debug printing code
  1.3541 +*****************************************************************************/
  1.3542 +#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */