/ Changes On Branch expr-codegen-enhancement
Login

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

Changes In Branch expr-codegen-enhancement Excluding Merge-Ins

This is equivalent to a diff from cc17f1f05f to cee835fe90

2013-11-16
13:55
Simplification and performance improvement to the logic that factors constant expressions ouf of inner loops. (check-in: ee9353fdf3 user: drh tags: trunk)
12:56
Fix testcase misc7-16 so that it works with the new UNIQUE constraint error message format. (check-in: c7f2ed9f44 user: drh tags: trunk)
2013-11-15
20:06
Add ALWAYS and NEVER macros to currently unreachable but important branches in sqlite3ExprCompare(). (Closed-Leaf check-in: cee835fe90 user: drh tags: expr-codegen-enhancement)
19:00
Merge the operator comment fixes from trunk. (check-in: 9f14f55c8a user: drh tags: expr-codegen-enhancement)
18:58
Fix comments on the OP_Divide and OP_Remainder operators, especially the "Synopsis:" comment, so that they agree with the actual implementation. (check-in: cc17f1f05f user: drh tags: trunk)
13:12
Add the --query option to the wordcount test program. (check-in: 5960d11eba user: drh tags: trunk)

Changes to src/backup.c.

    92     92       }else{
    93     93         pParse->db = pDb;
    94     94         if( sqlite3OpenTempDatabase(pParse) ){
    95     95           sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
    96     96           rc = SQLITE_ERROR;
    97     97         }
    98     98         sqlite3DbFree(pErrorDb, pParse->zErrMsg);
           99  +      sqlite3ParserReset(pParse);
    99    100         sqlite3StackFree(pErrorDb, pParse);
   100    101       }
   101    102       if( rc ){
   102    103         return 0;
   103    104       }
   104    105     }
   105    106   

Changes to src/build.c.

   146    146       ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
   147    147       ** set for each database that is used.  Generate code to start a
   148    148       ** transaction on each used database and to verify the schema cookie
   149    149       ** on each used database.
   150    150       */
   151    151       if( pParse->cookieGoto>0 ){
   152    152         yDbMask mask;
   153         -      int iDb;
          153  +      int iDb, i, addr;
   154    154         sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
   155    155         for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
   156    156           if( (mask & pParse->cookieMask)==0 ) continue;
   157    157           sqlite3VdbeUsesBtree(v, iDb);
   158    158           sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
   159    159           if( db->init.busy==0 ){
   160    160             assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   161    161             sqlite3VdbeAddOp3(v, OP_VerifyCookie,
   162    162                               iDb, pParse->cookieValue[iDb],
   163    163                               db->aDb[iDb].pSchema->iGeneration);
   164    164           }
   165    165         }
   166    166   #ifndef SQLITE_OMIT_VIRTUALTABLE
   167         -      {
   168         -        int i;
   169         -        for(i=0; i<pParse->nVtabLock; i++){
   170         -          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
   171         -          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   172         -        }
   173         -        pParse->nVtabLock = 0;
          167  +      for(i=0; i<pParse->nVtabLock; i++){
          168  +        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
          169  +        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
   174    170         }
          171  +      pParse->nVtabLock = 0;
   175    172   #endif
   176    173   
   177    174         /* Once all the cookies have been verified and transactions opened, 
   178    175         ** obtain the required table-locks. This is a no-op unless the 
   179    176         ** shared-cache feature is enabled.
   180    177         */
   181    178         codeTableLocks(pParse);
   182    179   
   183    180         /* Initialize any AUTOINCREMENT data structures required.
   184    181         */
   185    182         sqlite3AutoincrementBegin(pParse);
          183  +
          184  +      /* Code constant expressions that where factored out of inner loops */
          185  +      addr = pParse->cookieGoto;
          186  +      if( pParse->pConstExpr ){
          187  +        ExprList *pEL = pParse->pConstExpr;
          188  +        pParse->cookieGoto = 0;
          189  +        for(i=0; i<pEL->nExpr; i++){
          190  +          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
          191  +        }
          192  +      }
   186    193   
   187    194         /* Finally, jump back to the beginning of the executable code. */
   188         -      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
          195  +      sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
   189    196       }
   190    197     }
   191    198   
   192    199   
   193    200     /* Get the VDBE program ready for execution
   194    201     */
   195    202     if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){

Changes to src/expr.c.

   926    926       Expr *pOldExpr = pOldItem->pExpr;
   927    927       pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   928    928       pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   929    929       pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   930    930       pItem->sortOrder = pOldItem->sortOrder;
   931    931       pItem->done = 0;
   932    932       pItem->bSpanIsTab = pOldItem->bSpanIsTab;
   933         -    pItem->iOrderByCol = pOldItem->iOrderByCol;
   934         -    pItem->iAlias = pOldItem->iAlias;
          933  +    pItem->u = pOldItem->u;
   935    934     }
   936    935     return pNew;
   937    936   }
   938    937   
   939    938   /*
   940    939   ** If cursors, triggers, views and subqueries are all omitted from
   941    940   ** the build, then none of the following routines, except for 
................................................................................
  2352   2351     Vdbe *v = pParse->pVdbe;  /* The VM under construction */
  2353   2352     int op;                   /* The opcode being coded */
  2354   2353     int inReg = target;       /* Results stored in register inReg */
  2355   2354     int regFree1 = 0;         /* If non-zero free this temporary register */
  2356   2355     int regFree2 = 0;         /* If non-zero free this temporary register */
  2357   2356     int r1, r2, r3, r4;       /* Various register numbers */
  2358   2357     sqlite3 *db = pParse->db; /* The database connection */
         2358  +  Expr tempX;               /* Temporary expression node */
  2359   2359   
  2360   2360     assert( target>0 && target<=pParse->nMem );
  2361   2361     if( v==0 ){
  2362   2362       assert( pParse->db->mallocFailed );
  2363   2363       return 0;
  2364   2364     }
  2365   2365   
