/ Check-in [b1b50f31]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Modify sub-query handling. Tickets #1083 and #1084. (CVS 2286)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: b1b50f315873a8614920d1e3af4a07fb29a7ff6a
User & Date: danielk1977 2005-01-29 08:32:44
Context
2005-01-29
08:36
Update ioerr.test to be more deterministic. (CVS 2287) check-in: d0b16bae user: danielk1977 tags: trunk
08:32
Modify sub-query handling. Tickets #1083 and #1084. (CVS 2286) check-in: b1b50f31 user: danielk1977 tags: trunk
01:54
Modification to schema.test so that it works with SQLITE_OMIT_TRIGGER and SQLITE_OMIT_UTF16 defined. (CVS 2285) check-in: 95ecb274 user: danielk1977 tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/auth.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains code used to implement the sqlite3_set_authorizer()
    13     13   ** API.  This facility is an optional feature of the library.  Embedded
    14     14   ** systems that do not need this facility may omit it by recompiling
    15     15   ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
    16     16   **
    17         -** $Id: auth.c,v 1.20 2005/01/22 03:03:54 drh Exp $
           17  +** $Id: auth.c,v 1.21 2005/01/29 08:32:44 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   
    21     21   /*
    22     22   ** All of the code in this file may be omitted by defining a single
    23     23   ** macro.
    24     24   */
................................................................................
   111    111     const char *zCol;     /* Name of the column of the table */
   112    112     int iSrc;             /* Index in pTabList->a[] of table being read */
   113    113     const char *zDBase;   /* Name of database being accessed */
   114    114     TriggerStack *pStack; /* The stack of current triggers */
   115    115   
   116    116     if( db->xAuth==0 ) return;
   117    117     assert( pExpr->op==TK_COLUMN );
   118         -  for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
          118  +  for(iSrc=0; pTabList && iSrc<pTabList->nSrc; iSrc++){
   119    119       if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
   120    120     }
   121         -  if( iSrc>=0 && iSrc<pTabList->nSrc ){
          121  +  if( iSrc>=0 && pTabList && iSrc<pTabList->nSrc ){
   122    122       pTab = pTabList->a[iSrc].pTab;
   123    123     }else if( (pStack = pParse->trigStack)!=0 ){
   124    124       /* This must be an attempt to read the NEW or OLD pseudo-tables
   125    125       ** of a trigger.
   126    126       */
   127    127       assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
   128    128       pTab = pStack->pTab;

Changes to src/build.c.

    18     18   **     CREATE INDEX
    19     19   **     DROP INDEX
    20     20   **     creating ID lists
    21     21   **     BEGIN TRANSACTION
    22     22   **     COMMIT
    23     23   **     ROLLBACK
    24     24   **
    25         -** $Id: build.c,v 1.300 2005/01/27 00:33:38 danielk1977 Exp $
           25  +** $Id: build.c,v 1.301 2005/01/29 08:32:45 danielk1977 Exp $
    26     26   */
    27     27   #include "sqliteInt.h"
    28     28   #include <ctype.h>
    29     29   
    30     30   /*
    31     31   ** This routine is called when a new SQL statement is beginning to
    32     32   ** be parsed.  Initialize the pParse structure as needed.
................................................................................
    91     91   
    92     92     /* Get the VDBE program ready for execution
    93     93     */
    94     94     if( v && pParse->nErr==0 ){
    95     95       FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
    96     96       sqlite3VdbeTrace(v, trace);
    97     97       sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
    98         -                         pParse->nTab+3, pParse->explain);
           98  +                         pParse->nTab+3, pParse->nMaxDepth+1, pParse->explain);
    99     99       pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
   100    100       pParse->colNamesSet = 0;
   101    101     }else if( pParse->rc==SQLITE_OK ){
   102    102       pParse->rc = SQLITE_ERROR;
   103    103     }
   104    104     pParse->nTab = 0;
   105    105     pParse->nMem = 0;
   106    106     pParse->nSet = 0;
   107         -  pParse->nAgg = 0;
   108    107     pParse->nVar = 0;
   109    108     pParse->cookieMask = 0;
   110    109     pParse->cookieGoto = 0;
   111    110   }
   112    111   
   113    112   /*
   114    113   ** Run the parser and code generator recursively in order to generate
................................................................................
   892    891     pCol = &(p->aCol[p->nCol-1]);
   893    892     if( !sqlite3ExprIsConstant(pExpr) ){
   894    893       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
   895    894           pCol->zName);
   896    895     }else{
   897    896       sqlite3ExprDelete(pCol->pDflt);
   898    897       pCol->pDflt = sqlite3ExprDup(pExpr);
   899         -    sqlite3ExprResolveNames(pParse,0,0,0,pExpr,0,0);
   900    898     }
   901    899     sqlite3ExprDelete(pExpr);
   902    900   }
   903    901   
   904    902   /*
   905    903   ** Designate the PRIMARY KEY for the table.  pList is a list of names 
   906    904   ** of columns that form the primary key.  If pList is NULL, then the
................................................................................
  1435   1433       */
  1436   1434       if( pSelect ){
  1437   1435         Table *pSelTab;
  1438   1436         sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
  1439   1437         sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0);
  1440   1438         sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
  1441   1439         pParse->nTab = 2;
  1442         -      sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0, 0);
         1440  +      sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
  1443   1441         sqlite3VdbeAddOp(v, OP_Close, 1, 0);
  1444   1442         if( pParse->nErr==0 ){
  1445   1443           pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
  1446   1444           if( pSelTab==0 ) return;
  1447   1445           assert( p->aCol==0 );
  1448   1446           p->nCol = pSelTab->nCol;
  1449   1447           p->aCol = pSelTab->aCol;

Changes to src/delete.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains C code routines that are called by the parser
    13     13   ** in order to generate code for DELETE FROM statements.
    14     14   **
    15         -** $Id: delete.c,v 1.99 2005/01/20 11:32:24 danielk1977 Exp $
           15  +** $Id: delete.c,v 1.100 2005/01/29 08:32:45 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** Look up every table that is named in pSrc.  If any table is not found,
    21     21   ** add an error message to pParse->zErrMsg and return NULL.  If all tables
    22     22   ** are found, return a pointer to the last table.
................................................................................
    86     86     int i;                 /* Loop counter */
    87     87     WhereInfo *pWInfo;     /* Information about the WHERE clause */
    88     88     Index *pIdx;           /* For looping over indices of the table */
    89     89     int iCur;              /* VDBE Cursor number for pTab */
    90     90     sqlite3 *db;           /* Main database structure */
    91     91     AuthContext sContext;  /* Authorization context */
    92     92     int oldIdx = -1;       /* Cursor for the OLD table of AFTER triggers */
           93  +  NameContext sNC;       /* Name context to resolve expressions in */
    93     94   
    94     95   #ifndef SQLITE_OMIT_TRIGGER
    95     96     int isView;                  /* True if attempting to delete from a view */
    96     97     int triggers_exist = 0;      /* True if any triggers exist */
    97     98   #endif
    98     99   
    99    100     sContext.pParse = 0;
................................................................................
   144    145   
   145    146     /* Allocate a cursor used to store the old.* data for a trigger.
   146    147     */
   147    148     if( triggers_exist ){ 
   148    149       oldIdx = pParse->nTab++;
   149    150     }
   150    151   
   151         -  /* Resolve the column names in all the expressions.
          152  +  /* Resolve the column names in the WHERE clause.
   152    153     */
   153    154     assert( pTabList->nSrc==1 );
   154    155     iCur = pTabList->a[0].iCursor = pParse->nTab++;
   155         -  if( sqlite3ExprResolveNames(pParse, pTabList, 0, 0, pWhere, 0, 1) ){
          156  +  memset(&sNC, 0, sizeof(sNC));
          157  +  sNC.pParse = pParse;
          158  +  sNC.pSrcList = pTabList;
          159  +  if( sqlite3ExprResolveNames(&sNC, pWhere) ){
   156    160       goto delete_from_cleanup;
   157    161     }
   158    162   
   159    163     /* Start the view context
   160    164     */
   161    165     if( isView ){
   162    166       sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
................................................................................
   172    176     sqlite3BeginWriteOperation(pParse, triggers_exist, pTab->iDb);
   173    177   
   174    178     /* If we are trying to delete from a view, construct that view into
   175    179     ** a temporary table.
   176    180     */
   177    181     if( isView ){
   178    182       Select *pView = sqlite3SelectDup(pTab->pSelect);
   179         -    sqlite3Select(pParse, pView, SRT_TempTable, iCur, 0, 0, 0, 0, 0);
          183  +    sqlite3Select(pParse, pView, SRT_TempTable, iCur, 0, 0, 0, 0);
   180    184       sqlite3SelectDelete(pView);
   181    185     }
   182    186   
   183    187     /* Initialize the counter of the number of rows deleted, if
   184    188     ** we are counting rows.
   185    189     */
   186    190     if( db->flags & SQLITE_CountRows ){

Changes to src/expr.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains routines used for analyzing expressions and
    13     13   ** for generating VDBE code that evaluates expressions in SQLite.
    14     14   **
    15         -** $Id: expr.c,v 1.188 2005/01/23 22:41:37 danielk1977 Exp $
           15  +** $Id: expr.c,v 1.189 2005/01/29 08:32:45 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   #include <ctype.h>
    19     19   
    20     20   /*
    21     21   ** Return the 'affinity' of the expression pExpr if any.
    22     22   **
................................................................................
   512    512     pNew->pPrior = sqlite3SelectDup(p->pPrior);
   513    513     pNew->nLimit = p->nLimit;
   514    514     pNew->nOffset = p->nOffset;
   515    515     pNew->iLimit = -1;
   516    516     pNew->iOffset = -1;
   517    517     pNew->ppOpenTemp = 0;
   518    518     pNew->pFetch = 0;
          519  +  pNew->isResolved = 0;
          520  +  pNew->isAgg = 0;
   519    521     return pNew;
   520    522   }
   521    523   #else
   522    524   Select *sqlite3SelectDup(Select *p){
   523    525     assert( p==0 );
   524    526     return 0;
   525    527   }
................................................................................
   746    748     pExpr->iTable = -1;
   747    749     while( pNC && cnt==0 ){
   748    750       SrcList *pSrcList = pNC->pSrcList;
   749    751       ExprList *pEList = pNC->pEList;
   750    752   
   751    753       pNC->nRef++;
   752    754       /* assert( zTab==0 || pEList==0 ); */
   753         -    for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
   754         -      Table *pTab = pItem->pTab;
   755         -      Column *pCol;
   756         -
   757         -      if( pTab==0 ) continue;
   758         -      assert( pTab->nCol>0 );
   759         -      if( zTab ){
   760         -        if( pItem->zAlias ){
   761         -          char *zTabName = pItem->zAlias;
   762         -          if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   763         -        }else{
   764         -          char *zTabName = pTab->zName;
   765         -          if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
   766         -          if( zDb!=0 && sqlite3StrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
   767         -            continue;
          755  +    if( pSrcList ){
          756  +      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
          757  +        Table *pTab = pItem->pTab;
          758  +        Column *pCol;
          759  +  
          760  +        if( pTab==0 ) continue;
          761  +        assert( pTab->nCol>0 );
          762  +        if( zTab ){
          763  +          if( pItem->zAlias ){
          764  +            char *zTabName = pItem->zAlias;
          765  +            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
          766  +          }else{
          767  +            char *zTabName = pTab->zName;
          768  +            if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
          769  +            if( zDb!=0 && sqlite3StrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
          770  +              continue;
          771  +            }
   768    772             }
   769    773           }
   770         -      }
   771         -      if( 0==(cntTab++) ){
   772         -        pExpr->iTable = pItem->iCursor;
   773         -        pExpr->iDb = pTab->iDb;
   774         -        pMatch = pItem;
   775         -      }
   776         -      for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
   777         -        if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
   778         -          cnt++;
          774  +        if( 0==(cntTab++) ){
   779    775             pExpr->iTable = pItem->iCursor;
   780         -          pMatch = pItem;
   781    776             pExpr->iDb = pTab->iDb;
   782         -          /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
   783         -          pExpr->iColumn = j==pTab->iPKey ? -1 : j;
   784         -          pExpr->affinity = pTab->aCol[j].affinity;
   785         -          pExpr->pColl = pTab->aCol[j].pColl;
   786         -          break;
          777  +          pMatch = pItem;
          778  +        }
          779  +        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
          780  +          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
          781  +            cnt++;
          782  +            pExpr->iTable = pItem->iCursor;
          783  +            pMatch = pItem;
          784  +            pExpr->iDb = pTab->iDb;
          785  +            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
          786  +            pExpr->iColumn = j==pTab->iPKey ? -1 : j;
          787  +            pExpr->affinity = pTab->aCol[j].affinity;
          788  +            pExpr->pColl = pTab->aCol[j].pColl;
          789  +            break;
          790  +          }
   787    791           }
   788    792         }
   789    793       }
   790    794   
   791    795   #ifndef SQLITE_OMIT_TRIGGER
   792    796       /* If we have not already resolved the name, then maybe 
   793    797       ** it is a new.* or old.* trigger argument reference
................................................................................
   922    926     sqliteFree(zCol);
   923    927     sqlite3ExprDelete(pExpr->pLeft);
   924    928     pExpr->pLeft = 0;
   925    929     sqlite3ExprDelete(pExpr->pRight);
   926    930     pExpr->pRight = 0;
   927    931     pExpr->op = TK_COLUMN;
   928    932     if( cnt==1 ){
   929         -    assert( pNC!=0 && pNC->pSrcList!=0 );
          933  +    assert( pNC!=0 );
   930    934       sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
   931    935     }
   932    936     return cnt!=1;
   933    937   }
   934    938   
   935    939   /*
   936    940   ** pExpr is a node that defines a function of some kind.  It might
................................................................................
   987    991   ** to TK_AGG_FUNCTION.
   988    992   */
   989    993   static int nameResolverStep(void *pArg, Expr *pExpr){
   990    994     NameContext *pNC = (NameContext*)pArg;
   991    995     SrcList *pSrcList;
   992    996     Parse *pParse;
   993    997   
          998  +  if( pExpr==0 ) return 1;
   994    999     assert( pNC!=0 );
   995   1000     pSrcList = pNC->pSrcList;
   996   1001     pParse = pNC->pParse;
   997         -  if( pExpr==0 ) return 1;
         1002  +
   998   1003     if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
   999   1004     ExprSetProperty(pExpr, EP_Resolved);
  1000   1005   #ifndef NDEBUG
  1001   1006     if( pSrcList ){
  1002   1007       int i;
  1003   1008       for(i=0; i<pSrcList->nSrc; i++){
  1004   1009         assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
................................................................................
  1013   1018       case TK_STRING: {
  1014   1019         if( pExpr->token.z[0]=='\'' ) break;
  1015   1020         /* Fall thru into the TK_ID case if this is a double-quoted string */
  1016   1021       }
  1017   1022       /* A lone identifier is the name of a column.
  1018   1023       */
  1019   1024       case TK_ID: {
  1020         -      if( pSrcList==0 ) break;
  1021   1025         lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
  1022   1026         return 1;
  1023   1027       }
  1024   1028     
  1025   1029       /* A table name and column name:     ID.ID
  1026   1030       ** Or a database, table and column:  ID.ID.ID
  1027   1031       */
  1028   1032       case TK_DOT: {
  1029   1033         Token *pColumn;
  1030   1034         Token *pTable;
  1031   1035         Token *pDb;
  1032   1036         Expr *pRight;
  1033   1037   
  1034         -      if( pSrcList==0 ) break;
         1038  +      /* if( pSrcList==0 ) break; */
  1035   1039         pRight = pExpr->pRight;
  1036   1040         if( pRight->op==TK_ID ){
  1037   1041           pDb = 0;
  1038   1042           pTable = &pExpr->pLeft->token;
  1039   1043           pColumn = &pRight->token;
  1040   1044         }else{
  1041   1045           assert( pRight->op==TK_DOT );
................................................................................
  1048   1052       }
  1049   1053   
  1050   1054       /* Resolve function names
  1051   1055       */
  1052   1056       case TK_CTIME:
  1053   1057       case TK_CTIMESTAMP:
  1054   1058       case TK_CDATE:
  1055         -    /* Note: The above three were a seperate case in sqlmoto. Reason? */
  1056   1059       case TK_GLOB:
  1057   1060       case TK_LIKE:
  1058   1061       case TK_FUNCTION: {
  1059   1062         ExprList *pList = pExpr->pList;    /* The argument list */
  1060   1063         int n = pList ? pList->nExpr : 0;  /* Number of arguments */
  1061   1064         int no_such_func = 0;       /* True if no such function exists */
  1062   1065         int wrong_num_args = 0;     /* True if wrong number of arguments */
................................................................................
  1101   1104         }
  1102   1105         if( is_agg ) pNC->allowAgg = 1;
  1103   1106         /* FIX ME:  Compute pExpr->affinity based on the expected return
  1104   1107         ** type of the function 
  1105   1108         */
  1106   1109         return is_agg;
  1107   1110       }
         1111  +#ifndef SQLITE_OMIT_SUBQUERY
         1112  +    case TK_SELECT:
         1113  +    case TK_EXISTS:
         1114  +#endif
         1115  +    case TK_IN: {
         1116  +      if( pExpr->pSelect ){
         1117  +        int nRef = pNC->nRef;
         1118  +        sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
         1119  +        assert( pNC->nRef>=nRef );
         1120  +        if( nRef!=pNC->nRef ){
         1121  +          ExprSetProperty(pExpr, EP_VarSelect);
         1122  +        }
         1123  +      }
         1124  +    }
  1108   1125     }
  1109   1126     return 0;
  1110   1127   }
  1111   1128   
  1112         -/* Forward declaration */
  1113         -static int sqlite3ExprCodeSubquery(Parse*, NameContext*, Expr*);
  1114         -
  1115   1129   /*
  1116   1130   ** This routine walks an expression tree and resolves references to
  1117   1131   ** table columns.  Nodes of the form ID.ID or ID resolve into an
  1118   1132   ** index to the table in the table list and a column offset.  The 
  1119   1133   ** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
  1120   1134   ** value is changed to the index of the referenced table in pTabList
  1121   1135   ** plus the "base" value.  The base value will ultimately become the
................................................................................
  1130   1144   ** have the correct number of arguments.  Leave an error message
  1131   1145   ** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
  1132   1146   **
  1133   1147   ** If the expression contains aggregate functions then set the EP_Agg
  1134   1148   ** property on the expression.
  1135   1149   */
  1136   1150   int sqlite3ExprResolveNames(
  1137         -  Parse *pParse,          /* The parser context */
  1138         -  SrcList *pSrcList,      /* List of tables used to resolve column names */
  1139         -  ExprList *pEList,       /* List of expressions used to resolve "AS" */
  1140         -  NameContext *pNC,       /* Namespace of enclosing statement */
  1141         -  Expr *pExpr,            /* The expression to be analyzed. */
  1142         -  int allowAgg,           /* True to allow aggregate expressions */
  1143         -  int codeSubquery        /* If true, then generate code for subqueries too */
         1151  +  NameContext *pNC,       /* Namespace to resolve expressions in. */
         1152  +  Expr *pExpr             /* The expression to be analyzed. */
  1144   1153   ){
  1145         -  NameContext sNC;
  1146         -
  1147   1154     if( pExpr==0 ) return 0;
  1148         -  memset(&sNC, 0, sizeof(sNC));
  1149         -  sNC.pSrcList = pSrcList;
  1150         -  sNC.pParse = pParse;
  1151         -  sNC.pEList = pEList;
  1152         -  sNC.allowAgg = allowAgg;
  1153         -  sNC.pNext = pNC;
  1154         -  walkExprTree(pExpr, nameResolverStep, &sNC);
  1155         -  if( sNC.hasAgg ){
  1156         -    ExprSetProperty(pExpr, EP_Agg);
  1157         -  }
  1158         -  if( sNC.nErr>0 ){
         1155  +  walkExprTree(pExpr, nameResolverStep, pNC);
         1156  +  if( pNC->nErr>0 ){
  1159   1157       ExprSetProperty(pExpr, EP_Error);
  1160         -  }else if( codeSubquery  && sqlite3ExprCodeSubquery(pParse, &sNC, pExpr) ){
  1161         -    return 1;
  1162   1158     }
  1163   1159     return ExprHasProperty(pExpr, EP_Error);
  1164   1160   }
  1165   1161   
  1166   1162   /*
  1167   1163   ** A pointer instance of this structure is used to pass information
  1168   1164   ** through walkExprTree into codeSubqueryStep().
................................................................................
  1182   1178   **           expr IN (exprlist)
  1183   1179   ** and
  1184   1180   **           expr IN (SELECT ...)
  1185   1181   **
  1186   1182   ** The first form is handled by creating a set holding the list
  1187   1183   ** of allowed values.  The second form causes the SELECT to generate 
  1188   1184   ** a temporary table.
  1189         -**
  1190         -** This routine also looks for scalar SELECTs that are part of an expression.
  1191         -** If it finds any, it generates code to write the value of that select
  1192         -** into a memory cell.
  1193         -**
  1194         -** This routine is a callback for wallExprTree() used to implement
  1195         -** sqlite3ExprCodeSubquery().  See comments on those routines for
  1196         -** additional information.
  1197   1185   */
  1198   1186   #ifndef SQLITE_OMIT_SUBQUERY
  1199         -static int codeSubqueryStep(void *pArg, Expr *pExpr){
  1200         -  QueryCoder *pCoder = (QueryCoder*)pArg;
  1201         -  Parse *pParse = pCoder->pParse;
         1187  +void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
         1188  +  int label = 0;                         /* Address after sub-select code */
         1189  +  Vdbe *v = sqlite3GetVdbe(pParse);
         1190  +  if( v==0 ) return;
         1191  +
         1192  +  /* If this is not a variable (correlated) select, then execute
         1193  +  ** it only once. Unless this is part of a trigger program. In
         1194  +  ** that case re-execute every time (this could be optimized).
         1195  +  */
         1196  +  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
         1197  +    int mem = pParse->nMem++;
         1198  +    sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
         1199  +    label = sqlite3VdbeMakeLabel(v);
         1200  +    sqlite3VdbeAddOp(v, OP_If, 0, label);
         1201  +    sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
         1202  +    sqlite3VdbeAddOp(v, OP_MemStore, mem, 1);
         1203  +  }
         1204  +
         1205  +  if( pExpr->pSelect ){
         1206  +    sqlite3VdbeAddOp(v, OP_AggContextPush, 0, 0);
         1207  +  }
  1202   1208   
  1203   1209     switch( pExpr->op ){
  1204   1210       case TK_IN: {
  1205   1211         char affinity;
  1206         -      Vdbe *v = sqlite3GetVdbe(pParse);
  1207   1212         KeyInfo keyInfo;
  1208   1213         int addr;        /* Address of OP_OpenTemp instruction */
  1209   1214   
  1210         -      if( v==0 ) return 2;
  1211   1215         affinity = sqlite3ExprAffinity(pExpr->pLeft);
  1212   1216   
  1213   1217         /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  1214   1218         ** expression it is handled the same way. A temporary table is 
  1215   1219         ** filled with single-field index keys representing the results
  1216   1220         ** from the SELECT or the <exprlist>.
  1217   1221         **
................................................................................
  1234   1238           **
  1235   1239           ** Generate code to write the results of the select into the temporary
  1236   1240           ** table allocated and opened above.
  1237   1241           */
  1238   1242           int iParm = pExpr->iTable +  (((int)affinity)<<16);
  1239   1243           ExprList *pEList;
  1240   1244           assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  1241         -        sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0, 0);
         1245  +        sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
  1242   1246           pEList = pExpr->pSelect->pEList;
  1243   1247           if( pEList && pEList->nExpr>0 ){ 
  1244   1248             keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
  1245   1249                 pEList->a[0].pExpr);
  1246   1250           }
  1247   1251         }else if( pExpr->pList ){
  1248   1252           /* Case 2:     expr IN (exprlist)
................................................................................
  1262   1266           for(i=0; i<pExpr->pList->nExpr; i++){
  1263   1267             Expr *pE2 = pExpr->pList->a[i].pExpr;
  1264   1268   
  1265   1269             /* Check that the expression is constant and valid. */
  1266   1270             if( !sqlite3ExprIsConstant(pE2) ){
  1267   1271               sqlite3ErrorMsg(pParse,
  1268   1272                 "right-hand side of IN operator must be constant");
  1269         -            return 2;
  1270         -          }
  1271         -          if( sqlite3ExprResolveNames(pParse, 0, 0, 0, pE2, 0, 0) ){
  1272         -            return 2;
         1273  +            return;
  1273   1274             }
  1274   1275   
  1275   1276             /* Evaluate the expression and insert it into the temp table */
  1276   1277             sqlite3ExprCode(pParse, pE2);
  1277   1278             sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
  1278   1279             sqlite3VdbeAddOp(v, OP_String8, 0, 0);
  1279   1280             sqlite3VdbeAddOp(v, OP_PutStrKey, pExpr->iTable, 0);
  1280   1281           }
  1281   1282         }
  1282   1283         sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
  1283         -      return 1;
         1284  +      break;
  1284   1285       }
  1285   1286   
  1286   1287       case TK_EXISTS:
  1287   1288       case TK_SELECT: {
  1288   1289         /* This has to be a scalar SELECT.  Generate code to put the
  1289   1290         ** value of this select in a memory cell and record the number
  1290   1291         ** of the memory cell in iColumn.
  1291   1292         */
  1292         -      NameContext *pNC;
  1293         -      int nRef;
  1294         -      Vdbe *v;
  1295         -      int addr;
  1296   1293         int sop;
  1297   1294         Select *pSel;
  1298   1295   
  1299         -      pNC = pCoder->pNC;
  1300         -      if( pNC ) nRef = pNC->nRef;
  1301         -      sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  1302         -      v = sqlite3GetVdbe(pParse);
  1303         -      addr = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
  1304   1296         pExpr->iColumn = pParse->nMem++;
  1305   1297         pSel = pExpr->pSelect;
  1306   1298         if( pExpr->op==TK_SELECT ){
  1307   1299           sop = SRT_Mem;
  1308   1300         }else{
  1309   1301           static const Token one = { "1", 0, 1 };
  1310   1302           sop = SRT_Exists;
  1311   1303           sqlite3ExprListDelete(pSel->pEList);
  1312   1304           pSel->pEList = sqlite3ExprListAppend(0, 
  1313   1305                             sqlite3Expr(TK_INTEGER, 0, 0, &one), 0);
  1314   1306         }
  1315         -      sqlite3Select(pParse, pSel, sop, pExpr->iColumn, 0, 0, 0, 0, pNC);
  1316         -      if( pNC && pNC->nRef>nRef ){
  1317         -        /* Subquery value changes.  Evaluate at each use */
  1318         -        pExpr->iTable = addr+1;
  1319         -        sqlite3VdbeAddOp(v, OP_Return, 0, 0);
  1320         -        sqlite3VdbeChangeP2(v, addr, sqlite3VdbeCurrentAddr(v));
  1321         -      }else{
  1322         -        /* Subquery value is constant.  evaluate only once. */
  1323         -        pExpr->iTable = -1;
  1324         -        sqlite3VdbeChangeP2(v, addr, addr+1);
  1325         -      }
  1326         -      return 1;
         1307  +      sqlite3Select(pParse, pSel, sop, pExpr->iColumn, 0, 0, 0, 0);
         1308  +      break;
  1327   1309       }
  1328   1310     }
  1329         -  return 0;
         1311  +
         1312  +  if( pExpr->pSelect ){
         1313  +    sqlite3VdbeAddOp(v, OP_AggContextPop, 0, 0);
         1314  +  }
         1315  +  if( label<0 ){
         1316  +    sqlite3VdbeResolveLabel(v, label);
         1317  +  }
         1318  +  return;
  1330   1319   }
  1331   1320   #endif /* SQLITE_OMIT_SUBQUERY */
  1332   1321   
  1333         -/*
  1334         -** Generate code to evaluate subqueries and IN operators contained
  1335         -** in expression pExpr.
  1336         -*/
  1337         -static int sqlite3ExprCodeSubquery(
  1338         -  Parse *pParse,       /* Parser */
  1339         -  NameContext *pNC,    /* First enclosing namespace.  Often NULL */
  1340         -  Expr *pExpr          /* Subquery to be coded */
  1341         -){
  1342         -#ifndef SQLITE_OMIT_SUBQUERY
  1343         -  QueryCoder sCoder;
  1344         -  sCoder.pParse = pParse;
  1345         -  sCoder.pNC = pNC;
  1346         -  walkExprTree(pExpr, codeSubqueryStep, &sCoder);
  1347         -#endif
  1348         -  return 0;
  1349         -}
  1350         -
  1351   1322   /*
  1352   1323   ** Generate an instruction that will put the integer describe by
  1353   1324   ** text z[0..n-1] on the stack.
  1354   1325   */
  1355   1326   static void codeInteger(Vdbe *v, const char *z, int n){
  1356   1327     int i;
  1357   1328     if( sqlite3GetInt32(z, &i) ){
................................................................................
  1552   1523         }
  1553   1524         sqlite3VdbeOp3(v, OP_Function, nExpr, p2, (char*)pDef, P3_FUNCDEF);
  1554   1525         break;
  1555   1526       }
  1556   1527   #ifndef SQLITE_OMIT_SUBQUERY
  1557   1528       case TK_EXISTS:
  1558   1529       case TK_SELECT: {
  1559         -      if( pExpr->iTable>=0 ){
  1560         -        sqlite3VdbeAddOp(v, OP_Gosub, 0, pExpr->iTable);
  1561         -        VdbeComment((v, "# run subquery"));
  1562         -      }
         1530  +      sqlite3CodeSubselect(pParse, pExpr);
  1563   1531         sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
  1564   1532         VdbeComment((v, "# load subquery result"));
  1565   1533         break;
  1566   1534       }
  1567   1535       case TK_IN: {
  1568   1536         int addr;
  1569   1537         char affinity;
         1538  +      sqlite3CodeSubselect(pParse, pExpr);
  1570   1539   
  1571   1540         /* Figure out the affinity to use to create a key from the results
  1572   1541         ** of the expression. affinityStr stores a static string suitable for
  1573   1542         ** P3 of OP_MakeRecord.
  1574   1543         */
  1575   1544         affinity = comparisonAffinity(pExpr);
  1576   1545   

Changes to src/insert.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains C code routines that are called by the parser
    13     13   ** to handle INSERT statements in SQLite.
    14     14   **
    15         -** $Id: insert.c,v 1.134 2005/01/20 11:32:24 danielk1977 Exp $
           15  +** $Id: insert.c,v 1.135 2005/01/29 08:32:45 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** Set P3 of the most recently inserted opcode to a column affinity
    21     21   ** string for index pIdx. A column affinity string has one character
    22     22   ** for each column in the table, according to the affinity of the column:
................................................................................
   308    308     if( pSelect ){
   309    309       /* Data is coming from a SELECT.  Generate code to implement that SELECT
   310    310       */
   311    311       int rc, iInitCode;
   312    312       iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0);
   313    313       iSelectLoop = sqlite3VdbeCurrentAddr(v);
   314    314       iInsertBlock = sqlite3VdbeMakeLabel(v);
   315         -    rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0,0);
          315  +
          316  +    /* Resolve the expressions in the SELECT statement and execute it. */
          317  +    rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0);
   316    318       if( rc || pParse->nErr || sqlite3_malloc_failed ) goto insert_cleanup;
          319  +
   317    320       iCleanup = sqlite3VdbeMakeLabel(v);
   318    321       sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup);
   319    322       assert( pSelect->pEList );
   320    323       nColumn = pSelect->pEList->nExpr;
   321    324   
   322    325       /* Set useTempTable to TRUE if the result of the SELECT statement
   323    326       ** should be written into a temporary table.  Set to FALSE if each
................................................................................
   368    371       }else{
   369    372         sqlite3VdbeChangeP2(v, iInitCode, sqlite3VdbeCurrentAddr(v));
   370    373       }
   371    374     }else{
   372    375       /* This is the case if the data for the INSERT is coming from a VALUES
   373    376       ** clause
   374    377       */
   375         -    SrcList dummy;
          378  +    NameContext sNC;
          379  +    memset(&sNC, 0, sizeof(sNC));
          380  +    sNC.pParse = pParse;
   376    381       assert( pList!=0 );
   377    382       srcTab = -1;
   378    383       useTempTable = 0;
   379    384       assert( pList );
   380    385       nColumn = pList->nExpr;
   381         -    dummy.nSrc = 0;
   382    386       for(i=0; i<nColumn; i++){
   383         -      if( sqlite3ExprResolveNames(pParse,&dummy,0,0,pList->a[i].pExpr,0,1) ){
          387  +      if( sqlite3ExprResolveNames(&sNC, pList->a[i].pExpr) ){
   384    388           goto insert_cleanup;
   385    389         }
   386    390       }
   387    391     }
   388    392   
   389    393     /* Make sure the number of columns in the source data matches the number
   390    394     ** of columns to be inserted into the table.

Changes to src/main.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** Main file for the SQLite library.  The routines in this file
    13     13   ** implement the programmer interface to the library.  Routines in
    14     14   ** other files are for internal use by SQLite and should not be
    15     15   ** accessed by users of the library.
    16     16   **
    17         -** $Id: main.c,v 1.275 2005/01/25 04:27:55 danielk1977 Exp $
           17  +** $Id: main.c,v 1.276 2005/01/29 08:32:45 danielk1977 Exp $
    18     18   */
    19     19   #include "sqliteInt.h"
    20     20   #include "os.h"
    21     21   #include <ctype.h>
    22     22   
    23     23   /*
    24     24   ** The following constant value is used by the SQLITE_BIGENDIAN and
................................................................................
  1262   1262   */
  1263   1263   int sqlite3_reset(sqlite3_stmt *pStmt){
  1264   1264     int rc;
  1265   1265     if( pStmt==0 ){
  1266   1266       rc = SQLITE_OK;
  1267   1267     }else{
  1268   1268       rc = sqlite3VdbeReset((Vdbe*)pStmt);
  1269         -    sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0);
         1269  +    sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0, 0);
  1270   1270     }
  1271   1271     return rc;
  1272   1272   }
  1273   1273   
  1274   1274   /*
  1275   1275   ** Register a new collation sequence with the database handle db.
  1276   1276   */

