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