................................................................................
  2571   2571           codeInteger(pParse, pLeft, 1, target);
  2572   2572   #ifndef SQLITE_OMIT_FLOATING_POINT
  2573   2573         }else if( pLeft->op==TK_FLOAT ){
  2574   2574           assert( !ExprHasProperty(pExpr, EP_IntValue) );
  2575   2575           codeReal(v, pLeft->u.zToken, 1, target);
  2576   2576   #endif
  2577   2577         }else{
  2578         -        regFree1 = r1 = sqlite3GetTempReg(pParse);
  2579         -        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
         2578  +        tempX.op = TK_INTEGER;
         2579  +        tempX.flags = EP_IntValue|EP_TokenOnly;
         2580  +        tempX.u.iValue = 0;
         2581  +        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  2580   2582           r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  2581   2583           sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  2582   2584           testcase( regFree2==0 );
  2583   2585         }
  2584   2586         inReg = target;
  2585   2587         break;
  2586   2588       }
................................................................................
  2888   2890         int endLabel;                     /* GOTO label for end of CASE stmt */
  2889   2891         int nextCase;                     /* GOTO label for next WHEN clause */
  2890   2892         int nExpr;                        /* 2x number of WHEN terms */
  2891   2893         int i;                            /* Loop counter */
  2892   2894         ExprList *pEList;                 /* List of WHEN terms */
  2893   2895         struct ExprList_item *aListelem;  /* Array of WHEN terms */
  2894   2896         Expr opCompare;                   /* The X==Ei expression */
  2895         -      Expr cacheX;                      /* Cached expression X */
  2896   2897         Expr *pX;                         /* The X expression */
  2897   2898         Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
  2898   2899         VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  2899   2900   
  2900   2901         assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  2901   2902         assert(pExpr->x.pList->nExpr > 0);
  2902   2903         pEList = pExpr->x.pList;
  2903   2904         aListelem = pEList->a;
  2904   2905         nExpr = pEList->nExpr;
  2905   2906         endLabel = sqlite3VdbeMakeLabel(v);
  2906   2907         if( (pX = pExpr->pLeft)!=0 ){
  2907         -        cacheX = *pX;
         2908  +        tempX = *pX;
  2908   2909           testcase( pX->op==TK_COLUMN );
  2909         -        testcase( pX->op==TK_REGISTER );
  2910         -        exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
         2910  +        exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  2911   2911           testcase( regFree1==0 );
  2912   2912           opCompare.op = TK_EQ;
  2913         -        opCompare.pLeft = &cacheX;
         2913  +        opCompare.pLeft = &tempX;
  2914   2914           pTest = &opCompare;
  2915   2915           /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  2916   2916           ** The value in regFree1 might get SCopy-ed into the file result.
  2917   2917           ** So make sure that the regFree1 register is not reused for other
  2918   2918           ** purposes and possibly overwritten.  */
  2919   2919           regFree1 = 0;
  2920   2920         }
................................................................................
  2926   2926           }else{
  2927   2927             pTest = aListelem[i].pExpr;
  2928   2928           }
  2929   2929           nextCase = sqlite3VdbeMakeLabel(v);
  2930   2930           testcase( pTest->op==TK_COLUMN );
  2931   2931           sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  2932   2932           testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  2933         -        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  2934   2933           sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  2935   2934           sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  2936   2935           sqlite3ExprCachePop(pParse, 1);
  2937   2936           sqlite3VdbeResolveLabel(v, nextCase);
  2938   2937         }
  2939   2938         if( (nExpr&1)!=0 ){
  2940   2939           sqlite3ExprCachePush(pParse);
................................................................................
  2985   2984   ** Generate code to evaluate an expression and store the results
  2986   2985   ** into a register.  Return the register number where the results
  2987   2986   ** are stored.
  2988   2987   **
  2989   2988   ** If the register is a temporary register that can be deallocated,
  2990   2989   ** then write its number into *pReg.  If the result register is not
  2991   2990   ** a temporary, then set *pReg to zero.
         2991  +**
         2992  +** If pExpr is a constant, then this routine might generate this
         2993  +** code to fill the register in the initialization section of the
         2994  +** VDBE program, in order to factor it out of the evaluation loop.
  2992   2995   */
  2993   2996   int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  2994         -  int r1 = sqlite3GetTempReg(pParse);
  2995         -  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  2996         -  if( r2==r1 ){
  2997         -    *pReg = r1;
         2997  +  int r2;
         2998  +  pExpr = sqlite3ExprSkipCollate(pExpr);
         2999  +  if( pParse->cookieGoto>0
         3000  +   && pExpr->op!=TK_REGISTER
         3001  +   && sqlite3ExprIsConstantNotJoin(pExpr)
         3002  +  ){
         3003  +    ExprList *p = pParse->pConstExpr;
         3004  +    int i;
         3005  +    *pReg  = 0;
         3006  +    if( p ){
         3007  +      for(i=0; i<p->nExpr; i++){
         3008  +        if( sqlite3ExprCompare(p->a[i].pExpr, pExpr, -1)==0 ){
         3009  +          return p->a[i].u.iConstExprReg;
         3010  +        }
         3011  +      }
         3012  +    }
         3013  +    p = sqlite3ExprListAppend(pParse, p, sqlite3ExprDup(pParse->db, pExpr, 0));
         3014  +    pParse->pConstExpr = p;
         3015  +    r2 = ++pParse->nMem;
         3016  +    if( p ) p->a[p->nExpr-1].u.iConstExprReg = r2;
  2998   3017     }else{
  2999         -    sqlite3ReleaseTempReg(pParse, r1);
  3000         -    *pReg = 0;
         3018  +    int r1 = sqlite3GetTempReg(pParse);
         3019  +    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
         3020  +    if( r2==r1 ){
         3021  +      *pReg = r1;
         3022  +    }else{
         3023  +      sqlite3ReleaseTempReg(pParse, r1);
         3024  +      *pReg = 0;
         3025  +    }
  3001   3026     }
  3002   3027     return r2;
  3003   3028   }
  3004   3029   
  3005   3030   /*
  3006   3031   ** Generate code that will evaluate expression pExpr and store the
  3007   3032   ** results in register target.  The results are guaranteed to appear
................................................................................
  3036   3061   ** are reused.
  3037   3062   */
  3038   3063   int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  3039   3064     Vdbe *v = pParse->pVdbe;
  3040   3065     int inReg;
  3041   3066     inReg = sqlite3ExprCode(pParse, pExpr, target);
  3042   3067     assert( target>0 );
  3043         -  /* This routine is called for terms to INSERT or UPDATE.  And the only
  3044         -  ** other place where expressions can be converted into TK_REGISTER is
  3045         -  ** in WHERE clause processing.  So as currently implemented, there is
  3046         -  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
  3047         -  ** keep the ALWAYS() in case the conditions above change with future
  3048         -  ** modifications or enhancements. */
         3068  +  /* The only place, other than this routine, where expressions can be
         3069  +  ** converted to TK_REGISTER is internal subexpressions in BETWEEN and
         3070  +  ** CASE operators.  Neither ever calls this routine.  And this routine
         3071  +  ** is never called twice on the same expression.  Hence it is impossible
         3072  +  ** for the input to this routine to already be a register.  Nevertheless,
         3073  +  ** it seems prudent to keep the ALWAYS() in case the conditions above
         3074  +  ** change with future modifications or enhancements. */
  3049   3075     if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
  3050   3076       int iMem;
  3051   3077       iMem = ++pParse->nMem;
  3052   3078       sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  3053   3079       exprToRegister(pExpr, iMem);
  3054   3080     }
  3055   3081     return inReg;