Changes to src/pager.c.

    14     14   ** The pager is used to access a database disk file.  It implements
    15     15   ** atomic commit and rollback through the use of a journal file that
    16     16   ** is separate from the database file.  The pager also implements file
    17     17   ** locking to prevent two processes from writing the same database
    18     18   ** file simultaneously, or one process from reading the database while
    19     19   ** another is writing.
    20     20   **
    21         -** @(#) $Id: pager.c,v 1.186 2005/01/22 03:39:39 danielk1977 Exp $
           21  +** @(#) $Id: pager.c,v 1.187 2005/01/29 08:32:45 danielk1977 Exp $
    22     22   */
    23     23   #include "sqliteInt.h"
    24     24   #include "os.h"
    25     25   #include "pager.h"
    26     26   #include <assert.h>
    27     27   #include <string.h>
    28     28   
................................................................................
  1798   1798   */
  1799   1799   int sqlite3pager_close(Pager *pPager){
  1800   1800     PgHdr *pPg, *pNext;
  1801   1801     switch( pPager->state ){
  1802   1802       case PAGER_RESERVED:
  1803   1803       case PAGER_SYNCED: 
  1804   1804       case PAGER_EXCLUSIVE: {
         1805  +      /* We ignore any IO errors that occur during the rollback
         1806  +      ** operation. So disable IO error simulation so that testing
         1807  +      ** works more easily.
         1808  +      */
         1809  +#if defined(SQLITE_TEST) && (defined(OS_UNIX) || defined(OS_WIN))
         1810  +      extern int sqlite3_io_error_pending;
         1811  +      int ioerr_cnt = sqlite3_io_error_pending;
         1812  +      sqlite3_io_error_pending = -1;
         1813  +#endif
  1805   1814         sqlite3pager_rollback(pPager);
         1815  +#if defined(SQLITE_TEST) && (defined(OS_UNIX) || defined(OS_WIN))
         1816  +      sqlite3_io_error_pending = ioerr_cnt;
         1817  +#endif
  1806   1818         if( !MEMDB ){
  1807   1819           sqlite3OsUnlock(&pPager->fd, NO_LOCK);
  1808   1820         }
  1809   1821         assert( pPager->journalOpen==0 );
  1810   1822         break;
  1811   1823       }
  1812   1824       case PAGER_SHARED: {

Changes to src/parse.y.

    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains SQLite's grammar for SQL.  Process this file
    13     13   ** using the lemon parser generator to generate C code that runs
    14     14   ** the parser.  Lemon will also generate a header file containing
    15     15   ** numeric codes for all of the tokens.
    16     16   **
    17         -** @(#) $Id: parse.y,v 1.162 2005/01/21 03:12:15 danielk1977 Exp $
           17  +** @(#) $Id: parse.y,v 1.163 2005/01/29 08:32:45 danielk1977 Exp $
    18     18   */
    19     19   %token_prefix TK_
    20     20   %token_type {Token}
    21     21   %default_type {Token}
    22     22   %extra_argument {Parse *pParse}
    23     23   %syntax_error {
    24     24     if( pParse->zErrMsg==0 ){
................................................................................
   313    313     sqlite3DropTable(pParse, X, 1);
   314    314   }
   315    315   %endif // SQLITE_OMIT_VIEW
   316    316   
   317    317   //////////////////////// The SELECT statement /////////////////////////////////
   318    318   //
   319    319   cmd ::= select(X).  {
   320         -  sqlite3Select(pParse, X, SRT_Callback, 0, 0, 0, 0, 0, 0);
          320  +  sqlite3Select(pParse, X, SRT_Callback, 0, 0, 0, 0, 0);
   321    321     sqlite3SelectDelete(X);
   322    322   }
   323    323   
   324    324   %type select {Select*}
   325    325   %destructor select {sqlite3SelectDelete($$);}
   326    326   %type oneselect {Select*}
   327    327   %destructor oneselect {sqlite3SelectDelete($$);}
................................................................................
   605    605   %endif 
   606    606   expr(A) ::= REGISTER(X).     {A = sqlite3RegisterExpr(pParse, &X);}
   607    607   expr(A) ::= VARIABLE(X).     {
   608    608     Token *pToken = &X;
   609    609     Expr *pExpr = A = sqlite3Expr(TK_VARIABLE, 0, 0, pToken);
   610    610     sqlite3ExprAssignVarNumber(pParse, pExpr);
   611    611   }
   612         -term(A) ::= ID(X) LP exprlist(Y) RP(E). {
          612  +expr(A) ::= ID(X) LP exprlist(Y) RP(E). {
   613    613     A = sqlite3ExprFunction(Y, &X);
   614    614     sqlite3ExprSpan(A,&X,&E);
   615    615   }
   616    616   expr(A) ::= ID(X) LP STAR RP(E). {
   617    617     A = sqlite3ExprFunction(0, &X);
   618    618     sqlite3ExprSpan(A,&X,&E);
   619    619   }

Changes to src/select.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains C code routines that are called by the parser
    13     13   ** to handle SELECT statements in SQLite.
    14     14   **
    15         -** $Id: select.c,v 1.234 2005/01/26 03:58:36 danielk1977 Exp $
           15  +** $Id: select.c,v 1.235 2005/01/29 08:32:45 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   
    20     20   /*
    21     21   ** Allocate a new Select structure and return a pointer to that
    22     22   ** structure.
................................................................................
   310    310     sqlite3SelectDelete(p->pPrior);
   311    311     sqliteFree(p);
   312    312   }
   313    313   
   314    314   /*
   315    315   ** Delete the aggregate information from the parse structure.
   316    316   */
          317  +#if 0
   317    318   static void sqliteAggregateInfoReset(Parse *pParse){
   318    319     sqliteFree(pParse->aAgg);
   319    320     pParse->aAgg = 0;
   320    321     pParse->nAgg = 0;
   321    322     pParse->useAgg = 0;
   322    323   }
          324  +#endif
   323    325   
   324    326   /*
   325    327   ** Insert code into "v" that will push the record on the top of the
   326    328   ** stack into the sorter.
   327    329   */
   328    330   static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
   329    331     int i;
................................................................................
   665    667   **
   666    668   ** If the declaration type is the exact datatype definition extracted from
   667    669   ** the original CREATE TABLE statement if the expression is a column.
   668    670   ** 
   669    671   ** The declaration type for an expression is either TEXT, NUMERIC or ANY.
   670    672   ** The declaration type for a ROWID field is INTEGER.
   671    673   */
   672         -static const char *columnType(Parse *pParse, SrcList *pTabList, Expr *pExpr){
          674  +static const char *columnType(NameContext *pNC, Expr *pExpr){
   673    675     char const *zType;
   674    676     int j;
   675         -  if( pExpr==0 || pTabList==0 ) return 0;
   676         -
   677         -  sqlite3ExprResolveNames(pParse, pTabList, 0, 0, pExpr, 1, 0);
          677  +  if( pExpr==0 || pNC->pSrcList==0 ) return 0;
   678    678   
   679    679     /* The TK_AS operator can only occur in ORDER BY, GROUP BY, HAVING,
   680    680     ** and LIMIT clauses.  But pExpr originates in the result set of a
   681    681     ** SELECT.  So pExpr can never contain an AS operator.
   682    682     */
   683    683     assert( pExpr->op!=TK_AS );
   684    684   
   685    685     switch( pExpr->op ){
   686    686       case TK_COLUMN: {
   687         -      Table *pTab;
          687  +      Table *pTab = 0;
   688    688         int iCol = pExpr->iColumn;
   689         -      for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable; j++){}
   690         -      assert( j<pTabList->nSrc );
   691         -      pTab = pTabList->a[j].pTab;
          689  +      while( pNC && !pTab ){
          690  +        SrcList *pTabList = pNC->pSrcList;
          691  +        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
          692  +        if( j<pTabList->nSrc ){
          693  +          pTab = pTabList->a[j].pTab;
          694  +        }else{
          695  +          pNC = pNC->pNext;
          696  +        }
          697  +      }
          698  +      assert( pTab );
   692    699         if( iCol<0 ) iCol = pTab->iPKey;
   693    700         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
   694    701         if( iCol<0 ){
   695    702           zType = "INTEGER";
   696    703         }else{
   697    704           zType = pTab->aCol[iCol].zType;
   698    705         }
   699    706         break;
   700    707       }
   701    708   #ifndef SQLITE_OMIT_SUBQUERY
   702    709       case TK_SELECT: {
          710  +      NameContext sNC;
   703    711         Select *pS = pExpr->pSelect;
   704         -      zType = columnType(pParse, pS->pSrc, pS->pEList->a[0].pExpr); 
          712  +      sNC.pSrcList = pExpr->pSelect->pSrc;
          713  +      sNC.pNext = pNC;
          714  +      zType = columnType(&sNC, pS->pEList->a[0].pExpr); 
   705    715         break;
   706    716       }
   707    717   #endif
   708    718       default:
   709    719         zType = 0;
   710    720     }
   711    721     
................................................................................
   719    729   static void generateColumnTypes(
   720    730     Parse *pParse,      /* Parser context */
   721    731     SrcList *pTabList,  /* List of tables */
   722    732     ExprList *pEList    /* Expressions defining the result set */
   723    733   ){
   724    734     Vdbe *v = pParse->pVdbe;
   725    735     int i;
          736  +  NameContext sNC;
          737  +  sNC.pSrcList = pTabList;
   726    738     for(i=0; i<pEList->nExpr; i++){
   727    739       Expr *p = pEList->a[i].pExpr;
   728         -    const char *zType = columnType(pParse, pTabList, p);
          740  +    const char *zType = columnType(&sNC, p);
   729    741       if( zType==0 ) continue;
   730    742       /* The vdbe must make it's own copy of the column-type, in case the 
   731    743       ** schema is reset before this virtual machine is deleted.
   732    744       */
   733    745       sqlite3VdbeSetColName(v, i+pEList->nExpr, zType, strlen(zType));
   734    746     }
   735    747   }
................................................................................
   856    868     pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
   857    869     for(i=0, pCol=aCol; i<pTab->nCol; i++, pCol++){
   858    870       Expr *p, *pR;
   859    871       char *zType;
   860    872       char *zName;
   861    873       char *zBasename;
   862    874       int cnt;
          875  +    NameContext sNC;
   863    876       
   864    877       /* Get an appropriate name for the column
   865    878       */
   866    879       p = pEList->a[i].pExpr;
   867    880       assert( p->pRight==0 || p->pRight->token.z==0 || p->pRight->token.z[0]!=0 );
   868    881       if( (zName = pEList->a[i].zName)!=0 ){
   869    882         /* If the column contains an "AS <name>" phrase, use <name> as the name */
................................................................................
   895    908         sqliteFree(zBasename);
   896    909       }
   897    910       pCol->zName = zName;
   898    911   
   899    912       /* Get the typename, type affinity, and collating sequence for the
   900    913       ** column.
   901    914       */
   902         -    zType = sqliteStrDup(columnType(pParse, pSelect->pSrc ,p));
          915  +    sNC.pSrcList = pSelect->pSrc;
          916  +    zType = sqliteStrDup(columnType(&sNC, p));
   903    917       pCol->zType = zType;
   904    918       pCol->affinity = SQLITE_AFF_NUMERIC;
   905    919       if( zType ){
   906    920         pCol->affinity = sqlite3AffinityType(zType, strlen(zType));
   907    921       }
   908    922       pCol->pColl = sqlite3ExprCollSeq(pParse, p);
   909    923       if( !pCol->pColl ){
................................................................................
   971    985   #ifndef SQLITE_OMIT_SUBQUERY
   972    986         /* A sub-query in the FROM clause of a SELECT */
   973    987         assert( pFrom->pSelect!=0 );
   974    988         if( pFrom->zAlias==0 ){
   975    989           pFrom->zAlias =
   976    990             sqlite3MPrintf("sqlite_subquery_%p_", (void*)pFrom->pSelect);
   977    991         }
          992  +      sqlite3SelectResolve(pParse, pFrom->pSelect, 0);
   978    993         pFrom->pTab = pTab = 
   979    994           sqlite3ResultSetOfSelect(pParse, pFrom->zAlias, pFrom->pSelect);
   980    995         if( pTab==0 ){
   981    996           return 1;
   982    997         }
   983    998         /* The isTransient flag indicates that the Table structure has been
   984    999         ** dynamically allocated and may be freed at any time.  In other words,
................................................................................
  1488   1503     /* Generate code for the left and right SELECT statements.
  1489   1504     */
  1490   1505     switch( p->op ){
  1491   1506       case TK_ALL: {
  1492   1507         if( p->pOrderBy==0 ){
  1493   1508           pPrior->nLimit = p->nLimit;
  1494   1509           pPrior->nOffset = p->nOffset;
  1495         -        rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff, 0);
         1510  +        rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff);
  1496   1511           if( rc ){
  1497   1512             goto multi_select_end;
  1498   1513           }
  1499   1514           p->pPrior = 0;
  1500   1515           p->iLimit = pPrior->iLimit;
  1501   1516           p->iOffset = pPrior->iOffset;
  1502   1517           p->nLimit = -1;
  1503   1518           p->nOffset = 0;
  1504         -        rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff, 0);
         1519  +        rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff);
  1505   1520           p->pPrior = pPrior;
  1506   1521           if( rc ){
  1507   1522             goto multi_select_end;
  1508   1523           }
  1509   1524           break;
  1510   1525         }
  1511   1526         /* For UNION ALL ... ORDER BY fall through to the next case */
................................................................................
  1546   1561   	assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
  1547   1562           aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, unionTab, 0);
  1548   1563           assert( p->pEList );
  1549   1564         }
  1550   1565   
  1551   1566         /* Code the SELECT statements to our left
  1552   1567         */
  1553         -      rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff, 0);
         1568  +      assert( !pPrior->pOrderBy );
         1569  +      rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff);
  1554   1570         if( rc ){
  1555   1571           goto multi_select_end;
  1556   1572         }
  1557   1573   
  1558   1574         /* Code the current SELECT statement
  1559   1575         */
  1560   1576         switch( p->op ){
................................................................................
  1565   1581         p->pPrior = 0;
  1566   1582         pOrderBy = p->pOrderBy;
  1567   1583         p->pOrderBy = 0;
  1568   1584         nLimit = p->nLimit;
  1569   1585         p->nLimit = -1;
  1570   1586         nOffset = p->nOffset;
  1571   1587         p->nOffset = 0;
  1572         -      rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff, 0);
         1588  +      rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff);
  1573   1589         p->pPrior = pPrior;
  1574   1590         p->pOrderBy = pOrderBy;
  1575   1591         p->nLimit = nLimit;
  1576   1592         p->nOffset = nOffset;
  1577   1593         p->iLimit = -1;
  1578   1594         p->iOffset = -1;
  1579   1595         if( rc ){
................................................................................
  1634   1650         sqlite3VdbeAddOp(v, OP_KeyAsData, tab1, 1);
  1635   1651         assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
  1636   1652         aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab1, 0);
  1637   1653         assert( p->pEList );
  1638   1654   
  1639   1655         /* Code the SELECTs to our left into temporary table "tab1".
  1640   1656         */
  1641         -      rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff, 0);
         1657  +      rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff);
  1642   1658         if( rc ){
  1643   1659           goto multi_select_end;
  1644   1660         }
  1645   1661   
  1646   1662         /* Code the current SELECT into temporary table "tab2"
  1647   1663         */
  1648   1664         addr = sqlite3VdbeAddOp(v, OP_OpenTemp, tab2, 0);
................................................................................
  1654   1670         assert( nAddr<sizeof(aAddr)/sizeof(aAddr[0]) );
  1655   1671         aAddr[nAddr++] = sqlite3VdbeAddOp(v, OP_SetNumColumns, tab2, 0);
  1656   1672         p->pPrior = 0;
  1657   1673         nLimit = p->nLimit;
  1658   1674         p->nLimit = -1;
  1659   1675         nOffset = p->nOffset;
  1660   1676         p->nOffset = 0;
  1661         -      rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff, 0);
         1677  +      rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff);
  1662   1678         p->pPrior = pPrior;
  1663   1679         p->nLimit = nLimit;
  1664   1680         p->nOffset = nOffset;
  1665   1681         if( rc ){
  1666   1682           goto multi_select_end;
  1667   1683         }
  1668   1684   
................................................................................
  1753   1769   
  1754   1770       if( p->pOrderBy ){
  1755   1771         struct ExprList_item *pOrderByTerm = p->pOrderBy->a;
  1756   1772         for(i=0; i<p->pOrderBy->nExpr; i++, pOrderByTerm++){
  1757   1773           Expr *pExpr = pOrderByTerm->pExpr;
  1758   1774           char *zName = pOrderByTerm->zName;
  1759   1775           assert( pExpr->op==TK_COLUMN && pExpr->iColumn<nCol );
  1760         -        assert( !pExpr->pColl );
         1776  +        /* assert( !pExpr->pColl ); */
  1761   1777           if( zName ){
  1762   1778             pExpr->pColl = sqlite3LocateCollSeq(pParse, zName, -1);
  1763   1779           }else{
  1764   1780             pExpr->pColl = pKeyInfo->aColl[pExpr->iColumn];
  1765   1781           }
  1766   1782         }
  1767   1783         generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm);
................................................................................
  1793   1809   ** whose result set is defined by pEList appears as entry in the
  1794   1810   ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  1795   1811   ** FORM clause entry is iTable.  This routine make the necessary 
  1796   1812   ** changes to pExpr so that it refers directly to the source table
  1797   1813   ** of the subquery rather the result set of the subquery.
  1798   1814   */
  1799   1815   static void substExprList(ExprList*,int,ExprList*);  /* Forward Decl */
         1816  +static void substSelect(Select *, int, ExprList *);  /* Forward Decl */
  1800   1817   static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
  1801   1818     if( pExpr==0 ) return;
  1802   1819     if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  1803   1820       if( pExpr->iColumn<0 ){
  1804   1821         pExpr->op = TK_NULL;
  1805   1822       }else{
  1806   1823         Expr *pNew;
................................................................................
  1820   1837         pExpr->iAgg = pNew->iAgg;
  1821   1838         sqlite3TokenCopy(&pExpr->token, &pNew->token);
  1822   1839         sqlite3TokenCopy(&pExpr->span, &pNew->span);
  1823   1840       }
  1824   1841     }else{
  1825   1842       substExpr(pExpr->pLeft, iTable, pEList);
  1826   1843       substExpr(pExpr->pRight, iTable, pEList);
         1844  +    substSelect(pExpr->pSelect, iTable, pEList);
  1827   1845       substExprList(pExpr->pList, iTable, pEList);
  1828   1846     }
  1829   1847   }
  1830         -static void 
  1831         -substExprList(ExprList *pList, int iTable, ExprList *pEList){
         1848  +static void substExprList(ExprList *pList, int iTable, ExprList *pEList){
  1832   1849     int i;
  1833   1850     if( pList==0 ) return;
  1834   1851     for(i=0; i<pList->nExpr; i++){
  1835   1852       substExpr(pList->a[i].pExpr, iTable, pEList);
  1836   1853     }
         1854  +}
         1855  +static void substSelect(Select *p, int iTable, ExprList *pEList){
         1856  +  if( !p ) return;
         1857  +  substExprList(p->pEList, iTable, pEList);
         1858  +  substExprList(p->pGroupBy, iTable, pEList);
         1859  +  substExprList(p->pOrderBy, iTable, pEList);
         1860  +  substExpr(p->pHaving, iTable, pEList);
         1861  +  substExpr(p->pWhere, iTable, pEList);
  1837   1862   }
  1838   1863   #endif /* !defined(SQLITE_OMIT_VIEW) */
  1839   1864   
  1840   1865   #ifndef SQLITE_OMIT_VIEW
  1841   1866   /*
  1842   1867   ** This routine attempts to flatten subqueries in order to speed
  1843   1868   ** execution.  It returns 1 if it makes changes and 0 if no flattening
................................................................................
  2232   2257   ** the number of errors seen.
  2233   2258   **
  2234   2259   ** An ORDER BY or GROUP BY is a list of expressions.  If any expression
  2235   2260   ** is an integer constant, then that expression is replaced by the
  2236   2261   ** corresponding entry in the result set.
  2237   2262   */
  2238   2263   static int processOrderGroupBy(
  2239         -  Parse *pParse,        /* Parsing context */
         2264  +  NameContext *pNC,     /* Name context of the SELECT statement. */
  2240   2265     ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
  2241         -  SrcList *pTabList,    /* The FROM clause */
  2242         -  ExprList *pEList,     /* The result set */
  2243         -  NameContext *pNC,     /* Name context for enclosing query */
  2244         -  int isAgg,            /* True if aggregate functions are involved */
  2245   2266     const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
  2246   2267   ){
  2247   2268     int i;
         2269  +  ExprList *pEList = pNC->pEList;     /* The result set of the SELECT */
         2270  +  Parse *pParse = pNC->pParse;     /* The result set of the SELECT */
         2271  +  assert( pEList );
         2272  +
  2248   2273     if( pOrderBy==0 ) return 0;
  2249   2274     for(i=0; i<pOrderBy->nExpr; i++){
  2250   2275       int iCol;
  2251   2276       Expr *pE = pOrderBy->a[i].pExpr;
  2252         -    if( sqlite3ExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
  2253         -      sqlite3ExprDelete(pE);
  2254         -      pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
  2255         -    }
  2256         -    if( sqlite3ExprResolveNames(pParse, pTabList, pEList, pNC, pE, isAgg, 1) ){
  2257         -      return 1;
  2258         -    }
  2259         -    if( sqlite3ExprIsConstant(pE) ){
  2260         -      if( sqlite3ExprIsInteger(pE, &iCol)==0 ){
  2261         -        sqlite3ErrorMsg(pParse,
  2262         -          "%s BY terms must not be non-integer constants", zType);
  2263         -        return 1;
  2264         -      }else if( iCol<=0 || iCol>pEList->nExpr ){
         2277  +    if( sqlite3ExprIsInteger(pE, &iCol) ){
         2278  +      if( iCol>0 && iCol<=pEList->nExpr ){
         2279  +        sqlite3ExprDelete(pE);
         2280  +        pE = pOrderBy->a[i].pExpr = sqlite3ExprDup(pEList->a[iCol-1].pExpr);
         2281  +      }else{
  2265   2282           sqlite3ErrorMsg(pParse, 
  2266   2283              "%s BY column number %d out of range - should be "
  2267   2284              "between 1 and %d", zType, iCol, pEList->nExpr);
  2268   2285           return 1;
  2269   2286         }
  2270   2287       }
         2288  +    if( sqlite3ExprResolveNames(pNC, pE) ){
         2289  +      return 1;
         2290  +    }
         2291  +    if( sqlite3ExprIsConstant(pE) ){
         2292  +      sqlite3ErrorMsg(pParse,
         2293  +          "%s BY terms must not be non-integer constants", zType);
         2294  +      return 1;
         2295  +    }
  2271   2296     }
  2272   2297     return 0;
  2273   2298   }
  2274   2299   
         2300  +/*
         2301  +** This routine resolves any names used in the result set of the
         2302  +** supplied SELECT statement. If the SELECT statement being resolved
         2303  +** is a sub-select, then pOuterNC is a pointer to the NameContext 
         2304  +** of the parent SELECT.
         2305  +*/
         2306  +int sqlite3SelectResolve(
         2307  +  Parse *pParse,         /* The parser context */
         2308  +  Select *p,             /* The SELECT statement being coded. */
         2309  +  NameContext *pOuterNC  /* The outer name context. May be NULL. */
         2310  +){
         2311  +  ExprList *pEList;          /* Result set. */
         2312  +  int i;                     /* For-loop variable used in multiple places */
         2313  +  NameContext sNC;           /* Local name-context */
         2314  +
         2315  +  /* If this routine has run before, return immediately. */
         2316  +  if( p->isResolved ){
         2317  +    assert( !pOuterNC );
         2318  +    return SQLITE_OK;
         2319  +  }
         2320  +  p->isResolved = 1;
         2321  +
         2322  +  /* If there have already been errors, do nothing. */
         2323  +  if( pParse->nErr>0 ){
         2324  +    return SQLITE_ERROR;
         2325  +  }
         2326  +
         2327  +  /* Prepare the select statement. This call will allocate all cursors
         2328  +  ** required to handle the tables and subqueries in the FROM clause.
         2329  +  */
         2330  +  if( prepSelectStmt(pParse, p) ){
         2331  +    return SQLITE_ERROR;
         2332  +  }
         2333  +
         2334  +  /* Set up the local name-context to pass to ExprResolveNames().  */
         2335  +  sNC.pNext = pOuterNC;
         2336  +  sNC.pParse = pParse;
         2337  +  sNC.pSrcList = p->pSrc;
         2338  +  sNC.allowAgg = 1;
         2339  +  sNC.hasAgg = 0;
         2340  +  sNC.nErr = 0;
         2341  +  sNC.nRef = 0;
         2342  +  sNC.pEList = 0;
         2343  +
         2344  +  /* NameContext.nDepth stores the depth of recursion for this query. For
         2345  +  ** an outer query (e.g. SELECT * FROM sqlite_master) this is 1. For
         2346  +  ** a subquery it is 2. For a subquery of a subquery, 3. And so on. 
         2347  +  ** Parse.nMaxDepth is the maximum depth for any subquery resolved so
         2348  +  ** far. This is used to determine the number of aggregate contexts
         2349  +  ** required at runtime.
         2350  +  */
         2351  +  sNC.nDepth = (pOuterNC?pOuterNC->nDepth+1:1);
         2352  +  if( sNC.nDepth>pParse->nMaxDepth ){
         2353  +    pParse->nMaxDepth = sNC.nDepth;
         2354  +  }
         2355  +
         2356  +  /* Resolve names in the result set. */
         2357  +  pEList = p->pEList;
         2358  +  if( !pEList ) return SQLITE_ERROR;
         2359  +  for(i=0; i<pEList->nExpr; i++){
         2360  +    Expr *pX = pEList->a[i].pExpr;
         2361  +    if( sqlite3ExprResolveNames(&sNC, pX) ){
         2362  +      return SQLITE_ERROR;
         2363  +    }
         2364  +  }
         2365  +
         2366  +  /* If there are no aggregate functions in the result-set, and no GROUP BY 
         2367  +  ** expression, do not allow aggregates in any of the other expressions.
         2368  +  */
         2369  +  assert( !p->isAgg );
         2370  +  if( p->pGroupBy || sNC.hasAgg ){
         2371  +    p->isAgg = 1;
         2372  +  }else{
         2373  +    sNC.allowAgg = 0;
         2374  +  }
         2375  +
         2376  +  /* If a HAVING clause is present, then there must be a GROUP BY clause.
         2377  +  */
         2378  +  if( p->pHaving && !p->pGroupBy ){
         2379  +    sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
         2380  +    return SQLITE_ERROR;
         2381  +  }
         2382  +
         2383  +  /* Add the expression list to the name-context before parsing the
         2384  +  ** other expressions in the SELECT statement. This is so that
         2385  +  ** expressions in the WHERE clause (etc.) can refer to expressions by
         2386  +  ** aliases in the result set.
         2387  +  **
         2388  +  ** Minor point: If this is the case, then the expression will be
         2389  +  ** re-evaluated for each reference to it.
         2390  +  */
         2391  +  sNC.pEList = p->pEList;
         2392  +  if( sqlite3ExprResolveNames(&sNC, p->pWhere) ||
         2393  +      sqlite3ExprResolveNames(&sNC, p->pHaving) ||
         2394  +      processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") ||
         2395  +      processOrderGroupBy(&sNC, p->pGroupBy, "GROUP")
         2396  +  ){
         2397  +    return SQLITE_ERROR;
         2398  +  }
         2399  +
         2400  +  return SQLITE_OK;
         2401  +}
         2402  +
         2403  +/*
         2404  +** An instance of the following struct is used by sqlite3Select()
         2405  +** to save aggregate related information from the Parse object
         2406  +** at the start of each call and to restore it at the end. See
         2407  +** saveAggregateInfo() and restoreAggregateInfo().
         2408  +*/ 
         2409  +struct AggregateInfo {
         2410  +  u8 useAgg;
         2411  +  int nAgg;
         2412  +  AggExpr *aAgg;
         2413  +};
         2414  +typedef struct AggregateInfo AggregateInfo;
         2415  +
         2416  +/* 
         2417  +** Copy aggregate related information from the Parse structure
         2418  +** into the AggregateInfo structure. Zero the aggregate related
         2419  +** values in the Parse struct.
         2420  +*/
         2421  +static void saveAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
         2422  +  pInfo->aAgg = pParse->aAgg;
         2423  +  pInfo->nAgg = pParse->nAgg;
         2424  +  pInfo->useAgg = pParse->useAgg;
         2425  +  pParse->aAgg = 0;
         2426  +  pParse->nAgg = 0;
         2427  +  pParse->useAgg = 0;
         2428  +}
         2429  +
         2430  +/*
         2431  +** Copy aggregate related information from the AggregateInfo struct
         2432  +** back into the Parse structure. The aggregate related information
         2433  +** currently stored in the Parse structure is deleted.
         2434  +*/
         2435  +static void restoreAggregateInfo(Parse *pParse, AggregateInfo *pInfo){
         2436  +  sqliteFree(pParse->aAgg);
         2437  +  pParse->aAgg = pInfo->aAgg;
         2438  +  pParse->nAgg = pInfo->nAgg;
         2439  +  pParse->useAgg = pInfo->useAgg;
         2440  +}
         2441  +  
  2275   2442   /*
  2276   2443   ** Generate code for the given SELECT statement.
  2277   2444   **
  2278   2445   ** The results are distributed in various ways depending on the
  2279   2446   ** value of eDest and iParm.
  2280   2447   **
  2281   2448   **     eDest Value       Result
................................................................................
  2328   2495     Parse *pParse,         /* The parser context */
  2329   2496     Select *p,             /* The SELECT statement being coded. */
  2330   2497     int eDest,             /* How to dispose of the results */
  2331   2498     int iParm,             /* A parameter used by the eDest disposal method */
  2332   2499     Select *pParent,       /* Another SELECT for which this is a sub-query */
  2333   2500     int parentTab,         /* Index in pParent->pSrc of this query */
  2334   2501     int *pParentAgg,       /* True if pParent uses aggregate functions */
  2335         -  char *aff,             /* If eDest is SRT_Union, the affinity string */
  2336         -  NameContext *pNC       /* Namespace of the next outer query */
         2502  +  char *aff              /* If eDest is SRT_Union, the affinity string */
  2337   2503   ){
  2338   2504     int i;
  2339   2505     WhereInfo *pWInfo;
  2340   2506     Vdbe *v;
  2341         -  int isAgg = 0;         /* True for select lists like "count(*)" */
         2507  +  int isAgg;             /* True for select lists like "count(*)" */
  2342   2508     ExprList *pEList;      /* List of columns to extract. */
  2343   2509     SrcList *pTabList;     /* List of tables to select from */
  2344   2510     Expr *pWhere;          /* The WHERE clause.  May be NULL */
  2345   2511     ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
  2346   2512     ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
  2347   2513     Expr *pHaving;         /* The HAVING clause.  May be NULL */
  2348   2514     int isDistinct;        /* True if the DISTINCT keyword is present */
  2349   2515     int distinct;          /* Table to use for the distinct set */
  2350   2516     int rc = 1;            /* Value to return from this function */
         2517  +  AggregateInfo sAggInfo;
  2351   2518   
  2352   2519     if( sqlite3_malloc_failed || pParse->nErr || p==0 ) return 1;
  2353   2520     if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  2354   2521   
  2355   2522   #ifndef SQLITE_OMIT_COMPOUND_SELECT
  2356   2523     /* If there is are a sequence of queries, do the earlier ones first.
  2357   2524     */
................................................................................
  2361   2528         sqlite3ErrorMsg(pParse, "cursors cannot be used on compound queries");
  2362   2529         goto select_end;
  2363   2530       }
  2364   2531   #endif
  2365   2532       return multiSelect(pParse, p, eDest, iParm, aff);
  2366   2533     }
  2367   2534   #endif
         2535  +
         2536  +  saveAggregateInfo(pParse, &sAggInfo);
         2537  +  pOrderBy = p->pOrderBy;
         2538  +  if( eDest==SRT_Union || eDest==SRT_Except || eDest==SRT_Discard ){
         2539  +    p->pOrderBy = 0;
         2540  +  }
         2541  +  if( sqlite3SelectResolve(pParse, p, 0) ){
         2542  +    goto select_end;
         2543  +  }
         2544  +  p->pOrderBy = pOrderBy;
  2368   2545   
  2369   2546     /* Make local copies of the parameters for this query.
  2370   2547     */
  2371   2548     pTabList = p->pSrc;
  2372   2549     pWhere = p->pWhere;
  2373         -  pOrderBy = p->pOrderBy;
  2374   2550     pGroupBy = p->pGroupBy;
  2375   2551     pHaving = p->pHaving;
         2552  +  isAgg = p->isAgg;
  2376   2553     isDistinct = p->isDistinct;
         2554  +  pEList = p->pEList;
         2555  +  if( pEList==0 ) goto select_end;
  2377   2556   
  2378   2557     /* 
  2379   2558     ** Do not even attempt to generate any code if we have already seen
  2380   2559     ** errors before this routine starts.
  2381   2560     */
  2382   2561     if( pParse->nErr>0 ) goto select_end;
  2383   2562   
  2384         -  if( prepSelectStmt(pParse, p) ){
  2385         -    goto select_end;
  2386         -  }
  2387         -  pWhere = p->pWhere;
  2388         -  pEList = p->pEList;
  2389         -  if( pEList==0 ) goto select_end;
  2390         -
  2391   2563     /* If writing to memory or generating a set
  2392   2564     ** only a single column may be output.
  2393   2565     */
  2394   2566     assert( eDest!=SRT_Exists || pEList->nExpr==1 );
  2395   2567   #ifndef SQLITE_OMIT_SUBQUERY
  2396   2568     if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
  2397   2569       sqlite3ErrorMsg(pParse, "only a single result allowed for "
................................................................................
  2408   2580       case SRT_Discard:
  2409   2581         pOrderBy = 0;
  2410   2582         break;
  2411   2583       default:
  2412   2584         break;
  2413   2585     }
  2414   2586   
  2415         -  /* At this point, we should have allocated all the cursors that we
  2416         -  ** need to handle subquerys and temporary tables.  
  2417         -  **
  2418         -  ** Resolve the column names and do a semantics check on all the expressions.
  2419         -  */
  2420         -  for(i=0; i<pEList->nExpr; i++){
  2421         -    Expr *pX = pEList->a[i].pExpr;
  2422         -    if( sqlite3ExprResolveNames(pParse, pTabList, 0, pNC, pX, 1, 1) ){
  2423         -      goto select_end;
  2424         -    }
  2425         -    if( ExprHasProperty(pX, EP_Agg) ) isAgg = 1;
  2426         -  }
  2427         -  if( sqlite3ExprResolveNames(pParse, pTabList, pEList, pNC, pWhere, 0, 1) ){
  2428         -    goto select_end;
  2429         -  }
  2430         -  if( pHaving ){
  2431         -    if( pGroupBy==0 ){
  2432         -      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  2433         -      goto select_end;
  2434         -    }
  2435         -    if( sqlite3ExprResolveNames(pParse, pTabList, pEList, pNC, pHaving, 1, 1) ){
  2436         -      goto select_end;
  2437         -    }
  2438         -  }
  2439         -  if( pGroupBy ){
  2440         -    isAgg = 1;
  2441         -  }
  2442         -  if( processOrderGroupBy(pParse,pOrderBy,pTabList,pEList,pNC,isAgg,"ORDER")
  2443         -   || processOrderGroupBy(pParse,pGroupBy,pTabList,pEList,pNC,isAgg,"GROUP")
  2444         -  ){
  2445         -    goto select_end;
  2446         -  }
  2447         -
  2448   2587     /* We cannot use a SQL cursor on a join or on a DISTINCT query
  2449   2588     */
  2450   2589   #ifndef SQLITE_OMIT_CURSOR
  2451   2590     if( p->pFetch ){
  2452   2591       if( p->isDistinct ){
  2453   2592         sqlite3ErrorMsg(pParse, "cursors cannot be used on DISTINCT queries");
  2454   2593         goto select_end;
................................................................................
  2489   2628         zSavedAuthContext = pParse->zAuthContext;
  2490   2629         pParse->zAuthContext = pTabList->a[i].zName;
  2491   2630         needRestoreContext = 1;
  2492   2631       }else{
  2493   2632         needRestoreContext = 0;
  2494   2633       }
  2495   2634       sqlite3Select(pParse, pTabList->a[i].pSelect, SRT_TempTable, 
  2496         -                 pTabList->a[i].iCursor, p, i, &isAgg, 0, 0);
         2635  +                 pTabList->a[i].iCursor, p, i, &isAgg, 0);
  2497   2636       if( needRestoreContext ){
  2498   2637         pParse->zAuthContext = zSavedAuthContext;
  2499   2638       }
  2500   2639       pTabList = p->pSrc;
  2501   2640       pWhere = p->pWhere;
  2502   2641       if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
  2503   2642         pOrderBy = p->pOrderBy;
