os/persistentdata/persistentstorage/sql/SQLite364/select.c
changeset 0 bde4ae8d615e
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/os/persistentdata/persistentstorage/sql/SQLite364/select.c	Fri Jun 15 03:10:57 2012 +0200
     1.3 @@ -0,0 +1,4123 @@
     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: select.c,v 1.480 2008/10/07 19:53:14 drh Exp $
    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(sqlite3 *db, Select *p){
    1.28 +  sqlite3ExprListDelete(db, p->pEList);
    1.29 +  sqlite3SrcListDelete(db, p->pSrc);
    1.30 +  sqlite3ExprDelete(db, p->pWhere);
    1.31 +  sqlite3ExprListDelete(db, p->pGroupBy);
    1.32 +  sqlite3ExprDelete(db, p->pHaving);
    1.33 +  sqlite3ExprListDelete(db, p->pOrderBy);
    1.34 +  sqlite3SelectDelete(db, p->pPrior);
    1.35 +  sqlite3ExprDelete(db, p->pLimit);
    1.36 +  sqlite3ExprDelete(db, p->pOffset);
    1.37 +}
    1.38 +
    1.39 +/*
    1.40 +** Initialize a SelectDest structure.
    1.41 +*/
    1.42 +void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
    1.43 +  pDest->eDest = eDest;
    1.44 +  pDest->iParm = iParm;
    1.45 +  pDest->affinity = 0;
    1.46 +  pDest->iMem = 0;
    1.47 +  pDest->nMem = 0;
    1.48 +}
    1.49 +
    1.50 +
    1.51 +/*
    1.52 +** Allocate a new Select structure and return a pointer to that
    1.53 +** structure.
    1.54 +*/
    1.55 +Select *sqlite3SelectNew(
    1.56 +  Parse *pParse,        /* Parsing context */
    1.57 +  ExprList *pEList,     /* which columns to include in the result */
    1.58 +  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
    1.59 +  Expr *pWhere,         /* the WHERE clause */
    1.60 +  ExprList *pGroupBy,   /* the GROUP BY clause */
    1.61 +  Expr *pHaving,        /* the HAVING clause */
    1.62 +  ExprList *pOrderBy,   /* the ORDER BY clause */
    1.63 +  int isDistinct,       /* true if the DISTINCT keyword is present */
    1.64 +  Expr *pLimit,         /* LIMIT value.  NULL means not used */
    1.65 +  Expr *pOffset         /* OFFSET value.  NULL means no offset */
    1.66 +){
    1.67 +  Select *pNew;
    1.68 +  Select standin;
    1.69 +  sqlite3 *db = pParse->db;
    1.70 +  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
    1.71 +  assert( !pOffset || pLimit );   /* Can't have OFFSET without LIMIT. */
    1.72 +  if( pNew==0 ){
    1.73 +    pNew = &standin;
    1.74 +    memset(pNew, 0, sizeof(*pNew));
    1.75 +  }
    1.76 +  if( pEList==0 ){
    1.77 +    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0,0,0), 0);
    1.78 +  }
    1.79 +  pNew->pEList = pEList;
    1.80 +  pNew->pSrc = pSrc;
    1.81 +  pNew->pWhere = pWhere;
    1.82 +  pNew->pGroupBy = pGroupBy;
    1.83 +  pNew->pHaving = pHaving;
    1.84 +  pNew->pOrderBy = pOrderBy;
    1.85 +  pNew->selFlags = isDistinct ? SF_Distinct : 0;
    1.86 +  pNew->op = TK_SELECT;
    1.87 +  pNew->pLimit = pLimit;
    1.88 +  pNew->pOffset = pOffset;
    1.89 +  pNew->addrOpenEphm[0] = -1;
    1.90 +  pNew->addrOpenEphm[1] = -1;
    1.91 +  pNew->addrOpenEphm[2] = -1;
    1.92 +  if( db->mallocFailed ) {
    1.93 +    clearSelect(db, pNew);
    1.94 +    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
    1.95 +    pNew = 0;
    1.96 +  }
    1.97 +  return pNew;
    1.98 +}
    1.99 +
   1.100 +/*
   1.101 +** Delete the given Select structure and all of its substructures.
   1.102 +*/
   1.103 +void sqlite3SelectDelete(sqlite3 *db, Select *p){
   1.104 +  if( p ){
   1.105 +    clearSelect(db, p);
   1.106 +    sqlite3DbFree(db, p);
   1.107 +  }
   1.108 +}
   1.109 +
   1.110 +/*
   1.111 +** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
   1.112 +** type of join.  Return an integer constant that expresses that type
   1.113 +** in terms of the following bit values:
   1.114 +**
   1.115 +**     JT_INNER
   1.116 +**     JT_CROSS
   1.117 +**     JT_OUTER
   1.118 +**     JT_NATURAL
   1.119 +**     JT_LEFT
   1.120 +**     JT_RIGHT
   1.121 +**
   1.122 +** A full outer join is the combination of JT_LEFT and JT_RIGHT.
   1.123 +**
   1.124 +** If an illegal or unsupported join type is seen, then still return
   1.125 +** a join type, but put an error in the pParse structure.
   1.126 +*/
   1.127 +int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
   1.128 +  int jointype = 0;
   1.129 +  Token *apAll[3];
   1.130 +  Token *p;
   1.131 +  static const struct {
   1.132 +    const char zKeyword[8];
   1.133 +    u8 nChar;
   1.134 +    u8 code;
   1.135 +  } keywords[] = {
   1.136 +    { "natural", 7, JT_NATURAL },
   1.137 +    { "left",    4, JT_LEFT|JT_OUTER },
   1.138 +    { "right",   5, JT_RIGHT|JT_OUTER },
   1.139 +    { "full",    4, JT_LEFT|JT_RIGHT|JT_OUTER },
   1.140 +    { "outer",   5, JT_OUTER },
   1.141 +    { "inner",   5, JT_INNER },
   1.142 +    { "cross",   5, JT_INNER|JT_CROSS },
   1.143 +  };
   1.144 +  int i, j;
   1.145 +  apAll[0] = pA;
   1.146 +  apAll[1] = pB;
   1.147 +  apAll[2] = pC;
   1.148 +  for(i=0; i<3 && apAll[i]; i++){
   1.149 +    p = apAll[i];
   1.150 +    for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
   1.151 +      if( p->n==keywords[j].nChar 
   1.152 +          && sqlite3StrNICmp((char*)p->z, keywords[j].zKeyword, p->n)==0 ){
   1.153 +        jointype |= keywords[j].code;
   1.154 +        break;
   1.155 +      }
   1.156 +    }
   1.157 +    if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
   1.158 +      jointype |= JT_ERROR;
   1.159 +      break;
   1.160 +    }
   1.161 +  }
   1.162 +  if(
   1.163 +     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
   1.164 +     (jointype & JT_ERROR)!=0
   1.165 +  ){
   1.166 +    const char *zSp = " ";
   1.167 +    assert( pB!=0 );
   1.168 +    if( pC==0 ){ zSp++; }
   1.169 +    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
   1.170 +       "%T %T%s%T", pA, pB, zSp, pC);
   1.171 +    jointype = JT_INNER;
   1.172 +  }else if( jointype & JT_RIGHT ){
   1.173 +    sqlite3ErrorMsg(pParse, 
   1.174 +      "RIGHT and FULL OUTER JOINs are not currently supported");
   1.175 +    jointype = JT_INNER;
   1.176 +  }
   1.177 +  return jointype;
   1.178 +}
   1.179 +
   1.180 +/*
   1.181 +** Return the index of a column in a table.  Return -1 if the column
   1.182 +** is not contained in the table.
   1.183 +*/
   1.184 +static int columnIndex(Table *pTab, const char *zCol){
   1.185 +  int i;
   1.186 +  for(i=0; i<pTab->nCol; i++){
   1.187 +    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
   1.188 +  }
   1.189 +  return -1;
   1.190 +}
   1.191 +
   1.192 +/*
   1.193 +** Set the value of a token to a '\000'-terminated string.
   1.194 +*/
   1.195 +static void setToken(Token *p, const char *z){
   1.196 +  p->z = (u8*)z;
   1.197 +  p->n = z ? strlen(z) : 0;
   1.198 +  p->dyn = 0;
   1.199 +}
   1.200 +
   1.201 +/*
   1.202 +** Set the token to the double-quoted and escaped version of the string pointed
   1.203 +** to by z. For example;
   1.204 +**
   1.205 +**    {a"bc}  ->  {"a""bc"}
   1.206 +*/
   1.207 +static void setQuotedToken(Parse *pParse, Token *p, const char *z){
   1.208 +
   1.209 +  /* Check if the string appears to be quoted using "..." or `...`
   1.210 +  ** or [...] or '...' or if the string contains any " characters.  
   1.211 +  ** If it does, then record a version of the string with the special
   1.212 +  ** characters escaped.
   1.213 +  */
   1.214 +  const char *z2 = z;
   1.215 +  if( *z2!='[' && *z2!='`' && *z2!='\'' ){
   1.216 +    while( *z2 ){
   1.217 +      if( *z2=='"' ) break;
   1.218 +      z2++;
   1.219 +    }
   1.220 +  }
   1.221 +
   1.222 +  if( *z2 ){
   1.223 +    /* String contains " characters - copy and quote the string. */
   1.224 +    p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z);
   1.225 +    if( p->z ){
   1.226 +      p->n = strlen((char *)p->z);
   1.227 +      p->dyn = 1;
   1.228 +    }
   1.229 +  }else{
   1.230 +    /* String contains no " characters - copy the pointer. */
   1.231 +    p->z = (u8*)z;
   1.232 +    p->n = (z2 - z);
   1.233 +    p->dyn = 0;
   1.234 +  }
   1.235 +}
   1.236 +
   1.237 +/*
   1.238 +** Create an expression node for an identifier with the name of zName
   1.239 +*/
   1.240 +Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){
   1.241 +  Token dummy;
   1.242 +  setToken(&dummy, zName);
   1.243 +  return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy);
   1.244 +}
   1.245 +
   1.246 +/*
   1.247 +** Add a term to the WHERE expression in *ppExpr that requires the
   1.248 +** zCol column to be equal in the two tables pTab1 and pTab2.
   1.249 +*/
   1.250 +static void addWhereTerm(
   1.251 +  Parse *pParse,           /* Parsing context */
   1.252 +  const char *zCol,        /* Name of the column */
   1.253 +  const Table *pTab1,      /* First table */
   1.254 +  const char *zAlias1,     /* Alias for first table.  May be NULL */
   1.255 +  const Table *pTab2,      /* Second table */
   1.256 +  const char *zAlias2,     /* Alias for second table.  May be NULL */
   1.257 +  int iRightJoinTable,     /* VDBE cursor for the right table */
   1.258 +  Expr **ppExpr,           /* Add the equality term to this expression */
   1.259 +  int isOuterJoin          /* True if dealing with an OUTER join */
   1.260 +){
   1.261 +  Expr *pE1a, *pE1b, *pE1c;
   1.262 +  Expr *pE2a, *pE2b, *pE2c;
   1.263 +  Expr *pE;
   1.264 +
   1.265 +  pE1a = sqlite3CreateIdExpr(pParse, zCol);
   1.266 +  pE2a = sqlite3CreateIdExpr(pParse, zCol);
   1.267 +  if( zAlias1==0 ){
   1.268 +    zAlias1 = pTab1->zName;
   1.269 +  }
   1.270 +  pE1b = sqlite3CreateIdExpr(pParse, zAlias1);
   1.271 +  if( zAlias2==0 ){
   1.272 +    zAlias2 = pTab2->zName;
   1.273 +  }
   1.274 +  pE2b = sqlite3CreateIdExpr(pParse, zAlias2);
   1.275 +  pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0);
   1.276 +  pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0);
   1.277 +  pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0);
   1.278 +  if( pE && isOuterJoin ){
   1.279 +    ExprSetProperty(pE, EP_FromJoin);
   1.280 +    pE->iRightJoinTable = iRightJoinTable;
   1.281 +  }
   1.282 +  *ppExpr = sqlite3ExprAnd(pParse->db,*ppExpr, pE);
   1.283 +}
   1.284 +
   1.285 +/*
   1.286 +** Set the EP_FromJoin property on all terms of the given expression.
   1.287 +** And set the Expr.iRightJoinTable to iTable for every term in the
   1.288 +** expression.
   1.289 +**
   1.290 +** The EP_FromJoin property is used on terms of an expression to tell
   1.291 +** the LEFT OUTER JOIN processing logic that this term is part of the
   1.292 +** join restriction specified in the ON or USING clause and not a part
   1.293 +** of the more general WHERE clause.  These terms are moved over to the
   1.294 +** WHERE clause during join processing but we need to remember that they
   1.295 +** originated in the ON or USING clause.
   1.296 +**
   1.297 +** The Expr.iRightJoinTable tells the WHERE clause processing that the
   1.298 +** expression depends on table iRightJoinTable even if that table is not
   1.299 +** explicitly mentioned in the expression.  That information is needed
   1.300 +** for cases like this:
   1.301 +**
   1.302 +**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
   1.303 +**
   1.304 +** The where clause needs to defer the handling of the t1.x=5
   1.305 +** term until after the t2 loop of the join.  In that way, a
   1.306 +** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
   1.307 +** defer the handling of t1.x=5, it will be processed immediately
   1.308 +** after the t1 loop and rows with t1.x!=5 will never appear in
   1.309 +** the output, which is incorrect.
   1.310 +*/
   1.311 +static void setJoinExpr(Expr *p, int iTable){
   1.312 +  while( p ){
   1.313 +    ExprSetProperty(p, EP_FromJoin);
   1.314 +    p->iRightJoinTable = iTable;
   1.315 +    setJoinExpr(p->pLeft, iTable);
   1.316 +    p = p->pRight;
   1.317 +  } 
   1.318 +}
   1.319 +
   1.320 +/*
   1.321 +** This routine processes the join information for a SELECT statement.
   1.322 +** ON and USING clauses are converted into extra terms of the WHERE clause.
   1.323 +** NATURAL joins also create extra WHERE clause terms.
   1.324 +**
   1.325 +** The terms of a FROM clause are contained in the Select.pSrc structure.
   1.326 +** The left most table is the first entry in Select.pSrc.  The right-most
   1.327 +** table is the last entry.  The join operator is held in the entry to
   1.328 +** the left.  Thus entry 0 contains the join operator for the join between
   1.329 +** entries 0 and 1.  Any ON or USING clauses associated with the join are
   1.330 +** also attached to the left entry.
   1.331 +**
   1.332 +** This routine returns the number of errors encountered.
   1.333 +*/
   1.334 +static int sqliteProcessJoin(Parse *pParse, Select *p){
   1.335 +  SrcList *pSrc;                  /* All tables in the FROM clause */
   1.336 +  int i, j;                       /* Loop counters */
   1.337 +  struct SrcList_item *pLeft;     /* Left table being joined */
   1.338 +  struct SrcList_item *pRight;    /* Right table being joined */
   1.339 +
   1.340 +  pSrc = p->pSrc;
   1.341 +  pLeft = &pSrc->a[0];
   1.342 +  pRight = &pLeft[1];
   1.343 +  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
   1.344 +    Table *pLeftTab = pLeft->pTab;
   1.345 +    Table *pRightTab = pRight->pTab;
   1.346 +    int isOuter;
   1.347 +
   1.348 +    if( pLeftTab==0 || pRightTab==0 ) continue;
   1.349 +    isOuter = (pRight->jointype & JT_OUTER)!=0;
   1.350 +
   1.351 +    /* When the NATURAL keyword is present, add WHERE clause terms for
   1.352 +    ** every column that the two tables have in common.
   1.353 +    */
   1.354 +    if( pRight->jointype & JT_NATURAL ){
   1.355 +      if( pRight->pOn || pRight->pUsing ){
   1.356 +        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
   1.357 +           "an ON or USING clause", 0);
   1.358 +        return 1;
   1.359 +      }
   1.360 +      for(j=0; j<pLeftTab->nCol; j++){
   1.361 +        char *zName = pLeftTab->aCol[j].zName;
   1.362 +        if( columnIndex(pRightTab, zName)>=0 ){
   1.363 +          addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
   1.364 +                              pRightTab, pRight->zAlias,
   1.365 +                              pRight->iCursor, &p->pWhere, isOuter);
   1.366 +          
   1.367 +        }
   1.368 +      }
   1.369 +    }
   1.370 +
   1.371 +    /* Disallow both ON and USING clauses in the same join
   1.372 +    */
   1.373 +    if( pRight->pOn && pRight->pUsing ){
   1.374 +      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
   1.375 +        "clauses in the same join");
   1.376 +      return 1;
   1.377 +    }
   1.378 +
   1.379 +    /* Add the ON clause to the end of the WHERE clause, connected by
   1.380 +    ** an AND operator.
   1.381 +    */
   1.382 +    if( pRight->pOn ){
   1.383 +      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
   1.384 +      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
   1.385 +      pRight->pOn = 0;
   1.386 +    }
   1.387 +
   1.388 +    /* Create extra terms on the WHERE clause for each column named
   1.389 +    ** in the USING clause.  Example: If the two tables to be joined are 
   1.390 +    ** A and B and the USING clause names X, Y, and Z, then add this
   1.391 +    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
   1.392 +    ** Report an error if any column mentioned in the USING clause is
   1.393 +    ** not contained in both tables to be joined.
   1.394 +    */
   1.395 +    if( pRight->pUsing ){
   1.396 +      IdList *pList = pRight->pUsing;
   1.397 +      for(j=0; j<pList->nId; j++){
   1.398 +        char *zName = pList->a[j].zName;
   1.399 +        if( columnIndex(pLeftTab, zName)<0 || columnIndex(pRightTab, zName)<0 ){
   1.400 +          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
   1.401 +            "not present in both tables", zName);
   1.402 +          return 1;
   1.403 +        }
   1.404 +        addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, 
   1.405 +                            pRightTab, pRight->zAlias,
   1.406 +                            pRight->iCursor, &p->pWhere, isOuter);
   1.407 +      }
   1.408 +    }
   1.409 +  }
   1.410 +  return 0;
   1.411 +}
   1.412 +
   1.413 +/*
   1.414 +** Insert code into "v" that will push the record on the top of the
   1.415 +** stack into the sorter.
   1.416 +*/
   1.417 +static void pushOntoSorter(
   1.418 +  Parse *pParse,         /* Parser context */
   1.419 +  ExprList *pOrderBy,    /* The ORDER BY clause */
   1.420 +  Select *pSelect,       /* The whole SELECT statement */
   1.421 +  int regData            /* Register holding data to be sorted */
   1.422 +){
   1.423 +  Vdbe *v = pParse->pVdbe;
   1.424 +  int nExpr = pOrderBy->nExpr;
   1.425 +  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
   1.426 +  int regRecord = sqlite3GetTempReg(pParse);
   1.427 +  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
   1.428 +  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
   1.429 +  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
   1.430 +  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
   1.431 +  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
   1.432 +  sqlite3ReleaseTempReg(pParse, regRecord);
   1.433 +  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
   1.434 +  if( pSelect->iLimit ){
   1.435 +    int addr1, addr2;
   1.436 +    int iLimit;
   1.437 +    if( pSelect->iOffset ){
   1.438 +      iLimit = pSelect->iOffset+1;
   1.439 +    }else{
   1.440 +      iLimit = pSelect->iLimit;
   1.441 +    }
   1.442 +    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
   1.443 +    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   1.444 +    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   1.445 +    sqlite3VdbeJumpHere(v, addr1);
   1.446 +    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
   1.447 +    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
   1.448 +    sqlite3VdbeJumpHere(v, addr2);
   1.449 +    pSelect->iLimit = 0;
   1.450 +  }
   1.451 +}
   1.452 +
   1.453 +/*
   1.454 +** Add code to implement the OFFSET
   1.455 +*/
   1.456 +static void codeOffset(
   1.457 +  Vdbe *v,          /* Generate code into this VM */
   1.458 +  Select *p,        /* The SELECT statement being coded */
   1.459 +  int iContinue     /* Jump here to skip the current record */
   1.460 +){
   1.461 +  if( p->iOffset && iContinue!=0 ){
   1.462 +    int addr;
   1.463 +    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
   1.464 +    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
   1.465 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   1.466 +    VdbeComment((v, "skip OFFSET records"));
   1.467 +    sqlite3VdbeJumpHere(v, addr);
   1.468 +  }
   1.469 +}
   1.470 +
   1.471 +/*
   1.472 +** Add code that will check to make sure the N registers starting at iMem
   1.473 +** form a distinct entry.  iTab is a sorting index that holds previously
   1.474 +** seen combinations of the N values.  A new entry is made in iTab
   1.475 +** if the current N values are new.
   1.476 +**
   1.477 +** A jump to addrRepeat is made and the N+1 values are popped from the
   1.478 +** stack if the top N elements are not distinct.
   1.479 +*/
   1.480 +static void codeDistinct(
   1.481 +  Parse *pParse,     /* Parsing and code generating context */
   1.482 +  int iTab,          /* A sorting index used to test for distinctness */
   1.483 +  int addrRepeat,    /* Jump to here if not distinct */
   1.484 +  int N,             /* Number of elements */
   1.485 +  int iMem           /* First element */
   1.486 +){
   1.487 +  Vdbe *v;
   1.488 +  int r1;
   1.489 +
   1.490 +  v = pParse->pVdbe;
   1.491 +  r1 = sqlite3GetTempReg(pParse);
   1.492 +  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   1.493 +  sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1);
   1.494 +  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   1.495 +  sqlite3ReleaseTempReg(pParse, r1);
   1.496 +}
   1.497 +
   1.498 +/*
   1.499 +** Generate an error message when a SELECT is used within a subexpression
   1.500 +** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
   1.501 +** column.  We do this in a subroutine because the error occurs in multiple
   1.502 +** places.
   1.503 +*/
   1.504 +static int checkForMultiColumnSelectError(
   1.505 +  Parse *pParse,       /* Parse context. */
   1.506 +  SelectDest *pDest,   /* Destination of SELECT results */
   1.507 +  int nExpr            /* Number of result columns returned by SELECT */
   1.508 +){
   1.509 +  int eDest = pDest->eDest;
   1.510 +  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
   1.511 +    sqlite3ErrorMsg(pParse, "only a single result allowed for "
   1.512 +       "a SELECT that is part of an expression");
   1.513 +    return 1;
   1.514 +  }else{
   1.515 +    return 0;
   1.516 +  }
   1.517 +}
   1.518 +
   1.519 +/*
   1.520 +** This routine generates the code for the inside of the inner loop
   1.521 +** of a SELECT.
   1.522 +**
   1.523 +** If srcTab and nColumn are both zero, then the pEList expressions
   1.524 +** are evaluated in order to get the data for this row.  If nColumn>0
   1.525 +** then data is pulled from srcTab and pEList is used only to get the
   1.526 +** datatypes for each column.
   1.527 +*/
   1.528 +static void selectInnerLoop(
   1.529 +  Parse *pParse,          /* The parser context */
   1.530 +  Select *p,              /* The complete select statement being coded */
   1.531 +  ExprList *pEList,       /* List of values being extracted */
   1.532 +  int srcTab,             /* Pull data from this table */
   1.533 +  int nColumn,            /* Number of columns in the source table */
   1.534 +  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
   1.535 +  int distinct,           /* If >=0, make sure results are distinct */
   1.536 +  SelectDest *pDest,      /* How to dispose of the results */
   1.537 +  int iContinue,          /* Jump here to continue with next row */
   1.538 +  int iBreak              /* Jump here to break out of the inner loop */
   1.539 +){
   1.540 +  Vdbe *v = pParse->pVdbe;
   1.541 +  int i;
   1.542 +  int hasDistinct;        /* True if the DISTINCT keyword is present */
   1.543 +  int regResult;              /* Start of memory holding result set */
   1.544 +  int eDest = pDest->eDest;   /* How to dispose of results */
   1.545 +  int iParm = pDest->iParm;   /* First argument to disposal method */
   1.546 +  int nResultCol;             /* Number of result columns */
   1.547 +
   1.548 +  if( v==0 ) return;
   1.549 +  assert( pEList!=0 );
   1.550 +  hasDistinct = distinct>=0;
   1.551 +  if( pOrderBy==0 && !hasDistinct ){
   1.552 +    codeOffset(v, p, iContinue);
   1.553 +  }
   1.554 +
   1.555 +  /* Pull the requested columns.
   1.556 +  */
   1.557 +  if( nColumn>0 ){
   1.558 +    nResultCol = nColumn;
   1.559 +  }else{
   1.560 +    nResultCol = pEList->nExpr;
   1.561 +  }
   1.562 +  if( pDest->iMem==0 ){
   1.563 +    pDest->iMem = pParse->nMem+1;
   1.564 +    pDest->nMem = nResultCol;
   1.565 +    pParse->nMem += nResultCol;
   1.566 +  }else if( pDest->nMem!=nResultCol ){
   1.567 +    /* This happens when two SELECTs of a compound SELECT have differing
   1.568 +    ** numbers of result columns.  The error message will be generated by
   1.569 +    ** a higher-level routine. */
   1.570 +    return;
   1.571 +  }
   1.572 +  regResult = pDest->iMem;
   1.573 +  if( nColumn>0 ){
   1.574 +    for(i=0; i<nColumn; i++){
   1.575 +      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   1.576 +    }
   1.577 +  }else if( eDest!=SRT_Exists ){
   1.578 +    /* If the destination is an EXISTS(...) expression, the actual
   1.579 +    ** values returned by the SELECT are not required.
   1.580 +    */
   1.581 +    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
   1.582 +  }
   1.583 +  nColumn = nResultCol;
   1.584 +
   1.585 +  /* If the DISTINCT keyword was present on the SELECT statement
   1.586 +  ** and this row has been seen before, then do not make this row
   1.587 +  ** part of the result.
   1.588 +  */
   1.589 +  if( hasDistinct ){
   1.590 +    assert( pEList!=0 );
   1.591 +    assert( pEList->nExpr==nColumn );
   1.592 +    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
   1.593 +    if( pOrderBy==0 ){
   1.594 +      codeOffset(v, p, iContinue);
   1.595 +    }
   1.596 +  }
   1.597 +
   1.598 +  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
   1.599 +    return;
   1.600 +  }
   1.601 +
   1.602 +  switch( eDest ){
   1.603 +    /* In this mode, write each query result to the key of the temporary
   1.604 +    ** table iParm.
   1.605 +    */
   1.606 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
   1.607 +    case SRT_Union: {
   1.608 +      int r1;
   1.609 +      r1 = sqlite3GetTempReg(pParse);
   1.610 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   1.611 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   1.612 +      sqlite3ReleaseTempReg(pParse, r1);
   1.613 +      break;
   1.614 +    }
   1.615 +
   1.616 +    /* Construct a record from the query result, but instead of
   1.617 +    ** saving that record, use it as a key to delete elements from
   1.618 +    ** the temporary table iParm.
   1.619 +    */
   1.620 +    case SRT_Except: {
   1.621 +      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
   1.622 +      break;
   1.623 +    }
   1.624 +#endif
   1.625 +
   1.626 +    /* Store the result as data using a unique key.
   1.627 +    */
   1.628 +    case SRT_Table:
   1.629 +    case SRT_EphemTab: {
   1.630 +      int r1 = sqlite3GetTempReg(pParse);
   1.631 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   1.632 +      if( pOrderBy ){
   1.633 +        pushOntoSorter(pParse, pOrderBy, p, r1);
   1.634 +      }else{
   1.635 +        int r2 = sqlite3GetTempReg(pParse);
   1.636 +        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
   1.637 +        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
   1.638 +        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   1.639 +        sqlite3ReleaseTempReg(pParse, r2);
   1.640 +      }
   1.641 +      sqlite3ReleaseTempReg(pParse, r1);
   1.642 +      break;
   1.643 +    }
   1.644 +
   1.645 +#ifndef SQLITE_OMIT_SUBQUERY
   1.646 +    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
   1.647 +    ** then there should be a single item on the stack.  Write this
   1.648 +    ** item into the set table with bogus data.
   1.649 +    */
   1.650 +    case SRT_Set: {
   1.651 +      assert( nColumn==1 );
   1.652 +      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
   1.653 +      if( pOrderBy ){
   1.654 +        /* At first glance you would think we could optimize out the
   1.655 +        ** ORDER BY in this case since the order of entries in the set
   1.656 +        ** does not matter.  But there might be a LIMIT clause, in which
   1.657 +        ** case the order does matter */
   1.658 +        pushOntoSorter(pParse, pOrderBy, p, regResult);
   1.659 +      }else{
   1.660 +        int r1 = sqlite3GetTempReg(pParse);
   1.661 +        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
   1.662 +        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
   1.663 +        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
   1.664 +        sqlite3ReleaseTempReg(pParse, r1);
   1.665 +      }
   1.666 +      break;
   1.667 +    }
   1.668 +
   1.669 +    /* If any row exist in the result set, record that fact and abort.
   1.670 +    */
   1.671 +    case SRT_Exists: {
   1.672 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
   1.673 +      /* The LIMIT clause will terminate the loop for us */
   1.674 +      break;
   1.675 +    }
   1.676 +
   1.677 +    /* If this is a scalar select that is part of an expression, then
   1.678 +    ** store the results in the appropriate memory cell and break out
   1.679 +    ** of the scan loop.
   1.680 +    */
   1.681 +    case SRT_Mem: {
   1.682 +      assert( nColumn==1 );
   1.683 +      if( pOrderBy ){
   1.684 +        pushOntoSorter(pParse, pOrderBy, p, regResult);
   1.685 +      }else{
   1.686 +        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
   1.687 +        /* The LIMIT clause will jump out of the loop for us */
   1.688 +      }
   1.689 +      break;
   1.690 +    }
   1.691 +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
   1.692 +
   1.693 +    /* Send the data to the callback function or to a subroutine.  In the
   1.694 +    ** case of a subroutine, the subroutine itself is responsible for
   1.695 +    ** popping the data from the stack.
   1.696 +    */
   1.697 +    case SRT_Coroutine:
   1.698 +    case SRT_Output: {
   1.699 +      if( pOrderBy ){
   1.700 +        int r1 = sqlite3GetTempReg(pParse);
   1.701 +        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
   1.702 +        pushOntoSorter(pParse, pOrderBy, p, r1);
   1.703 +        sqlite3ReleaseTempReg(pParse, r1);
   1.704 +      }else if( eDest==SRT_Coroutine ){
   1.705 +        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   1.706 +      }else{
   1.707 +        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
   1.708 +        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
   1.709 +      }
   1.710 +      break;
   1.711 +    }
   1.712 +
   1.713 +#if !defined(SQLITE_OMIT_TRIGGER)
   1.714 +    /* Discard the results.  This is used for SELECT statements inside
   1.715 +    ** the body of a TRIGGER.  The purpose of such selects is to call
   1.716 +    ** user-defined functions that have side effects.  We do not care
   1.717 +    ** about the actual results of the select.
   1.718 +    */
   1.719 +    default: {
   1.720 +      assert( eDest==SRT_Discard );
   1.721 +      break;
   1.722 +    }
   1.723 +#endif
   1.724 +  }
   1.725 +
   1.726 +  /* Jump to the end of the loop if the LIMIT is reached.
   1.727 +  */
   1.728 +  if( p->iLimit ){
   1.729 +    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
   1.730 +                            ** pushOntoSorter() would have cleared p->iLimit */
   1.731 +    sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
   1.732 +    sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
   1.733 +  }
   1.734 +}
   1.735 +
   1.736 +/*
   1.737 +** Given an expression list, generate a KeyInfo structure that records
   1.738 +** the collating sequence for each expression in that expression list.
   1.739 +**
   1.740 +** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   1.741 +** KeyInfo structure is appropriate for initializing a virtual index to
   1.742 +** implement that clause.  If the ExprList is the result set of a SELECT
   1.743 +** then the KeyInfo structure is appropriate for initializing a virtual
   1.744 +** index to implement a DISTINCT test.
   1.745 +**
   1.746 +** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   1.747 +** function is responsible for seeing that this structure is eventually
   1.748 +** freed.  Add the KeyInfo structure to the P4 field of an opcode using
   1.749 +** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
   1.750 +*/
   1.751 +static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
   1.752 +  sqlite3 *db = pParse->db;
   1.753 +  int nExpr;
   1.754 +  KeyInfo *pInfo;
   1.755 +  struct ExprList_item *pItem;
   1.756 +  int i;
   1.757 +
   1.758 +  nExpr = pList->nExpr;
   1.759 +  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
   1.760 +  if( pInfo ){
   1.761 +    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
   1.762 +    pInfo->nField = nExpr;
   1.763 +    pInfo->enc = ENC(db);
   1.764 +    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
   1.765 +      CollSeq *pColl;
   1.766 +      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   1.767 +      if( !pColl ){
   1.768 +        pColl = db->pDfltColl;
   1.769 +      }
   1.770 +      pInfo->aColl[i] = pColl;
   1.771 +      pInfo->aSortOrder[i] = pItem->sortOrder;
   1.772 +    }
   1.773 +  }
   1.774 +  return pInfo;
   1.775 +}
   1.776 +
   1.777 +
   1.778 +/*
   1.779 +** If the inner loop was generated using a non-null pOrderBy argument,
   1.780 +** then the results were placed in a sorter.  After the loop is terminated
   1.781 +** we need to run the sorter and output the results.  The following
   1.782 +** routine generates the code needed to do that.
   1.783 +*/
   1.784 +static void generateSortTail(
   1.785 +  Parse *pParse,    /* Parsing context */
   1.786 +  Select *p,        /* The SELECT statement */
   1.787 +  Vdbe *v,          /* Generate code into this VDBE */
   1.788 +  int nColumn,      /* Number of columns of data */
   1.789 +  SelectDest *pDest /* Write the sorted results here */
   1.790 +){
   1.791 +  int brk = sqlite3VdbeMakeLabel(v);
   1.792 +  int cont = sqlite3VdbeMakeLabel(v);
   1.793 +  int addr;
   1.794 +  int iTab;
   1.795 +  int pseudoTab = 0;
   1.796 +  ExprList *pOrderBy = p->pOrderBy;
   1.797 +
   1.798 +  int eDest = pDest->eDest;
   1.799 +  int iParm = pDest->iParm;
   1.800 +
   1.801 +  int regRow;
   1.802 +  int regRowid;
   1.803 +
   1.804 +  iTab = pOrderBy->iECursor;
   1.805 +  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   1.806 +    pseudoTab = pParse->nTab++;
   1.807 +    sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn);
   1.808 +    sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Output);
   1.809 +  }
   1.810 +  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk);
   1.811 +  codeOffset(v, p, cont);
   1.812 +  regRow = sqlite3GetTempReg(pParse);
   1.813 +  regRowid = sqlite3GetTempReg(pParse);
   1.814 +  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
   1.815 +  switch( eDest ){
   1.816 +    case SRT_Table:
   1.817 +    case SRT_EphemTab: {
   1.818 +      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
   1.819 +      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
   1.820 +      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   1.821 +      break;
   1.822 +    }
   1.823 +#ifndef SQLITE_OMIT_SUBQUERY
   1.824 +    case SRT_Set: {
   1.825 +      assert( nColumn==1 );
   1.826 +      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
   1.827 +      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
   1.828 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
   1.829 +      break;
   1.830 +    }
   1.831 +    case SRT_Mem: {
   1.832 +      assert( nColumn==1 );
   1.833 +      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
   1.834 +      /* The LIMIT clause will terminate the loop for us */
   1.835 +      break;
   1.836 +    }
   1.837 +#endif
   1.838 +    case SRT_Output:
   1.839 +    case SRT_Coroutine: {
   1.840 +      int i;
   1.841 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid);
   1.842 +      sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid);
   1.843 +      for(i=0; i<nColumn; i++){
   1.844 +        assert( regRow!=pDest->iMem+i );
   1.845 +        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
   1.846 +      }
   1.847 +      if( eDest==SRT_Output ){
   1.848 +        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
   1.849 +        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
   1.850 +      }else{
   1.851 +        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
   1.852 +      }
   1.853 +      break;
   1.854 +    }
   1.855 +    default: {
   1.856 +      /* Do nothing */
   1.857 +      break;
   1.858 +    }
   1.859 +  }
   1.860 +  sqlite3ReleaseTempReg(pParse, regRow);
   1.861 +  sqlite3ReleaseTempReg(pParse, regRowid);
   1.862 +
   1.863 +  /* LIMIT has been implemented by the pushOntoSorter() routine.
   1.864 +  */
   1.865 +  assert( p->iLimit==0 );
   1.866 +
   1.867 +  /* The bottom of the loop
   1.868 +  */
   1.869 +  sqlite3VdbeResolveLabel(v, cont);
   1.870 +  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
   1.871 +  sqlite3VdbeResolveLabel(v, brk);
   1.872 +  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
   1.873 +    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
   1.874 +  }
   1.875 +
   1.876 +}
   1.877 +
   1.878 +/*
   1.879 +** Return a pointer to a string containing the 'declaration type' of the
   1.880 +** expression pExpr. The string may be treated as static by the caller.
   1.881 +**
   1.882 +** The declaration type is the exact datatype definition extracted from the
   1.883 +** original CREATE TABLE statement if the expression is a column. The
   1.884 +** declaration type for a ROWID field is INTEGER. Exactly when an expression
   1.885 +** is considered a column can be complex in the presence of subqueries. The
   1.886 +** result-set expression in all of the following SELECT statements is 
   1.887 +** considered a column by this function.
   1.888 +**
   1.889 +**   SELECT col FROM tbl;
   1.890 +**   SELECT (SELECT col FROM tbl;
   1.891 +**   SELECT (SELECT col FROM tbl);
   1.892 +**   SELECT abc FROM (SELECT col AS abc FROM tbl);
   1.893 +** 
   1.894 +** The declaration type for any expression other than a column is NULL.
   1.895 +*/
   1.896 +static const char *columnType(
   1.897 +  NameContext *pNC, 
   1.898 +  Expr *pExpr,
   1.899 +  const char **pzOriginDb,
   1.900 +  const char **pzOriginTab,
   1.901 +  const char **pzOriginCol
   1.902 +){
   1.903 +  char const *zType = 0;
   1.904 +  char const *zOriginDb = 0;
   1.905 +  char const *zOriginTab = 0;
   1.906 +  char const *zOriginCol = 0;
   1.907 +  int j;
   1.908 +  if( pExpr==0 || pNC->pSrcList==0 ) return 0;
   1.909 +
   1.910 +  switch( pExpr->op ){
   1.911 +    case TK_AGG_COLUMN:
   1.912 +    case TK_COLUMN: {
   1.913 +      /* The expression is a column. Locate the table the column is being
   1.914 +      ** extracted from in NameContext.pSrcList. This table may be real
   1.915 +      ** database table or a subquery.
   1.916 +      */
   1.917 +      Table *pTab = 0;            /* Table structure column is extracted from */
   1.918 +      Select *pS = 0;             /* Select the column is extracted from */
   1.919 +      int iCol = pExpr->iColumn;  /* Index of column in pTab */
   1.920 +      while( pNC && !pTab ){
   1.921 +        SrcList *pTabList = pNC->pSrcList;
   1.922 +        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
   1.923 +        if( j<pTabList->nSrc ){
   1.924 +          pTab = pTabList->a[j].pTab;
   1.925 +          pS = pTabList->a[j].pSelect;
   1.926 +        }else{
   1.927 +          pNC = pNC->pNext;
   1.928 +        }
   1.929 +      }
   1.930 +
   1.931 +      if( pTab==0 ){
   1.932 +        /* FIX ME:
   1.933 +        ** This can occurs if you have something like "SELECT new.x;" inside
   1.934 +        ** a trigger.  In other words, if you reference the special "new"
   1.935 +        ** table in the result set of a select.  We do not have a good way
   1.936 +        ** to find the actual table type, so call it "TEXT".  This is really
   1.937 +        ** something of a bug, but I do not know how to fix it.
   1.938 +        **
   1.939 +        ** This code does not produce the correct answer - it just prevents
   1.940 +        ** a segfault.  See ticket #1229.
   1.941 +        */
   1.942 +        zType = "TEXT";
   1.943 +        break;
   1.944 +      }
   1.945 +
   1.946 +      assert( pTab );
   1.947 +      if( pS ){
   1.948 +        /* The "table" is actually a sub-select or a view in the FROM clause
   1.949 +        ** of the SELECT statement. Return the declaration type and origin
   1.950 +        ** data for the result-set column of the sub-select.
   1.951 +        */
   1.952 +        if( iCol>=0 && iCol<pS->pEList->nExpr ){
   1.953 +          /* If iCol is less than zero, then the expression requests the
   1.954 +          ** rowid of the sub-select or view. This expression is legal (see 
   1.955 +          ** test case misc2.2.2) - it always evaluates to NULL.
   1.956 +          */
   1.957 +          NameContext sNC;
   1.958 +          Expr *p = pS->pEList->a[iCol].pExpr;
   1.959 +          sNC.pSrcList = pS->pSrc;
   1.960 +          sNC.pNext = 0;
   1.961 +          sNC.pParse = pNC->pParse;
   1.962 +          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
   1.963 +        }
   1.964 +      }else if( pTab->pSchema ){
   1.965 +        /* A real table */
   1.966 +        assert( !pS );
   1.967 +        if( iCol<0 ) iCol = pTab->iPKey;
   1.968 +        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   1.969 +        if( iCol<0 ){
   1.970 +          zType = "INTEGER";
   1.971 +          zOriginCol = "rowid";
   1.972 +        }else{
   1.973 +          zType = pTab->aCol[iCol].zType;
   1.974 +          zOriginCol = pTab->aCol[iCol].zName;
   1.975 +        }
   1.976 +        zOriginTab = pTab->zName;
   1.977 +        if( pNC->pParse ){
   1.978 +          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
   1.979 +          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
   1.980 +        }
   1.981 +      }
   1.982 +      break;
   1.983 +    }
   1.984 +#ifndef SQLITE_OMIT_SUBQUERY
   1.985 +    case TK_SELECT: {
   1.986 +      /* The expression is a sub-select. Return the declaration type and
   1.987 +      ** origin info for the single column in the result set of the SELECT
   1.988 +      ** statement.
   1.989 +      */
   1.990 +      NameContext sNC;
   1.991 +      Select *pS = pExpr->pSelect;
   1.992 +      Expr *p = pS->pEList->a[0].pExpr;
   1.993 +      sNC.pSrcList = pS->pSrc;
   1.994 +      sNC.pNext = pNC;
   1.995 +      sNC.pParse = pNC->pParse;
   1.996 +      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
   1.997 +      break;
   1.998 +    }
   1.999 +#endif
  1.1000 +  }
  1.1001 +  
  1.1002 +  if( pzOriginDb ){
  1.1003 +    assert( pzOriginTab && pzOriginCol );
  1.1004 +    *pzOriginDb = zOriginDb;
  1.1005 +    *pzOriginTab = zOriginTab;
  1.1006 +    *pzOriginCol = zOriginCol;
  1.1007 +  }
  1.1008 +  return zType;
  1.1009 +}
  1.1010 +
  1.1011 +/*
  1.1012 +** Generate code that will tell the VDBE the declaration types of columns
  1.1013 +** in the result set.
  1.1014 +*/
  1.1015 +static void generateColumnTypes(
  1.1016 +  Parse *pParse,      /* Parser context */
  1.1017 +  SrcList *pTabList,  /* List of tables */
  1.1018 +  ExprList *pEList    /* Expressions defining the result set */
  1.1019 +){
  1.1020 +#ifndef SQLITE_OMIT_DECLTYPE
  1.1021 +  Vdbe *v = pParse->pVdbe;
  1.1022 +  int i;
  1.1023 +  NameContext sNC;
  1.1024 +  sNC.pSrcList = pTabList;
  1.1025 +  sNC.pParse = pParse;
  1.1026 +  for(i=0; i<pEList->nExpr; i++){
  1.1027 +    Expr *p = pEList->a[i].pExpr;
  1.1028 +    const char *zType;
  1.1029 +#ifdef SQLITE_ENABLE_COLUMN_METADATA
  1.1030 +    const char *zOrigDb = 0;
  1.1031 +    const char *zOrigTab = 0;
  1.1032 +    const char *zOrigCol = 0;
  1.1033 +    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  1.1034 +
  1.1035 +    /* The vdbe must make its own copy of the column-type and other 
  1.1036 +    ** column specific strings, in case the schema is reset before this
  1.1037 +    ** virtual machine is deleted.
  1.1038 +    */
  1.1039 +    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT);
  1.1040 +    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT);
  1.1041 +    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT);
  1.1042 +#else
  1.1043 +    zType = columnType(&sNC, p, 0, 0, 0);
  1.1044 +#endif
  1.1045 +    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT);
  1.1046 +  }
  1.1047 +#endif /* SQLITE_OMIT_DECLTYPE */
  1.1048 +}
  1.1049 +
  1.1050 +/*
  1.1051 +** Generate code that will tell the VDBE the names of columns
  1.1052 +** in the result set.  This information is used to provide the
  1.1053 +** azCol[] values in the callback.
  1.1054 +*/
  1.1055 +static void generateColumnNames(
  1.1056 +  Parse *pParse,      /* Parser context */
  1.1057 +  SrcList *pTabList,  /* List of tables */
  1.1058 +  ExprList *pEList    /* Expressions defining the result set */
  1.1059 +){
  1.1060 +  Vdbe *v = pParse->pVdbe;
  1.1061 +  int i, j;
  1.1062 +  sqlite3 *db = pParse->db;
  1.1063 +  int fullNames, shortNames;
  1.1064 +
  1.1065 +#ifndef SQLITE_OMIT_EXPLAIN
  1.1066 +  /* If this is an EXPLAIN, skip this step */
  1.1067 +  if( pParse->explain ){
  1.1068 +    return;
  1.1069 +  }
  1.1070 +#endif
  1.1071 +
  1.1072 +  assert( v!=0 );
  1.1073 +  if( pParse->colNamesSet || v==0 || db->mallocFailed ) return;
  1.1074 +  pParse->colNamesSet = 1;
  1.1075 +  fullNames = (db->flags & SQLITE_FullColNames)!=0;
  1.1076 +  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  1.1077 +  sqlite3VdbeSetNumCols(v, pEList->nExpr);
  1.1078 +  for(i=0; i<pEList->nExpr; i++){
  1.1079 +    Expr *p;
  1.1080 +    p = pEList->a[i].pExpr;
  1.1081 +    if( p==0 ) continue;
  1.1082 +    if( pEList->a[i].zName ){
  1.1083 +      char *zName = pEList->a[i].zName;
  1.1084 +      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName));
  1.1085 +    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  1.1086 +      Table *pTab;
  1.1087 +      char *zCol;
  1.1088 +      int iCol = p->iColumn;
  1.1089 +      for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
  1.1090 +      assert( j<pTabList->nSrc );
  1.1091 +      pTab = pTabList->a[j].pTab;
  1.1092 +      if( iCol<0 ) iCol = pTab->iPKey;
  1.1093 +      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  1.1094 +      if( iCol<0 ){
  1.1095 +        zCol = "rowid";
  1.1096 +      }else{
  1.1097 +        zCol = pTab->aCol[iCol].zName;
  1.1098 +      }
  1.1099 +      if( !shortNames && !fullNames ){
  1.1100 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
  1.1101 +      }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
  1.1102 +        char *zName = 0;
  1.1103 +        char *zTab;
  1.1104 + 
  1.1105 +        zTab = pTabList->a[j].zAlias;
  1.1106 +        if( fullNames || zTab==0 ) zTab = pTab->zName;
  1.1107 +        zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol);
  1.1108 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC);
  1.1109 +      }else{
  1.1110 +        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol));
  1.1111 +      }
  1.1112 +    }else{
  1.1113 +      sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n);
  1.1114 +    }
  1.1115 +  }
  1.1116 +  generateColumnTypes(pParse, pTabList, pEList);
  1.1117 +}
  1.1118 +
  1.1119 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.1120 +/*
  1.1121 +** Name of the connection operator, used for error messages.
  1.1122 +*/
  1.1123 +static const char *selectOpName(int id){
  1.1124 +  char *z;
  1.1125 +  switch( id ){
  1.1126 +    case TK_ALL:       z = "UNION ALL";   break;
  1.1127 +    case TK_INTERSECT: z = "INTERSECT";   break;
  1.1128 +    case TK_EXCEPT:    z = "EXCEPT";      break;
  1.1129 +    default:           z = "UNION";       break;
  1.1130 +  }
  1.1131 +  return z;
  1.1132 +}
  1.1133 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1.1134 +
  1.1135 +/*
  1.1136 +** Given a an expression list (which is really the list of expressions
  1.1137 +** that form the result set of a SELECT statement) compute appropriate
  1.1138 +** column names for a table that would hold the expression list.
  1.1139 +**
  1.1140 +** All column names will be unique.
  1.1141 +**
  1.1142 +** Only the column names are computed.  Column.zType, Column.zColl,
  1.1143 +** and other fields of Column are zeroed.
  1.1144 +**
  1.1145 +** Return SQLITE_OK on success.  If a memory allocation error occurs,
  1.1146 +** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  1.1147 +*/
  1.1148 +static int selectColumnsFromExprList(
  1.1149 +  Parse *pParse,          /* Parsing context */
  1.1150 +  ExprList *pEList,       /* Expr list from which to derive column names */
  1.1151 +  int *pnCol,             /* Write the number of columns here */
  1.1152 +  Column **paCol          /* Write the new column list here */
  1.1153 +){
  1.1154 +  sqlite3 *db = pParse->db;
  1.1155 +  int i, j, cnt;
  1.1156 +  Column *aCol, *pCol;
  1.1157 +  int nCol;
  1.1158 +  Expr *p;
  1.1159 +  char *zName;
  1.1160 +  int nName;
  1.1161 +
  1.1162 +  *pnCol = nCol = pEList->nExpr;
  1.1163 +  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  1.1164 +  if( aCol==0 ) return SQLITE_NOMEM;
  1.1165 +  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  1.1166 +    /* Get an appropriate name for the column
  1.1167 +    */
  1.1168 +    p = pEList->a[i].pExpr;
  1.1169 +    assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
  1.1170 +    if( (zName = pEList->a[i].zName)!=0 ){
  1.1171 +      /* If the column contains an "AS <name>" phrase, use <name> as the name */
  1.1172 +      zName = sqlite3DbStrDup(db, zName);
  1.1173 +    }else{
  1.1174 +      Expr *pCol = p;
  1.1175 +      Table *pTab;
  1.1176 +      while( pCol->op==TK_DOT ) pCol = pCol->pRight;
  1.1177 +      if( pCol->op==TK_COLUMN && (pTab = pCol->pTab)!=0 ){
  1.1178 +        /* For columns use the column name name */
  1.1179 +        int iCol = pCol->iColumn;
  1.1180 +        if( iCol<0 ) iCol = pTab->iPKey;
  1.1181 +        zName = sqlite3MPrintf(db, "%s",
  1.1182 +                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  1.1183 +      }else{
  1.1184 +        /* Use the original text of the column expression as its name */
  1.1185 +        Token *pToken = (pCol->span.z?&pCol->span:&pCol->token);
  1.1186 +        zName = sqlite3MPrintf(db, "%T", pToken);
  1.1187 +      }
  1.1188 +    }
  1.1189 +    if( db->mallocFailed ){
  1.1190 +      sqlite3DbFree(db, zName);
  1.1191 +      break;
  1.1192 +    }
  1.1193 +    sqlite3Dequote(zName);
  1.1194 +
  1.1195 +    /* Make sure the column name is unique.  If the name is not unique,
  1.1196 +    ** append a integer to the name so that it becomes unique.
  1.1197 +    */
  1.1198 +    nName = strlen(zName);
  1.1199 +    for(j=cnt=0; j<i; j++){
  1.1200 +      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  1.1201 +        char *zNewName;
  1.1202 +        zName[nName] = 0;
  1.1203 +        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  1.1204 +        sqlite3DbFree(db, zName);
  1.1205 +        zName = zNewName;
  1.1206 +        j = -1;
  1.1207 +        if( zName==0 ) break;
  1.1208 +      }
  1.1209 +    }
  1.1210 +    pCol->zName = zName;
  1.1211 +  }
  1.1212 +  if( db->mallocFailed ){
  1.1213 +    int j;
  1.1214 +    for(j=0; j<i; j++){
  1.1215 +      sqlite3DbFree(db, aCol[j].zName);
  1.1216 +    }
  1.1217 +    sqlite3DbFree(db, aCol);
  1.1218 +    *paCol = 0;
  1.1219 +    *pnCol = 0;
  1.1220 +    return SQLITE_NOMEM;
  1.1221 +  }
  1.1222 +  return SQLITE_OK;
  1.1223 +}
  1.1224 +
  1.1225 +/*
  1.1226 +** Add type and collation information to a column list based on
  1.1227 +** a SELECT statement.
  1.1228 +** 
  1.1229 +** The column list presumably came from selectColumnNamesFromExprList().
  1.1230 +** The column list has only names, not types or collations.  This
  1.1231 +** routine goes through and adds the types and collations.
  1.1232 +**
  1.1233 +** This routine requires that all indentifiers in the SELECT
  1.1234 +** statement be resolved.
  1.1235 +*/
  1.1236 +static void selectAddColumnTypeAndCollation(
  1.1237 +  Parse *pParse,        /* Parsing contexts */
  1.1238 +  int nCol,             /* Number of columns */
  1.1239 +  Column *aCol,         /* List of columns */
  1.1240 +  Select *pSelect       /* SELECT used to determine types and collations */
  1.1241 +){
  1.1242 +  sqlite3 *db = pParse->db;
  1.1243 +  NameContext sNC;
  1.1244 +  Column *pCol;
  1.1245 +  CollSeq *pColl;
  1.1246 +  int i;
  1.1247 +  Expr *p;
  1.1248 +  struct ExprList_item *a;
  1.1249 +
  1.1250 +  assert( pSelect!=0 );
  1.1251 +  assert( (pSelect->selFlags & SF_Resolved)!=0 );
  1.1252 +  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
  1.1253 +  if( db->mallocFailed ) return;
  1.1254 +  memset(&sNC, 0, sizeof(sNC));
  1.1255 +  sNC.pSrcList = pSelect->pSrc;
  1.1256 +  a = pSelect->pEList->a;
  1.1257 +  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  1.1258 +    p = a[i].pExpr;
  1.1259 +    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
  1.1260 +    pCol->affinity = sqlite3ExprAffinity(p);
  1.1261 +    pColl = sqlite3ExprCollSeq(pParse, p);
  1.1262 +    if( pColl ){
  1.1263 +      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  1.1264 +    }
  1.1265 +  }
  1.1266 +}
  1.1267 +
  1.1268 +/*
  1.1269 +** Given a SELECT statement, generate a Table structure that describes
  1.1270 +** the result set of that SELECT.
  1.1271 +*/
  1.1272 +Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  1.1273 +  Table *pTab;
  1.1274 +  sqlite3 *db = pParse->db;
  1.1275 +  int savedFlags;
  1.1276 +
  1.1277 +  savedFlags = db->flags;
  1.1278 +  db->flags &= ~SQLITE_FullColNames;
  1.1279 +  db->flags |= SQLITE_ShortColNames;
  1.1280 +  sqlite3SelectPrep(pParse, pSelect, 0);
  1.1281 +  if( pParse->nErr ) return 0;
  1.1282 +  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  1.1283 +  db->flags = savedFlags;
  1.1284 +  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  1.1285 +  if( pTab==0 ){
  1.1286 +    return 0;
  1.1287 +  }
  1.1288 +  pTab->db = db;
  1.1289 +  pTab->nRef = 1;
  1.1290 +  pTab->zName = 0;
  1.1291 +  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  1.1292 +  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
  1.1293 +  pTab->iPKey = -1;
  1.1294 +  if( db->mallocFailed ){
  1.1295 +    sqlite3DeleteTable(pTab);
  1.1296 +    return 0;
  1.1297 +  }
  1.1298 +  return pTab;
  1.1299 +}
  1.1300 +
  1.1301 +/*
  1.1302 +** Get a VDBE for the given parser context.  Create a new one if necessary.
  1.1303 +** If an error occurs, return NULL and leave a message in pParse.
  1.1304 +*/
  1.1305 +Vdbe *sqlite3GetVdbe(Parse *pParse){
  1.1306 +  Vdbe *v = pParse->pVdbe;
  1.1307 +  if( v==0 ){
  1.1308 +    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  1.1309 +#ifndef SQLITE_OMIT_TRACE
  1.1310 +    if( v ){
  1.1311 +      sqlite3VdbeAddOp0(v, OP_Trace);
  1.1312 +    }
  1.1313 +#endif
  1.1314 +  }
  1.1315 +  return v;
  1.1316 +}
  1.1317 +
  1.1318 +
  1.1319 +/*
  1.1320 +** Compute the iLimit and iOffset fields of the SELECT based on the
  1.1321 +** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
  1.1322 +** that appear in the original SQL statement after the LIMIT and OFFSET
  1.1323 +** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
  1.1324 +** are the integer memory register numbers for counters used to compute 
  1.1325 +** the limit and offset.  If there is no limit and/or offset, then 
  1.1326 +** iLimit and iOffset are negative.
  1.1327 +**
  1.1328 +** This routine changes the values of iLimit and iOffset only if
  1.1329 +** a limit or offset is defined by pLimit and pOffset.  iLimit and
  1.1330 +** iOffset should have been preset to appropriate default values
  1.1331 +** (usually but not always -1) prior to calling this routine.
  1.1332 +** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  1.1333 +** redefined.  The UNION ALL operator uses this property to force
  1.1334 +** the reuse of the same limit and offset registers across multiple
  1.1335 +** SELECT statements.
  1.1336 +*/
  1.1337 +static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  1.1338 +  Vdbe *v = 0;
  1.1339 +  int iLimit = 0;
  1.1340 +  int iOffset;
  1.1341 +  int addr1;
  1.1342 +  if( p->iLimit ) return;
  1.1343 +
  1.1344 +  /* 
  1.1345 +  ** "LIMIT -1" always shows all rows.  There is some
  1.1346 +  ** contraversy about what the correct behavior should be.
  1.1347 +  ** The current implementation interprets "LIMIT 0" to mean
  1.1348 +  ** no rows.
  1.1349 +  */
  1.1350 +  if( p->pLimit ){
  1.1351 +    p->iLimit = iLimit = ++pParse->nMem;
  1.1352 +    v = sqlite3GetVdbe(pParse);
  1.1353 +    if( v==0 ) return;
  1.1354 +    sqlite3ExprCode(pParse, p->pLimit, iLimit);
  1.1355 +    sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  1.1356 +    VdbeComment((v, "LIMIT counter"));
  1.1357 +    sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  1.1358 +  }
  1.1359 +  if( p->pOffset ){
  1.1360 +    p->iOffset = iOffset = ++pParse->nMem;
  1.1361 +    if( p->pLimit ){
  1.1362 +      pParse->nMem++;   /* Allocate an extra register for limit+offset */
  1.1363 +    }
  1.1364 +    v = sqlite3GetVdbe(pParse);
  1.1365 +    if( v==0 ) return;
  1.1366 +    sqlite3ExprCode(pParse, p->pOffset, iOffset);
  1.1367 +    sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  1.1368 +    VdbeComment((v, "OFFSET counter"));
  1.1369 +    addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  1.1370 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  1.1371 +    sqlite3VdbeJumpHere(v, addr1);
  1.1372 +    if( p->pLimit ){
  1.1373 +      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  1.1374 +      VdbeComment((v, "LIMIT+OFFSET"));
  1.1375 +      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  1.1376 +      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  1.1377 +      sqlite3VdbeJumpHere(v, addr1);
  1.1378 +    }
  1.1379 +  }
  1.1380 +}
  1.1381 +
  1.1382 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.1383 +/*
  1.1384 +** Return the appropriate collating sequence for the iCol-th column of
  1.1385 +** the result set for the compound-select statement "p".  Return NULL if
  1.1386 +** the column has no default collating sequence.
  1.1387 +**
  1.1388 +** The collating sequence for the compound select is taken from the
  1.1389 +** left-most term of the select that has a collating sequence.
  1.1390 +*/
  1.1391 +static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  1.1392 +  CollSeq *pRet;
  1.1393 +  if( p->pPrior ){
  1.1394 +    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  1.1395 +  }else{
  1.1396 +    pRet = 0;
  1.1397 +  }
  1.1398 +  if( pRet==0 ){
  1.1399 +    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  1.1400 +  }
  1.1401 +  return pRet;
  1.1402 +}
  1.1403 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1.1404 +
  1.1405 +/* Forward reference */
  1.1406 +static int multiSelectOrderBy(
  1.1407 +  Parse *pParse,        /* Parsing context */
  1.1408 +  Select *p,            /* The right-most of SELECTs to be coded */
  1.1409 +  SelectDest *pDest     /* What to do with query results */
  1.1410 +);
  1.1411 +
  1.1412 +
  1.1413 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.1414 +/*
  1.1415 +** This routine is called to process a compound query form from
  1.1416 +** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  1.1417 +** INTERSECT
  1.1418 +**
  1.1419 +** "p" points to the right-most of the two queries.  the query on the
  1.1420 +** left is p->pPrior.  The left query could also be a compound query
  1.1421 +** in which case this routine will be called recursively. 
  1.1422 +**
  1.1423 +** The results of the total query are to be written into a destination
  1.1424 +** of type eDest with parameter iParm.
  1.1425 +**
  1.1426 +** Example 1:  Consider a three-way compound SQL statement.
  1.1427 +**
  1.1428 +**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  1.1429 +**
  1.1430 +** This statement is parsed up as follows:
  1.1431 +**
  1.1432 +**     SELECT c FROM t3
  1.1433 +**      |
  1.1434 +**      `----->  SELECT b FROM t2
  1.1435 +**                |
  1.1436 +**                `------>  SELECT a FROM t1
  1.1437 +**
  1.1438 +** The arrows in the diagram above represent the Select.pPrior pointer.
  1.1439 +** So if this routine is called with p equal to the t3 query, then
  1.1440 +** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
  1.1441 +**
  1.1442 +** Notice that because of the way SQLite parses compound SELECTs, the
  1.1443 +** individual selects always group from left to right.
  1.1444 +*/
  1.1445 +static int multiSelect(
  1.1446 +  Parse *pParse,        /* Parsing context */
  1.1447 +  Select *p,            /* The right-most of SELECTs to be coded */
  1.1448 +  SelectDest *pDest     /* What to do with query results */
  1.1449 +){
  1.1450 +  int rc = SQLITE_OK;   /* Success code from a subroutine */
  1.1451 +  Select *pPrior;       /* Another SELECT immediately to our left */
  1.1452 +  Vdbe *v;              /* Generate code to this VDBE */
  1.1453 +  SelectDest dest;      /* Alternative data destination */
  1.1454 +  Select *pDelete = 0;  /* Chain of simple selects to delete */
  1.1455 +  sqlite3 *db;          /* Database connection */
  1.1456 +
  1.1457 +  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
  1.1458 +  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  1.1459 +  */
  1.1460 +  assert( p && p->pPrior );  /* Calling function guarantees this much */
  1.1461 +  db = pParse->db;
  1.1462 +  pPrior = p->pPrior;
  1.1463 +  assert( pPrior->pRightmost!=pPrior );
  1.1464 +  assert( pPrior->pRightmost==p->pRightmost );
  1.1465 +  dest = *pDest;
  1.1466 +  if( pPrior->pOrderBy ){
  1.1467 +    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  1.1468 +      selectOpName(p->op));
  1.1469 +    rc = 1;
  1.1470 +    goto multi_select_end;
  1.1471 +  }
  1.1472 +  if( pPrior->pLimit ){
  1.1473 +    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  1.1474 +      selectOpName(p->op));
  1.1475 +    rc = 1;
  1.1476 +    goto multi_select_end;
  1.1477 +  }
  1.1478 +
  1.1479 +  v = sqlite3GetVdbe(pParse);
  1.1480 +  assert( v!=0 );  /* The VDBE already created by calling function */
  1.1481 +
  1.1482 +  /* Create the destination temporary table if necessary
  1.1483 +  */
  1.1484 +  if( dest.eDest==SRT_EphemTab ){
  1.1485 +    assert( p->pEList );
  1.1486 +    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
  1.1487 +    dest.eDest = SRT_Table;
  1.1488 +  }
  1.1489 +
  1.1490 +  /* Make sure all SELECTs in the statement have the same number of elements
  1.1491 +  ** in their result sets.
  1.1492 +  */
  1.1493 +  assert( p->pEList && pPrior->pEList );
  1.1494 +  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  1.1495 +    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  1.1496 +      " do not have the same number of result columns", selectOpName(p->op));
  1.1497 +    rc = 1;
  1.1498 +    goto multi_select_end;
  1.1499 +  }
  1.1500 +
  1.1501 +  /* Compound SELECTs that have an ORDER BY clause are handled separately.
  1.1502 +  */
  1.1503 +  if( p->pOrderBy ){
  1.1504 +    return multiSelectOrderBy(pParse, p, pDest);
  1.1505 +  }
  1.1506 +
  1.1507 +  /* Generate code for the left and right SELECT statements.
  1.1508 +  */
  1.1509 +  switch( p->op ){
  1.1510 +    case TK_ALL: {
  1.1511 +      int addr = 0;
  1.1512 +      assert( !pPrior->pLimit );
  1.1513 +      pPrior->pLimit = p->pLimit;
  1.1514 +      pPrior->pOffset = p->pOffset;
  1.1515 +      rc = sqlite3Select(pParse, pPrior, &dest);
  1.1516 +      p->pLimit = 0;
  1.1517 +      p->pOffset = 0;
  1.1518 +      if( rc ){
  1.1519 +        goto multi_select_end;
  1.1520 +      }
  1.1521 +      p->pPrior = 0;
  1.1522 +      p->iLimit = pPrior->iLimit;
  1.1523 +      p->iOffset = pPrior->iOffset;
  1.1524 +      if( p->iLimit ){
  1.1525 +        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  1.1526 +        VdbeComment((v, "Jump ahead if LIMIT reached"));
  1.1527 +      }
  1.1528 +      rc = sqlite3Select(pParse, p, &dest);
  1.1529 +      pDelete = p->pPrior;
  1.1530 +      p->pPrior = pPrior;
  1.1531 +      if( rc ){
  1.1532 +        goto multi_select_end;
  1.1533 +      }
  1.1534 +      if( addr ){
  1.1535 +        sqlite3VdbeJumpHere(v, addr);
  1.1536 +      }
  1.1537 +      break;
  1.1538 +    }
  1.1539 +    case TK_EXCEPT:
  1.1540 +    case TK_UNION: {
  1.1541 +      int unionTab;    /* Cursor number of the temporary table holding result */
  1.1542 +      int op = 0;      /* One of the SRT_ operations to apply to self */
  1.1543 +      int priorOp;     /* The SRT_ operation to apply to prior selects */
  1.1544 +      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  1.1545 +      int addr;
  1.1546 +      SelectDest uniondest;
  1.1547 +
  1.1548 +      priorOp = SRT_Union;
  1.1549 +      if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){
  1.1550 +        /* We can reuse a temporary table generated by a SELECT to our
  1.1551 +        ** right.
  1.1552 +        */
  1.1553 +        unionTab = dest.iParm;
  1.1554 +      }else{
  1.1555 +        /* We will need to create our own temporary table to hold the
  1.1556 +        ** intermediate results.
  1.1557 +        */
  1.1558 +        unionTab = pParse->nTab++;
  1.1559 +        assert( p->pOrderBy==0 );
  1.1560 +        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  1.1561 +        assert( p->addrOpenEphm[0] == -1 );
  1.1562 +        p->addrOpenEphm[0] = addr;
  1.1563 +        p->pRightmost->selFlags |= SF_UsesEphemeral;
  1.1564 +        assert( p->pEList );
  1.1565 +      }
  1.1566 +
  1.1567 +      /* Code the SELECT statements to our left
  1.1568 +      */
  1.1569 +      assert( !pPrior->pOrderBy );
  1.1570 +      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  1.1571 +      rc = sqlite3Select(pParse, pPrior, &uniondest);
  1.1572 +      if( rc ){
  1.1573 +        goto multi_select_end;
  1.1574 +      }
  1.1575 +
  1.1576 +      /* Code the current SELECT statement
  1.1577 +      */
  1.1578 +      if( p->op==TK_EXCEPT ){
  1.1579 +        op = SRT_Except;
  1.1580 +      }else{
  1.1581 +        assert( p->op==TK_UNION );
  1.1582 +        op = SRT_Union;
  1.1583 +      }
  1.1584 +      p->pPrior = 0;
  1.1585 +      pLimit = p->pLimit;
  1.1586 +      p->pLimit = 0;
  1.1587 +      pOffset = p->pOffset;
  1.1588 +      p->pOffset = 0;
  1.1589 +      uniondest.eDest = op;
  1.1590 +      rc = sqlite3Select(pParse, p, &uniondest);
  1.1591 +      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  1.1592 +      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  1.1593 +      sqlite3ExprListDelete(db, p->pOrderBy);
  1.1594 +      pDelete = p->pPrior;
  1.1595 +      p->pPrior = pPrior;
  1.1596 +      p->pOrderBy = 0;
  1.1597 +      sqlite3ExprDelete(db, p->pLimit);
  1.1598 +      p->pLimit = pLimit;
  1.1599 +      p->pOffset = pOffset;
  1.1600 +      p->iLimit = 0;
  1.1601 +      p->iOffset = 0;
  1.1602 +      if( rc ){
  1.1603 +        goto multi_select_end;
  1.1604 +      }
  1.1605 +
  1.1606 +
  1.1607 +      /* Convert the data in the temporary table into whatever form
  1.1608 +      ** it is that we currently need.
  1.1609 +      */      
  1.1610 +      if( dest.eDest!=priorOp || unionTab!=dest.iParm ){
  1.1611 +        int iCont, iBreak, iStart;
  1.1612 +        assert( p->pEList );
  1.1613 +        if( dest.eDest==SRT_Output ){
  1.1614 +          Select *pFirst = p;
  1.1615 +          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  1.1616 +          generateColumnNames(pParse, 0, pFirst->pEList);
  1.1617 +        }
  1.1618 +        iBreak = sqlite3VdbeMakeLabel(v);
  1.1619 +        iCont = sqlite3VdbeMakeLabel(v);
  1.1620 +        computeLimitRegisters(pParse, p, iBreak);
  1.1621 +        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  1.1622 +        iStart = sqlite3VdbeCurrentAddr(v);
  1.1623 +        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  1.1624 +                        0, -1, &dest, iCont, iBreak);
  1.1625 +        sqlite3VdbeResolveLabel(v, iCont);
  1.1626 +        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  1.1627 +        sqlite3VdbeResolveLabel(v, iBreak);
  1.1628 +        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  1.1629 +      }
  1.1630 +      break;
  1.1631 +    }
  1.1632 +    case TK_INTERSECT: {
  1.1633 +      int tab1, tab2;
  1.1634 +      int iCont, iBreak, iStart;
  1.1635 +      Expr *pLimit, *pOffset;
  1.1636 +      int addr;
  1.1637 +      SelectDest intersectdest;
  1.1638 +      int r1;
  1.1639 +
  1.1640 +      /* INTERSECT is different from the others since it requires
  1.1641 +      ** two temporary tables.  Hence it has its own case.  Begin
  1.1642 +      ** by allocating the tables we will need.
  1.1643 +      */
  1.1644 +      tab1 = pParse->nTab++;
  1.1645 +      tab2 = pParse->nTab++;
  1.1646 +      assert( p->pOrderBy==0 );
  1.1647 +
  1.1648 +      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  1.1649 +      assert( p->addrOpenEphm[0] == -1 );
  1.1650 +      p->addrOpenEphm[0] = addr;
  1.1651 +      p->pRightmost->selFlags |= SF_UsesEphemeral;
  1.1652 +      assert( p->pEList );
  1.1653 +
  1.1654 +      /* Code the SELECTs to our left into temporary table "tab1".
  1.1655 +      */
  1.1656 +      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  1.1657 +      rc = sqlite3Select(pParse, pPrior, &intersectdest);
  1.1658 +      if( rc ){
  1.1659 +        goto multi_select_end;
  1.1660 +      }
  1.1661 +
  1.1662 +      /* Code the current SELECT into temporary table "tab2"
  1.1663 +      */
  1.1664 +      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  1.1665 +      assert( p->addrOpenEphm[1] == -1 );
  1.1666 +      p->addrOpenEphm[1] = addr;
  1.1667 +      p->pPrior = 0;
  1.1668 +      pLimit = p->pLimit;
  1.1669 +      p->pLimit = 0;
  1.1670 +      pOffset = p->pOffset;
  1.1671 +      p->pOffset = 0;
  1.1672 +      intersectdest.iParm = tab2;
  1.1673 +      rc = sqlite3Select(pParse, p, &intersectdest);
  1.1674 +      pDelete = p->pPrior;
  1.1675 +      p->pPrior = pPrior;
  1.1676 +      sqlite3ExprDelete(db, p->pLimit);
  1.1677 +      p->pLimit = pLimit;
  1.1678 +      p->pOffset = pOffset;
  1.1679 +      if( rc ){
  1.1680 +        goto multi_select_end;
  1.1681 +      }
  1.1682 +
  1.1683 +      /* Generate code to take the intersection of the two temporary
  1.1684 +      ** tables.
  1.1685 +      */
  1.1686 +      assert( p->pEList );
  1.1687 +      if( dest.eDest==SRT_Output ){
  1.1688 +        Select *pFirst = p;
  1.1689 +        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  1.1690 +        generateColumnNames(pParse, 0, pFirst->pEList);
  1.1691 +      }
  1.1692 +      iBreak = sqlite3VdbeMakeLabel(v);
  1.1693 +      iCont = sqlite3VdbeMakeLabel(v);
  1.1694 +      computeLimitRegisters(pParse, p, iBreak);
  1.1695 +      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  1.1696 +      r1 = sqlite3GetTempReg(pParse);
  1.1697 +      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  1.1698 +      sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1);
  1.1699 +      sqlite3ReleaseTempReg(pParse, r1);
  1.1700 +      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  1.1701 +                      0, -1, &dest, iCont, iBreak);
  1.1702 +      sqlite3VdbeResolveLabel(v, iCont);
  1.1703 +      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  1.1704 +      sqlite3VdbeResolveLabel(v, iBreak);
  1.1705 +      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  1.1706 +      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  1.1707 +      break;
  1.1708 +    }
  1.1709 +  }
  1.1710 +
  1.1711 +  /* Compute collating sequences used by 
  1.1712 +  ** temporary tables needed to implement the compound select.
  1.1713 +  ** Attach the KeyInfo structure to all temporary tables.
  1.1714 +  **
  1.1715 +  ** This section is run by the right-most SELECT statement only.
  1.1716 +  ** SELECT statements to the left always skip this part.  The right-most
  1.1717 +  ** SELECT might also skip this part if it has no ORDER BY clause and
  1.1718 +  ** no temp tables are required.
  1.1719 +  */
  1.1720 +  if( p->selFlags & SF_UsesEphemeral ){
  1.1721 +    int i;                        /* Loop counter */
  1.1722 +    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
  1.1723 +    Select *pLoop;                /* For looping through SELECT statements */
  1.1724 +    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
  1.1725 +    int nCol;                     /* Number of columns in result set */
  1.1726 +
  1.1727 +    assert( p->pRightmost==p );
  1.1728 +    nCol = p->pEList->nExpr;
  1.1729 +    pKeyInfo = sqlite3DbMallocZero(db,
  1.1730 +                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
  1.1731 +    if( !pKeyInfo ){
  1.1732 +      rc = SQLITE_NOMEM;
  1.1733 +      goto multi_select_end;
  1.1734 +    }
  1.1735 +
  1.1736 +    pKeyInfo->enc = ENC(db);
  1.1737 +    pKeyInfo->nField = nCol;
  1.1738 +
  1.1739 +    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  1.1740 +      *apColl = multiSelectCollSeq(pParse, p, i);
  1.1741 +      if( 0==*apColl ){
  1.1742 +        *apColl = db->pDfltColl;
  1.1743 +      }
  1.1744 +    }
  1.1745 +
  1.1746 +    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  1.1747 +      for(i=0; i<2; i++){
  1.1748 +        int addr = pLoop->addrOpenEphm[i];
  1.1749 +        if( addr<0 ){
  1.1750 +          /* If [0] is unused then [1] is also unused.  So we can
  1.1751 +          ** always safely abort as soon as the first unused slot is found */
  1.1752 +          assert( pLoop->addrOpenEphm[1]<0 );
  1.1753 +          break;
  1.1754 +        }
  1.1755 +        sqlite3VdbeChangeP2(v, addr, nCol);
  1.1756 +        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  1.1757 +        pLoop->addrOpenEphm[i] = -1;
  1.1758 +      }
  1.1759 +    }
  1.1760 +    sqlite3DbFree(db, pKeyInfo);
  1.1761 +  }
  1.1762 +
  1.1763 +multi_select_end:
  1.1764 +  pDest->iMem = dest.iMem;
  1.1765 +  pDest->nMem = dest.nMem;
  1.1766 +  sqlite3SelectDelete(db, pDelete);
  1.1767 +  return rc;
  1.1768 +}
  1.1769 +#endif /* SQLITE_OMIT_COMPOUND_SELECT */
  1.1770 +
  1.1771 +/*
  1.1772 +** Code an output subroutine for a coroutine implementation of a
  1.1773 +** SELECT statment.
  1.1774 +**
  1.1775 +** The data to be output is contained in pIn->iMem.  There are
  1.1776 +** pIn->nMem columns to be output.  pDest is where the output should
  1.1777 +** be sent.
  1.1778 +**
  1.1779 +** regReturn is the number of the register holding the subroutine
  1.1780 +** return address.
  1.1781 +**
  1.1782 +** If regPrev>0 then it is a the first register in a vector that
  1.1783 +** records the previous output.  mem[regPrev] is a flag that is false
  1.1784 +** if there has been no previous output.  If regPrev>0 then code is
  1.1785 +** generated to suppress duplicates.  pKeyInfo is used for comparing
  1.1786 +** keys.
  1.1787 +**
  1.1788 +** If the LIMIT found in p->iLimit is reached, jump immediately to
  1.1789 +** iBreak.
  1.1790 +*/
  1.1791 +static int generateOutputSubroutine(
  1.1792 +  Parse *pParse,          /* Parsing context */
  1.1793 +  Select *p,              /* The SELECT statement */
  1.1794 +  SelectDest *pIn,        /* Coroutine supplying data */
  1.1795 +  SelectDest *pDest,      /* Where to send the data */
  1.1796 +  int regReturn,          /* The return address register */
  1.1797 +  int regPrev,            /* Previous result register.  No uniqueness if 0 */
  1.1798 +  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
  1.1799 +  int p4type,             /* The p4 type for pKeyInfo */
  1.1800 +  int iBreak              /* Jump here if we hit the LIMIT */
  1.1801 +){
  1.1802 +  Vdbe *v = pParse->pVdbe;
  1.1803 +  int iContinue;
  1.1804 +  int addr;
  1.1805 +
  1.1806 +  addr = sqlite3VdbeCurrentAddr(v);
  1.1807 +  iContinue = sqlite3VdbeMakeLabel(v);
  1.1808 +
  1.1809 +  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
  1.1810 +  */
  1.1811 +  if( regPrev ){
  1.1812 +    int j1, j2;
  1.1813 +    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  1.1814 +    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
  1.1815 +                              (char*)pKeyInfo, p4type);
  1.1816 +    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  1.1817 +    sqlite3VdbeJumpHere(v, j1);
  1.1818 +    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
  1.1819 +    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  1.1820 +  }
  1.1821 +  if( pParse->db->mallocFailed ) return 0;
  1.1822 +
  1.1823 +  /* Suppress the the first OFFSET entries if there is an OFFSET clause
  1.1824 +  */
  1.1825 +  codeOffset(v, p, iContinue);
  1.1826 +
  1.1827 +  switch( pDest->eDest ){
  1.1828 +    /* Store the result as data using a unique key.
  1.1829 +    */
  1.1830 +    case SRT_Table:
  1.1831 +    case SRT_EphemTab: {
  1.1832 +      int r1 = sqlite3GetTempReg(pParse);
  1.1833 +      int r2 = sqlite3GetTempReg(pParse);
  1.1834 +      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
  1.1835 +      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
  1.1836 +      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
  1.1837 +      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  1.1838 +      sqlite3ReleaseTempReg(pParse, r2);
  1.1839 +      sqlite3ReleaseTempReg(pParse, r1);
  1.1840 +      break;
  1.1841 +    }
  1.1842 +
  1.1843 +#ifndef SQLITE_OMIT_SUBQUERY
  1.1844 +    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  1.1845 +    ** then there should be a single item on the stack.  Write this
  1.1846 +    ** item into the set table with bogus data.
  1.1847 +    */
  1.1848 +    case SRT_Set: {
  1.1849 +      int r1;
  1.1850 +      assert( pIn->nMem==1 );
  1.1851 +      p->affinity = 
  1.1852 +         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
  1.1853 +      r1 = sqlite3GetTempReg(pParse);
  1.1854 +      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
  1.1855 +      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
  1.1856 +      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
  1.1857 +      sqlite3ReleaseTempReg(pParse, r1);
  1.1858 +      break;
  1.1859 +    }
  1.1860 +
  1.1861 +#if 0  /* Never occurs on an ORDER BY query */
  1.1862 +    /* If any row exist in the result set, record that fact and abort.
  1.1863 +    */
  1.1864 +    case SRT_Exists: {
  1.1865 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
  1.1866 +      /* The LIMIT clause will terminate the loop for us */
  1.1867 +      break;
  1.1868 +    }
  1.1869 +#endif
  1.1870 +
  1.1871 +    /* If this is a scalar select that is part of an expression, then
  1.1872 +    ** store the results in the appropriate memory cell and break out
  1.1873 +    ** of the scan loop.
  1.1874 +    */
  1.1875 +    case SRT_Mem: {
  1.1876 +      assert( pIn->nMem==1 );
  1.1877 +      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
  1.1878 +      /* The LIMIT clause will jump out of the loop for us */
  1.1879 +      break;
  1.1880 +    }
  1.1881 +#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  1.1882 +
  1.1883 +    /* The results are stored in a sequence of registers
  1.1884 +    ** starting at pDest->iMem.  Then the co-routine yields.
  1.1885 +    */
  1.1886 +    case SRT_Coroutine: {
  1.1887 +      if( pDest->iMem==0 ){
  1.1888 +        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
  1.1889 +        pDest->nMem = pIn->nMem;
  1.1890 +      }
  1.1891 +      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
  1.1892 +      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
  1.1893 +      break;
  1.1894 +    }
  1.1895 +
  1.1896 +    /* Results are stored in a sequence of registers.  Then the
  1.1897 +    ** OP_ResultRow opcode is used to cause sqlite3_step() to return
  1.1898 +    ** the next row of result.
  1.1899 +    */
  1.1900 +    case SRT_Output: {
  1.1901 +      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
  1.1902 +      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
  1.1903 +      break;
  1.1904 +    }
  1.1905 +
  1.1906 +#if !defined(SQLITE_OMIT_TRIGGER)
  1.1907 +    /* Discard the results.  This is used for SELECT statements inside
  1.1908 +    ** the body of a TRIGGER.  The purpose of such selects is to call
  1.1909 +    ** user-defined functions that have side effects.  We do not care
  1.1910 +    ** about the actual results of the select.
  1.1911 +    */
  1.1912 +    default: {
  1.1913 +      break;
  1.1914 +    }
  1.1915 +#endif
  1.1916 +  }
  1.1917 +
  1.1918 +  /* Jump to the end of the loop if the LIMIT is reached.
  1.1919 +  */
  1.1920 +  if( p->iLimit ){
  1.1921 +    sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
  1.1922 +    sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak);
  1.1923 +  }
  1.1924 +
  1.1925 +  /* Generate the subroutine return
  1.1926 +  */
  1.1927 +  sqlite3VdbeResolveLabel(v, iContinue);
  1.1928 +  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  1.1929 +
  1.1930 +  return addr;
  1.1931 +}
  1.1932 +
  1.1933 +/*
  1.1934 +** Alternative compound select code generator for cases when there
  1.1935 +** is an ORDER BY clause.
  1.1936 +**
  1.1937 +** We assume a query of the following form:
  1.1938 +**
  1.1939 +**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
  1.1940 +**
  1.1941 +** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
  1.1942 +** is to code both <selectA> and <selectB> with the ORDER BY clause as
  1.1943 +** co-routines.  Then run the co-routines in parallel and merge the results
  1.1944 +** into the output.  In addition to the two coroutines (called selectA and
  1.1945 +** selectB) there are 7 subroutines:
  1.1946 +**
  1.1947 +**    outA:    Move the output of the selectA coroutine into the output
  1.1948 +**             of the compound query.
  1.1949 +**
  1.1950 +**    outB:    Move the output of the selectB coroutine into the output
  1.1951 +**             of the compound query.  (Only generated for UNION and
  1.1952 +**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
  1.1953 +**             appears only in B.)
  1.1954 +**
  1.1955 +**    AltB:    Called when there is data from both coroutines and A<B.
  1.1956 +**
  1.1957 +**    AeqB:    Called when there is data from both coroutines and A==B.
  1.1958 +**
  1.1959 +**    AgtB:    Called when there is data from both coroutines and A>B.
  1.1960 +**
  1.1961 +**    EofA:    Called when data is exhausted from selectA.
  1.1962 +**
  1.1963 +**    EofB:    Called when data is exhausted from selectB.
  1.1964 +**
  1.1965 +** The implementation of the latter five subroutines depend on which 
  1.1966 +** <operator> is used:
  1.1967 +**
  1.1968 +**
  1.1969 +**             UNION ALL         UNION            EXCEPT          INTERSECT
  1.1970 +**          -------------  -----------------  --------------  -----------------
  1.1971 +**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
  1.1972 +**
  1.1973 +**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
  1.1974 +**
  1.1975 +**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
  1.1976 +**
  1.1977 +**   EofA:   outB, nextB      outB, nextB          halt             halt
  1.1978 +**
  1.1979 +**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
  1.1980 +**
  1.1981 +** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  1.1982 +** causes an immediate jump to EofA and an EOF on B following nextB causes
  1.1983 +** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
  1.1984 +** following nextX causes a jump to the end of the select processing.
  1.1985 +**
  1.1986 +** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  1.1987 +** within the output subroutine.  The regPrev register set holds the previously
  1.1988 +** output value.  A comparison is made against this value and the output
  1.1989 +** is skipped if the next results would be the same as the previous.
  1.1990 +**
  1.1991 +** The implementation plan is to implement the two coroutines and seven
  1.1992 +** subroutines first, then put the control logic at the bottom.  Like this:
  1.1993 +**
  1.1994 +**          goto Init
  1.1995 +**     coA: coroutine for left query (A)
  1.1996 +**     coB: coroutine for right query (B)
  1.1997 +**    outA: output one row of A
  1.1998 +**    outB: output one row of B (UNION and UNION ALL only)
  1.1999 +**    EofA: ...
  1.2000 +**    EofB: ...
  1.2001 +**    AltB: ...
  1.2002 +**    AeqB: ...
  1.2003 +**    AgtB: ...
  1.2004 +**    Init: initialize coroutine registers
  1.2005 +**          yield coA
  1.2006 +**          if eof(A) goto EofA
  1.2007 +**          yield coB
  1.2008 +**          if eof(B) goto EofB
  1.2009 +**    Cmpr: Compare A, B
  1.2010 +**          Jump AltB, AeqB, AgtB
  1.2011 +**     End: ...
  1.2012 +**
  1.2013 +** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  1.2014 +** actually called using Gosub and they do not Return.  EofA and EofB loop
  1.2015 +** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
  1.2016 +** and AgtB jump to either L2 or to one of EofA or EofB.
  1.2017 +*/
  1.2018 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.2019 +static int multiSelectOrderBy(
  1.2020 +  Parse *pParse,        /* Parsing context */
  1.2021 +  Select *p,            /* The right-most of SELECTs to be coded */
  1.2022 +  SelectDest *pDest     /* What to do with query results */
  1.2023 +){
  1.2024 +  int i, j;             /* Loop counters */
  1.2025 +  Select *pPrior;       /* Another SELECT immediately to our left */
  1.2026 +  Vdbe *v;              /* Generate code to this VDBE */
  1.2027 +  SelectDest destA;     /* Destination for coroutine A */
  1.2028 +  SelectDest destB;     /* Destination for coroutine B */
  1.2029 +  int regAddrA;         /* Address register for select-A coroutine */
  1.2030 +  int regEofA;          /* Flag to indicate when select-A is complete */
  1.2031 +  int regAddrB;         /* Address register for select-B coroutine */
  1.2032 +  int regEofB;          /* Flag to indicate when select-B is complete */
  1.2033 +  int addrSelectA;      /* Address of the select-A coroutine */
  1.2034 +  int addrSelectB;      /* Address of the select-B coroutine */
  1.2035 +  int regOutA;          /* Address register for the output-A subroutine */
  1.2036 +  int regOutB;          /* Address register for the output-B subroutine */
  1.2037 +  int addrOutA;         /* Address of the output-A subroutine */
  1.2038 +  int addrOutB;         /* Address of the output-B subroutine */
  1.2039 +  int addrEofA;         /* Address of the select-A-exhausted subroutine */
  1.2040 +  int addrEofB;         /* Address of the select-B-exhausted subroutine */
  1.2041 +  int addrAltB;         /* Address of the A<B subroutine */
  1.2042 +  int addrAeqB;         /* Address of the A==B subroutine */
  1.2043 +  int addrAgtB;         /* Address of the A>B subroutine */
  1.2044 +  int regLimitA;        /* Limit register for select-A */
  1.2045 +  int regLimitB;        /* Limit register for select-A */
  1.2046 +  int regPrev;          /* A range of registers to hold previous output */
  1.2047 +  int savedLimit;       /* Saved value of p->iLimit */
  1.2048 +  int savedOffset;      /* Saved value of p->iOffset */
  1.2049 +  int labelCmpr;        /* Label for the start of the merge algorithm */
  1.2050 +  int labelEnd;         /* Label for the end of the overall SELECT stmt */
  1.2051 +  int j1;               /* Jump instructions that get retargetted */
  1.2052 +  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  1.2053 +  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  1.2054 +  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
  1.2055 +  sqlite3 *db;          /* Database connection */
  1.2056 +  ExprList *pOrderBy;   /* The ORDER BY clause */
  1.2057 +  int nOrderBy;         /* Number of terms in the ORDER BY clause */
  1.2058 +  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
  1.2059 +
  1.2060 +  assert( p->pOrderBy!=0 );
  1.2061 +  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
  1.2062 +  db = pParse->db;
  1.2063 +  v = pParse->pVdbe;
  1.2064 +  if( v==0 ) return SQLITE_NOMEM;
  1.2065 +  labelEnd = sqlite3VdbeMakeLabel(v);
  1.2066 +  labelCmpr = sqlite3VdbeMakeLabel(v);
  1.2067 +
  1.2068 +
  1.2069 +  /* Patch up the ORDER BY clause
  1.2070 +  */
  1.2071 +  op = p->op;  
  1.2072 +  pPrior = p->pPrior;
  1.2073 +  assert( pPrior->pOrderBy==0 );
  1.2074 +  pOrderBy = p->pOrderBy;
  1.2075 +  assert( pOrderBy );
  1.2076 +  nOrderBy = pOrderBy->nExpr;
  1.2077 +
  1.2078 +  /* For operators other than UNION ALL we have to make sure that
  1.2079 +  ** the ORDER BY clause covers every term of the result set.  Add
  1.2080 +  ** terms to the ORDER BY clause as necessary.
  1.2081 +  */
  1.2082 +  if( op!=TK_ALL ){
  1.2083 +    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  1.2084 +      struct ExprList_item *pItem;
  1.2085 +      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  1.2086 +        assert( pItem->iCol>0 );
  1.2087 +        if( pItem->iCol==i ) break;
  1.2088 +      }
  1.2089 +      if( j==nOrderBy ){
  1.2090 +        Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0);
  1.2091 +        if( pNew==0 ) return SQLITE_NOMEM;
  1.2092 +        pNew->flags |= EP_IntValue;
  1.2093 +        pNew->iTable = i;
  1.2094 +        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0);
  1.2095 +        pOrderBy->a[nOrderBy++].iCol = i;
  1.2096 +      }
  1.2097 +    }
  1.2098 +  }
  1.2099 +
  1.2100 +  /* Compute the comparison permutation and keyinfo that is used with
  1.2101 +  ** the permutation in order to comparisons to determine if the next
  1.2102 +  ** row of results comes from selectA or selectB.  Also add explicit
  1.2103 +  ** collations to the ORDER BY clause terms so that when the subqueries
  1.2104 +  ** to the right and the left are evaluated, they use the correct
  1.2105 +  ** collation.
  1.2106 +  */
  1.2107 +  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  1.2108 +  if( aPermute ){
  1.2109 +    struct ExprList_item *pItem;
  1.2110 +    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  1.2111 +      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
  1.2112 +      aPermute[i] = pItem->iCol - 1;
  1.2113 +    }
  1.2114 +    pKeyMerge =
  1.2115 +      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
  1.2116 +    if( pKeyMerge ){
  1.2117 +      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  1.2118 +      pKeyMerge->nField = nOrderBy;
  1.2119 +      pKeyMerge->enc = ENC(db);
  1.2120 +      for(i=0; i<nOrderBy; i++){
  1.2121 +        CollSeq *pColl;
  1.2122 +        Expr *pTerm = pOrderBy->a[i].pExpr;
  1.2123 +        if( pTerm->flags & EP_ExpCollate ){
  1.2124 +          pColl = pTerm->pColl;
  1.2125 +        }else{
  1.2126 +          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  1.2127 +          pTerm->flags |= EP_ExpCollate;
  1.2128 +          pTerm->pColl = pColl;
  1.2129 +        }
  1.2130 +        pKeyMerge->aColl[i] = pColl;
  1.2131 +        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  1.2132 +      }
  1.2133 +    }
  1.2134 +  }else{
  1.2135 +    pKeyMerge = 0;
  1.2136 +  }
  1.2137 +
  1.2138 +  /* Reattach the ORDER BY clause to the query.
  1.2139 +  */
  1.2140 +  p->pOrderBy = pOrderBy;
  1.2141 +  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy);
  1.2142 +
  1.2143 +  /* Allocate a range of temporary registers and the KeyInfo needed
  1.2144 +  ** for the logic that removes duplicate result rows when the
  1.2145 +  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  1.2146 +  */
  1.2147 +  if( op==TK_ALL ){
  1.2148 +    regPrev = 0;
  1.2149 +  }else{
  1.2150 +    int nExpr = p->pEList->nExpr;
  1.2151 +    assert( nOrderBy>=nExpr );
  1.2152 +    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
  1.2153 +    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  1.2154 +    pKeyDup = sqlite3DbMallocZero(db,
  1.2155 +                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
  1.2156 +    if( pKeyDup ){
  1.2157 +      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
  1.2158 +      pKeyDup->nField = nExpr;
  1.2159 +      pKeyDup->enc = ENC(db);
  1.2160 +      for(i=0; i<nExpr; i++){
  1.2161 +        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  1.2162 +        pKeyDup->aSortOrder[i] = 0;
  1.2163 +      }
  1.2164 +    }
  1.2165 +  }
  1.2166 + 
  1.2167 +  /* Separate the left and the right query from one another
  1.2168 +  */
  1.2169 +  p->pPrior = 0;
  1.2170 +  pPrior->pRightmost = 0;
  1.2171 +  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  1.2172 +  if( pPrior->pPrior==0 ){
  1.2173 +    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  1.2174 +  }
  1.2175 +
  1.2176 +  /* Compute the limit registers */
  1.2177 +  computeLimitRegisters(pParse, p, labelEnd);
  1.2178 +  if( p->iLimit && op==TK_ALL ){
  1.2179 +    regLimitA = ++pParse->nMem;
  1.2180 +    regLimitB = ++pParse->nMem;
  1.2181 +    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  1.2182 +                                  regLimitA);
  1.2183 +    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  1.2184 +  }else{
  1.2185 +    regLimitA = regLimitB = 0;
  1.2186 +  }
  1.2187 +  sqlite3ExprDelete(db, p->pLimit);
  1.2188 +  p->pLimit = 0;
  1.2189 +  sqlite3ExprDelete(db, p->pOffset);
  1.2190 +  p->pOffset = 0;
  1.2191 +
  1.2192 +  regAddrA = ++pParse->nMem;
  1.2193 +  regEofA = ++pParse->nMem;
  1.2194 +  regAddrB = ++pParse->nMem;
  1.2195 +  regEofB = ++pParse->nMem;
  1.2196 +  regOutA = ++pParse->nMem;
  1.2197 +  regOutB = ++pParse->nMem;
  1.2198 +  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  1.2199 +  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  1.2200 +
  1.2201 +  /* Jump past the various subroutines and coroutines to the main
  1.2202 +  ** merge loop
  1.2203 +  */
  1.2204 +  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  1.2205 +  addrSelectA = sqlite3VdbeCurrentAddr(v);
  1.2206 +
  1.2207 +
  1.2208 +  /* Generate a coroutine to evaluate the SELECT statement to the
  1.2209 +  ** left of the compound operator - the "A" select.
  1.2210 +  */
  1.2211 +  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  1.2212 +  pPrior->iLimit = regLimitA;
  1.2213 +  sqlite3Select(pParse, pPrior, &destA);
  1.2214 +  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  1.2215 +  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  1.2216 +  VdbeNoopComment((v, "End coroutine for left SELECT"));
  1.2217 +
  1.2218 +  /* Generate a coroutine to evaluate the SELECT statement on 
  1.2219 +  ** the right - the "B" select
  1.2220 +  */
  1.2221 +  addrSelectB = sqlite3VdbeCurrentAddr(v);
  1.2222 +  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  1.2223 +  savedLimit = p->iLimit;
  1.2224 +  savedOffset = p->iOffset;
  1.2225 +  p->iLimit = regLimitB;
  1.2226 +  p->iOffset = 0;  
  1.2227 +  sqlite3Select(pParse, p, &destB);
  1.2228 +  p->iLimit = savedLimit;
  1.2229 +  p->iOffset = savedOffset;
  1.2230 +  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  1.2231 +  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  1.2232 +  VdbeNoopComment((v, "End coroutine for right SELECT"));
  1.2233 +
  1.2234 +  /* Generate a subroutine that outputs the current row of the A
  1.2235 +  ** select as the next output row of the compound select.
  1.2236 +  */
  1.2237 +  VdbeNoopComment((v, "Output routine for A"));
  1.2238 +  addrOutA = generateOutputSubroutine(pParse,
  1.2239 +                 p, &destA, pDest, regOutA,
  1.2240 +                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  1.2241 +  
  1.2242 +  /* Generate a subroutine that outputs the current row of the B
  1.2243 +  ** select as the next output row of the compound select.
  1.2244 +  */
  1.2245 +  if( op==TK_ALL || op==TK_UNION ){
  1.2246 +    VdbeNoopComment((v, "Output routine for B"));
  1.2247 +    addrOutB = generateOutputSubroutine(pParse,
  1.2248 +                 p, &destB, pDest, regOutB,
  1.2249 +                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  1.2250 +  }
  1.2251 +
  1.2252 +  /* Generate a subroutine to run when the results from select A
  1.2253 +  ** are exhausted and only data in select B remains.
  1.2254 +  */
  1.2255 +  VdbeNoopComment((v, "eof-A subroutine"));
  1.2256 +  if( op==TK_EXCEPT || op==TK_INTERSECT ){
  1.2257 +    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  1.2258 +  }else{  
  1.2259 +    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  1.2260 +    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  1.2261 +    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  1.2262 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  1.2263 +  }
  1.2264 +
  1.2265 +  /* Generate a subroutine to run when the results from select B
  1.2266 +  ** are exhausted and only data in select A remains.
  1.2267 +  */
  1.2268 +  if( op==TK_INTERSECT ){
  1.2269 +    addrEofB = addrEofA;
  1.2270 +  }else{  
  1.2271 +    VdbeNoopComment((v, "eof-B subroutine"));
  1.2272 +    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  1.2273 +    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  1.2274 +    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  1.2275 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  1.2276 +  }
  1.2277 +
  1.2278 +  /* Generate code to handle the case of A<B
  1.2279 +  */
  1.2280 +  VdbeNoopComment((v, "A-lt-B subroutine"));
  1.2281 +  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  1.2282 +  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  1.2283 +  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  1.2284 +  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  1.2285 +
  1.2286 +  /* Generate code to handle the case of A==B
  1.2287 +  */
  1.2288 +  if( op==TK_ALL ){
  1.2289 +    addrAeqB = addrAltB;
  1.2290 +  }else if( op==TK_INTERSECT ){
  1.2291 +    addrAeqB = addrAltB;
  1.2292 +    addrAltB++;
  1.2293 +  }else{
  1.2294 +    VdbeNoopComment((v, "A-eq-B subroutine"));
  1.2295 +    addrAeqB =
  1.2296 +    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  1.2297 +    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  1.2298 +    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  1.2299 +  }
  1.2300 +
  1.2301 +  /* Generate code to handle the case of A>B
  1.2302 +  */
  1.2303 +  VdbeNoopComment((v, "A-gt-B subroutine"));
  1.2304 +  addrAgtB = sqlite3VdbeCurrentAddr(v);
  1.2305 +  if( op==TK_ALL || op==TK_UNION ){
  1.2306 +    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  1.2307 +  }
  1.2308 +  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  1.2309 +  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  1.2310 +  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  1.2311 +
  1.2312 +  /* This code runs once to initialize everything.
  1.2313 +  */
  1.2314 +  sqlite3VdbeJumpHere(v, j1);
  1.2315 +  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  1.2316 +  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  1.2317 +  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  1.2318 +  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  1.2319 +  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  1.2320 +  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  1.2321 +
  1.2322 +  /* Implement the main merge loop
  1.2323 +  */
  1.2324 +  sqlite3VdbeResolveLabel(v, labelCmpr);
  1.2325 +  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  1.2326 +  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
  1.2327 +                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  1.2328 +  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  1.2329 +
  1.2330 +  /* Release temporary registers
  1.2331 +  */
  1.2332 +  if( regPrev ){
  1.2333 +    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
  1.2334 +  }
  1.2335 +
  1.2336 +  /* Jump to the this point in order to terminate the query.
  1.2337 +  */
  1.2338 +  sqlite3VdbeResolveLabel(v, labelEnd);
  1.2339 +
  1.2340 +  /* Set the number of output columns
  1.2341 +  */
  1.2342 +  if( pDest->eDest==SRT_Output ){
  1.2343 +    Select *pFirst = pPrior;
  1.2344 +    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  1.2345 +    generateColumnNames(pParse, 0, pFirst->pEList);
  1.2346 +  }
  1.2347 +
  1.2348 +  /* Reassembly the compound query so that it will be freed correctly
  1.2349 +  ** by the calling function */
  1.2350 +  if( p->pPrior ){
  1.2351 +    sqlite3SelectDelete(db, p->pPrior);
  1.2352 +  }
  1.2353 +  p->pPrior = pPrior;
  1.2354 +
  1.2355 +  /*** TBD:  Insert subroutine calls to close cursors on incomplete
  1.2356 +  **** subqueries ****/
  1.2357 +  return SQLITE_OK;
  1.2358 +}
  1.2359 +#endif
  1.2360 +
  1.2361 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  1.2362 +/* Forward Declarations */
  1.2363 +static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  1.2364 +static void substSelect(sqlite3*, Select *, int, ExprList *);
  1.2365 +
  1.2366 +/*
  1.2367 +** Scan through the expression pExpr.  Replace every reference to
  1.2368 +** a column in table number iTable with a copy of the iColumn-th
  1.2369 +** entry in pEList.  (But leave references to the ROWID column 
  1.2370 +** unchanged.)
  1.2371 +**
  1.2372 +** This routine is part of the flattening procedure.  A subquery
  1.2373 +** whose result set is defined by pEList appears as entry in the
  1.2374 +** FROM clause of a SELECT such that the VDBE cursor assigned to that
  1.2375 +** FORM clause entry is iTable.  This routine make the necessary 
  1.2376 +** changes to pExpr so that it refers directly to the source table
  1.2377 +** of the subquery rather the result set of the subquery.
  1.2378 +*/
  1.2379 +static void substExpr(
  1.2380 +  sqlite3 *db,        /* Report malloc errors to this connection */
  1.2381 +  Expr *pExpr,        /* Expr in which substitution occurs */
  1.2382 +  int iTable,         /* Table to be substituted */
  1.2383 +  ExprList *pEList    /* Substitute expressions */
  1.2384 +){
  1.2385 +  if( pExpr==0 ) return;
  1.2386 +  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  1.2387 +    if( pExpr->iColumn<0 ){
  1.2388 +      pExpr->op = TK_NULL;
  1.2389 +    }else{
  1.2390 +      Expr *pNew;
  1.2391 +      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  1.2392 +      assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
  1.2393 +      pNew = pEList->a[pExpr->iColumn].pExpr;
  1.2394 +      assert( pNew!=0 );
  1.2395 +      pExpr->op = pNew->op;
  1.2396 +      assert( pExpr->pLeft==0 );
  1.2397 +      pExpr->pLeft = sqlite3ExprDup(db, pNew->pLeft);
  1.2398 +      assert( pExpr->pRight==0 );
  1.2399 +      pExpr->pRight = sqlite3ExprDup(db, pNew->pRight);
  1.2400 +      assert( pExpr->pList==0 );
  1.2401 +      pExpr->pList = sqlite3ExprListDup(db, pNew->pList);
  1.2402 +      pExpr->iTable = pNew->iTable;
  1.2403 +      pExpr->pTab = pNew->pTab;
  1.2404 +      pExpr->iColumn = pNew->iColumn;
  1.2405 +      pExpr->iAgg = pNew->iAgg;
  1.2406 +      sqlite3TokenCopy(db, &pExpr->token, &pNew->token);
  1.2407 +      sqlite3TokenCopy(db, &pExpr->span, &pNew->span);
  1.2408 +      pExpr->pSelect = sqlite3SelectDup(db, pNew->pSelect);
  1.2409 +      pExpr->flags = pNew->flags;
  1.2410 +    }
  1.2411 +  }else{
  1.2412 +    substExpr(db, pExpr->pLeft, iTable, pEList);
  1.2413 +    substExpr(db, pExpr->pRight, iTable, pEList);
  1.2414 +    substSelect(db, pExpr->pSelect, iTable, pEList);
  1.2415 +    substExprList(db, pExpr->pList, iTable, pEList);
  1.2416 +  }
  1.2417 +}
  1.2418 +static void substExprList(
  1.2419 +  sqlite3 *db,         /* Report malloc errors here */
  1.2420 +  ExprList *pList,     /* List to scan and in which to make substitutes */
  1.2421 +  int iTable,          /* Table to be substituted */
  1.2422 +  ExprList *pEList     /* Substitute values */
  1.2423 +){
  1.2424 +  int i;
  1.2425 +  if( pList==0 ) return;
  1.2426 +  for(i=0; i<pList->nExpr; i++){
  1.2427 +    substExpr(db, pList->a[i].pExpr, iTable, pEList);
  1.2428 +  }
  1.2429 +}
  1.2430 +static void substSelect(
  1.2431 +  sqlite3 *db,         /* Report malloc errors here */
  1.2432 +  Select *p,           /* SELECT statement in which to make substitutions */
  1.2433 +  int iTable,          /* Table to be replaced */
  1.2434 +  ExprList *pEList     /* Substitute values */
  1.2435 +){
  1.2436 +  SrcList *pSrc;
  1.2437 +  struct SrcList_item *pItem;
  1.2438 +  int i;
  1.2439 +  if( !p ) return;
  1.2440 +  substExprList(db, p->pEList, iTable, pEList);
  1.2441 +  substExprList(db, p->pGroupBy, iTable, pEList);
  1.2442 +  substExprList(db, p->pOrderBy, iTable, pEList);
  1.2443 +  substExpr(db, p->pHaving, iTable, pEList);
  1.2444 +  substExpr(db, p->pWhere, iTable, pEList);
  1.2445 +  substSelect(db, p->pPrior, iTable, pEList);
  1.2446 +  pSrc = p->pSrc;
  1.2447 +  if( pSrc ){
  1.2448 +    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  1.2449 +      substSelect(db, pItem->pSelect, iTable, pEList);
  1.2450 +    }
  1.2451 +  }
  1.2452 +}
  1.2453 +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  1.2454 +
  1.2455 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  1.2456 +/*
  1.2457 +** This routine attempts to flatten subqueries in order to speed
  1.2458 +** execution.  It returns 1 if it makes changes and 0 if no flattening
  1.2459 +** occurs.
  1.2460 +**
  1.2461 +** To understand the concept of flattening, consider the following
  1.2462 +** query:
  1.2463 +**
  1.2464 +**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  1.2465 +**
  1.2466 +** The default way of implementing this query is to execute the
  1.2467 +** subquery first and store the results in a temporary table, then
  1.2468 +** run the outer query on that temporary table.  This requires two
  1.2469 +** passes over the data.  Furthermore, because the temporary table
  1.2470 +** has no indices, the WHERE clause on the outer query cannot be
  1.2471 +** optimized.
  1.2472 +**
  1.2473 +** This routine attempts to rewrite queries such as the above into
  1.2474 +** a single flat select, like this:
  1.2475 +**
  1.2476 +**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  1.2477 +**
  1.2478 +** The code generated for this simpification gives the same result
  1.2479 +** but only has to scan the data once.  And because indices might 
  1.2480 +** exist on the table t1, a complete scan of the data might be
  1.2481 +** avoided.
  1.2482 +**
  1.2483 +** Flattening is only attempted if all of the following are true:
  1.2484 +**
  1.2485 +**   (1)  The subquery and the outer query do not both use aggregates.
  1.2486 +**
  1.2487 +**   (2)  The subquery is not an aggregate or the outer query is not a join.
  1.2488 +**
  1.2489 +**   (3)  The subquery is not the right operand of a left outer join
  1.2490 +**        (Originally ticket #306.  Strenghtened by ticket #3300)
  1.2491 +**
  1.2492 +**   (4)  The subquery is not DISTINCT or the outer query is not a join.
  1.2493 +**
  1.2494 +**   (5)  The subquery is not DISTINCT or the outer query does not use
  1.2495 +**        aggregates.
  1.2496 +**
  1.2497 +**   (6)  The subquery does not use aggregates or the outer query is not
  1.2498 +**        DISTINCT.
  1.2499 +**
  1.2500 +**   (7)  The subquery has a FROM clause.
  1.2501 +**
  1.2502 +**   (8)  The subquery does not use LIMIT or the outer query is not a join.
  1.2503 +**
  1.2504 +**   (9)  The subquery does not use LIMIT or the outer query does not use
  1.2505 +**        aggregates.
  1.2506 +**
  1.2507 +**  (10)  The subquery does not use aggregates or the outer query does not
  1.2508 +**        use LIMIT.
  1.2509 +**
  1.2510 +**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
  1.2511 +**
  1.2512 +**  (12)  Not implemented.  Subsumed into restriction (3).  Was previously
  1.2513 +**        a separate restriction deriving from ticket #350.
  1.2514 +**
  1.2515 +**  (13)  The subquery and outer query do not both use LIMIT
  1.2516 +**
  1.2517 +**  (14)  The subquery does not use OFFSET
  1.2518 +**
  1.2519 +**  (15)  The outer query is not part of a compound select or the
  1.2520 +**        subquery does not have both an ORDER BY and a LIMIT clause.
  1.2521 +**        (See ticket #2339)
  1.2522 +**
  1.2523 +**  (16)  The outer query is not an aggregate or the subquery does
  1.2524 +**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
  1.2525 +**        until we introduced the group_concat() function.  
  1.2526 +**
  1.2527 +**  (17)  The sub-query is not a compound select, or it is a UNION ALL 
  1.2528 +**        compound clause made up entirely of non-aggregate queries, and 
  1.2529 +**        the parent query:
  1.2530 +**
  1.2531 +**          * is not itself part of a compound select,
  1.2532 +**          * is not an aggregate or DISTINCT query, and
  1.2533 +**          * has no other tables or sub-selects in the FROM clause.
  1.2534 +**
  1.2535 +**        The parent and sub-query may contain WHERE clauses. Subject to
  1.2536 +**        rules (11), (13) and (14), they may also contain ORDER BY,
  1.2537 +**        LIMIT and OFFSET clauses.
  1.2538 +**
  1.2539 +**  (18)  If the sub-query is a compound select, then all terms of the
  1.2540 +**        ORDER by clause of the parent must be simple references to 
  1.2541 +**        columns of the sub-query.
  1.2542 +**
  1.2543 +**  (19)  The subquery does not use LIMIT or the outer query does not
  1.2544 +**        have a WHERE clause.
  1.2545 +**
  1.2546 +** In this routine, the "p" parameter is a pointer to the outer query.
  1.2547 +** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
  1.2548 +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  1.2549 +**
  1.2550 +** If flattening is not attempted, this routine is a no-op and returns 0.
  1.2551 +** If flattening is attempted this routine returns 1.
  1.2552 +**
  1.2553 +** All of the expression analysis must occur on both the outer query and
  1.2554 +** the subquery before this routine runs.
  1.2555 +*/
  1.2556 +static int flattenSubquery(
  1.2557 +  Parse *pParse,       /* Parsing context */
  1.2558 +  Select *p,           /* The parent or outer SELECT statement */
  1.2559 +  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
  1.2560 +  int isAgg,           /* True if outer SELECT uses aggregate functions */
  1.2561 +  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
  1.2562 +){
  1.2563 +  const char *zSavedAuthContext = pParse->zAuthContext;
  1.2564 +  Select *pParent;
  1.2565 +  Select *pSub;       /* The inner query or "subquery" */
  1.2566 +  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
  1.2567 +  SrcList *pSrc;      /* The FROM clause of the outer query */
  1.2568 +  SrcList *pSubSrc;   /* The FROM clause of the subquery */
  1.2569 +  ExprList *pList;    /* The result set of the outer query */
  1.2570 +  int iParent;        /* VDBE cursor number of the pSub result set temp table */
  1.2571 +  int i;              /* Loop counter */
  1.2572 +  Expr *pWhere;                    /* The WHERE clause */
  1.2573 +  struct SrcList_item *pSubitem;   /* The subquery */
  1.2574 +  sqlite3 *db = pParse->db;
  1.2575 +
  1.2576 +  /* Check to see if flattening is permitted.  Return 0 if not.
  1.2577 +  */
  1.2578 +  if( p==0 ) return 0;
  1.2579 +  pSrc = p->pSrc;
  1.2580 +  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  1.2581 +  pSubitem = &pSrc->a[iFrom];
  1.2582 +  iParent = pSubitem->iCursor;
  1.2583 +  pSub = pSubitem->pSelect;
  1.2584 +  assert( pSub!=0 );
  1.2585 +  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
  1.2586 +  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
  1.2587 +  pSubSrc = pSub->pSrc;
  1.2588 +  assert( pSubSrc );
  1.2589 +  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  1.2590 +  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  1.2591 +  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
  1.2592 +  ** became arbitrary expressions, we were forced to add restrictions (13)
  1.2593 +  ** and (14). */
  1.2594 +  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
  1.2595 +  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
  1.2596 +  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
  1.2597 +    return 0;                                            /* Restriction (15) */
  1.2598 +  }
  1.2599 +  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
  1.2600 +  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
  1.2601 +         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
  1.2602 +     return 0;       
  1.2603 +  }
  1.2604 +  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  1.2605 +     return 0;         /* Restriction (6)  */
  1.2606 +  }
  1.2607 +  if( p->pOrderBy && pSub->pOrderBy ){
  1.2608 +     return 0;                                           /* Restriction (11) */
  1.2609 +  }
  1.2610 +  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
  1.2611 +  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
  1.2612 +
  1.2613 +  /* OBSOLETE COMMENT 1:
  1.2614 +  ** Restriction 3:  If the subquery is a join, make sure the subquery is 
  1.2615 +  ** not used as the right operand of an outer join.  Examples of why this
  1.2616 +  ** is not allowed:
  1.2617 +  **
  1.2618 +  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
  1.2619 +  **
  1.2620 +  ** If we flatten the above, we would get
  1.2621 +  **
  1.2622 +  **         (t1 LEFT OUTER JOIN t2) JOIN t3
  1.2623 +  **
  1.2624 +  ** which is not at all the same thing.
  1.2625 +  **
  1.2626 +  ** OBSOLETE COMMENT 2:
  1.2627 +  ** Restriction 12:  If the subquery is the right operand of a left outer
  1.2628 +  ** join, make sure the subquery has no WHERE clause.
  1.2629 +  ** An examples of why this is not allowed:
  1.2630 +  **
  1.2631 +  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  1.2632 +  **
  1.2633 +  ** If we flatten the above, we would get
  1.2634 +  **
  1.2635 +  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  1.2636 +  **
  1.2637 +  ** But the t2.x>0 test will always fail on a NULL row of t2, which
  1.2638 +  ** effectively converts the OUTER JOIN into an INNER JOIN.
  1.2639 +  **
  1.2640 +  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  1.2641 +  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  1.2642 +  ** is fraught with danger.  Best to avoid the whole thing.  If the
  1.2643 +  ** subquery is the right term of a LEFT JOIN, then do not flatten.
  1.2644 +  */
  1.2645 +  if( (pSubitem->jointype & JT_OUTER)!=0 ){
  1.2646 +    return 0;
  1.2647 +  }
  1.2648 +
  1.2649 +  /* Restriction 17: If the sub-query is a compound SELECT, then it must
  1.2650 +  ** use only the UNION ALL operator. And none of the simple select queries
  1.2651 +  ** that make up the compound SELECT are allowed to be aggregate or distinct
  1.2652 +  ** queries.
  1.2653 +  */
  1.2654 +  if( pSub->pPrior ){
  1.2655 +    if( p->pPrior || isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  1.2656 +      return 0;
  1.2657 +    }
  1.2658 +    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  1.2659 +      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  1.2660 +       || (pSub1->pPrior && pSub1->op!=TK_ALL) 
  1.2661 +       || !pSub1->pSrc || pSub1->pSrc->nSrc!=1
  1.2662 +      ){
  1.2663 +        return 0;
  1.2664 +      }
  1.2665 +    }
  1.2666 +
  1.2667 +    /* Restriction 18. */
  1.2668 +    if( p->pOrderBy ){
  1.2669 +      int ii;
  1.2670 +      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  1.2671 +        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
  1.2672 +      }
  1.2673 +    }
  1.2674 +  }
  1.2675 +
  1.2676 +  /***** If we reach this point, flattening is permitted. *****/
  1.2677 +
  1.2678 +  /* Authorize the subquery */
  1.2679 +  pParse->zAuthContext = pSubitem->zName;
  1.2680 +  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  1.2681 +  pParse->zAuthContext = zSavedAuthContext;
  1.2682 +
  1.2683 +  /* If the sub-query is a compound SELECT statement, then (by restrictions
  1.2684 +  ** 17 and 18 above) it must be a UNION ALL and the parent query must 
  1.2685 +  ** be of the form:
  1.2686 +  **
  1.2687 +  **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
  1.2688 +  **
  1.2689 +  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  1.2690 +  ** creates N copies of the parent query without any ORDER BY, LIMIT or 
  1.2691 +  ** OFFSET clauses and joins them to the left-hand-side of the original
  1.2692 +  ** using UNION ALL operators. In this case N is the number of simple
  1.2693 +  ** select statements in the compound sub-query.
  1.2694 +  */
  1.2695 +  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  1.2696 +    Select *pNew;
  1.2697 +    ExprList *pOrderBy = p->pOrderBy;
  1.2698 +    Expr *pLimit = p->pLimit;
  1.2699 +    Expr *pOffset = p->pOffset;
  1.2700 +    Select *pPrior = p->pPrior;
  1.2701 +    p->pOrderBy = 0;
  1.2702 +    p->pSrc = 0;
  1.2703 +    p->pPrior = 0;
  1.2704 +    p->pLimit = 0;
  1.2705 +    pNew = sqlite3SelectDup(db, p);
  1.2706 +    pNew->pPrior = pPrior;
  1.2707 +    p->pPrior = pNew;
  1.2708 +    p->pOrderBy = pOrderBy;
  1.2709 +    p->op = TK_ALL;
  1.2710 +    p->pSrc = pSrc;
  1.2711 +    p->pLimit = pLimit;
  1.2712 +    p->pOffset = pOffset;
  1.2713 +    p->pRightmost = 0;
  1.2714 +    pNew->pRightmost = 0;
  1.2715 +  }
  1.2716 +
  1.2717 +  /* Begin flattening the iFrom-th entry of the FROM clause 
  1.2718 +  ** in the outer query.
  1.2719 +  */
  1.2720 +  pSub = pSub1 = pSubitem->pSelect;
  1.2721 +  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  1.2722 +    int nSubSrc = pSubSrc->nSrc;
  1.2723 +    int jointype = 0;
  1.2724 +    pSubSrc = pSub->pSrc;
  1.2725 +    pSrc = pParent->pSrc;
  1.2726 +
  1.2727 +    /* Move all of the FROM elements of the subquery into the
  1.2728 +    ** the FROM clause of the outer query.  Before doing this, remember
  1.2729 +    ** the cursor number for the original outer query FROM element in
  1.2730 +    ** iParent.  The iParent cursor will never be used.  Subsequent code
  1.2731 +    ** will scan expressions looking for iParent references and replace
  1.2732 +    ** those references with expressions that resolve to the subquery FROM
  1.2733 +    ** elements we are now copying in.
  1.2734 +    */
  1.2735 +    if( pSrc ){
  1.2736 +      Table *pTabToDel;
  1.2737 +      pSubitem = &pSrc->a[iFrom];
  1.2738 +      nSubSrc = pSubSrc->nSrc;
  1.2739 +      jointype = pSubitem->jointype;
  1.2740 +      sqlite3DbFree(db, pSubitem->zDatabase);
  1.2741 +      sqlite3DbFree(db, pSubitem->zName);
  1.2742 +      sqlite3DbFree(db, pSubitem->zAlias);
  1.2743 +      pSubitem->zDatabase = 0;
  1.2744 +      pSubitem->zName = 0;
  1.2745 +      pSubitem->zAlias = 0;
  1.2746 +
  1.2747 +      /* If the FROM element is a subquery, defer deleting the Table
  1.2748 +      ** object associated with that subquery until code generation is
  1.2749 +      ** complete, since there may still exist Expr.pTab entires that
  1.2750 +      ** refer to the subquery even after flattening.  Ticket #3346.
  1.2751 +      */
  1.2752 +      if( (pTabToDel = pSubitem->pTab)!=0 ){
  1.2753 +        if( pTabToDel->nRef==1 ){
  1.2754 +          pTabToDel->pNextZombie = pParse->pZombieTab;
  1.2755 +          pParse->pZombieTab = pTabToDel;
  1.2756 +        }else{
  1.2757 +          pTabToDel->nRef--;
  1.2758 +        }
  1.2759 +      }
  1.2760 +      pSubitem->pTab = 0;
  1.2761 +    }
  1.2762 +    if( nSubSrc!=1 || !pSrc ){
  1.2763 +      int extra = nSubSrc - 1;
  1.2764 +      for(i=(pSrc?1:0); i<nSubSrc; i++){
  1.2765 +        pSrc = sqlite3SrcListAppend(db, pSrc, 0, 0);
  1.2766 +        if( pSrc==0 ){
  1.2767 +          pParent->pSrc = 0;
  1.2768 +          return 1;
  1.2769 +        }
  1.2770 +      }
  1.2771 +      pParent->pSrc = pSrc;
  1.2772 +      for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
  1.2773 +        pSrc->a[i] = pSrc->a[i-extra];
  1.2774 +      }
  1.2775 +    }
  1.2776 +    for(i=0; i<nSubSrc; i++){
  1.2777 +      pSrc->a[i+iFrom] = pSubSrc->a[i];
  1.2778 +      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  1.2779 +    }
  1.2780 +    pSrc->a[iFrom].jointype = jointype;
  1.2781 +  
  1.2782 +    /* Now begin substituting subquery result set expressions for 
  1.2783 +    ** references to the iParent in the outer query.
  1.2784 +    ** 
  1.2785 +    ** Example:
  1.2786 +    **
  1.2787 +    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  1.2788 +    **   \                     \_____________ subquery __________/          /
  1.2789 +    **    \_____________________ outer query ______________________________/
  1.2790 +    **
  1.2791 +    ** We look at every expression in the outer query and every place we see
  1.2792 +    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  1.2793 +    */
  1.2794 +    pList = pParent->pEList;
  1.2795 +    for(i=0; i<pList->nExpr; i++){
  1.2796 +      Expr *pExpr;
  1.2797 +      if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
  1.2798 +        pList->a[i].zName = 
  1.2799 +               sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n);
  1.2800 +      }
  1.2801 +    }
  1.2802 +    substExprList(db, pParent->pEList, iParent, pSub->pEList);
  1.2803 +    if( isAgg ){
  1.2804 +      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  1.2805 +      substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  1.2806 +    }
  1.2807 +    if( pSub->pOrderBy ){
  1.2808 +      assert( pParent->pOrderBy==0 );
  1.2809 +      pParent->pOrderBy = pSub->pOrderBy;
  1.2810 +      pSub->pOrderBy = 0;
  1.2811 +    }else if( pParent->pOrderBy ){
  1.2812 +      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  1.2813 +    }
  1.2814 +    if( pSub->pWhere ){
  1.2815 +      pWhere = sqlite3ExprDup(db, pSub->pWhere);
  1.2816 +    }else{
  1.2817 +      pWhere = 0;
  1.2818 +    }
  1.2819 +    if( subqueryIsAgg ){
  1.2820 +      assert( pParent->pHaving==0 );
  1.2821 +      pParent->pHaving = pParent->pWhere;
  1.2822 +      pParent->pWhere = pWhere;
  1.2823 +      substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  1.2824 +      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
  1.2825 +                                  sqlite3ExprDup(db, pSub->pHaving));
  1.2826 +      assert( pParent->pGroupBy==0 );
  1.2827 +      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy);
  1.2828 +    }else{
  1.2829 +      substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  1.2830 +      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  1.2831 +    }
  1.2832 +  
  1.2833 +    /* The flattened query is distinct if either the inner or the
  1.2834 +    ** outer query is distinct. 
  1.2835 +    */
  1.2836 +    pParent->selFlags |= pSub->selFlags & SF_Distinct;
  1.2837 +  
  1.2838 +    /*
  1.2839 +    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  1.2840 +    **
  1.2841 +    ** One is tempted to try to add a and b to combine the limits.  But this
  1.2842 +    ** does not work if either limit is negative.
  1.2843 +    */
  1.2844 +    if( pSub->pLimit ){
  1.2845 +      pParent->pLimit = pSub->pLimit;
  1.2846 +      pSub->pLimit = 0;
  1.2847 +    }
  1.2848 +  }
  1.2849 +
  1.2850 +  /* Finially, delete what is left of the subquery and return
  1.2851 +  ** success.
  1.2852 +  */
  1.2853 +  sqlite3SelectDelete(db, pSub1);
  1.2854 +
  1.2855 +  return 1;
  1.2856 +}
  1.2857 +#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  1.2858 +
  1.2859 +/*
  1.2860 +** Analyze the SELECT statement passed as an argument to see if it
  1.2861 +** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
  1.2862 +** it is, or 0 otherwise. At present, a query is considered to be
  1.2863 +** a min()/max() query if:
  1.2864 +**
  1.2865 +**   1. There is a single object in the FROM clause.
  1.2866 +**
  1.2867 +**   2. There is a single expression in the result set, and it is
  1.2868 +**      either min(x) or max(x), where x is a column reference.
  1.2869 +*/
  1.2870 +static int minMaxQuery(Parse *pParse, Select *p){
  1.2871 +  Expr *pExpr;
  1.2872 +  ExprList *pEList = p->pEList;
  1.2873 +
  1.2874 +  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
  1.2875 +  pExpr = pEList->a[0].pExpr;
  1.2876 +  pEList = pExpr->pList;
  1.2877 +  if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0;
  1.2878 +  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
  1.2879 +  if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL;
  1.2880 +  if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){
  1.2881 +    return WHERE_ORDERBY_MIN;
  1.2882 +  }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){
  1.2883 +    return WHERE_ORDERBY_MAX;
  1.2884 +  }
  1.2885 +  return WHERE_ORDERBY_NORMAL;
  1.2886 +}
  1.2887 +
  1.2888 +/*
  1.2889 +** If the source-list item passed as an argument was augmented with an
  1.2890 +** INDEXED BY clause, then try to locate the specified index. If there
  1.2891 +** was such a clause and the named index cannot be found, return 
  1.2892 +** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
  1.2893 +** pFrom->pIndex and return SQLITE_OK.
  1.2894 +*/
  1.2895 +int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  1.2896 +  if( pFrom->pTab && pFrom->zIndex ){
  1.2897 +    Table *pTab = pFrom->pTab;
  1.2898 +    char *zIndex = pFrom->zIndex;
  1.2899 +    Index *pIdx;
  1.2900 +    for(pIdx=pTab->pIndex; 
  1.2901 +        pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
  1.2902 +        pIdx=pIdx->pNext
  1.2903 +    );
  1.2904 +    if( !pIdx ){
  1.2905 +      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  1.2906 +      return SQLITE_ERROR;
  1.2907 +    }
  1.2908 +    pFrom->pIndex = pIdx;
  1.2909 +  }
  1.2910 +  return SQLITE_OK;
  1.2911 +}
  1.2912 +
  1.2913 +/*
  1.2914 +** This routine is a Walker callback for "expanding" a SELECT statement.
  1.2915 +** "Expanding" means to do the following:
  1.2916 +**
  1.2917 +**    (1)  Make sure VDBE cursor numbers have been assigned to every
  1.2918 +**         element of the FROM clause.
  1.2919 +**
  1.2920 +**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
  1.2921 +**         defines FROM clause.  When views appear in the FROM clause,
  1.2922 +**         fill pTabList->a[].pSelect with a copy of the SELECT statement
  1.2923 +**         that implements the view.  A copy is made of the view's SELECT
  1.2924 +**         statement so that we can freely modify or delete that statement
  1.2925 +**         without worrying about messing up the presistent representation
  1.2926 +**         of the view.
  1.2927 +**
  1.2928 +**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
  1.2929 +**         on joins and the ON and USING clause of joins.
  1.2930 +**
  1.2931 +**    (4)  Scan the list of columns in the result set (pEList) looking
  1.2932 +**         for instances of the "*" operator or the TABLE.* operator.
  1.2933 +**         If found, expand each "*" to be every column in every table
  1.2934 +**         and TABLE.* to be every column in TABLE.
  1.2935 +**
  1.2936 +*/
  1.2937 +static int selectExpander(Walker *pWalker, Select *p){
  1.2938 +  Parse *pParse = pWalker->pParse;
  1.2939 +  int i, j, k;
  1.2940 +  SrcList *pTabList;
  1.2941 +  ExprList *pEList;
  1.2942 +  struct SrcList_item *pFrom;
  1.2943 +  sqlite3 *db = pParse->db;
  1.2944 +
  1.2945 +  if( db->mallocFailed  ){
  1.2946 +    return WRC_Abort;
  1.2947 +  }
  1.2948 +  if( p->pSrc==0 || (p->selFlags & SF_Expanded)!=0 ){
  1.2949 +    return WRC_Prune;
  1.2950 +  }
  1.2951 +  p->selFlags |= SF_Expanded;
  1.2952 +  pTabList = p->pSrc;
  1.2953 +  pEList = p->pEList;
  1.2954 +
  1.2955 +  /* Make sure cursor numbers have been assigned to all entries in
  1.2956 +  ** the FROM clause of the SELECT statement.
  1.2957 +  */
  1.2958 +  sqlite3SrcListAssignCursors(pParse, pTabList);
  1.2959 +
  1.2960 +  /* Look up every table named in the FROM clause of the select.  If
  1.2961 +  ** an entry of the FROM clause is a subquery instead of a table or view,
  1.2962 +  ** then create a transient table structure to describe the subquery.
  1.2963 +  */
  1.2964 +  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  1.2965 +    Table *pTab;
  1.2966 +    if( pFrom->pTab!=0 ){
  1.2967 +      /* This statement has already been prepared.  There is no need
  1.2968 +      ** to go further. */
  1.2969 +      assert( i==0 );
  1.2970 +      return WRC_Prune;
  1.2971 +    }
  1.2972 +    if( pFrom->zName==0 ){
  1.2973 +#ifndef SQLITE_OMIT_SUBQUERY
  1.2974 +      Select *pSel = pFrom->pSelect;
  1.2975 +      /* A sub-query in the FROM clause of a SELECT */
  1.2976 +      assert( pSel!=0 );
  1.2977 +      assert( pFrom->pTab==0 );
  1.2978 +      sqlite3WalkSelect(pWalker, pSel);
  1.2979 +      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  1.2980 +      if( pTab==0 ) return WRC_Abort;
  1.2981 +      pTab->db = db;
  1.2982 +      pTab->nRef = 1;
  1.2983 +      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
  1.2984 +      while( pSel->pPrior ){ pSel = pSel->pPrior; }
  1.2985 +      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  1.2986 +      pTab->iPKey = -1;
  1.2987 +      pTab->tabFlags |= TF_Ephemeral;
  1.2988 +#endif
  1.2989 +    }else{
  1.2990 +      /* An ordinary table or view name in the FROM clause */
  1.2991 +      assert( pFrom->pTab==0 );
  1.2992 +      pFrom->pTab = pTab = 
  1.2993 +        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
  1.2994 +      if( pTab==0 ) return WRC_Abort;
  1.2995 +      pTab->nRef++;
  1.2996 +#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  1.2997 +      if( pTab->pSelect || IsVirtual(pTab) ){
  1.2998 +        /* We reach here if the named table is a really a view */
  1.2999 +        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  1.3000 +
  1.3001 +        /* If pFrom->pSelect!=0 it means we are dealing with a
  1.3002 +        ** view within a view.  The SELECT structure has already been
  1.3003 +        ** copied by the outer view so we can skip the copy step here
  1.3004 +        ** in the inner view.
  1.3005 +        */
  1.3006 +        if( pFrom->pSelect==0 ){
  1.3007 +          pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect);
  1.3008 +          sqlite3WalkSelect(pWalker, pFrom->pSelect);
  1.3009 +        }
  1.3010 +      }
  1.3011 +#endif
  1.3012 +    }
  1.3013 +
  1.3014 +    /* Locate the index named by the INDEXED BY clause, if any. */
  1.3015 +    if( sqlite3IndexedByLookup(pParse, pFrom) ){
  1.3016 +      return WRC_Abort;
  1.3017 +    }
  1.3018 +  }
  1.3019 +
  1.3020 +  /* Process NATURAL keywords, and ON and USING clauses of joins.
  1.3021 +  */
  1.3022 +  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  1.3023 +    return WRC_Abort;
  1.3024 +  }
  1.3025 +
  1.3026 +  /* For every "*" that occurs in the column list, insert the names of
  1.3027 +  ** all columns in all tables.  And for every TABLE.* insert the names
  1.3028 +  ** of all columns in TABLE.  The parser inserted a special expression
  1.3029 +  ** with the TK_ALL operator for each "*" that it found in the column list.
  1.3030 +  ** The following code just has to locate the TK_ALL expressions and expand
  1.3031 +  ** each one to the list of all columns in all tables.
  1.3032 +  **
  1.3033 +  ** The first loop just checks to see if there are any "*" operators
  1.3034 +  ** that need expanding.
  1.3035 +  */
  1.3036 +  for(k=0; k<pEList->nExpr; k++){
  1.3037 +    Expr *pE = pEList->a[k].pExpr;
  1.3038 +    if( pE->op==TK_ALL ) break;
  1.3039 +    if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
  1.3040 +         && pE->pLeft && pE->pLeft->op==TK_ID ) break;
  1.3041 +  }
  1.3042 +  if( k<pEList->nExpr ){
  1.3043 +    /*
  1.3044 +    ** If we get here it means the result set contains one or more "*"
  1.3045 +    ** operators that need to be expanded.  Loop through each expression
  1.3046 +    ** in the result set and expand them one by one.
  1.3047 +    */
  1.3048 +    struct ExprList_item *a = pEList->a;
  1.3049 +    ExprList *pNew = 0;
  1.3050 +    int flags = pParse->db->flags;
  1.3051 +    int longNames = (flags & SQLITE_FullColNames)!=0
  1.3052 +                      && (flags & SQLITE_ShortColNames)==0;
  1.3053 +
  1.3054 +    for(k=0; k<pEList->nExpr; k++){
  1.3055 +      Expr *pE = a[k].pExpr;
  1.3056 +      if( pE->op!=TK_ALL &&
  1.3057 +           (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
  1.3058 +        /* This particular expression does not need to be expanded.
  1.3059 +        */
  1.3060 +        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr, 0);
  1.3061 +        if( pNew ){
  1.3062 +          pNew->a[pNew->nExpr-1].zName = a[k].zName;
  1.3063 +        }
  1.3064 +        a[k].pExpr = 0;
  1.3065 +        a[k].zName = 0;
  1.3066 +      }else{
  1.3067 +        /* This expression is a "*" or a "TABLE.*" and needs to be
  1.3068 +        ** expanded. */
  1.3069 +        int tableSeen = 0;      /* Set to 1 when TABLE matches */
  1.3070 +        char *zTName;            /* text of name of TABLE */
  1.3071 +        if( pE->op==TK_DOT && pE->pLeft ){
  1.3072 +          zTName = sqlite3NameFromToken(db, &pE->pLeft->token);
  1.3073 +        }else{
  1.3074 +          zTName = 0;
  1.3075 +        }
  1.3076 +        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  1.3077 +          Table *pTab = pFrom->pTab;
  1.3078 +          char *zTabName = pFrom->zAlias;
  1.3079 +          if( zTabName==0 || zTabName[0]==0 ){ 
  1.3080 +            zTabName = pTab->zName;
  1.3081 +          }
  1.3082 +          if( db->mallocFailed ) break;
  1.3083 +          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  1.3084 +            continue;
  1.3085 +          }
  1.3086 +          tableSeen = 1;
  1.3087 +          for(j=0; j<pTab->nCol; j++){
  1.3088 +            Expr *pExpr, *pRight;
  1.3089 +            char *zName = pTab->aCol[j].zName;
  1.3090 +
  1.3091 +            /* If a column is marked as 'hidden' (currently only possible
  1.3092 +            ** for virtual tables), do not include it in the expanded
  1.3093 +            ** result-set list.
  1.3094 +            */
  1.3095 +            if( IsHiddenColumn(&pTab->aCol[j]) ){
  1.3096 +              assert(IsVirtual(pTab));
  1.3097 +              continue;
  1.3098 +            }
  1.3099 +
  1.3100 +            if( i>0 ){
  1.3101 +              struct SrcList_item *pLeft = &pTabList->a[i-1];
  1.3102 +              if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
  1.3103 +                        columnIndex(pLeft->pTab, zName)>=0 ){
  1.3104 +                /* In a NATURAL join, omit the join columns from the 
  1.3105 +                ** table on the right */
  1.3106 +                continue;
  1.3107 +              }
  1.3108 +              if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
  1.3109 +                /* In a join with a USING clause, omit columns in the
  1.3110 +                ** using clause from the table on the right. */
  1.3111 +                continue;
  1.3112 +              }
  1.3113 +            }
  1.3114 +            pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  1.3115 +            if( pRight==0 ) break;
  1.3116 +            setQuotedToken(pParse, &pRight->token, zName);
  1.3117 +            if( longNames || pTabList->nSrc>1 ){
  1.3118 +              Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0);
  1.3119 +              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  1.3120 +              if( pExpr==0 ) break;
  1.3121 +              setQuotedToken(pParse, &pLeft->token, zTabName);
  1.3122 +              setToken(&pExpr->span, 
  1.3123 +                  sqlite3MPrintf(db, "%s.%s", zTabName, zName));
  1.3124 +              pExpr->span.dyn = 1;
  1.3125 +              pExpr->token.z = 0;
  1.3126 +              pExpr->token.n = 0;
  1.3127 +              pExpr->token.dyn = 0;
  1.3128 +            }else{
  1.3129 +              pExpr = pRight;
  1.3130 +              pExpr->span = pExpr->token;
  1.3131 +              pExpr->span.dyn = 0;
  1.3132 +            }
  1.3133 +            if( longNames ){
  1.3134 +              pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pExpr->span);
  1.3135 +            }else{
  1.3136 +              pNew = sqlite3ExprListAppend(pParse, pNew, pExpr, &pRight->token);
  1.3137 +            }
  1.3138 +          }
  1.3139 +        }
  1.3140 +        if( !tableSeen ){
  1.3141 +          if( zTName ){
  1.3142 +            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  1.3143 +          }else{
  1.3144 +            sqlite3ErrorMsg(pParse, "no tables specified");
  1.3145 +          }
  1.3146 +        }
  1.3147 +        sqlite3DbFree(db, zTName);
  1.3148 +      }
  1.3149 +    }
  1.3150 +    sqlite3ExprListDelete(db, pEList);
  1.3151 +    p->pEList = pNew;
  1.3152 +  }
  1.3153 +#if SQLITE_MAX_COLUMN
  1.3154 +  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  1.3155 +    sqlite3ErrorMsg(pParse, "too many columns in result set");
  1.3156 +  }
  1.3157 +#endif
  1.3158 +  return WRC_Continue;
  1.3159 +}
  1.3160 +
  1.3161 +/*
  1.3162 +** No-op routine for the parse-tree walker.
  1.3163 +**
  1.3164 +** When this routine is the Walker.xExprCallback then expression trees
  1.3165 +** are walked without any actions being taken at each node.  Presumably,
  1.3166 +** when this routine is used for Walker.xExprCallback then 
  1.3167 +** Walker.xSelectCallback is set to do something useful for every 
  1.3168 +** subquery in the parser tree.
  1.3169 +*/
  1.3170 +static int exprWalkNoop(Walker *pWalker, Expr *pExpr){
  1.3171 +  return WRC_Continue;
  1.3172 +}
  1.3173 +
  1.3174 +/*
  1.3175 +** This routine "expands" a SELECT statement and all of its subqueries.
  1.3176 +** For additional information on what it means to "expand" a SELECT
  1.3177 +** statement, see the comment on the selectExpand worker callback above.
  1.3178 +**
  1.3179 +** Expanding a SELECT statement is the first step in processing a
  1.3180 +** SELECT statement.  The SELECT statement must be expanded before
  1.3181 +** name resolution is performed.
  1.3182 +**
  1.3183 +** If anything goes wrong, an error message is written into pParse.
  1.3184 +** The calling function can detect the problem by looking at pParse->nErr
  1.3185 +** and/or pParse->db->mallocFailed.
  1.3186 +*/
  1.3187 +static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  1.3188 +  Walker w;
  1.3189 +  w.xSelectCallback = selectExpander;
  1.3190 +  w.xExprCallback = exprWalkNoop;
  1.3191 +  w.pParse = pParse;
  1.3192 +  sqlite3WalkSelect(&w, pSelect);
  1.3193 +}
  1.3194 +
  1.3195 +
  1.3196 +#ifndef SQLITE_OMIT_SUBQUERY
  1.3197 +/*
  1.3198 +** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  1.3199 +** interface.
  1.3200 +**
  1.3201 +** For each FROM-clause subquery, add Column.zType and Column.zColl
  1.3202 +** information to the Table structure that represents the result set
  1.3203 +** of that subquery.
  1.3204 +**
  1.3205 +** The Table structure that represents the result set was constructed
  1.3206 +** by selectExpander() but the type and collation information was omitted
  1.3207 +** at that point because identifiers had not yet been resolved.  This
  1.3208 +** routine is called after identifier resolution.
  1.3209 +*/
  1.3210 +static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  1.3211 +  Parse *pParse;
  1.3212 +  int i;
  1.3213 +  SrcList *pTabList;
  1.3214 +  struct SrcList_item *pFrom;
  1.3215 +
  1.3216 +  assert( p->selFlags & SF_Resolved );
  1.3217 +  if( (p->selFlags & SF_HasTypeInfo)==0 ){
  1.3218 +    p->selFlags |= SF_HasTypeInfo;
  1.3219 +    pParse = pWalker->pParse;
  1.3220 +    pTabList = p->pSrc;
  1.3221 +    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  1.3222 +      Table *pTab = pFrom->pTab;
  1.3223 +      if( pTab && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  1.3224 +        /* A sub-query in the FROM clause of a SELECT */
  1.3225 +        Select *pSel = pFrom->pSelect;
  1.3226 +        assert( pSel );
  1.3227 +        while( pSel->pPrior ) pSel = pSel->pPrior;
  1.3228 +        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
  1.3229 +      }
  1.3230 +    }
  1.3231 +  }
  1.3232 +  return WRC_Continue;
  1.3233 +}
  1.3234 +#endif
  1.3235 +
  1.3236 +
  1.3237 +/*
  1.3238 +** This routine adds datatype and collating sequence information to
  1.3239 +** the Table structures of all FROM-clause subqueries in a
  1.3240 +** SELECT statement.
  1.3241 +**
  1.3242 +** Use this routine after name resolution.
  1.3243 +*/
  1.3244 +static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  1.3245 +#ifndef SQLITE_OMIT_SUBQUERY
  1.3246 +  Walker w;
  1.3247 +  w.xSelectCallback = selectAddSubqueryTypeInfo;
  1.3248 +  w.xExprCallback = exprWalkNoop;
  1.3249 +  w.pParse = pParse;
  1.3250 +  sqlite3WalkSelect(&w, pSelect);
  1.3251 +#endif
  1.3252 +}
  1.3253 +
  1.3254 +
  1.3255 +/*
  1.3256 +** This routine sets of a SELECT statement for processing.  The
  1.3257 +** following is accomplished:
  1.3258 +**
  1.3259 +**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
  1.3260 +**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
  1.3261 +**     *  ON and USING clauses are shifted into WHERE statements
  1.3262 +**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
  1.3263 +**     *  Identifiers in expression are matched to tables.
  1.3264 +**
  1.3265 +** This routine acts recursively on all subqueries within the SELECT.
  1.3266 +*/
  1.3267 +void sqlite3SelectPrep(
  1.3268 +  Parse *pParse,         /* The parser context */
  1.3269 +  Select *p,             /* The SELECT statement being coded. */
  1.3270 +  NameContext *pOuterNC  /* Name context for container */
  1.3271 +){
  1.3272 +  sqlite3 *db;
  1.3273 +  if( p==0 ) return;
  1.3274 +  db = pParse->db;
  1.3275 +  if( p->selFlags & SF_HasTypeInfo ) return;
  1.3276 +  if( pParse->nErr || db->mallocFailed ) return;
  1.3277 +  sqlite3SelectExpand(pParse, p);
  1.3278 +  if( pParse->nErr || db->mallocFailed ) return;
  1.3279 +  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  1.3280 +  if( pParse->nErr || db->mallocFailed ) return;
  1.3281 +  sqlite3SelectAddTypeInfo(pParse, p);
  1.3282 +}
  1.3283 +
  1.3284 +/*
  1.3285 +** Reset the aggregate accumulator.
  1.3286 +**
  1.3287 +** The aggregate accumulator is a set of memory cells that hold
  1.3288 +** intermediate results while calculating an aggregate.  This
  1.3289 +** routine simply stores NULLs in all of those memory cells.
  1.3290 +*/
  1.3291 +static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  1.3292 +  Vdbe *v = pParse->pVdbe;
  1.3293 +  int i;
  1.3294 +  struct AggInfo_func *pFunc;
  1.3295 +  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  1.3296 +    return;
  1.3297 +  }
  1.3298 +  for(i=0; i<pAggInfo->nColumn; i++){
  1.3299 +    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  1.3300 +  }
  1.3301 +  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  1.3302 +    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  1.3303 +    if( pFunc->iDistinct>=0 ){
  1.3304 +      Expr *pE = pFunc->pExpr;
  1.3305 +      if( pE->pList==0 || pE->pList->nExpr!=1 ){
  1.3306 +        sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed "
  1.3307 +           "by an expression");
  1.3308 +        pFunc->iDistinct = -1;
  1.3309 +      }else{
  1.3310 +        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList);
  1.3311 +        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  1.3312 +                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  1.3313 +      }
  1.3314 +    }
  1.3315 +  }
  1.3316 +}
  1.3317 +
  1.3318 +/*
  1.3319 +** Invoke the OP_AggFinalize opcode for every aggregate function
  1.3320 +** in the AggInfo structure.
  1.3321 +*/
  1.3322 +static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  1.3323 +  Vdbe *v = pParse->pVdbe;
  1.3324 +  int i;
  1.3325 +  struct AggInfo_func *pF;
  1.3326 +  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  1.3327 +    ExprList *pList = pF->pExpr->pList;
  1.3328 +    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  1.3329 +                      (void*)pF->pFunc, P4_FUNCDEF);
  1.3330 +  }
  1.3331 +}
  1.3332 +
  1.3333 +/*
  1.3334 +** Update the accumulator memory cells for an aggregate based on
  1.3335 +** the current cursor position.
  1.3336 +*/
  1.3337 +static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  1.3338 +  Vdbe *v = pParse->pVdbe;
  1.3339 +  int i;
  1.3340 +  struct AggInfo_func *pF;
  1.3341 +  struct AggInfo_col *pC;
  1.3342 +
  1.3343 +  pAggInfo->directMode = 1;
  1.3344 +  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  1.3345 +    int nArg;
  1.3346 +    int addrNext = 0;
  1.3347 +    int regAgg;
  1.3348 +    ExprList *pList = pF->pExpr->pList;
  1.3349 +    if( pList ){
  1.3350 +      nArg = pList->nExpr;
  1.3351 +      regAgg = sqlite3GetTempRange(pParse, nArg);
  1.3352 +      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
  1.3353 +    }else{
  1.3354 +      nArg = 0;
  1.3355 +      regAgg = 0;
  1.3356 +    }
  1.3357 +    if( pF->iDistinct>=0 ){
  1.3358 +      addrNext = sqlite3VdbeMakeLabel(v);
  1.3359 +      assert( nArg==1 );
  1.3360 +      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  1.3361 +    }
  1.3362 +    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
  1.3363 +      CollSeq *pColl = 0;
  1.3364 +      struct ExprList_item *pItem;
  1.3365 +      int j;
  1.3366 +      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
  1.3367 +      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  1.3368 +        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  1.3369 +      }
  1.3370 +      if( !pColl ){
  1.3371 +        pColl = pParse->db->pDfltColl;
  1.3372 +      }
  1.3373 +      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  1.3374 +    }
  1.3375 +    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  1.3376 +                      (void*)pF->pFunc, P4_FUNCDEF);
  1.3377 +    sqlite3VdbeChangeP5(v, nArg);
  1.3378 +    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  1.3379 +    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  1.3380 +    if( addrNext ){
  1.3381 +      sqlite3VdbeResolveLabel(v, addrNext);
  1.3382 +    }
  1.3383 +  }
  1.3384 +  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  1.3385 +    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  1.3386 +  }
  1.3387 +  pAggInfo->directMode = 0;
  1.3388 +}
  1.3389 +
  1.3390 +/*
  1.3391 +** Generate code for the SELECT statement given in the p argument.  
  1.3392 +**
  1.3393 +** The results are distributed in various ways depending on the
  1.3394 +** contents of the SelectDest structure pointed to by argument pDest
  1.3395 +** as follows:
  1.3396 +**
  1.3397 +**     pDest->eDest    Result
  1.3398 +**     ------------    -------------------------------------------
  1.3399 +**     SRT_Output      Generate a row of output (using the OP_ResultRow
  1.3400 +**                     opcode) for each row in the result set.
  1.3401 +**
  1.3402 +**     SRT_Mem         Only valid if the result is a single column.
  1.3403 +**                     Store the first column of the first result row
  1.3404 +**                     in register pDest->iParm then abandon the rest
  1.3405 +**                     of the query.  This destination implies "LIMIT 1".
  1.3406 +**
  1.3407 +**     SRT_Set         The result must be a single column.  Store each
  1.3408 +**                     row of result as the key in table pDest->iParm. 
  1.3409 +**                     Apply the affinity pDest->affinity before storing
  1.3410 +**                     results.  Used to implement "IN (SELECT ...)".
  1.3411 +**
  1.3412 +**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
  1.3413 +**
  1.3414 +**     SRT_Except      Remove results from the temporary table pDest->iParm.
  1.3415 +**
  1.3416 +**     SRT_Table       Store results in temporary table pDest->iParm.
  1.3417 +**                     This is like SRT_EphemTab except that the table
  1.3418 +**                     is assumed to already be open.
  1.3419 +**
  1.3420 +**     SRT_EphemTab    Create an temporary table pDest->iParm and store
  1.3421 +**                     the result there. The cursor is left open after
  1.3422 +**                     returning.  This is like SRT_Table except that
  1.3423 +**                     this destination uses OP_OpenEphemeral to create
  1.3424 +**                     the table first.
  1.3425 +**
  1.3426 +**     SRT_Coroutine   Generate a co-routine that returns a new row of
  1.3427 +**                     results each time it is invoked.  The entry point
  1.3428 +**                     of the co-routine is stored in register pDest->iParm.
  1.3429 +**
  1.3430 +**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
  1.3431 +**                     set is not empty.
  1.3432 +**
  1.3433 +**     SRT_Discard     Throw the results away.  This is used by SELECT
  1.3434 +**                     statements within triggers whose only purpose is
  1.3435 +**                     the side-effects of functions.
  1.3436 +**
  1.3437 +** This routine returns the number of errors.  If any errors are
  1.3438 +** encountered, then an appropriate error message is left in
  1.3439 +** pParse->zErrMsg.
  1.3440 +**
  1.3441 +** This routine does NOT free the Select structure passed in.  The
  1.3442 +** calling function needs to do that.
  1.3443 +*/
  1.3444 +int sqlite3Select(
  1.3445 +  Parse *pParse,         /* The parser context */
  1.3446 +  Select *p,             /* The SELECT statement being coded. */
  1.3447 +  SelectDest *pDest      /* What to do with the query results */
  1.3448 +){
  1.3449 +  int i, j;              /* Loop counters */
  1.3450 +  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
  1.3451 +  Vdbe *v;               /* The virtual machine under construction */
  1.3452 +  int isAgg;             /* True for select lists like "count(*)" */
  1.3453 +  ExprList *pEList;      /* List of columns to extract. */
  1.3454 +  SrcList *pTabList;     /* List of tables to select from */
  1.3455 +  Expr *pWhere;          /* The WHERE clause.  May be NULL */
  1.3456 +  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
  1.3457 +  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
  1.3458 +  Expr *pHaving;         /* The HAVING clause.  May be NULL */
  1.3459 +  int isDistinct;        /* True if the DISTINCT keyword is present */
  1.3460 +  int distinct;          /* Table to use for the distinct set */
  1.3461 +  int rc = 1;            /* Value to return from this function */
  1.3462 +  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
  1.3463 +  AggInfo sAggInfo;      /* Information used by aggregate queries */
  1.3464 +  int iEnd;              /* Address of the end of the query */
  1.3465 +  sqlite3 *db;           /* The database connection */
  1.3466 +
  1.3467 +  db = pParse->db;
  1.3468 +  if( p==0 || db->mallocFailed || pParse->nErr ){
  1.3469 +    return 1;
  1.3470 +  }
  1.3471 +  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  1.3472 +  memset(&sAggInfo, 0, sizeof(sAggInfo));
  1.3473 +
  1.3474 +  pOrderBy = p->pOrderBy;
  1.3475 +  if( IgnorableOrderby(pDest) ){
  1.3476 +    p->pOrderBy = 0;
  1.3477 +
  1.3478 +    /* In these cases the DISTINCT operator makes no difference to the
  1.3479 +    ** results, so remove it if it were specified.
  1.3480 +    */
  1.3481 +    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
  1.3482 +           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  1.3483 +    p->selFlags &= ~SF_Distinct;
  1.3484 +  }
  1.3485 +  sqlite3SelectPrep(pParse, p, 0);
  1.3486 +  if( pParse->nErr ){
  1.3487 +    goto select_end;
  1.3488 +  }
  1.3489 +  p->pOrderBy = pOrderBy;
  1.3490 +
  1.3491 +
  1.3492 +  /* Make local copies of the parameters for this query.
  1.3493 +  */
  1.3494 +  pTabList = p->pSrc;
  1.3495 +  isAgg = (p->selFlags & SF_Aggregate)!=0;
  1.3496 +  pEList = p->pEList;
  1.3497 +  if( pEList==0 ) goto select_end;
  1.3498 +
  1.3499 +  /* 
  1.3500 +  ** Do not even attempt to generate any code if we have already seen
  1.3501 +  ** errors before this routine starts.
  1.3502 +  */
  1.3503 +  if( pParse->nErr>0 ) goto select_end;
  1.3504 +
  1.3505 +  /* ORDER BY is ignored for some destinations.
  1.3506 +  */
  1.3507 +  if( IgnorableOrderby(pDest) ){
  1.3508 +    pOrderBy = 0;
  1.3509 +  }
  1.3510 +
  1.3511 +  /* Begin generating code.
  1.3512 +  */
  1.3513 +  v = sqlite3GetVdbe(pParse);
  1.3514 +  if( v==0 ) goto select_end;
  1.3515 +
  1.3516 +  /* Generate code for all sub-queries in the FROM clause
  1.3517 +  */
  1.3518 +#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  1.3519 +  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  1.3520 +    struct SrcList_item *pItem = &pTabList->a[i];
  1.3521 +    SelectDest dest;
  1.3522 +    Select *pSub = pItem->pSelect;
  1.3523 +    int isAggSub;
  1.3524 +
  1.3525 +    if( pSub==0 || pItem->isPopulated ) continue;
  1.3526 +
  1.3527 +    /* Increment Parse.nHeight by the height of the largest expression
  1.3528 +    ** tree refered to by this, the parent select. The child select
  1.3529 +    ** may contain expression trees of at most
  1.3530 +    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  1.3531 +    ** more conservative than necessary, but much easier than enforcing
  1.3532 +    ** an exact limit.
  1.3533 +    */
  1.3534 +    pParse->nHeight += sqlite3SelectExprHeight(p);
  1.3535 +
  1.3536 +    /* Check to see if the subquery can be absorbed into the parent. */
  1.3537 +    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  1.3538 +    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  1.3539 +      if( isAggSub ){
  1.3540 +        isAgg = 1;
  1.3541 +        p->selFlags |= SF_Aggregate;
  1.3542 +      }
  1.3543 +      i = -1;
  1.3544 +    }else{
  1.3545 +      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  1.3546 +      assert( pItem->isPopulated==0 );
  1.3547 +      sqlite3Select(pParse, pSub, &dest);
  1.3548 +      pItem->isPopulated = 1;
  1.3549 +    }
  1.3550 +    if( pParse->nErr || db->mallocFailed ){
  1.3551 +      goto select_end;
  1.3552 +    }
  1.3553 +    pParse->nHeight -= sqlite3SelectExprHeight(p);
  1.3554 +    pTabList = p->pSrc;
  1.3555 +    if( !IgnorableOrderby(pDest) ){
  1.3556 +      pOrderBy = p->pOrderBy;
  1.3557 +    }
  1.3558 +  }
  1.3559 +  pEList = p->pEList;
  1.3560 +#endif
  1.3561 +  pWhere = p->pWhere;
  1.3562 +  pGroupBy = p->pGroupBy;
  1.3563 +  pHaving = p->pHaving;
  1.3564 +  isDistinct = (p->selFlags & SF_Distinct)!=0;
  1.3565 +
  1.3566 +#ifndef SQLITE_OMIT_COMPOUND_SELECT
  1.3567 +  /* If there is are a sequence of queries, do the earlier ones first.
  1.3568 +  */
  1.3569 +  if( p->pPrior ){
  1.3570 +    if( p->pRightmost==0 ){
  1.3571 +      Select *pLoop, *pRight = 0;
  1.3572 +      int cnt = 0;
  1.3573 +      int mxSelect;
  1.3574 +      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  1.3575 +        pLoop->pRightmost = p;
  1.3576 +        pLoop->pNext = pRight;
  1.3577 +        pRight = pLoop;
  1.3578 +      }
  1.3579 +      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  1.3580 +      if( mxSelect && cnt>mxSelect ){
  1.3581 +        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  1.3582 +        return 1;
  1.3583 +      }
  1.3584 +    }
  1.3585 +    return multiSelect(pParse, p, pDest);
  1.3586 +  }
  1.3587 +#endif
  1.3588 +
  1.3589 +  /* If writing to memory or generating a set
  1.3590 +  ** only a single column may be output.
  1.3591 +  */
  1.3592 +#ifndef SQLITE_OMIT_SUBQUERY
  1.3593 +  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  1.3594 +    goto select_end;
  1.3595 +  }
  1.3596 +#endif
  1.3597 +
  1.3598 +  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
  1.3599 +  ** GROUP BY might use an index, DISTINCT never does.
  1.3600 +  */
  1.3601 +  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct && !p->pGroupBy ){
  1.3602 +    p->pGroupBy = sqlite3ExprListDup(db, p->pEList);
  1.3603 +    pGroupBy = p->pGroupBy;
  1.3604 +    p->selFlags &= ~SF_Distinct;
  1.3605 +    isDistinct = 0;
  1.3606 +  }
  1.3607 +
  1.3608 +  /* If there is an ORDER BY clause, then this sorting
  1.3609 +  ** index might end up being unused if the data can be 
  1.3610 +  ** extracted in pre-sorted order.  If that is the case, then the
  1.3611 +  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  1.3612 +  ** we figure out that the sorting index is not needed.  The addrSortIndex
  1.3613 +  ** variable is used to facilitate that change.
  1.3614 +  */
  1.3615 +  if( pOrderBy ){
  1.3616 +    KeyInfo *pKeyInfo;
  1.3617 +    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  1.3618 +    pOrderBy->iECursor = pParse->nTab++;
  1.3619 +    p->addrOpenEphm[2] = addrSortIndex =
  1.3620 +      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  1.3621 +                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  1.3622 +                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  1.3623 +  }else{
  1.3624 +    addrSortIndex = -1;
  1.3625 +  }
  1.3626 +
  1.3627 +  /* If the output is destined for a temporary table, open that table.
  1.3628 +  */
  1.3629 +  if( pDest->eDest==SRT_EphemTab ){
  1.3630 +    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
  1.3631 +  }
  1.3632 +
  1.3633 +  /* Set the limiter.
  1.3634 +  */
  1.3635 +  iEnd = sqlite3VdbeMakeLabel(v);
  1.3636 +  computeLimitRegisters(pParse, p, iEnd);
  1.3637 +
  1.3638 +  /* Open a virtual index to use for the distinct set.
  1.3639 +  */
  1.3640 +  if( isDistinct ){
  1.3641 +    KeyInfo *pKeyInfo;
  1.3642 +    assert( isAgg || pGroupBy );
  1.3643 +    distinct = pParse->nTab++;
  1.3644 +    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
  1.3645 +    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
  1.3646 +                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  1.3647 +  }else{
  1.3648 +    distinct = -1;
  1.3649 +  }
  1.3650 +
  1.3651 +  /* Aggregate and non-aggregate queries are handled differently */
  1.3652 +  if( !isAgg && pGroupBy==0 ){
  1.3653 +    /* This case is for non-aggregate queries
  1.3654 +    ** Begin the database scan
  1.3655 +    */
  1.3656 +    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
  1.3657 +    if( pWInfo==0 ) goto select_end;
  1.3658 +
  1.3659 +    /* If sorting index that was created by a prior OP_OpenEphemeral 
  1.3660 +    ** instruction ended up not being needed, then change the OP_OpenEphemeral
  1.3661 +    ** into an OP_Noop.
  1.3662 +    */
  1.3663 +    if( addrSortIndex>=0 && pOrderBy==0 ){
  1.3664 +      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
  1.3665 +      p->addrOpenEphm[2] = -1;
  1.3666 +    }
  1.3667 +
  1.3668 +    /* Use the standard inner loop
  1.3669 +    */
  1.3670 +    assert(!isDistinct);
  1.3671 +    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
  1.3672 +                    pWInfo->iContinue, pWInfo->iBreak);
  1.3673 +
  1.3674 +    /* End the database scan loop.
  1.3675 +    */
  1.3676 +    sqlite3WhereEnd(pWInfo);
  1.3677 +  }else{
  1.3678 +    /* This is the processing for aggregate queries */
  1.3679 +    NameContext sNC;    /* Name context for processing aggregate information */
  1.3680 +    int iAMem;          /* First Mem address for storing current GROUP BY */
  1.3681 +    int iBMem;          /* First Mem address for previous GROUP BY */
  1.3682 +    int iUseFlag;       /* Mem address holding flag indicating that at least
  1.3683 +                        ** one row of the input to the aggregator has been
  1.3684 +                        ** processed */
  1.3685 +    int iAbortFlag;     /* Mem address which causes query abort if positive */
  1.3686 +    int groupBySort;    /* Rows come from source in GROUP BY order */
  1.3687 +    int addrEnd;        /* End of processing for this SELECT */
  1.3688 +
  1.3689 +    /* Remove any and all aliases between the result set and the
  1.3690 +    ** GROUP BY clause.
  1.3691 +    */
  1.3692 +    if( pGroupBy ){
  1.3693 +      int i;                        /* Loop counter */
  1.3694 +      struct ExprList_item *pItem;  /* For looping over expression in a list */
  1.3695 +
  1.3696 +      for(i=p->pEList->nExpr, pItem=p->pEList->a; i>0; i--, pItem++){
  1.3697 +        pItem->iAlias = 0;
  1.3698 +      }
  1.3699 +      for(i=pGroupBy->nExpr, pItem=pGroupBy->a; i>0; i--, pItem++){
  1.3700 +        pItem->iAlias = 0;
  1.3701 +      }
  1.3702 +    }
  1.3703 +
  1.3704 + 
  1.3705 +    /* Create a label to jump to when we want to abort the query */
  1.3706 +    addrEnd = sqlite3VdbeMakeLabel(v);
  1.3707 +
  1.3708 +    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  1.3709 +    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  1.3710 +    ** SELECT statement.
  1.3711 +    */
  1.3712 +    memset(&sNC, 0, sizeof(sNC));
  1.3713 +    sNC.pParse = pParse;
  1.3714 +    sNC.pSrcList = pTabList;
  1.3715 +    sNC.pAggInfo = &sAggInfo;
  1.3716 +    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  1.3717 +    sAggInfo.pGroupBy = pGroupBy;
  1.3718 +    sqlite3ExprAnalyzeAggList(&sNC, pEList);
  1.3719 +    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  1.3720 +    if( pHaving ){
  1.3721 +      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  1.3722 +    }
  1.3723 +    sAggInfo.nAccumulator = sAggInfo.nColumn;
  1.3724 +    for(i=0; i<sAggInfo.nFunc; i++){
  1.3725 +      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList);
  1.3726 +    }
  1.3727 +    if( db->mallocFailed ) goto select_end;
  1.3728 +
  1.3729 +    /* Processing for aggregates with GROUP BY is very different and
  1.3730 +    ** much more complex than aggregates without a GROUP BY.
  1.3731 +    */
  1.3732 +    if( pGroupBy ){
  1.3733 +      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
  1.3734 +      int j1;             /* A-vs-B comparision jump */
  1.3735 +      int addrOutputRow;  /* Start of subroutine that outputs a result row */
  1.3736 +      int regOutputRow;   /* Return address register for output subroutine */
  1.3737 +      int addrSetAbort;   /* Set the abort flag and return */
  1.3738 +      int addrTopOfLoop;  /* Top of the input loop */
  1.3739 +      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  1.3740 +      int addrReset;      /* Subroutine for resetting the accumulator */
  1.3741 +      int regReset;       /* Return address register for reset subroutine */
  1.3742 +
  1.3743 +      /* If there is a GROUP BY clause we might need a sorting index to
  1.3744 +      ** implement it.  Allocate that sorting index now.  If it turns out
  1.3745 +      ** that we do not need it after all, the OpenEphemeral instruction
  1.3746 +      ** will be converted into a Noop.  
  1.3747 +      */
  1.3748 +      sAggInfo.sortingIdx = pParse->nTab++;
  1.3749 +      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  1.3750 +      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
  1.3751 +          sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
  1.3752 +          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  1.3753 +
  1.3754 +      /* Initialize memory locations used by GROUP BY aggregate processing
  1.3755 +      */
  1.3756 +      iUseFlag = ++pParse->nMem;
  1.3757 +      iAbortFlag = ++pParse->nMem;
  1.3758 +      regOutputRow = ++pParse->nMem;
  1.3759 +      addrOutputRow = sqlite3VdbeMakeLabel(v);
  1.3760 +      regReset = ++pParse->nMem;
  1.3761 +      addrReset = sqlite3VdbeMakeLabel(v);
  1.3762 +      iAMem = pParse->nMem + 1;
  1.3763 +      pParse->nMem += pGroupBy->nExpr;
  1.3764 +      iBMem = pParse->nMem + 1;
  1.3765 +      pParse->nMem += pGroupBy->nExpr;
  1.3766 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  1.3767 +      VdbeComment((v, "clear abort flag"));
  1.3768 +      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  1.3769 +      VdbeComment((v, "indicate accumulator empty"));
  1.3770 +
  1.3771 +      /* Begin a loop that will extract all source rows in GROUP BY order.
  1.3772 +      ** This might involve two separate loops with an OP_Sort in between, or
  1.3773 +      ** it might be a single loop that uses an index to extract information
  1.3774 +      ** in the right order to begin with.
  1.3775 +      */
  1.3776 +      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  1.3777 +      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
  1.3778 +      if( pWInfo==0 ) goto select_end;
  1.3779 +      if( pGroupBy==0 ){
  1.3780 +        /* The optimizer is able to deliver rows in group by order so
  1.3781 +        ** we do not have to sort.  The OP_OpenEphemeral table will be
  1.3782 +        ** cancelled later because we still need to use the pKeyInfo
  1.3783 +        */
  1.3784 +        pGroupBy = p->pGroupBy;
  1.3785 +        groupBySort = 0;
  1.3786 +      }else{
  1.3787 +        /* Rows are coming out in undetermined order.  We have to push
  1.3788 +        ** each row into a sorting index, terminate the first loop,
  1.3789 +        ** then loop over the sorting index in order to get the output
  1.3790 +        ** in sorted order
  1.3791 +        */
  1.3792 +        int regBase;
  1.3793 +        int regRecord;
  1.3794 +        int nCol;
  1.3795 +        int nGroupBy;
  1.3796 +
  1.3797 +        groupBySort = 1;
  1.3798 +        nGroupBy = pGroupBy->nExpr;
  1.3799 +        nCol = nGroupBy + 1;
  1.3800 +        j = nGroupBy+1;
  1.3801 +        for(i=0; i<sAggInfo.nColumn; i++){
  1.3802 +          if( sAggInfo.aCol[i].iSorterColumn>=j ){
  1.3803 +            nCol++;
  1.3804 +            j++;
  1.3805 +          }
  1.3806 +        }
  1.3807 +        regBase = sqlite3GetTempRange(pParse, nCol);
  1.3808 +        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  1.3809 +        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  1.3810 +        j = nGroupBy+1;
  1.3811 +        for(i=0; i<sAggInfo.nColumn; i++){
  1.3812 +          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  1.3813 +          if( pCol->iSorterColumn>=j ){
  1.3814 +            int r1 = j + regBase;
  1.3815 +            int r2;
  1.3816 +
  1.3817 +            r2 = sqlite3ExprCodeGetColumn(pParse, 
  1.3818 +                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  1.3819 +            if( r1!=r2 ){
  1.3820 +              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  1.3821 +            }
  1.3822 +            j++;
  1.3823 +          }
  1.3824 +        }
  1.3825 +        regRecord = sqlite3GetTempReg(pParse);
  1.3826 +        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  1.3827 +        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
  1.3828 +        sqlite3ReleaseTempReg(pParse, regRecord);
  1.3829 +        sqlite3ReleaseTempRange(pParse, regBase, nCol);
  1.3830 +        sqlite3WhereEnd(pWInfo);
  1.3831 +        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
  1.3832 +        VdbeComment((v, "GROUP BY sort"));
  1.3833 +        sAggInfo.useSortingIdx = 1;
  1.3834 +      }
  1.3835 +
  1.3836 +      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  1.3837 +      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  1.3838 +      ** Then compare the current GROUP BY terms against the GROUP BY terms
  1.3839 +      ** from the previous row currently stored in a0, a1, a2...
  1.3840 +      */
  1.3841 +      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  1.3842 +      for(j=0; j<pGroupBy->nExpr; j++){
  1.3843 +        if( groupBySort ){
  1.3844 +          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
  1.3845 +        }else{
  1.3846 +          sAggInfo.directMode = 1;
  1.3847 +          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  1.3848 +        }
  1.3849 +      }
  1.3850 +      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  1.3851 +                          (char*)pKeyInfo, P4_KEYINFO);
  1.3852 +      j1 = sqlite3VdbeCurrentAddr(v);
  1.3853 +      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  1.3854 +
  1.3855 +      /* Generate code that runs whenever the GROUP BY changes.
  1.3856 +      ** Changes in the GROUP BY are detected by the previous code
  1.3857 +      ** block.  If there were no changes, this block is skipped.
  1.3858 +      **
  1.3859 +      ** This code copies current group by terms in b0,b1,b2,...
  1.3860 +      ** over to a0,a1,a2.  It then calls the output subroutine
  1.3861 +      ** and resets the aggregate accumulator registers in preparation
  1.3862 +      ** for the next GROUP BY batch.
  1.3863 +      */
  1.3864 +      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  1.3865 +      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  1.3866 +      VdbeComment((v, "output one row"));
  1.3867 +      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  1.3868 +      VdbeComment((v, "check abort flag"));
  1.3869 +      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  1.3870 +      VdbeComment((v, "reset accumulator"));
  1.3871 +
  1.3872 +      /* Update the aggregate accumulators based on the content of
  1.3873 +      ** the current row
  1.3874 +      */
  1.3875 +      sqlite3VdbeJumpHere(v, j1);
  1.3876 +      updateAccumulator(pParse, &sAggInfo);
  1.3877 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  1.3878 +      VdbeComment((v, "indicate data in accumulator"));
  1.3879 +
  1.3880 +      /* End of the loop
  1.3881 +      */
  1.3882 +      if( groupBySort ){
  1.3883 +        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
  1.3884 +      }else{
  1.3885 +        sqlite3WhereEnd(pWInfo);
  1.3886 +        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
  1.3887 +      }
  1.3888 +
  1.3889 +      /* Output the final row of result
  1.3890 +      */
  1.3891 +      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  1.3892 +      VdbeComment((v, "output final row"));
  1.3893 +
  1.3894 +      /* Jump over the subroutines
  1.3895 +      */
  1.3896 +      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  1.3897 +
  1.3898 +      /* Generate a subroutine that outputs a single row of the result
  1.3899 +      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
  1.3900 +      ** is less than or equal to zero, the subroutine is a no-op.  If
  1.3901 +      ** the processing calls for the query to abort, this subroutine
  1.3902 +      ** increments the iAbortFlag memory location before returning in
  1.3903 +      ** order to signal the caller to abort.
  1.3904 +      */
  1.3905 +      addrSetAbort = sqlite3VdbeCurrentAddr(v);
  1.3906 +      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  1.3907 +      VdbeComment((v, "set abort flag"));
  1.3908 +      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  1.3909 +      sqlite3VdbeResolveLabel(v, addrOutputRow);
  1.3910 +      addrOutputRow = sqlite3VdbeCurrentAddr(v);
  1.3911 +      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  1.3912 +      VdbeComment((v, "Groupby result generator entry point"));
  1.3913 +      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  1.3914 +      finalizeAggFunctions(pParse, &sAggInfo);
  1.3915 +      if( pHaving ){
  1.3916 +        sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  1.3917 +      }
  1.3918 +      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  1.3919 +                      distinct, pDest,
  1.3920 +                      addrOutputRow+1, addrSetAbort);
  1.3921 +      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  1.3922 +      VdbeComment((v, "end groupby result generator"));
  1.3923 +
  1.3924 +      /* Generate a subroutine that will reset the group-by accumulator
  1.3925 +      */
  1.3926 +      sqlite3VdbeResolveLabel(v, addrReset);
  1.3927 +      resetAccumulator(pParse, &sAggInfo);
  1.3928 +      sqlite3VdbeAddOp1(v, OP_Return, regReset);
  1.3929 +     
  1.3930 +    } /* endif pGroupBy */
  1.3931 +    else {
  1.3932 +      ExprList *pMinMax = 0;
  1.3933 +      ExprList *pDel = 0;
  1.3934 +      u8 flag;
  1.3935 +
  1.3936 +      /* Check if the query is of one of the following forms:
  1.3937 +      **
  1.3938 +      **   SELECT min(x) FROM ...
  1.3939 +      **   SELECT max(x) FROM ...
  1.3940 +      **
  1.3941 +      ** If it is, then ask the code in where.c to attempt to sort results
  1.3942 +      ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
  1.3943 +      ** If where.c is able to produce results sorted in this order, then
  1.3944 +      ** add vdbe code to break out of the processing loop after the 
  1.3945 +      ** first iteration (since the first iteration of the loop is 
  1.3946 +      ** guaranteed to operate on the row with the minimum or maximum 
  1.3947 +      ** value of x, the only row required).
  1.3948 +      **
  1.3949 +      ** A special flag must be passed to sqlite3WhereBegin() to slightly
  1.3950 +      ** modify behaviour as follows:
  1.3951 +      **
  1.3952 +      **   + If the query is a "SELECT min(x)", then the loop coded by
  1.3953 +      **     where.c should not iterate over any values with a NULL value
  1.3954 +      **     for x.
  1.3955 +      **
  1.3956 +      **   + The optimizer code in where.c (the thing that decides which
  1.3957 +      **     index or indices to use) should place a different priority on 
  1.3958 +      **     satisfying the 'ORDER BY' clause than it does in other cases.
  1.3959 +      **     Refer to code and comments in where.c for details.
  1.3960 +      */
  1.3961 +      flag = minMaxQuery(pParse, p);
  1.3962 +      if( flag ){
  1.3963 +        pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList);
  1.3964 +        if( pMinMax && !db->mallocFailed ){
  1.3965 +          pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN;
  1.3966 +          pMinMax->a[0].pExpr->op = TK_COLUMN;
  1.3967 +        }
  1.3968 +      }
  1.3969 +
  1.3970 +      /* This case runs if the aggregate has no GROUP BY clause.  The
  1.3971 +      ** processing is much simpler since there is only a single row
  1.3972 +      ** of output.
  1.3973 +      */
  1.3974 +      resetAccumulator(pParse, &sAggInfo);
  1.3975 +      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
  1.3976 +      if( pWInfo==0 ){
  1.3977 +        sqlite3ExprListDelete(db, pDel);
  1.3978 +        goto select_end;
  1.3979 +      }
  1.3980 +      updateAccumulator(pParse, &sAggInfo);
  1.3981 +      if( !pMinMax && flag ){
  1.3982 +        sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
  1.3983 +        VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max")));
  1.3984 +      }
  1.3985 +      sqlite3WhereEnd(pWInfo);
  1.3986 +      finalizeAggFunctions(pParse, &sAggInfo);
  1.3987 +      pOrderBy = 0;
  1.3988 +      if( pHaving ){
  1.3989 +        sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  1.3990 +      }
  1.3991 +      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
  1.3992 +                      pDest, addrEnd, addrEnd);
  1.3993 +
  1.3994 +      sqlite3ExprListDelete(db, pDel);
  1.3995 +    }
  1.3996 +    sqlite3VdbeResolveLabel(v, addrEnd);
  1.3997 +    
  1.3998 +  } /* endif aggregate query */
  1.3999 +
  1.4000 +  /* If there is an ORDER BY clause, then we need to sort the results
  1.4001 +  ** and send them to the callback one by one.
  1.4002 +  */
  1.4003 +  if( pOrderBy ){
  1.4004 +    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  1.4005 +  }
  1.4006 +
  1.4007 +  /* Jump here to skip this query
  1.4008 +  */
  1.4009 +  sqlite3VdbeResolveLabel(v, iEnd);
  1.4010 +
  1.4011 +  /* The SELECT was successfully coded.   Set the return code to 0
  1.4012 +  ** to indicate no errors.
  1.4013 +  */
  1.4014 +  rc = 0;
  1.4015 +
  1.4016 +  /* Control jumps to here if an error is encountered above, or upon
  1.4017 +  ** successful coding of the SELECT.
  1.4018 +  */
  1.4019 +select_end:
  1.4020 +
  1.4021 +  /* Identify column names if results of the SELECT are to be output.
  1.4022 +  */
  1.4023 +  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  1.4024 +    generateColumnNames(pParse, pTabList, pEList);
  1.4025 +  }
  1.4026 +
  1.4027 +  sqlite3DbFree(db, sAggInfo.aCol);
  1.4028 +  sqlite3DbFree(db, sAggInfo.aFunc);
  1.4029 +  return rc;
  1.4030 +}
  1.4031 +
  1.4032 +#if defined(SQLITE_DEBUG)
  1.4033 +/*
  1.4034 +*******************************************************************************
  1.4035 +** The following code is used for testing and debugging only.  The code
  1.4036 +** that follows does not appear in normal builds.
  1.4037 +**
  1.4038 +** These routines are used to print out the content of all or part of a 
  1.4039 +** parse structures such as Select or Expr.  Such printouts are useful
  1.4040 +** for helping to understand what is happening inside the code generator
  1.4041 +** during the execution of complex SELECT statements.
  1.4042 +**
  1.4043 +** These routine are not called anywhere from within the normal
  1.4044 +** code base.  Then are intended to be called from within the debugger
  1.4045 +** or from temporary "printf" statements inserted for debugging.
  1.4046 +*/
  1.4047 +void sqlite3PrintExpr(Expr *p){
  1.4048 +  if( p->token.z && p->token.n>0 ){
  1.4049 +    sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
  1.4050 +  }else{
  1.4051 +    sqlite3DebugPrintf("(%d", p->op);
  1.4052 +  }
  1.4053 +  if( p->pLeft ){
  1.4054 +    sqlite3DebugPrintf(" ");
  1.4055 +    sqlite3PrintExpr(p->pLeft);
  1.4056 +  }
  1.4057 +  if( p->pRight ){
  1.4058 +    sqlite3DebugPrintf(" ");
  1.4059 +    sqlite3PrintExpr(p->pRight);
  1.4060 +  }
  1.4061 +  sqlite3DebugPrintf(")");
  1.4062 +}
  1.4063 +void sqlite3PrintExprList(ExprList *pList){
  1.4064 +  int i;
  1.4065 +  for(i=0; i<pList->nExpr; i++){
  1.4066 +    sqlite3PrintExpr(pList->a[i].pExpr);
  1.4067 +    if( i<pList->nExpr-1 ){
  1.4068 +      sqlite3DebugPrintf(", ");
  1.4069 +    }
  1.4070 +  }
  1.4071 +}
  1.4072 +void sqlite3PrintSelect(Select *p, int indent){
  1.4073 +  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  1.4074 +  sqlite3PrintExprList(p->pEList);
  1.4075 +  sqlite3DebugPrintf("\n");
  1.4076 +  if( p->pSrc ){
  1.4077 +    char *zPrefix;
  1.4078 +    int i;
  1.4079 +    zPrefix = "FROM";
  1.4080 +    for(i=0; i<p->pSrc->nSrc; i++){
  1.4081 +      struct SrcList_item *pItem = &p->pSrc->a[i];
  1.4082 +      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
  1.4083 +      zPrefix = "";
  1.4084 +      if( pItem->pSelect ){
  1.4085 +        sqlite3DebugPrintf("(\n");
  1.4086 +        sqlite3PrintSelect(pItem->pSelect, indent+10);
  1.4087 +        sqlite3DebugPrintf("%*s)", indent+8, "");
  1.4088 +      }else if( pItem->zName ){
  1.4089 +        sqlite3DebugPrintf("%s", pItem->zName);
  1.4090 +      }
  1.4091 +      if( pItem->pTab ){
  1.4092 +        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
  1.4093 +      }
  1.4094 +      if( pItem->zAlias ){
  1.4095 +        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
  1.4096 +      }
  1.4097 +      if( i<p->pSrc->nSrc-1 ){
  1.4098 +        sqlite3DebugPrintf(",");
  1.4099 +      }
  1.4100 +      sqlite3DebugPrintf("\n");
  1.4101 +    }
  1.4102 +  }
  1.4103 +  if( p->pWhere ){
  1.4104 +    sqlite3DebugPrintf("%*s WHERE ", indent, "");
  1.4105 +    sqlite3PrintExpr(p->pWhere);
  1.4106 +    sqlite3DebugPrintf("\n");
  1.4107 +  }
  1.4108 +  if( p->pGroupBy ){
  1.4109 +    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
  1.4110 +    sqlite3PrintExprList(p->pGroupBy);
  1.4111 +    sqlite3DebugPrintf("\n");
  1.4112 +  }
  1.4113 +  if( p->pHaving ){
  1.4114 +    sqlite3DebugPrintf("%*s HAVING ", indent, "");
  1.4115 +    sqlite3PrintExpr(p->pHaving);
  1.4116 +    sqlite3DebugPrintf("\n");
  1.4117 +  }
  1.4118 +  if( p->pOrderBy ){
  1.4119 +    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
  1.4120 +    sqlite3PrintExprList(p->pOrderBy);
  1.4121 +    sqlite3DebugPrintf("\n");
  1.4122 +  }
  1.4123 +}
  1.4124 +/* End of the structure debug printing code
  1.4125 +*****************************************************************************/
  1.4126 +#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */