extensions/sqlite/sqlite-source/expr.c
author Asher Baker <asherkin@gmail.com>
Thu Apr 26 16:58:18 2012 +0100 (2012-04-26)
changeset 3488 bee90c8ef6c3
parent 1952 b7aa2b626807
permissions -rw-r--r--
Fixed client serials not being unique on Windows (bug 5285, r=psychonic).
ds@1952
     1
/*
ds@1952
     2
** 2001 September 15
ds@1952
     3
**
ds@1952
     4
** The author disclaims copyright to this source code.  In place of
ds@1952
     5
** a legal notice, here is a blessing:
ds@1952
     6
**
ds@1952
     7
**    May you do good and not evil.
ds@1952
     8
**    May you find forgiveness for yourself and forgive others.
ds@1952
     9
**    May you share freely, never taking more than you give.
ds@1952
    10
**
ds@1952
    11
*************************************************************************
ds@1952
    12
** This file contains routines used for analyzing expressions and
ds@1952
    13
** for generating VDBE code that evaluates expressions in SQLite.
ds@1952
    14
**
ds@1952
    15
** $Id$
ds@1952
    16
*/
ds@1952
    17
#include "sqliteInt.h"
ds@1952
    18
#include <ctype.h>
ds@1952
    19
ds@1952
    20
/*
ds@1952
    21
** Return the 'affinity' of the expression pExpr if any.
ds@1952
    22
**
ds@1952
    23
** If pExpr is a column, a reference to a column via an 'AS' alias,
ds@1952
    24
** or a sub-select with a column as the return value, then the 
ds@1952
    25
** affinity of that column is returned. Otherwise, 0x00 is returned,
ds@1952
    26
** indicating no affinity for the expression.
ds@1952
    27
**
ds@1952
    28
** i.e. the WHERE clause expresssions in the following statements all
ds@1952
    29
** have an affinity:
ds@1952
    30
**
ds@1952
    31
** CREATE TABLE t1(a);
ds@1952
    32
** SELECT * FROM t1 WHERE a;
ds@1952
    33
** SELECT a AS b FROM t1 WHERE b;
ds@1952
    34
** SELECT * FROM t1 WHERE (select a from t1);
ds@1952
    35
*/
ds@1952
    36
char sqlite3ExprAffinity(Expr *pExpr){
ds@1952
    37
  int op = pExpr->op;
ds@1952
    38
  if( op==TK_SELECT ){
ds@1952
    39
    return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
ds@1952
    40
  }
ds@1952
    41
#ifndef SQLITE_OMIT_CAST
ds@1952
    42
  if( op==TK_CAST ){
ds@1952
    43
    return sqlite3AffinityType(&pExpr->token);
ds@1952
    44
  }
ds@1952
    45
#endif
ds@1952
    46
  return pExpr->affinity;
ds@1952
    47
}
ds@1952
    48
ds@1952
    49
/*
ds@1952
    50
** Set the collating sequence for expression pExpr to be the collating
ds@1952
    51
** sequence named by pToken.   Return a pointer to the revised expression.
ds@1952
    52
** The collating sequence is marked as "explicit" using the EP_ExpCollate
ds@1952
    53
** flag.  An explicit collating sequence will override implicit
ds@1952
    54
** collating sequences.
ds@1952
    55
*/
ds@1952
    56
Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
ds@1952
    57
  CollSeq *pColl;
ds@1952
    58
  if( pExpr==0 ) return 0;
ds@1952
    59
  pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
ds@1952
    60
  if( pColl ){
ds@1952
    61
    pExpr->pColl = pColl;
ds@1952
    62
    pExpr->flags |= EP_ExpCollate;
ds@1952
    63
  }
ds@1952
    64
  return pExpr;
ds@1952
    65
}
ds@1952
    66
ds@1952
    67
/*
ds@1952
    68
** Return the default collation sequence for the expression pExpr. If
ds@1952
    69
** there is no default collation type, return 0.
ds@1952
    70
*/
ds@1952
    71
CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
ds@1952
    72
  CollSeq *pColl = 0;
ds@1952
    73
  if( pExpr ){
ds@1952
    74
    int op;
ds@1952
    75
    pColl = pExpr->pColl;
ds@1952
    76
    op = pExpr->op;
ds@1952
    77
    if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
ds@1952
    78
      return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
ds@1952
    79
    }
ds@1952
    80
  }
ds@1952
    81
  if( sqlite3CheckCollSeq(pParse, pColl) ){ 
ds@1952
    82
    pColl = 0;
ds@1952
    83
  }
ds@1952
    84
  return pColl;
ds@1952
    85
}
ds@1952
    86
ds@1952
    87
/*
ds@1952
    88
** pExpr is an operand of a comparison operator.  aff2 is the
ds@1952
    89
** type affinity of the other operand.  This routine returns the
ds@1952
    90
** type affinity that should be used for the comparison operator.
ds@1952
    91
*/
ds@1952
    92
char sqlite3CompareAffinity(Expr *pExpr, char aff2){
ds@1952
    93
  char aff1 = sqlite3ExprAffinity(pExpr);
ds@1952
    94
  if( aff1 && aff2 ){
ds@1952
    95
    /* Both sides of the comparison are columns. If one has numeric
ds@1952
    96
    ** affinity, use that. Otherwise use no affinity.
ds@1952
    97
    */
ds@1952
    98
    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
ds@1952
    99
      return SQLITE_AFF_NUMERIC;
ds@1952
   100
    }else{
ds@1952
   101
      return SQLITE_AFF_NONE;
ds@1952
   102
    }
ds@1952
   103
  }else if( !aff1 && !aff2 ){
ds@1952
   104
    /* Neither side of the comparison is a column.  Compare the
ds@1952
   105
    ** results directly.
ds@1952
   106
    */
ds@1952
   107
    return SQLITE_AFF_NONE;
ds@1952
   108
  }else{
ds@1952
   109
    /* One side is a column, the other is not. Use the columns affinity. */
ds@1952
   110
    assert( aff1==0 || aff2==0 );
ds@1952
   111
    return (aff1 + aff2);
ds@1952
   112
  }
ds@1952
   113
}
ds@1952
   114
ds@1952
   115
/*
ds@1952
   116
** pExpr is a comparison operator.  Return the type affinity that should
ds@1952
   117
** be applied to both operands prior to doing the comparison.
ds@1952
   118
*/
ds@1952
   119
static char comparisonAffinity(Expr *pExpr){
ds@1952
   120
  char aff;
ds@1952
   121
  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
ds@1952
   122
          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
ds@1952
   123
          pExpr->op==TK_NE );
ds@1952
   124
  assert( pExpr->pLeft );
ds@1952
   125
  aff = sqlite3ExprAffinity(pExpr->pLeft);
ds@1952
   126
  if( pExpr->pRight ){
ds@1952
   127
    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
ds@1952
   128
  }
ds@1952
   129
  else if( pExpr->pSelect ){
ds@1952
   130
    aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
ds@1952
   131
  }
ds@1952
   132
  else if( !aff ){
ds@1952
   133
    aff = SQLITE_AFF_NONE;
ds@1952
   134
  }
ds@1952
   135
  return aff;
ds@1952
   136
}
ds@1952
   137
ds@1952
   138
/*
ds@1952
   139
** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
ds@1952
   140
** idx_affinity is the affinity of an indexed column. Return true
ds@1952
   141
** if the index with affinity idx_affinity may be used to implement
ds@1952
   142
** the comparison in pExpr.
ds@1952
   143
*/
ds@1952
   144
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
ds@1952
   145
  char aff = comparisonAffinity(pExpr);
ds@1952
   146
  switch( aff ){
ds@1952
   147
    case SQLITE_AFF_NONE:
ds@1952
   148
      return 1;
ds@1952
   149
    case SQLITE_AFF_TEXT:
ds@1952
   150
      return idx_affinity==SQLITE_AFF_TEXT;
ds@1952
   151
    default:
ds@1952
   152
      return sqlite3IsNumericAffinity(idx_affinity);
ds@1952
   153
  }
ds@1952
   154
}
ds@1952
   155
ds@1952
   156
/*
ds@1952
   157
** Return the P1 value that should be used for a binary comparison
ds@1952
   158
** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
ds@1952
   159
** If jumpIfNull is true, then set the low byte of the returned
ds@1952
   160
** P1 value to tell the opcode to jump if either expression
ds@1952
   161
** evaluates to NULL.
ds@1952
   162
*/
ds@1952
   163
static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
ds@1952
   164
  char aff = sqlite3ExprAffinity(pExpr2);
ds@1952
   165
  return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
ds@1952
   166
}
ds@1952
   167
ds@1952
   168
/*
ds@1952
   169
** Return a pointer to the collation sequence that should be used by
ds@1952
   170
** a binary comparison operator comparing pLeft and pRight.
ds@1952
   171
**
ds@1952
   172
** If the left hand expression has a collating sequence type, then it is
ds@1952
   173
** used. Otherwise the collation sequence for the right hand expression
ds@1952
   174
** is used, or the default (BINARY) if neither expression has a collating
ds@1952
   175
** type.
ds@1952
   176
**
ds@1952
   177
** Argument pRight (but not pLeft) may be a null pointer. In this case,
ds@1952
   178
** it is not considered.
ds@1952
   179
*/
ds@1952
   180
CollSeq *sqlite3BinaryCompareCollSeq(
ds@1952
   181
  Parse *pParse, 
ds@1952
   182
  Expr *pLeft, 
ds@1952
   183
  Expr *pRight
ds@1952
   184
){
ds@1952
   185
  CollSeq *pColl;
ds@1952
   186
  assert( pLeft );
ds@1952
   187
  if( pLeft->flags & EP_ExpCollate ){
ds@1952
   188
    assert( pLeft->pColl );
ds@1952
   189
    pColl = pLeft->pColl;
ds@1952
   190
  }else if( pRight && pRight->flags & EP_ExpCollate ){
ds@1952
   191
    assert( pRight->pColl );
ds@1952
   192
    pColl = pRight->pColl;
ds@1952
   193
  }else{
ds@1952
   194
    pColl = sqlite3ExprCollSeq(pParse, pLeft);
ds@1952
   195
    if( !pColl ){
ds@1952
   196
      pColl = sqlite3ExprCollSeq(pParse, pRight);
ds@1952
   197
    }
ds@1952
   198
  }
ds@1952
   199
  return pColl;
ds@1952
   200
}
ds@1952
   201
ds@1952
   202
/*
ds@1952
   203
** Generate code for a comparison operator.
ds@1952
   204
*/
ds@1952
   205
static int codeCompare(
ds@1952
   206
  Parse *pParse,    /* The parsing (and code generating) context */
ds@1952
   207
  Expr *pLeft,      /* The left operand */
ds@1952
   208
  Expr *pRight,     /* The right operand */
ds@1952
   209
  int opcode,       /* The comparison opcode */
ds@1952
   210
  int dest,         /* Jump here if true.  */
ds@1952
   211
  int jumpIfNull    /* If true, jump if either operand is NULL */
ds@1952
   212
){
ds@1952
   213
  int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
ds@1952
   214
  CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
ds@1952
   215
  return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
ds@1952
   216
}
ds@1952
   217
ds@1952
   218
/*
ds@1952
   219
** Construct a new expression node and return a pointer to it.  Memory
ds@1952
   220
** for this node is obtained from sqlite3_malloc().  The calling function
ds@1952
   221
** is responsible for making sure the node eventually gets freed.
ds@1952
   222
*/
ds@1952
   223
Expr *sqlite3Expr(
ds@1952
   224
  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
ds@1952
   225
  int op,                 /* Expression opcode */
ds@1952
   226
  Expr *pLeft,            /* Left operand */
ds@1952
   227
  Expr *pRight,           /* Right operand */
ds@1952
   228
  const Token *pToken     /* Argument token */
ds@1952
   229
){
ds@1952
   230
  Expr *pNew;
ds@1952
   231
  pNew = sqlite3DbMallocZero(db, sizeof(Expr));
ds@1952
   232
  if( pNew==0 ){
ds@1952
   233
    /* When malloc fails, delete pLeft and pRight. Expressions passed to 
ds@1952
   234
    ** this function must always be allocated with sqlite3Expr() for this 
ds@1952
   235
    ** reason. 
ds@1952
   236
    */
ds@1952
   237
    sqlite3ExprDelete(pLeft);
ds@1952
   238
    sqlite3ExprDelete(pRight);
ds@1952
   239
    return 0;
ds@1952
   240
  }
ds@1952
   241
  pNew->op = op;
ds@1952
   242
  pNew->pLeft = pLeft;
ds@1952
   243
  pNew->pRight = pRight;
ds@1952
   244
  pNew->iAgg = -1;
ds@1952
   245
  if( pToken ){
ds@1952
   246
    assert( pToken->dyn==0 );
ds@1952
   247
    pNew->span = pNew->token = *pToken;
ds@1952
   248
  }else if( pLeft ){
ds@1952
   249
    if( pRight ){
ds@1952
   250
      sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
ds@1952
   251
      if( pRight->flags & EP_ExpCollate ){
ds@1952
   252
        pNew->flags |= EP_ExpCollate;
ds@1952
   253
        pNew->pColl = pRight->pColl;
ds@1952
   254
      }
ds@1952
   255
    }
ds@1952
   256
    if( pLeft->flags & EP_ExpCollate ){
ds@1952
   257
      pNew->flags |= EP_ExpCollate;
ds@1952
   258
      pNew->pColl = pLeft->pColl;
ds@1952
   259
    }
ds@1952
   260
  }
ds@1952
   261
ds@1952
   262
  sqlite3ExprSetHeight(pNew);
ds@1952
   263
  return pNew;
ds@1952
   264
}
ds@1952
   265
ds@1952
   266
/*
ds@1952
   267
** Works like sqlite3Expr() except that it takes an extra Parse*
ds@1952
   268
** argument and notifies the associated connection object if malloc fails.
ds@1952
   269
*/
ds@1952
   270
Expr *sqlite3PExpr(
ds@1952
   271
  Parse *pParse,          /* Parsing context */
ds@1952
   272
  int op,                 /* Expression opcode */
ds@1952
   273
  Expr *pLeft,            /* Left operand */
ds@1952
   274
  Expr *pRight,           /* Right operand */
ds@1952
   275
  const Token *pToken     /* Argument token */
ds@1952
   276
){
ds@1952
   277
  return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
ds@1952
   278
}
ds@1952
   279
ds@1952
   280
/*
ds@1952
   281
** When doing a nested parse, you can include terms in an expression
ds@1952
   282
** that look like this:   #0 #1 #2 ...  These terms refer to elements
ds@1952
   283
** on the stack.  "#0" means the top of the stack.
ds@1952
   284
** "#1" means the next down on the stack.  And so forth.
ds@1952
   285
**
ds@1952
   286
** This routine is called by the parser to deal with on of those terms.
ds@1952
   287
** It immediately generates code to store the value in a memory location.
ds@1952
   288
** The returns an expression that will code to extract the value from
ds@1952
   289
** that memory location as needed.
ds@1952
   290
*/
ds@1952
   291
Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
ds@1952
   292
  Vdbe *v = pParse->pVdbe;
ds@1952
   293
  Expr *p;
ds@1952
   294
  int depth;
ds@1952
   295
  if( pParse->nested==0 ){
ds@1952
   296
    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
ds@1952
   297
    return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
ds@1952
   298
  }
ds@1952
   299
  if( v==0 ) return 0;
ds@1952
   300
  p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
ds@1952
   301
  if( p==0 ){
ds@1952
   302
    return 0;  /* Malloc failed */
ds@1952
   303
  }
ds@1952
   304
  depth = atoi((char*)&pToken->z[1]);
ds@1952
   305
  p->iTable = pParse->nMem++;
ds@1952
   306
  sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
ds@1952
   307
  sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
ds@1952
   308
  return p;
ds@1952
   309
}
ds@1952
   310
ds@1952
   311
/*
ds@1952
   312
** Join two expressions using an AND operator.  If either expression is
ds@1952
   313
** NULL, then just return the other expression.
ds@1952
   314
*/
ds@1952
   315
Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
ds@1952
   316
  if( pLeft==0 ){
ds@1952
   317
    return pRight;
ds@1952
   318
  }else if( pRight==0 ){
ds@1952
   319
    return pLeft;
ds@1952
   320
  }else{
ds@1952
   321
    return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
ds@1952
   322
  }
ds@1952
   323
}
ds@1952
   324
ds@1952
   325
/*
ds@1952
   326
** Set the Expr.span field of the given expression to span all
ds@1952
   327
** text between the two given tokens.
ds@1952
   328
*/
ds@1952
   329
void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
ds@1952
   330
  assert( pRight!=0 );
ds@1952
   331
  assert( pLeft!=0 );