................................................................................
  3323   3349           sqlite3ExplainNL(pOut);
  3324   3350         }
  3325   3351       }
  3326   3352       sqlite3ExplainPop(pOut);
  3327   3353     }
  3328   3354   }
  3329   3355   #endif /* SQLITE_DEBUG */
  3330         -
  3331         -/*
  3332         -** Return TRUE if pExpr is an constant expression that is appropriate
  3333         -** for factoring out of a loop.  Appropriate expressions are:
  3334         -**
  3335         -**    *  Any expression that evaluates to two or more opcodes.
  3336         -**
  3337         -**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
  3338         -**       or OP_Variable that does not need to be placed in a 
  3339         -**       specific register.
  3340         -**
  3341         -** There is no point in factoring out single-instruction constant
  3342         -** expressions that need to be placed in a particular register.  
  3343         -** We could factor them out, but then we would end up adding an
  3344         -** OP_SCopy instruction to move the value into the correct register
  3345         -** later.  We might as well just use the original instruction and
  3346         -** avoid the OP_SCopy.
  3347         -*/
  3348         -static int isAppropriateForFactoring(Expr *p){
  3349         -  if( !sqlite3ExprIsConstantNotJoin(p) ){
  3350         -    return 0;  /* Only constant expressions are appropriate for factoring */
  3351         -  }
  3352         -  if( (p->flags & EP_FixedDest)==0 ){
  3353         -    return 1;  /* Any constant without a fixed destination is appropriate */
  3354         -  }
  3355         -  while( p->op==TK_UPLUS ) p = p->pLeft;
  3356         -  switch( p->op ){
  3357         -#ifndef SQLITE_OMIT_BLOB_LITERAL
  3358         -    case TK_BLOB:
  3359         -#endif
  3360         -    case TK_VARIABLE:
  3361         -    case TK_INTEGER:
  3362         -    case TK_FLOAT:
  3363         -    case TK_NULL:
  3364         -    case TK_STRING: {
  3365         -      testcase( p->op==TK_BLOB );
  3366         -      testcase( p->op==TK_VARIABLE );
  3367         -      testcase( p->op==TK_INTEGER );
  3368         -      testcase( p->op==TK_FLOAT );
  3369         -      testcase( p->op==TK_NULL );
  3370         -      testcase( p->op==TK_STRING );
  3371         -      /* Single-instruction constants with a fixed destination are
  3372         -      ** better done in-line.  If we factor them, they will just end
  3373         -      ** up generating an OP_SCopy to move the value to the destination
  3374         -      ** register. */
  3375         -      return 0;
  3376         -    }
  3377         -    case TK_UMINUS: {
  3378         -      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  3379         -        return 0;
  3380         -      }
  3381         -      break;
  3382         -    }
  3383         -    default: {
  3384         -      break;
  3385         -    }
  3386         -  }
  3387         -  return 1;
  3388         -}
  3389         -
  3390         -/*
  3391         -** If pExpr is a constant expression that is appropriate for
  3392         -** factoring out of a loop, then evaluate the expression
  3393         -** into a register and convert the expression into a TK_REGISTER
  3394         -** expression.
  3395         -*/
  3396         -static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  3397         -  Parse *pParse = pWalker->pParse;
  3398         -  switch( pExpr->op ){
  3399         -    case TK_IN:
  3400         -    case TK_REGISTER: {
  3401         -      return WRC_Prune;
  3402         -    }
  3403         -    case TK_COLLATE: {
  3404         -      return WRC_Continue;
  3405         -    }
  3406         -    case TK_FUNCTION:
  3407         -    case TK_AGG_FUNCTION:
  3408         -    case TK_CONST_FUNC: {
  3409         -      /* The arguments to a function have a fixed destination.
  3410         -      ** Mark them this way to avoid generated unneeded OP_SCopy
  3411         -      ** instructions. 
  3412         -      */
  3413         -      ExprList *pList = pExpr->x.pList;
  3414         -      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  3415         -      if( pList ){
  3416         -        int i = pList->nExpr;
  3417         -        struct ExprList_item *pItem = pList->a;
  3418         -        for(; i>0; i--, pItem++){
  3419         -          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  3420         -        }
  3421         -      }
  3422         -      break;
  3423         -    }
  3424         -  }
  3425         -  if( isAppropriateForFactoring(pExpr) ){
  3426         -    int r1 = ++pParse->nMem;
  3427         -    int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  3428         -    /* If r2!=r1, it means that register r1 is never used.  That is harmless
  3429         -    ** but suboptimal, so we want to know about the situation to fix it.
  3430         -    ** Hence the following assert: */
  3431         -    assert( r2==r1 );
  3432         -    exprToRegister(pExpr, r2);
  3433         -    return WRC_Prune;
  3434         -  }
  3435         -  return WRC_Continue;
  3436         -}
  3437         -
  3438         -/*
  3439         -** Preevaluate constant subexpressions within pExpr and store the
  3440         -** results in registers.  Modify pExpr so that the constant subexpresions
  3441         -** are TK_REGISTER opcodes that refer to the precomputed values.
  3442         -**
  3443         -** This routine is a no-op if the jump to the cookie-check code has
  3444         -** already occur.  Since the cookie-check jump is generated prior to
  3445         -** any other serious processing, this check ensures that there is no
  3446         -** way to accidently bypass the constant initializations.
  3447         -**
  3448         -** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  3449         -** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  3450         -** interface.  This allows test logic to verify that the same answer is
  3451         -** obtained for queries regardless of whether or not constants are
  3452         -** precomputed into registers or if they are inserted in-line.
  3453         -*/
  3454         -void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  3455         -  Walker w;
  3456         -  if( pParse->cookieGoto ) return;
  3457         -  if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  3458         -  memset(&w, 0, sizeof(w));
  3459         -  w.xExprCallback = evalConstExpr;
  3460         -  w.pParse = pParse;
  3461         -  sqlite3WalkExpr(&w, pExpr);
  3462         -}
  3463         -
  3464   3356   
  3465   3357   /*
  3466   3358   ** Generate code that pushes the value of every element of the given
  3467   3359   ** expression list into a sequence of registers beginning at target.
  3468   3360   **
  3469   3361   ** Return the number of elements evaluated.
  3470   3362   */
