1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/os/persistentdata/persistentstorage/sql/SQLite/expr.c Fri Jun 15 03:10:57 2012 +0200
1.3 @@ -0,0 +1,3586 @@
1.4 +/*
1.5 +** 2001 September 15
1.6 +**
1.7 +** The author disclaims copyright to this source code. In place of
1.8 +** a legal notice, here is a blessing:
1.9 +**
1.10 +** May you do good and not evil.
1.11 +** May you find forgiveness for yourself and forgive others.
1.12 +** May you share freely, never taking more than you give.
1.13 +**
1.14 +*************************************************************************
1.15 +** This file contains routines used for analyzing expressions and
1.16 +** for generating VDBE code that evaluates expressions in SQLite.
1.17 +**
1.18 +** $Id: expr.c,v 1.387 2008/07/28 19:34:53 drh Exp $
1.19 +*/
1.20 +#include "sqliteInt.h"
1.21 +#include <ctype.h>
1.22 +
1.23 +/*
1.24 +** Return the 'affinity' of the expression pExpr if any.
1.25 +**
1.26 +** If pExpr is a column, a reference to a column via an 'AS' alias,
1.27 +** or a sub-select with a column as the return value, then the
1.28 +** affinity of that column is returned. Otherwise, 0x00 is returned,
1.29 +** indicating no affinity for the expression.
1.30 +**
1.31 +** i.e. the WHERE clause expresssions in the following statements all
1.32 +** have an affinity:
1.33 +**
1.34 +** CREATE TABLE t1(a);
1.35 +** SELECT * FROM t1 WHERE a;
1.36 +** SELECT a AS b FROM t1 WHERE b;
1.37 +** SELECT * FROM t1 WHERE (select a from t1);
1.38 +*/
1.39 +char sqlite3ExprAffinity(Expr *pExpr){
1.40 + int op = pExpr->op;
1.41 + if( op==TK_SELECT ){
1.42 + return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
1.43 + }
1.44 +#ifndef SQLITE_OMIT_CAST
1.45 + if( op==TK_CAST ){
1.46 + return sqlite3AffinityType(&pExpr->token);
1.47 + }
1.48 +#endif
1.49 + return pExpr->affinity;
1.50 +}
1.51 +
1.52 +/*
1.53 +** Set the collating sequence for expression pExpr to be the collating
1.54 +** sequence named by pToken. Return a pointer to the revised expression.
1.55 +** The collating sequence is marked as "explicit" using the EP_ExpCollate
1.56 +** flag. An explicit collating sequence will override implicit
1.57 +** collating sequences.
1.58 +*/
1.59 +Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
1.60 + char *zColl = 0; /* Dequoted name of collation sequence */
1.61 + CollSeq *pColl;
1.62 + sqlite3 *db = pParse->db;
1.63 + zColl = sqlite3NameFromToken(db, pName);
1.64 + if( pExpr && zColl ){
1.65 + pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
1.66 + if( pColl ){
1.67 + pExpr->pColl = pColl;
1.68 + pExpr->flags |= EP_ExpCollate;
1.69 + }
1.70 + }
1.71 + sqlite3DbFree(db, zColl);
1.72 + return pExpr;
1.73 +}
1.74 +
1.75 +/*
1.76 +** Return the default collation sequence for the expression pExpr. If
1.77 +** there is no default collation type, return 0.
1.78 +*/
1.79 +CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
1.80 + CollSeq *pColl = 0;
1.81 + if( pExpr ){
1.82 + int op;
1.83 + pColl = pExpr->pColl;
1.84 + op = pExpr->op;
1.85 + if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
1.86 + return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1.87 + }
1.88 + }
1.89 + if( sqlite3CheckCollSeq(pParse, pColl) ){
1.90 + pColl = 0;
1.91 + }
1.92 + return pColl;
1.93 +}
1.94 +
1.95 +/*
1.96 +** pExpr is an operand of a comparison operator. aff2 is the
1.97 +** type affinity of the other operand. This routine returns the
1.98 +** type affinity that should be used for the comparison operator.
1.99 +*/
1.100 +char sqlite3CompareAffinity(Expr *pExpr, char aff2){
1.101 + char aff1 = sqlite3ExprAffinity(pExpr);
1.102 + if( aff1 && aff2 ){
1.103 + /* Both sides of the comparison are columns. If one has numeric
1.104 + ** affinity, use that. Otherwise use no affinity.
1.105 + */
1.106 + if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
1.107 + return SQLITE_AFF_NUMERIC;
1.108 + }else{
1.109 + return SQLITE_AFF_NONE;
1.110 + }
1.111 + }else if( !aff1 && !aff2 ){
1.112 + /* Neither side of the comparison is a column. Compare the
1.113 + ** results directly.
1.114 + */
1.115 + return SQLITE_AFF_NONE;
1.116 + }else{
1.117 + /* One side is a column, the other is not. Use the columns affinity. */
1.118 + assert( aff1==0 || aff2==0 );
1.119 + return (aff1 + aff2);
1.120 + }
1.121 +}
1.122 +
1.123 +/*
1.124 +** pExpr is a comparison operator. Return the type affinity that should
1.125 +** be applied to both operands prior to doing the comparison.
1.126 +*/
1.127 +static char comparisonAffinity(Expr *pExpr){
1.128 + char aff;
1.129 + assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
1.130 + pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
1.131 + pExpr->op==TK_NE );
1.132 + assert( pExpr->pLeft );
1.133 + aff = sqlite3ExprAffinity(pExpr->pLeft);
1.134 + if( pExpr->pRight ){
1.135 + aff = sqlite3CompareAffinity(pExpr->pRight, aff);
1.136 + }
1.137 + else if( pExpr->pSelect ){
1.138 + aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
1.139 + }
1.140 + else if( !aff ){
1.141 + aff = SQLITE_AFF_NONE;
1.142 + }
1.143 + return aff;
1.144 +}
1.145 +
1.146 +/*
1.147 +** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
1.148 +** idx_affinity is the affinity of an indexed column. Return true
1.149 +** if the index with affinity idx_affinity may be used to implement
1.150 +** the comparison in pExpr.
1.151 +*/
1.152 +int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
1.153 + char aff = comparisonAffinity(pExpr);
1.154 + switch( aff ){
1.155 + case SQLITE_AFF_NONE:
1.156 + return 1;
1.157 + case SQLITE_AFF_TEXT:
1.158 + return idx_affinity==SQLITE_AFF_TEXT;
1.159 + default:
1.160 + return sqlite3IsNumericAffinity(idx_affinity);
1.161 + }
1.162 +}
1.163 +
1.164 +/*
1.165 +** Return the P5 value that should be used for a binary comparison
1.166 +** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
1.167 +*/
1.168 +static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
1.169 + u8 aff = (char)sqlite3ExprAffinity(pExpr2);
1.170 + aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
1.171 + return aff;
1.172 +}
1.173 +
1.174 +/*
1.175 +** Return a pointer to the collation sequence that should be used by
1.176 +** a binary comparison operator comparing pLeft and pRight.
1.177 +**
1.178 +** If the left hand expression has a collating sequence type, then it is
1.179 +** used. Otherwise the collation sequence for the right hand expression
1.180 +** is used, or the default (BINARY) if neither expression has a collating
1.181 +** type.
1.182 +**
1.183 +** Argument pRight (but not pLeft) may be a null pointer. In this case,
1.184 +** it is not considered.
1.185 +*/
1.186 +CollSeq *sqlite3BinaryCompareCollSeq(
1.187 + Parse *pParse,
1.188 + Expr *pLeft,
1.189 + Expr *pRight
1.190 +){
1.191 + CollSeq *pColl;
1.192 + assert( pLeft );
1.193 + if( pLeft->flags & EP_ExpCollate ){
1.194 + assert( pLeft->pColl );
1.195 + pColl = pLeft->pColl;
1.196 + }else if( pRight && pRight->flags & EP_ExpCollate ){
1.197 + assert( pRight->pColl );
1.198 + pColl = pRight->pColl;
1.199 + }else{
1.200 + pColl = sqlite3ExprCollSeq(pParse, pLeft);
1.201 + if( !pColl ){
1.202 + pColl = sqlite3ExprCollSeq(pParse, pRight);
1.203 + }
1.204 + }
1.205 + return pColl;
1.206 +}
1.207 +
1.208 +/*
1.209 +** Generate the operands for a comparison operation. Before
1.210 +** generating the code for each operand, set the EP_AnyAff
1.211 +** flag on the expression so that it will be able to used a
1.212 +** cached column value that has previously undergone an
1.213 +** affinity change.
1.214 +*/
1.215 +static void codeCompareOperands(
1.216 + Parse *pParse, /* Parsing and code generating context */
1.217 + Expr *pLeft, /* The left operand */
1.218 + int *pRegLeft, /* Register where left operand is stored */
1.219 + int *pFreeLeft, /* Free this register when done */
1.220 + Expr *pRight, /* The right operand */
1.221 + int *pRegRight, /* Register where right operand is stored */
1.222 + int *pFreeRight /* Write temp register for right operand there */
1.223 +){
1.224 + while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
1.225 + pLeft->flags |= EP_AnyAff;
1.226 + *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
1.227 + while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
1.228 + pRight->flags |= EP_AnyAff;
1.229 + *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
1.230 +}
1.231 +
1.232 +/*
1.233 +** Generate code for a comparison operator.
1.234 +*/
1.235 +static int codeCompare(
1.236 + Parse *pParse, /* The parsing (and code generating) context */
1.237 + Expr *pLeft, /* The left operand */
1.238 + Expr *pRight, /* The right operand */
1.239 + int opcode, /* The comparison opcode */
1.240 + int in1, int in2, /* Register holding operands */
1.241 + int dest, /* Jump here if true. */
1.242 + int jumpIfNull /* If true, jump if either operand is NULL */
1.243 +){
1.244 + int p5;
1.245 + int addr;
1.246 + CollSeq *p4;
1.247 +
1.248 + p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
1.249 + p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
1.250 + addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
1.251 + (void*)p4, P4_COLLSEQ);
1.252 + sqlite3VdbeChangeP5(pParse->pVdbe, p5);
1.253 + if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
1.254 + sqlite3ExprCacheAffinityChange(pParse, in1, 1);
1.255 + sqlite3ExprCacheAffinityChange(pParse, in2, 1);
1.256 + }
1.257 + return addr;
1.258 +}
1.259 +
1.260 +#if SQLITE_MAX_EXPR_DEPTH>0
1.261 +/*
1.262 +** Check that argument nHeight is less than or equal to the maximum
1.263 +** expression depth allowed. If it is not, leave an error message in
1.264 +** pParse.
1.265 +*/
1.266 +static int checkExprHeight(Parse *pParse, int nHeight){
1.267 + int rc = SQLITE_OK;
1.268 + int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
1.269 + if( nHeight>mxHeight ){
1.270 + sqlite3ErrorMsg(pParse,
1.271 + "Expression tree is too large (maximum depth %d)", mxHeight
1.272 + );
1.273 + rc = SQLITE_ERROR;
1.274 + }
1.275 + return rc;
1.276 +}
1.277 +
1.278 +/* The following three functions, heightOfExpr(), heightOfExprList()
1.279 +** and heightOfSelect(), are used to determine the maximum height
1.280 +** of any expression tree referenced by the structure passed as the
1.281 +** first argument.
1.282 +**
1.283 +** If this maximum height is greater than the current value pointed
1.284 +** to by pnHeight, the second parameter, then set *pnHeight to that
1.285 +** value.
1.286 +*/
1.287 +static void heightOfExpr(Expr *p, int *pnHeight){
1.288 + if( p ){
1.289 + if( p->nHeight>*pnHeight ){
1.290 + *pnHeight = p->nHeight;
1.291 + }
1.292 + }
1.293 +}
1.294 +static void heightOfExprList(ExprList *p, int *pnHeight){
1.295 + if( p ){
1.296 + int i;
1.297 + for(i=0; i<p->nExpr; i++){
1.298 + heightOfExpr(p->a[i].pExpr, pnHeight);
1.299 + }
1.300 + }
1.301 +}
1.302 +static void heightOfSelect(Select *p, int *pnHeight){
1.303 + if( p ){
1.304 + heightOfExpr(p->pWhere, pnHeight);
1.305 + heightOfExpr(p->pHaving, pnHeight);
1.306 + heightOfExpr(p->pLimit, pnHeight);
1.307 + heightOfExpr(p->pOffset, pnHeight);
1.308 + heightOfExprList(p->pEList, pnHeight);
1.309 + heightOfExprList(p->pGroupBy, pnHeight);
1.310 + heightOfExprList(p->pOrderBy, pnHeight);
1.311 + heightOfSelect(p->pPrior, pnHeight);
1.312 + }
1.313 +}
1.314 +
1.315 +/*
1.316 +** Set the Expr.nHeight variable in the structure passed as an
1.317 +** argument. An expression with no children, Expr.pList or
1.318 +** Expr.pSelect member has a height of 1. Any other expression
1.319 +** has a height equal to the maximum height of any other
1.320 +** referenced Expr plus one.
1.321 +*/
1.322 +static void exprSetHeight(Expr *p){
1.323 + int nHeight = 0;
1.324 + heightOfExpr(p->pLeft, &nHeight);
1.325 + heightOfExpr(p->pRight, &nHeight);
1.326 + heightOfExprList(p->pList, &nHeight);
1.327 + heightOfSelect(p->pSelect, &nHeight);
1.328 + p->nHeight = nHeight + 1;
1.329 +}
1.330 +
1.331 +/*
1.332 +** Set the Expr.nHeight variable using the exprSetHeight() function. If
1.333 +** the height is greater than the maximum allowed expression depth,
1.334 +** leave an error in pParse.
1.335 +*/
1.336 +void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
1.337 + exprSetHeight(p);
1.338 + checkExprHeight(pParse, p->nHeight);
1.339 +}
1.340 +
1.341 +/*
1.342 +** Return the maximum height of any expression tree referenced
1.343 +** by the select statement passed as an argument.
1.344 +*/
1.345 +int sqlite3SelectExprHeight(Select *p){
1.346 + int nHeight = 0;
1.347 + heightOfSelect(p, &nHeight);
1.348 + return nHeight;
1.349 +}
1.350 +#else
1.351 + #define checkExprHeight(x,y)
1.352 + #define exprSetHeight(y)
1.353 +#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
1.354 +
1.355 +/*
1.356 +** Construct a new expression node and return a pointer to it. Memory
1.357 +** for this node is obtained from sqlite3_malloc(). The calling function
1.358 +** is responsible for making sure the node eventually gets freed.
1.359 +*/
1.360 +Expr *sqlite3Expr(
1.361 + sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
1.362 + int op, /* Expression opcode */
1.363 + Expr *pLeft, /* Left operand */
1.364 + Expr *pRight, /* Right operand */
1.365 + const Token *pToken /* Argument token */
1.366 +){
1.367 + Expr *pNew;
1.368 + pNew = sqlite3DbMallocZero(db, sizeof(Expr));
1.369 + if( pNew==0 ){
1.370 + /* When malloc fails, delete pLeft and pRight. Expressions passed to
1.371 + ** this function must always be allocated with sqlite3Expr() for this
1.372 + ** reason.
1.373 + */
1.374 + sqlite3ExprDelete(db, pLeft);
1.375 + sqlite3ExprDelete(db, pRight);
1.376 + return 0;
1.377 + }
1.378 + pNew->op = op;
1.379 + pNew->pLeft = pLeft;
1.380 + pNew->pRight = pRight;
1.381 + pNew->iAgg = -1;
1.382 + pNew->span.z = (u8*)"";
1.383 + if( pToken ){
1.384 + assert( pToken->dyn==0 );
1.385 + pNew->span = pNew->token = *pToken;
1.386 + }else if( pLeft ){
1.387 + if( pRight ){
1.388 + if( pRight->span.dyn==0 && pLeft->span.dyn==0 ){
1.389 + sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
1.390 + }
1.391 + if( pRight->flags & EP_ExpCollate ){
1.392 + pNew->flags |= EP_ExpCollate;
1.393 + pNew->pColl = pRight->pColl;
1.394 + }
1.395 + }
1.396 + if( pLeft->flags & EP_ExpCollate ){
1.397 + pNew->flags |= EP_ExpCollate;
1.398 + pNew->pColl = pLeft->pColl;
1.399 + }
1.400 + }
1.401 +
1.402 + exprSetHeight(pNew);
1.403 + return pNew;
1.404 +}
1.405 +
1.406 +/*
1.407 +** Works like sqlite3Expr() except that it takes an extra Parse*
1.408 +** argument and notifies the associated connection object if malloc fails.
1.409 +*/
1.410 +Expr *sqlite3PExpr(
1.411 + Parse *pParse, /* Parsing context */
1.412 + int op, /* Expression opcode */
1.413 + Expr *pLeft, /* Left operand */
1.414 + Expr *pRight, /* Right operand */
1.415 + const Token *pToken /* Argument token */
1.416 +){
1.417 + Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
1.418 + if( p ){
1.419 + checkExprHeight(pParse, p->nHeight);
1.420 + }
1.421 + return p;
1.422 +}
1.423 +
1.424 +/*
1.425 +** When doing a nested parse, you can include terms in an expression
1.426 +** that look like this: #1 #2 ... These terms refer to registers
1.427 +** in the virtual machine. #N is the N-th register.
1.428 +**
1.429 +** This routine is called by the parser to deal with on of those terms.
1.430 +** It immediately generates code to store the value in a memory location.
1.431 +** The returns an expression that will code to extract the value from
1.432 +** that memory location as needed.
1.433 +*/
1.434 +Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
1.435 + Vdbe *v = pParse->pVdbe;
1.436 + Expr *p;
1.437 + if( pParse->nested==0 ){
1.438 + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
1.439 + return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
1.440 + }
1.441 + if( v==0 ) return 0;
1.442 + p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
1.443 + if( p==0 ){
1.444 + return 0; /* Malloc failed */
1.445 + }
1.446 + p->iTable = atoi((char*)&pToken->z[1]);
1.447 + return p;
1.448 +}
1.449 +
1.450 +/*
1.451 +** Join two expressions using an AND operator. If either expression is
1.452 +** NULL, then just return the other expression.
1.453 +*/
1.454 +Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
1.455 + if( pLeft==0 ){
1.456 + return pRight;
1.457 + }else if( pRight==0 ){
1.458 + return pLeft;
1.459 + }else{
1.460 + return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
1.461 + }
1.462 +}
1.463 +
1.464 +/*
1.465 +** Set the Expr.span field of the given expression to span all
1.466 +** text between the two given tokens. Both tokens must be pointing
1.467 +** at the same string.
1.468 +*/
1.469 +void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
1.470 + assert( pRight!=0 );
1.471 + assert( pLeft!=0 );
1.472 + if( pExpr ){
1.473 + pExpr->span.z = pLeft->z;
1.474 + pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
1.475 + }
1.476 +}
1.477 +
1.478 +/*
1.479 +** Construct a new expression node for a function with multiple
1.480 +** arguments.
1.481 +*/
1.482 +Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
1.483 + Expr *pNew;
1.484 + sqlite3 *db = pParse->db;
1.485 + assert( pToken );
1.486 + pNew = sqlite3DbMallocZero(db, sizeof(Expr) );
1.487 + if( pNew==0 ){
1.488 + sqlite3ExprListDelete(db, pList); /* Avoid leaking memory when malloc fails */
1.489 + return 0;
1.490 + }
1.491 + pNew->op = TK_FUNCTION;
1.492 + pNew->pList = pList;
1.493 + assert( pToken->dyn==0 );
1.494 + pNew->token = *pToken;
1.495 + pNew->span = pNew->token;
1.496 +
1.497 + sqlite3ExprSetHeight(pParse, pNew);
1.498 + return pNew;
1.499 +}
1.500 +
1.501 +/*
1.502 +** Assign a variable number to an expression that encodes a wildcard
1.503 +** in the original SQL statement.
1.504 +**
1.505 +** Wildcards consisting of a single "?" are assigned the next sequential
1.506 +** variable number.
1.507 +**
1.508 +** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1.509 +** sure "nnn" is not too be to avoid a denial of service attack when
1.510 +** the SQL statement comes from an external source.
1.511 +**
1.512 +** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
1.513 +** as the previous instance of the same wildcard. Or if this is the first
1.514 +** instance of the wildcard, the next sequenial variable number is
1.515 +** assigned.
1.516 +*/
1.517 +void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
1.518 + Token *pToken;
1.519 + sqlite3 *db = pParse->db;
1.520 +
1.521 + if( pExpr==0 ) return;
1.522 + pToken = &pExpr->token;
1.523 + assert( pToken->n>=1 );
1.524 + assert( pToken->z!=0 );
1.525 + assert( pToken->z[0]!=0 );
1.526 + if( pToken->n==1 ){
1.527 + /* Wildcard of the form "?". Assign the next variable number */
1.528 + pExpr->iTable = ++pParse->nVar;
1.529 + }else if( pToken->z[0]=='?' ){
1.530 + /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1.531 + ** use it as the variable number */
1.532 + int i;
1.533 + pExpr->iTable = i = atoi((char*)&pToken->z[1]);
1.534 + testcase( i==0 );
1.535 + testcase( i==1 );
1.536 + testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1.537 + testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1.538 + if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1.539 + sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1.540 + db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1.541 + }
1.542 + if( i>pParse->nVar ){
1.543 + pParse->nVar = i;
1.544 + }
1.545 + }else{
1.546 + /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
1.547 + ** number as the prior appearance of the same name, or if the name
1.548 + ** has never appeared before, reuse the same variable number
1.549 + */
1.550 + int i, n;
1.551 + n = pToken->n;
1.552 + for(i=0; i<pParse->nVarExpr; i++){
1.553 + Expr *pE;
1.554 + if( (pE = pParse->apVarExpr[i])!=0
1.555 + && pE->token.n==n
1.556 + && memcmp(pE->token.z, pToken->z, n)==0 ){
1.557 + pExpr->iTable = pE->iTable;
1.558 + break;
1.559 + }
1.560 + }
1.561 + if( i>=pParse->nVarExpr ){
1.562 + pExpr->iTable = ++pParse->nVar;
1.563 + if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
1.564 + pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
1.565 + pParse->apVarExpr =
1.566 + sqlite3DbReallocOrFree(
1.567 + db,
1.568 + pParse->apVarExpr,
1.569 + pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
1.570 + );
1.571 + }
1.572 + if( !db->mallocFailed ){
1.573 + assert( pParse->apVarExpr!=0 );
1.574 + pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
1.575 + }
1.576 + }
1.577 + }
1.578 + if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1.579 + sqlite3ErrorMsg(pParse, "too many SQL variables");
1.580 + }
1.581 +}
1.582 +
1.583 +/*
1.584 +** Recursively delete an expression tree.
1.585 +*/
1.586 +void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1.587 + if( p==0 ) return;
1.588 + if( p->span.dyn ) sqlite3DbFree(db, (char*)p->span.z);
1.589 + if( p->token.dyn ) sqlite3DbFree(db, (char*)p->token.z);
1.590 + sqlite3ExprDelete(db, p->pLeft);
1.591 + sqlite3ExprDelete(db, p->pRight);
1.592 + sqlite3ExprListDelete(db, p->pList);
1.593 + sqlite3SelectDelete(db, p->pSelect);
1.594 + sqlite3DbFree(db, p);
1.595 +}
1.596 +
1.597 +/*
1.598 +** The Expr.token field might be a string literal that is quoted.
1.599 +** If so, remove the quotation marks.
1.600 +*/
1.601 +void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
1.602 + if( ExprHasAnyProperty(p, EP_Dequoted) ){
1.603 + return;
1.604 + }
1.605 + ExprSetProperty(p, EP_Dequoted);
1.606 + if( p->token.dyn==0 ){
1.607 + sqlite3TokenCopy(db, &p->token, &p->token);
1.608 + }
1.609 + sqlite3Dequote((char*)p->token.z);
1.610 +}
1.611 +
1.612 +
1.613 +/*
1.614 +** The following group of routines make deep copies of expressions,
1.615 +** expression lists, ID lists, and select statements. The copies can
1.616 +** be deleted (by being passed to their respective ...Delete() routines)
1.617 +** without effecting the originals.
1.618 +**
1.619 +** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1.620 +** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1.621 +** by subsequent calls to sqlite*ListAppend() routines.
1.622 +**
1.623 +** Any tables that the SrcList might point to are not duplicated.
1.624 +*/
1.625 +Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
1.626 + Expr *pNew;
1.627 + if( p==0 ) return 0;
1.628 + pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
1.629 + if( pNew==0 ) return 0;
1.630 + memcpy(pNew, p, sizeof(*pNew));
1.631 + if( p->token.z!=0 ){
1.632 + pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
1.633 + pNew->token.dyn = 1;
1.634 + }else{
1.635 + assert( pNew->token.z==0 );
1.636 + }
1.637 + pNew->span.z = 0;
1.638 + pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
1.639 + pNew->pRight = sqlite3ExprDup(db, p->pRight);
1.640 + pNew->pList = sqlite3ExprListDup(db, p->pList);
1.641 + pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
1.642 + return pNew;
1.643 +}
1.644 +void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
1.645 + if( pTo->dyn ) sqlite3DbFree(db, (char*)pTo->z);
1.646 + if( pFrom->z ){
1.647 + pTo->n = pFrom->n;
1.648 + pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
1.649 + pTo->dyn = 1;
1.650 + }else{
1.651 + pTo->z = 0;
1.652 + }
1.653 +}
1.654 +ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
1.655 + ExprList *pNew;
1.656 + struct ExprList_item *pItem, *pOldItem;
1.657 + int i;
1.658 + if( p==0 ) return 0;
1.659 + pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
1.660 + if( pNew==0 ) return 0;
1.661 + pNew->iECursor = 0;
1.662 + pNew->nExpr = pNew->nAlloc = p->nExpr;
1.663 + pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
1.664 + if( pItem==0 ){
1.665 + sqlite3DbFree(db, pNew);
1.666 + return 0;
1.667 + }
1.668 + pOldItem = p->a;
1.669 + for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1.670 + Expr *pNewExpr, *pOldExpr;
1.671 + pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
1.672 + if( pOldExpr->span.z!=0 && pNewExpr ){
1.673 + /* Always make a copy of the span for top-level expressions in the
1.674 + ** expression list. The logic in SELECT processing that determines
1.675 + ** the names of columns in the result set needs this information */
1.676 + sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
1.677 + }
1.678 + assert( pNewExpr==0 || pNewExpr->span.z!=0
1.679 + || pOldExpr->span.z==0
1.680 + || db->mallocFailed );
1.681 + pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1.682 + pItem->sortOrder = pOldItem->sortOrder;
1.683 + pItem->isAgg = pOldItem->isAgg;
1.684 + pItem->done = 0;
1.685 + }
1.686 + return pNew;
1.687 +}
1.688 +
1.689 +/*
1.690 +** If cursors, triggers, views and subqueries are all omitted from
1.691 +** the build, then none of the following routines, except for
1.692 +** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1.693 +** called with a NULL argument.
1.694 +*/
1.695 +#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1.696 + || !defined(SQLITE_OMIT_SUBQUERY)
1.697 +SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
1.698 + SrcList *pNew;
1.699 + int i;
1.700 + int nByte;
1.701 + if( p==0 ) return 0;
1.702 + nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1.703 + pNew = sqlite3DbMallocRaw(db, nByte );
1.704 + if( pNew==0 ) return 0;
1.705 + pNew->nSrc = pNew->nAlloc = p->nSrc;
1.706 + for(i=0; i<p->nSrc; i++){
1.707 + struct SrcList_item *pNewItem = &pNew->a[i];
1.708 + struct SrcList_item *pOldItem = &p->a[i];
1.709 + Table *pTab;
1.710 + pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1.711 + pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1.712 + pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1.713 + pNewItem->jointype = pOldItem->jointype;
1.714 + pNewItem->iCursor = pOldItem->iCursor;
1.715 + pNewItem->isPopulated = pOldItem->isPopulated;
1.716 + pTab = pNewItem->pTab = pOldItem->pTab;
1.717 + if( pTab ){
1.718 + pTab->nRef++;
1.719 + }
1.720 + pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
1.721 + pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
1.722 + pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
1.723 + pNewItem->colUsed = pOldItem->colUsed;
1.724 + }
1.725 + return pNew;
1.726 +}
1.727 +IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1.728 + IdList *pNew;
1.729 + int i;
1.730 + if( p==0 ) return 0;
1.731 + pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
1.732 + if( pNew==0 ) return 0;
1.733 + pNew->nId = pNew->nAlloc = p->nId;
1.734 + pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
1.735 + if( pNew->a==0 ){
1.736 + sqlite3DbFree(db, pNew);
1.737 + return 0;
1.738 + }
1.739 + for(i=0; i<p->nId; i++){
1.740 + struct IdList_item *pNewItem = &pNew->a[i];
1.741 + struct IdList_item *pOldItem = &p->a[i];
1.742 + pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1.743 + pNewItem->idx = pOldItem->idx;
1.744 + }
1.745 + return pNew;
1.746 +}
1.747 +Select *sqlite3SelectDup(sqlite3 *db, Select *p){
1.748 + Select *pNew;
1.749 + if( p==0 ) return 0;
1.750 + pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
1.751 + if( pNew==0 ) return 0;
1.752 + pNew->isDistinct = p->isDistinct;
1.753 + pNew->pEList = sqlite3ExprListDup(db, p->pEList);
1.754 + pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
1.755 + pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
1.756 + pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
1.757 + pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
1.758 + pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
1.759 + pNew->op = p->op;
1.760 + pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
1.761 + pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
1.762 + pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
1.763 + pNew->iLimit = 0;
1.764 + pNew->iOffset = 0;
1.765 + pNew->isResolved = p->isResolved;
1.766 + pNew->isAgg = p->isAgg;
1.767 + pNew->usesEphm = 0;
1.768 + pNew->disallowOrderBy = 0;
1.769 + pNew->pRightmost = 0;
1.770 + pNew->addrOpenEphm[0] = -1;
1.771 + pNew->addrOpenEphm[1] = -1;
1.772 + pNew->addrOpenEphm[2] = -1;
1.773 + return pNew;
1.774 +}
1.775 +#else
1.776 +Select *sqlite3SelectDup(sqlite3 *db, Select *p){
1.777 + assert( p==0 );
1.778 + return 0;
1.779 +}
1.780 +#endif
1.781 +
1.782 +
1.783 +/*
1.784 +** Add a new element to the end of an expression list. If pList is
1.785 +** initially NULL, then create a new expression list.
1.786 +*/
1.787 +ExprList *sqlite3ExprListAppend(
1.788 + Parse *pParse, /* Parsing context */
1.789 + ExprList *pList, /* List to which to append. Might be NULL */
1.790 + Expr *pExpr, /* Expression to be appended */
1.791 + Token *pName /* AS keyword for the expression */
1.792 +){
1.793 + sqlite3 *db = pParse->db;
1.794 + if( pList==0 ){
1.795 + pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
1.796 + if( pList==0 ){
1.797 + goto no_mem;
1.798 + }
1.799 + assert( pList->nAlloc==0 );
1.800 + }
1.801 + if( pList->nAlloc<=pList->nExpr ){
1.802 + struct ExprList_item *a;
1.803 + int n = pList->nAlloc*2 + 4;
1.804 + a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
1.805 + if( a==0 ){
1.806 + goto no_mem;
1.807 + }
1.808 + pList->a = a;
1.809 + pList->nAlloc = n;
1.810 + }
1.811 + assert( pList->a!=0 );
1.812 + if( pExpr || pName ){
1.813 + struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1.814 + memset(pItem, 0, sizeof(*pItem));
1.815 + pItem->zName = sqlite3NameFromToken(db, pName);
1.816 + pItem->pExpr = pExpr;
1.817 + }
1.818 + return pList;
1.819 +
1.820 +no_mem:
1.821 + /* Avoid leaking memory if malloc has failed. */
1.822 + sqlite3ExprDelete(db, pExpr);
1.823 + sqlite3ExprListDelete(db, pList);
1.824 + return 0;
1.825 +}
1.826 +
1.827 +/*
1.828 +** If the expression list pEList contains more than iLimit elements,
1.829 +** leave an error message in pParse.
1.830 +*/
1.831 +void sqlite3ExprListCheckLength(
1.832 + Parse *pParse,
1.833 + ExprList *pEList,
1.834 + const char *zObject
1.835 +){
1.836 + int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1.837 + testcase( pEList && pEList->nExpr==mx );
1.838 + testcase( pEList && pEList->nExpr==mx+1 );
1.839 + if( pEList && pEList->nExpr>mx ){
1.840 + sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1.841 + }
1.842 +}
1.843 +
1.844 +/*
1.845 +** Delete an entire expression list.
1.846 +*/
1.847 +void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1.848 + int i;
1.849 + struct ExprList_item *pItem;
1.850 + if( pList==0 ) return;
1.851 + assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
1.852 + assert( pList->nExpr<=pList->nAlloc );
1.853 + for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1.854 + sqlite3ExprDelete(db, pItem->pExpr);
1.855 + sqlite3DbFree(db, pItem->zName);
1.856 + }
1.857 + sqlite3DbFree(db, pList->a);
1.858 + sqlite3DbFree(db, pList);
1.859 +}
1.860 +
1.861 +/*
1.862 +** Walk an expression tree. Call xFunc for each node visited. xFunc
1.863 +** is called on the node before xFunc is called on the nodes children.
1.864 +**
1.865 +** The return value from xFunc determines whether the tree walk continues.
1.866 +** 0 means continue walking the tree. 1 means do not walk children
1.867 +** of the current node but continue with siblings. 2 means abandon
1.868 +** the tree walk completely.
1.869 +**
1.870 +** The return value from this routine is 1 to abandon the tree walk
1.871 +** and 0 to continue.
1.872 +**
1.873 +** NOTICE: This routine does *not* descend into subqueries.
1.874 +*/
1.875 +static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
1.876 +static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
1.877 + int rc;
1.878 + if( pExpr==0 ) return 0;
1.879 + rc = (*xFunc)(pArg, pExpr);
1.880 + if( rc==0 ){
1.881 + if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
1.882 + if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
1.883 + if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
1.884 + }
1.885 + return rc>1;
1.886 +}
1.887 +
1.888 +/*
1.889 +** Call walkExprTree() for every expression in list p.
1.890 +*/
1.891 +static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
1.892 + int i;
1.893 + struct ExprList_item *pItem;
1.894 + if( !p ) return 0;
1.895 + for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
1.896 + if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
1.897 + }
1.898 + return 0;
1.899 +}
1.900 +
1.901 +/*
1.902 +** Call walkExprTree() for every expression in Select p, not including
1.903 +** expressions that are part of sub-selects in any FROM clause or the LIMIT
1.904 +** or OFFSET expressions..
1.905 +*/
1.906 +static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
1.907 + walkExprList(p->pEList, xFunc, pArg);
1.908 + walkExprTree(p->pWhere, xFunc, pArg);
1.909 + walkExprList(p->pGroupBy, xFunc, pArg);
1.910 + walkExprTree(p->pHaving, xFunc, pArg);
1.911 + walkExprList(p->pOrderBy, xFunc, pArg);
1.912 + if( p->pPrior ){
1.913 + walkSelectExpr(p->pPrior, xFunc, pArg);
1.914 + }
1.915 + return 0;
1.916 +}
1.917 +
1.918 +
1.919 +/*
1.920 +** This routine is designed as an xFunc for walkExprTree().
1.921 +**
1.922 +** pArg is really a pointer to an integer. If we can tell by looking
1.923 +** at pExpr that the expression that contains pExpr is not a constant
1.924 +** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
1.925 +** If pExpr does does not disqualify the expression from being a constant
1.926 +** then do nothing.
1.927 +**
1.928 +** After walking the whole tree, if no nodes are found that disqualify
1.929 +** the expression as constant, then we assume the whole expression
1.930 +** is constant. See sqlite3ExprIsConstant() for additional information.
1.931 +*/
1.932 +static int exprNodeIsConstant(void *pArg, Expr *pExpr){
1.933 + int *pN = (int*)pArg;
1.934 +
1.935 + /* If *pArg is 3 then any term of the expression that comes from
1.936 + ** the ON or USING clauses of a join disqualifies the expression
1.937 + ** from being considered constant. */
1.938 + if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
1.939 + *pN = 0;
1.940 + return 2;
1.941 + }
1.942 +
1.943 + switch( pExpr->op ){
1.944 + /* Consider functions to be constant if all their arguments are constant
1.945 + ** and *pArg==2 */
1.946 + case TK_FUNCTION:
1.947 + if( (*pN)==2 ) return 0;
1.948 + /* Fall through */
1.949 + case TK_ID:
1.950 + case TK_COLUMN:
1.951 + case TK_DOT:
1.952 + case TK_AGG_FUNCTION:
1.953 + case TK_AGG_COLUMN:
1.954 +#ifndef SQLITE_OMIT_SUBQUERY
1.955 + case TK_SELECT:
1.956 + case TK_EXISTS:
1.957 + testcase( pExpr->op==TK_SELECT );
1.958 + testcase( pExpr->op==TK_EXISTS );
1.959 +#endif
1.960 + testcase( pExpr->op==TK_ID );
1.961 + testcase( pExpr->op==TK_COLUMN );
1.962 + testcase( pExpr->op==TK_DOT );
1.963 + testcase( pExpr->op==TK_AGG_FUNCTION );
1.964 + testcase( pExpr->op==TK_AGG_COLUMN );
1.965 + *pN = 0;
1.966 + return 2;
1.967 + case TK_IN:
1.968 + if( pExpr->pSelect ){
1.969 + *pN = 0;
1.970 + return 2;
1.971 + }
1.972 + default:
1.973 + return 0;
1.974 + }
1.975 +}
1.976 +
1.977 +/*
1.978 +** Walk an expression tree. Return 1 if the expression is constant
1.979 +** and 0 if it involves variables or function calls.
1.980 +**
1.981 +** For the purposes of this function, a double-quoted string (ex: "abc")
1.982 +** is considered a variable but a single-quoted string (ex: 'abc') is
1.983 +** a constant.
1.984 +*/
1.985 +int sqlite3ExprIsConstant(Expr *p){
1.986 + int isConst = 1;
1.987 + walkExprTree(p, exprNodeIsConstant, &isConst);
1.988 + return isConst;
1.989 +}
1.990 +
1.991 +/*
1.992 +** Walk an expression tree. Return 1 if the expression is constant
1.993 +** that does no originate from the ON or USING clauses of a join.
1.994 +** Return 0 if it involves variables or function calls or terms from
1.995 +** an ON or USING clause.
1.996 +*/
1.997 +int sqlite3ExprIsConstantNotJoin(Expr *p){
1.998 + int isConst = 3;
1.999 + walkExprTree(p, exprNodeIsConstant, &isConst);
1.1000 + return isConst!=0;
1.1001 +}
1.1002 +
1.1003 +/*
1.1004 +** Walk an expression tree. Return 1 if the expression is constant
1.1005 +** or a function call with constant arguments. Return and 0 if there
1.1006 +** are any variables.
1.1007 +**
1.1008 +** For the purposes of this function, a double-quoted string (ex: "abc")
1.1009 +** is considered a variable but a single-quoted string (ex: 'abc') is
1.1010 +** a constant.
1.1011 +*/
1.1012 +int sqlite3ExprIsConstantOrFunction(Expr *p){
1.1013 + int isConst = 2;
1.1014 + walkExprTree(p, exprNodeIsConstant, &isConst);
1.1015 + return isConst!=0;
1.1016 +}
1.1017 +
1.1018 +/*
1.1019 +** If the expression p codes a constant integer that is small enough
1.1020 +** to fit in a 32-bit integer, return 1 and put the value of the integer
1.1021 +** in *pValue. If the expression is not an integer or if it is too big
1.1022 +** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1.1023 +*/
1.1024 +int sqlite3ExprIsInteger(Expr *p, int *pValue){
1.1025 + int rc = 0;
1.1026 + if( p->flags & EP_IntValue ){
1.1027 + *pValue = p->iTable;
1.1028 + return 1;
1.1029 + }
1.1030 + switch( p->op ){
1.1031 + case TK_INTEGER: {
1.1032 + rc = sqlite3GetInt32((char*)p->token.z, pValue);
1.1033 + break;
1.1034 + }
1.1035 + case TK_UPLUS: {
1.1036 + rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1.1037 + break;
1.1038 + }
1.1039 + case TK_UMINUS: {
1.1040 + int v;
1.1041 + if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1.1042 + *pValue = -v;
1.1043 + rc = 1;
1.1044 + }
1.1045 + break;
1.1046 + }
1.1047 + default: break;
1.1048 + }
1.1049 + if( rc ){
1.1050 + p->op = TK_INTEGER;
1.1051 + p->flags |= EP_IntValue;
1.1052 + p->iTable = *pValue;
1.1053 + }
1.1054 + return rc;
1.1055 +}
1.1056 +
1.1057 +/*
1.1058 +** Return TRUE if the given string is a row-id column name.
1.1059 +*/
1.1060 +int sqlite3IsRowid(const char *z){
1.1061 + if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1.1062 + if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1.1063 + if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1.1064 + return 0;
1.1065 +}
1.1066 +
1.1067 +/*
1.1068 +** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
1.1069 +** that name in the set of source tables in pSrcList and make the pExpr
1.1070 +** expression node refer back to that source column. The following changes
1.1071 +** are made to pExpr:
1.1072 +**
1.1073 +** pExpr->iDb Set the index in db->aDb[] of the database holding
1.1074 +** the table.
1.1075 +** pExpr->iTable Set to the cursor number for the table obtained
1.1076 +** from pSrcList.
1.1077 +** pExpr->iColumn Set to the column number within the table.
1.1078 +** pExpr->op Set to TK_COLUMN.
1.1079 +** pExpr->pLeft Any expression this points to is deleted
1.1080 +** pExpr->pRight Any expression this points to is deleted.
1.1081 +**
1.1082 +** The pDbToken is the name of the database (the "X"). This value may be
1.1083 +** NULL meaning that name is of the form Y.Z or Z. Any available database
1.1084 +** can be used. The pTableToken is the name of the table (the "Y"). This
1.1085 +** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
1.1086 +** means that the form of the name is Z and that columns from any table
1.1087 +** can be used.
1.1088 +**
1.1089 +** If the name cannot be resolved unambiguously, leave an error message
1.1090 +** in pParse and return non-zero. Return zero on success.
1.1091 +*/
1.1092 +static int lookupName(
1.1093 + Parse *pParse, /* The parsing context */
1.1094 + Token *pDbToken, /* Name of the database containing table, or NULL */
1.1095 + Token *pTableToken, /* Name of table containing column, or NULL */
1.1096 + Token *pColumnToken, /* Name of the column. */
1.1097 + NameContext *pNC, /* The name context used to resolve the name */
1.1098 + Expr *pExpr /* Make this EXPR node point to the selected column */
1.1099 +){
1.1100 + char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
1.1101 + char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
1.1102 + char *zCol = 0; /* Name of the column. The "Z" */
1.1103 + int i, j; /* Loop counters */
1.1104 + int cnt = 0; /* Number of matching column names */
1.1105 + int cntTab = 0; /* Number of matching table names */
1.1106 + sqlite3 *db = pParse->db; /* The database */
1.1107 + struct SrcList_item *pItem; /* Use for looping over pSrcList items */
1.1108 + struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
1.1109 + NameContext *pTopNC = pNC; /* First namecontext in the list */
1.1110 + Schema *pSchema = 0; /* Schema of the expression */
1.1111 +
1.1112 + assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
1.1113 + zDb = sqlite3NameFromToken(db, pDbToken);
1.1114 + zTab = sqlite3NameFromToken(db, pTableToken);
1.1115 + zCol = sqlite3NameFromToken(db, pColumnToken);
1.1116 + if( db->mallocFailed ){
1.1117 + goto lookupname_end;
1.1118 + }
1.1119 +
1.1120 + pExpr->iTable = -1;
1.1121 + while( pNC && cnt==0 ){
1.1122 + ExprList *pEList;
1.1123 + SrcList *pSrcList = pNC->pSrcList;
1.1124 +
1.1125 + if( pSrcList ){
1.1126 + for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
1.1127 + Table *pTab;
1.1128 + int iDb;
1.1129 + Column *pCol;
1.1130 +
1.1131 + pTab = pItem->pTab;
1.1132 + assert( pTab!=0 );
1.1133 + iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.1134 + assert( pTab->nCol>0 );
1.1135 + if( zTab ){
1.1136 + if( pItem->zAlias ){
1.1137 + char *zTabName = pItem->zAlias;
1.1138 + if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1.1139 + }else{
1.1140 + char *zTabName = pTab->zName;
1.1141 + if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1.1142 + if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
1.1143 + continue;
1.1144 + }
1.1145 + }
1.1146 + }
1.1147 + if( 0==(cntTab++) ){
1.1148 + pExpr->iTable = pItem->iCursor;
1.1149 + pSchema = pTab->pSchema;
1.1150 + pMatch = pItem;
1.1151 + }
1.1152 + for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
1.1153 + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1.1154 + const char *zColl = pTab->aCol[j].zColl;
1.1155 + IdList *pUsing;
1.1156 + cnt++;
1.1157 + pExpr->iTable = pItem->iCursor;
1.1158 + pMatch = pItem;
1.1159 + pSchema = pTab->pSchema;
1.1160 + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
1.1161 + pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1.1162 + pExpr->affinity = pTab->aCol[j].affinity;
1.1163 + if( (pExpr->flags & EP_ExpCollate)==0 ){
1.1164 + pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1.1165 + }
1.1166 + if( i<pSrcList->nSrc-1 ){
1.1167 + if( pItem[1].jointype & JT_NATURAL ){
1.1168 + /* If this match occurred in the left table of a natural join,
1.1169 + ** then skip the right table to avoid a duplicate match */
1.1170 + pItem++;
1.1171 + i++;
1.1172 + }else if( (pUsing = pItem[1].pUsing)!=0 ){
1.1173 + /* If this match occurs on a column that is in the USING clause
1.1174 + ** of a join, skip the search of the right table of the join
1.1175 + ** to avoid a duplicate match there. */
1.1176 + int k;
1.1177 + for(k=0; k<pUsing->nId; k++){
1.1178 + if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1.1179 + pItem++;
1.1180 + i++;
1.1181 + break;
1.1182 + }
1.1183 + }
1.1184 + }
1.1185 + }
1.1186 + break;
1.1187 + }
1.1188 + }
1.1189 + }
1.1190 + }
1.1191 +
1.1192 +#ifndef SQLITE_OMIT_TRIGGER
1.1193 + /* If we have not already resolved the name, then maybe
1.1194 + ** it is a new.* or old.* trigger argument reference
1.1195 + */
1.1196 + if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
1.1197 + TriggerStack *pTriggerStack = pParse->trigStack;
1.1198 + Table *pTab = 0;
1.1199 + u32 *piColMask;
1.1200 + if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
1.1201 + pExpr->iTable = pTriggerStack->newIdx;
1.1202 + assert( pTriggerStack->pTab );
1.1203 + pTab = pTriggerStack->pTab;
1.1204 + piColMask = &(pTriggerStack->newColMask);
1.1205 + }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
1.1206 + pExpr->iTable = pTriggerStack->oldIdx;
1.1207 + assert( pTriggerStack->pTab );
1.1208 + pTab = pTriggerStack->pTab;
1.1209 + piColMask = &(pTriggerStack->oldColMask);
1.1210 + }
1.1211 +
1.1212 + if( pTab ){
1.1213 + int iCol;
1.1214 + Column *pCol = pTab->aCol;
1.1215 +
1.1216 + pSchema = pTab->pSchema;
1.1217 + cntTab++;
1.1218 + for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
1.1219 + if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1.1220 + const char *zColl = pTab->aCol[iCol].zColl;
1.1221 + cnt++;
1.1222 + pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1.1223 + pExpr->affinity = pTab->aCol[iCol].affinity;
1.1224 + if( (pExpr->flags & EP_ExpCollate)==0 ){
1.1225 + pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1.1226 + }
1.1227 + pExpr->pTab = pTab;
1.1228 + if( iCol>=0 ){
1.1229 + testcase( iCol==31 );
1.1230 + testcase( iCol==32 );
1.1231 + *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
1.1232 + }
1.1233 + break;
1.1234 + }
1.1235 + }
1.1236 + }
1.1237 + }
1.1238 +#endif /* !defined(SQLITE_OMIT_TRIGGER) */
1.1239 +
1.1240 + /*
1.1241 + ** Perhaps the name is a reference to the ROWID
1.1242 + */
1.1243 + if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
1.1244 + cnt = 1;
1.1245 + pExpr->iColumn = -1;
1.1246 + pExpr->affinity = SQLITE_AFF_INTEGER;
1.1247 + }
1.1248 +
1.1249 + /*
1.1250 + ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
1.1251 + ** might refer to an result-set alias. This happens, for example, when
1.1252 + ** we are resolving names in the WHERE clause of the following command:
1.1253 + **
1.1254 + ** SELECT a+b AS x FROM table WHERE x<10;
1.1255 + **
1.1256 + ** In cases like this, replace pExpr with a copy of the expression that
1.1257 + ** forms the result set entry ("a+b" in the example) and return immediately.
1.1258 + ** Note that the expression in the result set should have already been
1.1259 + ** resolved by the time the WHERE clause is resolved.
1.1260 + */
1.1261 + if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
1.1262 + for(j=0; j<pEList->nExpr; j++){
1.1263 + char *zAs = pEList->a[j].zName;
1.1264 + if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
1.1265 + Expr *pDup, *pOrig;
1.1266 + assert( pExpr->pLeft==0 && pExpr->pRight==0 );
1.1267 + assert( pExpr->pList==0 );
1.1268 + assert( pExpr->pSelect==0 );
1.1269 + pOrig = pEList->a[j].pExpr;
1.1270 + if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
1.1271 + sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
1.1272 + sqlite3DbFree(db, zCol);
1.1273 + return 2;
1.1274 + }
1.1275 + pDup = sqlite3ExprDup(db, pOrig);
1.1276 + if( pExpr->flags & EP_ExpCollate ){
1.1277 + pDup->pColl = pExpr->pColl;
1.1278 + pDup->flags |= EP_ExpCollate;
1.1279 + }
1.1280 + if( pExpr->span.dyn ) sqlite3DbFree(db, (char*)pExpr->span.z);
1.1281 + if( pExpr->token.dyn ) sqlite3DbFree(db, (char*)pExpr->token.z);
1.1282 + memcpy(pExpr, pDup, sizeof(*pExpr));
1.1283 + sqlite3DbFree(db, pDup);
1.1284 + cnt = 1;
1.1285 + pMatch = 0;
1.1286 + assert( zTab==0 && zDb==0 );
1.1287 + goto lookupname_end_2;
1.1288 + }
1.1289 + }
1.1290 + }
1.1291 +
1.1292 + /* Advance to the next name context. The loop will exit when either
1.1293 + ** we have a match (cnt>0) or when we run out of name contexts.
1.1294 + */
1.1295 + if( cnt==0 ){
1.1296 + pNC = pNC->pNext;
1.1297 + }
1.1298 + }
1.1299 +
1.1300 + /*
1.1301 + ** If X and Y are NULL (in other words if only the column name Z is
1.1302 + ** supplied) and the value of Z is enclosed in double-quotes, then
1.1303 + ** Z is a string literal if it doesn't match any column names. In that
1.1304 + ** case, we need to return right away and not make any changes to
1.1305 + ** pExpr.
1.1306 + **
1.1307 + ** Because no reference was made to outer contexts, the pNC->nRef
1.1308 + ** fields are not changed in any context.
1.1309 + */
1.1310 + if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
1.1311 + sqlite3DbFree(db, zCol);
1.1312 + return 0;
1.1313 + }
1.1314 +
1.1315 + /*
1.1316 + ** cnt==0 means there was not match. cnt>1 means there were two or
1.1317 + ** more matches. Either way, we have an error.
1.1318 + */
1.1319 + if( cnt!=1 ){
1.1320 + const char *zErr;
1.1321 + zErr = cnt==0 ? "no such column" : "ambiguous column name";
1.1322 + if( zDb ){
1.1323 + sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
1.1324 + }else if( zTab ){
1.1325 + sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
1.1326 + }else{
1.1327 + sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
1.1328 + }
1.1329 + pTopNC->nErr++;
1.1330 + }
1.1331 +
1.1332 + /* If a column from a table in pSrcList is referenced, then record
1.1333 + ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
1.1334 + ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
1.1335 + ** column number is greater than the number of bits in the bitmask
1.1336 + ** then set the high-order bit of the bitmask.
1.1337 + */
1.1338 + if( pExpr->iColumn>=0 && pMatch!=0 ){
1.1339 + int n = pExpr->iColumn;
1.1340 + testcase( n==sizeof(Bitmask)*8-1 );
1.1341 + if( n>=sizeof(Bitmask)*8 ){
1.1342 + n = sizeof(Bitmask)*8-1;
1.1343 + }
1.1344 + assert( pMatch->iCursor==pExpr->iTable );
1.1345 + pMatch->colUsed |= ((Bitmask)1)<<n;
1.1346 + }
1.1347 +
1.1348 +lookupname_end:
1.1349 + /* Clean up and return
1.1350 + */
1.1351 + sqlite3DbFree(db, zDb);
1.1352 + sqlite3DbFree(db, zTab);
1.1353 + sqlite3ExprDelete(db, pExpr->pLeft);
1.1354 + pExpr->pLeft = 0;
1.1355 + sqlite3ExprDelete(db, pExpr->pRight);
1.1356 + pExpr->pRight = 0;
1.1357 + pExpr->op = TK_COLUMN;
1.1358 +lookupname_end_2:
1.1359 + sqlite3DbFree(db, zCol);
1.1360 + if( cnt==1 ){
1.1361 + assert( pNC!=0 );
1.1362 + sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
1.1363 + if( pMatch && !pMatch->pSelect ){
1.1364 + pExpr->pTab = pMatch->pTab;
1.1365 + }
1.1366 + /* Increment the nRef value on all name contexts from TopNC up to
1.1367 + ** the point where the name matched. */
1.1368 + for(;;){
1.1369 + assert( pTopNC!=0 );
1.1370 + pTopNC->nRef++;
1.1371 + if( pTopNC==pNC ) break;
1.1372 + pTopNC = pTopNC->pNext;
1.1373 + }
1.1374 + return 0;
1.1375 + } else {
1.1376 + return 1;
1.1377 + }
1.1378 +}
1.1379 +
1.1380 +/*
1.1381 +** This routine is designed as an xFunc for walkExprTree().
1.1382 +**
1.1383 +** Resolve symbolic names into TK_COLUMN operators for the current
1.1384 +** node in the expression tree. Return 0 to continue the search down
1.1385 +** the tree or 2 to abort the tree walk.
1.1386 +**
1.1387 +** This routine also does error checking and name resolution for
1.1388 +** function names. The operator for aggregate functions is changed
1.1389 +** to TK_AGG_FUNCTION.
1.1390 +*/
1.1391 +static int nameResolverStep(void *pArg, Expr *pExpr){
1.1392 + NameContext *pNC = (NameContext*)pArg;
1.1393 + Parse *pParse;
1.1394 +
1.1395 + if( pExpr==0 ) return 1;
1.1396 + assert( pNC!=0 );
1.1397 + pParse = pNC->pParse;
1.1398 +
1.1399 + if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1.1400 + ExprSetProperty(pExpr, EP_Resolved);
1.1401 +#ifndef NDEBUG
1.1402 + if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1.1403 + SrcList *pSrcList = pNC->pSrcList;
1.1404 + int i;
1.1405 + for(i=0; i<pNC->pSrcList->nSrc; i++){
1.1406 + assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1.1407 + }
1.1408 + }
1.1409 +#endif
1.1410 + switch( pExpr->op ){
1.1411 + /* Double-quoted strings (ex: "abc") are used as identifiers if
1.1412 + ** possible. Otherwise they remain as strings. Single-quoted
1.1413 + ** strings (ex: 'abc') are always string literals.
1.1414 + */
1.1415 + case TK_STRING: {
1.1416 + if( pExpr->token.z[0]=='\'' ) break;
1.1417 + /* Fall thru into the TK_ID case if this is a double-quoted string */
1.1418 + }
1.1419 + /* A lone identifier is the name of a column.
1.1420 + */
1.1421 + case TK_ID: {
1.1422 + lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1.1423 + return 1;
1.1424 + }
1.1425 +
1.1426 + /* A table name and column name: ID.ID
1.1427 + ** Or a database, table and column: ID.ID.ID
1.1428 + */
1.1429 + case TK_DOT: {
1.1430 + Token *pColumn;
1.1431 + Token *pTable;
1.1432 + Token *pDb;
1.1433 + Expr *pRight;
1.1434 +
1.1435 + /* if( pSrcList==0 ) break; */
1.1436 + pRight = pExpr->pRight;
1.1437 + if( pRight->op==TK_ID ){
1.1438 + pDb = 0;
1.1439 + pTable = &pExpr->pLeft->token;
1.1440 + pColumn = &pRight->token;
1.1441 + }else{
1.1442 + assert( pRight->op==TK_DOT );
1.1443 + pDb = &pExpr->pLeft->token;
1.1444 + pTable = &pRight->pLeft->token;
1.1445 + pColumn = &pRight->pRight->token;
1.1446 + }
1.1447 + lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1.1448 + return 1;
1.1449 + }
1.1450 +
1.1451 + /* Resolve function names
1.1452 + */
1.1453 + case TK_CONST_FUNC:
1.1454 + case TK_FUNCTION: {
1.1455 + ExprList *pList = pExpr->pList; /* The argument list */
1.1456 + int n = pList ? pList->nExpr : 0; /* Number of arguments */
1.1457 + int no_such_func = 0; /* True if no such function exists */
1.1458 + int wrong_num_args = 0; /* True if wrong number of arguments */
1.1459 + int is_agg = 0; /* True if is an aggregate function */
1.1460 + int i;
1.1461 + int auth; /* Authorization to use the function */
1.1462 + int nId; /* Number of characters in function name */
1.1463 + const char *zId; /* The function name. */
1.1464 + FuncDef *pDef; /* Information about the function */
1.1465 + int enc = ENC(pParse->db); /* The database encoding */
1.1466 +
1.1467 + zId = (char*)pExpr->token.z;
1.1468 + nId = pExpr->token.n;
1.1469 + pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1.1470 + if( pDef==0 ){
1.1471 + pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1.1472 + if( pDef==0 ){
1.1473 + no_such_func = 1;
1.1474 + }else{
1.1475 + wrong_num_args = 1;
1.1476 + }
1.1477 + }else{
1.1478 + is_agg = pDef->xFunc==0;
1.1479 + }
1.1480 +#ifndef SQLITE_OMIT_AUTHORIZATION
1.1481 + if( pDef ){
1.1482 + auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
1.1483 + if( auth!=SQLITE_OK ){
1.1484 + if( auth==SQLITE_DENY ){
1.1485 + sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
1.1486 + pDef->zName);
1.1487 + pNC->nErr++;
1.1488 + }
1.1489 + pExpr->op = TK_NULL;
1.1490 + return 1;
1.1491 + }
1.1492 + }
1.1493 +#endif
1.1494 + if( is_agg && !pNC->allowAgg ){
1.1495 + sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1.1496 + pNC->nErr++;
1.1497 + is_agg = 0;
1.1498 + }else if( no_such_func ){
1.1499 + sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1.1500 + pNC->nErr++;
1.1501 + }else if( wrong_num_args ){
1.1502 + sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1.1503 + nId, zId);
1.1504 + pNC->nErr++;
1.1505 + }
1.1506 + if( is_agg ){
1.1507 + pExpr->op = TK_AGG_FUNCTION;
1.1508 + pNC->hasAgg = 1;
1.1509 + }
1.1510 + if( is_agg ) pNC->allowAgg = 0;
1.1511 + for(i=0; pNC->nErr==0 && i<n; i++){
1.1512 + walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1.1513 + }
1.1514 + if( is_agg ) pNC->allowAgg = 1;
1.1515 + /* FIX ME: Compute pExpr->affinity based on the expected return
1.1516 + ** type of the function
1.1517 + */
1.1518 + return is_agg;
1.1519 + }
1.1520 +#ifndef SQLITE_OMIT_SUBQUERY
1.1521 + case TK_SELECT:
1.1522 + case TK_EXISTS:
1.1523 +#endif
1.1524 + case TK_IN: {
1.1525 + if( pExpr->pSelect ){
1.1526 + int nRef = pNC->nRef;
1.1527 +#ifndef SQLITE_OMIT_CHECK
1.1528 + if( pNC->isCheck ){
1.1529 + sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
1.1530 + }
1.1531 +#endif
1.1532 + sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1.1533 + assert( pNC->nRef>=nRef );
1.1534 + if( nRef!=pNC->nRef ){
1.1535 + ExprSetProperty(pExpr, EP_VarSelect);
1.1536 + }
1.1537 + }
1.1538 + break;
1.1539 + }
1.1540 +#ifndef SQLITE_OMIT_CHECK
1.1541 + case TK_VARIABLE: {
1.1542 + if( pNC->isCheck ){
1.1543 + sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
1.1544 + }
1.1545 + break;
1.1546 + }
1.1547 +#endif
1.1548 + }
1.1549 + return 0;
1.1550 +}
1.1551 +
1.1552 +/*
1.1553 +** This routine walks an expression tree and resolves references to
1.1554 +** table columns. Nodes of the form ID.ID or ID resolve into an
1.1555 +** index to the table in the table list and a column offset. The
1.1556 +** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
1.1557 +** value is changed to the index of the referenced table in pTabList
1.1558 +** plus the "base" value. The base value will ultimately become the
1.1559 +** VDBE cursor number for a cursor that is pointing into the referenced
1.1560 +** table. The Expr.iColumn value is changed to the index of the column
1.1561 +** of the referenced table. The Expr.iColumn value for the special
1.1562 +** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
1.1563 +** alias for ROWID.
1.1564 +**
1.1565 +** Also resolve function names and check the functions for proper
1.1566 +** usage. Make sure all function names are recognized and all functions
1.1567 +** have the correct number of arguments. Leave an error message
1.1568 +** in pParse->zErrMsg if anything is amiss. Return the number of errors.
1.1569 +**
1.1570 +** If the expression contains aggregate functions then set the EP_Agg
1.1571 +** property on the expression.
1.1572 +*/
1.1573 +int sqlite3ExprResolveNames(
1.1574 + NameContext *pNC, /* Namespace to resolve expressions in. */
1.1575 + Expr *pExpr /* The expression to be analyzed. */
1.1576 +){
1.1577 + int savedHasAgg;
1.1578 +
1.1579 + if( pExpr==0 ) return 0;
1.1580 +#if SQLITE_MAX_EXPR_DEPTH>0
1.1581 + {
1.1582 + if( checkExprHeight(pNC->pParse, pExpr->nHeight + pNC->pParse->nHeight) ){
1.1583 + return 1;
1.1584 + }
1.1585 + pNC->pParse->nHeight += pExpr->nHeight;
1.1586 + }
1.1587 +#endif
1.1588 + savedHasAgg = pNC->hasAgg;
1.1589 + pNC->hasAgg = 0;
1.1590 + walkExprTree(pExpr, nameResolverStep, pNC);
1.1591 +#if SQLITE_MAX_EXPR_DEPTH>0
1.1592 + pNC->pParse->nHeight -= pExpr->nHeight;
1.1593 +#endif
1.1594 + if( pNC->nErr>0 ){
1.1595 + ExprSetProperty(pExpr, EP_Error);
1.1596 + }
1.1597 + if( pNC->hasAgg ){
1.1598 + ExprSetProperty(pExpr, EP_Agg);
1.1599 + }else if( savedHasAgg ){
1.1600 + pNC->hasAgg = 1;
1.1601 + }
1.1602 + return ExprHasProperty(pExpr, EP_Error);
1.1603 +}
1.1604 +
1.1605 +/*
1.1606 +** A pointer instance of this structure is used to pass information
1.1607 +** through walkExprTree into codeSubqueryStep().
1.1608 +*/
1.1609 +typedef struct QueryCoder QueryCoder;
1.1610 +struct QueryCoder {
1.1611 + Parse *pParse; /* The parsing context */
1.1612 + NameContext *pNC; /* Namespace of first enclosing query */
1.1613 +};
1.1614 +
1.1615 +#ifdef SQLITE_TEST
1.1616 + int sqlite3_enable_in_opt = 1;
1.1617 +#else
1.1618 + #define sqlite3_enable_in_opt 1
1.1619 +#endif
1.1620 +
1.1621 +/*
1.1622 +** Return true if the IN operator optimization is enabled and
1.1623 +** the SELECT statement p exists and is of the
1.1624 +** simple form:
1.1625 +**
1.1626 +** SELECT <column> FROM <table>
1.1627 +**
1.1628 +** If this is the case, it may be possible to use an existing table
1.1629 +** or index instead of generating an epheremal table.
1.1630 +*/
1.1631 +#ifndef SQLITE_OMIT_SUBQUERY
1.1632 +static int isCandidateForInOpt(Select *p){
1.1633 + SrcList *pSrc;
1.1634 + ExprList *pEList;
1.1635 + Table *pTab;
1.1636 + if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
1.1637 + if( p==0 ) return 0; /* right-hand side of IN is SELECT */
1.1638 + if( p->pPrior ) return 0; /* Not a compound SELECT */
1.1639 + if( p->isDistinct ) return 0; /* No DISTINCT keyword */
1.1640 + if( p->isAgg ) return 0; /* Contains no aggregate functions */
1.1641 + if( p->pGroupBy ) return 0; /* Has no GROUP BY clause */
1.1642 + if( p->pLimit ) return 0; /* Has no LIMIT clause */
1.1643 + if( p->pOffset ) return 0;
1.1644 + if( p->pWhere ) return 0; /* Has no WHERE clause */
1.1645 + pSrc = p->pSrc;
1.1646 + if( pSrc==0 ) return 0; /* A single table in the FROM clause */
1.1647 + if( pSrc->nSrc!=1 ) return 0;
1.1648 + if( pSrc->a[0].pSelect ) return 0; /* FROM clause is not a subquery */
1.1649 + pTab = pSrc->a[0].pTab;
1.1650 + if( pTab==0 ) return 0;
1.1651 + if( pTab->pSelect ) return 0; /* FROM clause is not a view */
1.1652 + if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1.1653 + pEList = p->pEList;
1.1654 + if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
1.1655 + if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1.1656 + return 1;
1.1657 +}
1.1658 +#endif /* SQLITE_OMIT_SUBQUERY */
1.1659 +
1.1660 +/*
1.1661 +** This function is used by the implementation of the IN (...) operator.
1.1662 +** It's job is to find or create a b-tree structure that may be used
1.1663 +** either to test for membership of the (...) set or to iterate through
1.1664 +** its members, skipping duplicates.
1.1665 +**
1.1666 +** The cursor opened on the structure (database table, database index
1.1667 +** or ephermal table) is stored in pX->iTable before this function returns.
1.1668 +** The returned value indicates the structure type, as follows:
1.1669 +**
1.1670 +** IN_INDEX_ROWID - The cursor was opened on a database table.
1.1671 +** IN_INDEX_INDEX - The cursor was opened on a database index.
1.1672 +** IN_INDEX_EPH - The cursor was opened on a specially created and
1.1673 +** populated epheremal table.
1.1674 +**
1.1675 +** An existing structure may only be used if the SELECT is of the simple
1.1676 +** form:
1.1677 +**
1.1678 +** SELECT <column> FROM <table>
1.1679 +**
1.1680 +** If prNotFound parameter is 0, then the structure will be used to iterate
1.1681 +** through the set members, skipping any duplicates. In this case an
1.1682 +** epheremal table must be used unless the selected <column> is guaranteed
1.1683 +** to be unique - either because it is an INTEGER PRIMARY KEY or it
1.1684 +** is unique by virtue of a constraint or implicit index.
1.1685 +**
1.1686 +** If the prNotFound parameter is not 0, then the structure will be used
1.1687 +** for fast set membership tests. In this case an epheremal table must
1.1688 +** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1.1689 +** be found with <column> as its left-most column.
1.1690 +**
1.1691 +** When the structure is being used for set membership tests, the user
1.1692 +** needs to know whether or not the structure contains an SQL NULL
1.1693 +** value in order to correctly evaluate expressions like "X IN (Y, Z)".
1.1694 +** If there is a chance that the structure may contain a NULL value at
1.1695 +** runtime, then a register is allocated and the register number written
1.1696 +** to *prNotFound. If there is no chance that the structure contains a
1.1697 +** NULL value, then *prNotFound is left unchanged.
1.1698 +**
1.1699 +** If a register is allocated and its location stored in *prNotFound, then
1.1700 +** its initial value is NULL. If the structure does not remain constant
1.1701 +** for the duration of the query (i.e. the set is a correlated sub-select),
1.1702 +** the value of the allocated register is reset to NULL each time the
1.1703 +** structure is repopulated. This allows the caller to use vdbe code
1.1704 +** equivalent to the following:
1.1705 +**
1.1706 +** if( register==NULL ){
1.1707 +** has_null = <test if data structure contains null>
1.1708 +** register = 1
1.1709 +** }
1.1710 +**
1.1711 +** in order to avoid running the <test if data structure contains null>
1.1712 +** test more often than is necessary.
1.1713 +*/
1.1714 +#ifndef SQLITE_OMIT_SUBQUERY
1.1715 +int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
1.1716 + Select *p;
1.1717 + int eType = 0;
1.1718 + int iTab = pParse->nTab++;
1.1719 + int mustBeUnique = !prNotFound;
1.1720 +
1.1721 + /* The follwing if(...) expression is true if the SELECT is of the
1.1722 + ** simple form:
1.1723 + **
1.1724 + ** SELECT <column> FROM <table>
1.1725 + **
1.1726 + ** If this is the case, it may be possible to use an existing table
1.1727 + ** or index instead of generating an epheremal table.
1.1728 + */
1.1729 + p = pX->pSelect;
1.1730 + if( isCandidateForInOpt(p) ){
1.1731 + sqlite3 *db = pParse->db;
1.1732 + Index *pIdx;
1.1733 + Expr *pExpr = p->pEList->a[0].pExpr;
1.1734 + int iCol = pExpr->iColumn;
1.1735 + Vdbe *v = sqlite3GetVdbe(pParse);
1.1736 +
1.1737 + /* This function is only called from two places. In both cases the vdbe
1.1738 + ** has already been allocated. So assume sqlite3GetVdbe() is always
1.1739 + ** successful here.
1.1740 + */
1.1741 + assert(v);
1.1742 + if( iCol<0 ){
1.1743 + int iMem = ++pParse->nMem;
1.1744 + int iAddr;
1.1745 + Table *pTab = p->pSrc->a[0].pTab;
1.1746 + int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1.1747 + sqlite3VdbeUsesBtree(v, iDb);
1.1748 +
1.1749 + iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1.1750 + sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1.1751 +
1.1752 + sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1.1753 + eType = IN_INDEX_ROWID;
1.1754 +
1.1755 + sqlite3VdbeJumpHere(v, iAddr);
1.1756 + }else{
1.1757 + /* The collation sequence used by the comparison. If an index is to
1.1758 + ** be used in place of a temp-table, it must be ordered according
1.1759 + ** to this collation sequence.
1.1760 + */
1.1761 + CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
1.1762 +
1.1763 + /* Check that the affinity that will be used to perform the
1.1764 + ** comparison is the same as the affinity of the column. If
1.1765 + ** it is not, it is not possible to use any index.
1.1766 + */
1.1767 + Table *pTab = p->pSrc->a[0].pTab;
1.1768 + char aff = comparisonAffinity(pX);
1.1769 + int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
1.1770 +
1.1771 + for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
1.1772 + if( (pIdx->aiColumn[0]==iCol)
1.1773 + && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
1.1774 + && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
1.1775 + ){
1.1776 + int iDb;
1.1777 + int iMem = ++pParse->nMem;
1.1778 + int iAddr;
1.1779 + char *pKey;
1.1780 +
1.1781 + pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
1.1782 + iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1.1783 + sqlite3VdbeUsesBtree(v, iDb);
1.1784 +
1.1785 + iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1.1786 + sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1.1787 +
1.1788 + sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
1.1789 + sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
1.1790 + pKey,P4_KEYINFO_HANDOFF);
1.1791 + VdbeComment((v, "%s", pIdx->zName));
1.1792 + eType = IN_INDEX_INDEX;
1.1793 +
1.1794 + sqlite3VdbeJumpHere(v, iAddr);
1.1795 + if( prNotFound && !pTab->aCol[iCol].notNull ){
1.1796 + *prNotFound = ++pParse->nMem;
1.1797 + }
1.1798 + }
1.1799 + }
1.1800 + }
1.1801 + }
1.1802 +
1.1803 + if( eType==0 ){
1.1804 + int rMayHaveNull = 0;
1.1805 + if( prNotFound ){
1.1806 + *prNotFound = rMayHaveNull = ++pParse->nMem;
1.1807 + }
1.1808 + sqlite3CodeSubselect(pParse, pX, rMayHaveNull);
1.1809 + eType = IN_INDEX_EPH;
1.1810 + }else{
1.1811 + pX->iTable = iTab;
1.1812 + }
1.1813 + return eType;
1.1814 +}
1.1815 +#endif
1.1816 +
1.1817 +/*
1.1818 +** Generate code for scalar subqueries used as an expression
1.1819 +** and IN operators. Examples:
1.1820 +**
1.1821 +** (SELECT a FROM b) -- subquery
1.1822 +** EXISTS (SELECT a FROM b) -- EXISTS subquery
1.1823 +** x IN (4,5,11) -- IN operator with list on right-hand side
1.1824 +** x IN (SELECT a FROM b) -- IN operator with subquery on the right
1.1825 +**
1.1826 +** The pExpr parameter describes the expression that contains the IN
1.1827 +** operator or subquery.
1.1828 +*/
1.1829 +#ifndef SQLITE_OMIT_SUBQUERY
1.1830 +void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHaveNull){
1.1831 + int testAddr = 0; /* One-time test address */
1.1832 + Vdbe *v = sqlite3GetVdbe(pParse);
1.1833 + if( v==0 ) return;
1.1834 +
1.1835 +
1.1836 + /* This code must be run in its entirety every time it is encountered
1.1837 + ** if any of the following is true:
1.1838 + **
1.1839 + ** * The right-hand side is a correlated subquery
1.1840 + ** * The right-hand side is an expression list containing variables
1.1841 + ** * We are inside a trigger
1.1842 + **
1.1843 + ** If all of the above are false, then we can run this code just once
1.1844 + ** save the results, and reuse the same result on subsequent invocations.
1.1845 + */
1.1846 + if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1.1847 + int mem = ++pParse->nMem;
1.1848 + sqlite3VdbeAddOp1(v, OP_If, mem);
1.1849 + testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
1.1850 + assert( testAddr>0 || pParse->db->mallocFailed );
1.1851 + }
1.1852 +
1.1853 + switch( pExpr->op ){
1.1854 + case TK_IN: {
1.1855 + char affinity;
1.1856 + KeyInfo keyInfo;
1.1857 + int addr; /* Address of OP_OpenEphemeral instruction */
1.1858 +
1.1859 + if( rMayHaveNull ){
1.1860 + sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
1.1861 + }
1.1862 +
1.1863 + affinity = sqlite3ExprAffinity(pExpr->pLeft);
1.1864 +
1.1865 + /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1.1866 + ** expression it is handled the same way. A virtual table is
1.1867 + ** filled with single-field index keys representing the results
1.1868 + ** from the SELECT or the <exprlist>.
1.1869 + **
1.1870 + ** If the 'x' expression is a column value, or the SELECT...
1.1871 + ** statement returns a column value, then the affinity of that
1.1872 + ** column is used to build the index keys. If both 'x' and the
1.1873 + ** SELECT... statement are columns, then numeric affinity is used
1.1874 + ** if either column has NUMERIC or INTEGER affinity. If neither
1.1875 + ** 'x' nor the SELECT... statement are columns, then numeric affinity
1.1876 + ** is used.
1.1877 + */
1.1878 + pExpr->iTable = pParse->nTab++;
1.1879 + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, 1);
1.1880 + memset(&keyInfo, 0, sizeof(keyInfo));
1.1881 + keyInfo.nField = 1;
1.1882 +
1.1883 + if( pExpr->pSelect ){
1.1884 + /* Case 1: expr IN (SELECT ...)
1.1885 + **
1.1886 + ** Generate code to write the results of the select into the temporary
1.1887 + ** table allocated and opened above.
1.1888 + */
1.1889 + SelectDest dest;
1.1890 + ExprList *pEList;
1.1891 +
1.1892 + sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
1.1893 + dest.affinity = (int)affinity;
1.1894 + assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1.1895 + if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0) ){
1.1896 + return;
1.1897 + }
1.1898 + pEList = pExpr->pSelect->pEList;
1.1899 + if( pEList && pEList->nExpr>0 ){
1.1900 + keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1.1901 + pEList->a[0].pExpr);
1.1902 + }
1.1903 + }else if( pExpr->pList ){
1.1904 + /* Case 2: expr IN (exprlist)
1.1905 + **
1.1906 + ** For each expression, build an index key from the evaluation and
1.1907 + ** store it in the temporary table. If <expr> is a column, then use
1.1908 + ** that columns affinity when building index keys. If <expr> is not
1.1909 + ** a column, use numeric affinity.
1.1910 + */
1.1911 + int i;
1.1912 + ExprList *pList = pExpr->pList;
1.1913 + struct ExprList_item *pItem;
1.1914 + int r1, r2, r3;
1.1915 +
1.1916 + if( !affinity ){
1.1917 + affinity = SQLITE_AFF_NONE;
1.1918 + }
1.1919 + keyInfo.aColl[0] = pExpr->pLeft->pColl;
1.1920 +
1.1921 + /* Loop through each expression in <exprlist>. */
1.1922 + r1 = sqlite3GetTempReg(pParse);
1.1923 + r2 = sqlite3GetTempReg(pParse);
1.1924 + for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1.1925 + Expr *pE2 = pItem->pExpr;
1.1926 +
1.1927 + /* If the expression is not constant then we will need to
1.1928 + ** disable the test that was generated above that makes sure
1.1929 + ** this code only executes once. Because for a non-constant
1.1930 + ** expression we need to rerun this code each time.
1.1931 + */
1.1932 + if( testAddr && !sqlite3ExprIsConstant(pE2) ){
1.1933 + sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
1.1934 + testAddr = 0;
1.1935 + }
1.1936 +
1.1937 + /* Evaluate the expression and insert it into the temp table */
1.1938 + pParse->disableColCache++;
1.1939 + r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
1.1940 + assert( pParse->disableColCache>0 );
1.1941 + pParse->disableColCache--;
1.1942 + sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
1.1943 + sqlite3ExprCacheAffinityChange(pParse, r3, 1);
1.1944 + sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
1.1945 + }
1.1946 + sqlite3ReleaseTempReg(pParse, r1);
1.1947 + sqlite3ReleaseTempReg(pParse, r2);
1.1948 + }
1.1949 + sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
1.1950 + break;
1.1951 + }
1.1952 +
1.1953 + case TK_EXISTS:
1.1954 + case TK_SELECT: {
1.1955 + /* This has to be a scalar SELECT. Generate code to put the
1.1956 + ** value of this select in a memory cell and record the number
1.1957 + ** of the memory cell in iColumn.
1.1958 + */
1.1959 + static const Token one = { (u8*)"1", 0, 1 };
1.1960 + Select *pSel;
1.1961 + SelectDest dest;
1.1962 +
1.1963 + pSel = pExpr->pSelect;
1.1964 + sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
1.1965 + if( pExpr->op==TK_SELECT ){
1.1966 + dest.eDest = SRT_Mem;
1.1967 + sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
1.1968 + VdbeComment((v, "Init subquery result"));
1.1969 + }else{
1.1970 + dest.eDest = SRT_Exists;
1.1971 + sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
1.1972 + VdbeComment((v, "Init EXISTS result"));
1.1973 + }
1.1974 + sqlite3ExprDelete(pParse->db, pSel->pLimit);
1.1975 + pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
1.1976 + if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0) ){
1.1977 + return;
1.1978 + }
1.1979 + pExpr->iColumn = dest.iParm;
1.1980 + break;
1.1981 + }
1.1982 + }
1.1983 +
1.1984 + if( testAddr ){
1.1985 + sqlite3VdbeJumpHere(v, testAddr-1);
1.1986 + }
1.1987 +
1.1988 + return;
1.1989 +}
1.1990 +#endif /* SQLITE_OMIT_SUBQUERY */
1.1991 +
1.1992 +/*
1.1993 +** Duplicate an 8-byte value
1.1994 +*/
1.1995 +static char *dup8bytes(Vdbe *v, const char *in){
1.1996 + char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1.1997 + if( out ){
1.1998 + memcpy(out, in, 8);
1.1999 + }
1.2000 + return out;
1.2001 +}
1.2002 +
1.2003 +/*
1.2004 +** Generate an instruction that will put the floating point
1.2005 +** value described by z[0..n-1] into register iMem.
1.2006 +**
1.2007 +** The z[] string will probably not be zero-terminated. But the
1.2008 +** z[n] character is guaranteed to be something that does not look
1.2009 +** like the continuation of the number.
1.2010 +*/
1.2011 +static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
1.2012 + assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
1.2013 + if( z ){
1.2014 + double value;
1.2015 + char *zV;
1.2016 + assert( !isdigit(z[n]) );
1.2017 + sqlite3AtoF(z, &value);
1.2018 + if( sqlite3IsNaN(value) ){
1.2019 + sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
1.2020 + }else{
1.2021 + if( negateFlag ) value = -value;
1.2022 + zV = dup8bytes(v, (char*)&value);
1.2023 + sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
1.2024 + }
1.2025 + }
1.2026 +}
1.2027 +
1.2028 +
1.2029 +/*
1.2030 +** Generate an instruction that will put the integer describe by
1.2031 +** text z[0..n-1] into register iMem.
1.2032 +**
1.2033 +** The z[] string will probably not be zero-terminated. But the
1.2034 +** z[n] character is guaranteed to be something that does not look
1.2035 +** like the continuation of the number.
1.2036 +*/
1.2037 +static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
1.2038 + const char *z;
1.2039 + if( pExpr->flags & EP_IntValue ){
1.2040 + int i = pExpr->iTable;
1.2041 + if( negFlag ) i = -i;
1.2042 + sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
1.2043 + }else if( (z = (char*)pExpr->token.z)!=0 ){
1.2044 + int i;
1.2045 + int n = pExpr->token.n;
1.2046 + assert( !isdigit(z[n]) );
1.2047 + if( sqlite3GetInt32(z, &i) ){
1.2048 + if( negFlag ) i = -i;
1.2049 + sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
1.2050 + }else if( sqlite3FitsIn64Bits(z, negFlag) ){
1.2051 + i64 value;
1.2052 + char *zV;
1.2053 + sqlite3Atoi64(z, &value);
1.2054 + if( negFlag ) value = -value;
1.2055 + zV = dup8bytes(v, (char*)&value);
1.2056 + sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
1.2057 + }else{
1.2058 + codeReal(v, z, n, negFlag, iMem);
1.2059 + }
1.2060 + }
1.2061 +}
1.2062 +
1.2063 +
1.2064 +/*
1.2065 +** Generate code that will extract the iColumn-th column from
1.2066 +** table pTab and store the column value in a register. An effort
1.2067 +** is made to store the column value in register iReg, but this is
1.2068 +** not guaranteed. The location of the column value is returned.
1.2069 +**
1.2070 +** There must be an open cursor to pTab in iTable when this routine
1.2071 +** is called. If iColumn<0 then code is generated that extracts the rowid.
1.2072 +**
1.2073 +** This routine might attempt to reuse the value of the column that
1.2074 +** has already been loaded into a register. The value will always
1.2075 +** be used if it has not undergone any affinity changes. But if
1.2076 +** an affinity change has occurred, then the cached value will only be
1.2077 +** used if allowAffChng is true.
1.2078 +*/
1.2079 +int sqlite3ExprCodeGetColumn(
1.2080 + Parse *pParse, /* Parsing and code generating context */
1.2081 + Table *pTab, /* Description of the table we are reading from */
1.2082 + int iColumn, /* Index of the table column */
1.2083 + int iTable, /* The cursor pointing to the table */
1.2084 + int iReg, /* Store results here */
1.2085 + int allowAffChng /* True if prior affinity changes are OK */
1.2086 +){
1.2087 + Vdbe *v = pParse->pVdbe;
1.2088 + int i;
1.2089 + struct yColCache *p;
1.2090 +
1.2091 + for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
1.2092 + if( p->iTable==iTable && p->iColumn==iColumn
1.2093 + && (!p->affChange || allowAffChng) ){
1.2094 +#if 0
1.2095 + sqlite3VdbeAddOp0(v, OP_Noop);
1.2096 + VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
1.2097 +#endif
1.2098 + return p->iReg;
1.2099 + }
1.2100 + }
1.2101 + assert( v!=0 );
1.2102 + if( iColumn<0 ){
1.2103 + int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
1.2104 + sqlite3VdbeAddOp2(v, op, iTable, iReg);
1.2105 + }else if( pTab==0 ){
1.2106 + sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
1.2107 + }else{
1.2108 + int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1.2109 + sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
1.2110 + sqlite3ColumnDefault(v, pTab, iColumn);
1.2111 +#ifndef SQLITE_OMIT_FLOATING_POINT
1.2112 + if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1.2113 + sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
1.2114 + }
1.2115 +#endif
1.2116 + }
1.2117 + if( pParse->disableColCache==0 ){
1.2118 + i = pParse->iColCache;
1.2119 + p = &pParse->aColCache[i];
1.2120 + p->iTable = iTable;
1.2121 + p->iColumn = iColumn;
1.2122 + p->iReg = iReg;
1.2123 + p->affChange = 0;
1.2124 + i++;
1.2125 + if( i>=ArraySize(pParse->aColCache) ) i = 0;
1.2126 + if( i>pParse->nColCache ) pParse->nColCache = i;
1.2127 + pParse->iColCache = i;
1.2128 + }
1.2129 + return iReg;
1.2130 +}
1.2131 +
1.2132 +/*
1.2133 +** Clear all column cache entries associated with the vdbe
1.2134 +** cursor with cursor number iTable.
1.2135 +*/
1.2136 +void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
1.2137 + if( iTable<0 ){
1.2138 + pParse->nColCache = 0;
1.2139 + pParse->iColCache = 0;
1.2140 + }else{
1.2141 + int i;
1.2142 + for(i=0; i<pParse->nColCache; i++){
1.2143 + if( pParse->aColCache[i].iTable==iTable ){
1.2144 + testcase( i==pParse->nColCache-1 );
1.2145 + pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
1.2146 + pParse->iColCache = pParse->nColCache;
1.2147 + }
1.2148 + }
1.2149 + }
1.2150 +}
1.2151 +
1.2152 +/*
1.2153 +** Record the fact that an affinity change has occurred on iCount
1.2154 +** registers starting with iStart.
1.2155 +*/
1.2156 +void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
1.2157 + int iEnd = iStart + iCount - 1;
1.2158 + int i;
1.2159 + for(i=0; i<pParse->nColCache; i++){
1.2160 + int r = pParse->aColCache[i].iReg;
1.2161 + if( r>=iStart && r<=iEnd ){
1.2162 + pParse->aColCache[i].affChange = 1;
1.2163 + }
1.2164 + }
1.2165 +}
1.2166 +
1.2167 +/*
1.2168 +** Generate code to move content from registers iFrom...iFrom+nReg-1
1.2169 +** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
1.2170 +*/
1.2171 +void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
1.2172 + int i;
1.2173 + if( iFrom==iTo ) return;
1.2174 + sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
1.2175 + for(i=0; i<pParse->nColCache; i++){
1.2176 + int x = pParse->aColCache[i].iReg;
1.2177 + if( x>=iFrom && x<iFrom+nReg ){
1.2178 + pParse->aColCache[i].iReg += iTo-iFrom;
1.2179 + }
1.2180 + }
1.2181 +}
1.2182 +
1.2183 +/*
1.2184 +** Generate code to copy content from registers iFrom...iFrom+nReg-1
1.2185 +** over to iTo..iTo+nReg-1.
1.2186 +*/
1.2187 +void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
1.2188 + int i;
1.2189 + if( iFrom==iTo ) return;
1.2190 + for(i=0; i<nReg; i++){
1.2191 + sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
1.2192 + }
1.2193 +}
1.2194 +
1.2195 +/*
1.2196 +** Return true if any register in the range iFrom..iTo (inclusive)
1.2197 +** is used as part of the column cache.
1.2198 +*/
1.2199 +static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
1.2200 + int i;
1.2201 + for(i=0; i<pParse->nColCache; i++){
1.2202 + int r = pParse->aColCache[i].iReg;
1.2203 + if( r>=iFrom && r<=iTo ) return 1;
1.2204 + }
1.2205 + return 0;
1.2206 +}
1.2207 +
1.2208 +/*
1.2209 +** Theres is a value in register iCurrent. We ultimately want
1.2210 +** the value to be in register iTarget. It might be that
1.2211 +** iCurrent and iTarget are the same register.
1.2212 +**
1.2213 +** We are going to modify the value, so we need to make sure it
1.2214 +** is not a cached register. If iCurrent is a cached register,
1.2215 +** then try to move the value over to iTarget. If iTarget is a
1.2216 +** cached register, then clear the corresponding cache line.
1.2217 +**
1.2218 +** Return the register that the value ends up in.
1.2219 +*/
1.2220 +int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
1.2221 + int i;
1.2222 + assert( pParse->pVdbe!=0 );
1.2223 + if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
1.2224 + return iCurrent;
1.2225 + }
1.2226 + if( iCurrent!=iTarget ){
1.2227 + sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
1.2228 + }
1.2229 + for(i=0; i<pParse->nColCache; i++){
1.2230 + if( pParse->aColCache[i].iReg==iTarget ){
1.2231 + pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
1.2232 + pParse->iColCache = pParse->nColCache;
1.2233 + }
1.2234 + }
1.2235 + return iTarget;
1.2236 +}
1.2237 +
1.2238 +/*
1.2239 +** If the last instruction coded is an ephemeral copy of any of
1.2240 +** the registers in the nReg registers beginning with iReg, then
1.2241 +** convert the last instruction from OP_SCopy to OP_Copy.
1.2242 +*/
1.2243 +void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
1.2244 + int addr;
1.2245 + VdbeOp *pOp;
1.2246 + Vdbe *v;
1.2247 +
1.2248 + v = pParse->pVdbe;
1.2249 + addr = sqlite3VdbeCurrentAddr(v);
1.2250 + pOp = sqlite3VdbeGetOp(v, addr-1);
1.2251 + assert( pOp || pParse->db->mallocFailed );
1.2252 + if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
1.2253 + pOp->opcode = OP_Copy;
1.2254 + }
1.2255 +}
1.2256 +
1.2257 +/*
1.2258 +** Generate code into the current Vdbe to evaluate the given
1.2259 +** expression. Attempt to store the results in register "target".
1.2260 +** Return the register where results are stored.
1.2261 +**
1.2262 +** With this routine, there is no guaranteed that results will
1.2263 +** be stored in target. The result might be stored in some other
1.2264 +** register if it is convenient to do so. The calling function
1.2265 +** must check the return code and move the results to the desired
1.2266 +** register.
1.2267 +*/
1.2268 +int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
1.2269 + Vdbe *v = pParse->pVdbe; /* The VM under construction */
1.2270 + int op; /* The opcode being coded */
1.2271 + int inReg = target; /* Results stored in register inReg */
1.2272 + int regFree1 = 0; /* If non-zero free this temporary register */
1.2273 + int regFree2 = 0; /* If non-zero free this temporary register */
1.2274 + int r1, r2, r3, r4; /* Various register numbers */
1.2275 +
1.2276 + assert( v!=0 || pParse->db->mallocFailed );
1.2277 + assert( target>0 && target<=pParse->nMem );
1.2278 + if( v==0 ) return 0;
1.2279 +
1.2280 + if( pExpr==0 ){
1.2281 + op = TK_NULL;
1.2282 + }else{
1.2283 + op = pExpr->op;
1.2284 + }
1.2285 + switch( op ){
1.2286 + case TK_AGG_COLUMN: {
1.2287 + AggInfo *pAggInfo = pExpr->pAggInfo;
1.2288 + struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
1.2289 + if( !pAggInfo->directMode ){
1.2290 + assert( pCol->iMem>0 );
1.2291 + inReg = pCol->iMem;
1.2292 + break;
1.2293 + }else if( pAggInfo->useSortingIdx ){
1.2294 + sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
1.2295 + pCol->iSorterColumn, target);
1.2296 + break;
1.2297 + }
1.2298 + /* Otherwise, fall thru into the TK_COLUMN case */
1.2299 + }
1.2300 + case TK_COLUMN: {
1.2301 + if( pExpr->iTable<0 ){
1.2302 + /* This only happens when coding check constraints */
1.2303 + assert( pParse->ckBase>0 );
1.2304 + inReg = pExpr->iColumn + pParse->ckBase;
1.2305 + }else{
1.2306 + testcase( (pExpr->flags & EP_AnyAff)!=0 );
1.2307 + inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
1.2308 + pExpr->iColumn, pExpr->iTable, target,
1.2309 + pExpr->flags & EP_AnyAff);
1.2310 + }
1.2311 + break;
1.2312 + }
1.2313 + case TK_INTEGER: {
1.2314 + codeInteger(v, pExpr, 0, target);
1.2315 + break;
1.2316 + }
1.2317 + case TK_FLOAT: {
1.2318 + codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
1.2319 + break;
1.2320 + }
1.2321 + case TK_STRING: {
1.2322 + sqlite3DequoteExpr(pParse->db, pExpr);
1.2323 + sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
1.2324 + (char*)pExpr->token.z, pExpr->token.n);
1.2325 + break;
1.2326 + }
1.2327 + case TK_NULL: {
1.2328 + sqlite3VdbeAddOp2(v, OP_Null, 0, target);
1.2329 + break;
1.2330 + }
1.2331 +#ifndef SQLITE_OMIT_BLOB_LITERAL
1.2332 + case TK_BLOB: {
1.2333 + int n;
1.2334 + const char *z;
1.2335 + char *zBlob;
1.2336 + assert( pExpr->token.n>=3 );
1.2337 + assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
1.2338 + assert( pExpr->token.z[1]=='\'' );
1.2339 + assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
1.2340 + n = pExpr->token.n - 3;
1.2341 + z = (char*)pExpr->token.z + 2;
1.2342 + zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
1.2343 + sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
1.2344 + break;
1.2345 + }
1.2346 +#endif
1.2347 + case TK_VARIABLE: {
1.2348 + sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
1.2349 + if( pExpr->token.n>1 ){
1.2350 + sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1.2351 + }
1.2352 + break;
1.2353 + }
1.2354 + case TK_REGISTER: {
1.2355 + inReg = pExpr->iTable;
1.2356 + break;
1.2357 + }
1.2358 +#ifndef SQLITE_OMIT_CAST
1.2359 + case TK_CAST: {
1.2360 + /* Expressions of the form: CAST(pLeft AS token) */
1.2361 + int aff, to_op;
1.2362 + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
1.2363 + aff = sqlite3AffinityType(&pExpr->token);
1.2364 + to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1.2365 + assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
1.2366 + assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
1.2367 + assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1.2368 + assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
1.2369 + assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
1.2370 + testcase( to_op==OP_ToText );
1.2371 + testcase( to_op==OP_ToBlob );
1.2372 + testcase( to_op==OP_ToNumeric );
1.2373 + testcase( to_op==OP_ToInt );
1.2374 + testcase( to_op==OP_ToReal );
1.2375 + sqlite3VdbeAddOp1(v, to_op, inReg);
1.2376 + testcase( usedAsColumnCache(pParse, inReg, inReg) );
1.2377 + sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
1.2378 + break;
1.2379 + }
1.2380 +#endif /* SQLITE_OMIT_CAST */
1.2381 + case TK_LT:
1.2382 + case TK_LE:
1.2383 + case TK_GT:
1.2384 + case TK_GE:
1.2385 + case TK_NE:
1.2386 + case TK_EQ: {
1.2387 + assert( TK_LT==OP_Lt );
1.2388 + assert( TK_LE==OP_Le );
1.2389 + assert( TK_GT==OP_Gt );
1.2390 + assert( TK_GE==OP_Ge );
1.2391 + assert( TK_EQ==OP_Eq );
1.2392 + assert( TK_NE==OP_Ne );
1.2393 + testcase( op==TK_LT );
1.2394 + testcase( op==TK_LE );
1.2395 + testcase( op==TK_GT );
1.2396 + testcase( op==TK_GE );
1.2397 + testcase( op==TK_EQ );
1.2398 + testcase( op==TK_NE );
1.2399 + codeCompareOperands(pParse, pExpr->pLeft, &r1, ®Free1,
1.2400 + pExpr->pRight, &r2, ®Free2);
1.2401 + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
1.2402 + r1, r2, inReg, SQLITE_STOREP2);
1.2403 + testcase( regFree1==0 );
1.2404 + testcase( regFree2==0 );
1.2405 + break;
1.2406 + }
1.2407 + case TK_AND:
1.2408 + case TK_OR:
1.2409 + case TK_PLUS:
1.2410 + case TK_STAR:
1.2411 + case TK_MINUS:
1.2412 + case TK_REM:
1.2413 + case TK_BITAND:
1.2414 + case TK_BITOR:
1.2415 + case TK_SLASH:
1.2416 + case TK_LSHIFT:
1.2417 + case TK_RSHIFT:
1.2418 + case TK_CONCAT: {
1.2419 + assert( TK_AND==OP_And );
1.2420 + assert( TK_OR==OP_Or );
1.2421 + assert( TK_PLUS==OP_Add );
1.2422 + assert( TK_MINUS==OP_Subtract );
1.2423 + assert( TK_REM==OP_Remainder );
1.2424 + assert( TK_BITAND==OP_BitAnd );
1.2425 + assert( TK_BITOR==OP_BitOr );
1.2426 + assert( TK_SLASH==OP_Divide );
1.2427 + assert( TK_LSHIFT==OP_ShiftLeft );
1.2428 + assert( TK_RSHIFT==OP_ShiftRight );
1.2429 + assert( TK_CONCAT==OP_Concat );
1.2430 + testcase( op==TK_AND );
1.2431 + testcase( op==TK_OR );
1.2432 + testcase( op==TK_PLUS );
1.2433 + testcase( op==TK_MINUS );
1.2434 + testcase( op==TK_REM );
1.2435 + testcase( op==TK_BITAND );
1.2436 + testcase( op==TK_BITOR );
1.2437 + testcase( op==TK_SLASH );
1.2438 + testcase( op==TK_LSHIFT );
1.2439 + testcase( op==TK_RSHIFT );
1.2440 + testcase( op==TK_CONCAT );
1.2441 + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
1.2442 + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
1.2443 + sqlite3VdbeAddOp3(v, op, r2, r1, target);
1.2444 + testcase( regFree1==0 );
1.2445 + testcase( regFree2==0 );
1.2446 + break;
1.2447 + }
1.2448 + case TK_UMINUS: {
1.2449 + Expr *pLeft = pExpr->pLeft;
1.2450 + assert( pLeft );
1.2451 + if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1.2452 + if( pLeft->op==TK_FLOAT ){
1.2453 + codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target);
1.2454 + }else{
1.2455 + codeInteger(v, pLeft, 1, target);
1.2456 + }
1.2457 + }else{
1.2458 + regFree1 = r1 = sqlite3GetTempReg(pParse);
1.2459 + sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
1.2460 + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2);
1.2461 + sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
1.2462 + testcase( regFree2==0 );
1.2463 + }
1.2464 + inReg = target;
1.2465 + break;
1.2466 + }
1.2467 + case TK_BITNOT:
1.2468 + case TK_NOT: {
1.2469 + assert( TK_BITNOT==OP_BitNot );
1.2470 + assert( TK_NOT==OP_Not );
1.2471 + testcase( op==TK_BITNOT );
1.2472 + testcase( op==TK_NOT );
1.2473 + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
1.2474 + testcase( inReg==target );
1.2475 + testcase( usedAsColumnCache(pParse, inReg, inReg) );
1.2476 + inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
1.2477 + sqlite3VdbeAddOp1(v, op, inReg);
1.2478 + break;
1.2479 + }
1.2480 + case TK_ISNULL:
1.2481 + case TK_NOTNULL: {
1.2482 + int addr;
1.2483 + assert( TK_ISNULL==OP_IsNull );
1.2484 + assert( TK_NOTNULL==OP_NotNull );
1.2485 + testcase( op==TK_ISNULL );
1.2486 + testcase( op==TK_NOTNULL );
1.2487 + sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
1.2488 + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
1.2489 + testcase( regFree1==0 );
1.2490 + addr = sqlite3VdbeAddOp1(v, op, r1);
1.2491 + sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
1.2492 + sqlite3VdbeJumpHere(v, addr);
1.2493 + break;
1.2494 + }
1.2495 + case TK_AGG_FUNCTION: {
1.2496 + AggInfo *pInfo = pExpr->pAggInfo;
1.2497 + if( pInfo==0 ){
1.2498 + sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
1.2499 + &pExpr->span);
1.2500 + }else{
1.2501 + inReg = pInfo->aFunc[pExpr->iAgg].iMem;
1.2502 + }
1.2503 + break;
1.2504 + }
1.2505 + case TK_CONST_FUNC:
1.2506 + case TK_FUNCTION: {
1.2507 + ExprList *pList = pExpr->pList;
1.2508 + int nExpr = pList ? pList->nExpr : 0;
1.2509 + FuncDef *pDef;
1.2510 + int nId;
1.2511 + const char *zId;
1.2512 + int constMask = 0;
1.2513 + int i;
1.2514 + sqlite3 *db = pParse->db;
1.2515 + u8 enc = ENC(db);
1.2516 + CollSeq *pColl = 0;
1.2517 +
1.2518 + testcase( op==TK_CONST_FUNC );
1.2519 + testcase( op==TK_FUNCTION );
1.2520 + zId = (char*)pExpr->token.z;
1.2521 + nId = pExpr->token.n;
1.2522 + pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
1.2523 + assert( pDef!=0 );
1.2524 + if( pList ){
1.2525 + nExpr = pList->nExpr;
1.2526 + r1 = sqlite3GetTempRange(pParse, nExpr);
1.2527 + sqlite3ExprCodeExprList(pParse, pList, r1, 1);
1.2528 + }else{
1.2529 + nExpr = r1 = 0;
1.2530 + }
1.2531 +#ifndef SQLITE_OMIT_VIRTUALTABLE
1.2532 + /* Possibly overload the function if the first argument is
1.2533 + ** a virtual table column.
1.2534 + **
1.2535 + ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1.2536 + ** second argument, not the first, as the argument to test to
1.2537 + ** see if it is a column in a virtual table. This is done because
1.2538 + ** the left operand of infix functions (the operand we want to
1.2539 + ** control overloading) ends up as the second argument to the
1.2540 + ** function. The expression "A glob B" is equivalent to
1.2541 + ** "glob(B,A). We want to use the A in "A glob B" to test
1.2542 + ** for function overloading. But we use the B term in "glob(B,A)".
1.2543 + */
1.2544 + if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
1.2545 + pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
1.2546 + }else if( nExpr>0 ){
1.2547 + pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
1.2548 + }
1.2549 +#endif
1.2550 + for(i=0; i<nExpr && i<32; i++){
1.2551 + if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
1.2552 + constMask |= (1<<i);
1.2553 + }
1.2554 + if( pDef->needCollSeq && !pColl ){
1.2555 + pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1.2556 + }
1.2557 + }
1.2558 + if( pDef->needCollSeq ){
1.2559 + if( !pColl ) pColl = pParse->db->pDfltColl;
1.2560 + sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
1.2561 + }
1.2562 + sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
1.2563 + (char*)pDef, P4_FUNCDEF);
1.2564 + sqlite3VdbeChangeP5(v, nExpr);
1.2565 + if( nExpr ){
1.2566 + sqlite3ReleaseTempRange(pParse, r1, nExpr);
1.2567 + }
1.2568 + sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
1.2569 + break;
1.2570 + }
1.2571 +#ifndef SQLITE_OMIT_SUBQUERY
1.2572 + case TK_EXISTS:
1.2573 + case TK_SELECT: {
1.2574 + testcase( op==TK_EXISTS );
1.2575 + testcase( op==TK_SELECT );
1.2576 + if( pExpr->iColumn==0 ){
1.2577 + sqlite3CodeSubselect(pParse, pExpr, 0);
1.2578 + }
1.2579 + inReg = pExpr->iColumn;
1.2580 + break;
1.2581 + }
1.2582 + case TK_IN: {
1.2583 + int rNotFound = 0;
1.2584 + int rMayHaveNull = 0;
1.2585 + int j2, j3, j4, j5;
1.2586 + char affinity;
1.2587 + int eType;
1.2588 +
1.2589 + VdbeNoopComment((v, "begin IN expr r%d", target));
1.2590 + eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull);
1.2591 + if( rMayHaveNull ){
1.2592 + rNotFound = ++pParse->nMem;
1.2593 + }
1.2594 +
1.2595 + /* Figure out the affinity to use to create a key from the results
1.2596 + ** of the expression. affinityStr stores a static string suitable for
1.2597 + ** P4 of OP_MakeRecord.
1.2598 + */
1.2599 + affinity = comparisonAffinity(pExpr);
1.2600 +
1.2601 +
1.2602 + /* Code the <expr> from "<expr> IN (...)". The temporary table
1.2603 + ** pExpr->iTable contains the values that make up the (...) set.
1.2604 + */
1.2605 + pParse->disableColCache++;
1.2606 + sqlite3ExprCode(pParse, pExpr->pLeft, target);
1.2607 + pParse->disableColCache--;
1.2608 + j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target);
1.2609 + if( eType==IN_INDEX_ROWID ){
1.2610 + j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target);
1.2611 + j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target);
1.2612 + sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
1.2613 + j5 = sqlite3VdbeAddOp0(v, OP_Goto);
1.2614 + sqlite3VdbeJumpHere(v, j3);
1.2615 + sqlite3VdbeJumpHere(v, j4);
1.2616 + sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
1.2617 + }else{
1.2618 + r2 = regFree2 = sqlite3GetTempReg(pParse);
1.2619 +
1.2620 + /* Create a record and test for set membership. If the set contains
1.2621 + ** the value, then jump to the end of the test code. The target
1.2622 + ** register still contains the true (1) value written to it earlier.
1.2623 + */
1.2624 + sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1);
1.2625 + sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
1.2626 + j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
1.2627 +
1.2628 + /* If the set membership test fails, then the result of the
1.2629 + ** "x IN (...)" expression must be either 0 or NULL. If the set
1.2630 + ** contains no NULL values, then the result is 0. If the set
1.2631 + ** contains one or more NULL values, then the result of the
1.2632 + ** expression is also NULL.
1.2633 + */
1.2634 + if( rNotFound==0 ){
1.2635 + /* This branch runs if it is known at compile time (now) that
1.2636 + ** the set contains no NULL values. This happens as the result
1.2637 + ** of a "NOT NULL" constraint in the database schema. No need
1.2638 + ** to test the data structure at runtime in this case.
1.2639 + */
1.2640 + sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
1.2641 + }else{
1.2642 + /* This block populates the rNotFound register with either NULL
1.2643 + ** or 0 (an integer value). If the data structure contains one
1.2644 + ** or more NULLs, then set rNotFound to NULL. Otherwise, set it
1.2645 + ** to 0. If register rMayHaveNull is already set to some value
1.2646 + ** other than NULL, then the test has already been run and
1.2647 + ** rNotFound is already populated.
1.2648 + */
1.2649 + static const char nullRecord[] = { 0x02, 0x00 };
1.2650 + j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull);
1.2651 + sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound);
1.2652 + sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0,
1.2653 + nullRecord, P4_STATIC);
1.2654 + j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull);
1.2655 + sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound);
1.2656 + sqlite3VdbeJumpHere(v, j4);
1.2657 + sqlite3VdbeJumpHere(v, j3);
1.2658 +
1.2659 + /* Copy the value of register rNotFound (which is either NULL or 0)
1.2660 + ** into the target register. This will be the result of the
1.2661 + ** expression.
1.2662 + */
1.2663 + sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target);
1.2664 + }
1.2665 + }
1.2666 + sqlite3VdbeJumpHere(v, j2);
1.2667 + sqlite3VdbeJumpHere(v, j5);
1.2668 + VdbeComment((v, "end IN expr r%d", target));
1.2669 + break;
1.2670 + }
1.2671 +#endif
1.2672 + /*
1.2673 + ** x BETWEEN y AND z
1.2674 + **
1.2675 + ** This is equivalent to
1.2676 + **
1.2677 + ** x>=y AND x<=z
1.2678 + **
1.2679 + ** X is stored in pExpr->pLeft.
1.2680 + ** Y is stored in pExpr->pList->a[0].pExpr.
1.2681 + ** Z is stored in pExpr->pList->a[1].pExpr.
1.2682 + */
1.2683 + case TK_BETWEEN: {
1.2684 + Expr *pLeft = pExpr->pLeft;
1.2685 + struct ExprList_item *pLItem = pExpr->pList->a;
1.2686 + Expr *pRight = pLItem->pExpr;
1.2687 +
1.2688 + codeCompareOperands(pParse, pLeft, &r1, ®Free1,
1.2689 + pRight, &r2, ®Free2);
1.2690 + testcase( regFree1==0 );
1.2691 + testcase( regFree2==0 );
1.2692 + r3 = sqlite3GetTempReg(pParse);
1.2693 + r4 = sqlite3GetTempReg(pParse);
1.2694 + codeCompare(pParse, pLeft, pRight, OP_Ge,
1.2695 + r1, r2, r3, SQLITE_STOREP2);
1.2696 + pLItem++;
1.2697 + pRight = pLItem->pExpr;
1.2698 + sqlite3ReleaseTempReg(pParse, regFree2);
1.2699 + r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2);
1.2700 + testcase( regFree2==0 );
1.2701 + codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
1.2702 + sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
1.2703 + sqlite3ReleaseTempReg(pParse, r3);
1.2704 + sqlite3ReleaseTempReg(pParse, r4);
1.2705 + break;
1.2706 + }
1.2707 + case TK_UPLUS: {
1.2708 + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
1.2709 + break;
1.2710 + }
1.2711 +
1.2712 + /*
1.2713 + ** Form A:
1.2714 + ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
1.2715 + **
1.2716 + ** Form B:
1.2717 + ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
1.2718 + **
1.2719 + ** Form A is can be transformed into the equivalent form B as follows:
1.2720 + ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
1.2721 + ** WHEN x=eN THEN rN ELSE y END
1.2722 + **
1.2723 + ** X (if it exists) is in pExpr->pLeft.
1.2724 + ** Y is in pExpr->pRight. The Y is also optional. If there is no
1.2725 + ** ELSE clause and no other term matches, then the result of the
1.2726 + ** exprssion is NULL.
1.2727 + ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
1.2728 + **
1.2729 + ** The result of the expression is the Ri for the first matching Ei,
1.2730 + ** or if there is no matching Ei, the ELSE term Y, or if there is
1.2731 + ** no ELSE term, NULL.
1.2732 + */
1.2733 + case TK_CASE: {
1.2734 + int endLabel; /* GOTO label for end of CASE stmt */
1.2735 + int nextCase; /* GOTO label for next WHEN clause */
1.2736 + int nExpr; /* 2x number of WHEN terms */
1.2737 + int i; /* Loop counter */
1.2738 + ExprList *pEList; /* List of WHEN terms */
1.2739 + struct ExprList_item *aListelem; /* Array of WHEN terms */
1.2740 + Expr opCompare; /* The X==Ei expression */
1.2741 + Expr cacheX; /* Cached expression X */
1.2742 + Expr *pX; /* The X expression */
1.2743 + Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
1.2744 +
1.2745 + assert(pExpr->pList);
1.2746 + assert((pExpr->pList->nExpr % 2) == 0);
1.2747 + assert(pExpr->pList->nExpr > 0);
1.2748 + pEList = pExpr->pList;
1.2749 + aListelem = pEList->a;
1.2750 + nExpr = pEList->nExpr;
1.2751 + endLabel = sqlite3VdbeMakeLabel(v);
1.2752 + if( (pX = pExpr->pLeft)!=0 ){
1.2753 + cacheX = *pX;
1.2754 + testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
1.2755 + cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, ®Free1);
1.2756 + testcase( regFree1==0 );
1.2757 + cacheX.op = TK_REGISTER;
1.2758 + cacheX.iColumn = 0;
1.2759 + opCompare.op = TK_EQ;
1.2760 + opCompare.pLeft = &cacheX;
1.2761 + pTest = &opCompare;
1.2762 + }
1.2763 + pParse->disableColCache++;
1.2764 + for(i=0; i<nExpr; i=i+2){
1.2765 + if( pX ){
1.2766 + opCompare.pRight = aListelem[i].pExpr;
1.2767 + }else{
1.2768 + pTest = aListelem[i].pExpr;
1.2769 + }
1.2770 + nextCase = sqlite3VdbeMakeLabel(v);
1.2771 + testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
1.2772 + sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
1.2773 + testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
1.2774 + testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
1.2775 + sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
1.2776 + sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
1.2777 + sqlite3VdbeResolveLabel(v, nextCase);
1.2778 + }
1.2779 + if( pExpr->pRight ){
1.2780 + sqlite3ExprCode(pParse, pExpr->pRight, target);
1.2781 + }else{
1.2782 + sqlite3VdbeAddOp2(v, OP_Null, 0, target);
1.2783 + }
1.2784 + sqlite3VdbeResolveLabel(v, endLabel);
1.2785 + assert( pParse->disableColCache>0 );
1.2786 + pParse->disableColCache--;
1.2787 + break;
1.2788 + }
1.2789 +#ifndef SQLITE_OMIT_TRIGGER
1.2790 + case TK_RAISE: {
1.2791 + if( !pParse->trigStack ){
1.2792 + sqlite3ErrorMsg(pParse,
1.2793 + "RAISE() may only be used within a trigger-program");
1.2794 + return 0;
1.2795 + }
1.2796 + if( pExpr->iColumn!=OE_Ignore ){
1.2797 + assert( pExpr->iColumn==OE_Rollback ||
1.2798 + pExpr->iColumn == OE_Abort ||
1.2799 + pExpr->iColumn == OE_Fail );
1.2800 + sqlite3DequoteExpr(pParse->db, pExpr);
1.2801 + sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
1.2802 + (char*)pExpr->token.z, pExpr->token.n);
1.2803 + } else {
1.2804 + assert( pExpr->iColumn == OE_Ignore );
1.2805 + sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
1.2806 + sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1.2807 + VdbeComment((v, "raise(IGNORE)"));
1.2808 + }
1.2809 + break;
1.2810 + }
1.2811 +#endif
1.2812 + }
1.2813 + sqlite3ReleaseTempReg(pParse, regFree1);
1.2814 + sqlite3ReleaseTempReg(pParse, regFree2);
1.2815 + return inReg;
1.2816 +}
1.2817 +
1.2818 +/*
1.2819 +** Generate code to evaluate an expression and store the results
1.2820 +** into a register. Return the register number where the results
1.2821 +** are stored.
1.2822 +**
1.2823 +** If the register is a temporary register that can be deallocated,
1.2824 +** then write its number into *pReg. If the result register is not
1.2825 +** a temporary, then set *pReg to zero.
1.2826 +*/
1.2827 +int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
1.2828 + int r1 = sqlite3GetTempReg(pParse);
1.2829 + int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
1.2830 + if( r2==r1 ){
1.2831 + *pReg = r1;
1.2832 + }else{
1.2833 + sqlite3ReleaseTempReg(pParse, r1);
1.2834 + *pReg = 0;
1.2835 + }
1.2836 + return r2;
1.2837 +}
1.2838 +
1.2839 +/*
1.2840 +** Generate code that will evaluate expression pExpr and store the
1.2841 +** results in register target. The results are guaranteed to appear
1.2842 +** in register target.
1.2843 +*/
1.2844 +int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
1.2845 + int inReg;
1.2846 +
1.2847 + assert( target>0 && target<=pParse->nMem );
1.2848 + inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
1.2849 + assert( pParse->pVdbe || pParse->db->mallocFailed );
1.2850 + if( inReg!=target && pParse->pVdbe ){
1.2851 + sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
1.2852 + }
1.2853 + return target;
1.2854 +}
1.2855 +
1.2856 +/*
1.2857 +** Generate code that evalutes the given expression and puts the result
1.2858 +** in register target.
1.2859 +**
1.2860 +** Also make a copy of the expression results into another "cache" register
1.2861 +** and modify the expression so that the next time it is evaluated,
1.2862 +** the result is a copy of the cache register.
1.2863 +**
1.2864 +** This routine is used for expressions that are used multiple
1.2865 +** times. They are evaluated once and the results of the expression
1.2866 +** are reused.
1.2867 +*/
1.2868 +int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
1.2869 + Vdbe *v = pParse->pVdbe;
1.2870 + int inReg;
1.2871 + inReg = sqlite3ExprCode(pParse, pExpr, target);
1.2872 + assert( target>0 );
1.2873 + if( pExpr->op!=TK_REGISTER ){
1.2874 + int iMem;
1.2875 + iMem = ++pParse->nMem;
1.2876 + sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
1.2877 + pExpr->iTable = iMem;
1.2878 + pExpr->iColumn = pExpr->op;
1.2879 + pExpr->op = TK_REGISTER;
1.2880 + }
1.2881 + return inReg;
1.2882 +}
1.2883 +
1.2884 +/*
1.2885 +** Return TRUE if pExpr is an constant expression that is appropriate
1.2886 +** for factoring out of a loop. Appropriate expressions are:
1.2887 +**
1.2888 +** * Any expression that evaluates to two or more opcodes.
1.2889 +**
1.2890 +** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
1.2891 +** or OP_Variable that does not need to be placed in a
1.2892 +** specific register.
1.2893 +**
1.2894 +** There is no point in factoring out single-instruction constant
1.2895 +** expressions that need to be placed in a particular register.
1.2896 +** We could factor them out, but then we would end up adding an
1.2897 +** OP_SCopy instruction to move the value into the correct register
1.2898 +** later. We might as well just use the original instruction and
1.2899 +** avoid the OP_SCopy.
1.2900 +*/
1.2901 +static int isAppropriateForFactoring(Expr *p){
1.2902 + if( !sqlite3ExprIsConstantNotJoin(p) ){
1.2903 + return 0; /* Only constant expressions are appropriate for factoring */
1.2904 + }
1.2905 + if( (p->flags & EP_FixedDest)==0 ){
1.2906 + return 1; /* Any constant without a fixed destination is appropriate */
1.2907 + }
1.2908 + while( p->op==TK_UPLUS ) p = p->pLeft;
1.2909 + switch( p->op ){
1.2910 +#ifndef SQLITE_OMIT_BLOB_LITERAL
1.2911 + case TK_BLOB:
1.2912 +#endif
1.2913 + case TK_VARIABLE:
1.2914 + case TK_INTEGER:
1.2915 + case TK_FLOAT:
1.2916 + case TK_NULL:
1.2917 + case TK_STRING: {
1.2918 + testcase( p->op==TK_BLOB );
1.2919 + testcase( p->op==TK_VARIABLE );
1.2920 + testcase( p->op==TK_INTEGER );
1.2921 + testcase( p->op==TK_FLOAT );
1.2922 + testcase( p->op==TK_NULL );
1.2923 + testcase( p->op==TK_STRING );
1.2924 + /* Single-instruction constants with a fixed destination are
1.2925 + ** better done in-line. If we factor them, they will just end
1.2926 + ** up generating an OP_SCopy to move the value to the destination
1.2927 + ** register. */
1.2928 + return 0;
1.2929 + }
1.2930 + case TK_UMINUS: {
1.2931 + if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
1.2932 + return 0;
1.2933 + }
1.2934 + break;
1.2935 + }
1.2936 + default: {
1.2937 + break;
1.2938 + }
1.2939 + }
1.2940 + return 1;
1.2941 +}
1.2942 +
1.2943 +/*
1.2944 +** If pExpr is a constant expression that is appropriate for
1.2945 +** factoring out of a loop, then evaluate the expression
1.2946 +** into a register and convert the expression into a TK_REGISTER
1.2947 +** expression.
1.2948 +*/
1.2949 +static int evalConstExpr(void *pArg, Expr *pExpr){
1.2950 + Parse *pParse = (Parse*)pArg;
1.2951 + switch( pExpr->op ){
1.2952 + case TK_REGISTER: {
1.2953 + return 1;
1.2954 + }
1.2955 + case TK_FUNCTION:
1.2956 + case TK_AGG_FUNCTION:
1.2957 + case TK_CONST_FUNC: {
1.2958 + /* The arguments to a function have a fixed destination.
1.2959 + ** Mark them this way to avoid generated unneeded OP_SCopy
1.2960 + ** instructions.
1.2961 + */
1.2962 + ExprList *pList = pExpr->pList;
1.2963 + if( pList ){
1.2964 + int i = pList->nExpr;
1.2965 + struct ExprList_item *pItem = pList->a;
1.2966 + for(; i>0; i--, pItem++){
1.2967 + if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
1.2968 + }
1.2969 + }
1.2970 + break;
1.2971 + }
1.2972 + }
1.2973 + if( isAppropriateForFactoring(pExpr) ){
1.2974 + int r1 = ++pParse->nMem;
1.2975 + int r2;
1.2976 + r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
1.2977 + if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
1.2978 + pExpr->iColumn = pExpr->op;
1.2979 + pExpr->op = TK_REGISTER;
1.2980 + pExpr->iTable = r2;
1.2981 + return 1;
1.2982 + }
1.2983 + return 0;
1.2984 +}
1.2985 +
1.2986 +/*
1.2987 +** Preevaluate constant subexpressions within pExpr and store the
1.2988 +** results in registers. Modify pExpr so that the constant subexpresions
1.2989 +** are TK_REGISTER opcodes that refer to the precomputed values.
1.2990 +*/
1.2991 +void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
1.2992 + walkExprTree(pExpr, evalConstExpr, pParse);
1.2993 +}
1.2994 +
1.2995 +
1.2996 +/*
1.2997 +** Generate code that pushes the value of every element of the given
1.2998 +** expression list into a sequence of registers beginning at target.
1.2999 +**
1.3000 +** Return the number of elements evaluated.
1.3001 +*/
1.3002 +int sqlite3ExprCodeExprList(
1.3003 + Parse *pParse, /* Parsing context */
1.3004 + ExprList *pList, /* The expression list to be coded */
1.3005 + int target, /* Where to write results */
1.3006 + int doHardCopy /* Call sqlite3ExprHardCopy on each element if true */
1.3007 +){
1.3008 + struct ExprList_item *pItem;
1.3009 + int i, n;
1.3010 + assert( pList!=0 || pParse->db->mallocFailed );
1.3011 + if( pList==0 ){
1.3012 + return 0;
1.3013 + }
1.3014 + assert( target>0 );
1.3015 + n = pList->nExpr;
1.3016 + for(pItem=pList->a, i=0; i<n; i++, pItem++){
1.3017 + sqlite3ExprCode(pParse, pItem->pExpr, target+i);
1.3018 + if( doHardCopy ) sqlite3ExprHardCopy(pParse, target, n);
1.3019 + }
1.3020 + return n;
1.3021 +}
1.3022 +
1.3023 +/*
1.3024 +** Generate code for a boolean expression such that a jump is made
1.3025 +** to the label "dest" if the expression is true but execution
1.3026 +** continues straight thru if the expression is false.
1.3027 +**
1.3028 +** If the expression evaluates to NULL (neither true nor false), then
1.3029 +** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
1.3030 +**
1.3031 +** This code depends on the fact that certain token values (ex: TK_EQ)
1.3032 +** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1.3033 +** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
1.3034 +** the make process cause these values to align. Assert()s in the code
1.3035 +** below verify that the numbers are aligned correctly.
1.3036 +*/
1.3037 +void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1.3038 + Vdbe *v = pParse->pVdbe;
1.3039 + int op = 0;
1.3040 + int regFree1 = 0;
1.3041 + int regFree2 = 0;
1.3042 + int r1, r2;
1.3043 +
1.3044 + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
1.3045 + if( v==0 || pExpr==0 ) return;
1.3046 + op = pExpr->op;
1.3047 + switch( op ){
1.3048 + case TK_AND: {
1.3049 + int d2 = sqlite3VdbeMakeLabel(v);
1.3050 + testcase( jumpIfNull==0 );
1.3051 + testcase( pParse->disableColCache==0 );
1.3052 + sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
1.3053 + pParse->disableColCache++;
1.3054 + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1.3055 + assert( pParse->disableColCache>0 );
1.3056 + pParse->disableColCache--;
1.3057 + sqlite3VdbeResolveLabel(v, d2);
1.3058 + break;
1.3059 + }
1.3060 + case TK_OR: {
1.3061 + testcase( jumpIfNull==0 );
1.3062 + testcase( pParse->disableColCache==0 );
1.3063 + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1.3064 + pParse->disableColCache++;
1.3065 + sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1.3066 + assert( pParse->disableColCache>0 );
1.3067 + pParse->disableColCache--;
1.3068 + break;
1.3069 + }
1.3070 + case TK_NOT: {
1.3071 + testcase( jumpIfNull==0 );
1.3072 + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1.3073 + break;
1.3074 + }
1.3075 + case TK_LT:
1.3076 + case TK_LE:
1.3077 + case TK_GT:
1.3078 + case TK_GE:
1.3079 + case TK_NE:
1.3080 + case TK_EQ: {
1.3081 + assert( TK_LT==OP_Lt );
1.3082 + assert( TK_LE==OP_Le );
1.3083 + assert( TK_GT==OP_Gt );
1.3084 + assert( TK_GE==OP_Ge );
1.3085 + assert( TK_EQ==OP_Eq );
1.3086 + assert( TK_NE==OP_Ne );
1.3087 + testcase( op==TK_LT );
1.3088 + testcase( op==TK_LE );
1.3089 + testcase( op==TK_GT );
1.3090 + testcase( op==TK_GE );
1.3091 + testcase( op==TK_EQ );
1.3092 + testcase( op==TK_NE );
1.3093 + testcase( jumpIfNull==0 );
1.3094 + codeCompareOperands(pParse, pExpr->pLeft, &r1, ®Free1,
1.3095 + pExpr->pRight, &r2, ®Free2);
1.3096 + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
1.3097 + r1, r2, dest, jumpIfNull);
1.3098 + testcase( regFree1==0 );
1.3099 + testcase( regFree2==0 );
1.3100 + break;
1.3101 + }
1.3102 + case TK_ISNULL:
1.3103 + case TK_NOTNULL: {
1.3104 + assert( TK_ISNULL==OP_IsNull );
1.3105 + assert( TK_NOTNULL==OP_NotNull );
1.3106 + testcase( op==TK_ISNULL );
1.3107 + testcase( op==TK_NOTNULL );
1.3108 + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
1.3109 + sqlite3VdbeAddOp2(v, op, r1, dest);
1.3110 + testcase( regFree1==0 );
1.3111 + break;
1.3112 + }
1.3113 + case TK_BETWEEN: {
1.3114 + /* x BETWEEN y AND z
1.3115 + **
1.3116 + ** Is equivalent to
1.3117 + **
1.3118 + ** x>=y AND x<=z
1.3119 + **
1.3120 + ** Code it as such, taking care to do the common subexpression
1.3121 + ** elementation of x.
1.3122 + */
1.3123 + Expr exprAnd;
1.3124 + Expr compLeft;
1.3125 + Expr compRight;
1.3126 + Expr exprX;
1.3127 +
1.3128 + exprX = *pExpr->pLeft;
1.3129 + exprAnd.op = TK_AND;
1.3130 + exprAnd.pLeft = &compLeft;
1.3131 + exprAnd.pRight = &compRight;
1.3132 + compLeft.op = TK_GE;
1.3133 + compLeft.pLeft = &exprX;
1.3134 + compLeft.pRight = pExpr->pList->a[0].pExpr;
1.3135 + compRight.op = TK_LE;
1.3136 + compRight.pLeft = &exprX;
1.3137 + compRight.pRight = pExpr->pList->a[1].pExpr;
1.3138 + exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, ®Free1);
1.3139 + testcase( regFree1==0 );
1.3140 + exprX.op = TK_REGISTER;
1.3141 + testcase( jumpIfNull==0 );
1.3142 + sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
1.3143 + break;
1.3144 + }
1.3145 + default: {
1.3146 + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
1.3147 + sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
1.3148 + testcase( regFree1==0 );
1.3149 + testcase( jumpIfNull==0 );
1.3150 + break;
1.3151 + }
1.3152 + }
1.3153 + sqlite3ReleaseTempReg(pParse, regFree1);
1.3154 + sqlite3ReleaseTempReg(pParse, regFree2);
1.3155 +}
1.3156 +
1.3157 +/*
1.3158 +** Generate code for a boolean expression such that a jump is made
1.3159 +** to the label "dest" if the expression is false but execution
1.3160 +** continues straight thru if the expression is true.
1.3161 +**
1.3162 +** If the expression evaluates to NULL (neither true nor false) then
1.3163 +** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
1.3164 +** is 0.
1.3165 +*/
1.3166 +void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
1.3167 + Vdbe *v = pParse->pVdbe;
1.3168 + int op = 0;
1.3169 + int regFree1 = 0;
1.3170 + int regFree2 = 0;
1.3171 + int r1, r2;
1.3172 +
1.3173 + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
1.3174 + if( v==0 || pExpr==0 ) return;
1.3175 +
1.3176 + /* The value of pExpr->op and op are related as follows:
1.3177 + **
1.3178 + ** pExpr->op op
1.3179 + ** --------- ----------
1.3180 + ** TK_ISNULL OP_NotNull
1.3181 + ** TK_NOTNULL OP_IsNull
1.3182 + ** TK_NE OP_Eq
1.3183 + ** TK_EQ OP_Ne
1.3184 + ** TK_GT OP_Le
1.3185 + ** TK_LE OP_Gt
1.3186 + ** TK_GE OP_Lt
1.3187 + ** TK_LT OP_Ge
1.3188 + **
1.3189 + ** For other values of pExpr->op, op is undefined and unused.
1.3190 + ** The value of TK_ and OP_ constants are arranged such that we
1.3191 + ** can compute the mapping above using the following expression.
1.3192 + ** Assert()s verify that the computation is correct.
1.3193 + */
1.3194 + op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
1.3195 +
1.3196 + /* Verify correct alignment of TK_ and OP_ constants
1.3197 + */
1.3198 + assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
1.3199 + assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
1.3200 + assert( pExpr->op!=TK_NE || op==OP_Eq );
1.3201 + assert( pExpr->op!=TK_EQ || op==OP_Ne );
1.3202 + assert( pExpr->op!=TK_LT || op==OP_Ge );
1.3203 + assert( pExpr->op!=TK_LE || op==OP_Gt );
1.3204 + assert( pExpr->op!=TK_GT || op==OP_Le );
1.3205 + assert( pExpr->op!=TK_GE || op==OP_Lt );
1.3206 +
1.3207 + switch( pExpr->op ){
1.3208 + case TK_AND: {
1.3209 + testcase( jumpIfNull==0 );
1.3210 + testcase( pParse->disableColCache==0 );
1.3211 + sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
1.3212 + pParse->disableColCache++;
1.3213 + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
1.3214 + assert( pParse->disableColCache>0 );
1.3215 + pParse->disableColCache--;
1.3216 + break;
1.3217 + }
1.3218 + case TK_OR: {
1.3219 + int d2 = sqlite3VdbeMakeLabel(v);
1.3220 + testcase( jumpIfNull==0 );
1.3221 + testcase( pParse->disableColCache==0 );
1.3222 + sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
1.3223 + pParse->disableColCache++;
1.3224 + sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
1.3225 + assert( pParse->disableColCache>0 );
1.3226 + pParse->disableColCache--;
1.3227 + sqlite3VdbeResolveLabel(v, d2);
1.3228 + break;
1.3229 + }
1.3230 + case TK_NOT: {
1.3231 + sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1.3232 + break;
1.3233 + }
1.3234 + case TK_LT:
1.3235 + case TK_LE:
1.3236 + case TK_GT:
1.3237 + case TK_GE:
1.3238 + case TK_NE:
1.3239 + case TK_EQ: {
1.3240 + testcase( op==TK_LT );
1.3241 + testcase( op==TK_LE );
1.3242 + testcase( op==TK_GT );
1.3243 + testcase( op==TK_GE );
1.3244 + testcase( op==TK_EQ );
1.3245 + testcase( op==TK_NE );
1.3246 + testcase( jumpIfNull==0 );
1.3247 + codeCompareOperands(pParse, pExpr->pLeft, &r1, ®Free1,
1.3248 + pExpr->pRight, &r2, ®Free2);
1.3249 + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
1.3250 + r1, r2, dest, jumpIfNull);
1.3251 + testcase( regFree1==0 );
1.3252 + testcase( regFree2==0 );
1.3253 + break;
1.3254 + }
1.3255 + case TK_ISNULL:
1.3256 + case TK_NOTNULL: {
1.3257 + testcase( op==TK_ISNULL );
1.3258 + testcase( op==TK_NOTNULL );
1.3259 + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
1.3260 + sqlite3VdbeAddOp2(v, op, r1, dest);
1.3261 + testcase( regFree1==0 );
1.3262 + break;
1.3263 + }
1.3264 + case TK_BETWEEN: {
1.3265 + /* x BETWEEN y AND z
1.3266 + **
1.3267 + ** Is equivalent to
1.3268 + **
1.3269 + ** x>=y AND x<=z
1.3270 + **
1.3271 + ** Code it as such, taking care to do the common subexpression
1.3272 + ** elementation of x.
1.3273 + */
1.3274 + Expr exprAnd;
1.3275 + Expr compLeft;
1.3276 + Expr compRight;
1.3277 + Expr exprX;
1.3278 +
1.3279 + exprX = *pExpr->pLeft;
1.3280 + exprAnd.op = TK_AND;
1.3281 + exprAnd.pLeft = &compLeft;
1.3282 + exprAnd.pRight = &compRight;
1.3283 + compLeft.op = TK_GE;
1.3284 + compLeft.pLeft = &exprX;
1.3285 + compLeft.pRight = pExpr->pList->a[0].pExpr;
1.3286 + compRight.op = TK_LE;
1.3287 + compRight.pLeft = &exprX;
1.3288 + compRight.pRight = pExpr->pList->a[1].pExpr;
1.3289 + exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, ®Free1);
1.3290 + testcase( regFree1==0 );
1.3291 + exprX.op = TK_REGISTER;
1.3292 + testcase( jumpIfNull==0 );
1.3293 + sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
1.3294 + break;
1.3295 + }
1.3296 + default: {
1.3297 + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
1.3298 + sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
1.3299 + testcase( regFree1==0 );
1.3300 + testcase( jumpIfNull==0 );
1.3301 + break;
1.3302 + }
1.3303 + }
1.3304 + sqlite3ReleaseTempReg(pParse, regFree1);
1.3305 + sqlite3ReleaseTempReg(pParse, regFree2);
1.3306 +}
1.3307 +
1.3308 +/*
1.3309 +** Do a deep comparison of two expression trees. Return TRUE (non-zero)
1.3310 +** if they are identical and return FALSE if they differ in any way.
1.3311 +**
1.3312 +** Sometimes this routine will return FALSE even if the two expressions
1.3313 +** really are equivalent. If we cannot prove that the expressions are
1.3314 +** identical, we return FALSE just to be safe. So if this routine
1.3315 +** returns false, then you do not really know for certain if the two
1.3316 +** expressions are the same. But if you get a TRUE return, then you
1.3317 +** can be sure the expressions are the same. In the places where
1.3318 +** this routine is used, it does not hurt to get an extra FALSE - that
1.3319 +** just might result in some slightly slower code. But returning
1.3320 +** an incorrect TRUE could lead to a malfunction.
1.3321 +*/
1.3322 +int sqlite3ExprCompare(Expr *pA, Expr *pB){
1.3323 + int i;
1.3324 + if( pA==0||pB==0 ){
1.3325 + return pB==pA;
1.3326 + }
1.3327 + if( pA->op!=pB->op ) return 0;
1.3328 + if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
1.3329 + if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
1.3330 + if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
1.3331 + if( pA->pList ){
1.3332 + if( pB->pList==0 ) return 0;
1.3333 + if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
1.3334 + for(i=0; i<pA->pList->nExpr; i++){
1.3335 + if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
1.3336 + return 0;
1.3337 + }
1.3338 + }
1.3339 + }else if( pB->pList ){
1.3340 + return 0;
1.3341 + }
1.3342 + if( pA->pSelect || pB->pSelect ) return 0;
1.3343 + if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
1.3344 + if( pA->op!=TK_COLUMN && pA->token.z ){
1.3345 + if( pB->token.z==0 ) return 0;
1.3346 + if( pB->token.n!=pA->token.n ) return 0;
1.3347 + if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
1.3348 + return 0;
1.3349 + }
1.3350 + }
1.3351 + return 1;
1.3352 +}
1.3353 +
1.3354 +
1.3355 +/*
1.3356 +** Add a new element to the pAggInfo->aCol[] array. Return the index of
1.3357 +** the new element. Return a negative number if malloc fails.
1.3358 +*/
1.3359 +static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
1.3360 + int i;
1.3361 + pInfo->aCol = sqlite3ArrayAllocate(
1.3362 + db,
1.3363 + pInfo->aCol,
1.3364 + sizeof(pInfo->aCol[0]),
1.3365 + 3,
1.3366 + &pInfo->nColumn,
1.3367 + &pInfo->nColumnAlloc,
1.3368 + &i
1.3369 + );
1.3370 + return i;
1.3371 +}
1.3372 +
1.3373 +/*
1.3374 +** Add a new element to the pAggInfo->aFunc[] array. Return the index of
1.3375 +** the new element. Return a negative number if malloc fails.
1.3376 +*/
1.3377 +static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
1.3378 + int i;
1.3379 + pInfo->aFunc = sqlite3ArrayAllocate(
1.3380 + db,
1.3381 + pInfo->aFunc,
1.3382 + sizeof(pInfo->aFunc[0]),
1.3383 + 3,
1.3384 + &pInfo->nFunc,
1.3385 + &pInfo->nFuncAlloc,
1.3386 + &i
1.3387 + );
1.3388 + return i;
1.3389 +}
1.3390 +
1.3391 +/*
1.3392 +** This is an xFunc for walkExprTree() used to implement
1.3393 +** sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
1.3394 +** for additional information.
1.3395 +**
1.3396 +** This routine analyzes the aggregate function at pExpr.
1.3397 +*/
1.3398 +static int analyzeAggregate(void *pArg, Expr *pExpr){
1.3399 + int i;
1.3400 + NameContext *pNC = (NameContext *)pArg;
1.3401 + Parse *pParse = pNC->pParse;
1.3402 + SrcList *pSrcList = pNC->pSrcList;
1.3403 + AggInfo *pAggInfo = pNC->pAggInfo;
1.3404 +
1.3405 + switch( pExpr->op ){
1.3406 + case TK_AGG_COLUMN:
1.3407 + case TK_COLUMN: {
1.3408 + /* Check to see if the column is in one of the tables in the FROM
1.3409 + ** clause of the aggregate query */
1.3410 + if( pSrcList ){
1.3411 + struct SrcList_item *pItem = pSrcList->a;
1.3412 + for(i=0; i<pSrcList->nSrc; i++, pItem++){
1.3413 + struct AggInfo_col *pCol;
1.3414 + if( pExpr->iTable==pItem->iCursor ){
1.3415 + /* If we reach this point, it means that pExpr refers to a table
1.3416 + ** that is in the FROM clause of the aggregate query.
1.3417 + **
1.3418 + ** Make an entry for the column in pAggInfo->aCol[] if there
1.3419 + ** is not an entry there already.
1.3420 + */
1.3421 + int k;
1.3422 + pCol = pAggInfo->aCol;
1.3423 + for(k=0; k<pAggInfo->nColumn; k++, pCol++){
1.3424 + if( pCol->iTable==pExpr->iTable &&
1.3425 + pCol->iColumn==pExpr->iColumn ){
1.3426 + break;
1.3427 + }
1.3428 + }
1.3429 + if( (k>=pAggInfo->nColumn)
1.3430 + && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
1.3431 + ){
1.3432 + pCol = &pAggInfo->aCol[k];
1.3433 + pCol->pTab = pExpr->pTab;
1.3434 + pCol->iTable = pExpr->iTable;
1.3435 + pCol->iColumn = pExpr->iColumn;
1.3436 + pCol->iMem = ++pParse->nMem;
1.3437 + pCol->iSorterColumn = -1;
1.3438 + pCol->pExpr = pExpr;
1.3439 + if( pAggInfo->pGroupBy ){
1.3440 + int j, n;
1.3441 + ExprList *pGB = pAggInfo->pGroupBy;
1.3442 + struct ExprList_item *pTerm = pGB->a;
1.3443 + n = pGB->nExpr;
1.3444 + for(j=0; j<n; j++, pTerm++){
1.3445 + Expr *pE = pTerm->pExpr;
1.3446 + if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
1.3447 + pE->iColumn==pExpr->iColumn ){
1.3448 + pCol->iSorterColumn = j;
1.3449 + break;
1.3450 + }
1.3451 + }
1.3452 + }
1.3453 + if( pCol->iSorterColumn<0 ){
1.3454 + pCol->iSorterColumn = pAggInfo->nSortingColumn++;
1.3455 + }
1.3456 + }
1.3457 + /* There is now an entry for pExpr in pAggInfo->aCol[] (either
1.3458 + ** because it was there before or because we just created it).
1.3459 + ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
1.3460 + ** pAggInfo->aCol[] entry.
1.3461 + */
1.3462 + pExpr->pAggInfo = pAggInfo;
1.3463 + pExpr->op = TK_AGG_COLUMN;
1.3464 + pExpr->iAgg = k;
1.3465 + break;
1.3466 + } /* endif pExpr->iTable==pItem->iCursor */
1.3467 + } /* end loop over pSrcList */
1.3468 + }
1.3469 + return 1;
1.3470 + }
1.3471 + case TK_AGG_FUNCTION: {
1.3472 + /* The pNC->nDepth==0 test causes aggregate functions in subqueries
1.3473 + ** to be ignored */
1.3474 + if( pNC->nDepth==0 ){
1.3475 + /* Check to see if pExpr is a duplicate of another aggregate
1.3476 + ** function that is already in the pAggInfo structure
1.3477 + */
1.3478 + struct AggInfo_func *pItem = pAggInfo->aFunc;
1.3479 + for(i=0; i<pAggInfo->nFunc; i++, pItem++){
1.3480 + if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
1.3481 + break;
1.3482 + }
1.3483 + }
1.3484 + if( i>=pAggInfo->nFunc ){
1.3485 + /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
1.3486 + */
1.3487 + u8 enc = ENC(pParse->db);
1.3488 + i = addAggInfoFunc(pParse->db, pAggInfo);
1.3489 + if( i>=0 ){
1.3490 + pItem = &pAggInfo->aFunc[i];
1.3491 + pItem->pExpr = pExpr;
1.3492 + pItem->iMem = ++pParse->nMem;
1.3493 + pItem->pFunc = sqlite3FindFunction(pParse->db,
1.3494 + (char*)pExpr->token.z, pExpr->token.n,
1.3495 + pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
1.3496 + if( pExpr->flags & EP_Distinct ){
1.3497 + pItem->iDistinct = pParse->nTab++;
1.3498 + }else{
1.3499 + pItem->iDistinct = -1;
1.3500 + }
1.3501 + }
1.3502 + }
1.3503 + /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
1.3504 + */
1.3505 + pExpr->iAgg = i;
1.3506 + pExpr->pAggInfo = pAggInfo;
1.3507 + return 1;
1.3508 + }
1.3509 + }
1.3510 + }
1.3511 +
1.3512 + /* Recursively walk subqueries looking for TK_COLUMN nodes that need
1.3513 + ** to be changed to TK_AGG_COLUMN. But increment nDepth so that
1.3514 + ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
1.3515 + */
1.3516 + if( pExpr->pSelect ){
1.3517 + pNC->nDepth++;
1.3518 + walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
1.3519 + pNC->nDepth--;
1.3520 + }
1.3521 + return 0;
1.3522 +}
1.3523 +
1.3524 +/*
1.3525 +** Analyze the given expression looking for aggregate functions and
1.3526 +** for variables that need to be added to the pParse->aAgg[] array.
1.3527 +** Make additional entries to the pParse->aAgg[] array as necessary.
1.3528 +**
1.3529 +** This routine should only be called after the expression has been
1.3530 +** analyzed by sqlite3ExprResolveNames().
1.3531 +*/
1.3532 +void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
1.3533 + walkExprTree(pExpr, analyzeAggregate, pNC);
1.3534 +}
1.3535 +
1.3536 +/*
1.3537 +** Call sqlite3ExprAnalyzeAggregates() for every expression in an
1.3538 +** expression list. Return the number of errors.
1.3539 +**
1.3540 +** If an error is found, the analysis is cut short.
1.3541 +*/
1.3542 +void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
1.3543 + struct ExprList_item *pItem;
1.3544 + int i;
1.3545 + if( pList ){
1.3546 + for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1.3547 + sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
1.3548 + }
1.3549 + }
1.3550 +}
1.3551 +
1.3552 +/*
1.3553 +** Allocate or deallocate temporary use registers during code generation.
1.3554 +*/
1.3555 +int sqlite3GetTempReg(Parse *pParse){
1.3556 + if( pParse->nTempReg==0 ){
1.3557 + return ++pParse->nMem;
1.3558 + }
1.3559 + return pParse->aTempReg[--pParse->nTempReg];
1.3560 +}
1.3561 +void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
1.3562 + if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
1.3563 + sqlite3ExprWritableRegister(pParse, iReg, iReg);
1.3564 + pParse->aTempReg[pParse->nTempReg++] = iReg;
1.3565 + }
1.3566 +}
1.3567 +
1.3568 +/*
1.3569 +** Allocate or deallocate a block of nReg consecutive registers
1.3570 +*/
1.3571 +int sqlite3GetTempRange(Parse *pParse, int nReg){
1.3572 + int i, n;
1.3573 + i = pParse->iRangeReg;
1.3574 + n = pParse->nRangeReg;
1.3575 + if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
1.3576 + pParse->iRangeReg += nReg;
1.3577 + pParse->nRangeReg -= nReg;
1.3578 + }else{
1.3579 + i = pParse->nMem+1;
1.3580 + pParse->nMem += nReg;
1.3581 + }
1.3582 + return i;
1.3583 +}
1.3584 +void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
1.3585 + if( nReg>pParse->nRangeReg ){
1.3586 + pParse->nRangeReg = nReg;
1.3587 + pParse->iRangeReg = iReg;
1.3588 + }
1.3589 +}