ds@1952
   332
  if( pExpr && pRight->z && pLeft->z ){
ds@1952
   333
    assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
ds@1952
   334
    if( pLeft->dyn==0 && pRight->dyn==0 ){
ds@1952
   335
      pExpr->span.z = pLeft->z;
ds@1952
   336
      pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
ds@1952
   337
    }else{
ds@1952
   338
      pExpr->span.z = 0;
ds@1952
   339
    }
ds@1952
   340
  }
ds@1952
   341
}
ds@1952
   342
ds@1952
   343
/*
ds@1952
   344
** Construct a new expression node for a function with multiple
ds@1952
   345
** arguments.
ds@1952
   346
*/
ds@1952
   347
Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
ds@1952
   348
  Expr *pNew;
ds@1952
   349
  assert( pToken );
ds@1952
   350
  pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
ds@1952
   351
  if( pNew==0 ){
ds@1952
   352
    sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
ds@1952
   353
    return 0;
ds@1952
   354
  }
ds@1952
   355
  pNew->op = TK_FUNCTION;
ds@1952
   356
  pNew->pList = pList;
ds@1952
   357
  assert( pToken->dyn==0 );
ds@1952
   358
  pNew->token = *pToken;
ds@1952
   359
  pNew->span = pNew->token;
ds@1952
   360
ds@1952
   361
  sqlite3ExprSetHeight(pNew);
ds@1952
   362
  return pNew;
ds@1952
   363
}
ds@1952
   364
ds@1952
   365
/*
ds@1952
   366
** Assign a variable number to an expression that encodes a wildcard
ds@1952
   367
** in the original SQL statement.  
ds@1952
   368
**
ds@1952
   369
** Wildcards consisting of a single "?" are assigned the next sequential
ds@1952
   370
** variable number.
ds@1952
   371
**
ds@1952
   372
** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
ds@1952
   373
** sure "nnn" is not too be to avoid a denial of service attack when
ds@1952
   374
** the SQL statement comes from an external source.
ds@1952
   375
**
ds@1952
   376
** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
ds@1952
   377
** as the previous instance of the same wildcard.  Or if this is the first
ds@1952
   378
** instance of the wildcard, the next sequenial variable number is
ds@1952
   379
** assigned.
ds@1952
   380
*/
ds@1952
   381
void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
ds@1952
   382
  Token *pToken;
ds@1952
   383
  sqlite3 *db = pParse->db;
ds@1952
   384
ds@1952
   385
  if( pExpr==0 ) return;
ds@1952
   386
  pToken = &pExpr->token;
ds@1952
   387
  assert( pToken->n>=1 );
ds@1952
   388
  assert( pToken->z!=0 );
ds@1952
   389
  assert( pToken->z[0]!=0 );
ds@1952
   390
  if( pToken->n==1 ){
ds@1952
   391
    /* Wildcard of the form "?".  Assign the next variable number */
ds@1952
   392
    pExpr->iTable = ++pParse->nVar;
ds@1952
   393
  }else if( pToken->z[0]=='?' ){
ds@1952
   394
    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
ds@1952
   395
    ** use it as the variable number */
ds@1952
   396
    int i;
ds@1952
   397
    pExpr->iTable = i = atoi((char*)&pToken->z[1]);
ds@1952
   398
    if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
ds@1952
   399
      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
ds@1952
   400
          SQLITE_MAX_VARIABLE_NUMBER);
ds@1952
   401
    }
ds@1952
   402
    if( i>pParse->nVar ){
ds@1952
   403
      pParse->nVar = i;
ds@1952
   404
    }
ds@1952
   405
  }else{
ds@1952
   406
    /* Wildcards of the form ":aaa" or "$aaa".  Reuse the same variable
ds@1952
   407
    ** number as the prior appearance of the same name, or if the name
ds@1952
   408
    ** has never appeared before, reuse the same variable number
ds@1952
   409
    */
ds@1952
   410
    int i, n;
ds@1952
   411
    n = pToken->n;
ds@1952
   412
    for(i=0; i<pParse->nVarExpr; i++){
ds@1952
   413
      Expr *pE;
ds@1952
   414
      if( (pE = pParse->apVarExpr[i])!=0
ds@1952
   415
          && pE->token.n==n
ds@1952
   416
          && memcmp(pE->token.z, pToken->z, n)==0 ){
ds@1952
   417
        pExpr->iTable = pE->iTable;
ds@1952
   418
        break;
ds@1952
   419
      }
ds@1952
   420
    }
ds@1952
   421
    if( i>=pParse->nVarExpr ){
ds@1952
   422
      pExpr->iTable = ++pParse->nVar;
ds@1952
   423
      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
ds@1952
   424
        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
ds@1952
   425
        pParse->apVarExpr =
ds@1952
   426
            sqlite3DbReallocOrFree(
ds@1952
   427
              db,
ds@1952
   428
              pParse->apVarExpr,
ds@1952
   429
              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
ds@1952
   430
            );
ds@1952
   431
      }
ds@1952
   432
      if( !db->mallocFailed ){
ds@1952
   433
        assert( pParse->apVarExpr!=0 );
ds@1952
   434
        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
ds@1952
   435
      }
ds@1952
   436
    }
ds@1952
   437
  } 
ds@1952
   438
  if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
ds@1952
   439
    sqlite3ErrorMsg(pParse, "too many SQL variables");
ds@1952
   440
  }
ds@1952
   441
}
ds@1952
   442
ds@1952
   443
/*
ds@1952
   444
** Recursively delete an expression tree.
ds@1952
   445
*/
ds@1952
   446
void sqlite3ExprDelete(Expr *p){
ds@1952
   447
  if( p==0 ) return;
ds@1952
   448
  if( p->span.dyn ) sqlite3_free((char*)p->span.z);
ds@1952
   449
  if( p->token.dyn ) sqlite3_free((char*)p->token.z);
ds@1952
   450
  sqlite3ExprDelete(p->pLeft);
ds@1952
   451
  sqlite3ExprDelete(p->pRight);
ds@1952
   452
  sqlite3ExprListDelete(p->pList);
ds@1952
   453
  sqlite3SelectDelete(p->pSelect);
ds@1952
   454
  sqlite3_free(p);
ds@1952
   455
}
ds@1952
   456
ds@1952
   457
/*
ds@1952
   458
** The Expr.token field might be a string literal that is quoted.
ds@1952
   459
** If so, remove the quotation marks.
ds@1952
   460
*/
ds@1952
   461
void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
ds@1952
   462
  if( ExprHasAnyProperty(p, EP_Dequoted) ){
ds@1952
   463
    return;
ds@1952
   464
  }
ds@1952
   465
  ExprSetProperty(p, EP_Dequoted);
ds@1952
   466
  if( p->token.dyn==0 ){
ds@1952
   467
    sqlite3TokenCopy(db, &p->token, &p->token);
ds@1952
   468
  }
ds@1952
   469
  sqlite3Dequote((char*)p->token.z);
ds@1952
   470
}
ds@1952
   471
ds@1952
   472
ds@1952
   473
/*
ds@1952
   474
** The following group of routines make deep copies of expressions,
ds@1952
   475
** expression lists, ID lists, and select statements.  The copies can
ds@1952
   476
** be deleted (by being passed to their respective ...Delete() routines)
ds@1952
   477
** without effecting the originals.
ds@1952
   478
**
ds@1952
   479
** The expression list, ID, and source lists return by sqlite3ExprListDup(),
ds@1952
   480
** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
ds@1952
   481
** by subsequent calls to sqlite*ListAppend() routines.
ds@1952
   482
**
ds@1952
   483
** Any tables that the SrcList might point to are not duplicated.
ds@1952
   484
*/
ds@1952
   485
Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
ds@1952
   486
  Expr *pNew;
ds@1952
   487
  if( p==0 ) return 0;
ds@1952
   488
  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
ds@1952
   489
  if( pNew==0 ) return 0;
ds@1952
   490
  memcpy(pNew, p, sizeof(*pNew));
ds@1952
   491
  if( p->token.z!=0 ){
ds@1952
   492
    pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
ds@1952
   493
    pNew->token.dyn = 1;
ds@1952
   494
  }else{
ds@1952
   495
    assert( pNew->token.z==0 );
ds@1952
   496
  }
ds@1952
   497
  pNew->span.z = 0;
ds@1952
   498
  pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
ds@1952
   499
  pNew->pRight = sqlite3ExprDup(db, p->pRight);
ds@1952
   500
  pNew->pList = sqlite3ExprListDup(db, p->pList);
ds@1952
   501
  pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
ds@1952
   502
  return pNew;
ds@1952
   503
}
ds@1952
   504
void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
ds@1952
   505
  if( pTo->dyn ) sqlite3_free((char*)pTo->z);
ds@1952
   506
  if( pFrom->z ){
ds@1952
   507
    pTo->n = pFrom->n;
ds@1952
   508
    pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
ds@1952
   509
    pTo->dyn = 1;
ds@1952
   510
  }else{
ds@1952
   511
    pTo->z = 0;
ds@1952
   512
  }
ds@1952
   513
}
ds@1952
   514
ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
ds@1952
   515
  ExprList *pNew;
ds@1952
   516
  struct ExprList_item *pItem, *pOldItem;
ds@1952
   517
  int i;
ds@1952
   518
  if( p==0 ) return 0;
ds@1952
   519
  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
ds@1952
   520
  if( pNew==0 ) return 0;
ds@1952
   521
  pNew->iECursor = 0;
ds@1952
   522
  pNew->nExpr = pNew->nAlloc = p->nExpr;
ds@1952
   523
  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
ds@1952
   524
  if( pItem==0 ){
ds@1952
   525
    sqlite3_free(pNew);
ds@1952
   526
    return 0;
ds@1952
   527
  } 
ds@1952
   528
  pOldItem = p->a;
ds@1952
   529
  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
ds@1952
   530
    Expr *pNewExpr, *pOldExpr;
ds@1952
   531
    pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
ds@1952
   532
    if( pOldExpr->span.z!=0 && pNewExpr ){
ds@1952
   533
      /* Always make a copy of the span for top-level expressions in the
ds@1952
   534
      ** expression list.  The logic in SELECT processing that determines
ds@1952
   535
      ** the names of columns in the result set needs this information */
ds@1952
   536
      sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
ds@1952
   537
    }
ds@1952
   538
    assert( pNewExpr==0 || pNewExpr->span.z!=0 
ds@1952
   539
            || pOldExpr->span.z==0
ds@1952
   540
            || db->mallocFailed );
ds@1952
   541
    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
ds@1952
   542
    pItem->sortOrder = pOldItem->sortOrder;
ds@1952
   543
    pItem->isAgg = pOldItem->isAgg;
ds@1952
   544
    pItem->done = 0;
ds@1952
   545
  }
ds@1952
   546
  return pNew;
ds@1952
   547
}
ds@1952
   548
ds@1952
   549
/*
ds@1952
   550
** If cursors, triggers, views and subqueries are all omitted from
ds@1952
   551
** the build, then none of the following routines, except for 
ds@1952
   552
** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
ds@1952
   553
** called with a NULL argument.
ds@1952
   554
*/
ds@1952
   555
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
ds@1952
   556
 || !defined(SQLITE_OMIT_SUBQUERY)
ds@1952
   557
SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
ds@1952
   558
  SrcList *pNew;
ds@1952
   559
  int i;
ds@1952
   560
  int nByte;
ds@1952
   561
  if( p==0 ) return 0;
ds@1952
   562
  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
ds@1952
   563
  pNew = sqlite3DbMallocRaw(db, nByte );
ds@1952
   564
  if( pNew==0 ) return 0;
ds@1952
   565
  pNew->nSrc = pNew->nAlloc = p->nSrc;
ds@1952
   566
  for(i=0; i<p->nSrc; i++){
ds@1952
   567
    struct SrcList_item *pNewItem = &pNew->a[i];
ds@1952
   568
    struct SrcList_item *pOldItem = &p->a[i];
ds@1952
   569
    Table *pTab;
ds@1952
   570
    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
ds@1952
   571
    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
ds@1952
   572
    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
ds@1952
   573
    pNewItem->jointype = pOldItem->jointype;
ds@1952
   574
    pNewItem->iCursor = pOldItem->iCursor;
ds@1952
   575
    pNewItem->isPopulated = pOldItem->isPopulated;
ds@1952
   576
    pTab = pNewItem->pTab = pOldItem->pTab;
ds@1952
   577
    if( pTab ){
ds@1952
   578
      pTab->nRef++;
ds@1952
   579
    }
ds@1952
   580
    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
ds@1952
   581
    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
ds@1952
   582
    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
ds@1952
   583
    pNewItem->colUsed = pOldItem->colUsed;
ds@1952
   584
  }
ds@1952
   585
  return pNew;
ds@1952
   586
}
ds@1952
   587
IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
ds@1952
   588
  IdList *pNew;
ds@1952
   589
  int i;
ds@1952
   590
  if( p==0 ) return 0;
ds@1952
   591
  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
ds@1952
   592
  if( pNew==0 ) return 0;
ds@1952
   593
  pNew->nId = pNew->nAlloc = p->nId;
ds@1952
   594
  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
ds@1952
   595
  if( pNew->a==0 ){
ds@1952
   596
    sqlite3_free(pNew);
ds@1952
   597
    return 0;
ds@1952
   598
  }
ds@1952
   599
  for(i=0; i<p->nId; i++){
ds@1952
   600
    struct IdList_item *pNewItem = &pNew->a[i];
ds@1952
   601
    struct IdList_item *pOldItem = &p->a[i];
ds@1952
   602
    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
ds@1952
   603
    pNewItem->idx = pOldItem->idx;
ds@1952
   604
  }
ds@1952
   605
  return pNew;
ds@1952
   606
}
ds@1952
   607
Select *sqlite3SelectDup(sqlite3 *db, Select *p){
ds@1952
   608
  Select *pNew;
ds@1952
   609
  if( p==0 ) return 0;
ds@1952
   610
  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
ds@1952
   611
  if( pNew==0 ) return 0;
ds@1952
   612
  pNew->isDistinct = p->isDistinct;
ds@1952
   613
  pNew->pEList = sqlite3ExprListDup(db, p->pEList);
ds@1952
   614
  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
ds@1952
   615
  pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
ds@1952
   616
  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
ds@1952
   617
  pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
ds@1952
   618
  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
ds@1952
   619
  pNew->op = p->op;
ds@1952
   620
  pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
ds@1952
   621
  pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
ds@1952
   622
  pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
ds@1952
   623
  pNew->iLimit = -1;
ds@1952
   624
  pNew->iOffset = -1;
ds@1952
   625
  pNew->isResolved = p->isResolved;
ds@1952
   626
  pNew->isAgg = p->isAgg;
ds@1952
   627
  pNew->usesEphm = 0;
ds@1952
   628
  pNew->disallowOrderBy = 0;
ds@1952
   629
  pNew->pRightmost = 0;
ds@1952
   630
  pNew->addrOpenEphm[0] = -1;
ds@1952
   631
  pNew->addrOpenEphm[1] = -1;
ds@1952
   632
  pNew->addrOpenEphm[2] = -1;
ds@1952
   633
  return pNew;
ds@1952
   634
}
ds@1952
   635
#else
ds@1952
   636
Select *sqlite3SelectDup(sqlite3 *db, Select *p){
ds@1952
   637
  assert( p==0 );
ds@1952
   638
  return 0;
ds@1952
   639
}
ds@1952
   640
#endif
ds@1952
   641
ds@1952
   642
ds@1952
   643
/*
ds@1952
   644
** Add a new element to the end of an expression list.  If pList is
ds@1952
   645
** initially NULL, then create a new expression list.
ds@1952
   646
*/
ds@1952
   647
ExprList *sqlite3ExprListAppend(
ds@1952
   648
  Parse *pParse,          /* Parsing context */
ds@1952
   649
  ExprList *pList,        /* List to which to append. Might be NULL */
ds@1952
   650
  Expr *pExpr,            /* Expression to be appended */
ds@1952
   651
  Token *pName            /* AS keyword for the expression */
ds@1952
   652
){
ds@1952
   653
  sqlite3 *db = pParse->db;
ds@1952
   654
  if( pList==0 ){
ds@1952
   655
    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
ds@1952
   656
    if( pList==0 ){
ds@1952
   657
      goto no_mem;
ds@1952
   658
    }
ds@1952
   659
    assert( pList->nAlloc==0 );
ds@1952
   660
  }
ds@1952
   661
  if( pList->nAlloc<=pList->nExpr ){
ds@1952
   662
    struct ExprList_item *a;
ds@1952
   663
    int n = pList->nAlloc*2 + 4;
ds@1952
   664
    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
ds@1952
   665
    if( a==0 ){
ds@1952
   666
      goto no_mem;
ds@1952
   667
    }
ds@1952
   668
    pList->a = a;
ds@1952
   669
    pList->nAlloc = n;
ds@1952
   670
  }
ds@1952
   671
  assert( pList->a!=0 );
ds@1952
   672
  if( pExpr || pName ){
ds@1952
   673
    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
ds@1952
   674
    memset(pItem, 0, sizeof(*pItem));
ds@1952
   675
    pItem->zName = sqlite3NameFromToken(db, pName);
ds@1952
   676
    pItem->pExpr = pExpr;
ds@1952
   677
  }
ds@1952
   678
  return pList;
ds@1952
   679
ds@1952
   680
no_mem:     
ds@1952
   681
  /* Avoid leaking memory if malloc has failed. */
ds@1952
   682
  sqlite3ExprDelete(pExpr);
ds@1952
   683
  sqlite3ExprListDelete(pList);
ds@1952
   684
  return 0;
ds@1952
   685
}
ds@1952
   686