................................................................................
  3835   3727   ** expressions are the same.  But if you get a 0 or 1 return, then you
  3836   3728   ** can be sure the expressions are the same.  In the places where
  3837   3729   ** this routine is used, it does not hurt to get an extra 2 - that
  3838   3730   ** just might result in some slightly slower code.  But returning
  3839   3731   ** an incorrect 0 or 1 could lead to a malfunction.
  3840   3732   */
  3841   3733   int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  3842         -  if( pA==0||pB==0 ){
         3734  +  u32 combinedFlags;
         3735  +  if( pA==0 || pB==0 ){
  3843   3736       return pB==pA ? 0 : 2;
  3844   3737     }
  3845         -  assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
  3846         -  assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
  3847         -  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
         3738  +  combinedFlags = pA->flags | pB->flags;
         3739  +  if( combinedFlags & EP_IntValue ){
         3740  +    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
         3741  +      return 0;
         3742  +    }
  3848   3743       return 2;
  3849   3744     }
  3850         -  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  3851         -  if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
         3745  +  if( pA->op!=pB->op ){
  3852   3746       if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  3853   3747         return 1;
  3854   3748       }
  3855   3749       if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  3856   3750         return 1;
  3857   3751       }
  3858   3752       return 2;
  3859   3753     }
  3860         -  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  3861         -  if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  3862         -  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  3863         -  if( pA->iColumn!=pB->iColumn ) return 2;
  3864         -  if( pA->iTable!=pB->iTable 
  3865         -   && pA->op!=TK_REGISTER
  3866         -   && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  3867         -  if( ExprHasProperty(pA, EP_IntValue) ){
  3868         -    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  3869         -      return 2;
  3870         -    }
  3871         -  }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  3872         -    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
         3754  +  if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
  3873   3755       if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  3874   3756         return pA->op==TK_COLLATE ? 1 : 2;
  3875   3757       }
         3758  +  }
         3759  +  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
         3760  +  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
         3761  +    if( combinedFlags & EP_xIsSelect ) return 2;
         3762  +    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
         3763  +    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
         3764  +    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
         3765  +    if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
         3766  +      if( pA->iColumn!=pB->iColumn ) return 2;
         3767  +      if( pA->iTable!=pB->iTable 
         3768  +       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
         3769  +    }
  3876   3770     }
  3877   3771     return 0;
  3878   3772   }
  3879   3773   
  3880   3774   /*
  3881   3775   ** Compare two ExprList objects.  Return 0 if they are identical and 
  3882   3776   ** non-zero if they differ in any way.

Changes to src/prepare.c.

   519    519           break;
   520    520         }
   521    521       }
   522    522       assert( i>=0 && i<db->nDb );
   523    523     }
   524    524     return i;
   525    525   }
          526  +
          527  +/*
          528  +** Free all memory allocations in the pParse object
          529  +*/
          530  +void sqlite3ParserReset(Parse *pParse){
          531  +  if( pParse ) sqlite3ExprListDelete(pParse->db, pParse->pConstExpr);
          532  +}
   526    533   
   527    534   /*
   528    535   ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
   529    536   */
   530    537   static int sqlite3Prepare(
   531    538     sqlite3 *db,              /* Database handle. */
   532    539     const char *zSql,         /* UTF-8 encoded SQL statement. */
................................................................................
   677    684       TriggerPrg *pT = pParse->pTriggerPrg;
   678    685       pParse->pTriggerPrg = pT->pNext;
   679    686       sqlite3DbFree(db, pT);
   680    687     }
   681    688   
   682    689   end_prepare:
   683    690   
          691  +  sqlite3ParserReset(pParse);
   684    692     sqlite3StackFree(db, pParse);
   685    693     rc = sqlite3ApiExit(db, rc);
   686    694     assert( (rc&db->errMask)==rc );
   687    695     return rc;
   688    696   }
   689    697   static int sqlite3LockAndPrepare(
   690    698     sqlite3 *db,              /* Database handle. */

Changes to src/resolve.c.

   104    104     pDup = sqlite3ExprDup(db, pOrig, 0);
   105    105     if( pDup==0 ) return;
   106    106     if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
   107    107       incrAggFunctionDepth(pDup, nSubquery);
   108    108       pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
   109    109       if( pDup==0 ) return;
   110    110       ExprSetProperty(pDup, EP_Skip);
   111         -    if( pEList->a[iCol].iAlias==0 ){
   112         -      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
          111  +    if( pEList->a[iCol].u.x.iAlias==0 ){
          112  +      pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
   113    113       }
   114         -    pDup->iTable = pEList->a[iCol].iAlias;
          114  +    pDup->iTable = pEList->a[iCol].u.x.iAlias;
   115    115     }
   116    116     if( pExpr->op==TK_COLLATE ){
   117    117       pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
   118    118     }
   119    119   
   120    120     /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
   121    121     ** prevents ExprDelete() from deleting the Expr structure itself,
................................................................................
   972    972             pItem->pExpr = pNew;
   973    973           }else{
   974    974             assert( pItem->pExpr->op==TK_COLLATE );
   975    975             assert( pItem->pExpr->pLeft==pE );
   976    976             pItem->pExpr->pLeft = pNew;
   977    977           }
   978    978           sqlite3ExprDelete(db, pE);
   979         -        pItem->iOrderByCol = (u16)iCol;
          979  +        pItem->u.x.iOrderByCol = (u16)iCol;
   980    980           pItem->done = 1;
   981    981         }else{
   982    982           moreToDo = 1;
   983    983         }
   984    984       }
   985    985       pSelect = pSelect->pNext;
   986    986     }