................................................................................
  2519   2658     /* Check to see if this is a subquery that can be "flattened" into its parent.
  2520   2659     ** If flattening is a possiblity, do so and return immediately.  
  2521   2660     */
  2522   2661   #ifndef SQLITE_OMIT_VIEW
  2523   2662     if( pParent && pParentAgg &&
  2524   2663         flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
  2525   2664       if( isAgg ) *pParentAgg = 1;
  2526         -    return rc;
         2665  +    goto select_end;
  2527   2666     }
  2528   2667   #endif
  2529   2668   
  2530   2669     /* If there is an ORDER BY clause, resolve any collation sequences
  2531   2670     ** names that have been explicitly specified.
  2532   2671     */
  2533   2672     if( pOrderBy ){
................................................................................
  2551   2690     if( eDest==SRT_TempTable ){
  2552   2691       sqlite3VdbeAddOp(v, OP_OpenTemp, iParm, 0);
  2553   2692       sqlite3VdbeAddOp(v, OP_SetNumColumns, iParm, pEList->nExpr);
  2554   2693     }
  2555   2694   
  2556   2695     /* Do an analysis of aggregate expressions.
  2557   2696     */
  2558         -  sqliteAggregateInfoReset(pParse);
  2559   2697     if( isAgg || pGroupBy ){
  2560   2698       assert( pParse->nAgg==0 );
  2561   2699       isAgg = 1;
  2562   2700       for(i=0; i<pEList->nExpr; i++){
  2563   2701         if( sqlite3ExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
  2564   2702           goto select_end;
  2565   2703         }
................................................................................
  2742   2880     */
  2743   2881     rc = 0;
  2744   2882   
  2745   2883     /* Control jumps to here if an error is encountered above, or upon
  2746   2884     ** successful coding of the SELECT.
  2747   2885     */
  2748   2886   select_end:
  2749         -  sqliteAggregateInfoReset(pParse);
         2887  +  restoreAggregateInfo(pParse, &sAggInfo);
  2750   2888     return rc;
  2751   2889   }

Changes to src/sqliteInt.h.

     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** Internal interface definitions for SQLite.
    13     13   **
    14         -** @(#) $Id: sqliteInt.h,v 1.363 2005/01/22 03:03:55 drh Exp $
           14  +** @(#) $Id: sqliteInt.h,v 1.364 2005/01/29 08:32:45 danielk1977 Exp $
    15     15   */
    16     16   #ifndef _SQLITEINT_H_
    17     17   #define _SQLITEINT_H_
    18     18   
    19     19   /*
    20     20   ** Cursor support is turned off unless the SQLITE_ENABLE_CURSOR option
    21     21   ** is defined.
................................................................................
   834    834   ** The following are the meanings of bits in the Expr.flags field.
   835    835   */
   836    836   #define EP_FromJoin     0x0001  /* Originated in ON or USING clause of a join */
   837    837   #define EP_Agg          0x0002  /* Contains one or more aggregate functions */
   838    838   #define EP_Resolved     0x0004  /* IDs have been resolved to COLUMNs */
   839    839   #define EP_Error        0x0008  /* Expression contains one or more errors */
   840    840   #define EP_Not          0x0010  /* Operator preceeded by NOT */
          841  +#define EP_VarSelect    0x0020  /* pSelect is correlated, not constant */
   841    842   
   842    843   /*
   843    844   ** These macros can be used to test, set, or clear bits in the 
   844    845   ** Expr.flags field.
   845    846   */
   846    847   #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
   847    848   #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
................................................................................
   979    980   */
   980    981   struct Fetch {
   981    982     SqlCursor *pCursor;  /* Cursor used by the fetch */
   982    983     int isBackwards;     /* Cursor moves backwards if true, forward if false */
   983    984     int doRewind;        /* True to rewind cursor before starting */
   984    985   };
   985    986   
          987  +/*
          988  +** A NameContext defines a context in which to resolve table and column
          989  +** names.  The context consists of a list of tables (the pSrcList) field and
          990  +** a list of named expression (pEList).  The named expression list may
          991  +** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
          992  +** to the table being operated on by INSERT, UPDATE, or DELETE.  The
          993  +** pEList corresponds to the result set of a SELECT and is NULL for
          994  +** other statements.
          995  +**
          996  +** NameContexts can be nested.  When resolving names, the inner-most 
          997  +** context is searched first.  If no match is found, the next outer
          998  +** context is checked.  If there is still no match, the next context
          999  +** is checked.  This process continues until either a match is found
         1000  +** or all contexts are check.  When a match is found, the nRef member of
         1001  +** the context containing the match is incremented. 
         1002  +**
         1003  +** Each subquery gets a new NameContext.  The pNext field points to the
         1004  +** NameContext in the parent query.  Thus the process of scanning the
         1005  +** NameContext list corresponds to searching through successively outer
         1006  +** subqueries looking for a match.
         1007  +*/
         1008  +struct NameContext {
         1009  +  Parse *pParse;       /* The parser */
         1010  +  SrcList *pSrcList;   /* One or more tables used to resolve names */
         1011  +  ExprList *pEList;    /* Optional list of named expressions */
         1012  +  int nRef;            /* Number of names resolved by this context */
         1013  +  int nErr;            /* Number of errors encountered while resolving names */
         1014  +  u8 allowAgg;         /* Aggregate functions allowed here */
         1015  +  u8 hasAgg;
         1016  +  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
         1017  +  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
         1018  +};
         1019  +
   986   1020   /*
   987   1021   ** An instance of the following structure contains all information
   988   1022   ** needed to generate code for a single SELECT statement.
   989   1023   **
   990   1024   ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
   991   1025   ** If there is a LIMIT clause, the parser sets nLimit to the value of the
   992   1026   ** limit and nOffset to the value of the offset (or 0 if there is not
................................................................................
  1003   1037     Expr *pHaving;         /* The HAVING clause */
  1004   1038     ExprList *pOrderBy;    /* The ORDER BY clause */
  1005   1039     Select *pPrior;        /* Prior select in a compound select statement */
  1006   1040     int nLimit, nOffset;   /* LIMIT and OFFSET values.  -1 means not used */
  1007   1041     int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
  1008   1042     IdList **ppOpenTemp;   /* OP_OpenTemp addresses used by multi-selects */
  1009   1043     Fetch *pFetch;         /* If this stmt is part of a FETCH command */
         1044  +  u8 isResolved;         /* True once sqlite3SelectResolve() has run. */
         1045  +  u8 isAgg;              /* True if this is an aggregate query */
  1010   1046   };
  1011   1047   
  1012   1048   /*
  1013   1049   ** The results of a select can be distributed in several ways.
  1014   1050   */
  1015   1051   #define SRT_Callback     1  /* Invoke a callback with each row of result */
  1016   1052   #define SRT_Mem          2  /* Store result in a memory cell */
................................................................................
  1072   1108     int nTab;            /* Number of previously allocated VDBE cursors */
  1073   1109     int nMem;            /* Number of memory cells used so far */
  1074   1110     int nSet;            /* Number of sets used so far */
  1075   1111     u32 cookieMask;      /* Bitmask of schema verified databases */
  1076   1112     int cookieValue[MAX_ATTACHED+2];  /* Values of cookies to verify */
  1077   1113     int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
  1078   1114     u32 writeMask;       /* Start a write transaction on these databases */
         1115  +  u8 useAgg;           /* If true, extract field values from the aggregator
         1116  +                       ** while generating expressions.  Normally false */
  1079   1117   
  1080   1118     /* Above is constant between recursions.  Below is reset before and after
  1081   1119     ** each recursion */
  1082   1120   
  1083   1121     int nVar;            /* Number of '?' variables seen in the SQL so far */
  1084   1122     int nVarExpr;        /* Number of used slots in apVarExpr[] */
  1085   1123     int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
  1086   1124     Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
  1087   1125     u8 explain;          /* True if the EXPLAIN flag is found on the query */
  1088         -  u8 useAgg;           /* If true, extract field values from the aggregator
  1089         -                       ** while generating expressions.  Normally false */
  1090   1126   #ifndef SQLITE_OMIT_CURSOR
  1091   1127     u8 fetchDir;         /* The direction argument to the FETCH command */
  1092   1128     int dirArg1;         /* First argument to the direction */
  1093   1129     int dirArg2;         /* Second argument to the direction */
  1094   1130   #endif
  1095         -  int nAgg;            /* Number of aggregate expressions */
  1096         -  AggExpr *aAgg;       /* An array of aggregate expressions */
  1097   1131     Token sErrToken;     /* The token at which the error occurred */
  1098   1132     Token sNameToken;    /* Token with unqualified schema object name */
  1099   1133     Token sLastToken;    /* The last token parsed */
  1100   1134     const char *zSql;    /* All SQL text */
  1101   1135     const char *zTail;   /* All SQL text past the last semicolon parsed */
  1102   1136     Table *pNewTable;    /* A table being constructed by CREATE TABLE */
  1103   1137     Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
  1104   1138     TriggerStack *trigStack;  /* Trigger actions being coded */
  1105   1139     const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
         1140  +  int nAgg;            /* Number of aggregate expressions */
         1141  +  AggExpr *aAgg;       /* An array of aggregate expressions */
         1142  +  int nMaxDepth;       /* Maximum depth of subquery recursion */
  1106   1143   };
  1107   1144   
  1108   1145   /*
  1109   1146   ** An instance of the following structure can be declared on a stack and used
  1110   1147   ** to save the Parse.zAuthContext value so that it can be restored later.
  1111   1148   */
  1112   1149   struct AuthContext {
................................................................................
  1271   1308   ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  1272   1309   */
  1273   1310   typedef struct {
  1274   1311     sqlite3 *db;        /* The database being initialized */
  1275   1312     char **pzErrMsg;    /* Error message stored here */
  1276   1313   } InitData;
  1277   1314   
  1278         -/*
  1279         -** A NameContext defines a context in which to resolve table and column
  1280         -** names.  The context consists of a list of tables (the pSrcList) field and
  1281         -** a list of named expression (pEList).  The named expression list may
  1282         -** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
  1283         -** to the table being operated on by INSERT, UPDATE, or DELETE.  The
  1284         -** pEList corresponds to the result set of a SELECT and is NULL for
  1285         -** other statements.
  1286         -**
  1287         -** NameContexts can be nested.  When resolving names, the inner-most 
  1288         -** context is searched first.  If no match is found, the next outer
  1289         -** context is checked.  If there is still no match, the next context
  1290         -** is checked.  This process continues until either a match is found
  1291         -** or all contexts are check.  When a match is found, the nRef member of
  1292         -** the context containing the match is incremented. 
  1293         -**
  1294         -** Each subquery gets a new NameContext.  The pNext field points to the
  1295         -** NameContext in the parent query.  Thus the process of scanning the
  1296         -** NameContext list corresponds to searching through successively outer
  1297         -** subqueries looking for a match.
  1298         -*/
  1299         -struct NameContext {
  1300         -  Parse *pParse;       /* The parser */
  1301         -  SrcList *pSrcList;   /* One or more tables used to resolve names */
  1302         -  ExprList *pEList;    /* Optional list of named expressions */
  1303         -  int nRef;            /* Number of names resolved by this context */
  1304         -  int nErr;            /* Number of errors encountered while resolving names */
  1305         -  u8 allowAgg;         /* Aggregate functions allowed here */
  1306         -  u8 hasAgg;           /* Expression actually contains aggregate functions */
  1307         -  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
  1308         -};
  1309         -
  1310   1315   /*
  1311   1316   ** Each SQL cursor (a cursor created by the DECLARE ... CURSOR syntax)
  1312   1317   ** is represented by an instance of the following structure.
  1313   1318   */
  1314   1319   struct SqlCursor {
  1315   1320     char *zName;           /* Name of this cursor */
  1316   1321     int idx;               /* Index of this cursor in db->apSqlCursor[] */
................................................................................
  1409   1414   void sqlite3IdListDelete(IdList*);
  1410   1415   void sqlite3SrcListDelete(SrcList*);
  1411   1416   void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  1412   1417                           Token*);
  1413   1418   void sqlite3DropIndex(Parse*, SrcList*);
  1414   1419   void sqlite3AddKeyType(Vdbe*, ExprList*);
  1415   1420   void sqlite3AddIdxKeyType(Vdbe*, Index*);
  1416         -int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*,
  1417         -                  char *aff, NameContext*);
         1421  +int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
  1418   1422   Select *sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
  1419   1423                           int,int,int);
  1420   1424   void sqlite3SelectDelete(Select*);
  1421   1425   void sqlite3SelectUnbind(Select*);
  1422   1426   Table *sqlite3SrcListLookup(Parse*, SrcList*);
  1423   1427   int sqlite3IsReadOnly(Parse*, Table*, int);
  1424   1428   void sqlite3OpenTableForReading(Vdbe*, int iCur, Table*);
................................................................................
  1440   1444   void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  1441   1445   void sqlite3Vacuum(Parse*, Token*);
  1442   1446   int sqlite3RunVacuum(char**, sqlite3*);
  1443   1447   char *sqlite3NameFromToken(Token*);
  1444   1448   int sqlite3ExprCheck(Parse*, Expr*, int, int*);
  1445   1449   int sqlite3ExprCompare(Expr*, Expr*);
  1446   1450   int sqliteFuncId(Token*);
  1447         -int sqlite3ExprResolveNames(Parse*, SrcList*, ExprList*, NameContext*,
  1448         -                            Expr*, int, int);
         1451  +int sqlite3ExprResolveNames(NameContext *, Expr *);
  1449   1452   int sqlite3ExprAnalyzeAggregates(Parse*, Expr*);
  1450   1453   Vdbe *sqlite3GetVdbe(Parse*);
  1451   1454   void sqlite3Randomness(int, void*);
  1452   1455   void sqlite3RollbackAll(sqlite3*);
  1453   1456   void sqlite3CodeVerifySchema(Parse*, int);
  1454   1457   void sqlite3BeginTransaction(Parse*, int);
  1455   1458   void sqlite3CommitTransaction(Parse*);
................................................................................
  1569   1572   extern const unsigned char sqlite3UpperToLower[];
  1570   1573   void sqlite3RootPageMoved(Db*, int, int);
  1571   1574   void sqlite3Reindex(Parse*, Token*, Token*);
  1572   1575   void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  1573   1576   int sqlite3GetToken(const unsigned char *, int *);
  1574   1577   void sqlite3NestedParse(Parse*, const char*, ...);
  1575   1578   void sqlite3ExpirePreparedStatements(sqlite3*);
         1579  +void sqlite3CodeSubselect(Parse *, Expr *);
         1580  +int sqlite3SelectResolve(Parse *, Select *, NameContext *);
  1576   1581   
  1577   1582   #ifndef SQLITE_OMIT_CURSOR
  1578   1583   void sqlite3CursorDelete(SqlCursor*);
  1579   1584   void sqlite3CursorCreate(Parse*, Token*, Select*);
  1580   1585   void sqlite3CursorClose(Parse*, Token*);
  1581   1586   void sqlite3Fetch(Parse*, Token*, IdList*);
  1582   1587   #endif /* SQLITE_OMIT_CURSOR */
  1583   1588   
  1584   1589   #endif

Changes to src/trigger.c.

   636    636       orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
   637    637       pParse->trigStack->orconf = orconf;
   638    638       switch( pTriggerStep->op ){
   639    639         case TK_SELECT: {
   640    640   	Select * ss = sqlite3SelectDup(pTriggerStep->pSelect);		  
   641    641   	assert(ss);
   642    642   	assert(ss->pSrc);
   643         -	sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0, 0);
          643  +        sqlite3SelectResolve(pParse, ss, 0);
          644  +	sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0);
   644    645   	sqlite3SelectDelete(ss);
   645    646   	break;
   646    647         }
   647    648         case TK_UPDATE: {
   648    649           SrcList *pSrc;
   649    650           pSrc = targetSrcList(pParse, pTriggerStep);
   650    651           sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0);