ds@1952
   687
/*
ds@1952
   688
** If the expression list pEList contains more than iLimit elements,
ds@1952
   689
** leave an error message in pParse.
ds@1952
   690
*/
ds@1952
   691
void sqlite3ExprListCheckLength(
ds@1952
   692
  Parse *pParse,
ds@1952
   693
  ExprList *pEList,
ds@1952
   694
  int iLimit,
ds@1952
   695
  const char *zObject
ds@1952
   696
){
ds@1952
   697
  if( pEList && pEList->nExpr>iLimit ){
ds@1952
   698
    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
ds@1952
   699
  }
ds@1952
   700
}
ds@1952
   701
ds@1952
   702
ds@1952
   703
#if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
ds@1952
   704
/* The following three functions, heightOfExpr(), heightOfExprList()
ds@1952
   705
** and heightOfSelect(), are used to determine the maximum height
ds@1952
   706
** of any expression tree referenced by the structure passed as the
ds@1952
   707
** first argument.
ds@1952
   708
**
ds@1952
   709
** If this maximum height is greater than the current value pointed
ds@1952
   710
** to by pnHeight, the second parameter, then set *pnHeight to that
ds@1952
   711
** value.
ds@1952
   712
*/
ds@1952
   713
static void heightOfExpr(Expr *p, int *pnHeight){
ds@1952
   714
  if( p ){
ds@1952
   715
    if( p->nHeight>*pnHeight ){
ds@1952
   716
      *pnHeight = p->nHeight;
ds@1952
   717
    }
ds@1952
   718
  }
ds@1952
   719
}
ds@1952
   720
static void heightOfExprList(ExprList *p, int *pnHeight){
ds@1952
   721
  if( p ){
ds@1952
   722
    int i;
ds@1952
   723
    for(i=0; i<p->nExpr; i++){
ds@1952
   724
      heightOfExpr(p->a[i].pExpr, pnHeight);
ds@1952
   725
    }
ds@1952
   726
  }
ds@1952
   727
}
ds@1952
   728
static void heightOfSelect(Select *p, int *pnHeight){
ds@1952
   729
  if( p ){
ds@1952
   730
    heightOfExpr(p->pWhere, pnHeight);
ds@1952
   731
    heightOfExpr(p->pHaving, pnHeight);
ds@1952
   732
    heightOfExpr(p->pLimit, pnHeight);
ds@1952
   733
    heightOfExpr(p->pOffset, pnHeight);
ds@1952
   734
    heightOfExprList(p->pEList, pnHeight);
ds@1952
   735
    heightOfExprList(p->pGroupBy, pnHeight);
ds@1952
   736
    heightOfExprList(p->pOrderBy, pnHeight);
ds@1952
   737
    heightOfSelect(p->pPrior, pnHeight);
ds@1952
   738
  }
ds@1952
   739
}
ds@1952
   740
ds@1952
   741
/*
ds@1952
   742
** Set the Expr.nHeight variable in the structure passed as an 
ds@1952
   743
** argument. An expression with no children, Expr.pList or 
ds@1952
   744
** Expr.pSelect member has a height of 1. Any other expression
ds@1952
   745
** has a height equal to the maximum height of any other 
ds@1952
   746
** referenced Expr plus one.
ds@1952
   747
*/
ds@1952
   748
void sqlite3ExprSetHeight(Expr *p){
ds@1952
   749
  int nHeight = 0;
ds@1952
   750
  heightOfExpr(p->pLeft, &nHeight);
ds@1952
   751
  heightOfExpr(p->pRight, &nHeight);
ds@1952
   752
  heightOfExprList(p->pList, &nHeight);
ds@1952
   753
  heightOfSelect(p->pSelect, &nHeight);
ds@1952
   754
  p->nHeight = nHeight + 1;
ds@1952
   755
}
ds@1952
   756
ds@1952
   757
/*
ds@1952
   758
** Return the maximum height of any expression tree referenced
ds@1952
   759
** by the select statement passed as an argument.
ds@1952
   760
*/
ds@1952
   761
int sqlite3SelectExprHeight(Select *p){
ds@1952
   762
  int nHeight = 0;
ds@1952
   763
  heightOfSelect(p, &nHeight);
ds@1952
   764
  return nHeight;
ds@1952
   765
}
ds@1952
   766
#endif
ds@1952
   767
ds@1952
   768
/*
ds@1952
   769
** Delete an entire expression list.
ds@1952
   770
*/
ds@1952
   771
void sqlite3ExprListDelete(ExprList *pList){
ds@1952
   772
  int i;
ds@1952
   773
  struct ExprList_item *pItem;
ds@1952
   774
  if( pList==0 ) return;
ds@1952
   775
  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
ds@1952
   776
  assert( pList->nExpr<=pList->nAlloc );
ds@1952
   777
  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
ds@1952
   778
    sqlite3ExprDelete(pItem->pExpr);
ds@1952
   779
    sqlite3_free(pItem->zName);
ds@1952
   780
  }
ds@1952
   781
  sqlite3_free(pList->a);
ds@1952
   782
  sqlite3_free(pList);
ds@1952
   783
}
ds@1952
   784
ds@1952
   785
/*
ds@1952
   786
** Walk an expression tree.  Call xFunc for each node visited.
ds@1952
   787
**
ds@1952
   788
** The return value from xFunc determines whether the tree walk continues.
ds@1952
   789
** 0 means continue walking the tree.  1 means do not walk children
ds@1952
   790
** of the current node but continue with siblings.  2 means abandon
ds@1952
   791
** the tree walk completely.
ds@1952
   792
**
ds@1952
   793
** The return value from this routine is 1 to abandon the tree walk
ds@1952
   794
** and 0 to continue.
ds@1952
   795
**
ds@1952
   796
** NOTICE:  This routine does *not* descend into subqueries.
ds@1952
   797
*/
ds@1952
   798
static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
ds@1952
   799
static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
ds@1952
   800
  int rc;
ds@1952
   801
  if( pExpr==0 ) return 0;
ds@1952
   802
  rc = (*xFunc)(pArg, pExpr);
ds@1952
   803
  if( rc==0 ){
ds@1952
   804
    if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
ds@1952
   805
    if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
ds@1952
   806
    if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
ds@1952
   807
  }
ds@1952
   808
  return rc>1;
ds@1952
   809
}
ds@1952
   810
ds@1952
   811
/*
ds@1952
   812
** Call walkExprTree() for every expression in list p.
ds@1952
   813
*/
ds@1952
   814
static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
ds@1952
   815
  int i;
ds@1952
   816
  struct ExprList_item *pItem;
ds@1952
   817
  if( !p ) return 0;
ds@1952
   818
  for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
ds@1952
   819
    if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
ds@1952
   820
  }
ds@1952
   821
  return 0;
ds@1952
   822
}
ds@1952
   823
ds@1952
   824
/*
ds@1952
   825
** Call walkExprTree() for every expression in Select p, not including
ds@1952
   826
** expressions that are part of sub-selects in any FROM clause or the LIMIT
ds@1952
   827
** or OFFSET expressions..
ds@1952
   828
*/
ds@1952
   829
static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
ds@1952
   830
  walkExprList(p->pEList, xFunc, pArg);
ds@1952
   831
  walkExprTree(p->pWhere, xFunc, pArg);
ds@1952
   832
  walkExprList(p->pGroupBy, xFunc, pArg);
ds@1952
   833
  walkExprTree(p->pHaving, xFunc, pArg);
ds@1952
   834
  walkExprList(p->pOrderBy, xFunc, pArg);
ds@1952
   835
  if( p->pPrior ){
ds@1952
   836
    walkSelectExpr(p->pPrior, xFunc, pArg);
ds@1952
   837
  }
ds@1952
   838
  return 0;
ds@1952
   839
}
ds@1952
   840
ds@1952
   841
ds@1952
   842
/*
ds@1952
   843
** This routine is designed as an xFunc for walkExprTree().
ds@1952
   844
**
ds@1952
   845
** pArg is really a pointer to an integer.  If we can tell by looking
ds@1952
   846
** at pExpr that the expression that contains pExpr is not a constant
ds@1952
   847
** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
ds@1952
   848
** If pExpr does does not disqualify the expression from being a constant
ds@1952
   849
** then do nothing.
ds@1952
   850
**
ds@1952
   851
** After walking the whole tree, if no nodes are found that disqualify
ds@1952
   852
** the expression as constant, then we assume the whole expression
ds@1952
   853
** is constant.  See sqlite3ExprIsConstant() for additional information.
ds@1952
   854
*/
ds@1952
   855
static int exprNodeIsConstant(void *pArg, Expr *pExpr){
ds@1952
   856
  int *pN = (int*)pArg;
ds@1952
   857
ds@1952
   858
  /* If *pArg is 3 then any term of the expression that comes from
ds@1952
   859
  ** the ON or USING clauses of a join disqualifies the expression
ds@1952
   860
  ** from being considered constant. */
ds@1952
   861
  if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
ds@1952
   862
    *pN = 0;
ds@1952
   863
    return 2;
ds@1952
   864
  }
ds@1952
   865
ds@1952
   866
  switch( pExpr->op ){
ds@1952
   867
    /* Consider functions to be constant if all their arguments are constant
ds@1952
   868
    ** and *pArg==2 */
ds@1952
   869
    case TK_FUNCTION:
ds@1952
   870
      if( (*pN)==2 ) return 0;
ds@1952
   871
      /* Fall through */
ds@1952
   872
    case TK_ID:
ds@1952
   873
    case TK_COLUMN:
ds@1952
   874
    case TK_DOT:
ds@1952
   875
    case TK_AGG_FUNCTION:
ds@1952
   876
    case TK_AGG_COLUMN:
ds@1952
   877
#ifndef SQLITE_OMIT_SUBQUERY
ds@1952
   878
    case TK_SELECT:
ds@1952
   879
    case TK_EXISTS:
ds@1952
   880
#endif
ds@1952
   881
      *pN = 0;
ds@1952
   882
      return 2;
ds@1952
   883
    case TK_IN:
ds@1952
   884
      if( pExpr->pSelect ){
ds@1952
   885
        *pN = 0;
ds@1952
   886
        return 2;
ds@1952
   887
      }
ds@1952
   888
    default:
ds@1952
   889
      return 0;
ds@1952
   890
  }
ds@1952
   891
}
ds@1952
   892
ds@1952
   893
/*
ds@1952
   894
** Walk an expression tree.  Return 1 if the expression is constant
ds@1952
   895
** and 0 if it involves variables or function calls.
ds@1952
   896
**
ds@1952
   897
** For the purposes of this function, a double-quoted string (ex: "abc")
ds@1952
   898
** is considered a variable but a single-quoted string (ex: 'abc') is
ds@1952
   899
** a constant.
ds@1952
   900
*/
ds@1952
   901
int sqlite3ExprIsConstant(Expr *p){
ds@1952
   902
  int isConst = 1;
ds@1952
   903
  walkExprTree(p, exprNodeIsConstant, &isConst);
ds@1952
   904
  return isConst;
ds@1952
   905
}
ds@1952
   906
ds@1952
   907
/*
ds@1952
   908
** Walk an expression tree.  Return 1 if the expression is constant
ds@1952
   909
** that does no originate from the ON or USING clauses of a join.
ds@1952
   910
** Return 0 if it involves variables or function calls or terms from
ds@1952
   911
** an ON or USING clause.
ds@1952
   912
*/
ds@1952
   913
int sqlite3ExprIsConstantNotJoin(Expr *p){
ds@1952
   914
  int isConst = 3;
ds@1952
   915
  walkExprTree(p, exprNodeIsConstant, &isConst);
ds@1952
   916
  return isConst!=0;
ds@1952
   917
}
ds@1952
   918
ds@1952
   919
/*
ds@1952
   920
** Walk an expression tree.  Return 1 if the expression is constant
ds@1952
   921
** or a function call with constant arguments.  Return and 0 if there
ds@1952
   922
** are any variables.
ds@1952
   923
**
ds@1952
   924
** For the purposes of this function, a double-quoted string (ex: "abc")
ds@1952
   925
** is considered a variable but a single-quoted string (ex: 'abc') is
ds@1952
   926
** a constant.
ds@1952
   927
*/
ds@1952
   928
int sqlite3ExprIsConstantOrFunction(Expr *p){
ds@1952
   929
  int isConst = 2;
ds@1952
   930
  walkExprTree(p, exprNodeIsConstant, &isConst);
ds@1952
   931
  return isConst!=0;
ds@1952
   932
}
ds@1952
   933
ds@1952
   934
/*
ds@1952
   935
** If the expression p codes a constant integer that is small enough
ds@1952
   936
** to fit in a 32-bit integer, return 1 and put the value of the integer
ds@1952
   937
** in *pValue.  If the expression is not an integer or if it is too big
ds@1952
   938
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
ds@1952
   939
*/
ds@1952
   940
int sqlite3ExprIsInteger(Expr *p, int *pValue){
ds@1952
   941
  switch( p->op ){
ds@1952
   942
    case TK_INTEGER: {
ds@1952
   943
      if( sqlite3GetInt32((char*)p->token.z, pValue) ){
ds@1952
   944
        return 1;
ds@1952
   945
      }
ds@1952
   946
      break;
ds@1952
   947
    }
ds@1952
   948
    case TK_UPLUS: {
ds@1952
   949
      return sqlite3ExprIsInteger(p->pLeft, pValue);
ds@1952
   950
    }
ds@1952
   951
    case TK_UMINUS: {
ds@1952
   952
      int v;
ds@1952
   953
      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
ds@1952
   954
        *pValue = -v;
ds@1952
   955
        return 1;
ds@1952
   956
      }
ds@1952
   957
      break;
ds@1952
   958
    }
ds@1952
   959
    default: break;
ds@1952
   960
  }
ds@1952
   961
  return 0;
ds@1952
   962
}
ds@1952
   963
ds@1952
   964
/*
ds@1952
   965
** Return TRUE if the given string is a row-id column name.
ds@1952
   966
*/
ds@1952
   967
int sqlite3IsRowid(const char *z){
ds@1952
   968
  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
ds@1952
   969
  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
ds@1952
   970
  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
ds@1952
   971
  return 0;
ds@1952
   972
}
ds@1952
   973
ds@1952
   974
/*
ds@1952
   975
** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
ds@1952
   976
** that name in the set of source tables in pSrcList and make the pExpr 
ds@1952
   977
** expression node refer back to that source column.  The following changes
ds@1952
   978
** are made to pExpr:
ds@1952
   979
**
ds@1952
   980
**    pExpr->iDb           Set the index in db->aDb[] of the database holding
ds@1952
   981
**                         the table.
ds@1952
   982
**    pExpr->iTable        Set to the cursor number for the table obtained
ds@1952
   983
**                         from pSrcList.
ds@1952
   984
**    pExpr->iColumn       Set to the column number within the table.
ds@1952
   985
**    pExpr->op            Set to TK_COLUMN.
ds@1952
   986
**    pExpr->pLeft         Any expression this points to is deleted
ds@1952
   987
**    pExpr->pRight        Any expression this points to is deleted.
ds@1952
   988
**
ds@1952
   989
** The pDbToken is the name of the database (the "X").  This value may be
ds@1952
   990
** NULL meaning that name is of the form Y.Z or Z.  Any available database
ds@1952
   991
** can be used.  The pTableToken is the name of the table (the "Y").  This
ds@1952
   992
** value can be NULL if pDbToken is also NULL.  If pTableToken is NULL it
ds@1952
   993
** means that the form of the name is Z and that columns from any table
ds@1952
   994
** can be used.
ds@1952
   995
**
ds@1952
   996
** If the name cannot be resolved unambiguously, leave an error message
ds@1952
   997
** in pParse and return non-zero.  Return zero on success.
ds@1952
   998
*/
ds@1952
   999