................................................................................
   993    993     }
   994    994     return 0;
   995    995   }
   996    996   
   997    997   /*
   998    998   ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
   999    999   ** the SELECT statement pSelect.  If any term is reference to a
  1000         -** result set expression (as determined by the ExprList.a.iOrderByCol field)
  1001         -** then convert that term into a copy of the corresponding result set
         1000  +** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
         1001  +** field) then convert that term into a copy of the corresponding result set
  1002   1002   ** column.
  1003   1003   **
  1004   1004   ** If any errors are detected, add an error message to pParse and
  1005   1005   ** return non-zero.  Return zero if no errors are seen.
  1006   1006   */
  1007   1007   int sqlite3ResolveOrderGroupBy(
  1008   1008     Parse *pParse,        /* Parsing context.  Leave error messages here */
................................................................................
  1021   1021       sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  1022   1022       return 1;
  1023   1023     }
  1024   1024   #endif
  1025   1025     pEList = pSelect->pEList;
  1026   1026     assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
  1027   1027     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  1028         -    if( pItem->iOrderByCol ){
  1029         -      if( pItem->iOrderByCol>pEList->nExpr ){
         1028  +    if( pItem->u.x.iOrderByCol ){
         1029  +      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  1030   1030           resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  1031   1031           return 1;
  1032   1032         }
  1033         -      resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
         1033  +      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
  1034   1034       }
  1035   1035     }
  1036   1036     return 0;
  1037   1037   }
  1038   1038   
  1039   1039   /*
  1040   1040   ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
................................................................................
  1075   1075       if( zType[0]!='G' ){
  1076   1076         iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  1077   1077         if( iCol>0 ){
  1078   1078           /* If an AS-name match is found, mark this ORDER BY column as being
  1079   1079           ** a copy of the iCol-th result-set column.  The subsequent call to
  1080   1080           ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  1081   1081           ** copy of the iCol-th result-set expression. */
  1082         -        pItem->iOrderByCol = (u16)iCol;
         1082  +        pItem->u.x.iOrderByCol = (u16)iCol;
  1083   1083           continue;
  1084   1084         }
  1085   1085       }
  1086   1086       if( sqlite3ExprIsInteger(pE2, &iCol) ){
  1087   1087         /* The ORDER BY term is an integer constant.  Again, set the column
  1088   1088         ** number so that sqlite3ResolveOrderGroupBy() will convert the
  1089   1089         ** order-by term to a copy of the result-set expression */
  1090   1090         if( iCol<1 || iCol>0xffff ){
  1091   1091           resolveOutOfRangeError(pParse, zType, i+1, nResult);
  1092   1092           return 1;
  1093   1093         }
  1094         -      pItem->iOrderByCol = (u16)iCol;
         1094  +      pItem->u.x.iOrderByCol = (u16)iCol;
  1095   1095         continue;
  1096   1096       }
  1097   1097   
  1098   1098       /* Otherwise, treat the ORDER BY term as an ordinary expression */
  1099         -    pItem->iOrderByCol = 0;
         1099  +    pItem->u.x.iOrderByCol = 0;
  1100   1100       if( sqlite3ResolveExprNames(pNC, pE) ){
  1101   1101         return 1;
  1102   1102       }
  1103   1103       for(j=0; j<pSelect->pEList->nExpr; j++){
  1104   1104         if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  1105         -        pItem->iOrderByCol = j+1;
         1105  +        pItem->u.x.iOrderByCol = j+1;
  1106   1106         }
  1107   1107       }
  1108   1108     }
  1109   1109     return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  1110   1110   }
  1111   1111   
  1112   1112   /*

Changes to src/select.c.

  2368   2368     ** the ORDER BY clause covers every term of the result set.  Add
  2369   2369     ** terms to the ORDER BY clause as necessary.
  2370   2370     */
  2371   2371     if( op!=TK_ALL ){
  2372   2372       for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  2373   2373         struct ExprList_item *pItem;
  2374   2374         for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  2375         -        assert( pItem->iOrderByCol>0 );
  2376         -        if( pItem->iOrderByCol==i ) break;
         2375  +        assert( pItem->u.x.iOrderByCol>0 );
         2376  +        if( pItem->u.x.iOrderByCol==i ) break;
  2377   2377         }
  2378   2378         if( j==nOrderBy ){
  2379   2379           Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  2380   2380           if( pNew==0 ) return SQLITE_NOMEM;
  2381   2381           pNew->flags |= EP_IntValue;
  2382   2382           pNew->u.iValue = i;
  2383   2383           pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  2384         -        if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
         2384  +        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  2385   2385         }
  2386   2386       }
  2387   2387     }
  2388   2388   
  2389   2389     /* Compute the comparison permutation and keyinfo that is used with
  2390   2390     ** the permutation used to determine if the next
  2391   2391     ** row of results comes from selectA or selectB.  Also add explicit
................................................................................
  2393   2393     ** to the right and the left are evaluated, they use the correct
  2394   2394     ** collation.
  2395   2395     */
  2396   2396     aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  2397   2397     if( aPermute ){
  2398   2398       struct ExprList_item *pItem;
  2399   2399       for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  2400         -      assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
  2401         -      aPermute[i] = pItem->iOrderByCol - 1;
         2400  +      assert( pItem->u.x.iOrderByCol>0
         2401  +          && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
         2402  +      aPermute[i] = pItem->u.x.iOrderByCol - 1;
  2402   2403       }
  2403   2404       pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy, 1);
  2404   2405       if( pKeyMerge ){
  2405   2406         for(i=0; i<nOrderBy; i++){
  2406   2407           CollSeq *pColl;
  2407   2408           Expr *pTerm = pOrderBy->a[i].pExpr;
  2408   2409           if( pTerm->flags & EP_Collate ){
................................................................................
  2974   2975         testcase( pSub1->pSrc->nSrc>1 );
  2975   2976       }
  2976   2977   
  2977   2978       /* Restriction 18. */
  2978   2979       if( p->pOrderBy ){
  2979   2980         int ii;
  2980   2981         for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  2981         -        if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
         2982  +        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  2982   2983         }
  2983   2984       }
  2984   2985     }
  2985   2986   
  2986   2987     /***** If we reach this point, flattening is permitted. *****/
  2987   2988   
  2988   2989     /* Authorize the subquery */
