1 /* 2 ** 2001 September 15 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** This file contains routines used for analyzing expressions and 13 ** for generating VDBE code that evaluates expressions in SQLite. 14 */ 15 #include "sqliteInt.h" 16 17 /* Forward declarations */ 18 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int); 19 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree); 20 21 /* 22 ** Return the affinity character for a single column of a table. 23 */ 24 char sqlite3TableColumnAffinity(Table *pTab, int iCol){ 25 assert( iCol<pTab->nCol ); 26 return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER; 27 } 28 29 /* 30 ** Return the 'affinity' of the expression pExpr if any. 31 ** 32 ** If pExpr is a column, a reference to a column via an 'AS' alias, 33 ** or a sub-select with a column as the return value, then the 34 ** affinity of that column is returned. Otherwise, 0x00 is returned, 35 ** indicating no affinity for the expression. 36 ** 37 ** i.e. the WHERE clause expressions in the following statements all 38 ** have an affinity: 39 ** 40 ** CREATE TABLE t1(a); 41 ** SELECT * FROM t1 WHERE a; 42 ** SELECT a AS b FROM t1 WHERE b; 43 ** SELECT * FROM t1 WHERE (select a from t1); 44 */ 45 char sqlite3ExprAffinity(const Expr *pExpr){ 46 int op; 47 while( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){ 48 assert( pExpr->op==TK_COLLATE 49 || pExpr->op==TK_IF_NULL_ROW 50 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) ); 51 pExpr = pExpr->pLeft; 52 assert( pExpr!=0 ); 53 } 54 op = pExpr->op; 55 if( op==TK_REGISTER ) op = pExpr->op2; 56 if( (op==TK_COLUMN || op==TK_AGG_COLUMN) && pExpr->y.pTab ){ 57 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 58 } 59 if( op==TK_SELECT ){ 60 assert( pExpr->flags&EP_xIsSelect ); 61 assert( pExpr->x.pSelect!=0 ); 62 assert( pExpr->x.pSelect->pEList!=0 ); 63 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 ); 64 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); 65 } 66 #ifndef SQLITE_OMIT_CAST 67 if( op==TK_CAST ){ 68 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 69 return sqlite3AffinityType(pExpr->u.zToken, 0); 70 } 71 #endif 72 if( op==TK_SELECT_COLUMN ){ 73 assert( pExpr->pLeft->flags&EP_xIsSelect ); 74 assert( pExpr->iColumn < pExpr->iTable ); 75 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr ); 76 return sqlite3ExprAffinity( 77 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr 78 ); 79 } 80 if( op==TK_VECTOR ){ 81 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr); 82 } 83 return pExpr->affExpr; 84 } 85 86 /* 87 ** Set the collating sequence for expression pExpr to be the collating 88 ** sequence named by pToken. Return a pointer to a new Expr node that 89 ** implements the COLLATE operator. 90 ** 91 ** If a memory allocation error occurs, that fact is recorded in pParse->db 92 ** and the pExpr parameter is returned unchanged. 93 */ 94 Expr *sqlite3ExprAddCollateToken( 95 Parse *pParse, /* Parsing context */ 96 Expr *pExpr, /* Add the "COLLATE" clause to this expression */ 97 const Token *pCollName, /* Name of collating sequence */ 98 int dequote /* True to dequote pCollName */ 99 ){ 100 if( pCollName->n>0 ){ 101 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); 102 if( pNew ){ 103 pNew->pLeft = pExpr; 104 pNew->flags |= EP_Collate|EP_Skip; 105 pExpr = pNew; 106 } 107 } 108 return pExpr; 109 } 110 Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){ 111 Token s; 112 assert( zC!=0 ); 113 sqlite3TokenInit(&s, (char*)zC); 114 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); 115 } 116 117 /* 118 ** Skip over any TK_COLLATE operators. 119 */ 120 Expr *sqlite3ExprSkipCollate(Expr *pExpr){ 121 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ 122 assert( pExpr->op==TK_COLLATE ); 123 pExpr = pExpr->pLeft; 124 } 125 return pExpr; 126 } 127 128 /* 129 ** Skip over any TK_COLLATE operators and/or any unlikely() 130 ** or likelihood() or likely() functions at the root of an 131 ** expression. 132 */ 133 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){ 134 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){ 135 if( ExprHasProperty(pExpr, EP_Unlikely) ){ 136 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 137 assert( pExpr->x.pList->nExpr>0 ); 138 assert( pExpr->op==TK_FUNCTION ); 139 pExpr = pExpr->x.pList->a[0].pExpr; 140 }else{ 141 assert( pExpr->op==TK_COLLATE ); 142 pExpr = pExpr->pLeft; 143 } 144 } 145 return pExpr; 146 } 147 148 /* 149 ** Return the collation sequence for the expression pExpr. If 150 ** there is no defined collating sequence, return NULL. 151 ** 152 ** See also: sqlite3ExprNNCollSeq() 153 ** 154 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the 155 ** default collation if pExpr has no defined collation. 156 ** 157 ** The collating sequence might be determined by a COLLATE operator 158 ** or by the presence of a column with a defined collating sequence. 159 ** COLLATE operators take first precedence. Left operands take 160 ** precedence over right operands. 161 */ 162 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){ 163 sqlite3 *db = pParse->db; 164 CollSeq *pColl = 0; 165 const Expr *p = pExpr; 166 while( p ){ 167 int op = p->op; 168 if( op==TK_REGISTER ) op = p->op2; 169 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER) 170 && p->y.pTab!=0 171 ){ 172 /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally 173 ** a TK_COLUMN but was previously evaluated and cached in a register */ 174 int j = p->iColumn; 175 if( j>=0 ){ 176 const char *zColl = p->y.pTab->aCol[j].zColl; 177 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 178 } 179 break; 180 } 181 if( op==TK_CAST || op==TK_UPLUS ){ 182 p = p->pLeft; 183 continue; 184 } 185 if( op==TK_VECTOR ){ 186 p = p->x.pList->a[0].pExpr; 187 continue; 188 } 189 if( op==TK_COLLATE ){ 190 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); 191 break; 192 } 193 if( p->flags & EP_Collate ){ 194 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ 195 p = p->pLeft; 196 }else{ 197 Expr *pNext = p->pRight; 198 /* The Expr.x union is never used at the same time as Expr.pRight */ 199 assert( p->x.pList==0 || p->pRight==0 ); 200 if( p->x.pList!=0 201 && !db->mallocFailed 202 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) 203 ){ 204 int i; 205 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){ 206 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ 207 pNext = p->x.pList->a[i].pExpr; 208 break; 209 } 210 } 211 } 212 p = pNext; 213 } 214 }else{ 215 break; 216 } 217 } 218 if( sqlite3CheckCollSeq(pParse, pColl) ){ 219 pColl = 0; 220 } 221 return pColl; 222 } 223 224 /* 225 ** Return the collation sequence for the expression pExpr. If 226 ** there is no defined collating sequence, return a pointer to the 227 ** defautl collation sequence. 228 ** 229 ** See also: sqlite3ExprCollSeq() 230 ** 231 ** The sqlite3ExprCollSeq() routine works the same except that it 232 ** returns NULL if there is no defined collation. 233 */ 234 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){ 235 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr); 236 if( p==0 ) p = pParse->db->pDfltColl; 237 assert( p!=0 ); 238 return p; 239 } 240 241 /* 242 ** Return TRUE if the two expressions have equivalent collating sequences. 243 */ 244 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){ 245 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1); 246 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2); 247 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0; 248 } 249 250 /* 251 ** pExpr is an operand of a comparison operator. aff2 is the 252 ** type affinity of the other operand. This routine returns the 253 ** type affinity that should be used for the comparison operator. 254 */ 255 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){ 256 char aff1 = sqlite3ExprAffinity(pExpr); 257 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){ 258 /* Both sides of the comparison are columns. If one has numeric 259 ** affinity, use that. Otherwise use no affinity. 260 */ 261 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ 262 return SQLITE_AFF_NUMERIC; 263 }else{ 264 return SQLITE_AFF_BLOB; 265 } 266 }else{ 267 /* One side is a column, the other is not. Use the columns affinity. */ 268 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE ); 269 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE; 270 } 271 } 272 273 /* 274 ** pExpr is a comparison operator. Return the type affinity that should 275 ** be applied to both operands prior to doing the comparison. 276 */ 277 static char comparisonAffinity(const Expr *pExpr){ 278 char aff; 279 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || 280 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || 281 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); 282 assert( pExpr->pLeft ); 283 aff = sqlite3ExprAffinity(pExpr->pLeft); 284 if( pExpr->pRight ){ 285 aff = sqlite3CompareAffinity(pExpr->pRight, aff); 286 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 287 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); 288 }else if( aff==0 ){ 289 aff = SQLITE_AFF_BLOB; 290 } 291 return aff; 292 } 293 294 /* 295 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. 296 ** idx_affinity is the affinity of an indexed column. Return true 297 ** if the index with affinity idx_affinity may be used to implement 298 ** the comparison in pExpr. 299 */ 300 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){ 301 char aff = comparisonAffinity(pExpr); 302 if( aff<SQLITE_AFF_TEXT ){ 303 return 1; 304 } 305 if( aff==SQLITE_AFF_TEXT ){ 306 return idx_affinity==SQLITE_AFF_TEXT; 307 } 308 return sqlite3IsNumericAffinity(idx_affinity); 309 } 310 311 /* 312 ** Return the P5 value that should be used for a binary comparison 313 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. 314 */ 315 static u8 binaryCompareP5( 316 const Expr *pExpr1, /* Left operand */ 317 const Expr *pExpr2, /* Right operand */ 318 int jumpIfNull /* Extra flags added to P5 */ 319 ){ 320 u8 aff = (char)sqlite3ExprAffinity(pExpr2); 321 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; 322 return aff; 323 } 324 325 /* 326 ** Return a pointer to the collation sequence that should be used by 327 ** a binary comparison operator comparing pLeft and pRight. 328 ** 329 ** If the left hand expression has a collating sequence type, then it is 330 ** used. Otherwise the collation sequence for the right hand expression 331 ** is used, or the default (BINARY) if neither expression has a collating 332 ** type. 333 ** 334 ** Argument pRight (but not pLeft) may be a null pointer. In this case, 335 ** it is not considered. 336 */ 337 CollSeq *sqlite3BinaryCompareCollSeq( 338 Parse *pParse, 339 const Expr *pLeft, 340 const Expr *pRight 341 ){ 342 CollSeq *pColl; 343 assert( pLeft ); 344 if( pLeft->flags & EP_Collate ){ 345 pColl = sqlite3ExprCollSeq(pParse, pLeft); 346 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ 347 pColl = sqlite3ExprCollSeq(pParse, pRight); 348 }else{ 349 pColl = sqlite3ExprCollSeq(pParse, pLeft); 350 if( !pColl ){ 351 pColl = sqlite3ExprCollSeq(pParse, pRight); 352 } 353 } 354 return pColl; 355 } 356 357 /* Expresssion p is a comparison operator. Return a collation sequence 358 ** appropriate for the comparison operator. 359 ** 360 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq(). 361 ** However, if the OP_Commuted flag is set, then the order of the operands 362 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the 363 ** correct collating sequence is found. 364 */ 365 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){ 366 if( ExprHasProperty(p, EP_Commuted) ){ 367 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft); 368 }else{ 369 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight); 370 } 371 } 372 373 /* 374 ** Generate code for a comparison operator. 375 */ 376 static int codeCompare( 377 Parse *pParse, /* The parsing (and code generating) context */ 378 Expr *pLeft, /* The left operand */ 379 Expr *pRight, /* The right operand */ 380 int opcode, /* The comparison opcode */ 381 int in1, int in2, /* Register holding operands */ 382 int dest, /* Jump here if true. */ 383 int jumpIfNull, /* If true, jump if either operand is NULL */ 384 int isCommuted /* The comparison has been commuted */ 385 ){ 386 int p5; 387 int addr; 388 CollSeq *p4; 389 390 if( pParse->nErr ) return 0; 391 if( isCommuted ){ 392 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft); 393 }else{ 394 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); 395 } 396 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); 397 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, 398 (void*)p4, P4_COLLSEQ); 399 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); 400 return addr; 401 } 402 403 /* 404 ** Return true if expression pExpr is a vector, or false otherwise. 405 ** 406 ** A vector is defined as any expression that results in two or more 407 ** columns of result. Every TK_VECTOR node is an vector because the 408 ** parser will not generate a TK_VECTOR with fewer than two entries. 409 ** But a TK_SELECT might be either a vector or a scalar. It is only 410 ** considered a vector if it has two or more result columns. 411 */ 412 int sqlite3ExprIsVector(Expr *pExpr){ 413 return sqlite3ExprVectorSize(pExpr)>1; 414 } 415 416 /* 417 ** If the expression passed as the only argument is of type TK_VECTOR 418 ** return the number of expressions in the vector. Or, if the expression 419 ** is a sub-select, return the number of columns in the sub-select. For 420 ** any other type of expression, return 1. 421 */ 422 int sqlite3ExprVectorSize(Expr *pExpr){ 423 u8 op = pExpr->op; 424 if( op==TK_REGISTER ) op = pExpr->op2; 425 if( op==TK_VECTOR ){ 426 return pExpr->x.pList->nExpr; 427 }else if( op==TK_SELECT ){ 428 return pExpr->x.pSelect->pEList->nExpr; 429 }else{ 430 return 1; 431 } 432 } 433 434 /* 435 ** Return a pointer to a subexpression of pVector that is the i-th 436 ** column of the vector (numbered starting with 0). The caller must 437 ** ensure that i is within range. 438 ** 439 ** If pVector is really a scalar (and "scalar" here includes subqueries 440 ** that return a single column!) then return pVector unmodified. 441 ** 442 ** pVector retains ownership of the returned subexpression. 443 ** 444 ** If the vector is a (SELECT ...) then the expression returned is 445 ** just the expression for the i-th term of the result set, and may 446 ** not be ready for evaluation because the table cursor has not yet 447 ** been positioned. 448 */ 449 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ 450 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR ); 451 if( sqlite3ExprIsVector(pVector) ){ 452 assert( pVector->op2==0 || pVector->op==TK_REGISTER ); 453 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ 454 return pVector->x.pSelect->pEList->a[i].pExpr; 455 }else{ 456 return pVector->x.pList->a[i].pExpr; 457 } 458 } 459 return pVector; 460 } 461 462 /* 463 ** Compute and return a new Expr object which when passed to 464 ** sqlite3ExprCode() will generate all necessary code to compute 465 ** the iField-th column of the vector expression pVector. 466 ** 467 ** It is ok for pVector to be a scalar (as long as iField==0). 468 ** In that case, this routine works like sqlite3ExprDup(). 469 ** 470 ** The caller owns the returned Expr object and is responsible for 471 ** ensuring that the returned value eventually gets freed. 472 ** 473 ** The caller retains ownership of pVector. If pVector is a TK_SELECT, 474 ** then the returned object will reference pVector and so pVector must remain 475 ** valid for the life of the returned object. If pVector is a TK_VECTOR 476 ** or a scalar expression, then it can be deleted as soon as this routine 477 ** returns. 478 ** 479 ** A trick to cause a TK_SELECT pVector to be deleted together with 480 ** the returned Expr object is to attach the pVector to the pRight field 481 ** of the returned TK_SELECT_COLUMN Expr object. 482 */ 483 Expr *sqlite3ExprForVectorField( 484 Parse *pParse, /* Parsing context */ 485 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ 486 int iField, /* Which column of the vector to return */ 487 int nField /* Total number of columns in the vector */ 488 ){ 489 Expr *pRet; 490 if( pVector->op==TK_SELECT ){ 491 assert( pVector->flags & EP_xIsSelect ); 492 /* The TK_SELECT_COLUMN Expr node: 493 ** 494 ** pLeft: pVector containing TK_SELECT. Not deleted. 495 ** pRight: not used. But recursively deleted. 496 ** iColumn: Index of a column in pVector 497 ** iTable: 0 or the number of columns on the LHS of an assignment 498 ** pLeft->iTable: First in an array of register holding result, or 0 499 ** if the result is not yet computed. 500 ** 501 ** sqlite3ExprDelete() specifically skips the recursive delete of 502 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector 503 ** can be attached to pRight to cause this node to take ownership of 504 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes 505 ** with the same pLeft pointer to the pVector, but only one of them 506 ** will own the pVector. 507 */ 508 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0); 509 if( pRet ){ 510 pRet->iTable = nField; 511 pRet->iColumn = iField; 512 pRet->pLeft = pVector; 513 } 514 }else{ 515 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr; 516 pRet = sqlite3ExprDup(pParse->db, pVector, 0); 517 sqlite3RenameTokenRemap(pParse, pRet, pVector); 518 } 519 return pRet; 520 } 521 522 /* 523 ** If expression pExpr is of type TK_SELECT, generate code to evaluate 524 ** it. Return the register in which the result is stored (or, if the 525 ** sub-select returns more than one column, the first in an array 526 ** of registers in which the result is stored). 527 ** 528 ** If pExpr is not a TK_SELECT expression, return 0. 529 */ 530 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ 531 int reg = 0; 532 #ifndef SQLITE_OMIT_SUBQUERY 533 if( pExpr->op==TK_SELECT ){ 534 reg = sqlite3CodeSubselect(pParse, pExpr); 535 } 536 #endif 537 return reg; 538 } 539 540 /* 541 ** Argument pVector points to a vector expression - either a TK_VECTOR 542 ** or TK_SELECT that returns more than one column. This function returns 543 ** the register number of a register that contains the value of 544 ** element iField of the vector. 545 ** 546 ** If pVector is a TK_SELECT expression, then code for it must have 547 ** already been generated using the exprCodeSubselect() routine. In this 548 ** case parameter regSelect should be the first in an array of registers 549 ** containing the results of the sub-select. 550 ** 551 ** If pVector is of type TK_VECTOR, then code for the requested field 552 ** is generated. In this case (*pRegFree) may be set to the number of 553 ** a temporary register to be freed by the caller before returning. 554 ** 555 ** Before returning, output parameter (*ppExpr) is set to point to the 556 ** Expr object corresponding to element iElem of the vector. 557 */ 558 static int exprVectorRegister( 559 Parse *pParse, /* Parse context */ 560 Expr *pVector, /* Vector to extract element from */ 561 int iField, /* Field to extract from pVector */ 562 int regSelect, /* First in array of registers */ 563 Expr **ppExpr, /* OUT: Expression element */ 564 int *pRegFree /* OUT: Temp register to free */ 565 ){ 566 u8 op = pVector->op; 567 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR ); 568 if( op==TK_REGISTER ){ 569 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); 570 return pVector->iTable+iField; 571 } 572 if( op==TK_SELECT ){ 573 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr; 574 return regSelect+iField; 575 } 576 if( op==TK_VECTOR ){ 577 *ppExpr = pVector->x.pList->a[iField].pExpr; 578 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); 579 } 580 return 0; 581 } 582 583 /* 584 ** Expression pExpr is a comparison between two vector values. Compute 585 ** the result of the comparison (1, 0, or NULL) and write that 586 ** result into register dest. 587 ** 588 ** The caller must satisfy the following preconditions: 589 ** 590 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ 591 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ 592 ** otherwise: op==pExpr->op and p5==0 593 */ 594 static void codeVectorCompare( 595 Parse *pParse, /* Code generator context */ 596 Expr *pExpr, /* The comparison operation */ 597 int dest, /* Write results into this register */ 598 u8 op, /* Comparison operator */ 599 u8 p5 /* SQLITE_NULLEQ or zero */ 600 ){ 601 Vdbe *v = pParse->pVdbe; 602 Expr *pLeft = pExpr->pLeft; 603 Expr *pRight = pExpr->pRight; 604 int nLeft = sqlite3ExprVectorSize(pLeft); 605 int i; 606 int regLeft = 0; 607 int regRight = 0; 608 u8 opx = op; 609 int addrCmp = 0; 610 int addrDone = sqlite3VdbeMakeLabel(pParse); 611 int isCommuted = ExprHasProperty(pExpr,EP_Commuted); 612 613 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 614 if( pParse->nErr ) return; 615 if( nLeft!=sqlite3ExprVectorSize(pRight) ){ 616 sqlite3ErrorMsg(pParse, "row value misused"); 617 return; 618 } 619 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 620 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 621 || pExpr->op==TK_LT || pExpr->op==TK_GT 622 || pExpr->op==TK_LE || pExpr->op==TK_GE 623 ); 624 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ) 625 || (pExpr->op==TK_ISNOT && op==TK_NE) ); 626 assert( p5==0 || pExpr->op!=op ); 627 assert( p5==SQLITE_NULLEQ || pExpr->op==op ); 628 629 if( op==TK_LE ) opx = TK_LT; 630 if( op==TK_GE ) opx = TK_GT; 631 if( op==TK_NE ) opx = TK_EQ; 632 633 regLeft = exprCodeSubselect(pParse, pLeft); 634 regRight = exprCodeSubselect(pParse, pRight); 635 636 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest); 637 for(i=0; 1 /*Loop exits by "break"*/; i++){ 638 int regFree1 = 0, regFree2 = 0; 639 Expr *pL = 0, *pR = 0; 640 int r1, r2; 641 assert( i>=0 && i<nLeft ); 642 if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp); 643 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1); 644 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2); 645 addrCmp = sqlite3VdbeCurrentAddr(v); 646 codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted); 647 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 648 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 649 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 650 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 651 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); 652 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); 653 sqlite3ReleaseTempReg(pParse, regFree1); 654 sqlite3ReleaseTempReg(pParse, regFree2); 655 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){ 656 addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq); 657 testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT); 658 testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT); 659 } 660 if( p5==SQLITE_NULLEQ ){ 661 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest); 662 }else{ 663 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2); 664 } 665 if( i==nLeft-1 ){ 666 break; 667 } 668 if( opx==TK_EQ ){ 669 sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v); 670 }else{ 671 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE ); 672 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone); 673 if( i==nLeft-2 ) opx = op; 674 } 675 } 676 sqlite3VdbeJumpHere(v, addrCmp); 677 sqlite3VdbeResolveLabel(v, addrDone); 678 if( op==TK_NE ){ 679 sqlite3VdbeAddOp2(v, OP_Not, dest, dest); 680 } 681 } 682 683 #if SQLITE_MAX_EXPR_DEPTH>0 684 /* 685 ** Check that argument nHeight is less than or equal to the maximum 686 ** expression depth allowed. If it is not, leave an error message in 687 ** pParse. 688 */ 689 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ 690 int rc = SQLITE_OK; 691 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; 692 if( nHeight>mxHeight ){ 693 sqlite3ErrorMsg(pParse, 694 "Expression tree is too large (maximum depth %d)", mxHeight 695 ); 696 rc = SQLITE_ERROR; 697 } 698 return rc; 699 } 700 701 /* The following three functions, heightOfExpr(), heightOfExprList() 702 ** and heightOfSelect(), are used to determine the maximum height 703 ** of any expression tree referenced by the structure passed as the 704 ** first argument. 705 ** 706 ** If this maximum height is greater than the current value pointed 707 ** to by pnHeight, the second parameter, then set *pnHeight to that 708 ** value. 709 */ 710 static void heightOfExpr(Expr *p, int *pnHeight){ 711 if( p ){ 712 if( p->nHeight>*pnHeight ){ 713 *pnHeight = p->nHeight; 714 } 715 } 716 } 717 static void heightOfExprList(ExprList *p, int *pnHeight){ 718 if( p ){ 719 int i; 720 for(i=0; i<p->nExpr; i++){ 721 heightOfExpr(p->a[i].pExpr, pnHeight); 722 } 723 } 724 } 725 static void heightOfSelect(Select *pSelect, int *pnHeight){ 726 Select *p; 727 for(p=pSelect; p; p=p->pPrior){ 728 heightOfExpr(p->pWhere, pnHeight); 729 heightOfExpr(p->pHaving, pnHeight); 730 heightOfExpr(p->pLimit, pnHeight); 731 heightOfExprList(p->pEList, pnHeight); 732 heightOfExprList(p->pGroupBy, pnHeight); 733 heightOfExprList(p->pOrderBy, pnHeight); 734 } 735 } 736 737 /* 738 ** Set the Expr.nHeight variable in the structure passed as an 739 ** argument. An expression with no children, Expr.pList or 740 ** Expr.pSelect member has a height of 1. Any other expression 741 ** has a height equal to the maximum height of any other 742 ** referenced Expr plus one. 743 ** 744 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags, 745 ** if appropriate. 746 */ 747 static void exprSetHeight(Expr *p){ 748 int nHeight = 0; 749 heightOfExpr(p->pLeft, &nHeight); 750 heightOfExpr(p->pRight, &nHeight); 751 if( ExprHasProperty(p, EP_xIsSelect) ){ 752 heightOfSelect(p->x.pSelect, &nHeight); 753 }else if( p->x.pList ){ 754 heightOfExprList(p->x.pList, &nHeight); 755 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 756 } 757 p->nHeight = nHeight + 1; 758 } 759 760 /* 761 ** Set the Expr.nHeight variable using the exprSetHeight() function. If 762 ** the height is greater than the maximum allowed expression depth, 763 ** leave an error in pParse. 764 ** 765 ** Also propagate all EP_Propagate flags from the Expr.x.pList into 766 ** Expr.flags. 767 */ 768 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 769 if( pParse->nErr ) return; 770 exprSetHeight(p); 771 sqlite3ExprCheckHeight(pParse, p->nHeight); 772 } 773 774 /* 775 ** Return the maximum height of any expression tree referenced 776 ** by the select statement passed as an argument. 777 */ 778 int sqlite3SelectExprHeight(Select *p){ 779 int nHeight = 0; 780 heightOfSelect(p, &nHeight); 781 return nHeight; 782 } 783 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */ 784 /* 785 ** Propagate all EP_Propagate flags from the Expr.x.pList into 786 ** Expr.flags. 787 */ 788 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 789 if( pParse->nErr ) return; 790 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){ 791 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 792 } 793 } 794 #define exprSetHeight(y) 795 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */ 796 797 /* 798 ** This routine is the core allocator for Expr nodes. 799 ** 800 ** Construct a new expression node and return a pointer to it. Memory 801 ** for this node and for the pToken argument is a single allocation 802 ** obtained from sqlite3DbMalloc(). The calling function 803 ** is responsible for making sure the node eventually gets freed. 804 ** 805 ** If dequote is true, then the token (if it exists) is dequoted. 806 ** If dequote is false, no dequoting is performed. The deQuote 807 ** parameter is ignored if pToken is NULL or if the token does not 808 ** appear to be quoted. If the quotes were of the form "..." (double-quotes) 809 ** then the EP_DblQuoted flag is set on the expression node. 810 ** 811 ** Special case: If op==TK_INTEGER and pToken points to a string that 812 ** can be translated into a 32-bit integer, then the token is not 813 ** stored in u.zToken. Instead, the integer values is written 814 ** into u.iValue and the EP_IntValue flag is set. No extra storage 815 ** is allocated to hold the integer text and the dequote flag is ignored. 816 */ 817 Expr *sqlite3ExprAlloc( 818 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ 819 int op, /* Expression opcode */ 820 const Token *pToken, /* Token argument. Might be NULL */ 821 int dequote /* True to dequote */ 822 ){ 823 Expr *pNew; 824 int nExtra = 0; 825 int iValue = 0; 826 827 assert( db!=0 ); 828 if( pToken ){ 829 if( op!=TK_INTEGER || pToken->z==0 830 || sqlite3GetInt32(pToken->z, &iValue)==0 ){ 831 nExtra = pToken->n+1; 832 assert( iValue>=0 ); 833 } 834 } 835 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); 836 if( pNew ){ 837 memset(pNew, 0, sizeof(Expr)); 838 pNew->op = (u8)op; 839 pNew->iAgg = -1; 840 if( pToken ){ 841 if( nExtra==0 ){ 842 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse); 843 pNew->u.iValue = iValue; 844 }else{ 845 pNew->u.zToken = (char*)&pNew[1]; 846 assert( pToken->z!=0 || pToken->n==0 ); 847 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); 848 pNew->u.zToken[pToken->n] = 0; 849 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ 850 sqlite3DequoteExpr(pNew); 851 } 852 } 853 } 854 #if SQLITE_MAX_EXPR_DEPTH>0 855 pNew->nHeight = 1; 856 #endif 857 } 858 return pNew; 859 } 860 861 /* 862 ** Allocate a new expression node from a zero-terminated token that has 863 ** already been dequoted. 864 */ 865 Expr *sqlite3Expr( 866 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ 867 int op, /* Expression opcode */ 868 const char *zToken /* Token argument. Might be NULL */ 869 ){ 870 Token x; 871 x.z = zToken; 872 x.n = sqlite3Strlen30(zToken); 873 return sqlite3ExprAlloc(db, op, &x, 0); 874 } 875 876 /* 877 ** Attach subtrees pLeft and pRight to the Expr node pRoot. 878 ** 879 ** If pRoot==NULL that means that a memory allocation error has occurred. 880 ** In that case, delete the subtrees pLeft and pRight. 881 */ 882 void sqlite3ExprAttachSubtrees( 883 sqlite3 *db, 884 Expr *pRoot, 885 Expr *pLeft, 886 Expr *pRight 887 ){ 888 if( pRoot==0 ){ 889 assert( db->mallocFailed ); 890 sqlite3ExprDelete(db, pLeft); 891 sqlite3ExprDelete(db, pRight); 892 }else{ 893 if( pRight ){ 894 pRoot->pRight = pRight; 895 pRoot->flags |= EP_Propagate & pRight->flags; 896 } 897 if( pLeft ){ 898 pRoot->pLeft = pLeft; 899 pRoot->flags |= EP_Propagate & pLeft->flags; 900 } 901 exprSetHeight(pRoot); 902 } 903 } 904 905 /* 906 ** Allocate an Expr node which joins as many as two subtrees. 907 ** 908 ** One or both of the subtrees can be NULL. Return a pointer to the new 909 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, 910 ** free the subtrees and return NULL. 911 */ 912 Expr *sqlite3PExpr( 913 Parse *pParse, /* Parsing context */ 914 int op, /* Expression opcode */ 915 Expr *pLeft, /* Left operand */ 916 Expr *pRight /* Right operand */ 917 ){ 918 Expr *p; 919 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); 920 if( p ){ 921 memset(p, 0, sizeof(Expr)); 922 p->op = op & 0xff; 923 p->iAgg = -1; 924 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); 925 sqlite3ExprCheckHeight(pParse, p->nHeight); 926 }else{ 927 sqlite3ExprDelete(pParse->db, pLeft); 928 sqlite3ExprDelete(pParse->db, pRight); 929 } 930 return p; 931 } 932 933 /* 934 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due 935 ** do a memory allocation failure) then delete the pSelect object. 936 */ 937 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ 938 if( pExpr ){ 939 pExpr->x.pSelect = pSelect; 940 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); 941 sqlite3ExprSetHeightAndFlags(pParse, pExpr); 942 }else{ 943 assert( pParse->db->mallocFailed ); 944 sqlite3SelectDelete(pParse->db, pSelect); 945 } 946 } 947 948 /* 949 ** Expression list pEList is a list of vector values. This function 950 ** converts the contents of pEList to a VALUES(...) Select statement 951 ** returning 1 row for each element of the list. For example, the 952 ** expression list: 953 ** 954 ** ( (1,2), (3,4) (5,6) ) 955 ** 956 ** is translated to the equivalent of: 957 ** 958 ** VALUES(1,2), (3,4), (5,6) 959 ** 960 ** Each of the vector values in pEList must contain exactly nElem terms. 961 ** If a list element that is not a vector or does not contain nElem terms, 962 ** an error message is left in pParse. 963 ** 964 ** This is used as part of processing IN(...) expressions with a list 965 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))". 966 */ 967 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){ 968 int ii; 969 Select *pRet = 0; 970 assert( nElem>1 ); 971 for(ii=0; ii<pEList->nExpr; ii++){ 972 Select *pSel; 973 Expr *pExpr = pEList->a[ii].pExpr; 974 int nExprElem = (pExpr->op==TK_VECTOR ? pExpr->x.pList->nExpr : 1); 975 if( nExprElem!=nElem ){ 976 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d", 977 nExprElem, nExprElem>1?"s":"", nElem 978 ); 979 break; 980 } 981 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0); 982 pExpr->x.pList = 0; 983 if( pSel ){ 984 if( pRet ){ 985 pSel->op = TK_ALL; 986 pSel->pPrior = pRet; 987 } 988 pRet = pSel; 989 } 990 } 991 992 if( pRet && pRet->pPrior ){ 993 pRet->selFlags |= SF_MultiValue; 994 } 995 sqlite3ExprListDelete(pParse->db, pEList); 996 return pRet; 997 } 998 999 /* 1000 ** Join two expressions using an AND operator. If either expression is 1001 ** NULL, then just return the other expression. 1002 ** 1003 ** If one side or the other of the AND is known to be false, then instead 1004 ** of returning an AND expression, just return a constant expression with 1005 ** a value of false. 1006 */ 1007 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){ 1008 sqlite3 *db = pParse->db; 1009 if( pLeft==0 ){ 1010 return pRight; 1011 }else if( pRight==0 ){ 1012 return pLeft; 1013 }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight)) 1014 && !IN_RENAME_OBJECT 1015 ){ 1016 sqlite3ExprDeferredDelete(pParse, pLeft); 1017 sqlite3ExprDeferredDelete(pParse, pRight); 1018 return sqlite3Expr(db, TK_INTEGER, "0"); 1019 }else{ 1020 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight); 1021 } 1022 } 1023 1024 /* 1025 ** Construct a new expression node for a function with multiple 1026 ** arguments. 1027 */ 1028 Expr *sqlite3ExprFunction( 1029 Parse *pParse, /* Parsing context */ 1030 ExprList *pList, /* Argument list */ 1031 Token *pToken, /* Name of the function */ 1032 int eDistinct /* SF_Distinct or SF_ALL or 0 */ 1033 ){ 1034 Expr *pNew; 1035 sqlite3 *db = pParse->db; 1036 assert( pToken ); 1037 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); 1038 if( pNew==0 ){ 1039 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ 1040 return 0; 1041 } 1042 if( pList 1043 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] 1044 && !pParse->nested 1045 ){ 1046 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken); 1047 } 1048 pNew->x.pList = pList; 1049 ExprSetProperty(pNew, EP_HasFunc); 1050 assert( !ExprHasProperty(pNew, EP_xIsSelect) ); 1051 sqlite3ExprSetHeightAndFlags(pParse, pNew); 1052 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct); 1053 return pNew; 1054 } 1055 1056 /* 1057 ** Check to see if a function is usable according to current access 1058 ** rules: 1059 ** 1060 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL 1061 ** 1062 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from 1063 ** top-level SQL 1064 ** 1065 ** If the function is not usable, create an error. 1066 */ 1067 void sqlite3ExprFunctionUsable( 1068 Parse *pParse, /* Parsing and code generating context */ 1069 Expr *pExpr, /* The function invocation */ 1070 FuncDef *pDef /* The function being invoked */ 1071 ){ 1072 assert( !IN_RENAME_OBJECT ); 1073 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 ); 1074 if( ExprHasProperty(pExpr, EP_FromDDL) ){ 1075 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 1076 || (pParse->db->flags & SQLITE_TrustedSchema)==0 1077 ){ 1078 /* Functions prohibited in triggers and views if: 1079 ** (1) tagged with SQLITE_DIRECTONLY 1080 ** (2) not tagged with SQLITE_INNOCUOUS (which means it 1081 ** is tagged with SQLITE_FUNC_UNSAFE) and 1082 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning 1083 ** that the schema is possibly tainted). 1084 */ 1085 sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName); 1086 } 1087 } 1088 } 1089 1090 /* 1091 ** Assign a variable number to an expression that encodes a wildcard 1092 ** in the original SQL statement. 1093 ** 1094 ** Wildcards consisting of a single "?" are assigned the next sequential 1095 ** variable number. 1096 ** 1097 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make 1098 ** sure "nnn" is not too big to avoid a denial of service attack when 1099 ** the SQL statement comes from an external source. 1100 ** 1101 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number 1102 ** as the previous instance of the same wildcard. Or if this is the first 1103 ** instance of the wildcard, the next sequential variable number is 1104 ** assigned. 1105 */ 1106 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ 1107 sqlite3 *db = pParse->db; 1108 const char *z; 1109 ynVar x; 1110 1111 if( pExpr==0 ) return; 1112 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); 1113 z = pExpr->u.zToken; 1114 assert( z!=0 ); 1115 assert( z[0]!=0 ); 1116 assert( n==(u32)sqlite3Strlen30(z) ); 1117 if( z[1]==0 ){ 1118 /* Wildcard of the form "?". Assign the next variable number */ 1119 assert( z[0]=='?' ); 1120 x = (ynVar)(++pParse->nVar); 1121 }else{ 1122 int doAdd = 0; 1123 if( z[0]=='?' ){ 1124 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and 1125 ** use it as the variable number */ 1126 i64 i; 1127 int bOk; 1128 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/ 1129 i = z[1]-'0'; /* The common case of ?N for a single digit N */ 1130 bOk = 1; 1131 }else{ 1132 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); 1133 } 1134 testcase( i==0 ); 1135 testcase( i==1 ); 1136 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); 1137 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); 1138 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 1139 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", 1140 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); 1141 return; 1142 } 1143 x = (ynVar)i; 1144 if( x>pParse->nVar ){ 1145 pParse->nVar = (int)x; 1146 doAdd = 1; 1147 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){ 1148 doAdd = 1; 1149 } 1150 }else{ 1151 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable 1152 ** number as the prior appearance of the same name, or if the name 1153 ** has never appeared before, reuse the same variable number 1154 */ 1155 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n); 1156 if( x==0 ){ 1157 x = (ynVar)(++pParse->nVar); 1158 doAdd = 1; 1159 } 1160 } 1161 if( doAdd ){ 1162 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x); 1163 } 1164 } 1165 pExpr->iColumn = x; 1166 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 1167 sqlite3ErrorMsg(pParse, "too many SQL variables"); 1168 } 1169 } 1170 1171 /* 1172 ** Recursively delete an expression tree. 1173 */ 1174 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ 1175 assert( p!=0 ); 1176 /* Sanity check: Assert that the IntValue is non-negative if it exists */ 1177 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 ); 1178 1179 assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed ); 1180 assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced) 1181 || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) ); 1182 #ifdef SQLITE_DEBUG 1183 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ 1184 assert( p->pLeft==0 ); 1185 assert( p->pRight==0 ); 1186 assert( p->x.pSelect==0 ); 1187 } 1188 #endif 1189 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ 1190 /* The Expr.x union is never used at the same time as Expr.pRight */ 1191 assert( p->x.pList==0 || p->pRight==0 ); 1192 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft); 1193 if( p->pRight ){ 1194 assert( !ExprHasProperty(p, EP_WinFunc) ); 1195 sqlite3ExprDeleteNN(db, p->pRight); 1196 }else if( ExprHasProperty(p, EP_xIsSelect) ){ 1197 assert( !ExprHasProperty(p, EP_WinFunc) ); 1198 sqlite3SelectDelete(db, p->x.pSelect); 1199 }else{ 1200 sqlite3ExprListDelete(db, p->x.pList); 1201 #ifndef SQLITE_OMIT_WINDOWFUNC 1202 if( ExprHasProperty(p, EP_WinFunc) ){ 1203 sqlite3WindowDelete(db, p->y.pWin); 1204 } 1205 #endif 1206 } 1207 } 1208 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken); 1209 if( !ExprHasProperty(p, EP_Static) ){ 1210 sqlite3DbFreeNN(db, p); 1211 } 1212 } 1213 void sqlite3ExprDelete(sqlite3 *db, Expr *p){ 1214 if( p ) sqlite3ExprDeleteNN(db, p); 1215 } 1216 1217 1218 /* 1219 ** Arrange to cause pExpr to be deleted when the pParse is deleted. 1220 ** This is similar to sqlite3ExprDelete() except that the delete is 1221 ** deferred untilthe pParse is deleted. 1222 ** 1223 ** The pExpr might be deleted immediately on an OOM error. 1224 ** 1225 ** The deferred delete is (currently) implemented by adding the 1226 ** pExpr to the pParse->pConstExpr list with a register number of 0. 1227 */ 1228 void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){ 1229 pParse->pConstExpr = 1230 sqlite3ExprListAppend(pParse, pParse->pConstExpr, pExpr); 1231 } 1232 1233 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the 1234 ** expression. 1235 */ 1236 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){ 1237 if( p ){ 1238 if( IN_RENAME_OBJECT ){ 1239 sqlite3RenameExprUnmap(pParse, p); 1240 } 1241 sqlite3ExprDeleteNN(pParse->db, p); 1242 } 1243 } 1244 1245 /* 1246 ** Return the number of bytes allocated for the expression structure 1247 ** passed as the first argument. This is always one of EXPR_FULLSIZE, 1248 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. 1249 */ 1250 static int exprStructSize(Expr *p){ 1251 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; 1252 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; 1253 return EXPR_FULLSIZE; 1254 } 1255 1256 /* 1257 ** The dupedExpr*Size() routines each return the number of bytes required 1258 ** to store a copy of an expression or expression tree. They differ in 1259 ** how much of the tree is measured. 1260 ** 1261 ** dupedExprStructSize() Size of only the Expr structure 1262 ** dupedExprNodeSize() Size of Expr + space for token 1263 ** dupedExprSize() Expr + token + subtree components 1264 ** 1265 *************************************************************************** 1266 ** 1267 ** The dupedExprStructSize() function returns two values OR-ed together: 1268 ** (1) the space required for a copy of the Expr structure only and 1269 ** (2) the EP_xxx flags that indicate what the structure size should be. 1270 ** The return values is always one of: 1271 ** 1272 ** EXPR_FULLSIZE 1273 ** EXPR_REDUCEDSIZE | EP_Reduced 1274 ** EXPR_TOKENONLYSIZE | EP_TokenOnly 1275 ** 1276 ** The size of the structure can be found by masking the return value 1277 ** of this routine with 0xfff. The flags can be found by masking the 1278 ** return value with EP_Reduced|EP_TokenOnly. 1279 ** 1280 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size 1281 ** (unreduced) Expr objects as they or originally constructed by the parser. 1282 ** During expression analysis, extra information is computed and moved into 1283 ** later parts of the Expr object and that extra information might get chopped 1284 ** off if the expression is reduced. Note also that it does not work to 1285 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal 1286 ** to reduce a pristine expression tree from the parser. The implementation 1287 ** of dupedExprStructSize() contain multiple assert() statements that attempt 1288 ** to enforce this constraint. 1289 */ 1290 static int dupedExprStructSize(Expr *p, int flags){ 1291 int nSize; 1292 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ 1293 assert( EXPR_FULLSIZE<=0xfff ); 1294 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); 1295 if( 0==flags || p->op==TK_SELECT_COLUMN 1296 #ifndef SQLITE_OMIT_WINDOWFUNC 1297 || ExprHasProperty(p, EP_WinFunc) 1298 #endif 1299 ){ 1300 nSize = EXPR_FULLSIZE; 1301 }else{ 1302 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 1303 assert( !ExprHasProperty(p, EP_FromJoin) ); 1304 assert( !ExprHasProperty(p, EP_MemToken) ); 1305 assert( !ExprHasVVAProperty(p, EP_NoReduce) ); 1306 if( p->pLeft || p->x.pList ){ 1307 nSize = EXPR_REDUCEDSIZE | EP_Reduced; 1308 }else{ 1309 assert( p->pRight==0 ); 1310 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; 1311 } 1312 } 1313 return nSize; 1314 } 1315 1316 /* 1317 ** This function returns the space in bytes required to store the copy 1318 ** of the Expr structure and a copy of the Expr.u.zToken string (if that 1319 ** string is defined.) 1320 */ 1321 static int dupedExprNodeSize(Expr *p, int flags){ 1322 int nByte = dupedExprStructSize(p, flags) & 0xfff; 1323 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 1324 nByte += sqlite3Strlen30NN(p->u.zToken)+1; 1325 } 1326 return ROUND8(nByte); 1327 } 1328 1329 /* 1330 ** Return the number of bytes required to create a duplicate of the 1331 ** expression passed as the first argument. The second argument is a 1332 ** mask containing EXPRDUP_XXX flags. 1333 ** 1334 ** The value returned includes space to create a copy of the Expr struct 1335 ** itself and the buffer referred to by Expr.u.zToken, if any. 1336 ** 1337 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 1338 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 1339 ** and Expr.pRight variables (but not for any structures pointed to or 1340 ** descended from the Expr.x.pList or Expr.x.pSelect variables). 1341 */ 1342 static int dupedExprSize(Expr *p, int flags){ 1343 int nByte = 0; 1344 if( p ){ 1345 nByte = dupedExprNodeSize(p, flags); 1346 if( flags&EXPRDUP_REDUCE ){ 1347 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags); 1348 } 1349 } 1350 return nByte; 1351 } 1352 1353 /* 1354 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 1355 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 1356 ** to store the copy of expression p, the copies of p->u.zToken 1357 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions, 1358 ** if any. Before returning, *pzBuffer is set to the first byte past the 1359 ** portion of the buffer copied into by this function. 1360 */ 1361 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){ 1362 Expr *pNew; /* Value to return */ 1363 u8 *zAlloc; /* Memory space from which to build Expr object */ 1364 u32 staticFlag; /* EP_Static if space not obtained from malloc */ 1365 1366 assert( db!=0 ); 1367 assert( p ); 1368 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE ); 1369 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE ); 1370 1371 /* Figure out where to write the new Expr structure. */ 1372 if( pzBuffer ){ 1373 zAlloc = *pzBuffer; 1374 staticFlag = EP_Static; 1375 assert( zAlloc!=0 ); 1376 }else{ 1377 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags)); 1378 staticFlag = 0; 1379 } 1380 pNew = (Expr *)zAlloc; 1381 1382 if( pNew ){ 1383 /* Set nNewSize to the size allocated for the structure pointed to 1384 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or 1385 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed 1386 ** by the copy of the p->u.zToken string (if any). 1387 */ 1388 const unsigned nStructSize = dupedExprStructSize(p, dupFlags); 1389 const int nNewSize = nStructSize & 0xfff; 1390 int nToken; 1391 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 1392 nToken = sqlite3Strlen30(p->u.zToken) + 1; 1393 }else{ 1394 nToken = 0; 1395 } 1396 if( dupFlags ){ 1397 assert( ExprHasProperty(p, EP_Reduced)==0 ); 1398 memcpy(zAlloc, p, nNewSize); 1399 }else{ 1400 u32 nSize = (u32)exprStructSize(p); 1401 memcpy(zAlloc, p, nSize); 1402 if( nSize<EXPR_FULLSIZE ){ 1403 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize); 1404 } 1405 } 1406 1407 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ 1408 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken); 1409 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); 1410 pNew->flags |= staticFlag; 1411 ExprClearVVAProperties(pNew); 1412 if( dupFlags ){ 1413 ExprSetVVAProperty(pNew, EP_Immutable); 1414 } 1415 1416 /* Copy the p->u.zToken string, if any. */ 1417 if( nToken ){ 1418 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize]; 1419 memcpy(zToken, p->u.zToken, nToken); 1420 } 1421 1422 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){ 1423 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ 1424 if( ExprHasProperty(p, EP_xIsSelect) ){ 1425 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); 1426 }else{ 1427 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags); 1428 } 1429 } 1430 1431 /* Fill in pNew->pLeft and pNew->pRight. */ 1432 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){ 1433 zAlloc += dupedExprNodeSize(p, dupFlags); 1434 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){ 1435 pNew->pLeft = p->pLeft ? 1436 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0; 1437 pNew->pRight = p->pRight ? 1438 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0; 1439 } 1440 #ifndef SQLITE_OMIT_WINDOWFUNC 1441 if( ExprHasProperty(p, EP_WinFunc) ){ 1442 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin); 1443 assert( ExprHasProperty(pNew, EP_WinFunc) ); 1444 } 1445 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1446 if( pzBuffer ){ 1447 *pzBuffer = zAlloc; 1448 } 1449 }else{ 1450 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ 1451 if( pNew->op==TK_SELECT_COLUMN ){ 1452 pNew->pLeft = p->pLeft; 1453 assert( p->pRight==0 || p->pRight==p->pLeft 1454 || ExprHasProperty(p->pLeft, EP_Subquery) ); 1455 }else{ 1456 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); 1457 } 1458 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); 1459 } 1460 } 1461 } 1462 return pNew; 1463 } 1464 1465 /* 1466 ** Create and return a deep copy of the object passed as the second 1467 ** argument. If an OOM condition is encountered, NULL is returned 1468 ** and the db->mallocFailed flag set. 1469 */ 1470 #ifndef SQLITE_OMIT_CTE 1471 With *sqlite3WithDup(sqlite3 *db, With *p){ 1472 With *pRet = 0; 1473 if( p ){ 1474 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); 1475 pRet = sqlite3DbMallocZero(db, nByte); 1476 if( pRet ){ 1477 int i; 1478 pRet->nCte = p->nCte; 1479 for(i=0; i<p->nCte; i++){ 1480 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); 1481 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); 1482 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); 1483 } 1484 } 1485 } 1486 return pRet; 1487 } 1488 #else 1489 # define sqlite3WithDup(x,y) 0 1490 #endif 1491 1492 #ifndef SQLITE_OMIT_WINDOWFUNC 1493 /* 1494 ** The gatherSelectWindows() procedure and its helper routine 1495 ** gatherSelectWindowsCallback() are used to scan all the expressions 1496 ** an a newly duplicated SELECT statement and gather all of the Window 1497 ** objects found there, assembling them onto the linked list at Select->pWin. 1498 */ 1499 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){ 1500 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){ 1501 Select *pSelect = pWalker->u.pSelect; 1502 Window *pWin = pExpr->y.pWin; 1503 assert( pWin ); 1504 assert( IsWindowFunc(pExpr) ); 1505 assert( pWin->ppThis==0 ); 1506 sqlite3WindowLink(pSelect, pWin); 1507 } 1508 return WRC_Continue; 1509 } 1510 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){ 1511 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune; 1512 } 1513 static void gatherSelectWindows(Select *p){ 1514 Walker w; 1515 w.xExprCallback = gatherSelectWindowsCallback; 1516 w.xSelectCallback = gatherSelectWindowsSelectCallback; 1517 w.xSelectCallback2 = 0; 1518 w.pParse = 0; 1519 w.u.pSelect = p; 1520 sqlite3WalkSelect(&w, p); 1521 } 1522 #endif 1523 1524 1525 /* 1526 ** The following group of routines make deep copies of expressions, 1527 ** expression lists, ID lists, and select statements. The copies can 1528 ** be deleted (by being passed to their respective ...Delete() routines) 1529 ** without effecting the originals. 1530 ** 1531 ** The expression list, ID, and source lists return by sqlite3ExprListDup(), 1532 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 1533 ** by subsequent calls to sqlite*ListAppend() routines. 1534 ** 1535 ** Any tables that the SrcList might point to are not duplicated. 1536 ** 1537 ** The flags parameter contains a combination of the EXPRDUP_XXX flags. 1538 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a 1539 ** truncated version of the usual Expr structure that will be stored as 1540 ** part of the in-memory representation of the database schema. 1541 */ 1542 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){ 1543 assert( flags==0 || flags==EXPRDUP_REDUCE ); 1544 return p ? exprDup(db, p, flags, 0) : 0; 1545 } 1546 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){ 1547 ExprList *pNew; 1548 struct ExprList_item *pItem, *pOldItem; 1549 int i; 1550 Expr *pPriorSelectColOld = 0; 1551 Expr *pPriorSelectColNew = 0; 1552 assert( db!=0 ); 1553 if( p==0 ) return 0; 1554 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p)); 1555 if( pNew==0 ) return 0; 1556 pNew->nExpr = p->nExpr; 1557 pNew->nAlloc = p->nAlloc; 1558 pItem = pNew->a; 1559 pOldItem = p->a; 1560 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){ 1561 Expr *pOldExpr = pOldItem->pExpr; 1562 Expr *pNewExpr; 1563 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); 1564 if( pOldExpr 1565 && pOldExpr->op==TK_SELECT_COLUMN 1566 && (pNewExpr = pItem->pExpr)!=0 1567 ){ 1568 if( pNewExpr->pRight ){ 1569 pPriorSelectColOld = pOldExpr->pRight; 1570 pPriorSelectColNew = pNewExpr->pRight; 1571 pNewExpr->pLeft = pNewExpr->pRight; 1572 }else{ 1573 if( pOldExpr->pLeft!=pPriorSelectColOld ){ 1574 pPriorSelectColOld = pOldExpr->pLeft; 1575 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags); 1576 pNewExpr->pRight = pPriorSelectColNew; 1577 } 1578 pNewExpr->pLeft = pPriorSelectColNew; 1579 } 1580 } 1581 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName); 1582 pItem->sortFlags = pOldItem->sortFlags; 1583 pItem->eEName = pOldItem->eEName; 1584 pItem->done = 0; 1585 pItem->bNulls = pOldItem->bNulls; 1586 pItem->bSorterRef = pOldItem->bSorterRef; 1587 pItem->u = pOldItem->u; 1588 } 1589 return pNew; 1590 } 1591 1592 /* 1593 ** If cursors, triggers, views and subqueries are all omitted from 1594 ** the build, then none of the following routines, except for 1595 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes 1596 ** called with a NULL argument. 1597 */ 1598 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ 1599 || !defined(SQLITE_OMIT_SUBQUERY) 1600 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){ 1601 SrcList *pNew; 1602 int i; 1603 int nByte; 1604 assert( db!=0 ); 1605 if( p==0 ) return 0; 1606 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); 1607 pNew = sqlite3DbMallocRawNN(db, nByte ); 1608 if( pNew==0 ) return 0; 1609 pNew->nSrc = pNew->nAlloc = p->nSrc; 1610 for(i=0; i<p->nSrc; i++){ 1611 SrcItem *pNewItem = &pNew->a[i]; 1612 SrcItem *pOldItem = &p->a[i]; 1613 Table *pTab; 1614 pNewItem->pSchema = pOldItem->pSchema; 1615 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); 1616 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 1617 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); 1618 pNewItem->fg = pOldItem->fg; 1619 pNewItem->iCursor = pOldItem->iCursor; 1620 pNewItem->addrFillSub = pOldItem->addrFillSub; 1621 pNewItem->regReturn = pOldItem->regReturn; 1622 if( pNewItem->fg.isIndexedBy ){ 1623 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); 1624 } 1625 pNewItem->u2 = pOldItem->u2; 1626 if( pNewItem->fg.isCte ){ 1627 pNewItem->u2.pCteUse->nUse++; 1628 } 1629 if( pNewItem->fg.isTabFunc ){ 1630 pNewItem->u1.pFuncArg = 1631 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); 1632 } 1633 pTab = pNewItem->pTab = pOldItem->pTab; 1634 if( pTab ){ 1635 pTab->nTabRef++; 1636 } 1637 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); 1638 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags); 1639 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing); 1640 pNewItem->colUsed = pOldItem->colUsed; 1641 } 1642 return pNew; 1643 } 1644 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){ 1645 IdList *pNew; 1646 int i; 1647 assert( db!=0 ); 1648 if( p==0 ) return 0; 1649 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) ); 1650 if( pNew==0 ) return 0; 1651 pNew->nId = p->nId; 1652 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) ); 1653 if( pNew->a==0 ){ 1654 sqlite3DbFreeNN(db, pNew); 1655 return 0; 1656 } 1657 /* Note that because the size of the allocation for p->a[] is not 1658 ** necessarily a power of two, sqlite3IdListAppend() may not be called 1659 ** on the duplicate created by this function. */ 1660 for(i=0; i<p->nId; i++){ 1661 struct IdList_item *pNewItem = &pNew->a[i]; 1662 struct IdList_item *pOldItem = &p->a[i]; 1663 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 1664 pNewItem->idx = pOldItem->idx; 1665 } 1666 return pNew; 1667 } 1668 Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){ 1669 Select *pRet = 0; 1670 Select *pNext = 0; 1671 Select **pp = &pRet; 1672 Select *p; 1673 1674 assert( db!=0 ); 1675 for(p=pDup; p; p=p->pPrior){ 1676 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); 1677 if( pNew==0 ) break; 1678 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); 1679 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); 1680 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); 1681 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); 1682 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); 1683 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); 1684 pNew->op = p->op; 1685 pNew->pNext = pNext; 1686 pNew->pPrior = 0; 1687 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); 1688 pNew->iLimit = 0; 1689 pNew->iOffset = 0; 1690 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; 1691 pNew->addrOpenEphm[0] = -1; 1692 pNew->addrOpenEphm[1] = -1; 1693 pNew->nSelectRow = p->nSelectRow; 1694 pNew->pWith = sqlite3WithDup(db, p->pWith); 1695 #ifndef SQLITE_OMIT_WINDOWFUNC 1696 pNew->pWin = 0; 1697 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn); 1698 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew); 1699 #endif 1700 pNew->selId = p->selId; 1701 if( db->mallocFailed ){ 1702 /* Any prior OOM might have left the Select object incomplete. 1703 ** Delete the whole thing rather than allow an incomplete Select 1704 ** to be used by the code generator. */ 1705 pNew->pNext = 0; 1706 sqlite3SelectDelete(db, pNew); 1707 break; 1708 } 1709 *pp = pNew; 1710 pp = &pNew->pPrior; 1711 pNext = pNew; 1712 } 1713 1714 return pRet; 1715 } 1716 #else 1717 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){ 1718 assert( p==0 ); 1719 return 0; 1720 } 1721 #endif 1722 1723 1724 /* 1725 ** Add a new element to the end of an expression list. If pList is 1726 ** initially NULL, then create a new expression list. 1727 ** 1728 ** The pList argument must be either NULL or a pointer to an ExprList 1729 ** obtained from a prior call to sqlite3ExprListAppend(). This routine 1730 ** may not be used with an ExprList obtained from sqlite3ExprListDup(). 1731 ** Reason: This routine assumes that the number of slots in pList->a[] 1732 ** is a power of two. That is true for sqlite3ExprListAppend() returns 1733 ** but is not necessarily true from the return value of sqlite3ExprListDup(). 1734 ** 1735 ** If a memory allocation error occurs, the entire list is freed and 1736 ** NULL is returned. If non-NULL is returned, then it is guaranteed 1737 ** that the new entry was successfully appended. 1738 */ 1739 static const struct ExprList_item zeroItem = {0}; 1740 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew( 1741 sqlite3 *db, /* Database handle. Used for memory allocation */ 1742 Expr *pExpr /* Expression to be appended. Might be NULL */ 1743 ){ 1744 struct ExprList_item *pItem; 1745 ExprList *pList; 1746 1747 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 ); 1748 if( pList==0 ){ 1749 sqlite3ExprDelete(db, pExpr); 1750 return 0; 1751 } 1752 pList->nAlloc = 4; 1753 pList->nExpr = 1; 1754 pItem = &pList->a[0]; 1755 *pItem = zeroItem; 1756 pItem->pExpr = pExpr; 1757 return pList; 1758 } 1759 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow( 1760 sqlite3 *db, /* Database handle. Used for memory allocation */ 1761 ExprList *pList, /* List to which to append. Might be NULL */ 1762 Expr *pExpr /* Expression to be appended. Might be NULL */ 1763 ){ 1764 struct ExprList_item *pItem; 1765 ExprList *pNew; 1766 pList->nAlloc *= 2; 1767 pNew = sqlite3DbRealloc(db, pList, 1768 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0])); 1769 if( pNew==0 ){ 1770 sqlite3ExprListDelete(db, pList); 1771 sqlite3ExprDelete(db, pExpr); 1772 return 0; 1773 }else{ 1774 pList = pNew; 1775 } 1776 pItem = &pList->a[pList->nExpr++]; 1777 *pItem = zeroItem; 1778 pItem->pExpr = pExpr; 1779 return pList; 1780 } 1781 ExprList *sqlite3ExprListAppend( 1782 Parse *pParse, /* Parsing context */ 1783 ExprList *pList, /* List to which to append. Might be NULL */ 1784 Expr *pExpr /* Expression to be appended. Might be NULL */ 1785 ){ 1786 struct ExprList_item *pItem; 1787 if( pList==0 ){ 1788 return sqlite3ExprListAppendNew(pParse->db,pExpr); 1789 } 1790 if( pList->nAlloc<pList->nExpr+1 ){ 1791 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr); 1792 } 1793 pItem = &pList->a[pList->nExpr++]; 1794 *pItem = zeroItem; 1795 pItem->pExpr = pExpr; 1796 return pList; 1797 } 1798 1799 /* 1800 ** pColumns and pExpr form a vector assignment which is part of the SET 1801 ** clause of an UPDATE statement. Like this: 1802 ** 1803 ** (a,b,c) = (expr1,expr2,expr3) 1804 ** Or: (a,b,c) = (SELECT x,y,z FROM ....) 1805 ** 1806 ** For each term of the vector assignment, append new entries to the 1807 ** expression list pList. In the case of a subquery on the RHS, append 1808 ** TK_SELECT_COLUMN expressions. 1809 */ 1810 ExprList *sqlite3ExprListAppendVector( 1811 Parse *pParse, /* Parsing context */ 1812 ExprList *pList, /* List to which to append. Might be NULL */ 1813 IdList *pColumns, /* List of names of LHS of the assignment */ 1814 Expr *pExpr /* Vector expression to be appended. Might be NULL */ 1815 ){ 1816 sqlite3 *db = pParse->db; 1817 int n; 1818 int i; 1819 int iFirst = pList ? pList->nExpr : 0; 1820 /* pColumns can only be NULL due to an OOM but an OOM will cause an 1821 ** exit prior to this routine being invoked */ 1822 if( NEVER(pColumns==0) ) goto vector_append_error; 1823 if( pExpr==0 ) goto vector_append_error; 1824 1825 /* If the RHS is a vector, then we can immediately check to see that 1826 ** the size of the RHS and LHS match. But if the RHS is a SELECT, 1827 ** wildcards ("*") in the result set of the SELECT must be expanded before 1828 ** we can do the size check, so defer the size check until code generation. 1829 */ 1830 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){ 1831 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 1832 pColumns->nId, n); 1833 goto vector_append_error; 1834 } 1835 1836 for(i=0; i<pColumns->nId; i++){ 1837 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId); 1838 assert( pSubExpr!=0 || db->mallocFailed ); 1839 if( pSubExpr==0 ) continue; 1840 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); 1841 if( pList ){ 1842 assert( pList->nExpr==iFirst+i+1 ); 1843 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName; 1844 pColumns->a[i].zName = 0; 1845 } 1846 } 1847 1848 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){ 1849 Expr *pFirst = pList->a[iFirst].pExpr; 1850 assert( pFirst!=0 ); 1851 assert( pFirst->op==TK_SELECT_COLUMN ); 1852 1853 /* Store the SELECT statement in pRight so it will be deleted when 1854 ** sqlite3ExprListDelete() is called */ 1855 pFirst->pRight = pExpr; 1856 pExpr = 0; 1857 1858 /* Remember the size of the LHS in iTable so that we can check that 1859 ** the RHS and LHS sizes match during code generation. */ 1860 pFirst->iTable = pColumns->nId; 1861 } 1862 1863 vector_append_error: 1864 sqlite3ExprUnmapAndDelete(pParse, pExpr); 1865 sqlite3IdListDelete(db, pColumns); 1866 return pList; 1867 } 1868 1869 /* 1870 ** Set the sort order for the last element on the given ExprList. 1871 */ 1872 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){ 1873 struct ExprList_item *pItem; 1874 if( p==0 ) return; 1875 assert( p->nExpr>0 ); 1876 1877 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 ); 1878 assert( iSortOrder==SQLITE_SO_UNDEFINED 1879 || iSortOrder==SQLITE_SO_ASC 1880 || iSortOrder==SQLITE_SO_DESC 1881 ); 1882 assert( eNulls==SQLITE_SO_UNDEFINED 1883 || eNulls==SQLITE_SO_ASC 1884 || eNulls==SQLITE_SO_DESC 1885 ); 1886 1887 pItem = &p->a[p->nExpr-1]; 1888 assert( pItem->bNulls==0 ); 1889 if( iSortOrder==SQLITE_SO_UNDEFINED ){ 1890 iSortOrder = SQLITE_SO_ASC; 1891 } 1892 pItem->sortFlags = (u8)iSortOrder; 1893 1894 if( eNulls!=SQLITE_SO_UNDEFINED ){ 1895 pItem->bNulls = 1; 1896 if( iSortOrder!=eNulls ){ 1897 pItem->sortFlags |= KEYINFO_ORDER_BIGNULL; 1898 } 1899 } 1900 } 1901 1902 /* 1903 ** Set the ExprList.a[].zEName element of the most recently added item 1904 ** on the expression list. 1905 ** 1906 ** pList might be NULL following an OOM error. But pName should never be 1907 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 1908 ** is set. 1909 */ 1910 void sqlite3ExprListSetName( 1911 Parse *pParse, /* Parsing context */ 1912 ExprList *pList, /* List to which to add the span. */ 1913 Token *pName, /* Name to be added */ 1914 int dequote /* True to cause the name to be dequoted */ 1915 ){ 1916 assert( pList!=0 || pParse->db->mallocFailed!=0 ); 1917 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 ); 1918 if( pList ){ 1919 struct ExprList_item *pItem; 1920 assert( pList->nExpr>0 ); 1921 pItem = &pList->a[pList->nExpr-1]; 1922 assert( pItem->zEName==0 ); 1923 assert( pItem->eEName==ENAME_NAME ); 1924 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); 1925 if( dequote ){ 1926 /* If dequote==0, then pName->z does not point to part of a DDL 1927 ** statement handled by the parser. And so no token need be added 1928 ** to the token-map. */ 1929 sqlite3Dequote(pItem->zEName); 1930 if( IN_RENAME_OBJECT ){ 1931 sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName); 1932 } 1933 } 1934 } 1935 } 1936 1937 /* 1938 ** Set the ExprList.a[].zSpan element of the most recently added item 1939 ** on the expression list. 1940 ** 1941 ** pList might be NULL following an OOM error. But pSpan should never be 1942 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 1943 ** is set. 1944 */ 1945 void sqlite3ExprListSetSpan( 1946 Parse *pParse, /* Parsing context */ 1947 ExprList *pList, /* List to which to add the span. */ 1948 const char *zStart, /* Start of the span */ 1949 const char *zEnd /* End of the span */ 1950 ){ 1951 sqlite3 *db = pParse->db; 1952 assert( pList!=0 || db->mallocFailed!=0 ); 1953 if( pList ){ 1954 struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; 1955 assert( pList->nExpr>0 ); 1956 if( pItem->zEName==0 ){ 1957 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd); 1958 pItem->eEName = ENAME_SPAN; 1959 } 1960 } 1961 } 1962 1963 /* 1964 ** If the expression list pEList contains more than iLimit elements, 1965 ** leave an error message in pParse. 1966 */ 1967 void sqlite3ExprListCheckLength( 1968 Parse *pParse, 1969 ExprList *pEList, 1970 const char *zObject 1971 ){ 1972 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; 1973 testcase( pEList && pEList->nExpr==mx ); 1974 testcase( pEList && pEList->nExpr==mx+1 ); 1975 if( pEList && pEList->nExpr>mx ){ 1976 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); 1977 } 1978 } 1979 1980 /* 1981 ** Delete an entire expression list. 1982 */ 1983 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ 1984 int i = pList->nExpr; 1985 struct ExprList_item *pItem = pList->a; 1986 assert( pList->nExpr>0 ); 1987 do{ 1988 sqlite3ExprDelete(db, pItem->pExpr); 1989 sqlite3DbFree(db, pItem->zEName); 1990 pItem++; 1991 }while( --i>0 ); 1992 sqlite3DbFreeNN(db, pList); 1993 } 1994 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ 1995 if( pList ) exprListDeleteNN(db, pList); 1996 } 1997 1998 /* 1999 ** Return the bitwise-OR of all Expr.flags fields in the given 2000 ** ExprList. 2001 */ 2002 u32 sqlite3ExprListFlags(const ExprList *pList){ 2003 int i; 2004 u32 m = 0; 2005 assert( pList!=0 ); 2006 for(i=0; i<pList->nExpr; i++){ 2007 Expr *pExpr = pList->a[i].pExpr; 2008 assert( pExpr!=0 ); 2009 m |= pExpr->flags; 2010 } 2011 return m; 2012 } 2013 2014 /* 2015 ** This is a SELECT-node callback for the expression walker that 2016 ** always "fails". By "fail" in this case, we mean set 2017 ** pWalker->eCode to zero and abort. 2018 ** 2019 ** This callback is used by multiple expression walkers. 2020 */ 2021 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){ 2022 UNUSED_PARAMETER(NotUsed); 2023 pWalker->eCode = 0; 2024 return WRC_Abort; 2025 } 2026 2027 /* 2028 ** Check the input string to see if it is "true" or "false" (in any case). 2029 ** 2030 ** If the string is.... Return 2031 ** "true" EP_IsTrue 2032 ** "false" EP_IsFalse 2033 ** anything else 0 2034 */ 2035 u32 sqlite3IsTrueOrFalse(const char *zIn){ 2036 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue; 2037 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse; 2038 return 0; 2039 } 2040 2041 2042 /* 2043 ** If the input expression is an ID with the name "true" or "false" 2044 ** then convert it into an TK_TRUEFALSE term. Return non-zero if 2045 ** the conversion happened, and zero if the expression is unaltered. 2046 */ 2047 int sqlite3ExprIdToTrueFalse(Expr *pExpr){ 2048 u32 v; 2049 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING ); 2050 if( !ExprHasProperty(pExpr, EP_Quoted) 2051 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0 2052 ){ 2053 pExpr->op = TK_TRUEFALSE; 2054 ExprSetProperty(pExpr, v); 2055 return 1; 2056 } 2057 return 0; 2058 } 2059 2060 /* 2061 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE 2062 ** and 0 if it is FALSE. 2063 */ 2064 int sqlite3ExprTruthValue(const Expr *pExpr){ 2065 pExpr = sqlite3ExprSkipCollate((Expr*)pExpr); 2066 assert( pExpr->op==TK_TRUEFALSE ); 2067 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0 2068 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 ); 2069 return pExpr->u.zToken[4]==0; 2070 } 2071 2072 /* 2073 ** If pExpr is an AND or OR expression, try to simplify it by eliminating 2074 ** terms that are always true or false. Return the simplified expression. 2075 ** Or return the original expression if no simplification is possible. 2076 ** 2077 ** Examples: 2078 ** 2079 ** (x<10) AND true => (x<10) 2080 ** (x<10) AND false => false 2081 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22) 2082 ** (x<10) AND (y=22 OR true) => (x<10) 2083 ** (y=22) OR true => true 2084 */ 2085 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){ 2086 assert( pExpr!=0 ); 2087 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){ 2088 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight); 2089 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft); 2090 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){ 2091 pExpr = pExpr->op==TK_AND ? pRight : pLeft; 2092 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){ 2093 pExpr = pExpr->op==TK_AND ? pLeft : pRight; 2094 } 2095 } 2096 return pExpr; 2097 } 2098 2099 2100 /* 2101 ** These routines are Walker callbacks used to check expressions to 2102 ** see if they are "constant" for some definition of constant. The 2103 ** Walker.eCode value determines the type of "constant" we are looking 2104 ** for. 2105 ** 2106 ** These callback routines are used to implement the following: 2107 ** 2108 ** sqlite3ExprIsConstant() pWalker->eCode==1 2109 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 2110 ** sqlite3ExprIsTableConstant() pWalker->eCode==3 2111 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 2112 ** 2113 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression 2114 ** is found to not be a constant. 2115 ** 2116 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT 2117 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5 2118 ** when parsing an existing schema out of the sqlite_schema table and 4 2119 ** when processing a new CREATE TABLE statement. A bound parameter raises 2120 ** an error for new statements, but is silently converted 2121 ** to NULL for existing schemas. This allows sqlite_schema tables that 2122 ** contain a bound parameter because they were generated by older versions 2123 ** of SQLite to be parsed by newer versions of SQLite without raising a 2124 ** malformed schema error. 2125 */ 2126 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ 2127 2128 /* If pWalker->eCode is 2 then any term of the expression that comes from 2129 ** the ON or USING clauses of a left join disqualifies the expression 2130 ** from being considered constant. */ 2131 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){ 2132 pWalker->eCode = 0; 2133 return WRC_Abort; 2134 } 2135 2136 switch( pExpr->op ){ 2137 /* Consider functions to be constant if all their arguments are constant 2138 ** and either pWalker->eCode==4 or 5 or the function has the 2139 ** SQLITE_FUNC_CONST flag. */ 2140 case TK_FUNCTION: 2141 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc)) 2142 && !ExprHasProperty(pExpr, EP_WinFunc) 2143 ){ 2144 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL); 2145 return WRC_Continue; 2146 }else{ 2147 pWalker->eCode = 0; 2148 return WRC_Abort; 2149 } 2150 case TK_ID: 2151 /* Convert "true" or "false" in a DEFAULT clause into the 2152 ** appropriate TK_TRUEFALSE operator */ 2153 if( sqlite3ExprIdToTrueFalse(pExpr) ){ 2154 return WRC_Prune; 2155 } 2156 /* no break */ deliberate_fall_through 2157 case TK_COLUMN: 2158 case TK_AGG_FUNCTION: 2159 case TK_AGG_COLUMN: 2160 testcase( pExpr->op==TK_ID ); 2161 testcase( pExpr->op==TK_COLUMN ); 2162 testcase( pExpr->op==TK_AGG_FUNCTION ); 2163 testcase( pExpr->op==TK_AGG_COLUMN ); 2164 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){ 2165 return WRC_Continue; 2166 } 2167 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ 2168 return WRC_Continue; 2169 } 2170 /* no break */ deliberate_fall_through 2171 case TK_IF_NULL_ROW: 2172 case TK_REGISTER: 2173 case TK_DOT: 2174 testcase( pExpr->op==TK_REGISTER ); 2175 testcase( pExpr->op==TK_IF_NULL_ROW ); 2176 testcase( pExpr->op==TK_DOT ); 2177 pWalker->eCode = 0; 2178 return WRC_Abort; 2179 case TK_VARIABLE: 2180 if( pWalker->eCode==5 ){ 2181 /* Silently convert bound parameters that appear inside of CREATE 2182 ** statements into a NULL when parsing the CREATE statement text out 2183 ** of the sqlite_schema table */ 2184 pExpr->op = TK_NULL; 2185 }else if( pWalker->eCode==4 ){ 2186 /* A bound parameter in a CREATE statement that originates from 2187 ** sqlite3_prepare() causes an error */ 2188 pWalker->eCode = 0; 2189 return WRC_Abort; 2190 } 2191 /* no break */ deliberate_fall_through 2192 default: 2193 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */ 2194 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */ 2195 return WRC_Continue; 2196 } 2197 } 2198 static int exprIsConst(Expr *p, int initFlag, int iCur){ 2199 Walker w; 2200 w.eCode = initFlag; 2201 w.xExprCallback = exprNodeIsConstant; 2202 w.xSelectCallback = sqlite3SelectWalkFail; 2203 #ifdef SQLITE_DEBUG 2204 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 2205 #endif 2206 w.u.iCur = iCur; 2207 sqlite3WalkExpr(&w, p); 2208 return w.eCode; 2209 } 2210 2211 /* 2212 ** Walk an expression tree. Return non-zero if the expression is constant 2213 ** and 0 if it involves variables or function calls. 2214 ** 2215 ** For the purposes of this function, a double-quoted string (ex: "abc") 2216 ** is considered a variable but a single-quoted string (ex: 'abc') is 2217 ** a constant. 2218 */ 2219 int sqlite3ExprIsConstant(Expr *p){ 2220 return exprIsConst(p, 1, 0); 2221 } 2222 2223 /* 2224 ** Walk an expression tree. Return non-zero if 2225 ** 2226 ** (1) the expression is constant, and 2227 ** (2) the expression does originate in the ON or USING clause 2228 ** of a LEFT JOIN, and 2229 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN 2230 ** operands created by the constant propagation optimization. 2231 ** 2232 ** When this routine returns true, it indicates that the expression 2233 ** can be added to the pParse->pConstExpr list and evaluated once when 2234 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce(). 2235 */ 2236 int sqlite3ExprIsConstantNotJoin(Expr *p){ 2237 return exprIsConst(p, 2, 0); 2238 } 2239 2240 /* 2241 ** Walk an expression tree. Return non-zero if the expression is constant 2242 ** for any single row of the table with cursor iCur. In other words, the 2243 ** expression must not refer to any non-deterministic function nor any 2244 ** table other than iCur. 2245 */ 2246 int sqlite3ExprIsTableConstant(Expr *p, int iCur){ 2247 return exprIsConst(p, 3, iCur); 2248 } 2249 2250 2251 /* 2252 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy(). 2253 */ 2254 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){ 2255 ExprList *pGroupBy = pWalker->u.pGroupBy; 2256 int i; 2257 2258 /* Check if pExpr is identical to any GROUP BY term. If so, consider 2259 ** it constant. */ 2260 for(i=0; i<pGroupBy->nExpr; i++){ 2261 Expr *p = pGroupBy->a[i].pExpr; 2262 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){ 2263 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p); 2264 if( sqlite3IsBinary(pColl) ){ 2265 return WRC_Prune; 2266 } 2267 } 2268 } 2269 2270 /* Check if pExpr is a sub-select. If so, consider it variable. */ 2271 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2272 pWalker->eCode = 0; 2273 return WRC_Abort; 2274 } 2275 2276 return exprNodeIsConstant(pWalker, pExpr); 2277 } 2278 2279 /* 2280 ** Walk the expression tree passed as the first argument. Return non-zero 2281 ** if the expression consists entirely of constants or copies of terms 2282 ** in pGroupBy that sort with the BINARY collation sequence. 2283 ** 2284 ** This routine is used to determine if a term of the HAVING clause can 2285 ** be promoted into the WHERE clause. In order for such a promotion to work, 2286 ** the value of the HAVING clause term must be the same for all members of 2287 ** a "group". The requirement that the GROUP BY term must be BINARY 2288 ** assumes that no other collating sequence will have a finer-grained 2289 ** grouping than binary. In other words (A=B COLLATE binary) implies 2290 ** A=B in every other collating sequence. The requirement that the 2291 ** GROUP BY be BINARY is stricter than necessary. It would also work 2292 ** to promote HAVING clauses that use the same alternative collating 2293 ** sequence as the GROUP BY term, but that is much harder to check, 2294 ** alternative collating sequences are uncommon, and this is only an 2295 ** optimization, so we take the easy way out and simply require the 2296 ** GROUP BY to use the BINARY collating sequence. 2297 */ 2298 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){ 2299 Walker w; 2300 w.eCode = 1; 2301 w.xExprCallback = exprNodeIsConstantOrGroupBy; 2302 w.xSelectCallback = 0; 2303 w.u.pGroupBy = pGroupBy; 2304 w.pParse = pParse; 2305 sqlite3WalkExpr(&w, p); 2306 return w.eCode; 2307 } 2308 2309 /* 2310 ** Walk an expression tree for the DEFAULT field of a column definition 2311 ** in a CREATE TABLE statement. Return non-zero if the expression is 2312 ** acceptable for use as a DEFAULT. That is to say, return non-zero if 2313 ** the expression is constant or a function call with constant arguments. 2314 ** Return and 0 if there are any variables. 2315 ** 2316 ** isInit is true when parsing from sqlite_schema. isInit is false when 2317 ** processing a new CREATE TABLE statement. When isInit is true, parameters 2318 ** (such as ? or $abc) in the expression are converted into NULL. When 2319 ** isInit is false, parameters raise an error. Parameters should not be 2320 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite 2321 ** allowed it, so we need to support it when reading sqlite_schema for 2322 ** backwards compatibility. 2323 ** 2324 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node. 2325 ** 2326 ** For the purposes of this function, a double-quoted string (ex: "abc") 2327 ** is considered a variable but a single-quoted string (ex: 'abc') is 2328 ** a constant. 2329 */ 2330 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ 2331 assert( isInit==0 || isInit==1 ); 2332 return exprIsConst(p, 4+isInit, 0); 2333 } 2334 2335 #ifdef SQLITE_ENABLE_CURSOR_HINTS 2336 /* 2337 ** Walk an expression tree. Return 1 if the expression contains a 2338 ** subquery of some kind. Return 0 if there are no subqueries. 2339 */ 2340 int sqlite3ExprContainsSubquery(Expr *p){ 2341 Walker w; 2342 w.eCode = 1; 2343 w.xExprCallback = sqlite3ExprWalkNoop; 2344 w.xSelectCallback = sqlite3SelectWalkFail; 2345 #ifdef SQLITE_DEBUG 2346 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 2347 #endif 2348 sqlite3WalkExpr(&w, p); 2349 return w.eCode==0; 2350 } 2351 #endif 2352 2353 /* 2354 ** If the expression p codes a constant integer that is small enough 2355 ** to fit in a 32-bit integer, return 1 and put the value of the integer 2356 ** in *pValue. If the expression is not an integer or if it is too big 2357 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. 2358 */ 2359 int sqlite3ExprIsInteger(Expr *p, int *pValue){ 2360 int rc = 0; 2361 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */ 2362 2363 /* If an expression is an integer literal that fits in a signed 32-bit 2364 ** integer, then the EP_IntValue flag will have already been set */ 2365 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 2366 || sqlite3GetInt32(p->u.zToken, &rc)==0 ); 2367 2368 if( p->flags & EP_IntValue ){ 2369 *pValue = p->u.iValue; 2370 return 1; 2371 } 2372 switch( p->op ){ 2373 case TK_UPLUS: { 2374 rc = sqlite3ExprIsInteger(p->pLeft, pValue); 2375 break; 2376 } 2377 case TK_UMINUS: { 2378 int v; 2379 if( sqlite3ExprIsInteger(p->pLeft, &v) ){ 2380 assert( v!=(-2147483647-1) ); 2381 *pValue = -v; 2382 rc = 1; 2383 } 2384 break; 2385 } 2386 default: break; 2387 } 2388 return rc; 2389 } 2390 2391 /* 2392 ** Return FALSE if there is no chance that the expression can be NULL. 2393 ** 2394 ** If the expression might be NULL or if the expression is too complex 2395 ** to tell return TRUE. 2396 ** 2397 ** This routine is used as an optimization, to skip OP_IsNull opcodes 2398 ** when we know that a value cannot be NULL. Hence, a false positive 2399 ** (returning TRUE when in fact the expression can never be NULL) might 2400 ** be a small performance hit but is otherwise harmless. On the other 2401 ** hand, a false negative (returning FALSE when the result could be NULL) 2402 ** will likely result in an incorrect answer. So when in doubt, return 2403 ** TRUE. 2404 */ 2405 int sqlite3ExprCanBeNull(const Expr *p){ 2406 u8 op; 2407 assert( p!=0 ); 2408 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ 2409 p = p->pLeft; 2410 assert( p!=0 ); 2411 } 2412 op = p->op; 2413 if( op==TK_REGISTER ) op = p->op2; 2414 switch( op ){ 2415 case TK_INTEGER: 2416 case TK_STRING: 2417 case TK_FLOAT: 2418 case TK_BLOB: 2419 return 0; 2420 case TK_COLUMN: 2421 return ExprHasProperty(p, EP_CanBeNull) || 2422 p->y.pTab==0 || /* Reference to column of index on expression */ 2423 (p->iColumn>=0 2424 && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */ 2425 && p->y.pTab->aCol[p->iColumn].notNull==0); 2426 default: 2427 return 1; 2428 } 2429 } 2430 2431 /* 2432 ** Return TRUE if the given expression is a constant which would be 2433 ** unchanged by OP_Affinity with the affinity given in the second 2434 ** argument. 2435 ** 2436 ** This routine is used to determine if the OP_Affinity operation 2437 ** can be omitted. When in doubt return FALSE. A false negative 2438 ** is harmless. A false positive, however, can result in the wrong 2439 ** answer. 2440 */ 2441 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ 2442 u8 op; 2443 int unaryMinus = 0; 2444 if( aff==SQLITE_AFF_BLOB ) return 1; 2445 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ 2446 if( p->op==TK_UMINUS ) unaryMinus = 1; 2447 p = p->pLeft; 2448 } 2449 op = p->op; 2450 if( op==TK_REGISTER ) op = p->op2; 2451 switch( op ){ 2452 case TK_INTEGER: { 2453 return aff>=SQLITE_AFF_NUMERIC; 2454 } 2455 case TK_FLOAT: { 2456 return aff>=SQLITE_AFF_NUMERIC; 2457 } 2458 case TK_STRING: { 2459 return !unaryMinus && aff==SQLITE_AFF_TEXT; 2460 } 2461 case TK_BLOB: { 2462 return !unaryMinus; 2463 } 2464 case TK_COLUMN: { 2465 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ 2466 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0; 2467 } 2468 default: { 2469 return 0; 2470 } 2471 } 2472 } 2473 2474 /* 2475 ** Return TRUE if the given string is a row-id column name. 2476 */ 2477 int sqlite3IsRowid(const char *z){ 2478 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; 2479 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; 2480 if( sqlite3StrICmp(z, "OID")==0 ) return 1; 2481 return 0; 2482 } 2483 2484 /* 2485 ** pX is the RHS of an IN operator. If pX is a SELECT statement 2486 ** that can be simplified to a direct table access, then return 2487 ** a pointer to the SELECT statement. If pX is not a SELECT statement, 2488 ** or if the SELECT statement needs to be manifested into a transient 2489 ** table, then return NULL. 2490 */ 2491 #ifndef SQLITE_OMIT_SUBQUERY 2492 static Select *isCandidateForInOpt(Expr *pX){ 2493 Select *p; 2494 SrcList *pSrc; 2495 ExprList *pEList; 2496 Table *pTab; 2497 int i; 2498 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */ 2499 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */ 2500 p = pX->x.pSelect; 2501 if( p->pPrior ) return 0; /* Not a compound SELECT */ 2502 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ 2503 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 2504 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 2505 return 0; /* No DISTINCT keyword and no aggregate functions */ 2506 } 2507 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ 2508 if( p->pLimit ) return 0; /* Has no LIMIT clause */ 2509 if( p->pWhere ) return 0; /* Has no WHERE clause */ 2510 pSrc = p->pSrc; 2511 assert( pSrc!=0 ); 2512 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ 2513 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ 2514 pTab = pSrc->a[0].pTab; 2515 assert( pTab!=0 ); 2516 assert( pTab->pSelect==0 ); /* FROM clause is not a view */ 2517 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ 2518 pEList = p->pEList; 2519 assert( pEList!=0 ); 2520 /* All SELECT results must be columns. */ 2521 for(i=0; i<pEList->nExpr; i++){ 2522 Expr *pRes = pEList->a[i].pExpr; 2523 if( pRes->op!=TK_COLUMN ) return 0; 2524 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */ 2525 } 2526 return p; 2527 } 2528 #endif /* SQLITE_OMIT_SUBQUERY */ 2529 2530 #ifndef SQLITE_OMIT_SUBQUERY 2531 /* 2532 ** Generate code that checks the left-most column of index table iCur to see if 2533 ** it contains any NULL entries. Cause the register at regHasNull to be set 2534 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull 2535 ** to be set to NULL if iCur contains one or more NULL values. 2536 */ 2537 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ 2538 int addr1; 2539 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); 2540 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); 2541 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); 2542 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); 2543 VdbeComment((v, "first_entry_in(%d)", iCur)); 2544 sqlite3VdbeJumpHere(v, addr1); 2545 } 2546 #endif 2547 2548 2549 #ifndef SQLITE_OMIT_SUBQUERY 2550 /* 2551 ** The argument is an IN operator with a list (not a subquery) on the 2552 ** right-hand side. Return TRUE if that list is constant. 2553 */ 2554 static int sqlite3InRhsIsConstant(Expr *pIn){ 2555 Expr *pLHS; 2556 int res; 2557 assert( !ExprHasProperty(pIn, EP_xIsSelect) ); 2558 pLHS = pIn->pLeft; 2559 pIn->pLeft = 0; 2560 res = sqlite3ExprIsConstant(pIn); 2561 pIn->pLeft = pLHS; 2562 return res; 2563 } 2564 #endif 2565 2566 /* 2567 ** This function is used by the implementation of the IN (...) operator. 2568 ** The pX parameter is the expression on the RHS of the IN operator, which 2569 ** might be either a list of expressions or a subquery. 2570 ** 2571 ** The job of this routine is to find or create a b-tree object that can 2572 ** be used either to test for membership in the RHS set or to iterate through 2573 ** all members of the RHS set, skipping duplicates. 2574 ** 2575 ** A cursor is opened on the b-tree object that is the RHS of the IN operator 2576 ** and pX->iTable is set to the index of that cursor. 2577 ** 2578 ** The returned value of this function indicates the b-tree type, as follows: 2579 ** 2580 ** IN_INDEX_ROWID - The cursor was opened on a database table. 2581 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. 2582 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. 2583 ** IN_INDEX_EPH - The cursor was opened on a specially created and 2584 ** populated epheremal table. 2585 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be 2586 ** implemented as a sequence of comparisons. 2587 ** 2588 ** An existing b-tree might be used if the RHS expression pX is a simple 2589 ** subquery such as: 2590 ** 2591 ** SELECT <column1>, <column2>... FROM <table> 2592 ** 2593 ** If the RHS of the IN operator is a list or a more complex subquery, then 2594 ** an ephemeral table might need to be generated from the RHS and then 2595 ** pX->iTable made to point to the ephemeral table instead of an 2596 ** existing table. 2597 ** 2598 ** The inFlags parameter must contain, at a minimum, one of the bits 2599 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains 2600 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast 2601 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will 2602 ** be used to loop over all values of the RHS of the IN operator. 2603 ** 2604 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate 2605 ** through the set members) then the b-tree must not contain duplicates. 2606 ** An epheremal table will be created unless the selected columns are guaranteed 2607 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to 2608 ** a UNIQUE constraint or index. 2609 ** 2610 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 2611 ** for fast set membership tests) then an epheremal table must 2612 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an 2613 ** index can be found with the specified <columns> as its left-most. 2614 ** 2615 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and 2616 ** if the RHS of the IN operator is a list (not a subquery) then this 2617 ** routine might decide that creating an ephemeral b-tree for membership 2618 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the 2619 ** calling routine should implement the IN operator using a sequence 2620 ** of Eq or Ne comparison operations. 2621 ** 2622 ** When the b-tree is being used for membership tests, the calling function 2623 ** might need to know whether or not the RHS side of the IN operator 2624 ** contains a NULL. If prRhsHasNull is not a NULL pointer and 2625 ** if there is any chance that the (...) might contain a NULL value at 2626 ** runtime, then a register is allocated and the register number written 2627 ** to *prRhsHasNull. If there is no chance that the (...) contains a 2628 ** NULL value, then *prRhsHasNull is left unchanged. 2629 ** 2630 ** If a register is allocated and its location stored in *prRhsHasNull, then 2631 ** the value in that register will be NULL if the b-tree contains one or more 2632 ** NULL values, and it will be some non-NULL value if the b-tree contains no 2633 ** NULL values. 2634 ** 2635 ** If the aiMap parameter is not NULL, it must point to an array containing 2636 ** one element for each column returned by the SELECT statement on the RHS 2637 ** of the IN(...) operator. The i'th entry of the array is populated with the 2638 ** offset of the index column that matches the i'th column returned by the 2639 ** SELECT. For example, if the expression and selected index are: 2640 ** 2641 ** (?,?,?) IN (SELECT a, b, c FROM t1) 2642 ** CREATE INDEX i1 ON t1(b, c, a); 2643 ** 2644 ** then aiMap[] is populated with {2, 0, 1}. 2645 */ 2646 #ifndef SQLITE_OMIT_SUBQUERY 2647 int sqlite3FindInIndex( 2648 Parse *pParse, /* Parsing context */ 2649 Expr *pX, /* The IN expression */ 2650 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ 2651 int *prRhsHasNull, /* Register holding NULL status. See notes */ 2652 int *aiMap, /* Mapping from Index fields to RHS fields */ 2653 int *piTab /* OUT: index to use */ 2654 ){ 2655 Select *p; /* SELECT to the right of IN operator */ 2656 int eType = 0; /* Type of RHS table. IN_INDEX_* */ 2657 int iTab = pParse->nTab++; /* Cursor of the RHS table */ 2658 int mustBeUnique; /* True if RHS must be unique */ 2659 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ 2660 2661 assert( pX->op==TK_IN ); 2662 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; 2663 2664 /* If the RHS of this IN(...) operator is a SELECT, and if it matters 2665 ** whether or not the SELECT result contains NULL values, check whether 2666 ** or not NULL is actually possible (it may not be, for example, due 2667 ** to NOT NULL constraints in the schema). If no NULL values are possible, 2668 ** set prRhsHasNull to 0 before continuing. */ 2669 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){ 2670 int i; 2671 ExprList *pEList = pX->x.pSelect->pEList; 2672 for(i=0; i<pEList->nExpr; i++){ 2673 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; 2674 } 2675 if( i==pEList->nExpr ){ 2676 prRhsHasNull = 0; 2677 } 2678 } 2679 2680 /* Check to see if an existing table or index can be used to 2681 ** satisfy the query. This is preferable to generating a new 2682 ** ephemeral table. */ 2683 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ 2684 sqlite3 *db = pParse->db; /* Database connection */ 2685 Table *pTab; /* Table <table>. */ 2686 int iDb; /* Database idx for pTab */ 2687 ExprList *pEList = p->pEList; 2688 int nExpr = pEList->nExpr; 2689 2690 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ 2691 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ 2692 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ 2693 pTab = p->pSrc->a[0].pTab; 2694 2695 /* Code an OP_Transaction and OP_TableLock for <table>. */ 2696 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2697 assert( iDb>=0 && iDb<SQLITE_MAX_DB ); 2698 sqlite3CodeVerifySchema(pParse, iDb); 2699 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 2700 2701 assert(v); /* sqlite3GetVdbe() has always been previously called */ 2702 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ 2703 /* The "x IN (SELECT rowid FROM table)" case */ 2704 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); 2705 VdbeCoverage(v); 2706 2707 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 2708 eType = IN_INDEX_ROWID; 2709 ExplainQueryPlan((pParse, 0, 2710 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName)); 2711 sqlite3VdbeJumpHere(v, iAddr); 2712 }else{ 2713 Index *pIdx; /* Iterator variable */ 2714 int affinity_ok = 1; 2715 int i; 2716 2717 /* Check that the affinity that will be used to perform each 2718 ** comparison is the same as the affinity of each column in table 2719 ** on the RHS of the IN operator. If it not, it is not possible to 2720 ** use any index of the RHS table. */ 2721 for(i=0; i<nExpr && affinity_ok; i++){ 2722 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); 2723 int iCol = pEList->a[i].pExpr->iColumn; 2724 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ 2725 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); 2726 testcase( cmpaff==SQLITE_AFF_BLOB ); 2727 testcase( cmpaff==SQLITE_AFF_TEXT ); 2728 switch( cmpaff ){ 2729 case SQLITE_AFF_BLOB: 2730 break; 2731 case SQLITE_AFF_TEXT: 2732 /* sqlite3CompareAffinity() only returns TEXT if one side or the 2733 ** other has no affinity and the other side is TEXT. Hence, 2734 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT 2735 ** and for the term on the LHS of the IN to have no affinity. */ 2736 assert( idxaff==SQLITE_AFF_TEXT ); 2737 break; 2738 default: 2739 affinity_ok = sqlite3IsNumericAffinity(idxaff); 2740 } 2741 } 2742 2743 if( affinity_ok ){ 2744 /* Search for an existing index that will work for this IN operator */ 2745 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){ 2746 Bitmask colUsed; /* Columns of the index used */ 2747 Bitmask mCol; /* Mask for the current column */ 2748 if( pIdx->nColumn<nExpr ) continue; 2749 if( pIdx->pPartIdxWhere!=0 ) continue; 2750 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute 2751 ** BITMASK(nExpr) without overflowing */ 2752 testcase( pIdx->nColumn==BMS-2 ); 2753 testcase( pIdx->nColumn==BMS-1 ); 2754 if( pIdx->nColumn>=BMS-1 ) continue; 2755 if( mustBeUnique ){ 2756 if( pIdx->nKeyCol>nExpr 2757 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx)) 2758 ){ 2759 continue; /* This index is not unique over the IN RHS columns */ 2760 } 2761 } 2762 2763 colUsed = 0; /* Columns of index used so far */ 2764 for(i=0; i<nExpr; i++){ 2765 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); 2766 Expr *pRhs = pEList->a[i].pExpr; 2767 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); 2768 int j; 2769 2770 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr ); 2771 for(j=0; j<nExpr; j++){ 2772 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue; 2773 assert( pIdx->azColl[j] ); 2774 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ 2775 continue; 2776 } 2777 break; 2778 } 2779 if( j==nExpr ) break; 2780 mCol = MASKBIT(j); 2781 if( mCol & colUsed ) break; /* Each column used only once */ 2782 colUsed |= mCol; 2783 if( aiMap ) aiMap[i] = j; 2784 } 2785 2786 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); 2787 if( colUsed==(MASKBIT(nExpr)-1) ){ 2788 /* If we reach this point, that means the index pIdx is usable */ 2789 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 2790 ExplainQueryPlan((pParse, 0, 2791 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName)); 2792 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); 2793 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 2794 VdbeComment((v, "%s", pIdx->zName)); 2795 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); 2796 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; 2797 2798 if( prRhsHasNull ){ 2799 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 2800 i64 mask = (1<<nExpr)-1; 2801 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 2802 iTab, 0, 0, (u8*)&mask, P4_INT64); 2803 #endif 2804 *prRhsHasNull = ++pParse->nMem; 2805 if( nExpr==1 ){ 2806 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); 2807 } 2808 } 2809 sqlite3VdbeJumpHere(v, iAddr); 2810 } 2811 } /* End loop over indexes */ 2812 } /* End if( affinity_ok ) */ 2813 } /* End if not an rowid index */ 2814 } /* End attempt to optimize using an index */ 2815 2816 /* If no preexisting index is available for the IN clause 2817 ** and IN_INDEX_NOOP is an allowed reply 2818 ** and the RHS of the IN operator is a list, not a subquery 2819 ** and the RHS is not constant or has two or fewer terms, 2820 ** then it is not worth creating an ephemeral table to evaluate 2821 ** the IN operator so return IN_INDEX_NOOP. 2822 */ 2823 if( eType==0 2824 && (inFlags & IN_INDEX_NOOP_OK) 2825 && !ExprHasProperty(pX, EP_xIsSelect) 2826 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) 2827 ){ 2828 eType = IN_INDEX_NOOP; 2829 } 2830 2831 if( eType==0 ){ 2832 /* Could not find an existing table or index to use as the RHS b-tree. 2833 ** We will have to generate an ephemeral table to do the job. 2834 */ 2835 u32 savedNQueryLoop = pParse->nQueryLoop; 2836 int rMayHaveNull = 0; 2837 eType = IN_INDEX_EPH; 2838 if( inFlags & IN_INDEX_LOOP ){ 2839 pParse->nQueryLoop = 0; 2840 }else if( prRhsHasNull ){ 2841 *prRhsHasNull = rMayHaveNull = ++pParse->nMem; 2842 } 2843 assert( pX->op==TK_IN ); 2844 sqlite3CodeRhsOfIN(pParse, pX, iTab); 2845 if( rMayHaveNull ){ 2846 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull); 2847 } 2848 pParse->nQueryLoop = savedNQueryLoop; 2849 } 2850 2851 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ 2852 int i, n; 2853 n = sqlite3ExprVectorSize(pX->pLeft); 2854 for(i=0; i<n; i++) aiMap[i] = i; 2855 } 2856 *piTab = iTab; 2857 return eType; 2858 } 2859 #endif 2860 2861 #ifndef SQLITE_OMIT_SUBQUERY 2862 /* 2863 ** Argument pExpr is an (?, ?...) IN(...) expression. This 2864 ** function allocates and returns a nul-terminated string containing 2865 ** the affinities to be used for each column of the comparison. 2866 ** 2867 ** It is the responsibility of the caller to ensure that the returned 2868 ** string is eventually freed using sqlite3DbFree(). 2869 */ 2870 static char *exprINAffinity(Parse *pParse, Expr *pExpr){ 2871 Expr *pLeft = pExpr->pLeft; 2872 int nVal = sqlite3ExprVectorSize(pLeft); 2873 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0; 2874 char *zRet; 2875 2876 assert( pExpr->op==TK_IN ); 2877 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1); 2878 if( zRet ){ 2879 int i; 2880 for(i=0; i<nVal; i++){ 2881 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i); 2882 char a = sqlite3ExprAffinity(pA); 2883 if( pSelect ){ 2884 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a); 2885 }else{ 2886 zRet[i] = a; 2887 } 2888 } 2889 zRet[nVal] = '\0'; 2890 } 2891 return zRet; 2892 } 2893 #endif 2894 2895 #ifndef SQLITE_OMIT_SUBQUERY 2896 /* 2897 ** Load the Parse object passed as the first argument with an error 2898 ** message of the form: 2899 ** 2900 ** "sub-select returns N columns - expected M" 2901 */ 2902 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ 2903 if( pParse->nErr==0 ){ 2904 const char *zFmt = "sub-select returns %d columns - expected %d"; 2905 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); 2906 } 2907 } 2908 #endif 2909 2910 /* 2911 ** Expression pExpr is a vector that has been used in a context where 2912 ** it is not permitted. If pExpr is a sub-select vector, this routine 2913 ** loads the Parse object with a message of the form: 2914 ** 2915 ** "sub-select returns N columns - expected 1" 2916 ** 2917 ** Or, if it is a regular scalar vector: 2918 ** 2919 ** "row value misused" 2920 */ 2921 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){ 2922 #ifndef SQLITE_OMIT_SUBQUERY 2923 if( pExpr->flags & EP_xIsSelect ){ 2924 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1); 2925 }else 2926 #endif 2927 { 2928 sqlite3ErrorMsg(pParse, "row value misused"); 2929 } 2930 } 2931 2932 #ifndef SQLITE_OMIT_SUBQUERY 2933 /* 2934 ** Generate code that will construct an ephemeral table containing all terms 2935 ** in the RHS of an IN operator. The IN operator can be in either of two 2936 ** forms: 2937 ** 2938 ** x IN (4,5,11) -- IN operator with list on right-hand side 2939 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right 2940 ** 2941 ** The pExpr parameter is the IN operator. The cursor number for the 2942 ** constructed ephermeral table is returned. The first time the ephemeral 2943 ** table is computed, the cursor number is also stored in pExpr->iTable, 2944 ** however the cursor number returned might not be the same, as it might 2945 ** have been duplicated using OP_OpenDup. 2946 ** 2947 ** If the LHS expression ("x" in the examples) is a column value, or 2948 ** the SELECT statement returns a column value, then the affinity of that 2949 ** column is used to build the index keys. If both 'x' and the 2950 ** SELECT... statement are columns, then numeric affinity is used 2951 ** if either column has NUMERIC or INTEGER affinity. If neither 2952 ** 'x' nor the SELECT... statement are columns, then numeric affinity 2953 ** is used. 2954 */ 2955 void sqlite3CodeRhsOfIN( 2956 Parse *pParse, /* Parsing context */ 2957 Expr *pExpr, /* The IN operator */ 2958 int iTab /* Use this cursor number */ 2959 ){ 2960 int addrOnce = 0; /* Address of the OP_Once instruction at top */ 2961 int addr; /* Address of OP_OpenEphemeral instruction */ 2962 Expr *pLeft; /* the LHS of the IN operator */ 2963 KeyInfo *pKeyInfo = 0; /* Key information */ 2964 int nVal; /* Size of vector pLeft */ 2965 Vdbe *v; /* The prepared statement under construction */ 2966 2967 v = pParse->pVdbe; 2968 assert( v!=0 ); 2969 2970 /* The evaluation of the IN must be repeated every time it 2971 ** is encountered if any of the following is true: 2972 ** 2973 ** * The right-hand side is a correlated subquery 2974 ** * The right-hand side is an expression list containing variables 2975 ** * We are inside a trigger 2976 ** 2977 ** If all of the above are false, then we can compute the RHS just once 2978 ** and reuse it many names. 2979 */ 2980 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){ 2981 /* Reuse of the RHS is allowed */ 2982 /* If this routine has already been coded, but the previous code 2983 ** might not have been invoked yet, so invoke it now as a subroutine. 2984 */ 2985 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 2986 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 2987 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 2988 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d", 2989 pExpr->x.pSelect->selId)); 2990 } 2991 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 2992 pExpr->y.sub.iAddr); 2993 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable); 2994 sqlite3VdbeJumpHere(v, addrOnce); 2995 return; 2996 } 2997 2998 /* Begin coding the subroutine */ 2999 ExprSetProperty(pExpr, EP_Subrtn); 3000 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 3001 pExpr->y.sub.regReturn = ++pParse->nMem; 3002 pExpr->y.sub.iAddr = 3003 sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; 3004 VdbeComment((v, "return address")); 3005 3006 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 3007 } 3008 3009 /* Check to see if this is a vector IN operator */ 3010 pLeft = pExpr->pLeft; 3011 nVal = sqlite3ExprVectorSize(pLeft); 3012 3013 /* Construct the ephemeral table that will contain the content of 3014 ** RHS of the IN operator. 3015 */ 3016 pExpr->iTable = iTab; 3017 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal); 3018 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 3019 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 3020 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId)); 3021 }else{ 3022 VdbeComment((v, "RHS of IN operator")); 3023 } 3024 #endif 3025 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1); 3026 3027 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 3028 /* Case 1: expr IN (SELECT ...) 3029 ** 3030 ** Generate code to write the results of the select into the temporary 3031 ** table allocated and opened above. 3032 */ 3033 Select *pSelect = pExpr->x.pSelect; 3034 ExprList *pEList = pSelect->pEList; 3035 3036 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d", 3037 addrOnce?"":"CORRELATED ", pSelect->selId 3038 )); 3039 /* If the LHS and RHS of the IN operator do not match, that 3040 ** error will have been caught long before we reach this point. */ 3041 if( ALWAYS(pEList->nExpr==nVal) ){ 3042 Select *pCopy; 3043 SelectDest dest; 3044 int i; 3045 int rc; 3046 sqlite3SelectDestInit(&dest, SRT_Set, iTab); 3047 dest.zAffSdst = exprINAffinity(pParse, pExpr); 3048 pSelect->iLimit = 0; 3049 testcase( pSelect->selFlags & SF_Distinct ); 3050 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ 3051 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0); 3052 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest); 3053 sqlite3SelectDelete(pParse->db, pCopy); 3054 sqlite3DbFree(pParse->db, dest.zAffSdst); 3055 if( rc ){ 3056 sqlite3KeyInfoUnref(pKeyInfo); 3057 return; 3058 } 3059 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ 3060 assert( pEList!=0 ); 3061 assert( pEList->nExpr>0 ); 3062 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 3063 for(i=0; i<nVal; i++){ 3064 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i); 3065 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq( 3066 pParse, p, pEList->a[i].pExpr 3067 ); 3068 } 3069 } 3070 }else if( ALWAYS(pExpr->x.pList!=0) ){ 3071 /* Case 2: expr IN (exprlist) 3072 ** 3073 ** For each expression, build an index key from the evaluation and 3074 ** store it in the temporary table. If <expr> is a column, then use 3075 ** that columns affinity when building index keys. If <expr> is not 3076 ** a column, use numeric affinity. 3077 */ 3078 char affinity; /* Affinity of the LHS of the IN */ 3079 int i; 3080 ExprList *pList = pExpr->x.pList; 3081 struct ExprList_item *pItem; 3082 int r1, r2; 3083 affinity = sqlite3ExprAffinity(pLeft); 3084 if( affinity<=SQLITE_AFF_NONE ){ 3085 affinity = SQLITE_AFF_BLOB; 3086 }else if( affinity==SQLITE_AFF_REAL ){ 3087 affinity = SQLITE_AFF_NUMERIC; 3088 } 3089 if( pKeyInfo ){ 3090 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 3091 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 3092 } 3093 3094 /* Loop through each expression in <exprlist>. */ 3095 r1 = sqlite3GetTempReg(pParse); 3096 r2 = sqlite3GetTempReg(pParse); 3097 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ 3098 Expr *pE2 = pItem->pExpr; 3099 3100 /* If the expression is not constant then we will need to 3101 ** disable the test that was generated above that makes sure 3102 ** this code only executes once. Because for a non-constant 3103 ** expression we need to rerun this code each time. 3104 */ 3105 if( addrOnce && !sqlite3ExprIsConstant(pE2) ){ 3106 sqlite3VdbeChangeToNoop(v, addrOnce); 3107 ExprClearProperty(pExpr, EP_Subrtn); 3108 addrOnce = 0; 3109 } 3110 3111 /* Evaluate the expression and insert it into the temp table */ 3112 sqlite3ExprCode(pParse, pE2, r1); 3113 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1); 3114 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1); 3115 } 3116 sqlite3ReleaseTempReg(pParse, r1); 3117 sqlite3ReleaseTempReg(pParse, r2); 3118 } 3119 if( pKeyInfo ){ 3120 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); 3121 } 3122 if( addrOnce ){ 3123 sqlite3VdbeJumpHere(v, addrOnce); 3124 /* Subroutine return */ 3125 sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); 3126 sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1); 3127 sqlite3ClearTempRegCache(pParse); 3128 } 3129 } 3130 #endif /* SQLITE_OMIT_SUBQUERY */ 3131 3132 /* 3133 ** Generate code for scalar subqueries used as a subquery expression 3134 ** or EXISTS operator: 3135 ** 3136 ** (SELECT a FROM b) -- subquery 3137 ** EXISTS (SELECT a FROM b) -- EXISTS subquery 3138 ** 3139 ** The pExpr parameter is the SELECT or EXISTS operator to be coded. 3140 ** 3141 ** Return the register that holds the result. For a multi-column SELECT, 3142 ** the result is stored in a contiguous array of registers and the 3143 ** return value is the register of the left-most result column. 3144 ** Return 0 if an error occurs. 3145 */ 3146 #ifndef SQLITE_OMIT_SUBQUERY 3147 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ 3148 int addrOnce = 0; /* Address of OP_Once at top of subroutine */ 3149 int rReg = 0; /* Register storing resulting */ 3150 Select *pSel; /* SELECT statement to encode */ 3151 SelectDest dest; /* How to deal with SELECT result */ 3152 int nReg; /* Registers to allocate */ 3153 Expr *pLimit; /* New limit expression */ 3154 3155 Vdbe *v = pParse->pVdbe; 3156 assert( v!=0 ); 3157 if( pParse->nErr ) return 0; 3158 testcase( pExpr->op==TK_EXISTS ); 3159 testcase( pExpr->op==TK_SELECT ); 3160 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); 3161 assert( ExprHasProperty(pExpr, EP_xIsSelect) ); 3162 pSel = pExpr->x.pSelect; 3163 3164 /* If this routine has already been coded, then invoke it as a 3165 ** subroutine. */ 3166 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 3167 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId)); 3168 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 3169 pExpr->y.sub.iAddr); 3170 return pExpr->iTable; 3171 } 3172 3173 /* Begin coding the subroutine */ 3174 ExprSetProperty(pExpr, EP_Subrtn); 3175 pExpr->y.sub.regReturn = ++pParse->nMem; 3176 pExpr->y.sub.iAddr = 3177 sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1; 3178 VdbeComment((v, "return address")); 3179 3180 3181 /* The evaluation of the EXISTS/SELECT must be repeated every time it 3182 ** is encountered if any of the following is true: 3183 ** 3184 ** * The right-hand side is a correlated subquery 3185 ** * The right-hand side is an expression list containing variables 3186 ** * We are inside a trigger 3187 ** 3188 ** If all of the above are false, then we can run this code just once 3189 ** save the results, and reuse the same result on subsequent invocations. 3190 */ 3191 if( !ExprHasProperty(pExpr, EP_VarSelect) ){ 3192 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 3193 } 3194 3195 /* For a SELECT, generate code to put the values for all columns of 3196 ** the first row into an array of registers and return the index of 3197 ** the first register. 3198 ** 3199 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) 3200 ** into a register and return that register number. 3201 ** 3202 ** In both cases, the query is augmented with "LIMIT 1". Any 3203 ** preexisting limit is discarded in place of the new LIMIT 1. 3204 */ 3205 ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d", 3206 addrOnce?"":"CORRELATED ", pSel->selId)); 3207 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; 3208 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); 3209 pParse->nMem += nReg; 3210 if( pExpr->op==TK_SELECT ){ 3211 dest.eDest = SRT_Mem; 3212 dest.iSdst = dest.iSDParm; 3213 dest.nSdst = nReg; 3214 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); 3215 VdbeComment((v, "Init subquery result")); 3216 }else{ 3217 dest.eDest = SRT_Exists; 3218 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); 3219 VdbeComment((v, "Init EXISTS result")); 3220 } 3221 if( pSel->pLimit ){ 3222 /* The subquery already has a limit. If the pre-existing limit is X 3223 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */ 3224 sqlite3 *db = pParse->db; 3225 pLimit = sqlite3Expr(db, TK_INTEGER, "0"); 3226 if( pLimit ){ 3227 pLimit->affExpr = SQLITE_AFF_NUMERIC; 3228 pLimit = sqlite3PExpr(pParse, TK_NE, 3229 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit); 3230 } 3231 sqlite3ExprDelete(db, pSel->pLimit->pLeft); 3232 pSel->pLimit->pLeft = pLimit; 3233 }else{ 3234 /* If there is no pre-existing limit add a limit of 1 */ 3235 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1"); 3236 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0); 3237 } 3238 pSel->iLimit = 0; 3239 if( sqlite3Select(pParse, pSel, &dest) ){ 3240 if( pParse->nErr ){ 3241 pExpr->op2 = pExpr->op; 3242 pExpr->op = TK_ERROR; 3243 } 3244 return 0; 3245 } 3246 pExpr->iTable = rReg = dest.iSDParm; 3247 ExprSetVVAProperty(pExpr, EP_NoReduce); 3248 if( addrOnce ){ 3249 sqlite3VdbeJumpHere(v, addrOnce); 3250 } 3251 3252 /* Subroutine return */ 3253 sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn); 3254 sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1); 3255 sqlite3ClearTempRegCache(pParse); 3256 return rReg; 3257 } 3258 #endif /* SQLITE_OMIT_SUBQUERY */ 3259 3260 #ifndef SQLITE_OMIT_SUBQUERY 3261 /* 3262 ** Expr pIn is an IN(...) expression. This function checks that the 3263 ** sub-select on the RHS of the IN() operator has the same number of 3264 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not 3265 ** a sub-query, that the LHS is a vector of size 1. 3266 */ 3267 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ 3268 int nVector = sqlite3ExprVectorSize(pIn->pLeft); 3269 if( (pIn->flags & EP_xIsSelect)!=0 && !pParse->db->mallocFailed ){ 3270 if( nVector!=pIn->x.pSelect->pEList->nExpr ){ 3271 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); 3272 return 1; 3273 } 3274 }else if( nVector!=1 ){ 3275 sqlite3VectorErrorMsg(pParse, pIn->pLeft); 3276 return 1; 3277 } 3278 return 0; 3279 } 3280 #endif 3281 3282 #ifndef SQLITE_OMIT_SUBQUERY 3283 /* 3284 ** Generate code for an IN expression. 3285 ** 3286 ** x IN (SELECT ...) 3287 ** x IN (value, value, ...) 3288 ** 3289 ** The left-hand side (LHS) is a scalar or vector expression. The 3290 ** right-hand side (RHS) is an array of zero or more scalar values, or a 3291 ** subquery. If the RHS is a subquery, the number of result columns must 3292 ** match the number of columns in the vector on the LHS. If the RHS is 3293 ** a list of values, the LHS must be a scalar. 3294 ** 3295 ** The IN operator is true if the LHS value is contained within the RHS. 3296 ** The result is false if the LHS is definitely not in the RHS. The 3297 ** result is NULL if the presence of the LHS in the RHS cannot be 3298 ** determined due to NULLs. 3299 ** 3300 ** This routine generates code that jumps to destIfFalse if the LHS is not 3301 ** contained within the RHS. If due to NULLs we cannot determine if the LHS 3302 ** is contained in the RHS then jump to destIfNull. If the LHS is contained 3303 ** within the RHS then fall through. 3304 ** 3305 ** See the separate in-operator.md documentation file in the canonical 3306 ** SQLite source tree for additional information. 3307 */ 3308 static void sqlite3ExprCodeIN( 3309 Parse *pParse, /* Parsing and code generating context */ 3310 Expr *pExpr, /* The IN expression */ 3311 int destIfFalse, /* Jump here if LHS is not contained in the RHS */ 3312 int destIfNull /* Jump here if the results are unknown due to NULLs */ 3313 ){ 3314 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ 3315 int eType; /* Type of the RHS */ 3316 int rLhs; /* Register(s) holding the LHS values */ 3317 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */ 3318 Vdbe *v; /* Statement under construction */ 3319 int *aiMap = 0; /* Map from vector field to index column */ 3320 char *zAff = 0; /* Affinity string for comparisons */ 3321 int nVector; /* Size of vectors for this IN operator */ 3322 int iDummy; /* Dummy parameter to exprCodeVector() */ 3323 Expr *pLeft; /* The LHS of the IN operator */ 3324 int i; /* loop counter */ 3325 int destStep2; /* Where to jump when NULLs seen in step 2 */ 3326 int destStep6 = 0; /* Start of code for Step 6 */ 3327 int addrTruthOp; /* Address of opcode that determines the IN is true */ 3328 int destNotNull; /* Jump here if a comparison is not true in step 6 */ 3329 int addrTop; /* Top of the step-6 loop */ 3330 int iTab = 0; /* Index to use */ 3331 u8 okConstFactor = pParse->okConstFactor; 3332 3333 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 3334 pLeft = pExpr->pLeft; 3335 if( sqlite3ExprCheckIN(pParse, pExpr) ) return; 3336 zAff = exprINAffinity(pParse, pExpr); 3337 nVector = sqlite3ExprVectorSize(pExpr->pLeft); 3338 aiMap = (int*)sqlite3DbMallocZero( 3339 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1 3340 ); 3341 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; 3342 3343 /* Attempt to compute the RHS. After this step, if anything other than 3344 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab 3345 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, 3346 ** the RHS has not yet been coded. */ 3347 v = pParse->pVdbe; 3348 assert( v!=0 ); /* OOM detected prior to this routine */ 3349 VdbeNoopComment((v, "begin IN expr")); 3350 eType = sqlite3FindInIndex(pParse, pExpr, 3351 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, 3352 destIfFalse==destIfNull ? 0 : &rRhsHasNull, 3353 aiMap, &iTab); 3354 3355 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH 3356 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 3357 ); 3358 #ifdef SQLITE_DEBUG 3359 /* Confirm that aiMap[] contains nVector integer values between 0 and 3360 ** nVector-1. */ 3361 for(i=0; i<nVector; i++){ 3362 int j, cnt; 3363 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++; 3364 assert( cnt==1 ); 3365 } 3366 #endif 3367 3368 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a 3369 ** vector, then it is stored in an array of nVector registers starting 3370 ** at r1. 3371 ** 3372 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector 3373 ** so that the fields are in the same order as an existing index. The 3374 ** aiMap[] array contains a mapping from the original LHS field order to 3375 ** the field order that matches the RHS index. 3376 ** 3377 ** Avoid factoring the LHS of the IN(...) expression out of the loop, 3378 ** even if it is constant, as OP_Affinity may be used on the register 3379 ** by code generated below. */ 3380 assert( pParse->okConstFactor==okConstFactor ); 3381 pParse->okConstFactor = 0; 3382 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); 3383 pParse->okConstFactor = okConstFactor; 3384 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */ 3385 if( i==nVector ){ 3386 /* LHS fields are not reordered */ 3387 rLhs = rLhsOrig; 3388 }else{ 3389 /* Need to reorder the LHS fields according to aiMap */ 3390 rLhs = sqlite3GetTempRange(pParse, nVector); 3391 for(i=0; i<nVector; i++){ 3392 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); 3393 } 3394 } 3395 3396 /* If sqlite3FindInIndex() did not find or create an index that is 3397 ** suitable for evaluating the IN operator, then evaluate using a 3398 ** sequence of comparisons. 3399 ** 3400 ** This is step (1) in the in-operator.md optimized algorithm. 3401 */ 3402 if( eType==IN_INDEX_NOOP ){ 3403 ExprList *pList = pExpr->x.pList; 3404 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 3405 int labelOk = sqlite3VdbeMakeLabel(pParse); 3406 int r2, regToFree; 3407 int regCkNull = 0; 3408 int ii; 3409 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 3410 if( destIfNull!=destIfFalse ){ 3411 regCkNull = sqlite3GetTempReg(pParse); 3412 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); 3413 } 3414 for(ii=0; ii<pList->nExpr; ii++){ 3415 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); 3416 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ 3417 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); 3418 } 3419 sqlite3ReleaseTempReg(pParse, regToFree); 3420 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){ 3421 int op = rLhs!=r2 ? OP_Eq : OP_NotNull; 3422 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2, 3423 (void*)pColl, P4_COLLSEQ); 3424 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq); 3425 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq); 3426 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull); 3427 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull); 3428 sqlite3VdbeChangeP5(v, zAff[0]); 3429 }else{ 3430 int op = rLhs!=r2 ? OP_Ne : OP_IsNull; 3431 assert( destIfNull==destIfFalse ); 3432 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2, 3433 (void*)pColl, P4_COLLSEQ); 3434 VdbeCoverageIf(v, op==OP_Ne); 3435 VdbeCoverageIf(v, op==OP_IsNull); 3436 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); 3437 } 3438 } 3439 if( regCkNull ){ 3440 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); 3441 sqlite3VdbeGoto(v, destIfFalse); 3442 } 3443 sqlite3VdbeResolveLabel(v, labelOk); 3444 sqlite3ReleaseTempReg(pParse, regCkNull); 3445 goto sqlite3ExprCodeIN_finished; 3446 } 3447 3448 /* Step 2: Check to see if the LHS contains any NULL columns. If the 3449 ** LHS does contain NULLs then the result must be either FALSE or NULL. 3450 ** We will then skip the binary search of the RHS. 3451 */ 3452 if( destIfNull==destIfFalse ){ 3453 destStep2 = destIfFalse; 3454 }else{ 3455 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse); 3456 } 3457 if( pParse->nErr ) goto sqlite3ExprCodeIN_finished; 3458 for(i=0; i<nVector; i++){ 3459 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i); 3460 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; 3461 if( sqlite3ExprCanBeNull(p) ){ 3462 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); 3463 VdbeCoverage(v); 3464 } 3465 } 3466 3467 /* Step 3. The LHS is now known to be non-NULL. Do the binary search 3468 ** of the RHS using the LHS as a probe. If found, the result is 3469 ** true. 3470 */ 3471 if( eType==IN_INDEX_ROWID ){ 3472 /* In this case, the RHS is the ROWID of table b-tree and so we also 3473 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 3474 ** into a single opcode. */ 3475 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs); 3476 VdbeCoverage(v); 3477 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ 3478 }else{ 3479 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); 3480 if( destIfFalse==destIfNull ){ 3481 /* Combine Step 3 and Step 5 into a single opcode */ 3482 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse, 3483 rLhs, nVector); VdbeCoverage(v); 3484 goto sqlite3ExprCodeIN_finished; 3485 } 3486 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ 3487 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0, 3488 rLhs, nVector); VdbeCoverage(v); 3489 } 3490 3491 /* Step 4. If the RHS is known to be non-NULL and we did not find 3492 ** an match on the search above, then the result must be FALSE. 3493 */ 3494 if( rRhsHasNull && nVector==1 ){ 3495 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); 3496 VdbeCoverage(v); 3497 } 3498 3499 /* Step 5. If we do not care about the difference between NULL and 3500 ** FALSE, then just return false. 3501 */ 3502 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); 3503 3504 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. 3505 ** If any comparison is NULL, then the result is NULL. If all 3506 ** comparisons are FALSE then the final result is FALSE. 3507 ** 3508 ** For a scalar LHS, it is sufficient to check just the first row 3509 ** of the RHS. 3510 */ 3511 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); 3512 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); 3513 VdbeCoverage(v); 3514 if( nVector>1 ){ 3515 destNotNull = sqlite3VdbeMakeLabel(pParse); 3516 }else{ 3517 /* For nVector==1, combine steps 6 and 7 by immediately returning 3518 ** FALSE if the first comparison is not NULL */ 3519 destNotNull = destIfFalse; 3520 } 3521 for(i=0; i<nVector; i++){ 3522 Expr *p; 3523 CollSeq *pColl; 3524 int r3 = sqlite3GetTempReg(pParse); 3525 p = sqlite3VectorFieldSubexpr(pLeft, i); 3526 pColl = sqlite3ExprCollSeq(pParse, p); 3527 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3); 3528 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, 3529 (void*)pColl, P4_COLLSEQ); 3530 VdbeCoverage(v); 3531 sqlite3ReleaseTempReg(pParse, r3); 3532 } 3533 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); 3534 if( nVector>1 ){ 3535 sqlite3VdbeResolveLabel(v, destNotNull); 3536 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1); 3537 VdbeCoverage(v); 3538 3539 /* Step 7: If we reach this point, we know that the result must 3540 ** be false. */ 3541 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); 3542 } 3543 3544 /* Jumps here in order to return true. */ 3545 sqlite3VdbeJumpHere(v, addrTruthOp); 3546 3547 sqlite3ExprCodeIN_finished: 3548 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); 3549 VdbeComment((v, "end IN expr")); 3550 sqlite3ExprCodeIN_oom_error: 3551 sqlite3DbFree(pParse->db, aiMap); 3552 sqlite3DbFree(pParse->db, zAff); 3553 } 3554 #endif /* SQLITE_OMIT_SUBQUERY */ 3555 3556 #ifndef SQLITE_OMIT_FLOATING_POINT 3557 /* 3558 ** Generate an instruction that will put the floating point 3559 ** value described by z[0..n-1] into register iMem. 3560 ** 3561 ** The z[] string will probably not be zero-terminated. But the 3562 ** z[n] character is guaranteed to be something that does not look 3563 ** like the continuation of the number. 3564 */ 3565 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ 3566 if( ALWAYS(z!=0) ){ 3567 double value; 3568 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); 3569 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ 3570 if( negateFlag ) value = -value; 3571 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); 3572 } 3573 } 3574 #endif 3575 3576 3577 /* 3578 ** Generate an instruction that will put the integer describe by 3579 ** text z[0..n-1] into register iMem. 3580 ** 3581 ** Expr.u.zToken is always UTF8 and zero-terminated. 3582 */ 3583 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ 3584 Vdbe *v = pParse->pVdbe; 3585 if( pExpr->flags & EP_IntValue ){ 3586 int i = pExpr->u.iValue; 3587 assert( i>=0 ); 3588 if( negFlag ) i = -i; 3589 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); 3590 }else{ 3591 int c; 3592 i64 value; 3593 const char *z = pExpr->u.zToken; 3594 assert( z!=0 ); 3595 c = sqlite3DecOrHexToI64(z, &value); 3596 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){ 3597 #ifdef SQLITE_OMIT_FLOATING_POINT 3598 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z); 3599 #else 3600 #ifndef SQLITE_OMIT_HEX_INTEGER 3601 if( sqlite3_strnicmp(z,"0x",2)==0 ){ 3602 sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z); 3603 }else 3604 #endif 3605 { 3606 codeReal(v, z, negFlag, iMem); 3607 } 3608 #endif 3609 }else{ 3610 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; } 3611 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); 3612 } 3613 } 3614 } 3615 3616 3617 /* Generate code that will load into register regOut a value that is 3618 ** appropriate for the iIdxCol-th column of index pIdx. 3619 */ 3620 void sqlite3ExprCodeLoadIndexColumn( 3621 Parse *pParse, /* The parsing context */ 3622 Index *pIdx, /* The index whose column is to be loaded */ 3623 int iTabCur, /* Cursor pointing to a table row */ 3624 int iIdxCol, /* The column of the index to be loaded */ 3625 int regOut /* Store the index column value in this register */ 3626 ){ 3627 i16 iTabCol = pIdx->aiColumn[iIdxCol]; 3628 if( iTabCol==XN_EXPR ){ 3629 assert( pIdx->aColExpr ); 3630 assert( pIdx->aColExpr->nExpr>iIdxCol ); 3631 pParse->iSelfTab = iTabCur + 1; 3632 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); 3633 pParse->iSelfTab = 0; 3634 }else{ 3635 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, 3636 iTabCol, regOut); 3637 } 3638 } 3639 3640 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 3641 /* 3642 ** Generate code that will compute the value of generated column pCol 3643 ** and store the result in register regOut 3644 */ 3645 void sqlite3ExprCodeGeneratedColumn( 3646 Parse *pParse, 3647 Column *pCol, 3648 int regOut 3649 ){ 3650 int iAddr; 3651 Vdbe *v = pParse->pVdbe; 3652 assert( v!=0 ); 3653 assert( pParse->iSelfTab!=0 ); 3654 if( pParse->iSelfTab>0 ){ 3655 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut); 3656 }else{ 3657 iAddr = 0; 3658 } 3659 sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut); 3660 if( pCol->affinity>=SQLITE_AFF_TEXT ){ 3661 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1); 3662 } 3663 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr); 3664 } 3665 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 3666 3667 /* 3668 ** Generate code to extract the value of the iCol-th column of a table. 3669 */ 3670 void sqlite3ExprCodeGetColumnOfTable( 3671 Vdbe *v, /* Parsing context */ 3672 Table *pTab, /* The table containing the value */ 3673 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ 3674 int iCol, /* Index of the column to extract */ 3675 int regOut /* Extract the value into this register */ 3676 ){ 3677 Column *pCol; 3678 assert( v!=0 ); 3679 if( pTab==0 ){ 3680 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut); 3681 return; 3682 } 3683 if( iCol<0 || iCol==pTab->iPKey ){ 3684 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); 3685 }else{ 3686 int op; 3687 int x; 3688 if( IsVirtual(pTab) ){ 3689 op = OP_VColumn; 3690 x = iCol; 3691 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 3692 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){ 3693 Parse *pParse = sqlite3VdbeParser(v); 3694 if( pCol->colFlags & COLFLAG_BUSY ){ 3695 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName); 3696 }else{ 3697 int savedSelfTab = pParse->iSelfTab; 3698 pCol->colFlags |= COLFLAG_BUSY; 3699 pParse->iSelfTab = iTabCur+1; 3700 sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut); 3701 pParse->iSelfTab = savedSelfTab; 3702 pCol->colFlags &= ~COLFLAG_BUSY; 3703 } 3704 return; 3705 #endif 3706 }else if( !HasRowid(pTab) ){ 3707 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) ); 3708 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol); 3709 op = OP_Column; 3710 }else{ 3711 x = sqlite3TableColumnToStorage(pTab,iCol); 3712 testcase( x!=iCol ); 3713 op = OP_Column; 3714 } 3715 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); 3716 sqlite3ColumnDefault(v, pTab, iCol, regOut); 3717 } 3718 } 3719 3720 /* 3721 ** Generate code that will extract the iColumn-th column from 3722 ** table pTab and store the column value in register iReg. 3723 ** 3724 ** There must be an open cursor to pTab in iTable when this routine 3725 ** is called. If iColumn<0 then code is generated that extracts the rowid. 3726 */ 3727 int sqlite3ExprCodeGetColumn( 3728 Parse *pParse, /* Parsing and code generating context */ 3729 Table *pTab, /* Description of the table we are reading from */ 3730 int iColumn, /* Index of the table column */ 3731 int iTable, /* The cursor pointing to the table */ 3732 int iReg, /* Store results here */ 3733 u8 p5 /* P5 value for OP_Column + FLAGS */ 3734 ){ 3735 assert( pParse->pVdbe!=0 ); 3736 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg); 3737 if( p5 ){ 3738 VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1); 3739 if( pOp->opcode==OP_Column ) pOp->p5 = p5; 3740 } 3741 return iReg; 3742 } 3743 3744 /* 3745 ** Generate code to move content from registers iFrom...iFrom+nReg-1 3746 ** over to iTo..iTo+nReg-1. 3747 */ 3748 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ 3749 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); 3750 } 3751 3752 /* 3753 ** Convert a scalar expression node to a TK_REGISTER referencing 3754 ** register iReg. The caller must ensure that iReg already contains 3755 ** the correct value for the expression. 3756 */ 3757 static void exprToRegister(Expr *pExpr, int iReg){ 3758 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr); 3759 if( NEVER(p==0) ) return; 3760 p->op2 = p->op; 3761 p->op = TK_REGISTER; 3762 p->iTable = iReg; 3763 ExprClearProperty(p, EP_Skip); 3764 } 3765 3766 /* 3767 ** Evaluate an expression (either a vector or a scalar expression) and store 3768 ** the result in continguous temporary registers. Return the index of 3769 ** the first register used to store the result. 3770 ** 3771 ** If the returned result register is a temporary scalar, then also write 3772 ** that register number into *piFreeable. If the returned result register 3773 ** is not a temporary or if the expression is a vector set *piFreeable 3774 ** to 0. 3775 */ 3776 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ 3777 int iResult; 3778 int nResult = sqlite3ExprVectorSize(p); 3779 if( nResult==1 ){ 3780 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); 3781 }else{ 3782 *piFreeable = 0; 3783 if( p->op==TK_SELECT ){ 3784 #if SQLITE_OMIT_SUBQUERY 3785 iResult = 0; 3786 #else 3787 iResult = sqlite3CodeSubselect(pParse, p); 3788 #endif 3789 }else{ 3790 int i; 3791 iResult = pParse->nMem+1; 3792 pParse->nMem += nResult; 3793 for(i=0; i<nResult; i++){ 3794 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult); 3795 } 3796 } 3797 } 3798 return iResult; 3799 } 3800 3801 /* 3802 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5) 3803 ** so that a subsequent copy will not be merged into this one. 3804 */ 3805 static void setDoNotMergeFlagOnCopy(Vdbe *v){ 3806 if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){ 3807 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergable */ 3808 } 3809 } 3810 3811 /* 3812 ** Generate code to implement special SQL functions that are implemented 3813 ** in-line rather than by using the usual callbacks. 3814 */ 3815 static int exprCodeInlineFunction( 3816 Parse *pParse, /* Parsing context */ 3817 ExprList *pFarg, /* List of function arguments */ 3818 int iFuncId, /* Function ID. One of the INTFUNC_... values */ 3819 int target /* Store function result in this register */ 3820 ){ 3821 int nFarg; 3822 Vdbe *v = pParse->pVdbe; 3823 assert( v!=0 ); 3824 assert( pFarg!=0 ); 3825 nFarg = pFarg->nExpr; 3826 assert( nFarg>0 ); /* All in-line functions have at least one argument */ 3827 switch( iFuncId ){ 3828 case INLINEFUNC_coalesce: { 3829 /* Attempt a direct implementation of the built-in COALESCE() and 3830 ** IFNULL() functions. This avoids unnecessary evaluation of 3831 ** arguments past the first non-NULL argument. 3832 */ 3833 int endCoalesce = sqlite3VdbeMakeLabel(pParse); 3834 int i; 3835 assert( nFarg>=2 ); 3836 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); 3837 for(i=1; i<nFarg; i++){ 3838 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce); 3839 VdbeCoverage(v); 3840 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target); 3841 } 3842 setDoNotMergeFlagOnCopy(v); 3843 sqlite3VdbeResolveLabel(v, endCoalesce); 3844 break; 3845 } 3846 case INLINEFUNC_iif: { 3847 Expr caseExpr; 3848 memset(&caseExpr, 0, sizeof(caseExpr)); 3849 caseExpr.op = TK_CASE; 3850 caseExpr.x.pList = pFarg; 3851 return sqlite3ExprCodeTarget(pParse, &caseExpr, target); 3852 } 3853 3854 default: { 3855 /* The UNLIKELY() function is a no-op. The result is the value 3856 ** of the first argument. 3857 */ 3858 assert( nFarg==1 || nFarg==2 ); 3859 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); 3860 break; 3861 } 3862 3863 /*********************************************************************** 3864 ** Test-only SQL functions that are only usable if enabled 3865 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 3866 */ 3867 case INLINEFUNC_expr_compare: { 3868 /* Compare two expressions using sqlite3ExprCompare() */ 3869 assert( nFarg==2 ); 3870 sqlite3VdbeAddOp2(v, OP_Integer, 3871 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), 3872 target); 3873 break; 3874 } 3875 3876 case INLINEFUNC_expr_implies_expr: { 3877 /* Compare two expressions using sqlite3ExprImpliesExpr() */ 3878 assert( nFarg==2 ); 3879 sqlite3VdbeAddOp2(v, OP_Integer, 3880 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), 3881 target); 3882 break; 3883 } 3884 3885 case INLINEFUNC_implies_nonnull_row: { 3886 /* REsult of sqlite3ExprImpliesNonNullRow() */ 3887 Expr *pA1; 3888 assert( nFarg==2 ); 3889 pA1 = pFarg->a[1].pExpr; 3890 if( pA1->op==TK_COLUMN ){ 3891 sqlite3VdbeAddOp2(v, OP_Integer, 3892 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable), 3893 target); 3894 }else{ 3895 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 3896 } 3897 break; 3898 } 3899 3900 #ifdef SQLITE_DEBUG 3901 case INLINEFUNC_affinity: { 3902 /* The AFFINITY() function evaluates to a string that describes 3903 ** the type affinity of the argument. This is used for testing of 3904 ** the SQLite type logic. 3905 */ 3906 const char *azAff[] = { "blob", "text", "numeric", "integer", "real" }; 3907 char aff; 3908 assert( nFarg==1 ); 3909 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr); 3910 sqlite3VdbeLoadString(v, target, 3911 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]); 3912 break; 3913 } 3914 #endif 3915 } 3916 return target; 3917 } 3918 3919 3920 /* 3921 ** Generate code into the current Vdbe to evaluate the given 3922 ** expression. Attempt to store the results in register "target". 3923 ** Return the register where results are stored. 3924 ** 3925 ** With this routine, there is no guarantee that results will 3926 ** be stored in target. The result might be stored in some other 3927 ** register if it is convenient to do so. The calling function 3928 ** must check the return code and move the results to the desired 3929 ** register. 3930 */ 3931 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ 3932 Vdbe *v = pParse->pVdbe; /* The VM under construction */ 3933 int op; /* The opcode being coded */ 3934 int inReg = target; /* Results stored in register inReg */ 3935 int regFree1 = 0; /* If non-zero free this temporary register */ 3936 int regFree2 = 0; /* If non-zero free this temporary register */ 3937 int r1, r2; /* Various register numbers */ 3938 Expr tempX; /* Temporary expression node */ 3939 int p5 = 0; 3940 3941 assert( target>0 && target<=pParse->nMem ); 3942 assert( v!=0 ); 3943 3944 expr_code_doover: 3945 if( pExpr==0 ){ 3946 op = TK_NULL; 3947 }else{ 3948 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 3949 op = pExpr->op; 3950 } 3951 switch( op ){ 3952 case TK_AGG_COLUMN: { 3953 AggInfo *pAggInfo = pExpr->pAggInfo; 3954 struct AggInfo_col *pCol; 3955 assert( pAggInfo!=0 ); 3956 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn ); 3957 pCol = &pAggInfo->aCol[pExpr->iAgg]; 3958 if( !pAggInfo->directMode ){ 3959 assert( pCol->iMem>0 ); 3960 return pCol->iMem; 3961 }else if( pAggInfo->useSortingIdx ){ 3962 Table *pTab = pCol->pTab; 3963 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, 3964 pCol->iSorterColumn, target); 3965 if( pCol->iColumn<0 ){ 3966 VdbeComment((v,"%s.rowid",pTab->zName)); 3967 }else{ 3968 VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName)); 3969 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){ 3970 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 3971 } 3972 } 3973 return target; 3974 } 3975 /* Otherwise, fall thru into the TK_COLUMN case */ 3976 /* no break */ deliberate_fall_through 3977 } 3978 case TK_COLUMN: { 3979 int iTab = pExpr->iTable; 3980 int iReg; 3981 if( ExprHasProperty(pExpr, EP_FixedCol) ){ 3982 /* This COLUMN expression is really a constant due to WHERE clause 3983 ** constraints, and that constant is coded by the pExpr->pLeft 3984 ** expresssion. However, make sure the constant has the correct 3985 ** datatype by applying the Affinity of the table column to the 3986 ** constant. 3987 */ 3988 int aff; 3989 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target); 3990 if( pExpr->y.pTab ){ 3991 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 3992 }else{ 3993 aff = pExpr->affExpr; 3994 } 3995 if( aff>SQLITE_AFF_BLOB ){ 3996 static const char zAff[] = "B\000C\000D\000E"; 3997 assert( SQLITE_AFF_BLOB=='A' ); 3998 assert( SQLITE_AFF_TEXT=='B' ); 3999 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0, 4000 &zAff[(aff-'B')*2], P4_STATIC); 4001 } 4002 return iReg; 4003 } 4004 if( iTab<0 ){ 4005 if( pParse->iSelfTab<0 ){ 4006 /* Other columns in the same row for CHECK constraints or 4007 ** generated columns or for inserting into partial index. 4008 ** The row is unpacked into registers beginning at 4009 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register 4010 ** immediately prior to the first column. 4011 */ 4012 Column *pCol; 4013 Table *pTab = pExpr->y.pTab; 4014 int iSrc; 4015 int iCol = pExpr->iColumn; 4016 assert( pTab!=0 ); 4017 assert( iCol>=XN_ROWID ); 4018 assert( iCol<pTab->nCol ); 4019 if( iCol<0 ){ 4020 return -1-pParse->iSelfTab; 4021 } 4022 pCol = pTab->aCol + iCol; 4023 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) ); 4024 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab; 4025 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 4026 if( pCol->colFlags & COLFLAG_GENERATED ){ 4027 if( pCol->colFlags & COLFLAG_BUSY ){ 4028 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", 4029 pCol->zName); 4030 return 0; 4031 } 4032 pCol->colFlags |= COLFLAG_BUSY; 4033 if( pCol->colFlags & COLFLAG_NOTAVAIL ){ 4034 sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc); 4035 } 4036 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL); 4037 return iSrc; 4038 }else 4039 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 4040 if( pCol->affinity==SQLITE_AFF_REAL ){ 4041 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target); 4042 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 4043 return target; 4044 }else{ 4045 return iSrc; 4046 } 4047 }else{ 4048 /* Coding an expression that is part of an index where column names 4049 ** in the index refer to the table to which the index belongs */ 4050 iTab = pParse->iSelfTab - 1; 4051 } 4052 } 4053 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab, 4054 pExpr->iColumn, iTab, target, 4055 pExpr->op2); 4056 if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){ 4057 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); 4058 } 4059 return iReg; 4060 } 4061 case TK_INTEGER: { 4062 codeInteger(pParse, pExpr, 0, target); 4063 return target; 4064 } 4065 case TK_TRUEFALSE: { 4066 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target); 4067 return target; 4068 } 4069 #ifndef SQLITE_OMIT_FLOATING_POINT 4070 case TK_FLOAT: { 4071 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4072 codeReal(v, pExpr->u.zToken, 0, target); 4073 return target; 4074 } 4075 #endif 4076 case TK_STRING: { 4077 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4078 sqlite3VdbeLoadString(v, target, pExpr->u.zToken); 4079 return target; 4080 } 4081 default: { 4082 /* Make NULL the default case so that if a bug causes an illegal 4083 ** Expr node to be passed into this function, it will be handled 4084 ** sanely and not crash. But keep the assert() to bring the problem 4085 ** to the attention of the developers. */ 4086 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed ); 4087 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 4088 return target; 4089 } 4090 #ifndef SQLITE_OMIT_BLOB_LITERAL 4091 case TK_BLOB: { 4092 int n; 4093 const char *z; 4094 char *zBlob; 4095 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4096 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); 4097 assert( pExpr->u.zToken[1]=='\'' ); 4098 z = &pExpr->u.zToken[2]; 4099 n = sqlite3Strlen30(z) - 1; 4100 assert( z[n]=='\'' ); 4101 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); 4102 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); 4103 return target; 4104 } 4105 #endif 4106 case TK_VARIABLE: { 4107 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4108 assert( pExpr->u.zToken!=0 ); 4109 assert( pExpr->u.zToken[0]!=0 ); 4110 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); 4111 if( pExpr->u.zToken[1]!=0 ){ 4112 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn); 4113 assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) ); 4114 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */ 4115 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC); 4116 } 4117 return target; 4118 } 4119 case TK_REGISTER: { 4120 return pExpr->iTable; 4121 } 4122 #ifndef SQLITE_OMIT_CAST 4123 case TK_CAST: { 4124 /* Expressions of the form: CAST(pLeft AS token) */ 4125 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); 4126 if( inReg!=target ){ 4127 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target); 4128 inReg = target; 4129 } 4130 sqlite3VdbeAddOp2(v, OP_Cast, target, 4131 sqlite3AffinityType(pExpr->u.zToken, 0)); 4132 return inReg; 4133 } 4134 #endif /* SQLITE_OMIT_CAST */ 4135 case TK_IS: 4136 case TK_ISNOT: 4137 op = (op==TK_IS) ? TK_EQ : TK_NE; 4138 p5 = SQLITE_NULLEQ; 4139 /* fall-through */ 4140 case TK_LT: 4141 case TK_LE: 4142 case TK_GT: 4143 case TK_GE: 4144 case TK_NE: 4145 case TK_EQ: { 4146 Expr *pLeft = pExpr->pLeft; 4147 if( sqlite3ExprIsVector(pLeft) ){ 4148 codeVectorCompare(pParse, pExpr, target, op, p5); 4149 }else{ 4150 r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); 4151 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 4152 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg); 4153 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2, 4154 sqlite3VdbeCurrentAddr(v)+2, p5, 4155 ExprHasProperty(pExpr,EP_Commuted)); 4156 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 4157 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 4158 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 4159 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 4160 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); 4161 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); 4162 if( p5==SQLITE_NULLEQ ){ 4163 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg); 4164 }else{ 4165 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2); 4166 } 4167 testcase( regFree1==0 ); 4168 testcase( regFree2==0 ); 4169 } 4170 break; 4171 } 4172 case TK_AND: 4173 case TK_OR: 4174 case TK_PLUS: 4175 case TK_STAR: 4176 case TK_MINUS: 4177 case TK_REM: 4178 case TK_BITAND: 4179 case TK_BITOR: 4180 case TK_SLASH: 4181 case TK_LSHIFT: 4182 case TK_RSHIFT: 4183 case TK_CONCAT: { 4184 assert( TK_AND==OP_And ); testcase( op==TK_AND ); 4185 assert( TK_OR==OP_Or ); testcase( op==TK_OR ); 4186 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); 4187 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); 4188 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); 4189 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND ); 4190 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR ); 4191 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH ); 4192 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); 4193 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); 4194 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); 4195 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4196 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 4197 sqlite3VdbeAddOp3(v, op, r2, r1, target); 4198 testcase( regFree1==0 ); 4199 testcase( regFree2==0 ); 4200 break; 4201 } 4202 case TK_UMINUS: { 4203 Expr *pLeft = pExpr->pLeft; 4204 assert( pLeft ); 4205 if( pLeft->op==TK_INTEGER ){ 4206 codeInteger(pParse, pLeft, 1, target); 4207 return target; 4208 #ifndef SQLITE_OMIT_FLOATING_POINT 4209 }else if( pLeft->op==TK_FLOAT ){ 4210 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4211 codeReal(v, pLeft->u.zToken, 1, target); 4212 return target; 4213 #endif 4214 }else{ 4215 tempX.op = TK_INTEGER; 4216 tempX.flags = EP_IntValue|EP_TokenOnly; 4217 tempX.u.iValue = 0; 4218 ExprClearVVAProperties(&tempX); 4219 r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1); 4220 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); 4221 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); 4222 testcase( regFree2==0 ); 4223 } 4224 break; 4225 } 4226 case TK_BITNOT: 4227 case TK_NOT: { 4228 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); 4229 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); 4230 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4231 testcase( regFree1==0 ); 4232 sqlite3VdbeAddOp2(v, op, r1, inReg); 4233 break; 4234 } 4235 case TK_TRUTH: { 4236 int isTrue; /* IS TRUE or IS NOT TRUE */ 4237 int bNormal; /* IS TRUE or IS FALSE */ 4238 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4239 testcase( regFree1==0 ); 4240 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 4241 bNormal = pExpr->op2==TK_IS; 4242 testcase( isTrue && bNormal); 4243 testcase( !isTrue && bNormal); 4244 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal); 4245 break; 4246 } 4247 case TK_ISNULL: 4248 case TK_NOTNULL: { 4249 int addr; 4250 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 4251 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 4252 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 4253 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 4254 testcase( regFree1==0 ); 4255 addr = sqlite3VdbeAddOp1(v, op, r1); 4256 VdbeCoverageIf(v, op==TK_ISNULL); 4257 VdbeCoverageIf(v, op==TK_NOTNULL); 4258 sqlite3VdbeAddOp2(v, OP_Integer, 0, target); 4259 sqlite3VdbeJumpHere(v, addr); 4260 break; 4261 } 4262 case TK_AGG_FUNCTION: { 4263 AggInfo *pInfo = pExpr->pAggInfo; 4264 if( pInfo==0 4265 || NEVER(pExpr->iAgg<0) 4266 || NEVER(pExpr->iAgg>=pInfo->nFunc) 4267 ){ 4268 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4269 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken); 4270 }else{ 4271 return pInfo->aFunc[pExpr->iAgg].iMem; 4272 } 4273 break; 4274 } 4275 case TK_FUNCTION: { 4276 ExprList *pFarg; /* List of function arguments */ 4277 int nFarg; /* Number of function arguments */ 4278 FuncDef *pDef; /* The function definition object */ 4279 const char *zId; /* The function name */ 4280 u32 constMask = 0; /* Mask of function arguments that are constant */ 4281 int i; /* Loop counter */ 4282 sqlite3 *db = pParse->db; /* The database connection */ 4283 u8 enc = ENC(db); /* The text encoding used by this database */ 4284 CollSeq *pColl = 0; /* A collating sequence */ 4285 4286 #ifndef SQLITE_OMIT_WINDOWFUNC 4287 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 4288 return pExpr->y.pWin->regResult; 4289 } 4290 #endif 4291 4292 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){ 4293 /* SQL functions can be expensive. So try to avoid running them 4294 ** multiple times if we know they always give the same result */ 4295 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); 4296 } 4297 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 4298 assert( !ExprHasProperty(pExpr, EP_TokenOnly) ); 4299 pFarg = pExpr->x.pList; 4300 nFarg = pFarg ? pFarg->nExpr : 0; 4301 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4302 zId = pExpr->u.zToken; 4303 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); 4304 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 4305 if( pDef==0 && pParse->explain ){ 4306 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); 4307 } 4308 #endif 4309 if( pDef==0 || pDef->xFinalize!=0 ){ 4310 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId); 4311 break; 4312 } 4313 if( pDef->funcFlags & SQLITE_FUNC_INLINE ){ 4314 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 ); 4315 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 ); 4316 return exprCodeInlineFunction(pParse, pFarg, 4317 SQLITE_PTR_TO_INT(pDef->pUserData), target); 4318 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){ 4319 sqlite3ExprFunctionUsable(pParse, pExpr, pDef); 4320 } 4321 4322 for(i=0; i<nFarg; i++){ 4323 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){ 4324 testcase( i==31 ); 4325 constMask |= MASKBIT32(i); 4326 } 4327 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ 4328 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); 4329 } 4330 } 4331 if( pFarg ){ 4332 if( constMask ){ 4333 r1 = pParse->nMem+1; 4334 pParse->nMem += nFarg; 4335 }else{ 4336 r1 = sqlite3GetTempRange(pParse, nFarg); 4337 } 4338 4339 /* For length() and typeof() functions with a column argument, 4340 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG 4341 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data 4342 ** loading. 4343 */ 4344 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ 4345 u8 exprOp; 4346 assert( nFarg==1 ); 4347 assert( pFarg->a[0].pExpr!=0 ); 4348 exprOp = pFarg->a[0].pExpr->op; 4349 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ 4350 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); 4351 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); 4352 testcase( pDef->funcFlags & OPFLAG_LENGTHARG ); 4353 pFarg->a[0].pExpr->op2 = 4354 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG); 4355 } 4356 } 4357 4358 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, 4359 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR); 4360 }else{ 4361 r1 = 0; 4362 } 4363 #ifndef SQLITE_OMIT_VIRTUALTABLE 4364 /* Possibly overload the function if the first argument is 4365 ** a virtual table column. 4366 ** 4367 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the 4368 ** second argument, not the first, as the argument to test to 4369 ** see if it is a column in a virtual table. This is done because 4370 ** the left operand of infix functions (the operand we want to 4371 ** control overloading) ends up as the second argument to the 4372 ** function. The expression "A glob B" is equivalent to 4373 ** "glob(B,A). We want to use the A in "A glob B" to test 4374 ** for function overloading. But we use the B term in "glob(B,A)". 4375 */ 4376 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){ 4377 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); 4378 }else if( nFarg>0 ){ 4379 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); 4380 } 4381 #endif 4382 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 4383 if( !pColl ) pColl = db->pDfltColl; 4384 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 4385 } 4386 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 4387 if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){ 4388 Expr *pArg = pFarg->a[0].pExpr; 4389 if( pArg->op==TK_COLUMN ){ 4390 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target); 4391 }else{ 4392 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 4393 } 4394 }else 4395 #endif 4396 { 4397 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg, 4398 pDef, pExpr->op2); 4399 } 4400 if( nFarg ){ 4401 if( constMask==0 ){ 4402 sqlite3ReleaseTempRange(pParse, r1, nFarg); 4403 }else{ 4404 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1); 4405 } 4406 } 4407 return target; 4408 } 4409 #ifndef SQLITE_OMIT_SUBQUERY 4410 case TK_EXISTS: 4411 case TK_SELECT: { 4412 int nCol; 4413 testcase( op==TK_EXISTS ); 4414 testcase( op==TK_SELECT ); 4415 if( pParse->db->mallocFailed ){ 4416 return 0; 4417 }else if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){ 4418 sqlite3SubselectError(pParse, nCol, 1); 4419 }else{ 4420 return sqlite3CodeSubselect(pParse, pExpr); 4421 } 4422 break; 4423 } 4424 case TK_SELECT_COLUMN: { 4425 int n; 4426 if( pExpr->pLeft->iTable==0 ){ 4427 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft); 4428 } 4429 assert( pExpr->pLeft->op==TK_SELECT || pExpr->pLeft->op==TK_ERROR ); 4430 n = sqlite3ExprVectorSize(pExpr->pLeft); 4431 if( pExpr->iTable!=n ){ 4432 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 4433 pExpr->iTable, n); 4434 } 4435 return pExpr->pLeft->iTable + pExpr->iColumn; 4436 } 4437 case TK_IN: { 4438 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 4439 int destIfNull = sqlite3VdbeMakeLabel(pParse); 4440 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 4441 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 4442 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 4443 sqlite3VdbeResolveLabel(v, destIfFalse); 4444 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); 4445 sqlite3VdbeResolveLabel(v, destIfNull); 4446 return target; 4447 } 4448 #endif /* SQLITE_OMIT_SUBQUERY */ 4449 4450 4451 /* 4452 ** x BETWEEN y AND z 4453 ** 4454 ** This is equivalent to 4455 ** 4456 ** x>=y AND x<=z 4457 ** 4458 ** X is stored in pExpr->pLeft. 4459 ** Y is stored in pExpr->pList->a[0].pExpr. 4460 ** Z is stored in pExpr->pList->a[1].pExpr. 4461 */ 4462 case TK_BETWEEN: { 4463 exprCodeBetween(pParse, pExpr, target, 0, 0); 4464 return target; 4465 } 4466 case TK_SPAN: 4467 case TK_COLLATE: 4468 case TK_UPLUS: { 4469 pExpr = pExpr->pLeft; 4470 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */ 4471 } 4472 4473 case TK_TRIGGER: { 4474 /* If the opcode is TK_TRIGGER, then the expression is a reference 4475 ** to a column in the new.* or old.* pseudo-tables available to 4476 ** trigger programs. In this case Expr.iTable is set to 1 for the 4477 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn 4478 ** is set to the column of the pseudo-table to read, or to -1 to 4479 ** read the rowid field. 4480 ** 4481 ** The expression is implemented using an OP_Param opcode. The p1 4482 ** parameter is set to 0 for an old.rowid reference, or to (i+1) 4483 ** to reference another column of the old.* pseudo-table, where 4484 ** i is the index of the column. For a new.rowid reference, p1 is 4485 ** set to (n+1), where n is the number of columns in each pseudo-table. 4486 ** For a reference to any other column in the new.* pseudo-table, p1 4487 ** is set to (n+2+i), where n and i are as defined previously. For 4488 ** example, if the table on which triggers are being fired is 4489 ** declared as: 4490 ** 4491 ** CREATE TABLE t1(a, b); 4492 ** 4493 ** Then p1 is interpreted as follows: 4494 ** 4495 ** p1==0 -> old.rowid p1==3 -> new.rowid 4496 ** p1==1 -> old.a p1==4 -> new.a 4497 ** p1==2 -> old.b p1==5 -> new.b 4498 */ 4499 Table *pTab = pExpr->y.pTab; 4500 int iCol = pExpr->iColumn; 4501 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 4502 + sqlite3TableColumnToStorage(pTab, iCol); 4503 4504 assert( pExpr->iTable==0 || pExpr->iTable==1 ); 4505 assert( iCol>=-1 && iCol<pTab->nCol ); 4506 assert( pTab->iPKey<0 || iCol!=pTab->iPKey ); 4507 assert( p1>=0 && p1<(pTab->nCol*2+2) ); 4508 4509 sqlite3VdbeAddOp2(v, OP_Param, p1, target); 4510 VdbeComment((v, "r[%d]=%s.%s", target, 4511 (pExpr->iTable ? "new" : "old"), 4512 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName) 4513 )); 4514 4515 #ifndef SQLITE_OMIT_FLOATING_POINT 4516 /* If the column has REAL affinity, it may currently be stored as an 4517 ** integer. Use OP_RealAffinity to make sure it is really real. 4518 ** 4519 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to 4520 ** floating point when extracting it from the record. */ 4521 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){ 4522 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 4523 } 4524 #endif 4525 break; 4526 } 4527 4528 case TK_VECTOR: { 4529 sqlite3ErrorMsg(pParse, "row value misused"); 4530 break; 4531 } 4532 4533 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions 4534 ** that derive from the right-hand table of a LEFT JOIN. The 4535 ** Expr.iTable value is the table number for the right-hand table. 4536 ** The expression is only evaluated if that table is not currently 4537 ** on a LEFT JOIN NULL row. 4538 */ 4539 case TK_IF_NULL_ROW: { 4540 int addrINR; 4541 u8 okConstFactor = pParse->okConstFactor; 4542 addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable); 4543 /* Temporarily disable factoring of constant expressions, since 4544 ** even though expressions may appear to be constant, they are not 4545 ** really constant because they originate from the right-hand side 4546 ** of a LEFT JOIN. */ 4547 pParse->okConstFactor = 0; 4548 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); 4549 pParse->okConstFactor = okConstFactor; 4550 sqlite3VdbeJumpHere(v, addrINR); 4551 sqlite3VdbeChangeP3(v, addrINR, inReg); 4552 break; 4553 } 4554 4555 /* 4556 ** Form A: 4557 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 4558 ** 4559 ** Form B: 4560 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 4561 ** 4562 ** Form A is can be transformed into the equivalent form B as follows: 4563 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... 4564 ** WHEN x=eN THEN rN ELSE y END 4565 ** 4566 ** X (if it exists) is in pExpr->pLeft. 4567 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is 4568 ** odd. The Y is also optional. If the number of elements in x.pList 4569 ** is even, then Y is omitted and the "otherwise" result is NULL. 4570 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. 4571 ** 4572 ** The result of the expression is the Ri for the first matching Ei, 4573 ** or if there is no matching Ei, the ELSE term Y, or if there is 4574 ** no ELSE term, NULL. 4575 */ 4576 case TK_CASE: { 4577 int endLabel; /* GOTO label for end of CASE stmt */ 4578 int nextCase; /* GOTO label for next WHEN clause */ 4579 int nExpr; /* 2x number of WHEN terms */ 4580 int i; /* Loop counter */ 4581 ExprList *pEList; /* List of WHEN terms */ 4582 struct ExprList_item *aListelem; /* Array of WHEN terms */ 4583 Expr opCompare; /* The X==Ei expression */ 4584 Expr *pX; /* The X expression */ 4585 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ 4586 Expr *pDel = 0; 4587 sqlite3 *db = pParse->db; 4588 4589 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList ); 4590 assert(pExpr->x.pList->nExpr > 0); 4591 pEList = pExpr->x.pList; 4592 aListelem = pEList->a; 4593 nExpr = pEList->nExpr; 4594 endLabel = sqlite3VdbeMakeLabel(pParse); 4595 if( (pX = pExpr->pLeft)!=0 ){ 4596 pDel = sqlite3ExprDup(db, pX, 0); 4597 if( db->mallocFailed ){ 4598 sqlite3ExprDelete(db, pDel); 4599 break; 4600 } 4601 testcase( pX->op==TK_COLUMN ); 4602 exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 4603 testcase( regFree1==0 ); 4604 memset(&opCompare, 0, sizeof(opCompare)); 4605 opCompare.op = TK_EQ; 4606 opCompare.pLeft = pDel; 4607 pTest = &opCompare; 4608 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: 4609 ** The value in regFree1 might get SCopy-ed into the file result. 4610 ** So make sure that the regFree1 register is not reused for other 4611 ** purposes and possibly overwritten. */ 4612 regFree1 = 0; 4613 } 4614 for(i=0; i<nExpr-1; i=i+2){ 4615 if( pX ){ 4616 assert( pTest!=0 ); 4617 opCompare.pRight = aListelem[i].pExpr; 4618 }else{ 4619 pTest = aListelem[i].pExpr; 4620 } 4621 nextCase = sqlite3VdbeMakeLabel(pParse); 4622 testcase( pTest->op==TK_COLUMN ); 4623 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); 4624 testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); 4625 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); 4626 sqlite3VdbeGoto(v, endLabel); 4627 sqlite3VdbeResolveLabel(v, nextCase); 4628 } 4629 if( (nExpr&1)!=0 ){ 4630 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); 4631 }else{ 4632 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 4633 } 4634 sqlite3ExprDelete(db, pDel); 4635 setDoNotMergeFlagOnCopy(v); 4636 sqlite3VdbeResolveLabel(v, endLabel); 4637 break; 4638 } 4639 #ifndef SQLITE_OMIT_TRIGGER 4640 case TK_RAISE: { 4641 assert( pExpr->affExpr==OE_Rollback 4642 || pExpr->affExpr==OE_Abort 4643 || pExpr->affExpr==OE_Fail 4644 || pExpr->affExpr==OE_Ignore 4645 ); 4646 if( !pParse->pTriggerTab && !pParse->nested ){ 4647 sqlite3ErrorMsg(pParse, 4648 "RAISE() may only be used within a trigger-program"); 4649 return 0; 4650 } 4651 if( pExpr->affExpr==OE_Abort ){ 4652 sqlite3MayAbort(pParse); 4653 } 4654 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 4655 if( pExpr->affExpr==OE_Ignore ){ 4656 sqlite3VdbeAddOp4( 4657 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); 4658 VdbeCoverage(v); 4659 }else{ 4660 sqlite3HaltConstraint(pParse, 4661 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR, 4662 pExpr->affExpr, pExpr->u.zToken, 0, 0); 4663 } 4664 4665 break; 4666 } 4667 #endif 4668 } 4669 sqlite3ReleaseTempReg(pParse, regFree1); 4670 sqlite3ReleaseTempReg(pParse, regFree2); 4671 return inReg; 4672 } 4673 4674 /* 4675 ** Generate code that will evaluate expression pExpr just one time 4676 ** per prepared statement execution. 4677 ** 4678 ** If the expression uses functions (that might throw an exception) then 4679 ** guard them with an OP_Once opcode to ensure that the code is only executed 4680 ** once. If no functions are involved, then factor the code out and put it at 4681 ** the end of the prepared statement in the initialization section. 4682 ** 4683 ** If regDest>=0 then the result is always stored in that register and the 4684 ** result is not reusable. If regDest<0 then this routine is free to 4685 ** store the value whereever it wants. The register where the expression 4686 ** is stored is returned. When regDest<0, two identical expressions might 4687 ** code to the same register, if they do not contain function calls and hence 4688 ** are factored out into the initialization section at the end of the 4689 ** prepared statement. 4690 */ 4691 int sqlite3ExprCodeRunJustOnce( 4692 Parse *pParse, /* Parsing context */ 4693 Expr *pExpr, /* The expression to code when the VDBE initializes */ 4694 int regDest /* Store the value in this register */ 4695 ){ 4696 ExprList *p; 4697 assert( ConstFactorOk(pParse) ); 4698 p = pParse->pConstExpr; 4699 if( regDest<0 && p ){ 4700 struct ExprList_item *pItem; 4701 int i; 4702 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ 4703 if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){ 4704 return pItem->u.iConstExprReg; 4705 } 4706 } 4707 } 4708 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); 4709 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){ 4710 Vdbe *v = pParse->pVdbe; 4711 int addr; 4712 assert( v ); 4713 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 4714 pParse->okConstFactor = 0; 4715 if( !pParse->db->mallocFailed ){ 4716 if( regDest<0 ) regDest = ++pParse->nMem; 4717 sqlite3ExprCode(pParse, pExpr, regDest); 4718 } 4719 pParse->okConstFactor = 1; 4720 sqlite3ExprDelete(pParse->db, pExpr); 4721 sqlite3VdbeJumpHere(v, addr); 4722 }else{ 4723 p = sqlite3ExprListAppend(pParse, p, pExpr); 4724 if( p ){ 4725 struct ExprList_item *pItem = &p->a[p->nExpr-1]; 4726 pItem->reusable = regDest<0; 4727 if( regDest<0 ) regDest = ++pParse->nMem; 4728 pItem->u.iConstExprReg = regDest; 4729 } 4730 pParse->pConstExpr = p; 4731 } 4732 return regDest; 4733 } 4734 4735 /* 4736 ** Generate code to evaluate an expression and store the results 4737 ** into a register. Return the register number where the results 4738 ** are stored. 4739 ** 4740 ** If the register is a temporary register that can be deallocated, 4741 ** then write its number into *pReg. If the result register is not 4742 ** a temporary, then set *pReg to zero. 4743 ** 4744 ** If pExpr is a constant, then this routine might generate this 4745 ** code to fill the register in the initialization section of the 4746 ** VDBE program, in order to factor it out of the evaluation loop. 4747 */ 4748 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ 4749 int r2; 4750 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr); 4751 if( ConstFactorOk(pParse) 4752 && ALWAYS(pExpr!=0) 4753 && pExpr->op!=TK_REGISTER 4754 && sqlite3ExprIsConstantNotJoin(pExpr) 4755 ){ 4756 *pReg = 0; 4757 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); 4758 }else{ 4759 int r1 = sqlite3GetTempReg(pParse); 4760 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); 4761 if( r2==r1 ){ 4762 *pReg = r1; 4763 }else{ 4764 sqlite3ReleaseTempReg(pParse, r1); 4765 *pReg = 0; 4766 } 4767 } 4768 return r2; 4769 } 4770 4771 /* 4772 ** Generate code that will evaluate expression pExpr and store the 4773 ** results in register target. The results are guaranteed to appear 4774 ** in register target. 4775 */ 4776 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ 4777 int inReg; 4778 4779 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) ); 4780 assert( target>0 && target<=pParse->nMem ); 4781 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); 4782 if( pParse->pVdbe==0 ) return; 4783 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); 4784 if( inReg!=target ){ 4785 u8 op; 4786 if( ExprHasProperty(pExpr,EP_Subquery) ){ 4787 op = OP_Copy; 4788 }else{ 4789 op = OP_SCopy; 4790 } 4791 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target); 4792 } 4793 } 4794 4795 /* 4796 ** Make a transient copy of expression pExpr and then code it using 4797 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() 4798 ** except that the input expression is guaranteed to be unchanged. 4799 */ 4800 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ 4801 sqlite3 *db = pParse->db; 4802 pExpr = sqlite3ExprDup(db, pExpr, 0); 4803 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); 4804 sqlite3ExprDelete(db, pExpr); 4805 } 4806 4807 /* 4808 ** Generate code that will evaluate expression pExpr and store the 4809 ** results in register target. The results are guaranteed to appear 4810 ** in register target. If the expression is constant, then this routine 4811 ** might choose to code the expression at initialization time. 4812 */ 4813 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ 4814 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){ 4815 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target); 4816 }else{ 4817 sqlite3ExprCodeCopy(pParse, pExpr, target); 4818 } 4819 } 4820 4821 /* 4822 ** Generate code that pushes the value of every element of the given 4823 ** expression list into a sequence of registers beginning at target. 4824 ** 4825 ** Return the number of elements evaluated. The number returned will 4826 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF 4827 ** is defined. 4828 ** 4829 ** The SQLITE_ECEL_DUP flag prevents the arguments from being 4830 ** filled using OP_SCopy. OP_Copy must be used instead. 4831 ** 4832 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be 4833 ** factored out into initialization code. 4834 ** 4835 ** The SQLITE_ECEL_REF flag means that expressions in the list with 4836 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored 4837 ** in registers at srcReg, and so the value can be copied from there. 4838 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0 4839 ** are simply omitted rather than being copied from srcReg. 4840 */ 4841 int sqlite3ExprCodeExprList( 4842 Parse *pParse, /* Parsing context */ 4843 ExprList *pList, /* The expression list to be coded */ 4844 int target, /* Where to write results */ 4845 int srcReg, /* Source registers if SQLITE_ECEL_REF */ 4846 u8 flags /* SQLITE_ECEL_* flags */ 4847 ){ 4848 struct ExprList_item *pItem; 4849 int i, j, n; 4850 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy; 4851 Vdbe *v = pParse->pVdbe; 4852 assert( pList!=0 ); 4853 assert( target>0 ); 4854 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ 4855 n = pList->nExpr; 4856 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; 4857 for(pItem=pList->a, i=0; i<n; i++, pItem++){ 4858 Expr *pExpr = pItem->pExpr; 4859 #ifdef SQLITE_ENABLE_SORTER_REFERENCES 4860 if( pItem->bSorterRef ){ 4861 i--; 4862 n--; 4863 }else 4864 #endif 4865 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){ 4866 if( flags & SQLITE_ECEL_OMITREF ){ 4867 i--; 4868 n--; 4869 }else{ 4870 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); 4871 } 4872 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 4873 && sqlite3ExprIsConstantNotJoin(pExpr) 4874 ){ 4875 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i); 4876 }else{ 4877 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); 4878 if( inReg!=target+i ){ 4879 VdbeOp *pOp; 4880 if( copyOp==OP_Copy 4881 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy 4882 && pOp->p1+pOp->p3+1==inReg 4883 && pOp->p2+pOp->p3+1==target+i 4884 && pOp->p5==0 /* The do-not-merge flag must be clear */ 4885 ){ 4886 pOp->p3++; 4887 }else{ 4888 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); 4889 } 4890 } 4891 } 4892 } 4893 return n; 4894 } 4895 4896 /* 4897 ** Generate code for a BETWEEN operator. 4898 ** 4899 ** x BETWEEN y AND z 4900 ** 4901 ** The above is equivalent to 4902 ** 4903 ** x>=y AND x<=z 4904 ** 4905 ** Code it as such, taking care to do the common subexpression 4906 ** elimination of x. 4907 ** 4908 ** The xJumpIf parameter determines details: 4909 ** 4910 ** NULL: Store the boolean result in reg[dest] 4911 ** sqlite3ExprIfTrue: Jump to dest if true 4912 ** sqlite3ExprIfFalse: Jump to dest if false 4913 ** 4914 ** The jumpIfNull parameter is ignored if xJumpIf is NULL. 4915 */ 4916 static void exprCodeBetween( 4917 Parse *pParse, /* Parsing and code generating context */ 4918 Expr *pExpr, /* The BETWEEN expression */ 4919 int dest, /* Jump destination or storage location */ 4920 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ 4921 int jumpIfNull /* Take the jump if the BETWEEN is NULL */ 4922 ){ 4923 Expr exprAnd; /* The AND operator in x>=y AND x<=z */ 4924 Expr compLeft; /* The x>=y term */ 4925 Expr compRight; /* The x<=z term */ 4926 int regFree1 = 0; /* Temporary use register */ 4927 Expr *pDel = 0; 4928 sqlite3 *db = pParse->db; 4929 4930 memset(&compLeft, 0, sizeof(Expr)); 4931 memset(&compRight, 0, sizeof(Expr)); 4932 memset(&exprAnd, 0, sizeof(Expr)); 4933 4934 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 4935 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0); 4936 if( db->mallocFailed==0 ){ 4937 exprAnd.op = TK_AND; 4938 exprAnd.pLeft = &compLeft; 4939 exprAnd.pRight = &compRight; 4940 compLeft.op = TK_GE; 4941 compLeft.pLeft = pDel; 4942 compLeft.pRight = pExpr->x.pList->a[0].pExpr; 4943 compRight.op = TK_LE; 4944 compRight.pLeft = pDel; 4945 compRight.pRight = pExpr->x.pList->a[1].pExpr; 4946 exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 4947 if( xJump ){ 4948 xJump(pParse, &exprAnd, dest, jumpIfNull); 4949 }else{ 4950 /* Mark the expression is being from the ON or USING clause of a join 4951 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move 4952 ** it into the Parse.pConstExpr list. We should use a new bit for this, 4953 ** for clarity, but we are out of bits in the Expr.flags field so we 4954 ** have to reuse the EP_FromJoin bit. Bummer. */ 4955 pDel->flags |= EP_FromJoin; 4956 sqlite3ExprCodeTarget(pParse, &exprAnd, dest); 4957 } 4958 sqlite3ReleaseTempReg(pParse, regFree1); 4959 } 4960 sqlite3ExprDelete(db, pDel); 4961 4962 /* Ensure adequate test coverage */ 4963 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); 4964 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); 4965 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); 4966 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); 4967 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); 4968 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); 4969 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); 4970 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); 4971 testcase( xJump==0 ); 4972 } 4973 4974 /* 4975 ** Generate code for a boolean expression such that a jump is made 4976 ** to the label "dest" if the expression is true but execution 4977 ** continues straight thru if the expression is false. 4978 ** 4979 ** If the expression evaluates to NULL (neither true nor false), then 4980 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. 4981 ** 4982 ** This code depends on the fact that certain token values (ex: TK_EQ) 4983 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding 4984 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in 4985 ** the make process cause these values to align. Assert()s in the code 4986 ** below verify that the numbers are aligned correctly. 4987 */ 4988 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 4989 Vdbe *v = pParse->pVdbe; 4990 int op = 0; 4991 int regFree1 = 0; 4992 int regFree2 = 0; 4993 int r1, r2; 4994 4995 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 4996 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 4997 if( NEVER(pExpr==0) ) return; /* No way this can happen */ 4998 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) ); 4999 op = pExpr->op; 5000 switch( op ){ 5001 case TK_AND: 5002 case TK_OR: { 5003 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 5004 if( pAlt!=pExpr ){ 5005 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull); 5006 }else if( op==TK_AND ){ 5007 int d2 = sqlite3VdbeMakeLabel(pParse); 5008 testcase( jumpIfNull==0 ); 5009 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, 5010 jumpIfNull^SQLITE_JUMPIFNULL); 5011 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 5012 sqlite3VdbeResolveLabel(v, d2); 5013 }else{ 5014 testcase( jumpIfNull==0 ); 5015 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 5016 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 5017 } 5018 break; 5019 } 5020 case TK_NOT: { 5021 testcase( jumpIfNull==0 ); 5022 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 5023 break; 5024 } 5025 case TK_TRUTH: { 5026 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 5027 int isTrue; /* IS TRUE or IS NOT TRUE */ 5028 testcase( jumpIfNull==0 ); 5029 isNot = pExpr->op2==TK_ISNOT; 5030 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 5031 testcase( isTrue && isNot ); 5032 testcase( !isTrue && isNot ); 5033 if( isTrue ^ isNot ){ 5034 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 5035 isNot ? SQLITE_JUMPIFNULL : 0); 5036 }else{ 5037 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 5038 isNot ? SQLITE_JUMPIFNULL : 0); 5039 } 5040 break; 5041 } 5042 case TK_IS: 5043 case TK_ISNOT: 5044 testcase( op==TK_IS ); 5045 testcase( op==TK_ISNOT ); 5046 op = (op==TK_IS) ? TK_EQ : TK_NE; 5047 jumpIfNull = SQLITE_NULLEQ; 5048 /* no break */ deliberate_fall_through 5049 case TK_LT: 5050 case TK_LE: 5051 case TK_GT: 5052 case TK_GE: 5053 case TK_NE: 5054 case TK_EQ: { 5055 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 5056 testcase( jumpIfNull==0 ); 5057 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5058 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 5059 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 5060 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted)); 5061 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 5062 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 5063 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 5064 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 5065 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 5066 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 5067 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 5068 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 5069 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 5070 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 5071 testcase( regFree1==0 ); 5072 testcase( regFree2==0 ); 5073 break; 5074 } 5075 case TK_ISNULL: 5076 case TK_NOTNULL: { 5077 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 5078 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 5079 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5080 sqlite3VdbeAddOp2(v, op, r1, dest); 5081 VdbeCoverageIf(v, op==TK_ISNULL); 5082 VdbeCoverageIf(v, op==TK_NOTNULL); 5083 testcase( regFree1==0 ); 5084 break; 5085 } 5086 case TK_BETWEEN: { 5087 testcase( jumpIfNull==0 ); 5088 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); 5089 break; 5090 } 5091 #ifndef SQLITE_OMIT_SUBQUERY 5092 case TK_IN: { 5093 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 5094 int destIfNull = jumpIfNull ? dest : destIfFalse; 5095 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 5096 sqlite3VdbeGoto(v, dest); 5097 sqlite3VdbeResolveLabel(v, destIfFalse); 5098 break; 5099 } 5100 #endif 5101 default: { 5102 default_expr: 5103 if( ExprAlwaysTrue(pExpr) ){ 5104 sqlite3VdbeGoto(v, dest); 5105 }else if( ExprAlwaysFalse(pExpr) ){ 5106 /* No-op */ 5107 }else{ 5108 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 5109 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); 5110 VdbeCoverage(v); 5111 testcase( regFree1==0 ); 5112 testcase( jumpIfNull==0 ); 5113 } 5114 break; 5115 } 5116 } 5117 sqlite3ReleaseTempReg(pParse, regFree1); 5118 sqlite3ReleaseTempReg(pParse, regFree2); 5119 } 5120 5121 /* 5122 ** Generate code for a boolean expression such that a jump is made 5123 ** to the label "dest" if the expression is false but execution 5124 ** continues straight thru if the expression is true. 5125 ** 5126 ** If the expression evaluates to NULL (neither true nor false) then 5127 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull 5128 ** is 0. 5129 */ 5130 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 5131 Vdbe *v = pParse->pVdbe; 5132 int op = 0; 5133 int regFree1 = 0; 5134 int regFree2 = 0; 5135 int r1, r2; 5136 5137 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 5138 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 5139 if( pExpr==0 ) return; 5140 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 5141 5142 /* The value of pExpr->op and op are related as follows: 5143 ** 5144 ** pExpr->op op 5145 ** --------- ---------- 5146 ** TK_ISNULL OP_NotNull 5147 ** TK_NOTNULL OP_IsNull 5148 ** TK_NE OP_Eq 5149 ** TK_EQ OP_Ne 5150 ** TK_GT OP_Le 5151 ** TK_LE OP_Gt 5152 ** TK_GE OP_Lt 5153 ** TK_LT OP_Ge 5154 ** 5155 ** For other values of pExpr->op, op is undefined and unused. 5156 ** The value of TK_ and OP_ constants are arranged such that we 5157 ** can compute the mapping above using the following expression. 5158 ** Assert()s verify that the computation is correct. 5159 */ 5160 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); 5161 5162 /* Verify correct alignment of TK_ and OP_ constants 5163 */ 5164 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); 5165 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); 5166 assert( pExpr->op!=TK_NE || op==OP_Eq ); 5167 assert( pExpr->op!=TK_EQ || op==OP_Ne ); 5168 assert( pExpr->op!=TK_LT || op==OP_Ge ); 5169 assert( pExpr->op!=TK_LE || op==OP_Gt ); 5170 assert( pExpr->op!=TK_GT || op==OP_Le ); 5171 assert( pExpr->op!=TK_GE || op==OP_Lt ); 5172 5173 switch( pExpr->op ){ 5174 case TK_AND: 5175 case TK_OR: { 5176 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 5177 if( pAlt!=pExpr ){ 5178 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull); 5179 }else if( pExpr->op==TK_AND ){ 5180 testcase( jumpIfNull==0 ); 5181 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 5182 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 5183 }else{ 5184 int d2 = sqlite3VdbeMakeLabel(pParse); 5185 testcase( jumpIfNull==0 ); 5186 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, 5187 jumpIfNull^SQLITE_JUMPIFNULL); 5188 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 5189 sqlite3VdbeResolveLabel(v, d2); 5190 } 5191 break; 5192 } 5193 case TK_NOT: { 5194 testcase( jumpIfNull==0 ); 5195 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 5196 break; 5197 } 5198 case TK_TRUTH: { 5199 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 5200 int isTrue; /* IS TRUE or IS NOT TRUE */ 5201 testcase( jumpIfNull==0 ); 5202 isNot = pExpr->op2==TK_ISNOT; 5203 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 5204 testcase( isTrue && isNot ); 5205 testcase( !isTrue && isNot ); 5206 if( isTrue ^ isNot ){ 5207 /* IS TRUE and IS NOT FALSE */ 5208 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 5209 isNot ? 0 : SQLITE_JUMPIFNULL); 5210 5211 }else{ 5212 /* IS FALSE and IS NOT TRUE */ 5213 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 5214 isNot ? 0 : SQLITE_JUMPIFNULL); 5215 } 5216 break; 5217 } 5218 case TK_IS: 5219 case TK_ISNOT: 5220 testcase( pExpr->op==TK_IS ); 5221 testcase( pExpr->op==TK_ISNOT ); 5222 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; 5223 jumpIfNull = SQLITE_NULLEQ; 5224 /* no break */ deliberate_fall_through 5225 case TK_LT: 5226 case TK_LE: 5227 case TK_GT: 5228 case TK_GE: 5229 case TK_NE: 5230 case TK_EQ: { 5231 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 5232 testcase( jumpIfNull==0 ); 5233 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5234 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 5235 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 5236 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted)); 5237 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 5238 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 5239 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 5240 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 5241 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 5242 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 5243 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 5244 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 5245 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 5246 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 5247 testcase( regFree1==0 ); 5248 testcase( regFree2==0 ); 5249 break; 5250 } 5251 case TK_ISNULL: 5252 case TK_NOTNULL: { 5253 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5254 sqlite3VdbeAddOp2(v, op, r1, dest); 5255 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); 5256 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); 5257 testcase( regFree1==0 ); 5258 break; 5259 } 5260 case TK_BETWEEN: { 5261 testcase( jumpIfNull==0 ); 5262 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); 5263 break; 5264 } 5265 #ifndef SQLITE_OMIT_SUBQUERY 5266 case TK_IN: { 5267 if( jumpIfNull ){ 5268 sqlite3ExprCodeIN(pParse, pExpr, dest, dest); 5269 }else{ 5270 int destIfNull = sqlite3VdbeMakeLabel(pParse); 5271 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); 5272 sqlite3VdbeResolveLabel(v, destIfNull); 5273 } 5274 break; 5275 } 5276 #endif 5277 default: { 5278 default_expr: 5279 if( ExprAlwaysFalse(pExpr) ){ 5280 sqlite3VdbeGoto(v, dest); 5281 }else if( ExprAlwaysTrue(pExpr) ){ 5282 /* no-op */ 5283 }else{ 5284 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 5285 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); 5286 VdbeCoverage(v); 5287 testcase( regFree1==0 ); 5288 testcase( jumpIfNull==0 ); 5289 } 5290 break; 5291 } 5292 } 5293 sqlite3ReleaseTempReg(pParse, regFree1); 5294 sqlite3ReleaseTempReg(pParse, regFree2); 5295 } 5296 5297 /* 5298 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before 5299 ** code generation, and that copy is deleted after code generation. This 5300 ** ensures that the original pExpr is unchanged. 5301 */ 5302 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ 5303 sqlite3 *db = pParse->db; 5304 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); 5305 if( db->mallocFailed==0 ){ 5306 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); 5307 } 5308 sqlite3ExprDelete(db, pCopy); 5309 } 5310 5311 /* 5312 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any 5313 ** type of expression. 5314 ** 5315 ** If pExpr is a simple SQL value - an integer, real, string, blob 5316 ** or NULL value - then the VDBE currently being prepared is configured 5317 ** to re-prepare each time a new value is bound to variable pVar. 5318 ** 5319 ** Additionally, if pExpr is a simple SQL value and the value is the 5320 ** same as that currently bound to variable pVar, non-zero is returned. 5321 ** Otherwise, if the values are not the same or if pExpr is not a simple 5322 ** SQL value, zero is returned. 5323 */ 5324 static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){ 5325 int res = 0; 5326 int iVar; 5327 sqlite3_value *pL, *pR = 0; 5328 5329 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR); 5330 if( pR ){ 5331 iVar = pVar->iColumn; 5332 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); 5333 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB); 5334 if( pL ){ 5335 if( sqlite3_value_type(pL)==SQLITE_TEXT ){ 5336 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */ 5337 } 5338 res = 0==sqlite3MemCompare(pL, pR, 0); 5339 } 5340 sqlite3ValueFree(pR); 5341 sqlite3ValueFree(pL); 5342 } 5343 5344 return res; 5345 } 5346 5347 /* 5348 ** Do a deep comparison of two expression trees. Return 0 if the two 5349 ** expressions are completely identical. Return 1 if they differ only 5350 ** by a COLLATE operator at the top level. Return 2 if there are differences 5351 ** other than the top-level COLLATE operator. 5352 ** 5353 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 5354 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 5355 ** 5356 ** The pA side might be using TK_REGISTER. If that is the case and pB is 5357 ** not using TK_REGISTER but is otherwise equivalent, then still return 0. 5358 ** 5359 ** Sometimes this routine will return 2 even if the two expressions 5360 ** really are equivalent. If we cannot prove that the expressions are 5361 ** identical, we return 2 just to be safe. So if this routine 5362 ** returns 2, then you do not really know for certain if the two 5363 ** expressions are the same. But if you get a 0 or 1 return, then you 5364 ** can be sure the expressions are the same. In the places where 5365 ** this routine is used, it does not hurt to get an extra 2 - that 5366 ** just might result in some slightly slower code. But returning 5367 ** an incorrect 0 or 1 could lead to a malfunction. 5368 ** 5369 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in 5370 ** pParse->pReprepare can be matched against literals in pB. The 5371 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced. 5372 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in 5373 ** Argument pParse should normally be NULL. If it is not NULL and pA or 5374 ** pB causes a return value of 2. 5375 */ 5376 int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){ 5377 u32 combinedFlags; 5378 if( pA==0 || pB==0 ){ 5379 return pB==pA ? 0 : 2; 5380 } 5381 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){ 5382 return 0; 5383 } 5384 combinedFlags = pA->flags | pB->flags; 5385 if( combinedFlags & EP_IntValue ){ 5386 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ 5387 return 0; 5388 } 5389 return 2; 5390 } 5391 if( pA->op!=pB->op || pA->op==TK_RAISE ){ 5392 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){ 5393 return 1; 5394 } 5395 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){ 5396 return 1; 5397 } 5398 return 2; 5399 } 5400 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){ 5401 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){ 5402 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 5403 #ifndef SQLITE_OMIT_WINDOWFUNC 5404 assert( pA->op==pB->op ); 5405 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){ 5406 return 2; 5407 } 5408 if( ExprHasProperty(pA,EP_WinFunc) ){ 5409 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){ 5410 return 2; 5411 } 5412 } 5413 #endif 5414 }else if( pA->op==TK_NULL ){ 5415 return 0; 5416 }else if( pA->op==TK_COLLATE ){ 5417 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 5418 }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){ 5419 return 2; 5420 } 5421 } 5422 if( (pA->flags & (EP_Distinct|EP_Commuted)) 5423 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2; 5424 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ 5425 if( combinedFlags & EP_xIsSelect ) return 2; 5426 if( (combinedFlags & EP_FixedCol)==0 5427 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2; 5428 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2; 5429 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; 5430 if( pA->op!=TK_STRING 5431 && pA->op!=TK_TRUEFALSE 5432 && ALWAYS((combinedFlags & EP_Reduced)==0) 5433 ){ 5434 if( pA->iColumn!=pB->iColumn ) return 2; 5435 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2; 5436 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){ 5437 return 2; 5438 } 5439 } 5440 } 5441 return 0; 5442 } 5443 5444 /* 5445 ** Compare two ExprList objects. Return 0 if they are identical, 1 5446 ** if they are certainly different, or 2 if it is not possible to 5447 ** determine if they are identical or not. 5448 ** 5449 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 5450 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 5451 ** 5452 ** This routine might return non-zero for equivalent ExprLists. The 5453 ** only consequence will be disabled optimizations. But this routine 5454 ** must never return 0 if the two ExprList objects are different, or 5455 ** a malfunction will result. 5456 ** 5457 ** Two NULL pointers are considered to be the same. But a NULL pointer 5458 ** always differs from a non-NULL pointer. 5459 */ 5460 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){ 5461 int i; 5462 if( pA==0 && pB==0 ) return 0; 5463 if( pA==0 || pB==0 ) return 1; 5464 if( pA->nExpr!=pB->nExpr ) return 1; 5465 for(i=0; i<pA->nExpr; i++){ 5466 int res; 5467 Expr *pExprA = pA->a[i].pExpr; 5468 Expr *pExprB = pB->a[i].pExpr; 5469 if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1; 5470 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res; 5471 } 5472 return 0; 5473 } 5474 5475 /* 5476 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level 5477 ** are ignored. 5478 */ 5479 int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){ 5480 return sqlite3ExprCompare(0, 5481 sqlite3ExprSkipCollateAndLikely(pA), 5482 sqlite3ExprSkipCollateAndLikely(pB), 5483 iTab); 5484 } 5485 5486 /* 5487 ** Return non-zero if Expr p can only be true if pNN is not NULL. 5488 ** 5489 ** Or if seenNot is true, return non-zero if Expr p can only be 5490 ** non-NULL if pNN is not NULL 5491 */ 5492 static int exprImpliesNotNull( 5493 Parse *pParse, /* Parsing context */ 5494 Expr *p, /* The expression to be checked */ 5495 Expr *pNN, /* The expression that is NOT NULL */ 5496 int iTab, /* Table being evaluated */ 5497 int seenNot /* Return true only if p can be any non-NULL value */ 5498 ){ 5499 assert( p ); 5500 assert( pNN ); 5501 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){ 5502 return pNN->op!=TK_NULL; 5503 } 5504 switch( p->op ){ 5505 case TK_IN: { 5506 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0; 5507 assert( ExprHasProperty(p,EP_xIsSelect) 5508 || (p->x.pList!=0 && p->x.pList->nExpr>0) ); 5509 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 5510 } 5511 case TK_BETWEEN: { 5512 ExprList *pList = p->x.pList; 5513 assert( pList!=0 ); 5514 assert( pList->nExpr==2 ); 5515 if( seenNot ) return 0; 5516 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1) 5517 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1) 5518 ){ 5519 return 1; 5520 } 5521 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 5522 } 5523 case TK_EQ: 5524 case TK_NE: 5525 case TK_LT: 5526 case TK_LE: 5527 case TK_GT: 5528 case TK_GE: 5529 case TK_PLUS: 5530 case TK_MINUS: 5531 case TK_BITOR: 5532 case TK_LSHIFT: 5533 case TK_RSHIFT: 5534 case TK_CONCAT: 5535 seenNot = 1; 5536 /* no break */ deliberate_fall_through 5537 case TK_STAR: 5538 case TK_REM: 5539 case TK_BITAND: 5540 case TK_SLASH: { 5541 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1; 5542 /* no break */ deliberate_fall_through 5543 } 5544 case TK_SPAN: 5545 case TK_COLLATE: 5546 case TK_UPLUS: 5547 case TK_UMINUS: { 5548 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); 5549 } 5550 case TK_TRUTH: { 5551 if( seenNot ) return 0; 5552 if( p->op2!=TK_IS ) return 0; 5553 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 5554 } 5555 case TK_BITNOT: 5556 case TK_NOT: { 5557 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 5558 } 5559 } 5560 return 0; 5561 } 5562 5563 /* 5564 ** Return true if we can prove the pE2 will always be true if pE1 is 5565 ** true. Return false if we cannot complete the proof or if pE2 might 5566 ** be false. Examples: 5567 ** 5568 ** pE1: x==5 pE2: x==5 Result: true 5569 ** pE1: x>0 pE2: x==5 Result: false 5570 ** pE1: x=21 pE2: x=21 OR y=43 Result: true 5571 ** pE1: x!=123 pE2: x IS NOT NULL Result: true 5572 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true 5573 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false 5574 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false 5575 ** 5576 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has 5577 ** Expr.iTable<0 then assume a table number given by iTab. 5578 ** 5579 ** If pParse is not NULL, then the values of bound variables in pE1 are 5580 ** compared against literal values in pE2 and pParse->pVdbe->expmask is 5581 ** modified to record which bound variables are referenced. If pParse 5582 ** is NULL, then false will be returned if pE1 contains any bound variables. 5583 ** 5584 ** When in doubt, return false. Returning true might give a performance 5585 ** improvement. Returning false might cause a performance reduction, but 5586 ** it will always give the correct answer and is hence always safe. 5587 */ 5588 int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){ 5589 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){ 5590 return 1; 5591 } 5592 if( pE2->op==TK_OR 5593 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab) 5594 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) ) 5595 ){ 5596 return 1; 5597 } 5598 if( pE2->op==TK_NOTNULL 5599 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0) 5600 ){ 5601 return 1; 5602 } 5603 return 0; 5604 } 5605 5606 /* 5607 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow(). 5608 ** If the expression node requires that the table at pWalker->iCur 5609 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort. 5610 ** 5611 ** This routine controls an optimization. False positives (setting 5612 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives 5613 ** (never setting pWalker->eCode) is a harmless missed optimization. 5614 */ 5615 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){ 5616 testcase( pExpr->op==TK_AGG_COLUMN ); 5617 testcase( pExpr->op==TK_AGG_FUNCTION ); 5618 if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune; 5619 switch( pExpr->op ){ 5620 case TK_ISNOT: 5621 case TK_ISNULL: 5622 case TK_NOTNULL: 5623 case TK_IS: 5624 case TK_OR: 5625 case TK_VECTOR: 5626 case TK_CASE: 5627 case TK_IN: 5628 case TK_FUNCTION: 5629 case TK_TRUTH: 5630 testcase( pExpr->op==TK_ISNOT ); 5631 testcase( pExpr->op==TK_ISNULL ); 5632 testcase( pExpr->op==TK_NOTNULL ); 5633 testcase( pExpr->op==TK_IS ); 5634 testcase( pExpr->op==TK_OR ); 5635 testcase( pExpr->op==TK_VECTOR ); 5636 testcase( pExpr->op==TK_CASE ); 5637 testcase( pExpr->op==TK_IN ); 5638 testcase( pExpr->op==TK_FUNCTION ); 5639 testcase( pExpr->op==TK_TRUTH ); 5640 return WRC_Prune; 5641 case TK_COLUMN: 5642 if( pWalker->u.iCur==pExpr->iTable ){ 5643 pWalker->eCode = 1; 5644 return WRC_Abort; 5645 } 5646 return WRC_Prune; 5647 5648 case TK_AND: 5649 if( pWalker->eCode==0 ){ 5650 sqlite3WalkExpr(pWalker, pExpr->pLeft); 5651 if( pWalker->eCode ){ 5652 pWalker->eCode = 0; 5653 sqlite3WalkExpr(pWalker, pExpr->pRight); 5654 } 5655 } 5656 return WRC_Prune; 5657 5658 case TK_BETWEEN: 5659 if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){ 5660 assert( pWalker->eCode ); 5661 return WRC_Abort; 5662 } 5663 return WRC_Prune; 5664 5665 /* Virtual tables are allowed to use constraints like x=NULL. So 5666 ** a term of the form x=y does not prove that y is not null if x 5667 ** is the column of a virtual table */ 5668 case TK_EQ: 5669 case TK_NE: 5670 case TK_LT: 5671 case TK_LE: 5672 case TK_GT: 5673 case TK_GE: { 5674 Expr *pLeft = pExpr->pLeft; 5675 Expr *pRight = pExpr->pRight; 5676 testcase( pExpr->op==TK_EQ ); 5677 testcase( pExpr->op==TK_NE ); 5678 testcase( pExpr->op==TK_LT ); 5679 testcase( pExpr->op==TK_LE ); 5680 testcase( pExpr->op==TK_GT ); 5681 testcase( pExpr->op==TK_GE ); 5682 /* The y.pTab=0 assignment in wherecode.c always happens after the 5683 ** impliesNotNullRow() test */ 5684 if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0) 5685 && IsVirtual(pLeft->y.pTab)) 5686 || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0) 5687 && IsVirtual(pRight->y.pTab)) 5688 ){ 5689 return WRC_Prune; 5690 } 5691 /* no break */ deliberate_fall_through 5692 } 5693 default: 5694 return WRC_Continue; 5695 } 5696 } 5697 5698 /* 5699 ** Return true (non-zero) if expression p can only be true if at least 5700 ** one column of table iTab is non-null. In other words, return true 5701 ** if expression p will always be NULL or false if every column of iTab 5702 ** is NULL. 5703 ** 5704 ** False negatives are acceptable. In other words, it is ok to return 5705 ** zero even if expression p will never be true of every column of iTab 5706 ** is NULL. A false negative is merely a missed optimization opportunity. 5707 ** 5708 ** False positives are not allowed, however. A false positive may result 5709 ** in an incorrect answer. 5710 ** 5711 ** Terms of p that are marked with EP_FromJoin (and hence that come from 5712 ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis. 5713 ** 5714 ** This routine is used to check if a LEFT JOIN can be converted into 5715 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE 5716 ** clause requires that some column of the right table of the LEFT JOIN 5717 ** be non-NULL, then the LEFT JOIN can be safely converted into an 5718 ** ordinary join. 5719 */ 5720 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){ 5721 Walker w; 5722 p = sqlite3ExprSkipCollateAndLikely(p); 5723 if( p==0 ) return 0; 5724 if( p->op==TK_NOTNULL ){ 5725 p = p->pLeft; 5726 }else{ 5727 while( p->op==TK_AND ){ 5728 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1; 5729 p = p->pRight; 5730 } 5731 } 5732 w.xExprCallback = impliesNotNullRow; 5733 w.xSelectCallback = 0; 5734 w.xSelectCallback2 = 0; 5735 w.eCode = 0; 5736 w.u.iCur = iTab; 5737 sqlite3WalkExpr(&w, p); 5738 return w.eCode; 5739 } 5740 5741 /* 5742 ** An instance of the following structure is used by the tree walker 5743 ** to determine if an expression can be evaluated by reference to the 5744 ** index only, without having to do a search for the corresponding 5745 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur 5746 ** is the cursor for the table. 5747 */ 5748 struct IdxCover { 5749 Index *pIdx; /* The index to be tested for coverage */ 5750 int iCur; /* Cursor number for the table corresponding to the index */ 5751 }; 5752 5753 /* 5754 ** Check to see if there are references to columns in table 5755 ** pWalker->u.pIdxCover->iCur can be satisfied using the index 5756 ** pWalker->u.pIdxCover->pIdx. 5757 */ 5758 static int exprIdxCover(Walker *pWalker, Expr *pExpr){ 5759 if( pExpr->op==TK_COLUMN 5760 && pExpr->iTable==pWalker->u.pIdxCover->iCur 5761 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 5762 ){ 5763 pWalker->eCode = 1; 5764 return WRC_Abort; 5765 } 5766 return WRC_Continue; 5767 } 5768 5769 /* 5770 ** Determine if an index pIdx on table with cursor iCur contains will 5771 ** the expression pExpr. Return true if the index does cover the 5772 ** expression and false if the pExpr expression references table columns 5773 ** that are not found in the index pIdx. 5774 ** 5775 ** An index covering an expression means that the expression can be 5776 ** evaluated using only the index and without having to lookup the 5777 ** corresponding table entry. 5778 */ 5779 int sqlite3ExprCoveredByIndex( 5780 Expr *pExpr, /* The index to be tested */ 5781 int iCur, /* The cursor number for the corresponding table */ 5782 Index *pIdx /* The index that might be used for coverage */ 5783 ){ 5784 Walker w; 5785 struct IdxCover xcov; 5786 memset(&w, 0, sizeof(w)); 5787 xcov.iCur = iCur; 5788 xcov.pIdx = pIdx; 5789 w.xExprCallback = exprIdxCover; 5790 w.u.pIdxCover = &xcov; 5791 sqlite3WalkExpr(&w, pExpr); 5792 return !w.eCode; 5793 } 5794 5795 5796 /* 5797 ** An instance of the following structure is used by the tree walker 5798 ** to count references to table columns in the arguments of an 5799 ** aggregate function, in order to implement the 5800 ** sqlite3FunctionThisSrc() routine. 5801 */ 5802 struct SrcCount { 5803 SrcList *pSrc; /* One particular FROM clause in a nested query */ 5804 int iSrcInner; /* Smallest cursor number in this context */ 5805 int nThis; /* Number of references to columns in pSrcList */ 5806 int nOther; /* Number of references to columns in other FROM clauses */ 5807 }; 5808 5809 /* 5810 ** xSelect callback for sqlite3FunctionUsesThisSrc(). If this is the first 5811 ** SELECT with a FROM clause encountered during this iteration, set 5812 ** SrcCount.iSrcInner to the cursor number of the leftmost object in 5813 ** the FROM cause. 5814 */ 5815 static int selectSrcCount(Walker *pWalker, Select *pSel){ 5816 struct SrcCount *p = pWalker->u.pSrcCount; 5817 if( p->iSrcInner==0x7FFFFFFF && ALWAYS(pSel->pSrc) && pSel->pSrc->nSrc ){ 5818 pWalker->u.pSrcCount->iSrcInner = pSel->pSrc->a[0].iCursor; 5819 } 5820 return WRC_Continue; 5821 } 5822 5823 /* 5824 ** Count the number of references to columns. 5825 */ 5826 static int exprSrcCount(Walker *pWalker, Expr *pExpr){ 5827 /* There was once a NEVER() on the second term on the grounds that 5828 ** sqlite3FunctionUsesThisSrc() was always called before 5829 ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet 5830 ** been converted into TK_AGG_COLUMN. But this is no longer true due 5831 ** to window functions - sqlite3WindowRewrite() may now indirectly call 5832 ** FunctionUsesThisSrc() when creating a new sub-select. */ 5833 if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){ 5834 int i; 5835 struct SrcCount *p = pWalker->u.pSrcCount; 5836 SrcList *pSrc = p->pSrc; 5837 int nSrc = pSrc ? pSrc->nSrc : 0; 5838 for(i=0; i<nSrc; i++){ 5839 if( pExpr->iTable==pSrc->a[i].iCursor ) break; 5840 } 5841 if( i<nSrc ){ 5842 p->nThis++; 5843 }else if( pExpr->iTable<p->iSrcInner ){ 5844 /* In a well-formed parse tree (no name resolution errors), 5845 ** TK_COLUMN nodes with smaller Expr.iTable values are in an 5846 ** outer context. Those are the only ones to count as "other" */ 5847 p->nOther++; 5848 } 5849 } 5850 return WRC_Continue; 5851 } 5852 5853 /* 5854 ** Determine if any of the arguments to the pExpr Function reference 5855 ** pSrcList. Return true if they do. Also return true if the function 5856 ** has no arguments or has only constant arguments. Return false if pExpr 5857 ** references columns but not columns of tables found in pSrcList. 5858 */ 5859 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){ 5860 Walker w; 5861 struct SrcCount cnt; 5862 assert( pExpr->op==TK_AGG_FUNCTION ); 5863 memset(&w, 0, sizeof(w)); 5864 w.xExprCallback = exprSrcCount; 5865 w.xSelectCallback = selectSrcCount; 5866 w.u.pSrcCount = &cnt; 5867 cnt.pSrc = pSrcList; 5868 cnt.iSrcInner = (pSrcList&&pSrcList->nSrc)?pSrcList->a[0].iCursor:0x7FFFFFFF; 5869 cnt.nThis = 0; 5870 cnt.nOther = 0; 5871 sqlite3WalkExprList(&w, pExpr->x.pList); 5872 #ifndef SQLITE_OMIT_WINDOWFUNC 5873 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 5874 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter); 5875 } 5876 #endif 5877 return cnt.nThis>0 || cnt.nOther==0; 5878 } 5879 5880 /* 5881 ** This is a Walker expression node callback. 5882 ** 5883 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo 5884 ** object that is referenced does not refer directly to the Expr. If 5885 ** it does, make a copy. This is done because the pExpr argument is 5886 ** subject to change. 5887 ** 5888 ** The copy is stored on pParse->pConstExpr with a register number of 0. 5889 ** This will cause the expression to be deleted automatically when the 5890 ** Parse object is destroyed, but the zero register number means that it 5891 ** will not generate any code in the preamble. 5892 */ 5893 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){ 5894 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced)) 5895 && pExpr->pAggInfo!=0 5896 ){ 5897 AggInfo *pAggInfo = pExpr->pAggInfo; 5898 int iAgg = pExpr->iAgg; 5899 Parse *pParse = pWalker->pParse; 5900 sqlite3 *db = pParse->db; 5901 assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_AGG_FUNCTION ); 5902 if( pExpr->op==TK_AGG_COLUMN ){ 5903 assert( iAgg>=0 && iAgg<pAggInfo->nColumn ); 5904 if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){ 5905 pExpr = sqlite3ExprDup(db, pExpr, 0); 5906 if( pExpr ){ 5907 pAggInfo->aCol[iAgg].pCExpr = pExpr; 5908 sqlite3ExprDeferredDelete(pParse, pExpr); 5909 } 5910 } 5911 }else{ 5912 assert( iAgg>=0 && iAgg<pAggInfo->nFunc ); 5913 if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){ 5914 pExpr = sqlite3ExprDup(db, pExpr, 0); 5915 if( pExpr ){ 5916 pAggInfo->aFunc[iAgg].pFExpr = pExpr; 5917 sqlite3ExprDeferredDelete(pParse, pExpr); 5918 } 5919 } 5920 } 5921 } 5922 return WRC_Continue; 5923 } 5924 5925 /* 5926 ** Initialize a Walker object so that will persist AggInfo entries referenced 5927 ** by the tree that is walked. 5928 */ 5929 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){ 5930 memset(pWalker, 0, sizeof(*pWalker)); 5931 pWalker->pParse = pParse; 5932 pWalker->xExprCallback = agginfoPersistExprCb; 5933 pWalker->xSelectCallback = sqlite3SelectWalkNoop; 5934 } 5935 5936 /* 5937 ** Add a new element to the pAggInfo->aCol[] array. Return the index of 5938 ** the new element. Return a negative number if malloc fails. 5939 */ 5940 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ 5941 int i; 5942 pInfo->aCol = sqlite3ArrayAllocate( 5943 db, 5944 pInfo->aCol, 5945 sizeof(pInfo->aCol[0]), 5946 &pInfo->nColumn, 5947 &i 5948 ); 5949 return i; 5950 } 5951 5952 /* 5953 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of 5954 ** the new element. Return a negative number if malloc fails. 5955 */ 5956 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ 5957 int i; 5958 pInfo->aFunc = sqlite3ArrayAllocate( 5959 db, 5960 pInfo->aFunc, 5961 sizeof(pInfo->aFunc[0]), 5962 &pInfo->nFunc, 5963 &i 5964 ); 5965 return i; 5966 } 5967 5968 /* 5969 ** This is the xExprCallback for a tree walker. It is used to 5970 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates 5971 ** for additional information. 5972 */ 5973 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ 5974 int i; 5975 NameContext *pNC = pWalker->u.pNC; 5976 Parse *pParse = pNC->pParse; 5977 SrcList *pSrcList = pNC->pSrcList; 5978 AggInfo *pAggInfo = pNC->uNC.pAggInfo; 5979 5980 assert( pNC->ncFlags & NC_UAggInfo ); 5981 switch( pExpr->op ){ 5982 case TK_AGG_COLUMN: 5983 case TK_COLUMN: { 5984 testcase( pExpr->op==TK_AGG_COLUMN ); 5985 testcase( pExpr->op==TK_COLUMN ); 5986 /* Check to see if the column is in one of the tables in the FROM 5987 ** clause of the aggregate query */ 5988 if( ALWAYS(pSrcList!=0) ){ 5989 SrcItem *pItem = pSrcList->a; 5990 for(i=0; i<pSrcList->nSrc; i++, pItem++){ 5991 struct AggInfo_col *pCol; 5992 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 5993 if( pExpr->iTable==pItem->iCursor ){ 5994 /* If we reach this point, it means that pExpr refers to a table 5995 ** that is in the FROM clause of the aggregate query. 5996 ** 5997 ** Make an entry for the column in pAggInfo->aCol[] if there 5998 ** is not an entry there already. 5999 */ 6000 int k; 6001 pCol = pAggInfo->aCol; 6002 for(k=0; k<pAggInfo->nColumn; k++, pCol++){ 6003 if( pCol->iTable==pExpr->iTable && 6004 pCol->iColumn==pExpr->iColumn ){ 6005 break; 6006 } 6007 } 6008 if( (k>=pAggInfo->nColumn) 6009 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 6010 ){ 6011 pCol = &pAggInfo->aCol[k]; 6012 pCol->pTab = pExpr->y.pTab; 6013 pCol->iTable = pExpr->iTable; 6014 pCol->iColumn = pExpr->iColumn; 6015 pCol->iMem = ++pParse->nMem; 6016 pCol->iSorterColumn = -1; 6017 pCol->pCExpr = pExpr; 6018 if( pAggInfo->pGroupBy ){ 6019 int j, n; 6020 ExprList *pGB = pAggInfo->pGroupBy; 6021 struct ExprList_item *pTerm = pGB->a; 6022 n = pGB->nExpr; 6023 for(j=0; j<n; j++, pTerm++){ 6024 Expr *pE = pTerm->pExpr; 6025 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable && 6026 pE->iColumn==pExpr->iColumn ){ 6027 pCol->iSorterColumn = j; 6028 break; 6029 } 6030 } 6031 } 6032 if( pCol->iSorterColumn<0 ){ 6033 pCol->iSorterColumn = pAggInfo->nSortingColumn++; 6034 } 6035 } 6036 /* There is now an entry for pExpr in pAggInfo->aCol[] (either 6037 ** because it was there before or because we just created it). 6038 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that 6039 ** pAggInfo->aCol[] entry. 6040 */ 6041 ExprSetVVAProperty(pExpr, EP_NoReduce); 6042 pExpr->pAggInfo = pAggInfo; 6043 pExpr->op = TK_AGG_COLUMN; 6044 pExpr->iAgg = (i16)k; 6045 break; 6046 } /* endif pExpr->iTable==pItem->iCursor */ 6047 } /* end loop over pSrcList */ 6048 } 6049 return WRC_Prune; 6050 } 6051 case TK_AGG_FUNCTION: { 6052 if( (pNC->ncFlags & NC_InAggFunc)==0 6053 && pWalker->walkerDepth==pExpr->op2 6054 ){ 6055 /* Check to see if pExpr is a duplicate of another aggregate 6056 ** function that is already in the pAggInfo structure 6057 */ 6058 struct AggInfo_func *pItem = pAggInfo->aFunc; 6059 for(i=0; i<pAggInfo->nFunc; i++, pItem++){ 6060 if( pItem->pFExpr==pExpr ) break; 6061 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){ 6062 break; 6063 } 6064 } 6065 if( i>=pAggInfo->nFunc ){ 6066 /* pExpr is original. Make a new entry in pAggInfo->aFunc[] 6067 */ 6068 u8 enc = ENC(pParse->db); 6069 i = addAggInfoFunc(pParse->db, pAggInfo); 6070 if( i>=0 ){ 6071 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 6072 pItem = &pAggInfo->aFunc[i]; 6073 pItem->pFExpr = pExpr; 6074 pItem->iMem = ++pParse->nMem; 6075 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 6076 pItem->pFunc = sqlite3FindFunction(pParse->db, 6077 pExpr->u.zToken, 6078 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0); 6079 if( pExpr->flags & EP_Distinct ){ 6080 pItem->iDistinct = pParse->nTab++; 6081 }else{ 6082 pItem->iDistinct = -1; 6083 } 6084 } 6085 } 6086 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry 6087 */ 6088 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 6089 ExprSetVVAProperty(pExpr, EP_NoReduce); 6090 pExpr->iAgg = (i16)i; 6091 pExpr->pAggInfo = pAggInfo; 6092 return WRC_Prune; 6093 }else{ 6094 return WRC_Continue; 6095 } 6096 } 6097 } 6098 return WRC_Continue; 6099 } 6100 6101 /* 6102 ** Analyze the pExpr expression looking for aggregate functions and 6103 ** for variables that need to be added to AggInfo object that pNC->pAggInfo 6104 ** points to. Additional entries are made on the AggInfo object as 6105 ** necessary. 6106 ** 6107 ** This routine should only be called after the expression has been 6108 ** analyzed by sqlite3ResolveExprNames(). 6109 */ 6110 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ 6111 Walker w; 6112 w.xExprCallback = analyzeAggregate; 6113 w.xSelectCallback = sqlite3WalkerDepthIncrease; 6114 w.xSelectCallback2 = sqlite3WalkerDepthDecrease; 6115 w.walkerDepth = 0; 6116 w.u.pNC = pNC; 6117 w.pParse = 0; 6118 assert( pNC->pSrcList!=0 ); 6119 sqlite3WalkExpr(&w, pExpr); 6120 } 6121 6122 /* 6123 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an 6124 ** expression list. Return the number of errors. 6125 ** 6126 ** If an error is found, the analysis is cut short. 6127 */ 6128 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ 6129 struct ExprList_item *pItem; 6130 int i; 6131 if( pList ){ 6132 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ 6133 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); 6134 } 6135 } 6136 } 6137 6138 /* 6139 ** Allocate a single new register for use to hold some intermediate result. 6140 */ 6141 int sqlite3GetTempReg(Parse *pParse){ 6142 if( pParse->nTempReg==0 ){ 6143 return ++pParse->nMem; 6144 } 6145 return pParse->aTempReg[--pParse->nTempReg]; 6146 } 6147 6148 /* 6149 ** Deallocate a register, making available for reuse for some other 6150 ** purpose. 6151 */ 6152 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ 6153 if( iReg ){ 6154 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0); 6155 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){ 6156 pParse->aTempReg[pParse->nTempReg++] = iReg; 6157 } 6158 } 6159 } 6160 6161 /* 6162 ** Allocate or deallocate a block of nReg consecutive registers. 6163 */ 6164 int sqlite3GetTempRange(Parse *pParse, int nReg){ 6165 int i, n; 6166 if( nReg==1 ) return sqlite3GetTempReg(pParse); 6167 i = pParse->iRangeReg; 6168 n = pParse->nRangeReg; 6169 if( nReg<=n ){ 6170 pParse->iRangeReg += nReg; 6171 pParse->nRangeReg -= nReg; 6172 }else{ 6173 i = pParse->nMem+1; 6174 pParse->nMem += nReg; 6175 } 6176 return i; 6177 } 6178 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ 6179 if( nReg==1 ){ 6180 sqlite3ReleaseTempReg(pParse, iReg); 6181 return; 6182 } 6183 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0); 6184 if( nReg>pParse->nRangeReg ){ 6185 pParse->nRangeReg = nReg; 6186 pParse->iRangeReg = iReg; 6187 } 6188 } 6189 6190 /* 6191 ** Mark all temporary registers as being unavailable for reuse. 6192 ** 6193 ** Always invoke this procedure after coding a subroutine or co-routine 6194 ** that might be invoked from other parts of the code, to ensure that 6195 ** the sub/co-routine does not use registers in common with the code that 6196 ** invokes the sub/co-routine. 6197 */ 6198 void sqlite3ClearTempRegCache(Parse *pParse){ 6199 pParse->nTempReg = 0; 6200 pParse->nRangeReg = 0; 6201 } 6202 6203 /* 6204 ** Validate that no temporary register falls within the range of 6205 ** iFirst..iLast, inclusive. This routine is only call from within assert() 6206 ** statements. 6207 */ 6208 #ifdef SQLITE_DEBUG 6209 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ 6210 int i; 6211 if( pParse->nRangeReg>0 6212 && pParse->iRangeReg+pParse->nRangeReg > iFirst 6213 && pParse->iRangeReg <= iLast 6214 ){ 6215 return 0; 6216 } 6217 for(i=0; i<pParse->nTempReg; i++){ 6218 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){ 6219 return 0; 6220 } 6221 } 6222 return 1; 6223 } 6224 #endif /* SQLITE_DEBUG */ 6225