static int lookupName(
ds@1952
  1000
  Parse *pParse,       /* The parsing context */
ds@1952
  1001
  Token *pDbToken,     /* Name of the database containing table, or NULL */
ds@1952
  1002
  Token *pTableToken,  /* Name of table containing column, or NULL */
ds@1952
  1003
  Token *pColumnToken, /* Name of the column. */
ds@1952
  1004
  NameContext *pNC,    /* The name context used to resolve the name */
ds@1952
  1005
  Expr *pExpr          /* Make this EXPR node point to the selected column */
ds@1952
  1006
){
ds@1952
  1007
  char *zDb = 0;       /* Name of the database.  The "X" in X.Y.Z */
ds@1952
  1008
  char *zTab = 0;      /* Name of the table.  The "Y" in X.Y.Z or Y.Z */
ds@1952
  1009
  char *zCol = 0;      /* Name of the column.  The "Z" */
ds@1952
  1010
  int i, j;            /* Loop counters */
ds@1952
  1011
  int cnt = 0;         /* Number of matching column names */
ds@1952
  1012
  int cntTab = 0;      /* Number of matching table names */
ds@1952
  1013
  sqlite3 *db = pParse->db;  /* The database */
ds@1952
  1014
  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
ds@1952
  1015
  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
ds@1952
  1016
  NameContext *pTopNC = pNC;        /* First namecontext in the list */
ds@1952
  1017
  Schema *pSchema = 0;              /* Schema of the expression */
ds@1952
  1018
ds@1952
  1019
  assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
ds@1952
  1020
  zDb = sqlite3NameFromToken(db, pDbToken);
ds@1952
  1021
  zTab = sqlite3NameFromToken(db, pTableToken);
ds@1952
  1022
  zCol = sqlite3NameFromToken(db, pColumnToken);
ds@1952
  1023
  if( db->mallocFailed ){
ds@1952
  1024
    goto lookupname_end;
ds@1952
  1025
  }
ds@1952
  1026
ds@1952
  1027
  pExpr->iTable = -1;
ds@1952
  1028
  while( pNC && cnt==0 ){
ds@1952
  1029
    ExprList *pEList;
ds@1952
  1030
    SrcList *pSrcList = pNC->pSrcList;
ds@1952
  1031
ds@1952
  1032
    if( pSrcList ){
ds@1952
  1033
      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
ds@1952
  1034
        Table *pTab;
ds@1952
  1035
        int iDb;
ds@1952
  1036
        Column *pCol;
ds@1952
  1037
  
ds@1952
  1038
        pTab = pItem->pTab;
ds@1952
  1039
        assert( pTab!=0 );
ds@1952
  1040
        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
ds@1952
  1041
        assert( pTab->nCol>0 );
ds@1952
  1042
        if( zTab ){
ds@1952
  1043
          if( pItem->zAlias ){
ds@1952
  1044
            char *zTabName = pItem->zAlias;
ds@1952
  1045
            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
ds@1952
  1046
          }else{
ds@1952
  1047
            char *zTabName = pTab->zName;
ds@1952
  1048
            if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
ds@1952
  1049
            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
ds@1952
  1050
              continue;
ds@1952
  1051
            }
ds@1952
  1052
          }
ds@1952
  1053
        }
ds@1952
  1054
        if( 0==(cntTab++) ){
ds@1952
  1055
          pExpr->iTable = pItem->iCursor;
ds@1952
  1056
          pSchema = pTab->pSchema;
ds@1952
  1057
          pMatch = pItem;
ds@1952
  1058
        }
ds@1952
  1059
        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
ds@1952
  1060
          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
ds@1952
  1061
            const char *zColl = pTab->aCol[j].zColl;
ds@1952
  1062
            IdList *pUsing;
ds@1952
  1063
            cnt++;
ds@1952
  1064
            pExpr->iTable = pItem->iCursor;
ds@1952
  1065
            pMatch = pItem;
ds@1952
  1066
            pSchema = pTab->pSchema;
ds@1952
  1067
            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
ds@1952
  1068
            pExpr->iColumn = j==pTab->iPKey ? -1 : j;
ds@1952
  1069
            pExpr->affinity = pTab->aCol[j].affinity;
ds@1952
  1070
            if( (pExpr->flags & EP_ExpCollate)==0 ){
ds@1952
  1071
              pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
ds@1952
  1072
            }
ds@1952
  1073
            if( i<pSrcList->nSrc-1 ){
ds@1952
  1074
              if( pItem[1].jointype & JT_NATURAL ){
ds@1952
  1075
                /* If this match occurred in the left table of a natural join,
ds@1952
  1076
                ** then skip the right table to avoid a duplicate match */
ds@1952
  1077
                pItem++;
ds@1952
  1078
                i++;
ds@1952
  1079
              }else if( (pUsing = pItem[1].pUsing)!=0 ){
ds@1952
  1080
                /* If this match occurs on a column that is in the USING clause
ds@1952
  1081
                ** of a join, skip the search of the right table of the join
ds@1952
  1082
                ** to avoid a duplicate match there. */
ds@1952
  1083
                int k;
ds@1952
  1084
                for(k=0; k<pUsing->nId; k++){
ds@1952
  1085
                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
ds@1952
  1086
                    pItem++;
ds@1952
  1087
                    i++;
ds@1952
  1088
                    break;
ds@1952
  1089
                  }
ds@1952
  1090
                }
ds@1952
  1091
              }
ds@1952
  1092
            }
ds@1952
  1093
            break;
ds@1952
  1094
          }
ds@1952
  1095
        }
ds@1952
  1096
      }
ds@1952
  1097
    }
ds@1952
  1098
ds@1952
  1099
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
  1100
    /* If we have not already resolved the name, then maybe 
ds@1952
  1101
    ** it is a new.* or old.* trigger argument reference
ds@1952
  1102
    */
ds@1952
  1103
    if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
ds@1952
  1104
      TriggerStack *pTriggerStack = pParse->trigStack;
ds@1952
  1105
      Table *pTab = 0;
ds@1952
  1106
      if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
ds@1952
  1107
        pExpr->iTable = pTriggerStack->newIdx;
ds@1952
  1108
        assert( pTriggerStack->pTab );
ds@1952
  1109
        pTab = pTriggerStack->pTab;
ds@1952
  1110
      }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
ds@1952
  1111
        pExpr->iTable = pTriggerStack->oldIdx;
ds@1952
  1112
        assert( pTriggerStack->pTab );
ds@1952
  1113
        pTab = pTriggerStack->pTab;
ds@1952
  1114
      }
ds@1952
  1115
ds@1952
  1116
      if( pTab ){ 
ds@1952
  1117
        int iCol;
ds@1952
  1118
        Column *pCol = pTab->aCol;
ds@1952
  1119
ds@1952
  1120
        pSchema = pTab->pSchema;
ds@1952
  1121
        cntTab++;
ds@1952
  1122
        for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
ds@1952
  1123
          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
ds@1952
  1124
            const char *zColl = pTab->aCol[iCol].zColl;
ds@1952
  1125
            cnt++;
ds@1952
  1126
            pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
ds@1952
  1127
            pExpr->affinity = pTab->aCol[iCol].affinity;
ds@1952
  1128
            if( (pExpr->flags & EP_ExpCollate)==0 ){
ds@1952
  1129
              pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
ds@1952
  1130
            }
ds@1952
  1131
            pExpr->pTab = pTab;
ds@1952
  1132
            break;
ds@1952
  1133
          }
ds@1952
  1134
        }
ds@1952
  1135
      }
ds@1952
  1136
    }
ds@1952
  1137
#endif /* !defined(SQLITE_OMIT_TRIGGER) */
ds@1952
  1138
ds@1952
  1139
    /*
ds@1952
  1140
    ** Perhaps the name is a reference to the ROWID
ds@1952
  1141
    */
ds@1952
  1142
    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
ds@1952
  1143
      cnt = 1;
ds@1952
  1144
      pExpr->iColumn = -1;
ds@1952
  1145
      pExpr->affinity = SQLITE_AFF_INTEGER;
ds@1952
  1146
    }
ds@1952
  1147
ds@1952
  1148
    /*
ds@1952
  1149
    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
ds@1952
  1150
    ** might refer to an result-set alias.  This happens, for example, when
ds@1952
  1151
    ** we are resolving names in the WHERE clause of the following command:
ds@1952
  1152
    **
ds@1952
  1153
    **     SELECT a+b AS x FROM table WHERE x<10;
ds@1952
  1154
    **
ds@1952
  1155
    ** In cases like this, replace pExpr with a copy of the expression that
ds@1952
  1156
    ** forms the result set entry ("a+b" in the example) and return immediately.
ds@1952
  1157
    ** Note that the expression in the result set should have already been
ds@1952
  1158
    ** resolved by the time the WHERE clause is resolved.
ds@1952
  1159
    */
ds@1952
  1160
    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
ds@1952
  1161
      for(j=0; j<pEList->nExpr; j++){
ds@1952
  1162
        char *zAs = pEList->a[j].zName;
ds@1952
  1163
        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
ds@1952
  1164
          Expr *pDup, *pOrig;
ds@1952
  1165
          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
ds@1952
  1166
          assert( pExpr->pList==0 );
ds@1952
  1167
          assert( pExpr->pSelect==0 );
ds@1952
  1168
          pOrig = pEList->a[j].pExpr;
ds@1952
  1169
          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
ds@1952
  1170
            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
ds@1952
  1171
            sqlite3_free(zCol);
ds@1952
  1172
            return 2;
ds@1952
  1173
          }
ds@1952
  1174
          pDup = sqlite3ExprDup(db, pOrig);
ds@1952
  1175
          if( pExpr->flags & EP_ExpCollate ){
ds@1952
  1176
            pDup->pColl = pExpr->pColl;
ds@1952
  1177
            pDup->flags |= EP_ExpCollate;
ds@1952
  1178
          }
ds@1952
  1179
          if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
ds@1952
  1180
          if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
ds@1952
  1181
          memcpy(pExpr, pDup, sizeof(*pExpr));
ds@1952
  1182
          sqlite3_free(pDup);
ds@1952
  1183
          cnt = 1;
ds@1952
  1184
          pMatch = 0;
ds@1952
  1185
          assert( zTab==0 && zDb==0 );
ds@1952
  1186
          goto lookupname_end_2;
ds@1952
  1187
        }
ds@1952
  1188
      } 
ds@1952
  1189
    }
ds@1952
  1190
ds@1952
  1191
    /* Advance to the next name context.  The loop will exit when either
ds@1952
  1192
    ** we have a match (cnt>0) or when we run out of name contexts.
ds@1952
  1193
    */
ds@1952
  1194
    if( cnt==0 ){
ds@1952
  1195
      pNC = pNC->pNext;
ds@1952
  1196
    }
ds@1952
  1197
  }
ds@1952
  1198
ds@1952
  1199
  /*
ds@1952
  1200
  ** If X and Y are NULL (in other words if only the column name Z is
ds@1952
  1201
  ** supplied) and the value of Z is enclosed in double-quotes, then
ds@1952
  1202
  ** Z is a string literal if it doesn't match any column names.  In that
ds@1952
  1203
  ** case, we need to return right away and not make any changes to
ds@1952
  1204
  ** pExpr.
ds@1952
  1205
  **
ds@1952
  1206
  ** Because no reference was made to outer contexts, the pNC->nRef
ds@1952
  1207
  ** fields are not changed in any context.
ds@1952
  1208
  */
ds@1952
  1209
  if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
ds@1952
  1210
    sqlite3_free(zCol);
ds@1952
  1211
    return 0;
ds@1952
  1212
  }
ds@1952
  1213
ds@1952
  1214
  /*
ds@1952
  1215
  ** cnt==0 means there was not match.  cnt>1 means there were two or
ds@1952
  1216
  ** more matches.  Either way, we have an error.
ds@1952
  1217
  */
ds@1952
  1218
  if( cnt!=1 ){
ds@1952
  1219
    char *z = 0;
ds@1952
  1220
    char *zErr;
ds@1952
  1221
    zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
ds@1952
  1222
    if( zDb ){
ds@1952
  1223
      sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
ds@1952
  1224
    }else if( zTab ){
ds@1952
  1225
      sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
ds@1952
  1226
    }else{
ds@1952
  1227
      z = sqlite3StrDup(zCol);
ds@1952
  1228
    }
ds@1952
  1229
    if( z ){
ds@1952
  1230
      sqlite3ErrorMsg(pParse, zErr, z);
ds@1952
  1231
      sqlite3_free(z);
ds@1952
  1232
      pTopNC->nErr++;
ds@1952
  1233
    }else{
ds@1952
  1234
      db->mallocFailed = 1;
ds@1952
  1235
    }
ds@1952
  1236
  }
ds@1952
  1237
ds@1952
  1238
  /* If a column from a table in pSrcList is referenced, then record
ds@1952
  1239
  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
ds@1952
  1240
  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
ds@1952
  1241
  ** column number is greater than the number of bits in the bitmask
ds@1952
  1242
  ** then set the high-order bit of the bitmask.
ds@1952
  1243
  */
ds@1952
  1244
  if( pExpr->iColumn>=0 && pMatch!=0 ){
ds@1952
  1245
    int n = pExpr->iColumn;
ds@1952
  1246
    if( n>=sizeof(Bitmask)*8 ){
ds@1952
  1247
      n = sizeof(Bitmask)*8-1;
ds@1952
  1248
    }
ds@1952
  1249
    assert( pMatch->iCursor==pExpr->iTable );
ds@1952
  1250
    pMatch->colUsed |= ((Bitmask)1)<<n;
ds@1952
  1251
  }
ds@1952
  1252
ds@1952
  1253
lookupname_end:
ds@1952
  1254
  /* Clean up and return
ds@1952
  1255
  */
ds@1952
  1256
  sqlite3_free(zDb);
ds@1952
  1257
  sqlite3_free(zTab);
ds@1952
  1258
  sqlite3ExprDelete(pExpr->pLeft);
ds@1952
  1259
  pExpr->pLeft = 0;
ds@1952
  1260
  sqlite3ExprDelete(pExpr->pRight);
ds@1952
  1261
  pExpr->pRight = 0;
ds@1952
  1262
  pExpr->op = TK_COLUMN;
ds@1952
  1263
lookupname_end_2:
ds@1952
  1264
  sqlite3_free(zCol);
ds@1952
  1265
  if( cnt==1 ){
ds@1952
  1266
    assert( pNC!=0 );
ds@1952
  1267
    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
ds@1952
  1268
    if( pMatch && !pMatch->pSelect ){
ds@1952
  1269
      pExpr->pTab = pMatch->pTab;
ds@1952
  1270
    }
ds@1952
  1271
    /* Increment the nRef value on all name contexts from TopNC up to
ds@1952
  1272
    ** the point where the name matched. */
ds@1952
  1273
    for(;;){
ds@1952
  1274
      assert( pTopNC!=0 );
ds@1952
  1275
      pTopNC->nRef++;
ds@1952
  1276
      if( pTopNC==pNC ) break;
ds@1952
  1277
      pTopNC = pTopNC->pNext;
ds@1952
  1278
    }
ds@1952
  1279
    return 0;
ds@1952
  1280
  } else {
ds@1952
  1281
    return 1;
ds@1952
  1282
  }
ds@1952
  1283
}
ds@1952
  1284
ds@1952
  1285
/*
ds@1952
  1286
** This routine is designed as an xFunc for walkExprTree().
ds@1952
  1287
**
ds@1952
  1288
** Resolve symbolic names into TK_COLUMN operators for the current
ds@1952
  1289
** node in the expression tree.  Return 0 to continue the search down
ds@1952
  1290
** the tree or 2 to abort the tree walk.
ds@1952
  1291
**
ds@1952
  1292
** This routine also does error checking and name resolution for
ds@1952
  1293
** function names.  The operator for aggregate functions is changed
ds@1952
  1294
** to TK_AGG_FUNCTION.
ds@1952
  1295
*/
ds@1952
  1296
static int nameResolverStep(void *pArg, Expr *pExpr){
ds@1952
  1297
  NameContext *pNC = (NameContext*)pArg;
ds@1952
  1298
  Parse *pParse;
ds@1952
  1299
ds@1952
  1300
  if( pExpr==0 ) return 1;
ds@1952
  1301
  assert( pNC!=0 );
ds@1952
  1302
  pParse = pNC->pParse;
ds@1952
  1303
ds@1952
  1304
  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
ds@1952
  1305
  ExprSetProperty(pExpr, EP_Resolved);
ds@1952
  1306
#ifndef NDEBUG
ds@1952
  1307
  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
ds@1952
  1308
    SrcList *pSrcList = pNC->pSrcList;
ds@1952
  1309
    int i;
ds@1952
  1310
    for(i=0; i<pNC->pSrcList->nSrc; i++){
ds@1952
  1311
      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
ds@1952
  1312
    }
ds@1952
  1313
  }
ds@1952
  1314