................................................................................
   740    741             !checkColumnOverLap(pTrigger->pColumns, pChanges) ){
   741    742           fire_this = 0;
   742    743         }
   743    744       }
   744    745    
   745    746       if( fire_this ){
   746    747         int endTrigger;
   747         -      SrcList dummyTablist;
   748    748         Expr * whenExpr;
   749    749         AuthContext sContext;
          750  +      NameContext sNC;
   750    751   
   751         -      dummyTablist.nSrc = 0;
          752  +      memset(&sNC, 0, sizeof(sNC));
          753  +      sNC.pParse = pParse;
   752    754   
   753    755         /* Push an entry on to the trigger stack */
   754    756         trigStackEntry.pTrigger = pTrigger;
   755    757         trigStackEntry.newIdx = newIdx;
   756    758         trigStackEntry.oldIdx = oldIdx;
   757    759         trigStackEntry.pTab = pTab;
   758    760         trigStackEntry.pNext = pParse->trigStack;
................................................................................
   759    761         trigStackEntry.ignoreJump = ignoreJump;
   760    762         pParse->trigStack = &trigStackEntry;
   761    763         sqlite3AuthContextPush(pParse, &sContext, pTrigger->name);
   762    764   
   763    765         /* code the WHEN clause */
   764    766         endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
   765    767         whenExpr = sqlite3ExprDup(pTrigger->pWhen);
   766         -      if( sqlite3ExprResolveNames(pParse, &dummyTablist, 0, 0, whenExpr, 0,1) ){
          768  +      if( sqlite3ExprResolveNames(&sNC, whenExpr) ){
   767    769           pParse->trigStack = trigStackEntry.pNext;
   768    770           sqlite3ExprDelete(whenExpr);
   769    771           return 1;
   770    772         }
   771    773         sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1);
   772    774         sqlite3ExprDelete(whenExpr);
   773    775   

Changes to src/update.c.

     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   *************************************************************************
    12     12   ** This file contains C code routines that are called by the parser
    13     13   ** to handle UPDATE statements.
    14     14   **
    15         -** $Id: update.c,v 1.103 2005/01/19 23:24:51 drh Exp $
           15  +** $Id: update.c,v 1.104 2005/01/29 08:32:45 danielk1977 Exp $
    16     16   */
    17     17   #include "sqliteInt.h"
    18     18   
    19     19   /*
    20     20   ** Process an UPDATE statement.
    21     21   **
    22     22   **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
................................................................................
    45     45     int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
    46     46                            ** an expression for the i-th column of the table.
    47     47                            ** aXRef[i]==-1 if the i-th column is not changed. */
    48     48     int chngRecno;         /* True if the record number is being changed */
    49     49     Expr *pRecnoExpr = 0;  /* Expression defining the new record number */
    50     50     int openAll = 0;       /* True if all indices need to be opened */
    51     51     AuthContext sContext;  /* The authorization context */
           52  +  NameContext sNC;       /* The name-context to resolve expressions in */
    52     53   
    53     54   #ifndef SQLITE_OMIT_TRIGGER
    54     55     int isView;                  /* Trying to update a view */
    55     56     int triggers_exist = 0;      /* True if any row triggers exist */
    56     57   #endif
    57     58   
    58     59     int newIdx      = -1;  /* index of trigger "new" temp table       */
................................................................................
   108    109     ** need to occur right after the database cursor.  So go ahead and
   109    110     ** allocate enough space, just in case.
   110    111     */
   111    112     pTabList->a[0].iCursor = iCur = pParse->nTab++;
   112    113     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   113    114       pParse->nTab++;
   114    115     }
          116  +
          117  +  /* Initialize the name-context */
          118  +  memset(&sNC, 0, sizeof(sNC));
          119  +  sNC.pParse = pParse;
          120  +  sNC.pSrcList = pTabList;
   115    121   
   116    122     /* Resolve the column names in all the expressions of the
   117    123     ** of the UPDATE statement.  Also find the column index
   118    124     ** for each column to be updated in the pChanges array.  For each
   119    125     ** column to be updated, make sure we have authorization to change
   120    126     ** that column.
   121    127     */
   122    128     chngRecno = 0;
   123    129     for(i=0; i<pChanges->nExpr; i++){
   124         -    if( sqlite3ExprResolveNames(pParse, pTabList, 0, 0,
   125         -          pChanges->a[i].pExpr, 0, 1) ){
          130  +    if( sqlite3ExprResolveNames(&sNC, pChanges->a[i].pExpr) ){
   126    131         goto update_cleanup;
   127    132       }
   128    133       for(j=0; j<pTab->nCol; j++){
   129    134         if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
   130    135           if( j==pTab->iPKey ){
   131    136             chngRecno = 1;
   132    137             pRecnoExpr = pChanges->a[i].pExpr;
................................................................................
   194    199         aIdxUsed[j] = 0;
   195    200       }
   196    201     }
   197    202   
   198    203     /* Resolve the column names in all the expressions in the
   199    204     ** WHERE clause.
   200    205     */
   201         -  if( sqlite3ExprResolveNames(pParse, pTabList, 0, 0, pWhere, 0, 1) ){
          206  +  if( sqlite3ExprResolveNames(&sNC, pWhere) ){
   202    207       goto update_cleanup;
   203    208     }
   204    209   
   205    210     /* Start the view context
   206    211     */
   207    212     if( isView ){
   208    213       sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
................................................................................
   217    222   
   218    223     /* If we are trying to update a view, construct that view into
   219    224     ** a temporary table.
   220    225     */
   221    226     if( isView ){
   222    227       Select *pView;
   223    228       pView = sqlite3SelectDup(pTab->pSelect);
   224         -    sqlite3Select(pParse, pView, SRT_TempTable, iCur, 0, 0, 0, 0, 0);
          229  +    sqlite3Select(pParse, pView, SRT_TempTable, iCur, 0, 0, 0, 0);
   225    230       sqlite3SelectDelete(pView);
   226    231     }
   227    232   
   228    233     /* Begin the database scan
   229    234     */
   230    235     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0);
   231    236     if( pWInfo==0 ) goto update_cleanup;

Changes to src/vdbe.c.

    39     39   **
    40     40   ** Various scripts scan this source file in order to generate HTML
    41     41   ** documentation, headers files, or other derived files.  The formatting
    42     42   ** of the code in this file is, therefore, important.  See other comments
    43     43   ** in this file for details.  If in doubt, do not deviate from existing
    44     44   ** commenting and indentation practices when changing or adding code.
    45     45   **
    46         -** $Id: vdbe.c,v 1.448 2005/01/27 00:33:21 drh Exp $
           46  +** $Id: vdbe.c,v 1.449 2005/01/29 08:32:45 danielk1977 Exp $
    47     47   */
    48     48   #include "sqliteInt.h"
    49     49   #include "os.h"
    50     50   #include <ctype.h>
    51     51   #include "vdbeInt.h"
    52     52   
    53     53   /*
................................................................................
  3952   3952   case OP_ListReset: {
  3953   3953     if( p->pList ){
  3954   3954       sqlite3VdbeKeylistFree(p->pList);
  3955   3955       p->pList = 0;
  3956   3956     }
  3957   3957     break;
  3958   3958   }
         3959  +
         3960  +#ifndef SQLITE_OMIT_SUBQUERY
         3961  +/* Opcode: AggContextPush * * * 
         3962  +**
         3963  +** Save the state of the current aggregator. It is restored an 
         3964  +** AggContextPop opcode.
         3965  +** 
         3966  +*/
         3967  +case OP_AggContextPush: {
         3968  +  p->pAgg++;
         3969  +  assert( p->pAgg<&p->apAgg[p->nAgg] );
         3970  +  break;
         3971  +}
         3972  +
         3973  +/* Opcode: AggContextPop * * *
         3974  +**
         3975  +** Restore the aggregator to the state it was in when AggContextPush
         3976  +** was last called. Any data in the current aggregator is deleted.
         3977  +*/
         3978  +case OP_AggContextPop: {
         3979  +  p->pAgg--;
         3980  +  assert( p->pAgg>=p->apAgg );
         3981  +  break;
         3982  +}
         3983  +#endif
  3959   3984   
  3960   3985   #ifndef SQLITE_OMIT_TRIGGER
  3961   3986   /* Opcode: ContextPush * * * 
  3962   3987   **
  3963   3988   ** Save the current Vdbe context such that it can be restored by a ContextPop
  3964   3989   ** opcode. The context stores the last insert row id, the last statement change
  3965   3990   ** count, and the current statement change count.
................................................................................
  4181   4206        pc = pOp->p2 - 1;
  4182   4207     }
  4183   4208     break;
  4184   4209   }
  4185   4210   
  4186   4211   /* Opcode: AggReset P1 P2 P3
  4187   4212   **
  4188         -** Reset the aggregator so that it no longer contains any data.
  4189         -** Future aggregator elements will contain P2 values each and be sorted
         4213  +** Reset the current aggregator context so that it no longer contains any 
         4214  +** data. Future aggregator elements will contain P2 values each and be sorted
  4190   4215   ** using the KeyInfo structure pointed to by P3.
  4191   4216   **
  4192   4217   ** If P1 is non-zero, then only a single aggregator row is available (i.e.
  4193   4218   ** there is no GROUP BY expression). In this case it is illegal to invoke
  4194   4219   ** OP_AggFocus.
  4195   4220   */
  4196   4221   case OP_AggReset: {
  4197   4222     assert( !pOp->p3 || pOp->p3type==P3_KEYINFO );
  4198   4223     if( pOp->p1 ){
  4199         -    rc = sqlite3VdbeAggReset(0, &p->agg, (KeyInfo *)pOp->p3);
  4200         -    p->agg.nMem = pOp->p2;    /* Agg.nMem is used by AggInsert() */
  4201         -    rc = AggInsert(&p->agg, 0, 0);
         4224  +    rc = sqlite3VdbeAggReset(0, p->pAgg, (KeyInfo *)pOp->p3);
         4225  +    p->pAgg->nMem = pOp->p2;    /* Agg.nMem is used by AggInsert() */
         4226  +    rc = AggInsert(p->pAgg, 0, 0);
  4202   4227     }else{
  4203         -    rc = sqlite3VdbeAggReset(db, &p->agg, (KeyInfo *)pOp->p3);
  4204         -    p->agg.nMem = pOp->p2;
         4228  +    rc = sqlite3VdbeAggReset(db, p->pAgg, (KeyInfo *)pOp->p3);
         4229  +    p->pAgg->nMem = pOp->p2;
  4205   4230     }
  4206   4231     if( rc!=SQLITE_OK ){
  4207   4232       goto abort_due_to_error;
  4208   4233     }
  4209         -  p->agg.apFunc = sqliteMalloc( p->agg.nMem*sizeof(p->agg.apFunc[0]) );
  4210         -  if( p->agg.apFunc==0 ) goto no_mem;
         4234  +  p->pAgg->apFunc = sqliteMalloc( p->pAgg->nMem*sizeof(p->pAgg->apFunc[0]) );
         4235  +  if( p->pAgg->apFunc==0 ) goto no_mem;
  4211   4236     break;
  4212   4237   }
  4213   4238   
  4214   4239   /* Opcode: AggInit * P2 P3
  4215   4240   **
  4216   4241   ** Initialize the function parameters for an aggregate function.
  4217   4242   ** The aggregate will operate out of aggregate column P2.
  4218   4243   ** P3 is a pointer to the FuncDef structure for the function.
  4219   4244   */
  4220   4245   case OP_AggInit: {
  4221   4246     int i = pOp->p2;
  4222         -  assert( i>=0 && i<p->agg.nMem );
  4223         -  p->agg.apFunc[i] = (FuncDef*)pOp->p3;
         4247  +  assert( i>=0 && i<p->pAgg->nMem );
         4248  +  p->pAgg->apFunc[i] = (FuncDef*)pOp->p3;
  4224   4249     break;
  4225   4250   }
  4226   4251   
  4227   4252   /* Opcode: AggFunc * P2 P3
  4228   4253   **
  4229   4254   ** Execute the step function for an aggregate.  The
  4230   4255   ** function has P2 arguments.  P3 is a pointer to the FuncDef
................................................................................
  4251   4276     assert( apVal || n==0 );
  4252   4277   
  4253   4278     for(i=0; i<n; i++, pRec++){
  4254   4279       apVal[i] = pRec;
  4255   4280       storeTypeInfo(pRec, db->enc);
  4256   4281     }
  4257   4282     i = pTos->i;
  4258         -  assert( i>=0 && i<p->agg.nMem );
         4283  +  assert( i>=0 && i<p->pAgg->nMem );
  4259   4284     ctx.pFunc = (FuncDef*)pOp->p3;
  4260         -  pMem = &p->agg.pCurrent->aMem[i];
         4285  +  pMem = &p->pAgg->pCurrent->aMem[i];
  4261   4286     ctx.s.z = pMem->zShort;  /* Space used for small aggregate contexts */
  4262   4287     ctx.pAgg = pMem->z;
  4263   4288     ctx.cnt = ++pMem->i;
  4264   4289     ctx.isError = 0;
  4265   4290     ctx.pColl = 0;
  4266   4291     if( ctx.pFunc->needCollSeq ){
  4267   4292       assert( pOp>p->aOp );
................................................................................
  4297   4322     char *zKey;
  4298   4323     int nKey;
  4299   4324     int res;
  4300   4325     assert( pTos>=p->aStack );
  4301   4326     Stringify(pTos, db->enc);
  4302   4327     zKey = pTos->z;
  4303   4328     nKey = pTos->n;
  4304         -  assert( p->agg.pBtree );
  4305         -  assert( p->agg.pCsr );
  4306         -  rc = sqlite3BtreeMoveto(p->agg.pCsr, zKey, nKey, &res);
         4329  +  assert( p->pAgg->pBtree );
         4330  +  assert( p->pAgg->pCsr );
         4331  +  rc = sqlite3BtreeMoveto(p->pAgg->pCsr, zKey, nKey, &res);
  4307   4332     if( rc!=SQLITE_OK ){
  4308   4333       goto abort_due_to_error;
  4309   4334     }
  4310   4335     if( res==0 ){
  4311         -    rc = sqlite3BtreeData(p->agg.pCsr, 0, sizeof(AggElem*),
  4312         -        (char *)&p->agg.pCurrent);
         4336  +    rc = sqlite3BtreeData(p->pAgg->pCsr, 0, sizeof(AggElem*),
         4337  +        (char *)&p->pAgg->pCurrent);
  4313   4338       pc = pOp->p2 - 1;
  4314   4339     }else{
  4315         -    rc = AggInsert(&p->agg, zKey, nKey);
         4340  +    rc = AggInsert(p->pAgg, zKey, nKey);
  4316   4341     }
  4317   4342     if( rc!=SQLITE_OK ){
  4318   4343       goto abort_due_to_error;
  4319   4344     }
  4320   4345     Release(pTos);
  4321   4346     pTos--;
  4322   4347     break; 
................................................................................
  4326   4351   **
  4327   4352   ** Move the top of the stack into the P2-th field of the current
  4328   4353   ** aggregate.  String values are duplicated into new memory.
  4329   4354   */
  4330   4355   case OP_AggSet: {
  4331   4356     AggElem *pFocus;
  4332   4357     int i = pOp->p2;
  4333         -  pFocus = p->agg.pCurrent;
         4358  +  pFocus = p->pAgg->pCurrent;
  4334   4359     assert( pTos>=p->aStack );
  4335   4360     if( pFocus==0 ) goto no_mem;
  4336         -  assert( i>=0 && i<p->agg.nMem );
         4361  +  assert( i>=0 && i<p->pAgg->nMem );
  4337   4362     rc = sqlite3VdbeMemMove(&pFocus->aMem[i], pTos);
  4338   4363     pTos--;
  4339   4364     break;
  4340   4365   }
  4341   4366   
  4342   4367   /* Opcode: AggGet * P2 *
  4343   4368   **
................................................................................
  4344   4369   ** Push a new entry onto the stack which is a copy of the P2-th field
  4345   4370   ** of the current aggregate.  Strings are not duplicated so
  4346   4371   ** string values will be ephemeral.
  4347   4372   */
  4348   4373   case OP_AggGet: {
  4349   4374     AggElem *pFocus;
  4350   4375     int i = pOp->p2;
  4351         -  pFocus = p->agg.pCurrent;
         4376  +  pFocus = p->pAgg->pCurrent;
  4352   4377     if( pFocus==0 ){
  4353   4378       int res;
  4354   4379       if( sqlite3_malloc_failed ) goto no_mem;
  4355         -    rc = sqlite3BtreeFirst(p->agg.pCsr, &res);
         4380  +    rc = sqlite3BtreeFirst(p->pAgg->pCsr, &res);
  4356   4381       if( rc!=SQLITE_OK ){
  4357   4382         return rc;
  4358   4383       }
  4359   4384       if( res!=0 ){
  4360         -      rc = AggInsert(&p->agg,"",1);
  4361         -      pFocus = p->agg.pCurrent;
         4385  +      rc = AggInsert(p->pAgg, "", 1);
         4386  +      pFocus = p->pAgg->pCurrent;
  4362   4387       }else{
  4363         -      rc = sqlite3BtreeData(p->agg.pCsr, 0, 4, (char *)&pFocus);
         4388  +      rc = sqlite3BtreeData(p->pAgg->pCsr, 0, 4, (char *)&pFocus);
  4364   4389       }
  4365   4390     }
  4366         -  assert( i>=0 && i<p->agg.nMem );
         4391  +  assert( i>=0 && i<p->pAgg->nMem );
  4367   4392     pTos++;
  4368   4393     sqlite3VdbeMemShallowCopy(pTos, &pFocus->aMem[i], MEM_Ephem);
  4369   4394     if( pTos->flags&MEM_Str ){
  4370   4395       sqlite3VdbeChangeEncoding(pTos, db->enc);
  4371   4396     }
  4372   4397     break;
  4373   4398   }
................................................................................
  4384   4409   ** zero or more AggNext operations.  You must not execute an AggFocus
  4385   4410   ** in between an AggNext and an AggReset.
  4386   4411   */
  4387   4412   case OP_AggNext: {
  4388   4413     int res;
  4389   4414     assert( rc==SQLITE_OK );
  4390   4415     CHECK_FOR_INTERRUPT;
  4391         -  if( p->agg.searching==0 ){
  4392         -    p->agg.searching = 1;
  4393         -    if( p->agg.pCsr ){
  4394         -      rc = sqlite3BtreeFirst(p->agg.pCsr, &res);
         4416  +  if( p->pAgg->searching==0 ){
         4417  +    p->pAgg->searching = 1;
         4418  +    if( p->pAgg->pCsr ){
         4419  +      rc = sqlite3BtreeFirst(p->pAgg->pCsr, &res);
  4395   4420       }else{
  4396   4421         res = 0;
  4397   4422       }
  4398   4423     }else{
  4399         -    if( p->agg.pCsr ){
  4400         -      rc = sqlite3BtreeNext(p->agg.pCsr, &res);
         4424  +    if( p->pAgg->pCsr ){
         4425  +      rc = sqlite3BtreeNext(p->pAgg->pCsr, &res);
  4401   4426       }else{
  4402   4427         res = 1;
  4403   4428       }
  4404   4429     }
  4405   4430     if( rc!=SQLITE_OK ) goto abort_due_to_error;
  4406   4431     if( res!=0 ){
  4407   4432       pc = pOp->p2 - 1;
  4408   4433     }else{
  4409   4434       int i;
  4410   4435       sqlite3_context ctx;
  4411   4436       Mem *aMem;
  4412   4437   
  4413         -    if( p->agg.pCsr ){
  4414         -      rc = sqlite3BtreeData(p->agg.pCsr, 0, sizeof(AggElem*),
  4415         -          (char *)&p->agg.pCurrent);
         4438  +    if( p->pAgg->pCsr ){
         4439  +      rc = sqlite3BtreeData(p->pAgg->pCsr, 0, sizeof(AggElem*),
         4440  +          (char *)&p->pAgg->pCurrent);
  4416   4441         if( rc!=SQLITE_OK ) goto abort_due_to_error;
  4417   4442       }
  4418         -    aMem = p->agg.pCurrent->aMem;
  4419         -    for(i=0; i<p->agg.nMem; i++){
  4420         -      FuncDef *pFunc = p->agg.apFunc[i];
         4443  +    aMem = p->pAgg->pCurrent->aMem;
         4444  +    for(i=0; i<p->pAgg->nMem; i++){
         4445  +      FuncDef *pFunc = p->pAgg->apFunc[i];
  4421   4446         Mem *pMem = &aMem[i];
  4422   4447         if( pFunc==0 || pFunc->xFinalize==0 ) continue;
  4423   4448         ctx.s.flags = MEM_Null;
  4424   4449         ctx.s.z = pMem->zShort;
  4425   4450         ctx.pAgg = (void*)pMem->z;
  4426   4451         ctx.cnt = pMem->i;
  4427   4452         ctx.pFunc = pFunc;
................................................................................
  4513   4538     if( !pOp->p1 ){
  4514   4539       sqlite3ExpirePreparedStatements(db);
  4515   4540     }else{
  4516   4541       p->expired = 1;
  4517   4542     }
  4518   4543     break;
  4519   4544   }
  4520         -
  4521   4545   
  4522   4546   
  4523   4547   /* An other opcode is illegal...
  4524   4548   */
  4525   4549   default: {
  4526   4550     sqlite3_snprintf(sizeof(zBuf),zBuf,"%d",pOp->opcode);
  4527   4551     sqlite3SetString(&p->zErrMsg, "unknown opcode ", zBuf, (char*)0);

Changes to src/vdbe.h.

    11     11   *************************************************************************
    12     12   ** Header file for the Virtual DataBase Engine (VDBE)
    13     13   **
    14     14   ** This header defines the interface to the virtual database engine
    15     15   ** or VDBE.  The VDBE implements an abstract machine that runs a
    16     16   ** simple program to access and modify the underlying database.
    17     17   **
    18         -** $Id: vdbe.h,v 1.91 2004/09/06 17:24:13 drh Exp $
           18  +** $Id: vdbe.h,v 1.92 2005/01/29 08:32:45 danielk1977 Exp $
    19     19   */
    20     20   #ifndef _SQLITE_VDBE_H_
    21     21   #define _SQLITE_VDBE_H_
    22     22   #include <stdio.h>
    23     23   
    24     24   /*
    25     25   ** A single VDBE is an opaque structure named "Vdbe".  Only routines
................................................................................
   106    106   void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
   107    107   void sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
   108    108   void sqlite3VdbeDequoteP3(Vdbe*, int addr);
   109    109   int sqlite3VdbeFindOp(Vdbe*, int, int, int);
   110    110   VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
   111    111   int sqlite3VdbeMakeLabel(Vdbe*);
   112    112   void sqlite3VdbeDelete(Vdbe*);
   113         -void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
          113  +void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int);
   114    114   int sqlite3VdbeFinalize(Vdbe*);
   115    115   void sqlite3VdbeResolveLabel(Vdbe*, int);
   116    116   int sqlite3VdbeCurrentAddr(Vdbe*);
   117    117   void sqlite3VdbeTrace(Vdbe*,FILE*);
   118    118   int sqlite3VdbeReset(Vdbe*);
   119    119   int sqliteVdbeSetVariables(Vdbe*,int,const char**);
   120    120   void sqlite3VdbeSetNumCols(Vdbe*,int);

Changes to src/vdbeInt.h.

   317    317     int nVar;           /* Number of entries in aVar[] */
   318    318     Mem *aVar;          /* Values for the OP_Variable opcode. */
   319    319     char **azVar;       /* Name of variables */
   320    320     int okVar;          /* True if azVar[] has been initialized */
   321    321     int magic;              /* Magic number for sanity checking */
   322    322     int nMem;               /* Number of memory locations currently allocated */
   323    323     Mem *aMem;              /* The memory locations */
   324         -  Agg agg;                /* Aggregate information */
          324  +  int nAgg;               /* Number of elements in apAgg */
          325  +  Agg *apAgg;             /* Array of aggregate contexts */
          326  +  Agg *pAgg;              /* Current aggregate context */
   325    327     int nCallback;          /* Number of callbacks invoked so far */
   326    328     Keylist *pList;         /* A list of ROWIDs */
   327    329     int contextStackTop;    /* Index of top element in the context stack */
   328    330     int contextStackDepth;  /* The size of the "context" stack */
   329    331     Context *contextStack;  /* Stack used by opcodes ContextPush & ContextPop*/
   330    332     int pc;                 /* The program counter */
   331    333     int rc;                 /* Value to return */

Changes to src/vdbeaux.c.

   582    582   ** VDBE_MAGIC_RUN.
   583    583   */
   584    584   void sqlite3VdbeMakeReady(
   585    585     Vdbe *p,                       /* The VDBE */
   586    586     int nVar,                      /* Number of '?' see in the SQL statement */
   587    587     int nMem,                      /* Number of memory cells to allocate */
   588    588     int nCursor,                   /* Number of cursors to allocate */
          589  +  int nAgg,                      /* Number of aggregate contexts required */
   589    590     int isExplain                  /* True if the EXPLAIN keywords is present */
   590    591   ){
   591    592     int n;
   592    593   
   593    594     assert( p!=0 );
   594    595     assert( p->magic==VDBE_MAGIC_INIT );
   595    596   
................................................................................
   611    612       p->aStack = sqliteMalloc(
   612    613           n*sizeof(p->aStack[0])         /* aStack */
   613    614         + n*sizeof(Mem*)                 /* apArg */
   614    615         + nVar*sizeof(Mem)               /* aVar */
   615    616         + nVar*sizeof(char*)             /* azVar */
   616    617         + nMem*sizeof(Mem)               /* aMem */
   617    618         + nCursor*sizeof(Cursor*)        /* apCsr */
          619  +      + nAgg*sizeof(Agg)               /* Aggregate contexts */
   618    620       );
   619    621       if( !sqlite3_malloc_failed ){
   620    622         p->aMem = &p->aStack[n];
   621    623         p->nMem = nMem;
   622    624         p->aVar = &p->aMem[nMem];
   623    625         p->nVar = nVar;
   624    626         p->okVar = 0;
   625    627         p->apArg = (Mem**)&p->aVar[nVar];
   626    628         p->azVar = (char**)&p->apArg[n];
   627    629         p->apCsr = (Cursor**)&p->azVar[nVar];
          630  +      if( nAgg>0 ){
          631  +        p->nAgg = nAgg;
          632  +        p->apAgg = (Agg*)&p->apCsr[nCursor];
          633  +      }
   628    634         p->nCursor = nCursor;
   629    635         for(n=0; n<nVar; n++){
   630    636           p->aVar[n].flags = MEM_Null;
   631    637         }
   632         -      for(n=0; n<nMem; n++){
   633         -        p->aMem[n].flags = MEM_Null;
   634         -      }
   635    638       }
   636    639     }
          640  +  p->pAgg = p->apAgg;
          641  +  for(n=0; n<p->nMem; n++){
          642  +    p->aMem[n].flags = MEM_Null;
          643  +  }
   637    644   
   638    645   #ifdef SQLITE_DEBUG
   639    646     if( (p->db->flags & SQLITE_VdbeListing)!=0
   640    647       || sqlite3OsFileExists("vdbe_explain")
   641    648     ){
   642    649       int i;
   643    650       printf("VDBE Program Listing:\n");
................................................................................
   729    736   ** If db is not NULL, then this is being called from with an OP_AggReset
   730    737   ** opcode. Open the temp-table, if it has not already been opened and
   731    738   ** delete the contents of the table used for aggregate information, ready
   732    739   ** for the next round of aggregate processing.
   733    740   */
   734    741   int sqlite3VdbeAggReset(sqlite3 *db, Agg *pAgg, KeyInfo *pKeyInfo){
   735    742     int rc = 0;
   736         -  BtCursor *pCsr = pAgg->pCsr;
          743  +  BtCursor *pCsr;
   737    744   
          745  +  if( !pAgg ) return SQLITE_OK;
          746  +  pCsr = pAgg->pCsr;
   738    747     assert( (pCsr && pAgg->nTab>0) || (!pCsr && pAgg->nTab==0)
   739    748            || sqlite3_malloc_failed );
   740    749   
   741    750     /* If pCsr is not NULL, then the table used for aggregate information
   742    751     ** is open. Loop through it and free the AggElem* structure pointed at
   743    752     ** by each entry. If the finalizer has not been called for an AggElem,
   744    753     ** do that too. Finally, clear the btree table itself.
................................................................................
   882    891     if( p->contextStack ){
   883    892       for(i=0; i<p->contextStackTop; i++){
   884    893         sqlite3VdbeKeylistFree(p->contextStack[i].pList);
   885    894       }
   886    895       sqliteFree(p->contextStack);
   887    896     }
   888    897     sqlite3VdbeSorterReset(p);
   889         -  sqlite3VdbeAggReset(0, &p->agg, 0);
          898  +  for(i=0; i<p->nAgg; i++){
          899  +    sqlite3VdbeAggReset(0, &p->apAgg[i], 0);
          900  +  }
   890    901     p->contextStack = 0;
   891    902     p->contextStackDepth = 0;
   892    903     p->contextStackTop = 0;
   893    904     sqliteFree(p->zErrMsg);
   894    905     p->zErrMsg = 0;
   895    906   }
   896    907   

Changes to src/where.c.

    12     12   ** This module contains C code that generates VDBE code used to process
    13     13   ** the WHERE clause of SQL statements.  This module is reponsible for
    14     14   ** generating the code that loops through a table looking for applicable
    15     15   ** rows.  Indices are selected and used to speed the search when doing
    16     16   ** so is applicable.  Because this module is responsible for selecting
    17     17   ** indices, you might also think of this module as the "query optimizer".
    18     18   **
    19         -** $Id: where.c,v 1.131 2005/01/20 22:48:48 drh Exp $
           19  +** $Id: where.c,v 1.132 2005/01/29 08:32:45 danielk1977 Exp $
    20     20   */
    21     21   #include "sqliteInt.h"
    22     22   
    23     23   /*
    24     24   ** The query generator uses an array of instances of this structure to
    25     25   ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
    26     26   ** clause subexpression is separated from the others by an AND operator.
................................................................................
   187    187   ** In order for this routine to work, the calling function must have
   188    188   ** previously invoked sqlite3ExprResolveNames() on the expression.  See
   189    189   ** the header comment on that routine for additional information.
   190    190   ** The sqlite3ExprResolveNames() routines looks for column names and
   191    191   ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
   192    192   ** the VDBE cursor number of the table.
   193    193   */
          194  +static Bitmask exprListTableUsage(ExprMaskSet *, ExprList *);
   194    195   static Bitmask exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
   195    196     Bitmask mask = 0;
   196    197     if( p==0 ) return 0;
   197    198     if( p->op==TK_COLUMN ){
   198    199       mask = getMask(pMaskSet, p->iTable);
   199    200       return mask;
   200    201     }
   201         -  if( p->pRight ){
   202         -    mask = exprTableUsage(pMaskSet, p->pRight);
          202  +  mask = exprTableUsage(pMaskSet, p->pRight);
          203  +  mask |= exprTableUsage(pMaskSet, p->pLeft);
          204  +  mask |= exprListTableUsage(pMaskSet, p->pList);
          205  +  if( p->pSelect ){
          206  +    Select *pS = p->pSelect;
          207  +    mask |= exprListTableUsage(pMaskSet, pS->pEList);
          208  +    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
          209  +    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
          210  +    mask |= exprTableUsage(pMaskSet, pS->pWhere);
          211  +    mask |= exprTableUsage(pMaskSet, pS->pHaving);
   203    212     }
   204         -  if( p->pLeft ){
   205         -    mask |= exprTableUsage(pMaskSet, p->pLeft);
   206         -  }
   207         -  if( p->pList ){
   208         -    int i;
   209         -    for(i=0; i<p->pList->nExpr; i++){
   210         -      mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
          213  +  return mask;
          214  +}
          215  +static Bitmask exprListTableUsage(ExprMaskSet *pMaskSet, ExprList *pList){
          216  +  int i;
          217  +  Bitmask mask = 0;
          218  +  if( pList ){
          219  +    for(i=0; i<pList->nExpr; i++){
          220  +      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
   211    221       }
   212    222     }
   213    223     return mask;
   214    224   }
   215    225   
   216    226   /*
   217    227   ** Return TRUE if the given operator is one of the operators that is
................................................................................
   475    485     int brk,            /* Jump here to abandon the loop */
   476    486     WhereLevel *pLevel  /* When level of the FROM clause we are working on */
   477    487   ){
   478    488     Expr *pX = pTerm->p;
   479    489     if( pX->op!=TK_IN ){
   480    490       assert( pX->op==TK_EQ );
   481    491       sqlite3ExprCode(pParse, pX->pRight);
          492  +#ifndef SQLITE_OMIT_SUBQUERY
   482    493     }else{
   483         -    int iTab = pX->iTable;
          494  +    int iTab;
   484    495       Vdbe *v = pParse->pVdbe;
          496  +
          497  +    sqlite3CodeSubselect(pParse, pX);
          498  +    iTab = pX->iTable;
   485    499       sqlite3VdbeAddOp(v, OP_Rewind, iTab, brk);
   486    500       sqlite3VdbeAddOp(v, OP_KeyAsData, iTab, 1);
          501  +    VdbeComment((v, "# %.*s", pX->span.n, pX->span.z));
   487    502       pLevel->inP2 = sqlite3VdbeAddOp(v, OP_Column, iTab, 0);
   488    503       pLevel->inOp = OP_Next;
   489    504       pLevel->inP1 = iTab;
          505  +#endif
   490    506     }
   491    507     disableTerm(pLevel, &pTerm->p);
   492    508   }
   493    509   
   494    510   /*
   495    511   ** The number of bits in a Bitmask
   496    512   */

Changes to test/bind.test.

     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.  The
    12     12   # focus of this script testing the sqlite_bind API.
    13     13   #
    14         -# $Id: bind.test,v 1.27 2005/01/20 02:17:02 danielk1977 Exp $
           14  +# $Id: bind.test,v 1.28 2005/01/29 08:32:46 danielk1977 Exp $
    15     15   #
    16     16   
    17     17   set testdir [file dirname $argv0]
    18     18   source $testdir/tester.tcl
    19     19   
    20     20   proc sqlite_step {stmt N VALS COLS} {
    21     21     upvar VALS vals
................................................................................
   474    474   } 5
   475    475   do_test bind-10.15 {
   476    476     sqlite3_bind_parameter_index $VM ?4
   477    477   } 4
   478    478   do_test bind-10.16 {
   479    479     sqlite3_bind_parameter_name $VM 1
   480    480   } :abc
   481         -do_test bind-10.16 {
          481  +do_test bind-10.17 {
   482    482     sqlite3_bind_parameter_name $VM 2
   483    483   } {}
   484         -do_test bind-10.16 {
          484  +do_test bind-10.18 {
   485    485     sqlite3_bind_parameter_name $VM 3
   486    486   } {}
   487         -do_test bind-10.16 {
          487  +do_test bind-10.19 {
   488    488     sqlite3_bind_parameter_name $VM 4
   489    489   } {?4}
   490         -do_test bind-10.16 {
          490  +do_test bind-10.20 {
   491    491     sqlite3_bind_parameter_name $VM 5
   492    492   } :pqr
   493    493   catch {sqlite3_finalize $VM}
   494    494   
   495    495   # Make sure we catch an unterminated "(" in a Tcl-style variable name
   496    496   #
   497    497   ifcapable tclvar {
   498    498     do_test bind-11.1 {
   499    499       catchsql {SELECT * FROM sqlite_master WHERE name=$abc(123 and sql NOT NULL;}
   500    500     } {1 {unrecognized token: "$abc(123"}}
   501    501   }
   502    502   
   503    503   finish_test

Changes to test/collate3.test.

     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.  The
    12     12   # focus of this script is page cache subsystem.
    13     13   #
    14         -# $Id: collate3.test,v 1.9 2005/01/26 03:58:36 danielk1977 Exp $
           14  +# $Id: collate3.test,v 1.10 2005/01/29 08:32:46 danielk1977 Exp $
    15     15   
    16     16   set testdir [file dirname $argv0]
    17     17   source $testdir/tester.tcl
    18     18   
    19     19   #
    20     20   # Tests are organised as follows:
    21     21   #
................................................................................
   127    127   do_test collate3-2.8 {
   128    128     catchsql {
   129    129       SELECT DISTINCT c1 FROM collate3t1;
   130    130     }
   131    131   } {1 {no such collation sequence: string_compare}} 
   132    132   
   133    133   ifcapable compound {
   134         -do_test collate3-2.9 {
   135         -  catchsql {
   136         -    SELECT c1 FROM collate3t1 UNION SELECT c1 FROM collate3t1;
   137         -  }
   138         -} {1 {no such collation sequence: string_compare}} 
   139         -do_test collate3-2.10 {
   140         -  catchsql {
   141         -    SELECT c1 FROM collate3t1 EXCEPT SELECT c1 FROM collate3t1;
   142         -  }
   143         -} {1 {no such collation sequence: string_compare}} 
   144         -do_test collate3-2.11 {
   145         -  catchsql {
   146         -    SELECT c1 FROM collate3t1 INTERSECT SELECT c1 FROM collate3t1;
   147         -  }
   148         -} {1 {no such collation sequence: string_compare}} 
   149         -do_test collate3-2.12 {
   150         -  catchsql {
   151         -    SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1;
   152         -  }
   153         -} {0 {}}
   154         -do_test collate3-2.13 {
   155         -  catchsql {
   156         -    SELECT 10 UNION ALL SELECT 20 ORDER BY 1 COLLATE string_compare;
   157         -  }
   158         -} {1 {no such collation sequence: string_compare}} 
   159         -do_test collate3-2.14 {
   160         -  catchsql {
   161         -    SELECT 10 INTERSECT SELECT 20 ORDER BY 1 COLLATE string_compare;
   162         -  }
   163         -} {1 {no such collation sequence: string_compare}} 
   164         -do_test collate3-2.15 {
   165         -  catchsql {
   166         -    SELECT 10 EXCEPT SELECT 20 ORDER BY 1 COLLATE string_compare;
   167         -  }
   168         -} {1 {no such collation sequence: string_compare}} 
   169         -do_test collate3-2.16 {
   170         -  catchsql {
   171         -    SELECT 10 UNION SELECT 20 ORDER BY 1 COLLATE string_compare;
   172         -  }
   173         -} {1 {no such collation sequence: string_compare}} 
   174         -do_test collate3-2.17 {
   175         -  catchsql {
   176         -    SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1 ORDER BY 1;
   177         -  }
   178         -} {1 {no such collation sequence: string_compare}} 
          134  +  do_test collate3-2.9 {
          135  +    catchsql {
          136  +      SELECT c1 FROM collate3t1 UNION SELECT c1 FROM collate3t1;
          137  +    }
          138  +  } {1 {no such collation sequence: string_compare}} 
          139  +  do_test collate3-2.10 {
          140  +    catchsql {
          141  +      SELECT c1 FROM collate3t1 EXCEPT SELECT c1 FROM collate3t1;
          142  +    }
          143  +  } {1 {no such collation sequence: string_compare}} 
          144  +  do_test collate3-2.11 {
          145  +    catchsql {
          146  +      SELECT c1 FROM collate3t1 INTERSECT SELECT c1 FROM collate3t1;
          147  +    }
          148  +  } {1 {no such collation sequence: string_compare}} 
          149  +  do_test collate3-2.12 {
          150  +    catchsql {
          151  +      SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1;
          152  +    }
          153  +  } {0 {}}
          154  +  do_test collate3-2.13 {
          155  +    catchsql {
          156  +      SELECT 10 UNION ALL SELECT 20 ORDER BY 1 COLLATE string_compare;
          157  +    }
          158  +  } {1 {no such collation sequence: string_compare}} 
          159  +  do_test collate3-2.14 {
          160  +    catchsql {
          161  +      SELECT 10 INTERSECT SELECT 20 ORDER BY 1 COLLATE string_compare;
          162  +    }
          163  +  } {1 {no such collation sequence: string_compare}} 
          164  +  do_test collate3-2.15 {
          165  +    catchsql {
          166  +      SELECT 10 EXCEPT SELECT 20 ORDER BY 1 COLLATE string_compare;
          167  +    }
          168  +  } {1 {no such collation sequence: string_compare}} 
          169  +  do_test collate3-2.16 {
          170  +    catchsql {
          171  +      SELECT 10 UNION SELECT 20 ORDER BY 1 COLLATE string_compare;
          172  +    }
          173  +  } {1 {no such collation sequence: string_compare}} 
          174  +  do_test collate3-2.17 {
          175  +    catchsql {
          176  +      SELECT c1 FROM collate3t1 UNION ALL SELECT c1 FROM collate3t1 ORDER BY 1;
          177  +    }
          178  +  } {1 {no such collation sequence: string_compare}} 
   179    179   } ;# ifcapable compound
   180    180   
   181    181   #
   182    182   # Create an index that uses a collation sequence then close and
   183    183   # re-open the database without re-registering the collation
   184    184   # sequence. Then check that for the table with the index 
   185    185   # * An INSERT fails,

Changes to test/insert3.test.

     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.  The
    12     12   # focus of this file is testing corner cases of the INSERT statement.
    13     13   #
    14         -# $Id: insert3.test,v 1.2 2005/01/15 00:36:37 drh Exp $
           14  +# $Id: insert3.test,v 1.3 2005/01/29 08:32:46 danielk1977 Exp $
    15     15   
    16     16   set testdir [file dirname $argv0]
    17     17   source $testdir/tester.tcl
    18     18   
    19     19   # All the tests in this file require trigger support
    20     20   #
    21     21   ifcapable {trigger} {
................................................................................
    54     54     }
    55     55   } {5 2 453 1 hello 2}
    56     56   do_test insert3-1.3 {
    57     57     execsql {
    58     58       SELECT * FROM log2 ORDER BY x;
    59     59     }
    60     60   } {hi 1}
    61         -do_test insert3-1.4 {
    62         -  execsql {
    63         -    INSERT INTO t1 SELECT * FROM t1;
    64         -    SELECT 'a:', x, y FROM log UNION ALL SELECT 'b:', x, y FROM log2 ORDER BY x;
    65         -  }
    66         -} {a: 5 4 b: 10 2 b: 20 1 a: 453 2 a: hello 4 b: hi 2 b: world 1}
    67         -do_test insert3-1.5 {
    68         -  execsql {
    69         -    INSERT INTO t1(a) VALUES('xyz');
    70         -    SELECT * FROM log ORDER BY x;
    71         -  }
    72         -} {5 4 453 2 hello 4 xyz 1}
           61  +ifcapable compound {
           62  +  do_test insert3-1.4 {
           63  +    execsql {
           64  +      INSERT INTO t1 SELECT * FROM t1;
           65  +      SELECT 'a:', x, y FROM log UNION ALL 
           66  +          SELECT 'b:', x, y FROM log2 ORDER BY x;
           67  +    }
           68  +  } {a: 5 4 b: 10 2 b: 20 1 a: 453 2 a: hello 4 b: hi 2 b: world 1}
           69  +  do_test insert3-1.5 {
           70  +    execsql {
           71  +      INSERT INTO t1(a) VALUES('xyz');
           72  +      SELECT * FROM log ORDER BY x;
           73  +    }
           74  +  } {5 4 453 2 hello 4 xyz 1}
           75  +}
    73     76   
    74     77   do_test insert3-2.1 {
    75     78     execsql {
    76     79       CREATE TABLE t2(
    77     80         a INTEGER PRIMARY KEY,
    78     81         b DEFAULT 'b',
    79     82         c DEFAULT 'c'

Changes to test/misc4.test.

     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.
    12     12   #
    13     13   # This file implements tests for miscellanous features that were
    14     14   # left out of other test files.
    15     15   #
    16         -# $Id: misc4.test,v 1.13 2005/01/21 03:12:16 danielk1977 Exp $
           16  +# $Id: misc4.test,v 1.14 2005/01/29 08:32:46 danielk1977 Exp $
    17     17   
    18     18   set testdir [file dirname $argv0]
    19     19   source $testdir/tester.tcl
    20     20   
    21     21   # Prepare a statement that will create a temporary table.  Then do
    22     22   # a rollback.  Then try to execute the prepared statement.
    23     23   #
................................................................................
   115    115         insert into b values ('+1',4);
   116    116         
   117    117         select a.*, x.*
   118    118           from a, (select key,sum(period) from b group by key) as x
   119    119           where a.key=x.key;
   120    120       }
   121    121     } {01 data01 01 3.0 +1 data+1 +1 7.0}
          122  +
          123  +  # This test case tests the same property as misc4-4.1, but it is
          124  +  # a bit smaller which makes it easier to work with while debugging.
          125  +  do_test misc4-4.2 {
          126  +    execsql {
          127  +      CREATE TABLE ab(a TEXT, b TEXT);
          128  +      INSERT INTO ab VALUES('01', '1');
          129  +    }
          130  +    execsql {
          131  +      select * from ab, (select b from ab) as x where x.b = ab.a;
          132  +    }
          133  +  } {}
   122    134   }
          135  +
   123    136   
   124    137   # Ticket #1036.  When creating tables from a SELECT on a view, use the
   125    138   # short names of columns.
   126    139   #
   127    140   ifcapable view {
   128    141     do_test misc4-5.1 {
   129    142       execsql {

Changes to test/select6.test.

     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.  The
    12     12   # focus of this file is testing SELECT statements that contain
    13     13   # subqueries in their FROM clause.
    14     14   #
    15         -# $Id: select6.test,v 1.16 2005/01/21 03:12:16 danielk1977 Exp $
           15  +# $Id: select6.test,v 1.17 2005/01/29 08:32:46 danielk1977 Exp $
    16     16   
    17     17   set testdir [file dirname $argv0]
    18     18   source $testdir/tester.tcl
    19     19   
    20     20   # Omit this whole file if the library is build without subquery support.
    21     21   ifcapable !subquery {
    22     22     finish_test
................................................................................
   153    153       SELECT a.q, a.p, b.r
   154    154       FROM (SELECT count(*) as p , b as q FROM t2 GROUP BY q) AS a,
   155    155            (SELECT max(a) as r, b as s FROM t2 GROUP BY s) as b
   156    156       WHERE a.q=b.s ORDER BY a.q
   157    157     }
   158    158   } {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}
   159    159   
   160         -do_test sqlite6-3.1 {
          160  +do_test select6-3.1 {
   161    161     execsql2 {
   162    162       SELECT * FROM (SELECT * FROM (SELECT * FROM t1 WHERE x=3));
   163    163     }
   164    164   } {x 3 y 2}
   165         -do_test sqlite6-3.2 {
          165  +do_test select6-3.2 {
   166    166     execsql {
   167    167       SELECT * FROM
   168    168         (SELECT a.q, a.p, b.r
   169    169          FROM (SELECT count(*) as p , b as q FROM t2 GROUP BY q) AS a,
   170    170               (SELECT max(a) as r, b as s FROM t2 GROUP BY s) as b
   171    171          WHERE a.q=b.s ORDER BY a.q)
   172         -    ORDER BY q
          172  +    ORDER BY "a.q"
   173    173     }
   174    174   } {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}
   175    175   do_test select6-3.3 {
   176    176     execsql {
   177    177       SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1)
   178    178     }
   179    179   } {10.5 3.7 14.2}

Changes to test/subquery.test.

     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #*************************************************************************
    11     11   # This file implements regression tests for SQLite library.  The
    12     12   # focus of this script is testing correlated subqueries
    13     13   #
    14         -# $Id: subquery.test,v 1.2 2005/01/21 11:55:28 danielk1977 Exp $
           14  +# $Id: subquery.test,v 1.3 2005/01/29 08:32:47 danielk1977 Exp $
    15     15   #
    16     16   
    17     17   set testdir [file dirname $argv0]
    18     18   source $testdir/tester.tcl
    19     19   
    20     20   ifcapable !subquery {
    21     21     finish_test
................................................................................
    55     55   } {3}
    56     56   do_test subquery-1.4 {
    57     57     execsql {
    58     58       SELECT b FROM t1 WHERE NOT EXISTS(SELECT * FROM t2 WHERE y=a)
    59     59     }
    60     60   } {13 31 57}
    61     61   
           62  +# Simple tests to make sure correlated subqueries in WHERE clauses
           63  +# are used by the query optimizer correctly.
           64  +do_test subquery-1.5 {
           65  +  execsql {
           66  +    SELECT a, x FROM t1, t2 WHERE t1.a = (SELECT x);
           67  +  }
           68  +} {1 1 3 3 5 5 7 7}
           69  +do_test subquery-1.6 {
           70  +  execsql {
           71  +    CREATE INDEX i1 ON t1(a);
           72  +    SELECT a, x FROM t1, t2 WHERE t1.a = (SELECT x);
           73  +  }
           74  +} {1 1 3 3 5 5 7 7}
           75  +do_test subquery-1.7 {
           76  +  execsql {
           77  +    SELECT a, x FROM t2, t1 WHERE t1.a = (SELECT x);
           78  +  }
           79  +} {1 1 3 3 5 5 7 7}
           80  +
           81  +# Try an aggregate in both the subquery and the parent query.
           82  +do_test subquery-1.6 {
           83  +  execsql {
           84  +    SELECT count(*) FROM t1 WHERE a > (SELECT count(*) FROM t2);
           85  +  }
           86  +} {2}
           87  +
           88  +
           89  +#------------------------------------------------------------------
           90  +# The following test cases - subquery-2.* - are not logically
           91  +# organized. They're here largely because they were failing during
           92  +# one stage of development of sub-queries.
           93  +#
           94  +do_test subquery-2.1 {
           95  +  execsql {
           96  +    SELECT (SELECT 10);
           97  +  }
           98  +} {10}
           99  +do_test subquery-2.2.1 {
          100  +  execsql {
          101  +    CREATE TABLE t3(a PRIMARY KEY, b);
          102  +    INSERT INTO t3 VALUES(1, 2);
          103  +    INSERT INTO t3 VALUES(3, 1);
          104  +  }
          105  +} {}
          106  +do_test subquery-2.2.2 {
          107  +  execsql {
          108  +    SELECT * FROM t3 WHERE a IN (SELECT b FROM t3);
          109  +  }
          110  +} {1 2}
          111  +do_test subquery-2.2.3 {
          112  +  execsql {
          113  +    DROP TABLE t3;
          114  +  }
          115  +} {}
          116  +do_test subquery-2.3.1 {
          117  +  execsql {
          118  +    CREATE TABLE t3(a TEXT);
          119  +    INSERT INTO t3 VALUES('10');
          120  +  }
          121  +} {}
          122  +do_test subquery-2.3.2 {
          123  +  execsql {
          124  +    SELECT a IN (10.0, 20) FROM t3;
          125  +  }
          126  +} {0}
          127  +do_test subquery-2.3.3 {
          128  +  execsql {
          129  +    DROP TABLE t3;
          130  +  }
          131  +} {}
          132  +do_test subquery-2.4.1 {
          133  +  execsql {
          134  +    CREATE TABLE t3(a TEXT);
          135  +    INSERT INTO t3 VALUES('XX');
          136  +  }
          137  +} {}
          138  +do_test subquery-2.4.2 {
          139  +  execsql {
          140  +    SELECT count(*) FROM t3 WHERE a IN (SELECT 'XX')
          141  +  }
          142  +} {1}
          143  +do_test subquery-2.4.3 {
          144  +  execsql {
          145  +    DROP TABLE t3;
          146  +  }
          147  +} {}
          148  +do_test subquery-2.5.1 {
          149  +  execsql {
          150  +    CREATE TABLE t3(a INTEGER);
          151  +    INSERT INTO t3 VALUES(10);
          152  +
          153  +    CREATE TABLE t4(x TEXT);
          154  +    INSERT INTO t4 VALUES('10.0');
          155  +  }
          156  +} {}
          157  +do_test subquery-2.5.2 {
          158  +  execsql {
          159  +    SELECT * FROM t4 WHERE x IN (SELECT a FROM t3);
          160  +  }
          161  +} {10.0}
          162  +do_test subquery-2.5.3 {
          163  +  execsql {
          164  +    CREATE INDEX t4i ON t4(x);
          165  +    SELECT * FROM t4 WHERE x IN (SELECT a FROM t3);
          166  +  }
          167  +} {10.0}
          168  +do_test subquery-2.5.4 {
          169  +  execsql {
          170  +    DROP TABLE t3;
          171  +    DROP TABLE t4;
          172  +  }
          173  +} {}
          174  +
          175  +#------------------------------------------------------------------
          176  +# The following test cases - subquery-3.* - test tickets that
          177  +# were raised during development of correlated subqueries.
          178  +#
          179  +
          180  +# Ticket 1083
          181  +ifcapable view {
          182  +  do_test subquery-3.1 {
          183  +    catchsql { DROP TABLE t1; }
          184  +    catchsql { DROP TABLE t2; }
          185  +    execsql {
          186  +      CREATE TABLE t1(a,b);
          187  +      INSERT INTO t1 VALUES(1,2);
          188  +      CREATE VIEW v1 AS SELECT b FROM t1 WHERE a>0;
          189  +      CREATE TABLE t2(p,q);
          190  +      INSERT INTO t2 VALUES(2,9);
          191  +      SELECT * FROM v1 WHERE EXISTS(SELECT * FROM t2 WHERE p=v1.b);
          192  +    }
          193  +  } {2}
          194  +}
          195  +
          196  +# Ticket 1084
          197  +do_test subquery-3.2 {
          198  +  catchsql {
          199  +    CREATE TABLE t1(a,b);
          200  +    INSERT INTO t1 VALUES(1,2);
          201  +  }
          202  +  execsql {
          203  +    SELECT (SELECT t1.a) FROM t1;
          204  +  }
          205  +} {1}
          206  +
          207  +#------------------------------------------------------------------
          208  +# These tests - subquery-4.* - use the TCL statement cache to try 
          209  +# and expose bugs to do with re-using statements that have been 
          210  +# passed to sqlite3_reset().
          211  +#
          212  +# One problem was that VDBE memory cells were not being initialised
          213  +# to NULL on the second and subsequent executions.
          214  +#
          215  +do_test subquery-4.1.1 {
          216  +  execsql {
          217  +    SELECT (SELECT a FROM t1);
          218  +  }
          219  +} {1}
          220  +do_test subquery-4.2 {
          221  +  execsql {
          222  +    DELETE FROM t1;
          223  +    SELECT (SELECT a FROM t1);
          224  +  }
          225  +} {{}}
          226  +do_test subquery-4.2.1 {
          227  +  execsql {
          228  +    CREATE TABLE t3(a PRIMARY KEY);
          229  +    INSERT INTO t3 VALUES(10);
          230  +  }
          231  +  execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1)}
          232  +} {}
          233  +do_test subquery-4.2.2 {
          234  +  execsql {INSERT INTO t3 VALUES((SELECT max(a) FROM t3)+1)}
          235  +} {}
          236  +
          237  +
    62    238   
    63    239   finish_test
          240  +
          241  +

Changes to test/trigger2.test.

   118    118           SELECT * FROM clog ORDER BY idx;
   119    119         }] {
   120    120           lappend r [expr {int($v)}]
   121    121         }
   122    122         set r
   123    123       } [list 1 1 2  4  6 10 20 \
   124    124               2 1 2 13 24 10 20 \
   125         -  	  3 3 4 13 24 30 40 \
   126         -  	  4 3 4 40 60 30 40 \
          125  +  	    3 3 4 13 24 30 40 \
          126  +  	    4 3 4 40 60 30 40 \
   127    127               1 1 2 13 24 10 20 ]
   128    128     
   129    129       execsql {
   130    130         DELETE FROM rlog;
   131    131         DELETE FROM tbl;
   132    132         INSERT INTO tbl VALUES (100, 100);
   133    133         INSERT INTO tbl VALUES (300, 200);

Changes to test/view.test.

     7      7   #    May you find forgiveness for yourself and forgive others.
     8      8   #    May you share freely, never taking more than you give.
     9      9   #
    10     10   #***********************************************************************
    11     11   # This file implements regression tests for SQLite library.  The
    12     12   # focus of this file is testing VIEW statements.
    13     13   #
    14         -# $Id: view.test,v 1.22 2005/01/21 04:25:47 danielk1977 Exp $
           14  +# $Id: view.test,v 1.23 2005/01/29 08:32:47 danielk1977 Exp $
    15     15   set testdir [file dirname $argv0]
    16     16   source $testdir/tester.tcl
    17     17   
    18     18   # Omit this entire file if the library is not configured with views enabled.
    19     19   ifcapable !view {
    20     20     finish_test
    21     21     return
................................................................................
   150    150   ifcapable compound {
   151    151   do_test  view-3.4 {
   152    152     execsql2 {
   153    153       CREATE VIEW v3 AS SELECT a FROM t1 UNION SELECT b FROM t1 ORDER BY b;
   154    154       SELECT * FROM v3 LIMIT 4;
   155    155     }
   156    156   } {b 2 b 3 b 5 b 6}
   157         -do_test  view-3.5 {
          157  +do_test view-3.5 {
   158    158     execsql2 {
   159    159       CREATE VIEW v4 AS 
   160    160         SELECT a, b FROM t1 
   161    161         UNION
   162    162         SELECT b AS 'x', a AS 'y' FROM t1
   163    163         ORDER BY x, y;
   164    164       SELECT y FROM v4 ORDER BY y LIMIT 4;