................................................................................
  4381   4382       ** GROUP BY clause.
  4382   4383       */
  4383   4384       if( pGroupBy ){
  4384   4385         int k;                        /* Loop counter */
  4385   4386         struct ExprList_item *pItem;  /* For looping over expression in a list */
  4386   4387   
  4387   4388         for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  4388         -        pItem->iAlias = 0;
         4389  +        pItem->u.x.iAlias = 0;
  4389   4390         }
  4390   4391         for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  4391         -        pItem->iAlias = 0;
         4392  +        pItem->u.x.iAlias = 0;
  4392   4393         }
  4393   4394         if( p->nSelectRow>100 ) p->nSelectRow = 100;
  4394   4395       }else{
  4395   4396         p->nSelectRow = 1;
  4396   4397       }
  4397   4398   
  4398   4399    

Changes to src/sqliteInt.h.

  1825   1825   #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
  1826   1826   #define EP_Error     0x000008 /* Expression contains one or more errors */
  1827   1827   #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
  1828   1828   #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  1829   1829   #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  1830   1830   #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  1831   1831   #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE opeartor */
  1832         -#define EP_FixedDest 0x000200 /* Result needed in a specific register */
         1832  +      /* unused      0x000200 */
  1833   1833   #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
  1834   1834   #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  1835   1835   #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
  1836   1836   #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  1837   1837   #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  1838   1838   #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
  1839   1839   #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