#endif
ds@1952
  1315
  switch( pExpr->op ){
ds@1952
  1316
    /* Double-quoted strings (ex: "abc") are used as identifiers if
ds@1952
  1317
    ** possible.  Otherwise they remain as strings.  Single-quoted
ds@1952
  1318
    ** strings (ex: 'abc') are always string literals.
ds@1952
  1319
    */
ds@1952
  1320
    case TK_STRING: {
ds@1952
  1321
      if( pExpr->token.z[0]=='\'' ) break;
ds@1952
  1322
      /* Fall thru into the TK_ID case if this is a double-quoted string */
ds@1952
  1323
    }
ds@1952
  1324
    /* A lone identifier is the name of a column.
ds@1952
  1325
    */
ds@1952
  1326
    case TK_ID: {
ds@1952
  1327
      lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
ds@1952
  1328
      return 1;
ds@1952
  1329
    }
ds@1952
  1330
  
ds@1952
  1331
    /* A table name and column name:     ID.ID
ds@1952
  1332
    ** Or a database, table and column:  ID.ID.ID
ds@1952
  1333
    */
ds@1952
  1334
    case TK_DOT: {
ds@1952
  1335
      Token *pColumn;
ds@1952
  1336
      Token *pTable;
ds@1952
  1337
      Token *pDb;
ds@1952
  1338
      Expr *pRight;
ds@1952
  1339
ds@1952
  1340
      /* if( pSrcList==0 ) break; */
ds@1952
  1341
      pRight = pExpr->pRight;
ds@1952
  1342
      if( pRight->op==TK_ID ){
ds@1952
  1343
        pDb = 0;
ds@1952
  1344
        pTable = &pExpr->pLeft->token;
ds@1952
  1345
        pColumn = &pRight->token;
ds@1952
  1346
      }else{
ds@1952
  1347
        assert( pRight->op==TK_DOT );
ds@1952
  1348
        pDb = &pExpr->pLeft->token;
ds@1952
  1349
        pTable = &pRight->pLeft->token;
ds@1952
  1350
        pColumn = &pRight->pRight->token;
ds@1952
  1351
      }
ds@1952
  1352
      lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
ds@1952
  1353
      return 1;
ds@1952
  1354
    }
ds@1952
  1355
ds@1952
  1356
    /* Resolve function names
ds@1952
  1357
    */
ds@1952
  1358
    case TK_CONST_FUNC:
ds@1952
  1359
    case TK_FUNCTION: {
ds@1952
  1360
      ExprList *pList = pExpr->pList;    /* The argument list */
ds@1952
  1361
      int n = pList ? pList->nExpr : 0;  /* Number of arguments */
ds@1952
  1362
      int no_such_func = 0;       /* True if no such function exists */
ds@1952
  1363
      int wrong_num_args = 0;     /* True if wrong number of arguments */
ds@1952
  1364
      int is_agg = 0;             /* True if is an aggregate function */
ds@1952
  1365
      int i;
ds@1952
  1366
      int auth;                   /* Authorization to use the function */
ds@1952
  1367
      int nId;                    /* Number of characters in function name */
ds@1952
  1368
      const char *zId;            /* The function name. */
ds@1952
  1369
      FuncDef *pDef;              /* Information about the function */
ds@1952
  1370
      int enc = ENC(pParse->db);  /* The database encoding */
ds@1952
  1371
ds@1952
  1372
      zId = (char*)pExpr->token.z;
ds@1952
  1373
      nId = pExpr->token.n;
ds@1952
  1374
      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
ds@1952
  1375
      if( pDef==0 ){
ds@1952
  1376
        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
ds@1952
  1377
        if( pDef==0 ){
ds@1952
  1378
          no_such_func = 1;
ds@1952
  1379
        }else{
ds@1952
  1380
          wrong_num_args = 1;
ds@1952
  1381
        }
ds@1952
  1382
      }else{
ds@1952
  1383
        is_agg = pDef->xFunc==0;
ds@1952
  1384
      }
ds@1952
  1385
#ifndef SQLITE_OMIT_AUTHORIZATION
ds@1952
  1386
      if( pDef ){
ds@1952
  1387
        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
ds@1952
  1388
        if( auth!=SQLITE_OK ){
ds@1952
  1389
          if( auth==SQLITE_DENY ){
ds@1952
  1390
            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
ds@1952
  1391
                                    pDef->zName);
ds@1952
  1392
            pNC->nErr++;
ds@1952
  1393
          }
ds@1952
  1394
          pExpr->op = TK_NULL;
ds@1952
  1395
          return 1;
ds@1952
  1396
        }
ds@1952
  1397
      }
ds@1952
  1398
#endif
ds@1952
  1399
      if( is_agg && !pNC->allowAgg ){
ds@1952
  1400
        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
ds@1952
  1401
        pNC->nErr++;
ds@1952
  1402
        is_agg = 0;
ds@1952
  1403
      }else if( no_such_func ){
ds@1952
  1404
        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
ds@1952
  1405
        pNC->nErr++;
ds@1952
  1406
      }else if( wrong_num_args ){
ds@1952
  1407
        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
ds@1952
  1408
             nId, zId);
ds@1952
  1409
        pNC->nErr++;
ds@1952
  1410
      }
ds@1952
  1411
      if( is_agg ){
ds@1952
  1412
        pExpr->op = TK_AGG_FUNCTION;
ds@1952
  1413
        pNC->hasAgg = 1;
ds@1952
  1414
      }
ds@1952
  1415
      if( is_agg ) pNC->allowAgg = 0;
ds@1952
  1416
      for(i=0; pNC->nErr==0 && i<n; i++){
ds@1952
  1417
        walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
ds@1952
  1418
      }
ds@1952
  1419
      if( is_agg ) pNC->allowAgg = 1;
ds@1952
  1420
      /* FIX ME:  Compute pExpr->affinity based on the expected return
ds@1952
  1421
      ** type of the function 
ds@1952
  1422
      */
ds@1952
  1423
      return is_agg;
ds@1952
  1424
    }
ds@1952
  1425
#ifndef SQLITE_OMIT_SUBQUERY
ds@1952
  1426
    case TK_SELECT:
ds@1952
  1427
    case TK_EXISTS:
ds@1952
  1428
#endif
ds@1952
  1429
    case TK_IN: {
ds@1952
  1430
      if( pExpr->pSelect ){
ds@1952
  1431
        int nRef = pNC->nRef;
ds@1952
  1432
#ifndef SQLITE_OMIT_CHECK
ds@1952
  1433
        if( pNC->isCheck ){
ds@1952
  1434
          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
ds@1952
  1435
        }
ds@1952
  1436
#endif
ds@1952
  1437
        sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
ds@1952
  1438
        assert( pNC->nRef>=nRef );
ds@1952
  1439
        if( nRef!=pNC->nRef ){
ds@1952
  1440
          ExprSetProperty(pExpr, EP_VarSelect);
ds@1952
  1441
        }
ds@1952
  1442
      }
ds@1952
  1443
      break;
ds@1952
  1444
    }
ds@1952
  1445
#ifndef SQLITE_OMIT_CHECK
ds@1952
  1446
    case TK_VARIABLE: {
ds@1952
  1447
      if( pNC->isCheck ){
ds@1952
  1448
        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
ds@1952
  1449
      }
ds@1952
  1450
      break;
ds@1952
  1451
    }
ds@1952
  1452
#endif
ds@1952
  1453
  }
ds@1952
  1454
  return 0;
ds@1952
  1455
}
ds@1952
  1456
ds@1952
  1457
/*
ds@1952
  1458
** This routine walks an expression tree and resolves references to
ds@1952
  1459
** table columns.  Nodes of the form ID.ID or ID resolve into an
ds@1952
  1460
** index to the table in the table list and a column offset.  The 
ds@1952
  1461
** Expr.opcode for such nodes is changed to TK_COLUMN.  The Expr.iTable
ds@1952
  1462
** value is changed to the index of the referenced table in pTabList
ds@1952
  1463
** plus the "base" value.  The base value will ultimately become the
ds@1952
  1464
** VDBE cursor number for a cursor that is pointing into the referenced
ds@1952
  1465
** table.  The Expr.iColumn value is changed to the index of the column 
ds@1952
  1466
** of the referenced table.  The Expr.iColumn value for the special
ds@1952
  1467
** ROWID column is -1.  Any INTEGER PRIMARY KEY column is tried as an
ds@1952
  1468
** alias for ROWID.
ds@1952
  1469
**
ds@1952
  1470
** Also resolve function names and check the functions for proper
ds@1952
  1471
** usage.  Make sure all function names are recognized and all functions
ds@1952
  1472
** have the correct number of arguments.  Leave an error message
ds@1952
  1473
** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
ds@1952
  1474
**
ds@1952
  1475
** If the expression contains aggregate functions then set the EP_Agg
ds@1952
  1476
** property on the expression.
ds@1952
  1477
*/
ds@1952
  1478
int sqlite3ExprResolveNames( 
ds@1952
  1479
  NameContext *pNC,       /* Namespace to resolve expressions in. */
ds@1952
  1480
  Expr *pExpr             /* The expression to be analyzed. */
ds@1952
  1481
){
ds@1952
  1482
  int savedHasAgg;
ds@1952
  1483
  if( pExpr==0 ) return 0;
ds@1952
  1484
#if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
ds@1952
  1485
  if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
ds@1952
  1486
    sqlite3ErrorMsg(pNC->pParse, 
ds@1952
  1487
       "Expression tree is too large (maximum depth %d)",
ds@1952
  1488
       SQLITE_MAX_EXPR_DEPTH
ds@1952
  1489
    );
ds@1952
  1490
    return 1;
ds@1952
  1491
  }
ds@1952
  1492
  pNC->pParse->nHeight += pExpr->nHeight;
ds@1952
  1493
#endif
ds@1952
  1494
  savedHasAgg = pNC->hasAgg;
ds@1952
  1495
  pNC->hasAgg = 0;
ds@1952
  1496
  walkExprTree(pExpr, nameResolverStep, pNC);
ds@1952
  1497
#if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0
ds@1952
  1498
  pNC->pParse->nHeight -= pExpr->nHeight;
ds@1952
  1499
#endif
ds@1952
  1500
  if( pNC->nErr>0 ){
ds@1952
  1501
    ExprSetProperty(pExpr, EP_Error);
ds@1952
  1502
  }
ds@1952
  1503
  if( pNC->hasAgg ){
ds@1952
  1504
    ExprSetProperty(pExpr, EP_Agg);
ds@1952
  1505
  }else if( savedHasAgg ){
ds@1952
  1506
    pNC->hasAgg = 1;
ds@1952
  1507
  }
ds@1952
  1508
  return ExprHasProperty(pExpr, EP_Error);
ds@1952
  1509
}
ds@1952
  1510
ds@1952
  1511
/*
ds@1952
  1512
** A pointer instance of this structure is used to pass information
ds@1952
  1513
** through walkExprTree into codeSubqueryStep().
ds@1952
  1514
*/
ds@1952
  1515
typedef struct QueryCoder QueryCoder;
ds@1952
  1516
struct QueryCoder {
ds@1952
  1517
  Parse *pParse;       /* The parsing context */
ds@1952
  1518
  NameContext *pNC;    /* Namespace of first enclosing query */
ds@1952
  1519
};
ds@1952
  1520
ds@1952
  1521
ds@1952
  1522
/*
ds@1952
  1523
** Generate code for scalar subqueries used as an expression
ds@1952
  1524
** and IN operators.  Examples:
ds@1952
  1525
**
ds@1952
  1526
**     (SELECT a FROM b)          -- subquery
ds@1952
  1527
**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
ds@1952
  1528
**     x IN (4,5,11)              -- IN operator with list on right-hand side
ds@1952
  1529
**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
ds@1952
  1530
**
ds@1952
  1531
** The pExpr parameter describes the expression that contains the IN
ds@1952
  1532
** operator or subquery.
ds@1952
  1533
*/
ds@1952
  1534
#ifndef SQLITE_OMIT_SUBQUERY
ds@1952
  1535
void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
ds@1952
  1536
  int testAddr = 0;                       /* One-time test address */
ds@1952
  1537
  Vdbe *v = sqlite3GetVdbe(pParse);
ds@1952
  1538
  if( v==0 ) return;
ds@1952
  1539
ds@1952
  1540
ds@1952
  1541
  /* This code must be run in its entirety every time it is encountered
ds@1952
  1542
  ** if any of the following is true:
ds@1952
  1543
  **
ds@1952
  1544
  **    *  The right-hand side is a correlated subquery
ds@1952
  1545
  **    *  The right-hand side is an expression list containing variables
ds@1952
  1546
  **    *  We are inside a trigger
ds@1952
  1547
  **
ds@1952
  1548
  ** If all of the above are false, then we can run this code just once
ds@1952
  1549
  ** save the results, and reuse the same result on subsequent invocations.
ds@1952
  1550
  */
ds@1952
  1551
  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
ds@1952
  1552
    int mem = pParse->nMem++;
ds@1952
  1553
    sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
ds@1952
  1554
    testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
ds@1952
  1555
    assert( testAddr>0 || pParse->db->mallocFailed );
ds@1952
  1556
    sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
ds@1952
  1557
  }
ds@1952
  1558
ds@1952
  1559
  switch( pExpr->op ){
ds@1952
  1560
    case TK_IN: {
ds@1952
  1561
      char affinity;
ds@1952
  1562
      KeyInfo keyInfo;
ds@1952
  1563
      int addr;        /* Address of OP_OpenEphemeral instruction */
ds@1952
  1564
ds@1952
  1565
      affinity = sqlite3ExprAffinity(pExpr->pLeft);
ds@1952
  1566
ds@1952
  1567
      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
ds@1952
  1568
      ** expression it is handled the same way. A virtual table is 
ds@1952
  1569
      ** filled with single-field index keys representing the results
ds@1952
  1570
      ** from the SELECT or the <exprlist>.
ds@1952
  1571
      **
ds@1952
  1572
      ** If the 'x' expression is a column value, or the SELECT...
ds@1952
  1573
      ** statement returns a column value, then the affinity of that
ds@1952
  1574
      ** column is used to build the index keys. If both 'x' and the
ds@1952
  1575
      ** SELECT... statement are columns, then numeric affinity is used
ds@1952
  1576
      ** if either column has NUMERIC or INTEGER affinity. If neither
ds@1952
  1577
      ** 'x' nor the SELECT... statement are columns, then numeric affinity
ds@1952
  1578
      ** is used.
ds@1952
  1579
      */
ds@1952
  1580
      pExpr->iTable = pParse->nTab++;
ds@1952
  1581
      addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
ds@1952
  1582
      memset(&keyInfo, 0, sizeof(keyInfo));
ds@1952
  1583
      keyInfo.nField = 1;
ds@1952
  1584
      sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
ds@1952
  1585
ds@1952
  1586
      if( pExpr->pSelect ){
ds@1952
  1587
        /* Case 1:     expr IN (SELECT ...)
ds@1952
  1588
        **
ds@1952
  1589
        ** Generate code to write the results of the select into the temporary
ds@1952
  1590
        ** table allocated and opened above.
ds@1952
  1591
        */
ds@1952
  1592
        int iParm = pExpr->iTable +  (((int)affinity)<<16);
ds@1952
  1593
        ExprList *pEList;
ds@1952
  1594
        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
ds@1952
  1595
        if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
ds@1952
  1596
          return;
ds@1952
  1597
        }
ds@1952
  1598
        pEList = pExpr->pSelect->pEList;
ds@1952
  1599
        if( pEList && pEList->nExpr>0 ){ 
ds@1952
  1600
          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
ds@1952
  1601
              pEList->a[0].pExpr);
ds@1952
  1602
        }
ds@1952
  1603
      }else if( pExpr->pList ){
ds@1952
  1604
        /* Case 2:     expr IN (exprlist)
ds@1952
  1605
        **
ds@1952
  1606
        ** For each expression, build an index key from the evaluation and
ds@1952
  1607
        ** store it in the temporary table. If <expr> is a column, then use
ds@1952
  1608
        ** that columns affinity when building index keys. If <expr> is not
ds@1952
  1609
        ** a column, use numeric affinity.
ds@1952
  1610
        */
ds@1952
  1611
        int i;
ds@1952
  1612
        ExprList *pList = pExpr->pList;
ds@1952
  1613
        struct ExprList_item *pItem;
ds@1952
  1614
ds@1952
  1615
        if( !affinity ){
ds@1952
  1616
          affinity = SQLITE_AFF_NONE;
ds@1952
  1617
        }
ds@1952
  1618
        keyInfo.aColl[0] = pExpr->pLeft->pColl;
ds@1952
  1619
ds@1952
  1620
        /* Loop through each expression in <exprlist>. */
ds@1952
  1621
        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
ds@1952
  1622
          Expr *pE2 = pItem->pExpr;
ds@1952
  1623
ds@1952
  1624
          /* If the expression is not constant then we will need to
ds@1952
  1625
          ** disable the test that was generated above that makes sure
ds@1952
  1626
          ** this code only executes once.  Because for a non-constant
ds@1952
  1627
          ** expression we need to rerun this code each time.
ds@1952
  1628
          */
ds@1952
  1629
          if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
ds@1952
  1630
            sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
ds@1952
  1631
            testAddr = 0;
ds@1952
  1632
          }
ds@1952
  1633
ds@1952
  1634
          /* Evaluate the expression and insert it into the temp table */
ds@1952
  1635
          sqlite3ExprCode(pParse, pE2);
ds@1952
  1636
          sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
ds@1952
  1637
          sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
ds@1952
  1638
        }
ds@1952
  1639
      }
ds@1952
  1640
      sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
ds@1952
  1641
      break;
ds@1952
  1642
    }
ds@1952
  1643
ds@1952
  1644
    case TK_EXISTS:
ds@1952
  1645
    case TK_SELECT: {
ds@1952
  1646
      /* This has to be a scalar SELECT.  Generate code to put the
ds@1952
  1647
      ** value of this select in a memory cell and record the number
ds@1952
  1648
      ** of the memory cell in iColumn.
ds@1952
  1649
      */
ds@1952
  1650
      static const Token one = { (u8*)"1", 0, 1 };
ds@1952
  1651
      Select *pSel;
ds@1952
  1652
      int iMem;
ds@1952
  1653
      int sop;
ds@1952
  1654
ds@1952
  1655
      pExpr->iColumn = iMem = pParse->nMem++;
ds@1952
  1656
      pSel = pExpr->pSelect;
ds@1952
  1657
      if( pExpr->op==TK_SELECT ){
ds@1952
  1658
        sop = SRT_Mem;
ds@1952
  1659
        sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
ds@1952
  1660
        VdbeComment((v, "# Init subquery result"));
ds@1952
  1661
      }else{
ds@1952
  1662
        sop = SRT_Exists;
ds@1952
  1663
        sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
ds@1952
  1664
        VdbeComment((v, "# Init EXISTS result"));
ds@1952
  1665
      }
ds@1952
  1666
      sqlite3ExprDelete(pSel->pLimit);
ds@1952
  1667
      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
ds@1952
  1668
      if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
ds@1952
  1669
        return;
ds@1952
  1670
      }
ds@1952
  1671
      break;
ds@1952
  1672
    }
ds@1952
  1673
  }
ds@1952
  1674
ds@1952
  1675
  if( testAddr ){
ds@1952
  1676
    sqlite3VdbeJumpHere(v, testAddr);
ds@1952
  1677
  }
ds@1952
  1678
ds@1952
  1679
  return;
ds@1952
  1680
}
ds@1952
  1681
#endif /* SQLITE_OMIT_SUBQUERY */
ds@1952
  1682
ds@1952
  1683
/*
ds@1952
  1684
** Generate an instruction that will put the integer describe by
ds@1952
  1685
** text z[0..n-1] on the stack.
ds@1952
  1686
*/
ds@1952
  1687
static void codeInteger(Vdbe *v, const char *z, int n){
ds@1952
  1688
  assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
ds@1952
  1689
  if( z ){
ds@1952
  1690
    int i;
ds@1952
  1691
    if( sqlite3GetInt32(z, &i) ){
ds@1952
  1692
      sqlite3VdbeAddOp(v, OP_Integer, i, 0);
ds@1952
  1693
    }else if( sqlite3FitsIn64Bits(z) ){
ds@1952
  1694
      sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
ds@1952
  1695
    }else{
ds@1952
  1696
      sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
ds@1952
  1697
    }
ds@1952
  1698
  }
ds@1952
  1699
}
ds@1952
  1700
ds@1952
  1701
ds@1952
  1702
/*
ds@1952
  1703
** Generate code that will extract the iColumn-th column from
ds@1952
  1704
** table pTab and push that column value on the stack.  There
ds@1952
  1705
** is an open cursor to pTab in iTable.  If iColumn<0 then
ds@1952
  1706
** code is generated that extracts the rowid.
ds@1952
  1707
*/
ds@1952
  1708
void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
ds@1952
  1709
  if( iColumn<0 ){
ds@1952
  1710
    int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
ds@1952
  1711
    sqlite3VdbeAddOp(v, op, iTable, 0);
ds@1952
  1712
  }else if( pTab==0 ){
ds@1952
  1713
    sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
ds@1952
  1714
  }else{
ds@1952
  1715
    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
ds@1952
  1716
    sqlite3VdbeAddOp(v, op, iTable, iColumn);
ds@1952
  1717
    sqlite3ColumnDefault(v, pTab, iColumn);
ds@1952
  1718
#ifndef SQLITE_OMIT_FLOATING_POINT
ds@1952
  1719
    if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
ds@1952
  1720
      sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
ds@1952
  1721
    }
ds@1952
  1722
#endif
ds@1952
  1723
  }
ds@1952
  1724
}
ds@1952
  1725
ds@1952
  1726
/*
ds@1952
  1727
** Generate code into the current Vdbe to evaluate the given
ds@1952
  1728
** expression and leave the result on the top of stack.
ds@1952
  1729
**
ds@1952
  1730
** This code depends on the fact that certain token values (ex: TK_EQ)
ds@1952
  1731
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
ds@1952
  1732
** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
ds@1952
  1733
** the make process cause these values to align.  Assert()s in the code
ds@1952
  1734
** below verify that the numbers are aligned correctly.
ds@1952
  1735
*/
ds@1952
  1736
void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
ds@1952
  1737
  Vdbe *v = pParse->pVdbe;
ds@1952
  1738
  int op;
ds@1952
  1739
  int stackChng = 1;    /* Amount of change to stack depth */
ds@1952
  1740
ds@1952
  1741
  if( v==0 ) return;
ds@1952
  1742
  if( pExpr==0 ){
ds@1952
  1743
    sqlite3VdbeAddOp(v, OP_Null, 0, 0);
ds@1952
  1744
    return;
ds@1952
  1745
  }
ds@1952
  1746
  op = pExpr->op;
ds@1952
  1747
  switch( op ){
ds@1952
  1748
    case TK_AGG_COLUMN: {
ds@1952
  1749
      AggInfo *pAggInfo = pExpr->pAggInfo;
ds@1952
  1750
      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
ds@1952
  1751
      if( !pAggInfo->directMode ){
ds@1952
  1752
        sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
ds@1952
  1753
        break;
ds@1952
  1754
      }else if( pAggInfo->useSortingIdx ){
ds@1952
  1755
        sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
ds@1952
  1756
                              pCol->iSorterColumn);
ds@1952
  1757
        break;
ds@1952
  1758
      }
ds@1952
  1759
      /* Otherwise, fall thru into the TK_COLUMN case */
ds@1952
  1760
    }
ds@1952
  1761
    case TK_COLUMN: {
ds@1952
  1762
      if( pExpr->iTable<0 ){
ds@1952
  1763
        /* This only happens when coding check constraints */
ds@1952
  1764
        assert( pParse->ckOffset>0 );
ds@1952
  1765
        sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
ds@1952
  1766
      }else{
ds@1952
  1767
        sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
ds@1952
  1768
      }
ds@1952
  1769
      break;
ds@1952
  1770
    }
ds@1952
  1771
    case TK_INTEGER: {
ds@1952
  1772
      codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
ds@1952
  1773
      break;
ds@1952
  1774
    }
ds@1952
  1775
    case TK_FLOAT:
ds@1952
  1776
    case TK_STRING: {
ds@1952
  1777
      assert( TK_FLOAT==OP_Real );
ds@1952
  1778
      assert( TK_STRING==OP_String8 );
ds@1952
  1779
      sqlite3DequoteExpr(pParse->db, pExpr);
ds@1952
  1780
      sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
ds@1952
  1781
      break;
ds@1952
  1782
    }
ds@1952
  1783
    case TK_NULL: {
ds@1952
  1784
      sqlite3VdbeAddOp(v, OP_Null, 0, 0);
ds@1952
  1785
      break;
ds@1952
  1786
    }
ds@1952
  1787
#ifndef SQLITE_OMIT_BLOB_LITERAL
ds@1952
  1788
    case TK_BLOB: {
ds@1952
  1789
      int n;
ds@1952
  1790
      const char *z;
ds@1952
  1791
      assert( TK_BLOB==OP_HexBlob );
ds@1952
  1792
      n = pExpr->token.n - 3;
ds@1952
  1793
      z = (char*)pExpr->token.z + 2;
ds@1952
  1794
      assert( n>=0 );
ds@1952
  1795
      if( n==0 ){
ds@1952
  1796
        z = "";
ds@1952
  1797
      }
ds@1952
  1798
      sqlite3VdbeOp3(v, op, 0, 0, z, n);
ds@1952
  1799
      break;
ds@1952
  1800
    }
ds@1952
  1801
#endif
ds@1952
  1802
    case TK_VARIABLE: {
ds@1952
  1803
      sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
ds@1952
  1804
      if( pExpr->token.n>1 ){
ds@1952
  1805
        sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
ds@1952
  1806
      }
ds@1952
  1807
      break;
ds@1952
  1808
    }
ds@1952
  1809
    case TK_REGISTER: {
ds@1952
  1810
      sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
ds@1952
  1811
      break;
ds@1952
  1812
    }
ds@1952
  1813
#ifndef SQLITE_OMIT_CAST
ds@1952
  1814
    case TK_CAST: {
ds@1952
  1815
      /* Expressions of the form:   CAST(pLeft AS token) */
ds@1952
  1816
      int aff, to_op;
ds@1952
  1817
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  1818
      aff = sqlite3AffinityType(&pExpr->token);
ds@1952
  1819
      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
ds@1952
  1820
      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
ds@1952
  1821
      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
ds@1952
  1822
      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
ds@1952
  1823
      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
ds@1952
  1824
      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
ds@1952
  1825
      sqlite3VdbeAddOp(v, to_op, 0, 0);
ds@1952
  1826
      stackChng = 0;
ds@1952
  1827
      break;
ds@1952
  1828
    }
ds@1952
  1829
#endif /* SQLITE_OMIT_CAST */
ds@1952
  1830
    case TK_LT:
ds@1952
  1831
    case TK_LE:
ds@1952
  1832
    case TK_GT:
ds@1952
  1833
    case TK_GE:
ds@1952
  1834
    case TK_NE:
ds@1952
  1835
    case TK_EQ: {
ds@1952
  1836
      assert( TK_LT==OP_Lt );
ds@1952
  1837
      assert( TK_LE==OP_Le );
ds@1952
  1838
      assert( TK_GT==OP_Gt );
ds@1952
  1839
      assert( TK_GE==OP_Ge );
ds@1952
  1840
      assert( TK_EQ==OP_Eq );
ds@1952
  1841
      assert( TK_NE==OP_Ne );
ds@1952
  1842
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  1843
      sqlite3ExprCode(pParse, pExpr->pRight);
ds@1952
  1844
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
ds@1952
  1845
      stackChng = -1;
ds@1952
  1846
      break;
ds@1952
  1847
    }
ds@1952
  1848
    case TK_AND:
ds@1952
  1849
    case TK_OR:
ds@1952
  1850
    case TK_PLUS:
ds@1952
  1851
    case TK_STAR:
ds@1952
  1852
    case TK_MINUS:
ds@1952
  1853
    case TK_REM:
ds@1952
  1854
    case TK_BITAND:
ds@1952
  1855
    case TK_BITOR:
ds@1952
  1856
    case TK_SLASH:
ds@1952
  1857
    case TK_LSHIFT:
ds@1952
  1858
    case TK_RSHIFT: 
ds@1952
  1859
    case TK_CONCAT: {
ds@1952
  1860
      assert( TK_AND==OP_And );
ds@1952
  1861
      assert( TK_OR==OP_Or );
ds@1952
  1862
      assert( TK_PLUS==OP_Add );
ds@1952
  1863
      assert( TK_MINUS==OP_Subtract );
ds@1952
  1864
      assert( TK_REM==OP_Remainder );
ds@1952
  1865
      assert( TK_BITAND==OP_BitAnd );
ds@1952
  1866
      assert( TK_BITOR==OP_BitOr );
ds@1952
  1867
      assert( TK_SLASH==OP_Divide );
ds@1952
  1868
      assert( TK_LSHIFT==OP_ShiftLeft );
ds@1952
  1869
      assert( TK_RSHIFT==OP_ShiftRight );
ds@1952
  1870
      assert( TK_CONCAT==OP_Concat );
ds@1952
  1871
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  1872
      sqlite3ExprCode(pParse, pExpr->pRight);
ds@1952
  1873
      sqlite3VdbeAddOp(v, op, 0, 0);
ds@1952
  1874
      stackChng = -1;
ds@1952
  1875
      break;
ds@1952
  1876
    }
ds@1952
  1877
    case TK_UMINUS: {
ds@1952
  1878
      Expr *pLeft = pExpr->pLeft;
ds@1952
  1879
      assert( pLeft );
ds@1952
  1880
      if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
ds@1952
  1881
        Token *p = &pLeft->token;
ds@1952
  1882
        char *z = sqlite3MPrintf(pParse->db, "-%.*s", p->n, p->z);
ds@1952
  1883
        if( pLeft->op==TK_FLOAT ){
ds@1952
  1884
          sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
ds@1952
  1885
        }else{
ds@1952
  1886
          codeInteger(v, z, p->n+1);
ds@1952
  1887
        }
ds@1952
  1888
        sqlite3_free(z);
ds@1952
  1889
        break;
ds@1952
  1890
      }
ds@1952
  1891
      /* Fall through into TK_NOT */
ds@1952
  1892
    }
ds@1952
  1893
    case TK_BITNOT:
ds@1952
  1894
    case TK_NOT: {
ds@1952
  1895
      assert( TK_BITNOT==OP_BitNot );
ds@1952
  1896
      assert( TK_NOT==OP_Not );
ds@1952
  1897
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  1898
      sqlite3VdbeAddOp(v, op, 0, 0);
ds@1952
  1899
      stackChng = 0;
ds@1952
  1900
      break;
ds@1952
  1901
    }
ds@1952
  1902
    case TK_ISNULL:
ds@1952
  1903
    case TK_NOTNULL: {
ds@1952
  1904
      int dest;
ds@1952
  1905
      assert( TK_ISNULL==OP_IsNull );
ds@1952
  1906
      assert( TK_NOTNULL==OP_NotNull );
ds@1952
  1907
      sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
ds@1952
  1908
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  1909
      dest = sqlite3VdbeCurrentAddr(v) + 2;
ds@1952
  1910
      sqlite3VdbeAddOp(v, op, 1, dest);
ds@1952
  1911
      sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
ds@1952
  1912
      stackChng = 0;
ds@1952
  1913
      break;
ds@1952
  1914
    }
ds@1952
  1915
    case TK_AGG_FUNCTION: {
ds@1952
  1916
      AggInfo *pInfo = pExpr->pAggInfo;
ds@1952
  1917
      if( pInfo==0 ){
ds@1952
  1918
        sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
ds@1952
  1919
            &pExpr->span);
ds@1952
  1920
      }else{
ds@1952
  1921
        sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
ds@1952
  1922
      }
ds@1952
  1923
      break;
ds@1952
  1924
    }
ds@1952
  1925
    case TK_CONST_FUNC:
ds@1952
  1926
    case TK_FUNCTION: {
ds@1952
  1927
      ExprList *pList = pExpr->pList;
ds@1952
  1928
      int nExpr = pList ? pList->nExpr : 0;
ds@1952
  1929
      FuncDef *pDef;
ds@1952
  1930
      int nId;
ds@1952
  1931
      const char *zId;
ds@1952
  1932
      int constMask = 0;
ds@1952
  1933
      int i;
ds@1952
  1934
      sqlite3 *db = pParse->db;
ds@1952
  1935
      u8 enc = ENC(db);
ds@1952
  1936
      CollSeq *pColl = 0;
ds@1952
  1937
ds@1952
  1938
      zId = (char*)pExpr->token.z;
ds@1952
  1939
      nId = pExpr->token.n;
ds@1952
  1940
      pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
ds@1952
  1941
      assert( pDef!=0 );
ds@1952
  1942
      nExpr = sqlite3ExprCodeExprList(pParse, pList);
ds@1952
  1943
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
  1944
      /* Possibly overload the function if the first argument is
ds@1952
  1945
      ** a virtual table column.
ds@1952
  1946
      **
ds@1952
  1947
      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
ds@1952
  1948
      ** second argument, not the first, as the argument to test to
ds@1952
  1949
      ** see if it is a column in a virtual table.  This is done because
ds@1952
  1950
      ** the left operand of infix functions (the operand we want to
ds@1952
  1951
      ** control overloading) ends up as the second argument to the
ds@1952
  1952
      ** function.  The expression "A glob B" is equivalent to 
ds@1952
  1953
      ** "glob(B,A).  We want to use the A in "A glob B" to test
ds@1952
  1954
      ** for function overloading.  But we use the B term in "glob(B,A)".
ds@1952
  1955
      */
ds@1952
  1956
      if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
ds@1952
  1957
        pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
ds@1952
  1958
      }else if( nExpr>0 ){
ds@1952
  1959
        pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
ds@1952
  1960
      }
ds@1952
  1961
#endif
ds@1952
  1962
      for(i=0; i<nExpr && i<32; i++){
ds@1952
  1963
        if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
ds@1952
  1964
          constMask |= (1<<i);
ds@1952
  1965
        }
ds@1952
  1966
        if( pDef->needCollSeq && !pColl ){
ds@1952
  1967
          pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
ds@1952
  1968
        }
ds@1952
  1969
      }