................................................................................
  1896   1896     struct ExprList_item { /* For each expression in the list */
  1897   1897       Expr *pExpr;            /* The list of expressions */
  1898   1898       char *zName;            /* Token associated with this expression */
  1899   1899       char *zSpan;            /* Original text of the expression */
  1900   1900       u8 sortOrder;           /* 1 for DESC or 0 for ASC */
  1901   1901       unsigned done :1;       /* A flag to indicate when processing is finished */
  1902   1902       unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  1903         -    u16 iOrderByCol;        /* For ORDER BY, column number in result set */
  1904         -    u16 iAlias;             /* Index into Parse.aAlias[] for zName */
         1903  +    union {
         1904  +      struct {
         1905  +        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
         1906  +        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
         1907  +      } x;
         1908  +      int iConstExprReg;      /* Register in which Expr value is cached */
         1909  +    } u;
  1905   1910     } *a;                  /* Alloc a power of two greater or equal to nExpr */
  1906   1911   };
  1907   1912   
  1908   1913   /*
  1909   1914   ** An instance of this structure is used by the parser to record both
  1910   1915   ** the parse tree for an expression and the span of input text for an
  1911   1916   ** expression.
................................................................................
  2274   2279       int iTable;           /* Table cursor number */
  2275   2280       int iColumn;          /* Table column number */
  2276   2281       u8 tempReg;           /* iReg is a temp register that needs to be freed */
  2277   2282       int iLevel;           /* Nesting level */
  2278   2283       int iReg;             /* Reg with value of this column. 0 means none. */
  2279   2284       int lru;              /* Least recently used entry has the smallest value */
  2280   2285     } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
         2286  +  ExprList *pConstExpr;/* Constant expressions */
  2281   2287     yDbMask writeMask;   /* Start a write transaction on these databases */
  2282   2288     yDbMask cookieMask;  /* Bitmask of schema verified databases */
  2283   2289     int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
  2284   2290     int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
  2285   2291     int regRowid;        /* Register holding rowid of CREATE TABLE entry */
  2286   2292     int regRoot;         /* Register holding root page number for new objects */
  2287   2293     int nMaxArg;         /* Max args passed to user function by sub-program */
................................................................................
  2887   2893   void sqlite3ExprCacheRemove(Parse*, int, int);
  2888   2894   void sqlite3ExprCacheClear(Parse*);
  2889   2895   void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  2890   2896   int sqlite3ExprCode(Parse*, Expr*, int);
  2891   2897   int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  2892   2898   int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  2893   2899   int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  2894         -void sqlite3ExprCodeConstants(Parse*, Expr*);
  2895   2900   int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  2896   2901   void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  2897   2902   void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  2898   2903   Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  2899   2904   Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  2900   2905   Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  2901   2906   Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
................................................................................
  3255   3260   int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  3256   3261   int sqlite3VtabBegin(sqlite3 *, VTable *);
  3257   3262   FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  3258   3263   void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  3259   3264   sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  3260   3265   int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  3261   3266   int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
         3267  +void sqlite3ParserReset(Parse*);
  3262   3268   int sqlite3Reprepare(Vdbe*);
  3263   3269   void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  3264   3270   CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  3265   3271   int sqlite3TempInMemory(const sqlite3*);
  3266   3272   const char *sqlite3JournalModename(int);
  3267   3273   #ifndef SQLITE_OMIT_WAL
  3268   3274     int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);

Changes to src/trigger.c.

   920    920       pPrg->aColmask[0] = pSubParse->oldmask;
   921    921       pPrg->aColmask[1] = pSubParse->newmask;
   922    922       sqlite3VdbeDelete(v);
   923    923     }
   924    924   
   925    925     assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
   926    926     assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
          927  +  sqlite3ParserReset(pSubParse);
   927    928     sqlite3StackFree(db, pSubParse);
   928    929   
   929    930     return pPrg;
   930    931   }
   931    932       
   932    933   /*
   933    934   ** Return a pointer to a TriggerPrg object containing the sub-program for

Changes to src/vdbeblob.c.

   324    324       *ppBlob = (sqlite3_blob *)pBlob;
   325    325     }else{
   326    326       if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
   327    327       sqlite3DbFree(db, pBlob);
   328    328     }
   329    329     sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
   330    330     sqlite3DbFree(db, zErr);
          331  +  sqlite3ParserReset(pParse);
   331    332     sqlite3StackFree(db, pParse);
   332    333     rc = sqlite3ApiExit(db, rc);
   333    334     sqlite3_mutex_leave(db->mutex);
   334    335     return rc;
   335    336   }
   336    337   
   337    338   /*

Changes to src/vtab.c.

   734    734       }
   735    735       pParse->declareVtab = 0;
   736    736     
   737    737       if( pParse->pVdbe ){
   738    738         sqlite3VdbeFinalize(pParse->pVdbe);
   739    739       }
   740    740       sqlite3DeleteTable(db, pParse->pNewTable);
          741  +    sqlite3ParserReset(pParse);
   741    742       sqlite3StackFree(db, pParse);
   742    743     }
   743    744   
   744    745     assert( (rc&0xff)==rc );
   745    746     rc = sqlite3ApiExit(db, rc);
   746    747     sqlite3_mutex_leave(db->mutex);
   747    748     return rc;

Changes to src/where.c.

   665    665       ** be the name of an indexed column with TEXT affinity. */
   666    666       return 0;
   667    667     }
   668    668     assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
   669    669   
   670    670     pRight = pList->a[0].pExpr;
   671    671     op = pRight->op;
   672         -  if( op==TK_REGISTER ){
   673         -    op = pRight->op2;
   674         -  }
   675    672     if( op==TK_VARIABLE ){
   676    673       Vdbe *pReprepare = pParse->pReprepare;
   677    674       int iCol = pRight->iColumn;
   678    675       pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
   679    676       if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
   680    677         z = (char *)sqlite3_value_text(pVal);
   681    678       }