ds@1952
  1970
      if( pDef->needCollSeq ){
ds@1952
  1971
        if( !pColl ) pColl = pParse->db->pDfltColl; 
ds@1952
  1972
        sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
ds@1952
  1973
      }
ds@1952
  1974
      sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
ds@1952
  1975
      stackChng = 1-nExpr;
ds@1952
  1976
      break;
ds@1952
  1977
    }
ds@1952
  1978
#ifndef SQLITE_OMIT_SUBQUERY
ds@1952
  1979
    case TK_EXISTS:
ds@1952
  1980
    case TK_SELECT: {
ds@1952
  1981
      if( pExpr->iColumn==0 ){
ds@1952
  1982
        sqlite3CodeSubselect(pParse, pExpr);
ds@1952
  1983
      }
ds@1952
  1984
      sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
ds@1952
  1985
      VdbeComment((v, "# load subquery result"));
ds@1952
  1986
      break;
ds@1952
  1987
    }
ds@1952
  1988
    case TK_IN: {
ds@1952
  1989
      int addr;
ds@1952
  1990
      char affinity;
ds@1952
  1991
      int ckOffset = pParse->ckOffset;
ds@1952
  1992
      sqlite3CodeSubselect(pParse, pExpr);
ds@1952
  1993
ds@1952
  1994
      /* Figure out the affinity to use to create a key from the results
ds@1952
  1995
      ** of the expression. affinityStr stores a static string suitable for
ds@1952
  1996
      ** P3 of OP_MakeRecord.
ds@1952
  1997
      */
ds@1952
  1998
      affinity = comparisonAffinity(pExpr);
ds@1952
  1999
ds@1952
  2000
      sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
ds@1952
  2001
      pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
ds@1952
  2002
ds@1952
  2003
      /* Code the <expr> from "<expr> IN (...)". The temporary table
ds@1952
  2004
      ** pExpr->iTable contains the values that make up the (...) set.
ds@1952
  2005
      */
ds@1952
  2006
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  2007
      addr = sqlite3VdbeCurrentAddr(v);
ds@1952
  2008
      sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4);            /* addr + 0 */
ds@1952
  2009
      sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
ds@1952
  2010
      sqlite3VdbeAddOp(v, OP_Null, 0, 0);
ds@1952
  2011
      sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
ds@1952
  2012
      sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);   /* addr + 4 */
ds@1952
  2013
      sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
ds@1952
  2014
      sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);                  /* addr + 6 */
ds@1952
  2015
ds@1952
  2016
      break;
ds@1952
  2017
    }
ds@1952
  2018
#endif
ds@1952
  2019
    case TK_BETWEEN: {
ds@1952
  2020
      Expr *pLeft = pExpr->pLeft;
ds@1952
  2021
      struct ExprList_item *pLItem = pExpr->pList->a;
ds@1952
  2022
      Expr *pRight = pLItem->pExpr;
ds@1952
  2023
      sqlite3ExprCode(pParse, pLeft);
ds@1952
  2024
      sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
ds@1952
  2025
      sqlite3ExprCode(pParse, pRight);
ds@1952
  2026
      codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
ds@1952
  2027
      sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
ds@1952
  2028
      pLItem++;
ds@1952
  2029
      pRight = pLItem->pExpr;
ds@1952
  2030
      sqlite3ExprCode(pParse, pRight);
ds@1952
  2031
      codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
ds@1952
  2032
      sqlite3VdbeAddOp(v, OP_And, 0, 0);
ds@1952
  2033
      break;
ds@1952
  2034
    }
ds@1952
  2035
    case TK_UPLUS: {
ds@1952
  2036
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  2037
      stackChng = 0;
ds@1952
  2038
      break;
ds@1952
  2039
    }
ds@1952
  2040
    case TK_CASE: {
ds@1952
  2041
      int expr_end_label;
ds@1952
  2042
      int jumpInst;
ds@1952
  2043
      int nExpr;
ds@1952
  2044
      int i;
ds@1952
  2045
      ExprList *pEList;
ds@1952
  2046
      struct ExprList_item *aListelem;
ds@1952
  2047
ds@1952
  2048
      assert(pExpr->pList);
ds@1952
  2049
      assert((pExpr->pList->nExpr % 2) == 0);
ds@1952
  2050
      assert(pExpr->pList->nExpr > 0);
ds@1952
  2051
      pEList = pExpr->pList;
ds@1952
  2052
      aListelem = pEList->a;
ds@1952
  2053
      nExpr = pEList->nExpr;
ds@1952
  2054
      expr_end_label = sqlite3VdbeMakeLabel(v);
ds@1952
  2055
      if( pExpr->pLeft ){
ds@1952
  2056
        sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  2057
      }
ds@1952
  2058
      for(i=0; i<nExpr; i=i+2){
ds@1952
  2059
        sqlite3ExprCode(pParse, aListelem[i].pExpr);
ds@1952
  2060
        if( pExpr->pLeft ){
ds@1952
  2061
          sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
ds@1952
  2062
          jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
ds@1952
  2063
                                 OP_Ne, 0, 1);
ds@1952
  2064
          sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
ds@1952
  2065
        }else{
ds@1952
  2066
          jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
ds@1952
  2067
        }
ds@1952
  2068
        sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
ds@1952
  2069
        sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
ds@1952
  2070
        sqlite3VdbeJumpHere(v, jumpInst);
ds@1952
  2071
      }
ds@1952
  2072
      if( pExpr->pLeft ){
ds@1952
  2073
        sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
ds@1952
  2074
      }
ds@1952
  2075
      if( pExpr->pRight ){
ds@1952
  2076
        sqlite3ExprCode(pParse, pExpr->pRight);
ds@1952
  2077
      }else{
ds@1952
  2078
        sqlite3VdbeAddOp(v, OP_Null, 0, 0);
ds@1952
  2079
      }
ds@1952
  2080
      sqlite3VdbeResolveLabel(v, expr_end_label);
ds@1952
  2081
      break;
ds@1952
  2082
    }
ds@1952
  2083
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
  2084
    case TK_RAISE: {
ds@1952
  2085
      if( !pParse->trigStack ){
ds@1952
  2086
        sqlite3ErrorMsg(pParse,
ds@1952
  2087
                       "RAISE() may only be used within a trigger-program");
ds@1952
  2088
        return;
ds@1952
  2089
      }
ds@1952
  2090
      if( pExpr->iColumn!=OE_Ignore ){
ds@1952
  2091
         assert( pExpr->iColumn==OE_Rollback ||
ds@1952
  2092
                 pExpr->iColumn == OE_Abort ||
ds@1952
  2093
                 pExpr->iColumn == OE_Fail );
ds@1952
  2094
         sqlite3DequoteExpr(pParse->db, pExpr);
ds@1952
  2095
         sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
ds@1952
  2096
                        (char*)pExpr->token.z, pExpr->token.n);
ds@1952
  2097
      } else {
ds@1952
  2098
         assert( pExpr->iColumn == OE_Ignore );
ds@1952
  2099
         sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
ds@1952
  2100
         sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
ds@1952
  2101
         VdbeComment((v, "# raise(IGNORE)"));
ds@1952
  2102
      }
ds@1952
  2103
      stackChng = 0;
ds@1952
  2104
      break;
ds@1952
  2105
    }
ds@1952
  2106
#endif
ds@1952
  2107
  }
ds@1952
  2108
ds@1952
  2109
  if( pParse->ckOffset ){
ds@1952
  2110
    pParse->ckOffset += stackChng;
ds@1952
  2111
    assert( pParse->ckOffset );
ds@1952
  2112
  }
ds@1952
  2113
}
ds@1952
  2114
ds@1952
  2115
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
  2116
/*
ds@1952
  2117
** Generate code that evalutes the given expression and leaves the result
ds@1952
  2118
** on the stack.  See also sqlite3ExprCode().
ds@1952
  2119
**
ds@1952
  2120
** This routine might also cache the result and modify the pExpr tree
ds@1952
  2121
** so that it will make use of the cached result on subsequent evaluations
ds@1952
  2122
** rather than evaluate the whole expression again.  Trivial expressions are
ds@1952
  2123
** not cached.  If the expression is cached, its result is stored in a 
ds@1952
  2124
** memory location.
ds@1952
  2125
*/
ds@1952
  2126
void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
ds@1952
  2127
  Vdbe *v = pParse->pVdbe;
ds@1952
  2128
  int iMem;
ds@1952
  2129
  int addr1, addr2;
ds@1952
  2130
  if( v==0 ) return;
ds@1952
  2131
  addr1 = sqlite3VdbeCurrentAddr(v);
ds@1952
  2132
  sqlite3ExprCode(pParse, pExpr);
ds@1952
  2133
  addr2 = sqlite3VdbeCurrentAddr(v);
ds@1952
  2134
  if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
ds@1952
  2135
    iMem = pExpr->iTable = pParse->nMem++;
ds@1952
  2136
    sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
ds@1952
  2137
    pExpr->op = TK_REGISTER;
ds@1952
  2138
  }
ds@1952
  2139
}
ds@1952
  2140
#endif
ds@1952
  2141
ds@1952
  2142
/*
ds@1952
  2143
** Generate code that pushes the value of every element of the given
ds@1952
  2144
** expression list onto the stack.
ds@1952
  2145
**
ds@1952
  2146
** Return the number of elements pushed onto the stack.
ds@1952
  2147
*/
ds@1952
  2148
int sqlite3ExprCodeExprList(
ds@1952
  2149
  Parse *pParse,     /* Parsing context */
ds@1952
  2150
  ExprList *pList    /* The expression list to be coded */
ds@1952
  2151
){
ds@1952
  2152
  struct ExprList_item *pItem;
ds@1952
  2153
  int i, n;
ds@1952
  2154
  if( pList==0 ) return 0;
ds@1952
  2155
  n = pList->nExpr;
ds@1952
  2156
  for(pItem=pList->a, i=n; i>0; i--, pItem++){
ds@1952
  2157
    sqlite3ExprCode(pParse, pItem->pExpr);
ds@1952
  2158
  }
ds@1952
  2159
  return n;
ds@1952
  2160
}
ds@1952
  2161
ds@1952
  2162
/*
ds@1952
  2163
** Generate code for a boolean expression such that a jump is made
ds@1952
  2164
** to the label "dest" if the expression is true but execution
ds@1952
  2165
** continues straight thru if the expression is false.
ds@1952
  2166
**
ds@1952
  2167
** If the expression evaluates to NULL (neither true nor false), then
ds@1952
  2168
** take the jump if the jumpIfNull flag is true.
ds@1952
  2169
**
ds@1952
  2170
** This code depends on the fact that certain token values (ex: TK_EQ)
ds@1952
  2171
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
ds@1952
  2172
** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
ds@1952
  2173
** the make process cause these values to align.  Assert()s in the code
ds@1952
  2174
** below verify that the numbers are aligned correctly.
ds@1952
  2175
*/
ds@1952
  2176
void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
ds@1952
  2177
  Vdbe *v = pParse->pVdbe;
ds@1952
  2178
  int op = 0;
ds@1952
  2179
  int ckOffset = pParse->ckOffset;
ds@1952
  2180
  if( v==0 || pExpr==0 ) return;
ds@1952
  2181
  op = pExpr->op;
ds@1952
  2182
  switch( op ){
ds@1952
  2183
    case TK_AND: {
ds@1952
  2184
      int d2 = sqlite3VdbeMakeLabel(v);
ds@1952
  2185
      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
ds@1952
  2186
      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
ds@1952
  2187
      sqlite3VdbeResolveLabel(v, d2);
ds@1952
  2188
      break;
ds@1952
  2189
    }
ds@1952
  2190
    case TK_OR: {
ds@1952
  2191
      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
ds@1952
  2192
      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
ds@1952
  2193
      break;
ds@1952
  2194
    }
ds@1952
  2195
    case TK_NOT: {
ds@1952
  2196
      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
ds@1952
  2197
      break;
ds@1952
  2198
    }
ds@1952
  2199
    case TK_LT:
ds@1952
  2200
    case TK_LE:
ds@1952
  2201
    case TK_GT:
ds@1952
  2202
    case TK_GE:
ds@1952
  2203
    case TK_NE:
ds@1952
  2204
    case TK_EQ: {
ds@1952
  2205
      assert( TK_LT==OP_Lt );
ds@1952
  2206
      assert( TK_LE==OP_Le );
ds@1952
  2207
      assert( TK_GT==OP_Gt );
ds@1952
  2208
      assert( TK_GE==OP_Ge );
ds@1952
  2209
      assert( TK_EQ==OP_Eq );
ds@1952
  2210
      assert( TK_NE==OP_Ne );
ds@1952
  2211
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  2212
      sqlite3ExprCode(pParse, pExpr->pRight);
ds@1952
  2213
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
ds@1952
  2214
      break;
ds@1952
  2215
    }
ds@1952
  2216
    case TK_ISNULL:
ds@1952
  2217
    case TK_NOTNULL: {
ds@1952
  2218
      assert( TK_ISNULL==OP_IsNull );
ds@1952
  2219
      assert( TK_NOTNULL==OP_NotNull );
ds@1952
  2220
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  2221
      sqlite3VdbeAddOp(v, op, 1, dest);
ds@1952
  2222
      break;
ds@1952
  2223
    }
ds@1952
  2224
    case TK_BETWEEN: {
ds@1952
  2225
      /* The expression "x BETWEEN y AND z" is implemented as:
ds@1952
  2226
      **
ds@1952
  2227
      ** 1 IF (x < y) GOTO 3
ds@1952
  2228
      ** 2 IF (x <= z) GOTO <dest>
ds@1952
  2229
      ** 3 ...
ds@1952
  2230
      */
ds@1952
  2231
      int addr;
ds@1952
  2232
      Expr *pLeft = pExpr->pLeft;
ds@1952
  2233
      Expr *pRight = pExpr->pList->a[0].pExpr;
ds@1952
  2234
      sqlite3ExprCode(pParse, pLeft);
ds@1952
  2235
      sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
ds@1952
  2236
      sqlite3ExprCode(pParse, pRight);
ds@1952
  2237
      addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
ds@1952
  2238
ds@1952
  2239
      pRight = pExpr->pList->a[1].pExpr;
ds@1952
  2240
      sqlite3ExprCode(pParse, pRight);
ds@1952
  2241
      codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
ds@1952
  2242
ds@1952
  2243
      sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
ds@1952
  2244
      sqlite3VdbeJumpHere(v, addr);
ds@1952
  2245
      sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
ds@1952
  2246
      break;
ds@1952
  2247
    }
ds@1952
  2248
    default: {
ds@1952
  2249
      sqlite3ExprCode(pParse, pExpr);
ds@1952
  2250
      sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
ds@1952
  2251
      break;
ds@1952
  2252
    }
ds@1952
  2253
  }
ds@1952
  2254
  pParse->ckOffset = ckOffset;
ds@1952
  2255
}
ds@1952
  2256
ds@1952
  2257
/*
ds@1952
  2258
** Generate code for a boolean expression such that a jump is made
ds@1952
  2259
** to the label "dest" if the expression is false but execution
ds@1952
  2260
** continues straight thru if the expression is true.
ds@1952
  2261
**
ds@1952
  2262
** If the expression evaluates to NULL (neither true nor false) then
ds@1952
  2263
** jump if jumpIfNull is true or fall through if jumpIfNull is false.
ds@1952
  2264
*/
ds@1952
  2265
void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
ds@1952
  2266
  Vdbe *v = pParse->pVdbe;
ds@1952
  2267
  int op = 0;
ds@1952
  2268
  int ckOffset = pParse->ckOffset;
ds@1952
  2269
  if( v==0 || pExpr==0 ) return;
ds@1952
  2270
ds@1952
  2271
  /* The value of pExpr->op and op are related as follows:
ds@1952
  2272
  **
ds@1952
  2273
  **       pExpr->op            op
ds@1952
  2274
  **       ---------          ----------
ds@1952
  2275
  **       TK_ISNULL          OP_NotNull
ds@1952
  2276
  **       TK_NOTNULL         OP_IsNull
ds@1952
  2277
  **       TK_NE              OP_Eq
ds@1952
  2278
  **       TK_EQ              OP_Ne
ds@1952
  2279
  **       TK_GT              OP_Le
ds@1952
  2280
  **       TK_LE              OP_Gt
ds@1952
  2281
  **       TK_GE              OP_Lt
ds@1952
  2282
  **       TK_LT              OP_Ge
ds@1952
  2283
  **
ds@1952
  2284
  ** For other values of pExpr->op, op is undefined and unused.
ds@1952
  2285
  ** The value of TK_ and OP_ constants are arranged such that we
ds@1952
  2286
  ** can compute the mapping above using the following expression.
ds@1952
  2287
  ** Assert()s verify that the computation is correct.
ds@1952
  2288
  */
ds@1952
  2289
  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
ds@1952
  2290
ds@1952
  2291
  /* Verify correct alignment of TK_ and OP_ constants
ds@1952
  2292
  */
ds@1952
  2293
  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