................................................................................
  2997   2994       int start_constraints;       /* Start of range is constrained */
  2998   2995       int nConstraint;             /* Number of constraint terms */
  2999   2996       Index *pIdx;                 /* The index we will be using */
  3000   2997       int iIdxCur;                 /* The VDBE cursor for the index */
  3001   2998       int nExtraReg = 0;           /* Number of extra registers needed */
  3002   2999       int op;                      /* Instruction opcode */
  3003   3000       char *zStartAff;             /* Affinity for start of range constraint */
  3004         -    char *zEndAff;               /* Affinity for end of range constraint */
         3001  +    char cEndAff = 0;            /* Affinity for end of range constraint */
  3005   3002   
  3006   3003       pIdx = pLoop->u.btree.pIndex;
  3007   3004       iIdxCur = pLevel->iIdxCur;
  3008   3005       assert( nEq>=pLoop->u.btree.nSkip );
  3009   3006   
  3010   3007       /* If this loop satisfies a sort order (pOrderBy) request that 
  3011   3008       ** was passed to this function to implement a "SELECT min(x) ..." 
................................................................................
  3038   3035       }
  3039   3036   
  3040   3037       /* Generate code to evaluate all constraint terms using == or IN
  3041   3038       ** and store the values of those terms in an array of registers
  3042   3039       ** starting at regBase.
  3043   3040       */
  3044   3041       regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  3045         -    zEndAff = sqlite3DbStrDup(db, zStartAff);
         3042  +    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
         3043  +    if( zStartAff ) cEndAff = zStartAff[nEq];
  3046   3044       addrNxt = pLevel->addrNxt;
  3047   3045   
  3048   3046       /* If we are doing a reverse order scan on an ascending index, or
  3049   3047       ** a forward order scan on a descending index, interchange the 
  3050   3048       ** start and end terms (pRangeStart and pRangeEnd).
  3051   3049       */
  3052   3050       if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
................................................................................
  3108   3106       if( pRangeEnd ){
  3109   3107         Expr *pRight = pRangeEnd->pExpr->pRight;
  3110   3108         sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  3111   3109         sqlite3ExprCode(pParse, pRight, regBase+nEq);
  3112   3110         if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  3113   3111           sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  3114   3112         }
  3115         -      if( zEndAff ){
  3116         -        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  3117         -          /* Since the comparison is to be performed with no conversions
  3118         -          ** applied to the operands, set the affinity to apply to pRight to 
  3119         -          ** SQLITE_AFF_NONE.  */
  3120         -          zEndAff[nEq] = SQLITE_AFF_NONE;
  3121         -        }
  3122         -        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  3123         -          zEndAff[nEq] = SQLITE_AFF_NONE;
  3124         -        }
  3125         -      }  
  3126         -      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
         3113  +      if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
         3114  +       && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
         3115  +      ){
         3116  +        codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
         3117  +      }
  3127   3118         nConstraint++;
  3128   3119         testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  3129   3120       }
  3130   3121       sqlite3DbFree(db, zStartAff);
  3131         -    sqlite3DbFree(db, zEndAff);
  3132   3122   
  3133   3123       /* Top of the loop body */
  3134   3124       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  3135   3125   
  3136   3126       /* Check if the index cursor is past the end of the range. */
  3137   3127       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  3138   3128       testcase( op==OP_Noop );
................................................................................
  5422   5412   #endif
  5423   5413   
  5424   5414     /* Split the WHERE clause into separate subexpressions where each
  5425   5415     ** subexpression is separated by an AND operator.
  5426   5416     */
  5427   5417     initMaskSet(pMaskSet);
  5428   5418     whereClauseInit(&pWInfo->sWC, pWInfo);
  5429         -  sqlite3ExprCodeConstants(pParse, pWhere);
  5430   5419     whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  5431   5420     sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  5432   5421       
  5433   5422     /* Special case: a WHERE clause that is constant.  Evaluate the
  5434   5423     ** expression and either jump over all of the code or fall thru.
  5435   5424     */
  5436   5425     if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){

Changes to test/default.test.

    60     60       execsql {
    61     61         INSERT INTO t4 DEFAULT VALUES;
    62     62         PRAGMA table_info(t4);
    63     63       }
    64     64     } {0 c {} 0 'abc' 0}
    65     65   }
    66     66   
           67  +do_execsql_test default-3.1 {
           68  +  CREATE TABLE t3(
           69  +    a INTEGER PRIMARY KEY AUTOINCREMENT,
           70  +    b INT DEFAULT 12345 UNIQUE NOT NULL CHECK( b>=0 AND b<99999 ),
           71  +    c VARCHAR(123,456) DEFAULT 'hello' NOT NULL ON CONFLICT REPLACE,
           72  +    d REAL,
           73  +    e FLOATING POINT(5,10) DEFAULT 4.36,
           74  +    f NATIONAL CHARACTER(15) COLLATE RTRIM,
           75  +    g LONG INTEGER DEFAULT( 3600*12 )
           76  +  );
           77  +  INSERT INTO t3 VALUES(null, 5, 'row1', '5.25', 'xyz', 321, '432');
           78  +  SELECT a, typeof(a), b, typeof(b), c, typeof(c), 
           79  +         d, typeof(d), e, typeof(e), f, typeof(f),
           80  +         g, typeof(g) FROM t3;
           81  +} {1 integer 5 integer row1 text 5.25 real xyz text 321 text 432 integer}
           82  +do_execsql_test default-3.2 {
           83  +  DELETE FROM t3;
           84  +  INSERT INTO t3 DEFAULT VALUES;
           85  +  SELECT * FROM t3;
           86  +} {2 12345 hello {} 4.36 {} 43200}
           87  +do_execsql_test default-3.3 {
           88  +  CREATE TABLE t300(
           89  +    a INT DEFAULT 2147483647,
           90  +    b INT DEFAULT 2147483648,
           91  +    c INT DEFAULT +9223372036854775807,
           92  +    d INT DEFAULT -2147483647,
           93  +    e INT DEFAULT -2147483648,
           94  +    f INT DEFAULT -9223372036854775808,
           95  +    g INT DEFAULT (-(-9223372036854775808)),
           96  +    h INT DEFAULT (-(-9223372036854775807))
           97  +  );
           98  +  INSERT INTO t300 DEFAULT VALUES;
           99  +  SELECT * FROM t300;
          100  +} {2147483647 2147483648 9223372036854775807 -2147483647 -2147483648 -9223372036854775808 9.22337203685478e+18 9223372036854775807}
          101  +
    67    102   finish_test