ds@1952
  2294
  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
ds@1952
  2295
  assert( pExpr->op!=TK_NE || op==OP_Eq );
ds@1952
  2296
  assert( pExpr->op!=TK_EQ || op==OP_Ne );
ds@1952
  2297
  assert( pExpr->op!=TK_LT || op==OP_Ge );
ds@1952
  2298
  assert( pExpr->op!=TK_LE || op==OP_Gt );
ds@1952
  2299
  assert( pExpr->op!=TK_GT || op==OP_Le );
ds@1952
  2300
  assert( pExpr->op!=TK_GE || op==OP_Lt );
ds@1952
  2301
ds@1952
  2302
  switch( pExpr->op ){
ds@1952
  2303
    case TK_AND: {
ds@1952
  2304
      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
ds@1952
  2305
      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
ds@1952
  2306
      break;
ds@1952
  2307
    }
ds@1952
  2308
    case TK_OR: {
ds@1952
  2309
      int d2 = sqlite3VdbeMakeLabel(v);
ds@1952
  2310
      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
ds@1952
  2311
      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
ds@1952
  2312
      sqlite3VdbeResolveLabel(v, d2);
ds@1952
  2313
      break;
ds@1952
  2314
    }
ds@1952
  2315
    case TK_NOT: {
ds@1952
  2316
      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
ds@1952
  2317
      break;
ds@1952
  2318
    }
ds@1952
  2319
    case TK_LT:
ds@1952
  2320
    case TK_LE:
ds@1952
  2321
    case TK_GT:
ds@1952
  2322
    case TK_GE:
ds@1952
  2323
    case TK_NE:
ds@1952
  2324
    case TK_EQ: {
ds@1952
  2325
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  2326
      sqlite3ExprCode(pParse, pExpr->pRight);
ds@1952
  2327
      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
ds@1952
  2328
      break;
ds@1952
  2329
    }
ds@1952
  2330
    case TK_ISNULL:
ds@1952
  2331
    case TK_NOTNULL: {
ds@1952
  2332
      sqlite3ExprCode(pParse, pExpr->pLeft);
ds@1952
  2333
      sqlite3VdbeAddOp(v, op, 1, dest);
ds@1952
  2334
      break;
ds@1952
  2335
    }
ds@1952
  2336
    case TK_BETWEEN: {
ds@1952
  2337
      /* The expression is "x BETWEEN y AND z". It is implemented as:
ds@1952
  2338
      **
ds@1952
  2339
      ** 1 IF (x >= y) GOTO 3
ds@1952
  2340
      ** 2 GOTO <dest>
ds@1952
  2341
      ** 3 IF (x > z) GOTO <dest>
ds@1952
  2342
      */
ds@1952
  2343
      int addr;
ds@1952
  2344
      Expr *pLeft = pExpr->pLeft;
ds@1952
  2345
      Expr *pRight = pExpr->pList->a[0].pExpr;
ds@1952
  2346
      sqlite3ExprCode(pParse, pLeft);
ds@1952
  2347
      sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
ds@1952
  2348
      sqlite3ExprCode(pParse, pRight);
ds@1952
  2349
      addr = sqlite3VdbeCurrentAddr(v);
ds@1952
  2350
      codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
ds@1952
  2351
ds@1952
  2352
      sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
ds@1952
  2353
      sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
ds@1952
  2354
      pRight = pExpr->pList->a[1].pExpr;
ds@1952
  2355
      sqlite3ExprCode(pParse, pRight);
ds@1952
  2356
      codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
ds@1952
  2357
      break;
ds@1952
  2358
    }
ds@1952
  2359
    default: {
ds@1952
  2360
      sqlite3ExprCode(pParse, pExpr);
ds@1952
  2361
      sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
ds@1952
  2362
      break;
ds@1952
  2363
    }
ds@1952
  2364
  }
ds@1952
  2365
  pParse->ckOffset = ckOffset;
ds@1952
  2366
}
ds@1952
  2367
ds@1952
  2368
/*
ds@1952
  2369
** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
ds@1952
  2370
** if they are identical and return FALSE if they differ in any way.
ds@1952
  2371
**
ds@1952
  2372
** Sometimes this routine will return FALSE even if the two expressions
ds@1952
  2373
** really are equivalent.  If we cannot prove that the expressions are
ds@1952
  2374
** identical, we return FALSE just to be safe.  So if this routine
ds@1952
  2375
** returns false, then you do not really know for certain if the two
ds@1952
  2376
** expressions are the same.  But if you get a TRUE return, then you
ds@1952
  2377
** can be sure the expressions are the same.  In the places where
ds@1952
  2378
** this routine is used, it does not hurt to get an extra FALSE - that
ds@1952
  2379
** just might result in some slightly slower code.  But returning
ds@1952
  2380
** an incorrect TRUE could lead to a malfunction.
ds@1952
  2381
*/
ds@1952
  2382
int sqlite3ExprCompare(Expr *pA, Expr *pB){
ds@1952
  2383
  int i;
ds@1952
  2384
  if( pA==0||pB==0 ){
ds@1952
  2385
    return pB==pA;
ds@1952
  2386
  }
ds@1952
  2387
  if( pA->op!=pB->op ) return 0;
ds@1952
  2388
  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
ds@1952
  2389
  if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
ds@1952
  2390
  if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
ds@1952
  2391
  if( pA->pList ){
ds@1952
  2392
    if( pB->pList==0 ) return 0;
ds@1952
  2393
    if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
ds@1952
  2394
    for(i=0; i<pA->pList->nExpr; i++){
ds@1952
  2395
      if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
ds@1952
  2396
        return 0;
ds@1952
  2397
      }
ds@1952
  2398
    }
ds@1952
  2399
  }else if( pB->pList ){
ds@1952
  2400
    return 0;
ds@1952
  2401
  }
ds@1952
  2402
  if( pA->pSelect || pB->pSelect ) return 0;
ds@1952
  2403
  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
ds@1952
  2404
  if( pA->op!=TK_COLUMN && pA->token.z ){
ds@1952
  2405
    if( pB->token.z==0 ) return 0;
ds@1952
  2406
    if( pB->token.n!=pA->token.n ) return 0;
ds@1952
  2407
    if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
ds@1952
  2408
      return 0;
ds@1952
  2409
    }
ds@1952
  2410
  }
ds@1952
  2411
  return 1;
ds@1952
  2412
}
ds@1952
  2413
ds@1952
  2414
ds@1952
  2415
/*
ds@1952
  2416
** Add a new element to the pAggInfo->aCol[] array.  Return the index of
ds@1952
  2417
** the new element.  Return a negative number if malloc fails.
ds@1952
  2418
*/
ds@1952
  2419
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
ds@1952
  2420
  int i;
ds@1952
  2421
  pInfo->aCol = sqlite3ArrayAllocate(
ds@1952
  2422
       db,
ds@1952
  2423
       pInfo->aCol,
ds@1952
  2424
       sizeof(pInfo->aCol[0]),
ds@1952
  2425
       3,
ds@1952
  2426
       &pInfo->nColumn,
ds@1952
  2427
       &pInfo->nColumnAlloc,
ds@1952
  2428
       &i
ds@1952
  2429
  );
ds@1952
  2430
  return i;
ds@1952
  2431
}    
ds@1952
  2432
ds@1952
  2433
/*
ds@1952
  2434
** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
ds@1952
  2435
** the new element.  Return a negative number if malloc fails.
ds@1952
  2436
*/
ds@1952
  2437
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
ds@1952
  2438
  int i;
ds@1952
  2439
  pInfo->aFunc = sqlite3ArrayAllocate(
ds@1952
  2440
       db, 
ds@1952
  2441
       pInfo->aFunc,
ds@1952
  2442
       sizeof(pInfo->aFunc[0]),
ds@1952
  2443
       3,
ds@1952
  2444
       &pInfo->nFunc,
ds@1952
  2445
       &pInfo->nFuncAlloc,
ds@1952
  2446
       &i
ds@1952
  2447
  );
ds@1952
  2448
  return i;
ds@1952
  2449
}    
ds@1952
  2450
ds@1952
  2451
/*
ds@1952
  2452
** This is an xFunc for walkExprTree() used to implement 
ds@1952
  2453
** sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
ds@1952
  2454
** for additional information.
ds@1952
  2455
**
ds@1952
  2456
** This routine analyzes the aggregate function at pExpr.
ds@1952
  2457
*/
ds@1952
  2458
static int analyzeAggregate(void *pArg, Expr *pExpr){
ds@1952
  2459
  int i;
ds@1952
  2460
  NameContext *pNC = (NameContext *)pArg;
ds@1952
  2461
  Parse *pParse = pNC->pParse;
ds@1952
  2462
  SrcList *pSrcList = pNC->pSrcList;
ds@1952
  2463
  AggInfo *pAggInfo = pNC->pAggInfo;
ds@1952
  2464
ds@1952
  2465
  switch( pExpr->op ){
ds@1952
  2466
    case TK_AGG_COLUMN:
ds@1952
  2467
    case TK_COLUMN: {
ds@1952
  2468
      /* Check to see if the column is in one of the tables in the FROM
ds@1952
  2469
      ** clause of the aggregate query */
ds@1952
  2470
      if( pSrcList ){
ds@1952
  2471
        struct SrcList_item *pItem = pSrcList->a;
ds@1952
  2472
        for(i=0; i<pSrcList->nSrc; i++, pItem++){
ds@1952
  2473
          struct AggInfo_col *pCol;
ds@1952
  2474
          if( pExpr->iTable==pItem->iCursor ){
ds@1952
  2475
            /* If we reach this point, it means that pExpr refers to a table
ds@1952
  2476
            ** that is in the FROM clause of the aggregate query.  
ds@1952
  2477
            **
ds@1952
  2478
            ** Make an entry for the column in pAggInfo->aCol[] if there
ds@1952
  2479
            ** is not an entry there already.
ds@1952
  2480
            */
ds@1952
  2481
            int k;
ds@1952
  2482
            pCol = pAggInfo->aCol;
ds@1952
  2483
            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
ds@1952
  2484
              if( pCol->iTable==pExpr->iTable &&
ds@1952
  2485
                  pCol->iColumn==pExpr->iColumn ){
ds@1952
  2486
                break;
ds@1952
  2487
              }
ds@1952
  2488
            }
ds@1952
  2489
            if( (k>=pAggInfo->nColumn)
ds@1952
  2490
             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
ds@1952
  2491
            ){
ds@1952
  2492
              pCol = &pAggInfo->aCol[k];
ds@1952
  2493
              pCol->pTab = pExpr->pTab;
ds@1952
  2494
              pCol->iTable = pExpr->iTable;
ds@1952
  2495
              pCol->iColumn = pExpr->iColumn;
ds@1952
  2496
              pCol->iMem = pParse->nMem++;
ds@1952
  2497
              pCol->iSorterColumn = -1;
ds@1952
  2498
              pCol->pExpr = pExpr;
ds@1952
  2499
              if( pAggInfo->pGroupBy ){
ds@1952
  2500
                int j, n;
ds@1952
  2501
                ExprList *pGB = pAggInfo->pGroupBy;
ds@1952
  2502
                struct ExprList_item *pTerm = pGB->a;
ds@1952
  2503
                n = pGB->nExpr;
ds@1952
  2504
                for(j=0; j<n; j++, pTerm++){
ds@1952
  2505
                  Expr *pE = pTerm->pExpr;
ds@1952
  2506
                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
ds@1952
  2507
                      pE->iColumn==pExpr->iColumn ){
ds@1952
  2508
                    pCol->iSorterColumn = j;
ds@1952
  2509
                    break;
ds@1952
  2510
                  }
ds@1952
  2511
                }
ds@1952
  2512
              }
ds@1952
  2513
              if( pCol->iSorterColumn<0 ){
ds@1952
  2514
                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
ds@1952
  2515
              }
ds@1952
  2516
            }
ds@1952
  2517
            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
ds@1952
  2518
            ** because it was there before or because we just created it).
ds@1952
  2519
            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
ds@1952
  2520
            ** pAggInfo->aCol[] entry.
ds@1952
  2521
            */
ds@1952
  2522
            pExpr->pAggInfo = pAggInfo;
ds@1952
  2523
            pExpr->op = TK_AGG_COLUMN;
ds@1952
  2524
            pExpr->iAgg = k;
ds@1952
  2525
            break;
ds@1952
  2526
          } /* endif pExpr->iTable==pItem->iCursor */
ds@1952
  2527
        } /* end loop over pSrcList */
ds@1952
  2528
      }
ds@1952
  2529
      return 1;
ds@1952
  2530
    }
ds@1952
  2531
    case TK_AGG_FUNCTION: {
ds@1952
  2532
      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
ds@1952
  2533
      ** to be ignored */
ds@1952
  2534
      if( pNC->nDepth==0 ){
ds@1952
  2535
        /* Check to see if pExpr is a duplicate of another aggregate 
ds@1952
  2536
        ** function that is already in the pAggInfo structure
ds@1952
  2537
        */
ds@1952
  2538
        struct AggInfo_func *pItem = pAggInfo->aFunc;
ds@1952
  2539
        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
ds@1952
  2540
          if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
ds@1952
  2541
            break;
ds@1952
  2542
          }
ds@1952
  2543
        }
ds@1952
  2544
        if( i>=pAggInfo->nFunc ){
ds@1952
  2545
          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
ds@1952
  2546
          */
ds@1952
  2547
          u8 enc = ENC(pParse->db);
ds@1952
  2548
          i = addAggInfoFunc(pParse->db, pAggInfo);
ds@1952
  2549
          if( i>=0 ){
ds@1952
  2550
            pItem = &pAggInfo->aFunc[i];
ds@1952
  2551
            pItem->pExpr = pExpr;
ds@1952
  2552
            pItem->iMem = pParse->nMem++;
ds@1952
  2553
            pItem->pFunc = sqlite3FindFunction(pParse->db,
ds@1952
  2554
                   (char*)pExpr->token.z, pExpr->token.n,
ds@1952
  2555
                   pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
ds@1952
  2556
            if( pExpr->flags & EP_Distinct ){
ds@1952
  2557
              pItem->iDistinct = pParse->nTab++;
ds@1952
  2558
            }else{
ds@1952
  2559
              pItem->iDistinct = -1;
ds@1952
  2560
            }
ds@1952
  2561
          }
ds@1952
  2562
        }
ds@1952
  2563
        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
ds@1952
  2564
        */
ds@1952
  2565
        pExpr->iAgg = i;
ds@1952
  2566
        pExpr->pAggInfo = pAggInfo;
ds@1952
  2567
        return 1;
ds@1952
  2568
      }
ds@1952
  2569
    }
ds@1952
  2570
  }
ds@1952
  2571
ds@1952
  2572
  /* Recursively walk subqueries looking for TK_COLUMN nodes that need
ds@1952
  2573
  ** to be changed to TK_AGG_COLUMN.  But increment nDepth so that
ds@1952
  2574
  ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
ds@1952
  2575
  */
ds@1952
  2576
  if( pExpr->pSelect ){
ds@1952
  2577
    pNC->nDepth++;
ds@1952
  2578
    walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
ds@1952
  2579
    pNC->nDepth--;
ds@1952
  2580
  }
ds@1952
  2581
  return 0;
ds@1952
  2582
}
ds@1952
  2583
ds@1952
  2584
/*
ds@1952
  2585
** Analyze the given expression looking for aggregate functions and
ds@1952
  2586
** for variables that need to be added to the pParse->aAgg[] array.
ds@1952
  2587
** Make additional entries to the pParse->aAgg[] array as necessary.
ds@1952
  2588
**
ds@1952
  2589
** This routine should only be called after the expression has been
ds@1952
  2590
** analyzed by sqlite3ExprResolveNames().
ds@1952
  2591
**
ds@1952
  2592
** If errors are seen, leave an error message in zErrMsg and return
ds@1952
  2593
** the number of errors.
ds@1952
  2594
*/
ds@1952
  2595
int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
ds@1952
  2596
  int nErr = pNC->pParse->nErr;
ds@1952
  2597
  walkExprTree(pExpr, analyzeAggregate, pNC);
ds@1952
  2598
  return pNC->pParse->nErr - nErr;
ds@1952
  2599
}
ds@1952
  2600
ds@1952
  2601
/*
ds@1952
  2602
** Call sqlite3ExprAnalyzeAggregates() for every expression in an
ds@1952
  2603
** expression list.  Return the number of errors.
ds@1952
  2604
**
ds@1952
  2605
** If an error is found, the analysis is cut short.
ds@1952
  2606
*/
ds@1952
  2607
int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
ds@1952
  2608
  struct ExprList_item *pItem;
ds@1952
  2609
  int i;
ds@1952
  2610
  int nErr = 0;
ds@1952
  2611
  if( pList ){
ds@1952
  2612
    for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
ds@1952
  2613
      nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
ds@1952
  2614
    }
ds@1952
  2615
  }
ds@1952
  2616
  return nErr;
ds@1952
  2617
}