Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/src/expr.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / src / expr.c` 7902 lines ยท 275861 bytes Raw Blame History 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(const Table *pTab, int iCol){ 25 if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER; 26 return pTab->aCol[iCol].affinity; 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 op = pExpr->op; 48 while( 1 /* exit-by-break */ ){ 49 if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){ 50 assert( ExprUseYTab(pExpr) ); 51 assert( pExpr->y.pTab!=0 ); 52 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 53 } 54 if( op==TK_SELECT ){ 55 assert( ExprUseXSelect(pExpr) ); 56 assert( pExpr->x.pSelect!=0 ); 57 assert( pExpr->x.pSelect->pEList!=0 ); 58 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 ); 59 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); 60 } 61 #ifndef SQLITE_OMIT_CAST 62 if( op==TK_CAST ){ 63 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 64 return sqlite3AffinityType(pExpr->u.zToken, 0); 65 } 66 #endif 67 if( op==TK_SELECT_COLUMN ){ 68 assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) ); 69 assert( pExpr->iColumn < pExpr->iTable ); 70 assert( pExpr->iColumn >= 0 ); 71 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr ); 72 return sqlite3ExprAffinity( 73 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr 74 ); 75 } 76 if( op==TK_VECTOR 77 || (op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER) 78 ){ 79 assert( ExprUseXList(pExpr) ); 80 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr); 81 } 82 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){ 83 assert( pExpr->op==TK_COLLATE 84 || pExpr->op==TK_IF_NULL_ROW 85 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) ); 86 pExpr = pExpr->pLeft; 87 op = pExpr->op; 88 continue; 89 } 90 if( op!=TK_REGISTER ) break; 91 op = pExpr->op2; 92 if( NEVER( op==TK_REGISTER ) ) break; 93 } 94 return pExpr->affExpr; 95 } 96 97 /* 98 ** Make a guess at all the possible datatypes of the result that could 99 ** be returned by an expression. Return a bitmask indicating the answer: 100 ** 101 ** 0x01 Numeric 102 ** 0x02 Text 103 ** 0x04 Blob 104 ** 105 ** If the expression must return NULL, then 0x00 is returned. 106 */ 107 int sqlite3ExprDataType(const Expr *pExpr){ 108 while( pExpr ){ 109 switch( pExpr->op ){ 110 case TK_COLLATE: 111 case TK_IF_NULL_ROW: 112 case TK_UPLUS: { 113 pExpr = pExpr->pLeft; 114 break; 115 } 116 case TK_NULL: { 117 pExpr = 0; 118 break; 119 } 120 case TK_STRING: { 121 return 0x02; 122 } 123 case TK_BLOB: { 124 return 0x04; 125 } 126 case TK_CONCAT: { 127 return 0x06; 128 } 129 case TK_VARIABLE: 130 case TK_AGG_FUNCTION: 131 case TK_FUNCTION: { 132 return 0x07; 133 } 134 case TK_COLUMN: 135 case TK_AGG_COLUMN: 136 case TK_SELECT: 137 case TK_CAST: 138 case TK_SELECT_COLUMN: 139 case TK_VECTOR: { 140 int aff = sqlite3ExprAffinity(pExpr); 141 if( aff>=SQLITE_AFF_NUMERIC ) return 0x05; 142 if( aff==SQLITE_AFF_TEXT ) return 0x06; 143 return 0x07; 144 } 145 case TK_CASE: { 146 int res = 0; 147 int ii; 148 ExprList *pList = pExpr->x.pList; 149 assert( ExprUseXList(pExpr) && pList!=0 ); 150 assert( pList->nExpr > 0); 151 for(ii=1; iinExpr; ii+=2){ 152 res |= sqlite3ExprDataType(pList->a[ii].pExpr); 153 } 154 if( pList->nExpr % 2 ){ 155 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr); 156 } 157 return res; 158 } 159 default: { 160 return 0x01; 161 } 162 } /* End of switch(op) */ 163 } /* End of while(pExpr) */ 164 return 0x00; 165 } 166 167 /* 168 ** Set the collating sequence for expression pExpr to be the collating 169 ** sequence named by pToken. Return a pointer to a new Expr node that 170 ** implements the COLLATE operator. 171 ** 172 ** If a memory allocation error occurs, that fact is recorded in pParse->db 173 ** and the pExpr parameter is returned unchanged. 174 */ 175 Expr *sqlite3ExprAddCollateToken( 176 Parse *pParse, /* Parsing context */ 177 Expr *pExpr, /* Add the "COLLATE" clause to this expression */ 178 const Token *pCollName, /* Name of collating sequence */ 179 int dequote /* True to dequote pCollName */ 180 ){ 181 if( pCollName->n>0 && pParse->nErr==0 ){ 182 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); 183 assert( pExpr!=0 ); 184 if( pNew ){ 185 pNew->pLeft = pExpr; 186 pNew->flags |= EP_Collate|EP_Skip; 187 #if SQLITE_MAX_EXPR_DEPTH>0 188 pNew->nHeight = pExpr->nHeight+1; 189 sqlite3ExprCheckHeight(pParse, pNew->nHeight); 190 testcase( pParse->nErr>0 ); 191 #endif 192 pExpr = pNew; 193 } 194 } 195 return pExpr; 196 } 197 Expr *sqlite3ExprAddCollateString( 198 Parse *pParse, /* Parsing context */ 199 Expr *pExpr, /* Add the "COLLATE" clause to this expression */ 200 const char *zC /* The collating sequence name */ 201 ){ 202 Token s; 203 assert( zC!=0 ); 204 sqlite3TokenInit(&s, (char*)zC); 205 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); 206 } 207 208 /* 209 ** Skip over any TK_COLLATE operators. 210 */ 211 Expr *sqlite3ExprSkipCollate(Expr *pExpr){ 212 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ 213 assert( pExpr->op==TK_COLLATE ); 214 pExpr = pExpr->pLeft; 215 } 216 return pExpr; 217 } 218 219 /* 220 ** Skip over any TK_COLLATE operators and/or any unlikely() 221 ** or likelihood() or likely() functions at the root of an 222 ** expression. 223 */ 224 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){ 225 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){ 226 if( ExprHasProperty(pExpr, EP_Unlikely) ){ 227 assert( ExprUseXList(pExpr) ); 228 assert( pExpr->x.pList->nExpr>0 ); 229 assert( pExpr->op==TK_FUNCTION ); 230 pExpr = pExpr->x.pList->a[0].pExpr; 231 }else if( pExpr->op==TK_COLLATE ){ 232 pExpr = pExpr->pLeft; 233 }else{ 234 break; 235 } 236 } 237 return pExpr; 238 } 239 240 /* 241 ** Return the collation sequence for the expression pExpr. If 242 ** there is no defined collating sequence, return NULL. 243 ** 244 ** See also: sqlite3ExprNNCollSeq() 245 ** 246 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the 247 ** default collation if pExpr has no defined collation. 248 ** 249 ** The collating sequence might be determined by a COLLATE operator 250 ** or by the presence of a column with a defined collating sequence. 251 ** COLLATE operators take first precedence. Left operands take 252 ** precedence over right operands. 253 */ 254 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){ 255 sqlite3 *db = pParse->db; 256 CollSeq *pColl = 0; 257 const Expr *p = pExpr; 258 while( p ){ 259 int op = p->op; 260 if( op==TK_REGISTER ) op = p->op2; 261 if( (op==TK_AGG_COLUMN && p->y.pTab!=0) 262 || op==TK_COLUMN || op==TK_TRIGGER 263 ){ 264 int j; 265 assert( ExprUseYTab(p) ); 266 assert( p->y.pTab!=0 ); 267 if( (j = p->iColumn)>=0 ){ 268 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]); 269 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 270 } 271 break; 272 } 273 if( op==TK_CAST || op==TK_UPLUS ){ 274 p = p->pLeft; 275 continue; 276 } 277 if( op==TK_VECTOR 278 || (op==TK_FUNCTION && p->affExpr==SQLITE_AFF_DEFER) 279 ){ 280 assert( ExprUseXList(p) ); 281 p = p->x.pList->a[0].pExpr; 282 continue; 283 } 284 if( op==TK_COLLATE ){ 285 assert( !ExprHasProperty(p, EP_IntValue) ); 286 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); 287 break; 288 } 289 if( p->flags & EP_Collate ){ 290 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ 291 p = p->pLeft; 292 }else{ 293 Expr *pNext = p->pRight; 294 /* The Expr.x union is never used at the same time as Expr.pRight */ 295 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 ); 296 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){ 297 int i; 298 for(i=0; ix.pList->nExpr; i++){ 299 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ 300 pNext = p->x.pList->a[i].pExpr; 301 break; 302 } 303 } 304 } 305 p = pNext; 306 } 307 }else{ 308 break; 309 } 310 } 311 if( sqlite3CheckCollSeq(pParse, pColl) ){ 312 pColl = 0; 313 } 314 return pColl; 315 } 316 317 /* 318 ** Return the collation sequence for the expression pExpr. If 319 ** there is no defined collating sequence, return a pointer to the 320 ** default collation sequence. 321 ** 322 ** See also: sqlite3ExprCollSeq() 323 ** 324 ** The sqlite3ExprCollSeq() routine works the same except that it 325 ** returns NULL if there is no defined collation. 326 */ 327 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){ 328 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr); 329 if( p==0 ) p = pParse->db->pDfltColl; 330 assert( p!=0 ); 331 return p; 332 } 333 334 /* 335 ** Return TRUE if the two expressions have equivalent collating sequences. 336 */ 337 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){ 338 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1); 339 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2); 340 assert( (pColl1==pColl2) == 341 (sqlite3_stricmp(pColl1->zName,pColl2->zName)==0) ); 342 return pColl1==pColl2; 343 } 344 345 /* 346 ** pExpr is an operand of a comparison operator. aff2 is the 347 ** type affinity of the other operand. This routine returns the 348 ** type affinity that should be used for the comparison operator. 349 */ 350 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){ 351 char aff1 = sqlite3ExprAffinity(pExpr); 352 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){ 353 /* Both sides of the comparison are columns. If one has numeric 354 ** affinity, use that. Otherwise use no affinity. 355 */ 356 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ 357 return SQLITE_AFF_NUMERIC; 358 }else{ 359 return SQLITE_AFF_BLOB; 360 } 361 }else{ 362 /* One side is a column, the other is not. Use the columns affinity. */ 363 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE ); 364 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE; 365 } 366 } 367 368 /* 369 ** pExpr is a comparison operator. Return the type affinity that should 370 ** be applied to both operands prior to doing the comparison. 371 */ 372 static char comparisonAffinity(const Expr *pExpr){ 373 char aff; 374 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || 375 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || 376 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); 377 assert( pExpr->pLeft ); 378 assert( !ExprUseXSelect(pExpr) ); 379 aff = sqlite3ExprAffinity(pExpr->pLeft); 380 if( pExpr->pRight ){ 381 aff = sqlite3CompareAffinity(pExpr->pRight, aff); 382 }else if( aff==0 ){ 383 aff = SQLITE_AFF_BLOB; 384 } 385 return aff; 386 } 387 388 /* 389 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. 390 ** idx_affinity is the affinity of an indexed column. Return true 391 ** if the index with affinity idx_affinity may be used to implement 392 ** the comparison in pExpr. 393 */ 394 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){ 395 char aff = comparisonAffinity(pExpr); 396 if( affflags & EP_Collate ){ 439 pColl = sqlite3ExprCollSeq(pParse, pLeft); 440 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ 441 pColl = sqlite3ExprCollSeq(pParse, pRight); 442 }else{ 443 pColl = sqlite3ExprCollSeq(pParse, pLeft); 444 if( !pColl ){ 445 pColl = sqlite3ExprCollSeq(pParse, pRight); 446 } 447 } 448 return pColl; 449 } 450 451 /* Expression p is a comparison operator. Return a collation sequence 452 ** appropriate for the comparison operator. 453 ** 454 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq(). 455 ** However, if the OP_Commuted flag is set, then the order of the operands 456 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the 457 ** correct collating sequence is found. 458 */ 459 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){ 460 if( ExprHasProperty(p, EP_Commuted) ){ 461 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft); 462 }else{ 463 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight); 464 } 465 } 466 467 /* 468 ** Generate code for a comparison operator. 469 */ 470 static int codeCompare( 471 Parse *pParse, /* The parsing (and code generating) context */ 472 Expr *pLeft, /* The left operand */ 473 Expr *pRight, /* The right operand */ 474 int opcode, /* The comparison opcode */ 475 int in1, int in2, /* Register holding operands */ 476 int dest, /* Jump here if true. */ 477 int jumpIfNull, /* If true, jump if either operand is NULL */ 478 int isCommuted /* The comparison has been commuted */ 479 ){ 480 int p5; 481 int addr; 482 CollSeq *p4; 483 484 if( pParse->nErr ) return 0; 485 if( isCommuted ){ 486 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft); 487 }else{ 488 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); 489 } 490 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); 491 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, 492 (void*)p4, P4_COLLSEQ); 493 sqlite3VdbeChangeP5(pParse->pVdbe, (u16)p5); 494 return addr; 495 } 496 497 /* 498 ** Return true if expression pExpr is a vector, or false otherwise. 499 ** 500 ** A vector is defined as any expression that results in two or more 501 ** columns of result. Every TK_VECTOR node is an vector because the 502 ** parser will not generate a TK_VECTOR with fewer than two entries. 503 ** But a TK_SELECT might be either a vector or a scalar. It is only 504 ** considered a vector if it has two or more result columns. 505 */ 506 int sqlite3ExprIsVector(const Expr *pExpr){ 507 return sqlite3ExprVectorSize(pExpr)>1; 508 } 509 510 /* 511 ** If the expression passed as the only argument is of type TK_VECTOR 512 ** return the number of expressions in the vector. Or, if the expression 513 ** is a sub-select, return the number of columns in the sub-select. For 514 ** any other type of expression, return 1. 515 */ 516 int sqlite3ExprVectorSize(const Expr *pExpr){ 517 u8 op = pExpr->op; 518 if( op==TK_REGISTER ) op = pExpr->op2; 519 if( op==TK_VECTOR ){ 520 assert( ExprUseXList(pExpr) ); 521 return pExpr->x.pList->nExpr; 522 }else if( op==TK_SELECT ){ 523 assert( ExprUseXSelect(pExpr) ); 524 return pExpr->x.pSelect->pEList->nExpr; 525 }else{ 526 return 1; 527 } 528 } 529 530 /* 531 ** Return a pointer to a subexpression of pVector that is the i-th 532 ** column of the vector (numbered starting with 0). The caller must 533 ** ensure that i is within range. 534 ** 535 ** If pVector is really a scalar (and "scalar" here includes subqueries 536 ** that return a single column!) then return pVector unmodified. 537 ** 538 ** pVector retains ownership of the returned subexpression. 539 ** 540 ** If the vector is a (SELECT ...) then the expression returned is 541 ** just the expression for the i-th term of the result set, and may 542 ** not be ready for evaluation because the table cursor has not yet 543 ** been positioned. 544 */ 545 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ 546 assert( iop==TK_ERROR ); 547 if( sqlite3ExprIsVector(pVector) ){ 548 assert( pVector->op2==0 || pVector->op==TK_REGISTER ); 549 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ 550 assert( ExprUseXSelect(pVector) ); 551 return pVector->x.pSelect->pEList->a[i].pExpr; 552 }else{ 553 assert( ExprUseXList(pVector) ); 554 return pVector->x.pList->a[i].pExpr; 555 } 556 } 557 return pVector; 558 } 559 560 /* 561 ** Compute and return a new Expr object which when passed to 562 ** sqlite3ExprCode() will generate all necessary code to compute 563 ** the iField-th column of the vector expression pVector. 564 ** 565 ** It is ok for pVector to be a scalar (as long as iField==0). 566 ** In that case, this routine works like sqlite3ExprDup(). 567 ** 568 ** The caller owns the returned Expr object and is responsible for 569 ** ensuring that the returned value eventually gets freed. 570 ** 571 ** The caller retains ownership of pVector. If pVector is a TK_SELECT, 572 ** then the returned object will reference pVector and so pVector must remain 573 ** valid for the life of the returned object. If pVector is a TK_VECTOR 574 ** or a scalar expression, then it can be deleted as soon as this routine 575 ** returns. 576 ** 577 ** A trick to cause a TK_SELECT pVector to be deleted together with 578 ** the returned Expr object is to attach the pVector to the pRight field 579 ** of the returned TK_SELECT_COLUMN Expr object. 580 */ 581 Expr *sqlite3ExprForVectorField( 582 Parse *pParse, /* Parsing context */ 583 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ 584 int iField, /* Which column of the vector to return */ 585 int nField /* Total number of columns in the vector */ 586 ){ 587 Expr *pRet; 588 if( pVector->op==TK_SELECT ){ 589 assert( ExprUseXSelect(pVector) ); 590 /* The TK_SELECT_COLUMN Expr node: 591 ** 592 ** pLeft: pVector containing TK_SELECT. Not deleted. 593 ** pRight: not used. But recursively deleted. 594 ** iColumn: Index of a column in pVector 595 ** iTable: 0 or the number of columns on the LHS of an assignment 596 ** pLeft->iTable: First in an array of register holding result, or 0 597 ** if the result is not yet computed. 598 ** 599 ** sqlite3ExprDelete() specifically skips the recursive delete of 600 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector 601 ** can be attached to pRight to cause this node to take ownership of 602 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes 603 ** with the same pLeft pointer to the pVector, but only one of them 604 ** will own the pVector. 605 */ 606 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0); 607 if( pRet ){ 608 ExprSetProperty(pRet, EP_FullSize); 609 pRet->iTable = nField; 610 pRet->iColumn = iField; 611 pRet->pLeft = pVector; 612 } 613 }else{ 614 if( pVector->op==TK_VECTOR ){ 615 Expr **ppVector; 616 assert( ExprUseXList(pVector) ); 617 ppVector = &pVector->x.pList->a[iField].pExpr; 618 pVector = *ppVector; 619 if( IN_RENAME_OBJECT ){ 620 /* This must be a vector UPDATE inside a trigger */ 621 *ppVector = 0; 622 return pVector; 623 } 624 } 625 pRet = sqlite3ExprDup(pParse->db, pVector, 0); 626 } 627 return pRet; 628 } 629 630 /* 631 ** If expression pExpr is of type TK_SELECT, generate code to evaluate 632 ** it. Return the register in which the result is stored (or, if the 633 ** sub-select returns more than one column, the first in an array 634 ** of registers in which the result is stored). 635 ** 636 ** If pExpr is not a TK_SELECT expression, return 0. 637 */ 638 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ 639 int reg = 0; 640 #ifndef SQLITE_OMIT_SUBQUERY 641 if( pExpr->op==TK_SELECT ){ 642 reg = sqlite3CodeSubselect(pParse, pExpr); 643 } 644 #endif 645 return reg; 646 } 647 648 /* 649 ** Argument pVector points to a vector expression - either a TK_VECTOR 650 ** or TK_SELECT that returns more than one column. This function returns 651 ** the register number of a register that contains the value of 652 ** element iField of the vector. 653 ** 654 ** If pVector is a TK_SELECT expression, then code for it must have 655 ** already been generated using the exprCodeSubselect() routine. In this 656 ** case parameter regSelect should be the first in an array of registers 657 ** containing the results of the sub-select. 658 ** 659 ** If pVector is of type TK_VECTOR, then code for the requested field 660 ** is generated. In this case (*pRegFree) may be set to the number of 661 ** a temporary register to be freed by the caller before returning. 662 ** 663 ** Before returning, output parameter (*ppExpr) is set to point to the 664 ** Expr object corresponding to element iElem of the vector. 665 */ 666 static int exprVectorRegister( 667 Parse *pParse, /* Parse context */ 668 Expr *pVector, /* Vector to extract element from */ 669 int iField, /* Field to extract from pVector */ 670 int regSelect, /* First in array of registers */ 671 Expr *pTmp, /* Temporary space */ 672 Expr **ppExpr, /* OUT: Expression element */ 673 int *pRegFree /* OUT: Temp register to free */ 674 ){ 675 u8 op = pVector->op; 676 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR ); 677 if( op==TK_REGISTER ){ 678 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); 679 return pVector->iTable+iField; 680 } 681 if( op==TK_SELECT ){ 682 assert( ExprUseXSelect(pVector) ); 683 /* Use the temporary expression node to wrap expression iField of the 684 ** sub-select in a TK_SELECT_COLUMN node. This causes the caller to 685 ** use the affinity of the expression in any comparison, but not the 686 ** collation sequence. */ 687 memset(pTmp, 0, sizeof(Expr)); 688 pTmp->op = TK_SELECT_COLUMN; 689 pTmp->pLeft = pVector; 690 pTmp->iColumn = iField; 691 pTmp->iTable = pVector->x.pSelect->pEList->nExpr; 692 *ppExpr = pTmp; 693 return regSelect+iField; 694 } 695 if( op==TK_VECTOR ){ 696 assert( ExprUseXList(pVector) ); 697 *ppExpr = pVector->x.pList->a[iField].pExpr; 698 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); 699 } 700 return 0; 701 } 702 703 /* 704 ** Expression pExpr is a comparison between two vector values. Compute 705 ** the result of the comparison (1, 0, or NULL) and write that 706 ** result into register dest. 707 ** 708 ** The caller must satisfy the following preconditions: 709 ** 710 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ 711 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ 712 ** otherwise: op==pExpr->op and p5==0 713 */ 714 static void codeVectorCompare( 715 Parse *pParse, /* Code generator context */ 716 Expr *pExpr, /* The comparison operation */ 717 int dest, /* Write results into this register */ 718 u8 op, /* Comparison operator */ 719 u8 p5 /* SQLITE_NULLEQ or zero */ 720 ){ 721 Vdbe *v = pParse->pVdbe; 722 Expr *pLeft = pExpr->pLeft; 723 Expr *pRight = pExpr->pRight; 724 int nLeft = sqlite3ExprVectorSize(pLeft); 725 int i; 726 int regLeft = 0; 727 int regRight = 0; 728 u8 opx = op; 729 int addrCmp = 0; 730 int addrDone = sqlite3VdbeMakeLabel(pParse); 731 int isCommuted = ExprHasProperty(pExpr,EP_Commuted); 732 733 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 734 if( pParse->nErr ) return; 735 if( nLeft!=sqlite3ExprVectorSize(pRight) ){ 736 sqlite3ErrorMsg(pParse, "row value misused"); 737 return; 738 } 739 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 740 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 741 || pExpr->op==TK_LT || pExpr->op==TK_GT 742 || pExpr->op==TK_LE || pExpr->op==TK_GE 743 ); 744 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ) 745 || (pExpr->op==TK_ISNOT && op==TK_NE) ); 746 assert( p5==0 || pExpr->op!=op ); 747 assert( p5==SQLITE_NULLEQ || pExpr->op==op ); 748 749 if( op==TK_LE ) opx = TK_LT; 750 if( op==TK_GE ) opx = TK_GT; 751 if( op==TK_NE ) opx = TK_EQ; 752 753 regLeft = exprCodeSubselect(pParse, pLeft); 754 regRight = exprCodeSubselect(pParse, pRight); 755 756 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest); 757 for(i=0; 1 /*Loop exits by "break"*/; i++){ 758 int regFree1 = 0, regFree2 = 0; 759 Expr *pL = 0, *pR = 0; 760 Expr tmp1, tmp2; 761 int r1, r2; 762 assert( i>=0 && i0 805 /* 806 ** Check that argument nHeight is less than or equal to the maximum 807 ** expression depth allowed. If it is not, leave an error message in 808 ** pParse. 809 */ 810 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ 811 int rc = SQLITE_OK; 812 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; 813 if( nHeight>mxHeight ){ 814 sqlite3ErrorMsg(pParse, 815 "Expression tree is too large (maximum depth %d)", mxHeight 816 ); 817 rc = SQLITE_ERROR; 818 } 819 return rc; 820 } 821 822 /* The following three functions, heightOfExpr(), heightOfExprList() 823 ** and heightOfSelect(), are used to determine the maximum height 824 ** of any expression tree referenced by the structure passed as the 825 ** first argument. 826 ** 827 ** If this maximum height is greater than the current value pointed 828 ** to by pnHeight, the second parameter, then set *pnHeight to that 829 ** value. 830 */ 831 static void heightOfExpr(const Expr *p, int *pnHeight){ 832 if( p ){ 833 if( p->nHeight>*pnHeight ){ 834 *pnHeight = p->nHeight; 835 } 836 } 837 } 838 static void heightOfExprList(const ExprList *p, int *pnHeight){ 839 if( p ){ 840 int i; 841 for(i=0; inExpr; i++){ 842 heightOfExpr(p->a[i].pExpr, pnHeight); 843 } 844 } 845 } 846 static void heightOfSelect(const Select *pSelect, int *pnHeight){ 847 const Select *p; 848 for(p=pSelect; p; p=p->pPrior){ 849 heightOfExpr(p->pWhere, pnHeight); 850 heightOfExpr(p->pHaving, pnHeight); 851 heightOfExpr(p->pLimit, pnHeight); 852 heightOfExprList(p->pEList, pnHeight); 853 heightOfExprList(p->pGroupBy, pnHeight); 854 heightOfExprList(p->pOrderBy, pnHeight); 855 } 856 } 857 858 /* 859 ** Set the Expr.nHeight variable in the structure passed as an 860 ** argument. An expression with no children, Expr.pList or 861 ** Expr.pSelect member has a height of 1. Any other expression 862 ** has a height equal to the maximum height of any other 863 ** referenced Expr plus one. 864 ** 865 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags, 866 ** if appropriate. 867 */ 868 static void exprSetHeight(Expr *p){ 869 int nHeight = p->pLeft ? p->pLeft->nHeight : 0; 870 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){ 871 nHeight = p->pRight->nHeight; 872 } 873 if( ExprUseXSelect(p) ){ 874 heightOfSelect(p->x.pSelect, &nHeight); 875 }else if( p->x.pList ){ 876 heightOfExprList(p->x.pList, &nHeight); 877 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 878 } 879 p->nHeight = nHeight + 1; 880 } 881 882 /* 883 ** Set the Expr.nHeight variable using the exprSetHeight() function. If 884 ** the height is greater than the maximum allowed expression depth, 885 ** leave an error in pParse. 886 ** 887 ** Also propagate all EP_Propagate flags from the Expr.x.pList into 888 ** Expr.flags. 889 */ 890 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 891 if( pParse->nErr ) return; 892 exprSetHeight(p); 893 sqlite3ExprCheckHeight(pParse, p->nHeight); 894 } 895 896 /* 897 ** Return the maximum height of any expression tree referenced 898 ** by the select statement passed as an argument. 899 */ 900 int sqlite3SelectExprHeight(const Select *p){ 901 int nHeight = 0; 902 heightOfSelect(p, &nHeight); 903 return nHeight; 904 } 905 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */ 906 /* 907 ** Propagate all EP_Propagate flags from the Expr.x.pList into 908 ** Expr.flags. 909 */ 910 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 911 if( pParse->nErr ) return; 912 if( p && ExprUseXList(p) && p->x.pList ){ 913 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 914 } 915 } 916 #define exprSetHeight(y) 917 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */ 918 919 /* 920 ** Set the error offset for an Expr node, if possible. 921 */ 922 void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){ 923 if( pExpr==0 ) return; 924 if( NEVER(ExprUseWJoin(pExpr)) ) return; 925 pExpr->w.iOfst = iOfst; 926 } 927 928 /* 929 ** This routine is the core allocator for Expr nodes. 930 ** 931 ** Construct a new expression node and return a pointer to it. Memory 932 ** for this node and for the pToken argument is a single allocation 933 ** obtained from sqlite3DbMalloc(). The calling function 934 ** is responsible for making sure the node eventually gets freed. 935 ** 936 ** If dequote is true, then the token (if it exists) is dequoted. 937 ** If dequote is false, no dequoting is performed. The deQuote 938 ** parameter is ignored if pToken is NULL or if the token does not 939 ** appear to be quoted. If the quotes were of the form "..." (double-quotes) 940 ** then the EP_DblQuoted flag is set on the expression node. 941 ** 942 ** Special case (tag-`20240227`-a): If op==TK_INTEGER and pToken points to 943 ** a string that can be translated into a 32-bit integer, then the token is 944 ** not stored in u.zToken. Instead, the integer values is written 945 ** into u.iValue and the EP_IntValue flag is set. No extra storage 946 ** is allocated to hold the integer text and the dequote flag is ignored. 947 ** See also tag-`20240227`-b. 948 */ 949 Expr *sqlite3ExprAlloc( 950 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ 951 int op, /* Expression opcode */ 952 const Token *pToken, /* Token argument. Might be NULL */ 953 int dequote /* True to dequote */ 954 ){ 955 Expr *pNew; 956 int nExtra = pToken ? pToken->n+1 : 0; 957 958 assert( db!=0 ); 959 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); 960 if( pNew ){ 961 memset(pNew, 0, sizeof(Expr)); 962 pNew->op = (u8)op; 963 pNew->iAgg = -1; 964 if( nExtra ){ 965 assert( pToken!=0 ); 966 pNew->u.zToken = (char*)&pNew[1]; 967 assert( pToken->z!=0 || pToken->n==0 ); 968 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); 969 pNew->u.zToken[pToken->n] = 0; 970 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ 971 sqlite3DequoteExpr(pNew); 972 } 973 } 974 #if SQLITE_MAX_EXPR_DEPTH>0 975 pNew->nHeight = 1; 976 #endif 977 } 978 return pNew; 979 } 980 981 /* 982 ** Allocate a new expression node from a zero-terminated token that has 983 ** already been dequoted. 984 */ 985 Expr *sqlite3Expr( 986 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ 987 int op, /* Expression opcode */ 988 const char *zToken /* Token argument. Might be NULL */ 989 ){ 990 Token x; 991 x.z = zToken; 992 x.n = sqlite3Strlen30(zToken); 993 return sqlite3ExprAlloc(db, op, &x, 0); 994 } 995 996 /* 997 ** Allocate an expression for a 32-bit signed integer literal. 998 */ 999 Expr *sqlite3ExprInt32(sqlite3 *db, int iVal){ 1000 Expr *pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)); 1001 if( pNew ){ 1002 memset(pNew, 0, sizeof(Expr)); 1003 pNew->op = TK_INTEGER; 1004 pNew->iAgg = -1; 1005 pNew->flags = EP_IntValue|EP_Leaf|(iVal?EP_IsTrue:EP_IsFalse); 1006 pNew->u.iValue = iVal; 1007 #if SQLITE_MAX_EXPR_DEPTH>0 1008 pNew->nHeight = 1; 1009 #endif 1010 } 1011 return pNew; 1012 } 1013 1014 /* 1015 ** Attach subtrees pLeft and pRight to the Expr node pRoot. 1016 ** 1017 ** If pRoot==NULL that means that a memory allocation error has occurred. 1018 ** In that case, delete the subtrees pLeft and pRight. 1019 */ 1020 void sqlite3ExprAttachSubtrees( 1021 sqlite3 *db, 1022 Expr *pRoot, 1023 Expr *pLeft, 1024 Expr *pRight 1025 ){ 1026 if( pRoot==0 ){ 1027 assert( db->mallocFailed ); 1028 sqlite3ExprDelete(db, pLeft); 1029 sqlite3ExprDelete(db, pRight); 1030 }else{ 1031 assert( ExprUseXList(pRoot) ); 1032 assert( pRoot->x.pSelect==0 ); 1033 if( pRight ){ 1034 pRoot->pRight = pRight; 1035 pRoot->flags |= EP_Propagate & pRight->flags; 1036 #if SQLITE_MAX_EXPR_DEPTH>0 1037 pRoot->nHeight = pRight->nHeight+1; 1038 }else{ 1039 pRoot->nHeight = 1; 1040 #endif 1041 } 1042 if( pLeft ){ 1043 pRoot->pLeft = pLeft; 1044 pRoot->flags |= EP_Propagate & pLeft->flags; 1045 #if SQLITE_MAX_EXPR_DEPTH>0 1046 if( pLeft->nHeight>=pRoot->nHeight ){ 1047 pRoot->nHeight = pLeft->nHeight+1; 1048 } 1049 #endif 1050 } 1051 } 1052 } 1053 1054 /* 1055 ** Allocate an Expr node which joins as many as two subtrees. 1056 ** 1057 ** One or both of the subtrees can be NULL. Return a pointer to the new 1058 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, 1059 ** free the subtrees and return NULL. 1060 */ 1061 Expr *sqlite3PExpr( 1062 Parse *pParse, /* Parsing context */ 1063 int op, /* Expression opcode */ 1064 Expr *pLeft, /* Left operand */ 1065 Expr *pRight /* Right operand */ 1066 ){ 1067 Expr *p; 1068 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); 1069 if( p ){ 1070 memset(p, 0, sizeof(Expr)); 1071 p->op = op & 0xff; 1072 p->iAgg = -1; 1073 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); 1074 sqlite3ExprCheckHeight(pParse, p->nHeight); 1075 }else{ 1076 sqlite3ExprDelete(pParse->db, pLeft); 1077 sqlite3ExprDelete(pParse->db, pRight); 1078 } 1079 return p; 1080 } 1081 1082 /* 1083 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due 1084 ** do a memory allocation failure) then delete the pSelect object. 1085 */ 1086 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ 1087 if( pExpr ){ 1088 pExpr->x.pSelect = pSelect; 1089 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); 1090 sqlite3ExprSetHeightAndFlags(pParse, pExpr); 1091 }else{ 1092 assert( pParse->db->mallocFailed ); 1093 sqlite3SelectDelete(pParse->db, pSelect); 1094 } 1095 } 1096 1097 /* 1098 ** Expression list pEList is a list of vector values. This function 1099 ** converts the contents of pEList to a VALUES(...) Select statement 1100 ** returning 1 row for each element of the list. For example, the 1101 ** expression list: 1102 ** 1103 ** ( (1,2), (3,4) (5,6) ) 1104 ** 1105 ** is translated to the equivalent of: 1106 ** 1107 ** VALUES(1,2), (3,4), (5,6) 1108 ** 1109 ** Each of the vector values in pEList must contain exactly nElem terms. 1110 ** If a list element that is not a vector or does not contain nElem terms, 1111 ** an error message is left in pParse. 1112 ** 1113 ** This is used as part of processing IN(...) expressions with a list 1114 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))". 1115 */ 1116 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){ 1117 int ii; 1118 Select *pRet = 0; 1119 assert( nElem>1 ); 1120 for(ii=0; iinExpr; ii++){ 1121 Select *pSel; 1122 Expr *pExpr = pEList->a[ii].pExpr; 1123 int nExprElem; 1124 if( pExpr->op==TK_VECTOR ){ 1125 assert( ExprUseXList(pExpr) ); 1126 nExprElem = pExpr->x.pList->nExpr; 1127 }else{ 1128 nExprElem = 1; 1129 } 1130 if( nExprElem!=nElem ){ 1131 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d", 1132 nExprElem, nExprElem>1?"s":"", nElem 1133 ); 1134 break; 1135 } 1136 assert( ExprUseXList(pExpr) ); 1137 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0); 1138 pExpr->x.pList = 0; 1139 if( pSel ){ 1140 if( pRet ){ 1141 pSel->op = TK_ALL; 1142 pSel->pPrior = pRet; 1143 } 1144 pRet = pSel; 1145 } 1146 } 1147 1148 if( pRet && pRet->pPrior ){ 1149 pRet->selFlags |= SF_MultiValue; 1150 } 1151 sqlite3ExprListDelete(pParse->db, pEList); 1152 return pRet; 1153 } 1154 1155 /* 1156 ** Join two expressions using an AND operator. If either expression is 1157 ** NULL, then just return the other expression. 1158 ** 1159 ** If one side or the other of the AND is known to be false, and neither side 1160 ** is part of an ON clause, then instead of returning an AND expression, 1161 ** just return a constant expression with a value of false. 1162 */ 1163 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){ 1164 sqlite3 *db = pParse->db; 1165 if( pLeft==0 ){ 1166 return pRight; 1167 }else if( pRight==0 ){ 1168 return pLeft; 1169 }else{ 1170 u32 f = pLeft->flags | pRight->flags; 1171 if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse|EP_HasFunc))==EP_IsFalse 1172 && !IN_RENAME_OBJECT 1173 ){ 1174 Expr *p; 1175 sqlite3ExprDeferredDelete(pParse, pLeft); 1176 sqlite3ExprDeferredDelete(pParse, pRight); 1177 p = sqlite3ExprInt32(db, 0); 1178 if( p ) p->op2 = 1; 1179 return p; 1180 }else{ 1181 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight); 1182 } 1183 } 1184 } 1185 1186 /* 1187 ** Construct a new expression node for a function with multiple 1188 ** arguments. 1189 */ 1190 Expr *sqlite3ExprFunction( 1191 Parse *pParse, /* Parsing context */ 1192 ExprList *pList, /* Argument list */ 1193 const Token *pToken, /* Name of the function */ 1194 int eDistinct /* SF_Distinct or SF_ALL or 0 */ 1195 ){ 1196 Expr *pNew; 1197 sqlite3 *db = pParse->db; 1198 assert( pToken ); 1199 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); 1200 if( pNew==0 ){ 1201 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ 1202 return 0; 1203 } 1204 assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) ); 1205 pNew->w.iOfst = (int)(pToken->z - pParse->zTail); 1206 if( pList 1207 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] 1208 && !pParse->nested 1209 ){ 1210 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken); 1211 } 1212 pNew->x.pList = pList; 1213 ExprSetProperty(pNew, EP_HasFunc); 1214 assert( ExprUseXList(pNew) ); 1215 sqlite3ExprSetHeightAndFlags(pParse, pNew); 1216 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct); 1217 return pNew; 1218 } 1219 1220 /* 1221 ** Report an error when attempting to use an ORDER BY clause within 1222 ** the arguments of a non-aggregate function. 1223 */ 1224 void sqlite3ExprOrderByAggregateError(Parse *pParse, Expr *p){ 1225 sqlite3ErrorMsg(pParse, 1226 "ORDER BY may not be used with non-aggregate %#T()", p 1227 ); 1228 } 1229 1230 /* 1231 ** Attach an ORDER BY clause to a function call. 1232 ** 1233 ** functionname( arguments ORDER BY sortlist ) 1234 ** \_____________________/ \______/ 1235 ** pExpr pOrderBy 1236 ** 1237 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER 1238 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node. 1239 */ 1240 void sqlite3ExprAddFunctionOrderBy( 1241 Parse *pParse, /* Parsing context */ 1242 Expr *pExpr, /* The function call to which ORDER BY is to be added */ 1243 ExprList *pOrderBy /* The ORDER BY clause to add */ 1244 ){ 1245 Expr *pOB; 1246 sqlite3 *db = pParse->db; 1247 if( NEVER(pOrderBy==0) ){ 1248 assert( db->mallocFailed ); 1249 return; 1250 } 1251 if( pExpr==0 ){ 1252 assert( db->mallocFailed ); 1253 sqlite3ExprListDelete(db, pOrderBy); 1254 return; 1255 } 1256 assert( pExpr->op==TK_FUNCTION ); 1257 assert( pExpr->pLeft==0 ); 1258 assert( ExprUseXList(pExpr) ); 1259 if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){ 1260 /* Ignore ORDER BY on zero-argument aggregates */ 1261 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pOrderBy); 1262 return; 1263 } 1264 if( IsWindowFunc(pExpr) ){ 1265 sqlite3ExprOrderByAggregateError(pParse, pExpr); 1266 sqlite3ExprListDelete(db, pOrderBy); 1267 return; 1268 } 1269 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ 1270 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); 1271 sqlite3ExprListDelete(db, pOrderBy); 1272 return; 1273 } 1274 1275 pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0); 1276 if( pOB==0 ){ 1277 sqlite3ExprListDelete(db, pOrderBy); 1278 return; 1279 } 1280 pOB->x.pList = pOrderBy; 1281 assert( ExprUseXList(pOB) ); 1282 pExpr->pLeft = pOB; 1283 ExprSetProperty(pOB, EP_FullSize); 1284 } 1285 1286 /* 1287 ** Check to see if a function is usable according to current access 1288 ** rules: 1289 ** 1290 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL 1291 ** 1292 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from 1293 ** top-level SQL 1294 ** 1295 ** If the function is not usable, create an error. 1296 */ 1297 void sqlite3ExprFunctionUsable( 1298 Parse *pParse, /* Parsing and code generating context */ 1299 const Expr *pExpr, /* The function invocation */ 1300 const FuncDef *pDef /* The function being invoked */ 1301 ){ 1302 assert( !IN_RENAME_OBJECT ); 1303 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 ); 1304 if( ExprHasProperty(pExpr, EP_FromDDL) 1305 || pParse->prepFlags & SQLITE_PREPARE_FROM_DDL 1306 ){ 1307 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 1308 || (pParse->db->flags & SQLITE_TrustedSchema)==0 1309 ){ 1310 /* Functions prohibited in triggers and views if: 1311 ** (1) tagged with SQLITE_DIRECTONLY 1312 ** (2) not tagged with SQLITE_INNOCUOUS (which means it 1313 ** is tagged with SQLITE_FUNC_UNSAFE) and 1314 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning 1315 ** that the schema is possibly tainted). 1316 */ 1317 sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr); 1318 } 1319 } 1320 } 1321 1322 /* 1323 ** Assign a variable number to an expression that encodes a wildcard 1324 ** in the original SQL statement. 1325 ** 1326 ** Wildcards consisting of a single "?" are assigned the next sequential 1327 ** variable number. 1328 ** 1329 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make 1330 ** sure "nnn" is not too big to avoid a denial of service attack when 1331 ** the SQL statement comes from an external source. 1332 ** 1333 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number 1334 ** as the previous instance of the same wildcard. Or if this is the first 1335 ** instance of the wildcard, the next sequential variable number is 1336 ** assigned. 1337 */ 1338 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ 1339 sqlite3 *db = pParse->db; 1340 const char *z; 1341 ynVar x; 1342 1343 if( pExpr==0 ) return; 1344 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); 1345 z = pExpr->u.zToken; 1346 assert( z!=0 ); 1347 assert( z[0]!=0 ); 1348 assert( n==(u32)sqlite3Strlen30(z) ); 1349 if( z[1]==0 ){ 1350 /* Wildcard of the form "?". Assign the next variable number */ 1351 assert( z[0]=='?' ); 1352 x = (ynVar)(++pParse->nVar); 1353 }else{ 1354 int doAdd = 0; 1355 if( z[0]=='?' ){ 1356 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and 1357 ** use it as the variable number */ 1358 i64 i; 1359 int bOk; 1360 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/ 1361 i = z[1]-'0'; /* The common case of ?N for a single digit N */ 1362 bOk = 1; 1363 }else{ 1364 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); 1365 } 1366 testcase( i==0 ); 1367 testcase( i==1 ); 1368 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); 1369 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); 1370 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 1371 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", 1372 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); 1373 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr); 1374 return; 1375 } 1376 x = (ynVar)i; 1377 if( x>pParse->nVar ){ 1378 pParse->nVar = (int)x; 1379 doAdd = 1; 1380 }else if( xaVnbmc[x>>6] & MASKBIT64(x&63))==0; 1382 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){ 1383 doAdd = 1; 1384 } 1385 }else{ 1386 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable 1387 ** number as the prior appearance of the same name, or if the name 1388 ** has never appeared before, reuse the same variable number 1389 */ 1390 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n); 1391 if( x==0 ){ 1392 x = (ynVar)(++pParse->nVar); 1393 doAdd = 1; 1394 } 1395 } 1396 if( doAdd ){ 1397 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x); 1398 if( pParse->pVList!=0 && xaVnbmc[x>>6] |= MASKBIT64(x&63); 1400 } 1401 } 1402 } 1403 pExpr->iColumn = x; 1404 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 1405 sqlite3ErrorMsg(pParse, "too many SQL variables"); 1406 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr); 1407 } 1408 } 1409 1410 /* 1411 ** Recursively delete an expression tree. 1412 */ 1413 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ 1414 assert( p!=0 ); 1415 assert( db!=0 ); 1416 exprDeleteRestart: 1417 assert( !ExprUseUValue(p) || p->u.iValue>=0 ); 1418 assert( !ExprUseYWin(p) || !ExprUseYSub(p) ); 1419 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed ); 1420 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) ); 1421 #ifdef SQLITE_DEBUG 1422 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ 1423 assert( p->pLeft==0 ); 1424 assert( p->pRight==0 ); 1425 assert( !ExprUseXSelect(p) || p->x.pSelect==0 ); 1426 assert( !ExprUseXList(p) || p->x.pList==0 ); 1427 } 1428 #endif 1429 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ 1430 /* The Expr.x union is never used at the same time as Expr.pRight */ 1431 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 ); 1432 if( p->pRight ){ 1433 assert( !ExprHasProperty(p, EP_WinFunc) ); 1434 sqlite3ExprDeleteNN(db, p->pRight); 1435 }else if( ExprUseXSelect(p) ){ 1436 assert( !ExprHasProperty(p, EP_WinFunc) ); 1437 sqlite3SelectDelete(db, p->x.pSelect); 1438 }else{ 1439 sqlite3ExprListDelete(db, p->x.pList); 1440 #ifndef SQLITE_OMIT_WINDOWFUNC 1441 if( ExprHasProperty(p, EP_WinFunc) ){ 1442 sqlite3WindowDelete(db, p->y.pWin); 1443 } 1444 #endif 1445 } 1446 if( p->pLeft && p->op!=TK_SELECT_COLUMN ){ 1447 Expr *pLeft = p->pLeft; 1448 if( !ExprHasProperty(p, EP_Static) 1449 && !ExprHasProperty(pLeft, EP_Static) 1450 ){ 1451 /* Avoid unnecessary recursion on unary operators */ 1452 sqlite3DbNNFreeNN(db, p); 1453 p = pLeft; 1454 goto exprDeleteRestart; 1455 }else{ 1456 sqlite3ExprDeleteNN(db, pLeft); 1457 } 1458 } 1459 } 1460 if( !ExprHasProperty(p, EP_Static) ){ 1461 sqlite3DbNNFreeNN(db, p); 1462 } 1463 } 1464 void sqlite3ExprDelete(sqlite3 *db, Expr *p){ 1465 if( p ) sqlite3ExprDeleteNN(db, p); 1466 } 1467 void sqlite3ExprDeleteGeneric(sqlite3 *db, void *p){ 1468 if( ALWAYS(p) ) sqlite3ExprDeleteNN(db, (Expr*)p); 1469 } 1470 1471 /* 1472 ** Clear both elements of an OnOrUsing object 1473 */ 1474 void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){ 1475 if( p==0 ){ 1476 /* Nothing to clear */ 1477 }else if( p->pOn ){ 1478 sqlite3ExprDeleteNN(db, p->pOn); 1479 }else if( p->pUsing ){ 1480 sqlite3IdListDelete(db, p->pUsing); 1481 } 1482 } 1483 1484 /* 1485 ** Arrange to cause pExpr to be deleted when the pParse is deleted. 1486 ** This is similar to sqlite3ExprDelete() except that the delete is 1487 ** deferred until the pParse is deleted. 1488 ** 1489 ** The pExpr might be deleted immediately on an OOM error. 1490 ** 1491 ** Return 0 if the delete was successfully deferred. Return non-zero 1492 ** if the delete happened immediately because of an OOM. 1493 */ 1494 int sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){ 1495 return 0==sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr); 1496 } 1497 1498 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the 1499 ** expression. 1500 */ 1501 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){ 1502 if( p ){ 1503 if( IN_RENAME_OBJECT ){ 1504 sqlite3RenameExprUnmap(pParse, p); 1505 } 1506 sqlite3ExprDeleteNN(pParse->db, p); 1507 } 1508 } 1509 1510 /* 1511 ** Return the number of bytes allocated for the expression structure 1512 ** passed as the first argument. This is always one of EXPR_FULLSIZE, 1513 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. 1514 */ 1515 static int exprStructSize(const Expr *p){ 1516 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; 1517 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; 1518 return EXPR_FULLSIZE; 1519 } 1520 1521 /* 1522 ** The dupedExpr*Size() routines each return the number of bytes required 1523 ** to store a copy of an expression or expression tree. They differ in 1524 ** how much of the tree is measured. 1525 ** 1526 ** dupedExprStructSize() Size of only the Expr structure 1527 ** dupedExprNodeSize() Size of Expr + space for token 1528 ** dupedExprSize() Expr + token + subtree components 1529 ** 1530 *************************************************************************** 1531 ** 1532 ** The dupedExprStructSize() function returns two values OR-ed together: 1533 ** (1) the space required for a copy of the Expr structure only and 1534 ** (2) the EP_xxx flags that indicate what the structure size should be. 1535 ** The return values is always one of: 1536 ** 1537 ** EXPR_FULLSIZE 1538 ** EXPR_REDUCEDSIZE | EP_Reduced 1539 ** EXPR_TOKENONLYSIZE | EP_TokenOnly 1540 ** 1541 ** The size of the structure can be found by masking the return value 1542 ** of this routine with 0xfff. The flags can be found by masking the 1543 ** return value with EP_Reduced|EP_TokenOnly. 1544 ** 1545 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size 1546 ** (unreduced) Expr objects as they or originally constructed by the parser. 1547 ** During expression analysis, extra information is computed and moved into 1548 ** later parts of the Expr object and that extra information might get chopped 1549 ** off if the expression is reduced. Note also that it does not work to 1550 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal 1551 ** to reduce a pristine expression tree from the parser. The implementation 1552 ** of dupedExprStructSize() contain multiple assert() statements that attempt 1553 ** to enforce this constraint. 1554 */ 1555 static int dupedExprStructSize(const Expr *p, int flags){ 1556 int nSize; 1557 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ 1558 assert( EXPR_FULLSIZE<=0xfff ); 1559 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); 1560 if( 0==flags || ExprHasProperty(p, EP_FullSize) ){ 1561 nSize = EXPR_FULLSIZE; 1562 }else{ 1563 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 1564 assert( !ExprHasProperty(p, EP_OuterON) ); 1565 assert( !ExprHasVVAProperty(p, EP_NoReduce) ); 1566 if( p->pLeft || p->x.pList ){ 1567 nSize = EXPR_REDUCEDSIZE | EP_Reduced; 1568 }else{ 1569 assert( p->pRight==0 ); 1570 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; 1571 } 1572 } 1573 return nSize; 1574 } 1575 1576 /* 1577 ** This function returns the space in bytes required to store the copy 1578 ** of the Expr structure and a copy of the Expr.u.zToken string (if that 1579 ** string is defined.) 1580 */ 1581 static int dupedExprNodeSize(const Expr *p, int flags){ 1582 int nByte = dupedExprStructSize(p, flags) & 0xfff; 1583 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 1584 nByte += sqlite3Strlen30NN(p->u.zToken)+1; 1585 } 1586 return ROUND8(nByte); 1587 } 1588 1589 /* 1590 ** Return the number of bytes required to create a duplicate of the 1591 ** expression passed as the first argument. 1592 ** 1593 ** The value returned includes space to create a copy of the Expr struct 1594 ** itself and the buffer referred to by Expr.u.zToken, if any. 1595 ** 1596 ** The return value includes space to duplicate all Expr nodes in the 1597 ** tree formed by Expr.pLeft and Expr.pRight, but not any other 1598 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin. 1599 */ 1600 static u64 dupedExprSize(const Expr *p){ 1601 u64 nByte; 1602 assert( p!=0 ); 1603 nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE); 1604 if( p->pLeft ) nByte += dupedExprSize(p->pLeft); 1605 if( p->pRight ) nByte += dupedExprSize(p->pRight); 1606 assert( nByte==ROUND8(nByte) ); 1607 return nByte; 1608 } 1609 1610 /* 1611 ** An EdupBuf is a memory allocation used to stored multiple Expr objects 1612 ** together with their Expr.zToken content. This is used to help implement 1613 ** compression while doing sqlite3ExprDup(). The top-level Expr does the 1614 ** allocation for itself and many of its decendents, then passes an instance 1615 ** of the structure down into exprDup() so that they decendents can have 1616 ** access to that memory. 1617 */ 1618 typedef struct EdupBuf EdupBuf; 1619 struct EdupBuf { 1620 u8 *zAlloc; /* Memory space available for storage */ 1621 #ifdef SQLITE_DEBUG 1622 u8 *zEnd; /* First byte past the end of memory */ 1623 #endif 1624 }; 1625 1626 /* 1627 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf 1628 ** is not NULL then it points to memory that can be used to store a copy 1629 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf 1630 ** is updated with the new buffer tail prior to returning. 1631 */ 1632 static Expr *exprDup( 1633 sqlite3 *db, /* Database connection (for memory allocation) */ 1634 const Expr *p, /* Expr tree to be duplicated */ 1635 int dupFlags, /* EXPRDUP_REDUCE for compression. 0 if not */ 1636 EdupBuf *pEdupBuf /* Preallocated storage space, or NULL */ 1637 ){ 1638 Expr *pNew; /* Value to return */ 1639 EdupBuf sEdupBuf; /* Memory space from which to build Expr object */ 1640 u32 staticFlag; /* EP_Static if space not obtained from malloc */ 1641 int nToken = -1; /* Space needed for p->u.zToken. -1 means unknown */ 1642 1643 assert( db!=0 ); 1644 assert( p ); 1645 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE ); 1646 assert( pEdupBuf==0 || dupFlags==EXPRDUP_REDUCE ); 1647 1648 /* Figure out where to write the new Expr structure. */ 1649 if( pEdupBuf ){ 1650 sEdupBuf.zAlloc = pEdupBuf->zAlloc; 1651 #ifdef SQLITE_DEBUG 1652 sEdupBuf.zEnd = pEdupBuf->zEnd; 1653 #endif 1654 staticFlag = EP_Static; 1655 assert( sEdupBuf.zAlloc!=0 ); 1656 assert( dupFlags==EXPRDUP_REDUCE ); 1657 }else{ 1658 u64 nAlloc; 1659 if( dupFlags ){ 1660 nAlloc = dupedExprSize(p); 1661 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 1662 nToken = sqlite3Strlen30NN(p->u.zToken)+1; 1663 nAlloc = ROUND8(EXPR_FULLSIZE + nToken); 1664 }else{ 1665 nToken = 0; 1666 nAlloc = ROUND8(EXPR_FULLSIZE); 1667 } 1668 assert( nAlloc==ROUND8(nAlloc) ); 1669 sEdupBuf.zAlloc = sqlite3DbMallocRawNN(db, nAlloc); 1670 #ifdef SQLITE_DEBUG 1671 sEdupBuf.zEnd = sEdupBuf.zAlloc ? sEdupBuf.zAlloc+nAlloc : 0; 1672 #endif 1673 1674 staticFlag = 0; 1675 } 1676 pNew = (Expr *)sEdupBuf.zAlloc; 1677 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); 1678 1679 if( pNew ){ 1680 /* Set nNewSize to the size allocated for the structure pointed to 1681 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or 1682 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed 1683 ** by the copy of the p->u.zToken string (if any). 1684 */ 1685 const unsigned nStructSize = dupedExprStructSize(p, dupFlags); 1686 int nNewSize = nStructSize & 0xfff; 1687 if( nToken<0 ){ 1688 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 1689 nToken = sqlite3Strlen30(p->u.zToken) + 1; 1690 }else{ 1691 nToken = 0; 1692 } 1693 } 1694 if( dupFlags ){ 1695 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken ); 1696 assert( ExprHasProperty(p, EP_Reduced)==0 ); 1697 memcpy(sEdupBuf.zAlloc, p, nNewSize); 1698 }else{ 1699 u32 nSize = (u32)exprStructSize(p); 1700 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= 1701 (int)EXPR_FULLSIZE+nToken ); 1702 memcpy(sEdupBuf.zAlloc, p, nSize); 1703 if( nSizeflags &= ~(EP_Reduced|EP_TokenOnly|EP_Static); 1711 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); 1712 pNew->flags |= staticFlag; 1713 ExprClearVVAProperties(pNew); 1714 if( dupFlags ){ 1715 ExprSetVVAProperty(pNew, EP_Immutable); 1716 } 1717 1718 /* Copy the p->u.zToken string, if any. */ 1719 assert( nToken>=0 ); 1720 if( nToken>0 ){ 1721 char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize]; 1722 memcpy(zToken, p->u.zToken, nToken); 1723 nNewSize += nToken; 1724 } 1725 sEdupBuf.zAlloc += ROUND8(nNewSize); 1726 1727 if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){ 1728 1729 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ 1730 if( ExprUseXSelect(p) ){ 1731 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); 1732 }else{ 1733 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, 1734 p->op!=TK_ORDER ? dupFlags : 0); 1735 } 1736 1737 #ifndef SQLITE_OMIT_WINDOWFUNC 1738 if( ExprHasProperty(p, EP_WinFunc) ){ 1739 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin); 1740 assert( ExprHasProperty(pNew, EP_WinFunc) ); 1741 } 1742 #endif /* SQLITE_OMIT_WINDOWFUNC */ 1743 1744 /* Fill in pNew->pLeft and pNew->pRight. */ 1745 if( dupFlags ){ 1746 if( p->op==TK_SELECT_COLUMN ){ 1747 pNew->pLeft = p->pLeft; 1748 assert( p->pRight==0 1749 || p->pRight==p->pLeft 1750 || ExprHasProperty(p->pLeft, EP_Subquery) ); 1751 }else{ 1752 pNew->pLeft = p->pLeft ? 1753 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0; 1754 } 1755 pNew->pRight = p->pRight ? 1756 exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0; 1757 }else{ 1758 if( p->op==TK_SELECT_COLUMN ){ 1759 pNew->pLeft = p->pLeft; 1760 assert( p->pRight==0 1761 || p->pRight==p->pLeft 1762 || ExprHasProperty(p->pLeft, EP_Subquery) ); 1763 }else{ 1764 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); 1765 } 1766 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); 1767 } 1768 } 1769 } 1770 if( pEdupBuf ) memcpy(pEdupBuf, &sEdupBuf, sizeof(sEdupBuf)); 1771 assert( sEdupBuf.zAlloc <= sEdupBuf.zEnd ); 1772 return pNew; 1773 } 1774 1775 /* 1776 ** Create and return a deep copy of the object passed as the second 1777 ** argument. If an OOM condition is encountered, NULL is returned 1778 ** and the db->mallocFailed flag set. 1779 */ 1780 #ifndef SQLITE_OMIT_CTE 1781 With *sqlite3WithDup(sqlite3 *db, With *p){ 1782 With *pRet = 0; 1783 if( p ){ 1784 sqlite3_int64 nByte = SZ_WITH(p->nCte); 1785 pRet = sqlite3DbMallocZero(db, nByte); 1786 if( pRet ){ 1787 int i; 1788 pRet->nCte = p->nCte; 1789 for(i=0; inCte; i++){ 1790 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); 1791 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); 1792 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); 1793 pRet->a[i].eM10d = p->a[i].eM10d; 1794 } 1795 } 1796 } 1797 return pRet; 1798 } 1799 #else 1800 # define sqlite3WithDup(x,y) 0 1801 #endif 1802 1803 #ifndef SQLITE_OMIT_WINDOWFUNC 1804 /* 1805 ** The gatherSelectWindows() procedure and its helper routine 1806 ** gatherSelectWindowsCallback() are used to scan all the expressions 1807 ** an a newly duplicated SELECT statement and gather all of the Window 1808 ** objects found there, assembling them onto the linked list at Select->pWin. 1809 */ 1810 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){ 1811 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){ 1812 Select *pSelect = pWalker->u.pSelect; 1813 Window *pWin = pExpr->y.pWin; 1814 assert( pWin ); 1815 assert( IsWindowFunc(pExpr) ); 1816 assert( pWin->ppThis==0 ); 1817 sqlite3WindowLink(pSelect, pWin); 1818 } 1819 return WRC_Continue; 1820 } 1821 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){ 1822 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune; 1823 } 1824 static void gatherSelectWindows(Select *p){ 1825 Walker w; 1826 w.xExprCallback = gatherSelectWindowsCallback; 1827 w.xSelectCallback = gatherSelectWindowsSelectCallback; 1828 w.xSelectCallback2 = 0; 1829 w.pParse = 0; 1830 w.u.pSelect = p; 1831 sqlite3WalkSelect(&w, p); 1832 } 1833 #endif 1834 1835 1836 /* 1837 ** The following group of routines make deep copies of expressions, 1838 ** expression lists, ID lists, and select statements. The copies can 1839 ** be deleted (by being passed to their respective ...Delete() routines) 1840 ** without effecting the originals. 1841 ** 1842 ** The expression list, ID, and source lists return by sqlite3ExprListDup(), 1843 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 1844 ** by subsequent calls to sqlite*ListAppend() routines. 1845 ** 1846 ** Any tables that the SrcList might point to are not duplicated. 1847 ** 1848 ** The flags parameter contains a combination of the EXPRDUP_XXX flags. 1849 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a 1850 ** truncated version of the usual Expr structure that will be stored as 1851 ** part of the in-memory representation of the database schema. 1852 */ 1853 Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){ 1854 assert( flags==0 || flags==EXPRDUP_REDUCE ); 1855 return p ? exprDup(db, p, flags, 0) : 0; 1856 } 1857 ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){ 1858 ExprList *pNew; 1859 struct ExprList_item *pItem; 1860 const struct ExprList_item *pOldItem; 1861 int i; 1862 Expr *pPriorSelectColOld = 0; 1863 Expr *pPriorSelectColNew = 0; 1864 assert( db!=0 ); 1865 if( p==0 ) return 0; 1866 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p)); 1867 if( pNew==0 ) return 0; 1868 pNew->nExpr = p->nExpr; 1869 pNew->nAlloc = p->nAlloc; 1870 pItem = pNew->a; 1871 pOldItem = p->a; 1872 for(i=0; inExpr; i++, pItem++, pOldItem++){ 1873 Expr *pOldExpr = pOldItem->pExpr; 1874 Expr *pNewExpr; 1875 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); 1876 if( pOldExpr 1877 && pOldExpr->op==TK_SELECT_COLUMN 1878 && (pNewExpr = pItem->pExpr)!=0 1879 ){ 1880 if( pNewExpr->pRight ){ 1881 pPriorSelectColOld = pOldExpr->pRight; 1882 pPriorSelectColNew = pNewExpr->pRight; 1883 pNewExpr->pLeft = pNewExpr->pRight; 1884 }else{ 1885 if( pOldExpr->pLeft!=pPriorSelectColOld ){ 1886 pPriorSelectColOld = pOldExpr->pLeft; 1887 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags); 1888 pNewExpr->pRight = pPriorSelectColNew; 1889 } 1890 pNewExpr->pLeft = pPriorSelectColNew; 1891 } 1892 } 1893 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName); 1894 pItem->fg = pOldItem->fg; 1895 pItem->u = pOldItem->u; 1896 } 1897 return pNew; 1898 } 1899 1900 /* 1901 ** If cursors, triggers, views and subqueries are all omitted from 1902 ** the build, then none of the following routines, except for 1903 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes 1904 ** called with a NULL argument. 1905 */ 1906 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ 1907 || !defined(SQLITE_OMIT_SUBQUERY) 1908 SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){ 1909 SrcList *pNew; 1910 int i; 1911 assert( db!=0 ); 1912 if( p==0 ) return 0; 1913 pNew = sqlite3DbMallocRawNN(db, SZ_SRCLIST(p->nSrc) ); 1914 if( pNew==0 ) return 0; 1915 pNew->nSrc = pNew->nAlloc = p->nSrc; 1916 for(i=0; inSrc; i++){ 1917 SrcItem *pNewItem = &pNew->a[i]; 1918 const SrcItem *pOldItem = &p->a[i]; 1919 Table *pTab; 1920 pNewItem->fg = pOldItem->fg; 1921 if( pOldItem->fg.isSubquery ){ 1922 Subquery *pNewSubq = sqlite3DbMallocRaw(db, sizeof(Subquery)); 1923 if( pNewSubq==0 ){ 1924 assert( db->mallocFailed ); 1925 pNewItem->fg.isSubquery = 0; 1926 }else{ 1927 memcpy(pNewSubq, pOldItem->u4.pSubq, sizeof(*pNewSubq)); 1928 pNewSubq->pSelect = sqlite3SelectDup(db, pNewSubq->pSelect, flags); 1929 if( pNewSubq->pSelect==0 ){ 1930 sqlite3DbFree(db, pNewSubq); 1931 pNewSubq = 0; 1932 pNewItem->fg.isSubquery = 0; 1933 } 1934 } 1935 pNewItem->u4.pSubq = pNewSubq; 1936 }else if( pOldItem->fg.fixedSchema ){ 1937 pNewItem->u4.pSchema = pOldItem->u4.pSchema; 1938 }else{ 1939 pNewItem->u4.zDatabase = sqlite3DbStrDup(db, pOldItem->u4.zDatabase); 1940 } 1941 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 1942 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); 1943 pNewItem->iCursor = pOldItem->iCursor; 1944 if( pNewItem->fg.isIndexedBy ){ 1945 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); 1946 }else if( pNewItem->fg.isTabFunc ){ 1947 pNewItem->u1.pFuncArg = 1948 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); 1949 }else{ 1950 pNewItem->u1.nRow = pOldItem->u1.nRow; 1951 } 1952 pNewItem->u2 = pOldItem->u2; 1953 if( pNewItem->fg.isCte ){ 1954 pNewItem->u2.pCteUse->nUse++; 1955 } 1956 pTab = pNewItem->pSTab = pOldItem->pSTab; 1957 if( pTab ){ 1958 pTab->nTabRef++; 1959 } 1960 if( pOldItem->fg.isUsing ){ 1961 assert( pNewItem->fg.isUsing ); 1962 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing); 1963 }else{ 1964 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags); 1965 } 1966 pNewItem->colUsed = pOldItem->colUsed; 1967 } 1968 return pNew; 1969 } 1970 IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){ 1971 IdList *pNew; 1972 int i; 1973 assert( db!=0 ); 1974 if( p==0 ) return 0; 1975 pNew = sqlite3DbMallocRawNN(db, SZ_IDLIST(p->nId)); 1976 if( pNew==0 ) return 0; 1977 pNew->nId = p->nId; 1978 for(i=0; inId; i++){ 1979 struct IdList_item *pNewItem = &pNew->a[i]; 1980 const struct IdList_item *pOldItem = &p->a[i]; 1981 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 1982 } 1983 return pNew; 1984 } 1985 Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){ 1986 Select *pRet = 0; 1987 Select *pNext = 0; 1988 Select **pp = &pRet; 1989 const Select *p; 1990 1991 assert( db!=0 ); 1992 for(p=pDup; p; p=p->pPrior){ 1993 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); 1994 if( pNew==0 ) break; 1995 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); 1996 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); 1997 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); 1998 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); 1999 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); 2000 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); 2001 pNew->op = p->op; 2002 pNew->pNext = pNext; 2003 pNew->pPrior = 0; 2004 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); 2005 pNew->iLimit = 0; 2006 pNew->iOffset = 0; 2007 pNew->selFlags = p->selFlags; 2008 pNew->nSelectRow = p->nSelectRow; 2009 pNew->pWith = sqlite3WithDup(db, p->pWith); 2010 #ifndef SQLITE_OMIT_WINDOWFUNC 2011 pNew->pWin = 0; 2012 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn); 2013 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew); 2014 #endif 2015 pNew->selId = p->selId; 2016 if( db->mallocFailed ){ 2017 /* Any prior OOM might have left the Select object incomplete. 2018 ** Delete the whole thing rather than allow an incomplete Select 2019 ** to be used by the code generator. */ 2020 pNew->pNext = 0; 2021 sqlite3SelectDelete(db, pNew); 2022 break; 2023 } 2024 *pp = pNew; 2025 pp = &pNew->pPrior; 2026 pNext = pNew; 2027 } 2028 return pRet; 2029 } 2030 #else 2031 Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){ 2032 assert( p==0 ); 2033 return 0; 2034 } 2035 #endif 2036 2037 2038 /* 2039 ** Add a new element to the end of an expression list. If pList is 2040 ** initially NULL, then create a new expression list. 2041 ** 2042 ** The pList argument must be either NULL or a pointer to an ExprList 2043 ** obtained from a prior call to sqlite3ExprListAppend(). 2044 ** 2045 ** If a memory allocation error occurs, the entire list is freed and 2046 ** NULL is returned. If non-NULL is returned, then it is guaranteed 2047 ** that the new entry was successfully appended. 2048 */ 2049 static const struct ExprList_item zeroItem = {0}; 2050 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew( 2051 sqlite3 *db, /* Database handle. Used for memory allocation */ 2052 Expr *pExpr /* Expression to be appended. Might be NULL */ 2053 ){ 2054 struct ExprList_item *pItem; 2055 ExprList *pList; 2056 2057 pList = sqlite3DbMallocRawNN(db, SZ_EXPRLIST(4)); 2058 if( pList==0 ){ 2059 sqlite3ExprDelete(db, pExpr); 2060 return 0; 2061 } 2062 pList->nAlloc = 4; 2063 pList->nExpr = 1; 2064 pItem = &pList->a[0]; 2065 *pItem = zeroItem; 2066 pItem->pExpr = pExpr; 2067 return pList; 2068 } 2069 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow( 2070 sqlite3 *db, /* Database handle. Used for memory allocation */ 2071 ExprList *pList, /* List to which to append. Might be NULL */ 2072 Expr *pExpr /* Expression to be appended. Might be NULL */ 2073 ){ 2074 struct ExprList_item *pItem; 2075 ExprList *pNew; 2076 pList->nAlloc *= 2; 2077 pNew = sqlite3DbRealloc(db, pList, SZ_EXPRLIST(pList->nAlloc)); 2078 if( pNew==0 ){ 2079 sqlite3ExprListDelete(db, pList); 2080 sqlite3ExprDelete(db, pExpr); 2081 return 0; 2082 }else{ 2083 pList = pNew; 2084 } 2085 pItem = &pList->a[pList->nExpr++]; 2086 *pItem = zeroItem; 2087 pItem->pExpr = pExpr; 2088 return pList; 2089 } 2090 ExprList *sqlite3ExprListAppend( 2091 Parse *pParse, /* Parsing context */ 2092 ExprList *pList, /* List to which to append. Might be NULL */ 2093 Expr *pExpr /* Expression to be appended. Might be NULL */ 2094 ){ 2095 struct ExprList_item *pItem; 2096 if( pList==0 ){ 2097 return sqlite3ExprListAppendNew(pParse->db,pExpr); 2098 } 2099 if( pList->nAllocnExpr+1 ){ 2100 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr); 2101 } 2102 pItem = &pList->a[pList->nExpr++]; 2103 *pItem = zeroItem; 2104 pItem->pExpr = pExpr; 2105 return pList; 2106 } 2107 2108 /* 2109 ** pColumns and pExpr form a vector assignment which is part of the SET 2110 ** clause of an UPDATE statement. Like this: 2111 ** 2112 ** (a,b,c) = (expr1,expr2,expr3) 2113 ** Or: (a,b,c) = (SELECT x,y,z FROM ....) 2114 ** 2115 ** For each term of the vector assignment, append new entries to the 2116 ** expression list pList. In the case of a subquery on the RHS, append 2117 ** TK_SELECT_COLUMN expressions. 2118 */ 2119 ExprList *sqlite3ExprListAppendVector( 2120 Parse *pParse, /* Parsing context */ 2121 ExprList *pList, /* List to which to append. Might be NULL */ 2122 IdList *pColumns, /* List of names of LHS of the assignment */ 2123 Expr *pExpr /* Vector expression to be appended. Might be NULL */ 2124 ){ 2125 sqlite3 *db = pParse->db; 2126 int n; 2127 int i; 2128 int iFirst = pList ? pList->nExpr : 0; 2129 /* pColumns can only be NULL due to an OOM but an OOM will cause an 2130 ** exit prior to this routine being invoked */ 2131 if( NEVER(pColumns==0) ) goto vector_append_error; 2132 if( pExpr==0 ) goto vector_append_error; 2133 2134 /* If the RHS is a vector, then we can immediately check to see that 2135 ** the size of the RHS and LHS match. But if the RHS is a SELECT, 2136 ** wildcards ("*") in the result set of the SELECT must be expanded before 2137 ** we can do the size check, so defer the size check until code generation. 2138 */ 2139 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){ 2140 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 2141 pColumns->nId, n); 2142 goto vector_append_error; 2143 } 2144 2145 for(i=0; inId; i++){ 2146 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId); 2147 assert( pSubExpr!=0 || db->mallocFailed ); 2148 if( pSubExpr==0 ) continue; 2149 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); 2150 if( pList ){ 2151 assert( pList->nExpr==iFirst+i+1 ); 2152 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName; 2153 pColumns->a[i].zName = 0; 2154 } 2155 } 2156 2157 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){ 2158 Expr *pFirst = pList->a[iFirst].pExpr; 2159 assert( pFirst!=0 ); 2160 assert( pFirst->op==TK_SELECT_COLUMN ); 2161 2162 /* Store the SELECT statement in pRight so it will be deleted when 2163 ** sqlite3ExprListDelete() is called */ 2164 pFirst->pRight = pExpr; 2165 pExpr = 0; 2166 2167 /* Remember the size of the LHS in iTable so that we can check that 2168 ** the RHS and LHS sizes match during code generation. */ 2169 pFirst->iTable = pColumns->nId; 2170 } 2171 2172 vector_append_error: 2173 sqlite3ExprUnmapAndDelete(pParse, pExpr); 2174 sqlite3IdListDelete(db, pColumns); 2175 return pList; 2176 } 2177 2178 /* 2179 ** Set the sort order for the last element on the given ExprList. 2180 */ 2181 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){ 2182 struct ExprList_item *pItem; 2183 if( p==0 ) return; 2184 assert( p->nExpr>0 ); 2185 2186 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 ); 2187 assert( iSortOrder==SQLITE_SO_UNDEFINED 2188 || iSortOrder==SQLITE_SO_ASC 2189 || iSortOrder==SQLITE_SO_DESC 2190 ); 2191 assert( eNulls==SQLITE_SO_UNDEFINED 2192 || eNulls==SQLITE_SO_ASC 2193 || eNulls==SQLITE_SO_DESC 2194 ); 2195 2196 pItem = &p->a[p->nExpr-1]; 2197 assert( pItem->fg.bNulls==0 ); 2198 if( iSortOrder==SQLITE_SO_UNDEFINED ){ 2199 iSortOrder = SQLITE_SO_ASC; 2200 } 2201 pItem->fg.sortFlags = (u8)iSortOrder; 2202 2203 if( eNulls!=SQLITE_SO_UNDEFINED ){ 2204 pItem->fg.bNulls = 1; 2205 if( iSortOrder!=eNulls ){ 2206 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL; 2207 } 2208 } 2209 } 2210 2211 /* 2212 ** Set the ExprList.a[].zEName element of the most recently added item 2213 ** on the expression list. 2214 ** 2215 ** pList might be NULL following an OOM error. But pName should never be 2216 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 2217 ** is set. 2218 */ 2219 void sqlite3ExprListSetName( 2220 Parse *pParse, /* Parsing context */ 2221 ExprList *pList, /* List to which to add the span. */ 2222 const Token *pName, /* Name to be added */ 2223 int dequote /* True to cause the name to be dequoted */ 2224 ){ 2225 assert( pList!=0 || pParse->db->mallocFailed!=0 ); 2226 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 ); 2227 if( pList ){ 2228 struct ExprList_item *pItem; 2229 assert( pList->nExpr>0 ); 2230 pItem = &pList->a[pList->nExpr-1]; 2231 assert( pItem->zEName==0 ); 2232 assert( pItem->fg.eEName==ENAME_NAME ); 2233 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); 2234 if( dequote ){ 2235 /* If dequote==0, then pName->z does not point to part of a DDL 2236 ** statement handled by the parser. And so no token need be added 2237 ** to the token-map. */ 2238 sqlite3Dequote(pItem->zEName); 2239 if( IN_RENAME_OBJECT ){ 2240 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName); 2241 } 2242 } 2243 } 2244 } 2245 2246 /* 2247 ** Set the ExprList.a[].zSpan element of the most recently added item 2248 ** on the expression list. 2249 ** 2250 ** pList might be NULL following an OOM error. But pSpan should never be 2251 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 2252 ** is set. 2253 */ 2254 void sqlite3ExprListSetSpan( 2255 Parse *pParse, /* Parsing context */ 2256 ExprList *pList, /* List to which to add the span. */ 2257 const char *zStart, /* Start of the span */ 2258 const char *zEnd /* End of the span */ 2259 ){ 2260 sqlite3 *db = pParse->db; 2261 assert( pList!=0 || db->mallocFailed!=0 ); 2262 if( pList ){ 2263 struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; 2264 assert( pList->nExpr>0 ); 2265 if( pItem->zEName==0 ){ 2266 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd); 2267 pItem->fg.eEName = ENAME_SPAN; 2268 } 2269 } 2270 } 2271 2272 /* 2273 ** If the expression list pEList contains more than iLimit elements, 2274 ** leave an error message in pParse. 2275 */ 2276 void sqlite3ExprListCheckLength( 2277 Parse *pParse, 2278 ExprList *pEList, 2279 const char *zObject 2280 ){ 2281 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; 2282 testcase( pEList && pEList->nExpr==mx ); 2283 testcase( pEList && pEList->nExpr==mx+1 ); 2284 if( pEList && pEList->nExpr>mx ){ 2285 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); 2286 } 2287 } 2288 2289 /* 2290 ** Delete an entire expression list. 2291 */ 2292 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ 2293 int i = pList->nExpr; 2294 struct ExprList_item *pItem = pList->a; 2295 assert( pList->nExpr>0 ); 2296 assert( db!=0 ); 2297 do{ 2298 sqlite3ExprDelete(db, pItem->pExpr); 2299 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName); 2300 pItem++; 2301 }while( --i>0 ); 2302 sqlite3DbNNFreeNN(db, pList); 2303 } 2304 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ 2305 if( pList ) exprListDeleteNN(db, pList); 2306 } 2307 void sqlite3ExprListDeleteGeneric(sqlite3 *db, void *pList){ 2308 if( ALWAYS(pList) ) exprListDeleteNN(db, (ExprList*)pList); 2309 } 2310 2311 /* 2312 ** Return the bitwise-OR of all Expr.flags fields in the given 2313 ** ExprList. 2314 */ 2315 u32 sqlite3ExprListFlags(const ExprList *pList){ 2316 int i; 2317 u32 m = 0; 2318 assert( pList!=0 ); 2319 for(i=0; inExpr; i++){ 2320 Expr *pExpr = pList->a[i].pExpr; 2321 assert( pExpr!=0 ); 2322 m |= pExpr->flags; 2323 } 2324 return m; 2325 } 2326 2327 /* 2328 ** Check the input string to see if it is "true" or "false" (in any case). 2329 ** 2330 ** If the string is.... Return 2331 ** "true" EP_IsTrue 2332 ** "false" EP_IsFalse 2333 ** anything else 0 2334 */ 2335 u32 sqlite3IsTrueOrFalse(const char *zIn){ 2336 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue; 2337 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse; 2338 return 0; 2339 } 2340 2341 2342 /* 2343 ** If the input expression is an ID with the name "true" or "false" 2344 ** then convert it into an TK_TRUEFALSE term. Return non-zero if 2345 ** the conversion happened, and zero if the expression is unaltered. 2346 */ 2347 int sqlite3ExprIdToTrueFalse(Expr *pExpr){ 2348 u32 v; 2349 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING ); 2350 if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue) 2351 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0 2352 ){ 2353 pExpr->op = TK_TRUEFALSE; 2354 ExprSetProperty(pExpr, v); 2355 return 1; 2356 } 2357 return 0; 2358 } 2359 2360 /* 2361 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE 2362 ** and 0 if it is FALSE. 2363 */ 2364 int sqlite3ExprTruthValue(const Expr *pExpr){ 2365 pExpr = sqlite3ExprSkipCollateAndLikely((Expr*)pExpr); 2366 assert( pExpr->op==TK_TRUEFALSE ); 2367 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 2368 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0 2369 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 ); 2370 return pExpr->u.zToken[4]==0; 2371 } 2372 2373 /* 2374 ** If pExpr is an AND or OR expression, try to simplify it by eliminating 2375 ** terms that are always true or false. Return the simplified expression. 2376 ** Or return the original expression if no simplification is possible. 2377 ** 2378 ** Examples: 2379 ** 2380 ** (x<10) AND true => (x<10) 2381 ** (x<10) AND false => false 2382 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22) 2383 ** (x<10) AND (y=22 OR true) => (x<10) 2384 ** (y=22) OR true => true 2385 */ 2386 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){ 2387 assert( pExpr!=0 ); 2388 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){ 2389 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight); 2390 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft); 2391 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){ 2392 pExpr = pExpr->op==TK_AND ? pRight : pLeft; 2393 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){ 2394 pExpr = pExpr->op==TK_AND ? pLeft : pRight; 2395 } 2396 } 2397 return pExpr; 2398 } 2399 2400 /* 2401 ** Return true if it might be advantageous to compute the right operand 2402 ** of expression pExpr first, before the left operand. 2403 ** 2404 ** Normally the left operand is computed before the right operand. But if 2405 ** the left operand contains a subquery and the right does not, then it 2406 ** might be more efficient to compute the right operand first. 2407 */ 2408 static int exprEvalRhsFirst(Expr *pExpr){ 2409 if( ExprHasProperty(pExpr->pLeft, EP_Subquery) 2410 && !ExprHasProperty(pExpr->pRight, EP_Subquery) 2411 ){ 2412 return 1; 2413 }else{ 2414 return 0; 2415 } 2416 } 2417 2418 /* 2419 ** Compute the two operands of a binary operator. 2420 ** 2421 ** If either operand contains a subquery, then the code strives to 2422 ** compute the operand containing the subquery second. If the other 2423 ** operand evalutes to NULL, then a jump is made. The address of the 2424 ** IsNull operand that does this jump is returned. The caller can use 2425 ** this to optimize the computation so as to avoid doing the potentially 2426 ** expensive subquery. 2427 ** 2428 ** If no optimization opportunities exist, return 0. 2429 */ 2430 static int exprComputeOperands( 2431 Parse *pParse, /* Parsing context */ 2432 Expr *pExpr, /* The comparison expression */ 2433 int *pR1, /* OUT: Register holding the left operand */ 2434 int *pR2, /* OUT: Register holding the right operand */ 2435 int *pFree1, /* OUT: Temp register to free if not zero */ 2436 int *pFree2 /* OUT: Another temp register to free if not zero */ 2437 ){ 2438 int addrIsNull; 2439 int r1, r2; 2440 Vdbe *v = pParse->pVdbe; 2441 2442 assert( v!=0 ); 2443 /* 2444 ** If the left operand contains a (possibly expensive) subquery and the 2445 ** right operand does not and the right operation might be NULL, 2446 ** then compute the right operand first and do an IsNull jump if the 2447 ** right operand evalutes to NULL. 2448 */ 2449 if( exprEvalRhsFirst(pExpr) && sqlite3ExprCanBeNull(pExpr->pRight) ){ 2450 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pFree2); 2451 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, r2); 2452 VdbeComment((v, "skip left operand")); 2453 VdbeCoverage(v); 2454 }else{ 2455 r2 = 0; /* Silence a false-positive uninit-var warning in MSVC */ 2456 addrIsNull = 0; 2457 } 2458 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, pFree1); 2459 if( addrIsNull==0 ){ 2460 /* 2461 ** If the right operand contains a subquery and the left operand does not 2462 ** and the left operand might be NULL, then do an IsNull check 2463 ** check on the left operand before computing the right operand. 2464 */ 2465 if( ExprHasProperty(pExpr->pRight, EP_Subquery) 2466 && sqlite3ExprCanBeNull(pExpr->pLeft) 2467 ){ 2468 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, r1); 2469 VdbeComment((v, "skip right operand")); 2470 VdbeCoverage(v); 2471 } 2472 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pFree2); 2473 } 2474 *pR1 = r1; 2475 *pR2 = r2; 2476 return addrIsNull; 2477 } 2478 2479 /* 2480 ** pExpr is a TK_FUNCTION node. Try to determine whether or not the 2481 ** function is a constant function. A function is constant if all of 2482 ** the following are true: 2483 ** 2484 ** (1) It is a scalar function (not an aggregate or window function) 2485 ** (2) It has either the SQLITE_FUNC_CONSTANT or SQLITE_FUNC_SLOCHNG 2486 ** property. 2487 ** (3) All of its arguments are constants 2488 ** 2489 ** This routine sets pWalker->eCode to 0 if pExpr is not a constant. 2490 ** It makes no changes to pWalker->eCode if pExpr is constant. In 2491 ** every case, it returns WRC_Abort. 2492 ** 2493 ** Called as a service subroutine from exprNodeIsConstant(). 2494 */ 2495 static SQLITE_NOINLINE int exprNodeIsConstantFunction( 2496 Walker *pWalker, 2497 Expr *pExpr 2498 ){ 2499 int n; /* Number of arguments */ 2500 ExprList *pList; /* List of arguments */ 2501 FuncDef *pDef; /* The function */ 2502 sqlite3 *db; /* The database */ 2503 2504 assert( pExpr->op==TK_FUNCTION ); 2505 if( ExprHasProperty(pExpr, EP_TokenOnly) 2506 || (pList = pExpr->x.pList)==0 2507 ){; 2508 n = 0; 2509 }else{ 2510 n = pList->nExpr; 2511 sqlite3WalkExprList(pWalker, pList); 2512 if( pWalker->eCode==0 ) return WRC_Abort; 2513 } 2514 db = pWalker->pParse->db; 2515 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0); 2516 if( pDef==0 2517 || pDef->xFinalize!=0 2518 || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0 2519 || NEVER(ExprHasProperty(pExpr, EP_WinFunc)) 2520 ){ 2521 pWalker->eCode = 0; 2522 return WRC_Abort; 2523 } 2524 return WRC_Prune; 2525 } 2526 2527 2528 /* 2529 ** These routines are Walker callbacks used to check expressions to 2530 ** see if they are "constant" for some definition of constant. The 2531 ** Walker.eCode value determines the type of "constant" we are looking 2532 ** for. 2533 ** 2534 ** These callback routines are used to implement the following: 2535 ** 2536 ** sqlite3ExprIsConstant() pWalker->eCode==1 2537 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 2538 ** sqlite3ExprIsTableConstant() pWalker->eCode==3 2539 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 2540 ** sqlite3ExprListIsConstant() pWalker->eCode==1 or 6 2541 ** 2542 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression 2543 ** is found to not be a constant. 2544 ** 2545 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT 2546 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5 2547 ** when parsing an existing schema out of the sqlite_schema table and 4 2548 ** when processing a new CREATE TABLE statement. A bound parameter raises 2549 ** an error for new statements, but is silently converted 2550 ** to NULL for existing schemas. This allows sqlite_schema tables that 2551 ** contain a bound parameter because they were generated by older versions 2552 ** of SQLite to be parsed by newer versions of SQLite without raising a 2553 ** malformed schema error. 2554 */ 2555 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ 2556 assert( pWalker->eCode>0 ); 2557 2558 /* If pWalker->eCode is 2 then any term of the expression that comes from 2559 ** the ON or USING clauses of an outer join disqualifies the expression 2560 ** from being considered constant. */ 2561 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){ 2562 pWalker->eCode = 0; 2563 return WRC_Abort; 2564 } 2565 2566 switch( pExpr->op ){ 2567 case TK_FUNCTION: 2568 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 2569 pWalker->eCode = 0; /* Window functions are never constant */ 2570 return WRC_Abort; 2571 }else if( pWalker->eCode>=4 && pWalker->eCode<=5 ){ 2572 /* Functions used within a CREATE TABLE statement are constant as 2573 ** long as all of their arguments are constant */ 2574 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL); 2575 return WRC_Continue; 2576 }else if( ExprHasProperty(pExpr,EP_ConstFunc) ){ 2577 /* Functions marked with EP_ConstFunc are constant as long as 2578 ** all their arugments are constant and they are not window functions */ 2579 return WRC_Continue; 2580 }else if( pWalker->pParse ){ 2581 /* Functions are constant if they have SQLITE_FUNC_CONSTANT or 2582 ** SQLITE_FUNC_SLOCHNG and if all arguments are constant */ 2583 return exprNodeIsConstantFunction(pWalker, pExpr); 2584 }else{ 2585 pWalker->eCode = 0; /* Function call is not constant */ 2586 return WRC_Abort; 2587 } 2588 case TK_ID: 2589 /* Convert "true" or "false" in a DEFAULT clause into the 2590 ** appropriate TK_TRUEFALSE operator */ 2591 if( sqlite3ExprIdToTrueFalse(pExpr) ){ 2592 return WRC_Prune; 2593 } 2594 /* no break */ deliberate_fall_through 2595 case TK_COLUMN: 2596 case TK_AGG_FUNCTION: 2597 case TK_AGG_COLUMN: 2598 testcase( pExpr->op==TK_ID ); 2599 testcase( pExpr->op==TK_COLUMN ); 2600 testcase( pExpr->op==TK_AGG_FUNCTION ); 2601 testcase( pExpr->op==TK_AGG_COLUMN ); 2602 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){ 2603 return WRC_Continue; 2604 } 2605 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ 2606 return WRC_Continue; 2607 } 2608 /* no break */ deliberate_fall_through 2609 case TK_IF_NULL_ROW: 2610 case TK_REGISTER: 2611 case TK_DOT: 2612 case TK_RAISE: 2613 testcase( pExpr->op==TK_REGISTER ); 2614 testcase( pExpr->op==TK_IF_NULL_ROW ); 2615 testcase( pExpr->op==TK_DOT ); 2616 testcase( pExpr->op==TK_RAISE ); 2617 pWalker->eCode = 0; 2618 return WRC_Abort; 2619 case TK_IS: 2620 case TK_ISNOT: 2621 if( pWalker->eCode==6 ){ 2622 pWalker->eCode = 0; 2623 return WRC_Abort; 2624 } 2625 return WRC_Continue; 2626 case TK_VARIABLE: 2627 if( pWalker->eCode==5 ){ 2628 /* Silently convert bound parameters that appear inside of CREATE 2629 ** statements into a NULL when parsing the CREATE statement text out 2630 ** of the sqlite_schema table */ 2631 pExpr->op = TK_NULL; 2632 }else if( pWalker->eCode==4 ){ 2633 /* A bound parameter in a CREATE statement that originates from 2634 ** sqlite3_prepare() causes an error */ 2635 pWalker->eCode = 0; 2636 return WRC_Abort; 2637 } 2638 /* no break */ deliberate_fall_through 2639 default: 2640 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */ 2641 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */ 2642 return WRC_Continue; 2643 } 2644 } 2645 static int exprIsConst(Parse *pParse, Expr *p, int initFlag){ 2646 Walker w; 2647 w.eCode = initFlag; 2648 w.pParse = pParse; 2649 w.xExprCallback = exprNodeIsConstant; 2650 w.xSelectCallback = sqlite3SelectWalkFail; 2651 #ifdef SQLITE_DEBUG 2652 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 2653 #endif 2654 sqlite3WalkExpr(&w, p); 2655 return w.eCode; 2656 } 2657 2658 /* 2659 ** Walk an expression tree. Return non-zero if the expression is constant 2660 ** or return zero if the expression involves variables or function calls. 2661 ** 2662 ** For the purposes of this function, a double-quoted string (ex: "abc") 2663 ** is considered a variable but a single-quoted string (ex: 'abc') is 2664 ** a constant. 2665 ** 2666 ** The pParse parameter may be NULL. But if it is NULL, there is no way 2667 ** to determine if function calls are constant or not, and hence all 2668 ** function calls will be considered to be non-constant. If pParse is 2669 ** not NULL, then a function call might be constant, depending on the 2670 ** function and on its parameters. 2671 */ 2672 int sqlite3ExprIsConstant(Parse *pParse, Expr *p){ 2673 return exprIsConst(pParse, p, 1); 2674 } 2675 2676 /* 2677 ** Return true if all expressions in pList are constant. If parameter bNoIs 2678 ** is true, do not consider expressions that contain "IS" operators to be 2679 ** constant. IS operators are not always considered constant as expressions 2680 ** like "x IS TRUE" need to be transformed to TK_TRUTH expression nodes, 2681 ** which happens at the same time as column name resolution. 2682 */ 2683 int sqlite3ExprListIsConstant(Parse *pParse, ExprList *pList, int bNoIs){ 2684 const int iInit = bNoIs ? 6 : 1; 2685 int ii; 2686 for(ii=0; iinExpr; ii++){ 2687 if( 0==exprIsConst(pParse, pList->a[ii].pExpr, iInit) ) return 0; 2688 } 2689 return 1; 2690 } 2691 2692 /* 2693 ** Walk an expression tree. Return non-zero if 2694 ** 2695 ** (1) the expression is constant, and 2696 ** (2) the expression does not originate in the ON or USING clause 2697 ** of a LEFT JOIN, and 2698 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN 2699 ** operands created by the constant propagation optimization. 2700 ** 2701 ** When this routine returns true, it indicates that the expression 2702 ** can be added to the pParse->pConstExpr list and evaluated once when 2703 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce(). 2704 */ 2705 static int sqlite3ExprIsConstantNotJoin(Parse *pParse, Expr *p){ 2706 return exprIsConst(pParse, p, 2); 2707 } 2708 2709 /* 2710 ** This routine examines sub-SELECT statements as an expression is being 2711 ** walked as part of sqlite3ExprIsTableConstant(). Sub-SELECTs are considered 2712 ** constant as long as they are uncorrelated - meaning that they do not 2713 ** contain any terms from outer contexts. 2714 */ 2715 static int exprSelectWalkTableConstant(Walker *pWalker, Select *pSelect){ 2716 assert( pSelect!=0 ); 2717 assert( pWalker->eCode==3 || pWalker->eCode==0 ); 2718 if( (pSelect->selFlags & SF_Correlated)!=0 ){ 2719 pWalker->eCode = 0; 2720 return WRC_Abort; 2721 } 2722 return WRC_Prune; 2723 } 2724 2725 /* 2726 ** Walk an expression tree. Return non-zero if the expression is constant 2727 ** for any single row of the table with cursor iCur. In other words, the 2728 ** expression must not refer to any non-deterministic function nor any 2729 ** table other than iCur. 2730 ** 2731 ** Consider uncorrelated subqueries to be constants if the bAllowSubq 2732 ** parameter is true. 2733 */ 2734 int sqlite3ExprIsTableConstant(Expr *p, int iCur, int bAllowSubq){ 2735 Walker w; 2736 w.eCode = 3; 2737 w.pParse = 0; 2738 w.xExprCallback = exprNodeIsConstant; 2739 if( bAllowSubq ){ 2740 w.xSelectCallback = exprSelectWalkTableConstant; 2741 }else{ 2742 w.xSelectCallback = sqlite3SelectWalkFail; 2743 #ifdef SQLITE_DEBUG 2744 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 2745 #endif 2746 } 2747 w.u.iCur = iCur; 2748 sqlite3WalkExpr(&w, p); 2749 return w.eCode; 2750 } 2751 2752 /* 2753 ** Check pExpr to see if it is an constraint on the single data source 2754 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr 2755 ** constrains pSrc but does not depend on any other tables or data 2756 ** sources anywhere else in the query. Return true (non-zero) if pExpr 2757 ** is a constraint on pSrc only. 2758 ** 2759 ** This is an optimization. False negatives will perhaps cause slower 2760 ** queries, but false positives will yield incorrect answers. So when in 2761 ** doubt, return 0. 2762 ** 2763 ** To be an single-source constraint, the following must be true: 2764 ** 2765 ** (1) pExpr cannot refer to any table other than pSrc->iCursor. 2766 ** 2767 ** (2a) pExpr cannot use subqueries unless the bAllowSubq parameter is 2768 ** true and the subquery is non-correlated 2769 ** 2770 ** (2b) pExpr cannot use non-deterministic functions. 2771 ** 2772 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN. 2773 ** (Is there some way to relax this constraint?) 2774 ** 2775 ** (4) If pSrc is the right operand of a LEFT JOIN, then... 2776 ** (4a) pExpr must come from an ON clause.. 2777 ** (4b) and specifically the ON clause associated with the LEFT JOIN. 2778 ** 2779 ** (5) If pSrc is the right operand of a LEFT JOIN or the left 2780 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE 2781 ** clause, not an ON clause. 2782 ** 2783 ** (6) Either: 2784 ** 2785 ** (6a) pExpr does not originate in an ON or USING clause, or 2786 ** 2787 ** (6b) The ON or USING clause from which pExpr is derived is 2788 ** not to the left of a RIGHT JOIN (or FULL JOIN). 2789 ** 2790 ** Without this restriction, accepting pExpr as a single-table 2791 ** constraint might move the the ON/USING filter expression 2792 ** from the left side of a RIGHT JOIN over to the right side, 2793 ** which leads to incorrect answers. See also restriction (9) 2794 ** on push-down. 2795 */ 2796 int sqlite3ExprIsSingleTableConstraint( 2797 Expr *pExpr, /* The constraint */ 2798 const SrcList *pSrcList, /* Complete FROM clause */ 2799 int iSrc, /* Which element of pSrcList to use */ 2800 int bAllowSubq /* Allow non-correlated subqueries */ 2801 ){ 2802 const SrcItem *pSrc = &pSrcList->a[iSrc]; 2803 if( pSrc->fg.jointype & JT_LTORJ ){ 2804 return 0; /* rule (3) */ 2805 } 2806 if( pSrc->fg.jointype & JT_LEFT ){ 2807 if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (4a) */ 2808 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */ 2809 }else{ 2810 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (5) */ 2811 } 2812 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) /* (6a) */ 2813 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */ 2814 ){ 2815 int jj; 2816 for(jj=0; jjw.iJoin==pSrcList->a[jj].iCursor ){ 2818 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){ 2819 return 0; /* restriction (6) */ 2820 } 2821 break; 2822 } 2823 } 2824 } 2825 /* Rules (1), (2a), and (2b) handled by the following: */ 2826 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq); 2827 } 2828 2829 2830 /* 2831 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy(). 2832 */ 2833 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){ 2834 ExprList *pGroupBy = pWalker->u.pGroupBy; 2835 int i; 2836 2837 /* Check if pExpr is identical to any GROUP BY term. If so, consider 2838 ** it constant. */ 2839 for(i=0; inExpr; i++){ 2840 Expr *p = pGroupBy->a[i].pExpr; 2841 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){ 2842 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p); 2843 if( sqlite3IsBinary(pColl) ){ 2844 return WRC_Prune; 2845 } 2846 } 2847 } 2848 2849 /* Check if pExpr is a sub-select. If so, consider it variable. */ 2850 if( ExprUseXSelect(pExpr) ){ 2851 pWalker->eCode = 0; 2852 return WRC_Abort; 2853 } 2854 2855 return exprNodeIsConstant(pWalker, pExpr); 2856 } 2857 2858 /* 2859 ** Walk the expression tree passed as the first argument. Return non-zero 2860 ** if the expression consists entirely of constants or copies of terms 2861 ** in pGroupBy that sort with the BINARY collation sequence. 2862 ** 2863 ** This routine is used to determine if a term of the HAVING clause can 2864 ** be promoted into the WHERE clause. In order for such a promotion to work, 2865 ** the value of the HAVING clause term must be the same for all members of 2866 ** a "group". The requirement that the GROUP BY term must be BINARY 2867 ** assumes that no other collating sequence will have a finer-grained 2868 ** grouping than binary. In other words (A=B COLLATE binary) implies 2869 ** A=B in every other collating sequence. The requirement that the 2870 ** GROUP BY be BINARY is stricter than necessary. It would also work 2871 ** to promote HAVING clauses that use the same alternative collating 2872 ** sequence as the GROUP BY term, but that is much harder to check, 2873 ** alternative collating sequences are uncommon, and this is only an 2874 ** optimization, so we take the easy way out and simply require the 2875 ** GROUP BY to use the BINARY collating sequence. 2876 */ 2877 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){ 2878 Walker w; 2879 w.eCode = 1; 2880 w.xExprCallback = exprNodeIsConstantOrGroupBy; 2881 w.xSelectCallback = 0; 2882 w.u.pGroupBy = pGroupBy; 2883 w.pParse = pParse; 2884 sqlite3WalkExpr(&w, p); 2885 return w.eCode; 2886 } 2887 2888 /* 2889 ** Walk an expression tree for the DEFAULT field of a column definition 2890 ** in a CREATE TABLE statement. Return non-zero if the expression is 2891 ** acceptable for use as a DEFAULT. That is to say, return non-zero if 2892 ** the expression is constant or a function call with constant arguments. 2893 ** Return and 0 if there are any variables. 2894 ** 2895 ** isInit is true when parsing from sqlite_schema. isInit is false when 2896 ** processing a new CREATE TABLE statement. When isInit is true, parameters 2897 ** (such as ? or $abc) in the expression are converted into NULL. When 2898 ** isInit is false, parameters raise an error. Parameters should not be 2899 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite 2900 ** allowed it, so we need to support it when reading sqlite_schema for 2901 ** backwards compatibility. 2902 ** 2903 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node. 2904 ** 2905 ** For the purposes of this function, a double-quoted string (ex: "abc") 2906 ** is considered a variable but a single-quoted string (ex: 'abc') is 2907 ** a constant. 2908 */ 2909 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ 2910 assert( isInit==0 || isInit==1 ); 2911 return exprIsConst(0, p, 4+isInit); 2912 } 2913 2914 /* 2915 ** Walk an expression tree. Return 1 if the expression contains a 2916 ** subquery of some kind. Return 0 if there are no subqueries. 2917 */ 2918 int sqlite3ExprContainsSubquery(Expr *p){ 2919 Walker w; 2920 w.eCode = 1; 2921 w.xExprCallback = sqlite3ExprWalkNoop; 2922 w.xSelectCallback = sqlite3SelectWalkFail; 2923 #ifdef SQLITE_DEBUG 2924 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 2925 #endif 2926 sqlite3WalkExpr(&w, p); 2927 return w.eCode==0; 2928 } 2929 2930 /* 2931 ** If the expression p codes a constant integer between 0 and 0x7fffffff, 2932 ** then return 1 and put the value of the integer in *pValue. If the 2933 ** expression is not an integer or if it is an integer that is out side 2934 ** the range of 0...0x7fffffff, then return 0 and leave *pValue unchanged. 2935 ** 2936 ** If the pParse pointer is provided, then allow the expression p to be 2937 ** a parameter (TK_VARIABLE) that is bound to an integer between 0 and 2938 ** 0x7fffffff. Variables that hold anything other than integers, or that 2939 ** hold integers outside the range of 0..0x7fffffff are not seen. 2940 ** But if pParse is NULL, then p must be a pure integer literal between 2941 ** 0 and 0x7fffffff. 2942 ** 2943 ** If pParse is not NULL and expression p is a variable, then the variable 2944 ** is marked so as to cause the statement to be reprepared each time a new 2945 ** value is bound to it. Except, if parameter bRSI is true, then the statement 2946 ** will only be reprepared if the rebind changes the value to or from a 2947 ** "small integer" (either 0 or 1). 2948 ** 2949 ** If pParse is NULL but bRSI is non-zero, then to not accept the input 2950 ** as an integer if the TK_INTEGER opcode has its op2 field set to non-zero. 2951 ** A non-zero Expr.op2 indicates that the expression is a compile-time 2952 ** reduction of a constant expression. For example, "123 NOTNULL" would 2953 ** be rendered by the parser as a TK_INTEGER with value 1, but with op2 set. 2954 ** 2955 ** Summary: 2956 ** 2957 ** pParse bRsi What happens 2958 ** -------- ---- ------------------------------------------------ 2959 ** NULL 0 Reject if TK_VARIABLE. Accept if op2!=0 2960 ** 2961 ** NULL 1 Reject if TK_VARIABLE or op2!=0 2962 ** 2963 ** not-NULL 0 Accept TK_VARIABLE and/or op2!=0 but for TK_VARIABLE, 2964 ** cause the statement to reprepare on *any* 2965 ** binding change 2966 ** 2967 ** not-NULL 1 As previous, except reprepare only happens if a binding 2968 ** change move the variable value to or from an integer 0 2969 ** or 1. 2970 */ 2971 int sqlite3ExprIsInteger(const Expr *p, int *pValue, Parse *pParse, int bRSI){ 2972 int iSign = 1; /* Either +1 or -1. */ 2973 while( 1/*exit-by-break*/ ){ 2974 if( NEVER(p==0) ) return 0; 2975 if( ExprUseUValue(p) ){ 2976 assert( p->op==TK_INTEGER ); 2977 *pValue = p->u.iValue*iSign; 2978 if( bRSI && pParse==0 && p->op2 ){ 2979 return 0; 2980 } 2981 return 1; 2982 } 2983 if( p->op==TK_UPLUS ){ 2984 p = p->pLeft; 2985 pParse = 0; 2986 continue; 2987 } 2988 if( p->op==TK_UMINUS ){ 2989 iSign = -iSign; 2990 p = p->pLeft; 2991 pParse = 0; 2992 continue; 2993 } 2994 if( p->op==TK_VARIABLE && pParse!=0 ){ 2995 sqlite3_value *pVal; /* The variable */ 2996 int rc = 0; /* 1 if successful, 0 if failed */ 2997 assert( iSign==1 ); 2998 if( NEVER(pParse->pVdbe==0) ) break; 2999 if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) break; 3000 pVal = sqlite3VdbeGetBoundValue(pParse->pReprepare, p->iColumn, 3001 SQLITE_AFF_BLOB); 3002 if( pVal ){ 3003 i64 vv; 3004 if( sqlite3_value_type(pVal)==SQLITE_INTEGER 3005 && (vv = sqlite3_value_int64(pVal))>=0 3006 && vv<=0x7fffffff 3007 ){ 3008 *pValue = (int)vv; 3009 rc = 1; 3010 } 3011 sqlite3ValueFree(pVal); 3012 } 3013 sqlite3VdbeReprepareOnBind(pParse->pVdbe, p->iColumn, bRSI); 3014 return rc; 3015 } 3016 break; 3017 } 3018 return 0; 3019 } 3020 3021 /* 3022 ** Return FALSE if there is no chance that the expression can be NULL. 3023 ** 3024 ** If the expression might be NULL or if the expression is too complex 3025 ** to tell return TRUE. 3026 ** 3027 ** This routine is used as an optimization, to skip OP_IsNull opcodes 3028 ** when we know that a value cannot be NULL. Hence, a false positive 3029 ** (returning TRUE when in fact the expression can never be NULL) might 3030 ** be a small performance hit but is otherwise harmless. On the other 3031 ** hand, a false negative (returning FALSE when the result could be NULL) 3032 ** will likely result in an incorrect answer. So when in doubt, return 3033 ** TRUE. 3034 */ 3035 int sqlite3ExprCanBeNull(const Expr *p){ 3036 u8 op; 3037 assert( p!=0 ); 3038 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ 3039 p = p->pLeft; 3040 assert( p!=0 ); 3041 } 3042 op = p->op; 3043 if( op==TK_REGISTER ) op = p->op2; 3044 switch( op ){ 3045 case TK_INTEGER: 3046 case TK_STRING: 3047 case TK_FLOAT: 3048 case TK_BLOB: 3049 return 0; 3050 case TK_COLUMN: 3051 assert( ExprUseYTab(p) ); 3052 return ExprHasProperty(p, EP_CanBeNull) 3053 || NEVER(p->y.pTab==0) /* Reference to column of index on expr */ 3054 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW 3055 || (p->iColumn==XN_ROWID && IsView(p->y.pTab)) 3056 #endif 3057 || (p->iColumn>=0 3058 && p->y.pTab->aCol!=0 /* Possible due to prior error */ 3059 && ALWAYS(p->iColumny.pTab->nCol) 3060 && p->y.pTab->aCol[p->iColumn].notNull==0); 3061 default: 3062 return 1; 3063 } 3064 } 3065 3066 /* 3067 ** Return TRUE if the given expression is a constant which would be 3068 ** unchanged by OP_Affinity with the affinity given in the second 3069 ** argument. 3070 ** 3071 ** This routine is used to determine if the OP_Affinity operation 3072 ** can be omitted. When in doubt return FALSE. A false negative 3073 ** is harmless. A false positive, however, can result in the wrong 3074 ** answer. 3075 */ 3076 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ 3077 u8 op; 3078 int unaryMinus = 0; 3079 if( aff==SQLITE_AFF_BLOB ) return 1; 3080 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ 3081 if( p->op==TK_UMINUS ) unaryMinus = 1; 3082 p = p->pLeft; 3083 } 3084 op = p->op; 3085 if( op==TK_REGISTER ) op = p->op2; 3086 switch( op ){ 3087 case TK_INTEGER: { 3088 return aff>=SQLITE_AFF_NUMERIC; 3089 } 3090 case TK_FLOAT: { 3091 return aff>=SQLITE_AFF_NUMERIC; 3092 } 3093 case TK_STRING: { 3094 return !unaryMinus && aff==SQLITE_AFF_TEXT; 3095 } 3096 case TK_BLOB: { 3097 return !unaryMinus; 3098 } 3099 case TK_COLUMN: { 3100 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ 3101 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0; 3102 } 3103 default: { 3104 return 0; 3105 } 3106 } 3107 } 3108 3109 /* 3110 ** Return TRUE if the given string is a row-id column name. 3111 */ 3112 int sqlite3IsRowid(const char *z){ 3113 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; 3114 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; 3115 if( sqlite3StrICmp(z, "OID")==0 ) return 1; 3116 return 0; 3117 } 3118 3119 /* 3120 ** Return a pointer to a buffer containing a usable rowid alias for table 3121 ** pTab. An alias is usable if there is not an explicit user-defined column 3122 ** of the same name. 3123 */ 3124 const char *sqlite3RowidAlias(Table *pTab){ 3125 const char *azOpt[] = {"_ROWID_", "ROWID", "OID"}; 3126 int ii; 3127 assert( VisibleRowid(pTab) ); 3128 for(ii=0; iix.pSelect; 3151 if( p->pPrior ) return 0; /* Not a compound SELECT */ 3152 if( p->selFlags & SF_Aggregate ){ 3153 return 0; /* No GROUP BY keyword or aggregate functions */ 3154 } 3155 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ 3156 if( p->pLimit ) return 0; /* Has no LIMIT clause */ 3157 if( p->pWhere ) return 0; /* Has no WHERE clause */ 3158 pSrc = p->pSrc; 3159 assert( pSrc!=0 ); 3160 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ 3161 if( pSrc->a[0].fg.isSubquery) return 0;/* FROM is not a subquery or view */ 3162 pTab = pSrc->a[0].pSTab; 3163 assert( pTab!=0 ); 3164 assert( !IsView(pTab) ); /* FROM clause is not a view */ 3165 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ 3166 pEList = p->pEList; 3167 assert( pEList!=0 ); 3168 /* All SELECT results must be columns. */ 3169 for(i=0; inExpr; i++){ 3170 Expr *pRes = pEList->a[i].pExpr; 3171 if( pRes->op!=TK_COLUMN ) return 0; 3172 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */ 3173 } 3174 return p; 3175 } 3176 #endif /* SQLITE_OMIT_SUBQUERY */ 3177 3178 #ifndef SQLITE_OMIT_SUBQUERY 3179 /* 3180 ** Generate code that checks the left-most column of index table iCur to see if 3181 ** it contains any NULL entries. Cause the register at regHasNull to be set 3182 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull 3183 ** to be set to NULL if iCur contains one or more NULL values. 3184 */ 3185 static void sqlite3SetHasNullFlag( 3186 Vdbe *v, /* Write new code into this statement under construction */ 3187 int iCur, /* Cursor for the index */ 3188 int regHasNull, /* Register in which to store hasNull flag */ 3189 int eSortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ 3190 ){ 3191 int addr1; 3192 int op; 3193 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); 3194 if( eSortOrder==SQLITE_SO_ASC ){ 3195 op = OP_Rewind; 3196 }else{ 3197 op = OP_Last; 3198 } 3199 addr1 = sqlite3VdbeAddOp1(v, op, iCur); VdbeCoverage(v); 3200 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); 3201 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); 3202 VdbeComment((v, op==OP_Last?"last_entry_in(%d)":"first_entry_in(%d)", iCur)); 3203 sqlite3VdbeJumpHere(v, addr1); 3204 } 3205 #endif 3206 3207 3208 #ifndef SQLITE_OMIT_SUBQUERY 3209 /* 3210 ** The argument is an IN operator with a list (not a subquery) on the 3211 ** right-hand side. Return TRUE if that list is constant. 3212 */ 3213 static int sqlite3InRhsIsConstant(Parse *pParse, Expr *pIn){ 3214 Expr *pLHS; 3215 int res; 3216 assert( !ExprHasProperty(pIn, EP_xIsSelect) ); 3217 pLHS = pIn->pLeft; 3218 pIn->pLeft = 0; 3219 res = sqlite3ExprIsConstant(pParse, pIn); 3220 pIn->pLeft = pLHS; 3221 return res; 3222 } 3223 #endif 3224 3225 /* 3226 ** This function is used by the implementation of the IN (...) operator. 3227 ** The pX parameter is the expression on the RHS of the IN operator, which 3228 ** might be either a list of expressions or a subquery. 3229 ** 3230 ** The job of this routine is to find or create a b-tree object that can 3231 ** be used either to test for membership in the RHS set or to iterate through 3232 ** all members of the RHS set, skipping duplicates. 3233 ** 3234 ** A cursor is opened on the b-tree object that is the RHS of the IN operator 3235 ** and the *piTab parameter is set to the index of that cursor. 3236 ** 3237 ** The returned value of this function indicates the b-tree type, as follows: 3238 ** 3239 ** IN_INDEX_ROWID - The cursor was opened on a database table. 3240 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. 3241 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. 3242 ** IN_INDEX_EPH - The cursor was opened on a specially created and 3243 ** populated ephemeral table. 3244 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be 3245 ** implemented as a sequence of comparisons. 3246 ** 3247 ** An existing b-tree might be used if the RHS expression pX is a simple 3248 ** subquery such as: 3249 ** 3250 ** SELECT , ... FROM 3251 ** 3252 ** If the RHS of the IN operator is a list or a more complex subquery, then 3253 ** an ephemeral table might need to be generated from the RHS and then 3254 ** pX->iTable made to point to the ephemeral table instead of an 3255 ** existing table. In this case, the creation and initialization of the 3256 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag 3257 ** will be set on pX and the pX->y.sub fields will be set to show where 3258 ** the subroutine is coded. 3259 ** 3260 ** The inFlags parameter must contain, at a minimum, one of the bits 3261 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains 3262 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast 3263 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will 3264 ** be used to loop over all values of the RHS of the IN operator. 3265 ** 3266 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate 3267 ** through the set members) then the b-tree must not contain duplicates. 3268 ** An ephemeral table will be created unless the selected columns are guaranteed 3269 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to 3270 ** a UNIQUE constraint or index. 3271 ** 3272 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 3273 ** for fast set membership tests) then an ephemeral table must 3274 ** be used unless is a single INTEGER PRIMARY KEY column or an 3275 ** index can be found with the specified as its left-most. 3276 ** 3277 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and 3278 ** if the RHS of the IN operator is a list (not a subquery) then this 3279 ** routine might decide that creating an ephemeral b-tree for membership 3280 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the 3281 ** calling routine should implement the IN operator using a sequence 3282 ** of Eq or Ne comparison operations. 3283 ** 3284 ** When the b-tree is being used for membership tests, the calling function 3285 ** might need to know whether or not the RHS side of the IN operator 3286 ** contains a NULL. If prRhsHasNull is not a NULL pointer and 3287 ** if there is any chance that the (...) might contain a NULL value at 3288 ** runtime, then a register is allocated and the register number written 3289 ** to *prRhsHasNull. If there is no chance that the (...) contains a 3290 ** NULL value, then *prRhsHasNull is left unchanged. 3291 ** 3292 ** If a register is allocated and its location stored in *prRhsHasNull, then 3293 ** the value in that register will be NULL if the b-tree contains one or more 3294 ** NULL values, and it will be some non-NULL value if the b-tree contains no 3295 ** NULL values. 3296 ** 3297 ** If the aiMap parameter is not NULL, it must point to an array containing 3298 ** one element for each column returned by the SELECT statement on the RHS 3299 ** of the IN(...) operator. The i'th entry of the array is populated with the 3300 ** offset of the index column that matches the i'th column returned by the 3301 ** SELECT. For example, if the expression and selected index are: 3302 ** 3303 ** (?,?,?) IN (SELECT a, b, c FROM t1) 3304 ** CREATE INDEX i1 ON t1(b, c, a); 3305 ** 3306 ** then aiMap[] is populated with {2, 0, 1}. 3307 */ 3308 #ifndef SQLITE_OMIT_SUBQUERY 3309 int sqlite3FindInIndex( 3310 Parse *pParse, /* Parsing context */ 3311 Expr *pX, /* The IN expression */ 3312 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ 3313 int *prRhsHasNull, /* Register holding NULL status. See notes */ 3314 int *aiMap, /* Mapping from Index fields to RHS fields */ 3315 int *piTab /* OUT: index to use */ 3316 ){ 3317 Select *p; /* SELECT to the right of IN operator */ 3318 int eType = 0; /* Type of RHS table. IN_INDEX_* */ 3319 int iTab; /* Cursor of the RHS table */ 3320 int mustBeUnique; /* True if RHS must be unique */ 3321 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ 3322 3323 assert( pX->op==TK_IN ); 3324 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; 3325 iTab = pParse->nTab++; 3326 3327 /* If the RHS of this IN(...) operator is a SELECT, and if it matters 3328 ** whether or not the SELECT result contains NULL values, check whether 3329 ** or not NULL is actually possible (it may not be, for example, due 3330 ** to NOT NULL constraints in the schema). If no NULL values are possible, 3331 ** set prRhsHasNull to 0 before continuing. */ 3332 if( prRhsHasNull && ExprUseXSelect(pX) ){ 3333 int i; 3334 ExprList *pEList = pX->x.pSelect->pEList; 3335 for(i=0; inExpr; i++){ 3336 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; 3337 } 3338 if( i==pEList->nExpr ){ 3339 prRhsHasNull = 0; 3340 } 3341 } 3342 3343 /* Check to see if an existing table or index can be used to 3344 ** satisfy the query. This is preferable to generating a new 3345 ** ephemeral table. */ 3346 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ 3347 sqlite3 *db = pParse->db; /* Database connection */ 3348 Table *pTab; /* Table
. */ 3349 int iDb; /* Database idx for pTab */ 3350 ExprList *pEList = p->pEList; 3351 int nExpr = pEList->nExpr; 3352 3353 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ 3354 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ 3355 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ 3356 pTab = p->pSrc->a[0].pSTab; 3357 3358 /* Code an OP_Transaction and OP_TableLock for
. */ 3359 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 3360 assert( iDb>=0 && iDbtnum, 0, pTab->zName); 3363 3364 assert(v); /* sqlite3GetVdbe() has always been previously called */ 3365 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ 3366 /* The "x IN (SELECT rowid FROM table)" case */ 3367 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); 3368 VdbeCoverage(v); 3369 3370 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 3371 eType = IN_INDEX_ROWID; 3372 ExplainQueryPlan((pParse, 0, 3373 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName)); 3374 sqlite3VdbeJumpHere(v, iAddr); 3375 }else{ 3376 Index *pIdx; /* Iterator variable */ 3377 int affinity_ok = 1; 3378 int i; 3379 3380 /* Check that the affinity that will be used to perform each 3381 ** comparison is the same as the affinity of each column in table 3382 ** on the RHS of the IN operator. If it not, it is not possible to 3383 ** use any index of the RHS table. */ 3384 for(i=0; ipLeft, i); 3386 int iCol = pEList->a[i].pExpr->iColumn; 3387 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ 3388 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); 3389 testcase( cmpaff==SQLITE_AFF_BLOB ); 3390 testcase( cmpaff==SQLITE_AFF_TEXT ); 3391 switch( cmpaff ){ 3392 case SQLITE_AFF_BLOB: 3393 break; 3394 case SQLITE_AFF_TEXT: 3395 /* sqlite3CompareAffinity() only returns TEXT if one side or the 3396 ** other has no affinity and the other side is TEXT. Hence, 3397 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT 3398 ** and for the term on the LHS of the IN to have no affinity. */ 3399 assert( idxaff==SQLITE_AFF_TEXT ); 3400 break; 3401 default: 3402 affinity_ok = sqlite3IsNumericAffinity(idxaff); 3403 } 3404 } 3405 3406 if( affinity_ok ){ 3407 /* Search for an existing index that will work for this IN operator */ 3408 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){ 3409 Bitmask colUsed; /* Columns of the index used */ 3410 Bitmask mCol; /* Mask for the current column */ 3411 if( pIdx->nColumnpPartIdxWhere!=0 ) continue; 3413 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute 3414 ** BITMASK(nExpr) without overflowing */ 3415 testcase( pIdx->nColumn==BMS-2 ); 3416 testcase( pIdx->nColumn==BMS-1 ); 3417 if( pIdx->nColumn>=BMS-1 ) continue; 3418 if( mustBeUnique ){ 3419 if( pIdx->nKeyCol>nExpr 3420 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx)) 3421 ){ 3422 continue; /* This index is not unique over the IN RHS columns */ 3423 } 3424 } 3425 3426 colUsed = 0; /* Columns of index used so far */ 3427 for(i=0; ipLeft, i); 3429 Expr *pRhs = pEList->a[i].pExpr; 3430 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); 3431 int j; 3432 3433 for(j=0; jaiColumn[j]!=pRhs->iColumn ) continue; 3435 assert( pIdx->azColl[j] ); 3436 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ 3437 continue; 3438 } 3439 break; 3440 } 3441 if( j==nExpr ) break; 3442 mCol = MASKBIT(j); 3443 if( mCol & colUsed ) break; /* Each column used only once */ 3444 colUsed |= mCol; 3445 if( aiMap ) aiMap[i] = j; 3446 } 3447 3448 assert( nExpr>0 && nExprzName)); 3455 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); 3456 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 3457 VdbeComment((v, "%s", pIdx->zName)); 3458 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); 3459 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; 3460 3461 if( prRhsHasNull ){ 3462 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 3463 u64 mask = (1<nMem; 3468 if( nExpr==1 ){ 3469 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull, 3470 pIdx->aSortOrder[0]); 3471 } 3472 } 3473 sqlite3VdbeJumpHere(v, iAddr); 3474 } 3475 } /* End loop over indexes */ 3476 } /* End if( affinity_ok ) */ 3477 } /* End if not an rowid index */ 3478 } /* End attempt to optimize using an index */ 3479 3480 /* If no preexisting index is available for the IN clause 3481 ** and IN_INDEX_NOOP is an allowed reply 3482 ** and the RHS of the IN operator is a list, not a subquery 3483 ** and the RHS is not constant or has two or fewer terms, 3484 ** then it is not worth creating an ephemeral table to evaluate 3485 ** the IN operator so return IN_INDEX_NOOP. 3486 */ 3487 if( eType==0 3488 && (inFlags & IN_INDEX_NOOP_OK) 3489 && ExprUseXList(pX) 3490 && (!sqlite3InRhsIsConstant(pParse,pX) || pX->x.pList->nExpr<=2) 3491 ){ 3492 pParse->nTab--; /* Back out the allocation of the unused cursor */ 3493 iTab = -1; /* Cursor is not allocated */ 3494 eType = IN_INDEX_NOOP; 3495 } 3496 3497 if( eType==0 ){ 3498 /* Could not find an existing table or index to use as the RHS b-tree. 3499 ** We will have to generate an ephemeral table to do the job. 3500 */ 3501 u32 savedNQueryLoop = pParse->nQueryLoop; 3502 int rMayHaveNull = 0; 3503 int bloomOk = (inFlags & IN_INDEX_MEMBERSHIP)!=0; 3504 eType = IN_INDEX_EPH; 3505 if( inFlags & IN_INDEX_LOOP ){ 3506 pParse->nQueryLoop = 0; 3507 }else if( prRhsHasNull ){ 3508 *prRhsHasNull = rMayHaveNull = ++pParse->nMem; 3509 } 3510 assert( pX->op==TK_IN ); 3511 if( !bloomOk 3512 && ExprUseXSelect(pX) 3513 && (pX->x.pSelect->selFlags & SF_ClonedRhsIn)!=0 3514 ){ 3515 bloomOk = 1; 3516 } 3517 sqlite3CodeRhsOfIN(pParse, pX, iTab, bloomOk); 3518 if( rMayHaveNull ){ 3519 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull, SQLITE_SO_ASC); 3520 } 3521 pParse->nQueryLoop = savedNQueryLoop; 3522 } 3523 3524 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ 3525 int i, n; 3526 n = sqlite3ExprVectorSize(pX->pLeft); 3527 for(i=0; ipLeft; 3550 int nVal = sqlite3ExprVectorSize(pLeft); 3551 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0; 3552 char *zRet; 3553 3554 assert( pExpr->op==TK_IN ); 3555 zRet = sqlite3DbMallocRaw(pParse->db, 1+(i64)nVal); 3556 if( zRet ){ 3557 int i; 3558 for(i=0; ipEList->a[i].pExpr, a); 3563 }else{ 3564 zRet[i] = a; 3565 } 3566 if( zRet[i]==SQLITE_AFF_REAL ) zRet[i] = SQLITE_AFF_NUMERIC; 3567 } 3568 zRet[nVal] = '\0'; 3569 } 3570 return zRet; 3571 } 3572 #endif 3573 3574 #ifndef SQLITE_OMIT_SUBQUERY 3575 /* 3576 ** Load the Parse object passed as the first argument with an error 3577 ** message of the form: 3578 ** 3579 ** "sub-select returns N columns - expected M" 3580 */ 3581 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ 3582 if( pParse->nErr==0 ){ 3583 const char *zFmt = "sub-select returns %d columns - expected %d"; 3584 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); 3585 } 3586 } 3587 #endif 3588 3589 /* 3590 ** Expression pExpr is a vector that has been used in a context where 3591 ** it is not permitted. If pExpr is a sub-select vector, this routine 3592 ** loads the Parse object with a message of the form: 3593 ** 3594 ** "sub-select returns N columns - expected 1" 3595 ** 3596 ** Or, if it is a regular scalar vector: 3597 ** 3598 ** "row value misused" 3599 */ 3600 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){ 3601 #ifndef SQLITE_OMIT_SUBQUERY 3602 if( ExprUseXSelect(pExpr) ){ 3603 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1); 3604 }else 3605 #endif 3606 { 3607 sqlite3ErrorMsg(pParse, "row value misused"); 3608 } 3609 } 3610 3611 #ifndef SQLITE_OMIT_SUBQUERY 3612 /* 3613 ** Scan all previously generated bytecode looking for an OP_BeginSubrtn 3614 ** that is compatible with pExpr. If found, add the y.sub values 3615 ** to pExpr and return true. If not found, return false. 3616 */ 3617 static int findCompatibleInRhsSubrtn( 3618 Parse *pParse, /* Parsing context */ 3619 Expr *pExpr, /* IN operator with RHS that we want to reuse */ 3620 SubrtnSig *pNewSig /* Signature for the IN operator */ 3621 ){ 3622 VdbeOp *pOp, *pEnd; 3623 SubrtnSig *pSig; 3624 Vdbe *v; 3625 3626 if( pNewSig==0 ) return 0; 3627 if( (pParse->mSubrtnSig & (1<<(pNewSig->selId&7)))==0 ) return 0; 3628 assert( pExpr->op==TK_IN ); 3629 assert( !ExprUseYSub(pExpr) ); 3630 assert( ExprUseXSelect(pExpr) ); 3631 assert( pExpr->x.pSelect!=0 ); 3632 assert( (pExpr->x.pSelect->selFlags & SF_All)==0 ); 3633 v = pParse->pVdbe; 3634 assert( v!=0 ); 3635 pOp = sqlite3VdbeGetOp(v, 1); 3636 pEnd = sqlite3VdbeGetLastOp(v); 3637 for(; pOpp4type!=P4_SUBRTNSIG ) continue; 3639 assert( pOp->opcode==OP_BeginSubrtn ); 3640 pSig = pOp->p4.pSubrtnSig; 3641 assert( pSig!=0 ); 3642 if( !pSig->bComplete ) continue; 3643 if( pNewSig->selId!=pSig->selId ) continue; 3644 if( strcmp(pNewSig->zAff,pSig->zAff)!=0 ) continue; 3645 pExpr->y.sub.iAddr = pSig->iAddr; 3646 pExpr->y.sub.regReturn = pSig->regReturn; 3647 pExpr->iTable = pSig->iTable; 3648 ExprSetProperty(pExpr, EP_Subrtn); 3649 return 1; 3650 } 3651 return 0; 3652 } 3653 #endif /* SQLITE_OMIT_SUBQUERY */ 3654 3655 #ifndef SQLITE_OMIT_SUBQUERY 3656 /* 3657 ** Generate code that will construct an ephemeral table containing all terms 3658 ** in the RHS of an IN operator. The IN operator can be in either of two 3659 ** forms: 3660 ** 3661 ** x IN (4,5,11) -- IN operator with list on right-hand side 3662 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right 3663 ** 3664 ** The pExpr parameter is the IN operator. The cursor number for the 3665 ** constructed ephemeral table is returned. The first time the ephemeral 3666 ** table is computed, the cursor number is also stored in pExpr->iTable, 3667 ** however the cursor number returned might not be the same, as it might 3668 ** have been duplicated using OP_OpenDup. 3669 ** 3670 ** If the LHS expression ("x" in the examples) is a column value, or 3671 ** the SELECT statement returns a column value, then the affinity of that 3672 ** column is used to build the index keys. If both 'x' and the 3673 ** SELECT... statement are columns, then numeric affinity is used 3674 ** if either column has NUMERIC or INTEGER affinity. If neither 3675 ** 'x' nor the SELECT... statement are columns, then numeric affinity 3676 ** is used. 3677 */ 3678 void sqlite3CodeRhsOfIN( 3679 Parse *pParse, /* Parsing context */ 3680 Expr *pExpr, /* The IN operator */ 3681 int iTab, /* Use this cursor number */ 3682 int allowBloom /* True to allow the use of a Bloom filter */ 3683 ){ 3684 int addrOnce = 0; /* Address of the OP_Once instruction at top */ 3685 int addr; /* Address of OP_OpenEphemeral instruction */ 3686 Expr *pLeft; /* the LHS of the IN operator */ 3687 KeyInfo *pKeyInfo = 0; /* Key information */ 3688 int nVal; /* Size of vector pLeft */ 3689 Vdbe *v; /* The prepared statement under construction */ 3690 SubrtnSig *pSig = 0; /* Signature for this subroutine */ 3691 3692 v = pParse->pVdbe; 3693 assert( v!=0 ); 3694 3695 /* The evaluation of the IN must be repeated every time it 3696 ** is encountered if any of the following is true: 3697 ** 3698 ** * The right-hand side is a correlated subquery 3699 ** * The right-hand side is an expression list containing variables 3700 ** * We are inside a trigger 3701 ** 3702 ** If all of the above are false, then we can compute the RHS just once 3703 ** and reuse it many names. 3704 */ 3705 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){ 3706 /* Reuse of the RHS is allowed 3707 ** 3708 ** Compute a signature for the RHS of the IN operator to facility 3709 ** finding and reusing prior instances of the same IN operator. 3710 */ 3711 assert( !ExprUseXSelect(pExpr) || pExpr->x.pSelect!=0 ); 3712 if( ExprUseXSelect(pExpr) && (pExpr->x.pSelect->selFlags & SF_All)==0 ){ 3713 pSig = sqlite3DbMallocRawNN(pParse->db, sizeof(pSig[0])); 3714 if( pSig ){ 3715 pSig->selId = pExpr->x.pSelect->selId; 3716 pSig->zAff = exprINAffinity(pParse, pExpr); 3717 } 3718 } 3719 3720 /* Check to see if there is a prior materialization of the RHS of 3721 ** this IN operator. If there is, then make use of that prior 3722 ** materialization rather than recomputing it. 3723 */ 3724 if( ExprHasProperty(pExpr, EP_Subrtn) 3725 || findCompatibleInRhsSubrtn(pParse, pExpr, pSig) 3726 ){ 3727 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 3728 if( ExprUseXSelect(pExpr) ){ 3729 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d", 3730 pExpr->x.pSelect->selId)); 3731 } 3732 assert( ExprUseYSub(pExpr) ); 3733 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 3734 pExpr->y.sub.iAddr); 3735 assert( iTab!=pExpr->iTable ); 3736 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable); 3737 sqlite3VdbeJumpHere(v, addrOnce); 3738 if( pSig ){ 3739 sqlite3DbFree(pParse->db, pSig->zAff); 3740 sqlite3DbFree(pParse->db, pSig); 3741 } 3742 return; 3743 } 3744 3745 /* Begin coding the subroutine */ 3746 assert( !ExprUseYWin(pExpr) ); 3747 ExprSetProperty(pExpr, EP_Subrtn); 3748 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 3749 pExpr->y.sub.regReturn = ++pParse->nMem; 3750 pExpr->y.sub.iAddr = 3751 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1; 3752 if( pSig ){ 3753 pSig->bComplete = 0; 3754 pSig->iAddr = pExpr->y.sub.iAddr; 3755 pSig->regReturn = pExpr->y.sub.regReturn; 3756 pSig->iTable = iTab; 3757 pParse->mSubrtnSig = 1 << (pSig->selId&7); 3758 sqlite3VdbeChangeP4(v, -1, (const char*)pSig, P4_SUBRTNSIG); 3759 } 3760 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 3761 } 3762 3763 /* Check to see if this is a vector IN operator */ 3764 pLeft = pExpr->pLeft; 3765 nVal = sqlite3ExprVectorSize(pLeft); 3766 3767 /* Construct the ephemeral table that will contain the content of 3768 ** RHS of the IN operator. 3769 */ 3770 pExpr->iTable = iTab; 3771 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal); 3772 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 3773 if( ExprUseXSelect(pExpr) ){ 3774 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId)); 3775 }else{ 3776 VdbeComment((v, "RHS of IN operator")); 3777 } 3778 #endif 3779 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1); 3780 assert( pKeyInfo!=0 || pParse->nErr ); 3781 if( pKeyInfo==0 ) return; 3782 3783 if( ExprUseXSelect(pExpr) ){ 3784 /* Case 1: expr IN (SELECT ...) 3785 ** 3786 ** Generate code to write the results of the select into the temporary 3787 ** table allocated and opened above. 3788 */ 3789 Select *pSelect = pExpr->x.pSelect; 3790 ExprList *pEList = pSelect->pEList; 3791 3792 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d", 3793 addrOnce?"":"CORRELATED ", pSelect->selId 3794 )); 3795 /* If the LHS and RHS of the IN operator do not match, that 3796 ** error will have been caught long before we reach this point. */ 3797 if( ALWAYS(pEList->nExpr==nVal) ){ 3798 Select *pCopy; 3799 SelectDest dest; 3800 int i; 3801 int rc; 3802 int addrBloom = 0; 3803 sqlite3SelectDestInit(&dest, SRT_Set, iTab); 3804 dest.zAffSdst = exprINAffinity(pParse, pExpr); 3805 pSelect->iLimit = 0; 3806 assert( pEList!=0 ); 3807 assert( pEList->nExpr>0 ); 3808 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 3809 for(i=0; iaColl[i] = pColl = sqlite3BinaryCompareCollSeq( 3813 pParse, p, pEList->a[i].pExpr 3814 ); 3815 if( !sqlite3IsBinary(pColl) ){ 3816 allowBloom = 0; /* tag-`202607231411` */ 3817 } 3818 } 3819 if( addrOnce 3820 && allowBloom 3821 && OptimizationEnabled(pParse->db, SQLITE_BloomFilter) 3822 ){ 3823 int regBloom = ++pParse->nMem; 3824 addrBloom = sqlite3VdbeAddOp2(v, OP_Blob, 10000, regBloom); 3825 VdbeComment((v, "Bloom filter")); 3826 dest.iSDParm2 = regBloom; 3827 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); 3828 pKeyInfo = 0; 3829 } 3830 testcase( pSelect->selFlags & SF_Distinct ); 3831 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0); 3832 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest); 3833 sqlite3SelectDelete(pParse->db, pCopy); 3834 sqlite3DbFree(pParse->db, dest.zAffSdst); 3835 if( addrBloom ){ 3836 /* Remember that location of the Bloom filter in the P3 operand 3837 ** of the OP_Once that began this subroutine. tag-`202407032019` */ 3838 sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2; 3839 if( dest.iSDParm2==0 ){ 3840 /* If the Bloom filter won't actually be used, keep it small */ 3841 sqlite3VdbeGetOp(v, addrBloom)->p1 = 10; 3842 } 3843 } 3844 if( rc ){ 3845 sqlite3KeyInfoUnref(pKeyInfo); 3846 return; 3847 } 3848 } 3849 }else if( ALWAYS(pExpr->x.pList!=0) ){ 3850 /* Case 2: expr IN (exprlist) 3851 ** 3852 ** For each expression, build an index key from the evaluation and 3853 ** store it in the temporary table. If is a column, then use 3854 ** that columns affinity when building index keys. If is not 3855 ** a column, use numeric affinity. 3856 */ 3857 char affinity; /* Affinity of the LHS of the IN */ 3858 int i; 3859 ExprList *pList = pExpr->x.pList; 3860 struct ExprList_item *pItem; 3861 int r1, r2; 3862 affinity = sqlite3ExprAffinity(pLeft); 3863 if( affinity<=SQLITE_AFF_NONE ){ 3864 affinity = SQLITE_AFF_BLOB; 3865 }else if( affinity==SQLITE_AFF_REAL ){ 3866 affinity = SQLITE_AFF_NUMERIC; 3867 } 3868 assert( pKeyInfo!=0 ); 3869 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 3870 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 3871 3872 /* Loop through each expression in . */ 3873 r1 = sqlite3GetTempReg(pParse); 3874 r2 = sqlite3GetTempReg(pParse); 3875 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ 3876 Expr *pE2 = pItem->pExpr; 3877 3878 /* If the expression is not constant then we will need to 3879 ** disable the test that was generated above that makes sure 3880 ** this code only executes once. Because for a non-constant 3881 ** expression we need to rerun this code each time. 3882 */ 3883 if( addrOnce && !sqlite3ExprIsConstant(pParse, pE2) ){ 3884 sqlite3VdbeChangeToNoop(v, addrOnce-1); 3885 sqlite3VdbeChangeToNoop(v, addrOnce); 3886 ExprClearProperty(pExpr, EP_Subrtn); 3887 addrOnce = 0; 3888 } 3889 3890 /* Evaluate the expression and insert it into the temp table */ 3891 sqlite3ExprCode(pParse, pE2, r1); 3892 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1); 3893 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1); 3894 } 3895 sqlite3ReleaseTempReg(pParse, r1); 3896 sqlite3ReleaseTempReg(pParse, r2); 3897 } 3898 if( pSig ) pSig->bComplete = 1; 3899 if( pKeyInfo ){ 3900 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); 3901 } 3902 if( addrOnce ){ 3903 sqlite3VdbeAddOp1(v, OP_NullRow, iTab); 3904 sqlite3VdbeJumpHere(v, addrOnce); 3905 /* Subroutine return */ 3906 assert( ExprUseYSub(pExpr) ); 3907 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn 3908 || pParse->nErr ); 3909 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn, 3910 pExpr->y.sub.iAddr, 1); 3911 VdbeCoverage(v); 3912 sqlite3ClearTempRegCache(pParse); 3913 } 3914 } 3915 #endif /* SQLITE_OMIT_SUBQUERY */ 3916 3917 /* 3918 ** Generate code for scalar subqueries used as a subquery expression 3919 ** or EXISTS operator: 3920 ** 3921 ** (SELECT a FROM b) -- subquery 3922 ** EXISTS (SELECT a FROM b) -- EXISTS subquery 3923 ** 3924 ** The pExpr parameter is the SELECT or EXISTS operator to be coded. 3925 ** 3926 ** Return the register that holds the result. For a multi-column SELECT, 3927 ** the result is stored in a contiguous array of registers and the 3928 ** return value is the register of the left-most result column. 3929 ** Return 0 if an error occurs. 3930 */ 3931 #ifndef SQLITE_OMIT_SUBQUERY 3932 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ 3933 int addrOnce = 0; /* Address of OP_Once at top of subroutine */ 3934 int rReg = 0; /* Register storing resulting */ 3935 Select *pSel; /* SELECT statement to encode */ 3936 SelectDest dest; /* How to deal with SELECT result */ 3937 int nReg; /* Registers to allocate */ 3938 Expr *pLimit; /* New limit expression */ 3939 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 3940 int addrExplain; /* Address of OP_Explain instruction */ 3941 #endif 3942 3943 Vdbe *v = pParse->pVdbe; 3944 assert( v!=0 ); 3945 if( pParse->nErr ) return 0; 3946 testcase( pExpr->op==TK_EXISTS ); 3947 testcase( pExpr->op==TK_SELECT ); 3948 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); 3949 assert( ExprUseXSelect(pExpr) ); 3950 pSel = pExpr->x.pSelect; 3951 3952 /* If this routine has already been coded, then invoke it as a 3953 ** subroutine. */ 3954 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 3955 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId)); 3956 assert( ExprUseYSub(pExpr) ); 3957 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 3958 pExpr->y.sub.iAddr); 3959 return pExpr->iTable; 3960 } 3961 3962 /* Begin coding the subroutine */ 3963 assert( !ExprUseYWin(pExpr) ); 3964 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) ); 3965 ExprSetProperty(pExpr, EP_Subrtn); 3966 pExpr->y.sub.regReturn = ++pParse->nMem; 3967 pExpr->y.sub.iAddr = 3968 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1; 3969 3970 /* The evaluation of the EXISTS/SELECT must be repeated every time it 3971 ** is encountered if any of the following is true: 3972 ** 3973 ** * The right-hand side is a correlated subquery 3974 ** * The right-hand side is an expression list containing variables 3975 ** * We are inside a trigger 3976 ** 3977 ** If all of the above are false, then we can run this code just once 3978 ** save the results, and reuse the same result on subsequent invocations. 3979 */ 3980 if( !ExprHasProperty(pExpr, EP_VarSelect) ){ 3981 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 3982 } 3983 3984 /* For a SELECT, generate code to put the values for all columns of 3985 ** the first row into an array of registers and return the index of 3986 ** the first register. 3987 ** 3988 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) 3989 ** into a register and return that register number. 3990 ** 3991 ** In both cases, the query is augmented with "LIMIT 1". Any 3992 ** preexisting limit is discarded in place of the new LIMIT 1. 3993 */ 3994 ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d", 3995 addrOnce?"":"CORRELATED ", pSel->selId)); 3996 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1); 3997 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; 3998 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); 3999 pParse->nMem += nReg; 4000 if( pExpr->op==TK_SELECT ){ 4001 dest.eDest = SRT_Mem; 4002 if( (pSel->selFlags&SF_Distinct) && pSel->pLimit && pSel->pLimit->pRight ){ 4003 /* If there is both a DISTINCT and an OFFSET clause, then allocate 4004 ** a separate dest.iSdst array for sqlite3Select() and other 4005 ** routines to populate. In this case results will be copied over 4006 ** into the dest.iSDParm array only after OFFSET processing. This 4007 ** ensures that in the case where OFFSET excludes all rows, the 4008 ** dest.iSDParm array is not left populated with the contents of the 4009 ** last row visited - it should be all NULLs if all rows were 4010 ** excluded by OFFSET. */ 4011 dest.iSdst = pParse->nMem+1; 4012 pParse->nMem += nReg; 4013 }else{ 4014 dest.iSdst = dest.iSDParm; 4015 } 4016 dest.nSdst = nReg; 4017 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, pParse->nMem); 4018 VdbeComment((v, "Init subquery result")); 4019 }else{ 4020 dest.eDest = SRT_Exists; 4021 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); 4022 VdbeComment((v, "Init EXISTS result")); 4023 } 4024 if( pSel->pLimit ){ 4025 /* The subquery already has a limit. If the pre-existing limit X is 4026 ** not already integer value 1 or 0, then make the new limit X<>0 so that 4027 ** the new limit is either 1 or 0 */ 4028 Expr *pLeft = pSel->pLimit->pLeft; 4029 if( ExprHasProperty(pLeft, EP_IntValue)==0 4030 || (pLeft->u.iValue!=1 && pLeft->u.iValue!=0) 4031 ){ 4032 sqlite3 *db = pParse->db; 4033 pLimit = sqlite3ExprInt32(db, 0); 4034 if( pLimit ){ 4035 pLimit->affExpr = SQLITE_AFF_NUMERIC; 4036 pLimit = sqlite3PExpr(pParse, TK_NE, 4037 sqlite3ExprDup(db, pLeft, 0), pLimit); 4038 } 4039 sqlite3ExprDeferredDelete(pParse, pLeft); 4040 pSel->pLimit->pLeft = pLimit; 4041 } 4042 }else{ 4043 /* If there is no limit add a limit of 1. (tag-`202611101908`) */ 4044 pLimit = sqlite3ExprInt32(pParse->db, 1); 4045 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0); 4046 } 4047 pSel->iLimit = 0; 4048 if( sqlite3Select(pParse, pSel, &dest) ){ 4049 pExpr->op2 = pExpr->op; 4050 pExpr->op = TK_ERROR; 4051 return 0; 4052 } 4053 pExpr->iTable = rReg = dest.iSDParm; 4054 ExprSetVVAProperty(pExpr, EP_NoReduce); 4055 if( addrOnce ){ 4056 sqlite3VdbeJumpHere(v, addrOnce); 4057 } 4058 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1); 4059 4060 if( dest.eDest==SRT_Mem 4061 && sqlite3ExprCanReturnSubtype(pParse, pSel->pEList->a[0].pExpr) 4062 ){ 4063 sqlite3VdbeAddOp1(v, OP_ClrSubtype, rReg); 4064 } 4065 4066 /* Subroutine return */ 4067 assert( ExprUseYSub(pExpr) ); 4068 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn 4069 || pParse->nErr ); 4070 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn, 4071 pExpr->y.sub.iAddr, 1); 4072 VdbeCoverage(v); 4073 sqlite3ClearTempRegCache(pParse); 4074 return rReg; 4075 } 4076 #endif /* SQLITE_OMIT_SUBQUERY */ 4077 4078 #ifndef SQLITE_OMIT_SUBQUERY 4079 /* 4080 ** Expr pIn is an IN(...) expression. This function checks that the 4081 ** sub-select on the RHS of the IN() operator has the same number of 4082 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not 4083 ** a sub-query, that the LHS is a vector of size 1. 4084 */ 4085 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ 4086 int nVector = sqlite3ExprVectorSize(pIn->pLeft); 4087 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){ 4088 if( nVector!=pIn->x.pSelect->pEList->nExpr ){ 4089 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); 4090 return 1; 4091 } 4092 }else if( nVector!=1 ){ 4093 sqlite3VectorErrorMsg(pParse, pIn->pLeft); 4094 return 1; 4095 } 4096 return 0; 4097 } 4098 #endif 4099 4100 #ifndef SQLITE_OMIT_SUBQUERY 4101 /* 4102 ** Generate code for an IN expression. 4103 ** 4104 ** x IN (SELECT ...) 4105 ** x IN (value, value, ...) 4106 ** 4107 ** The left-hand side (LHS) is a scalar or vector expression. The 4108 ** right-hand side (RHS) is an array of zero or more scalar values, or a 4109 ** subquery. If the RHS is a subquery, the number of result columns must 4110 ** match the number of columns in the vector on the LHS. If the RHS is 4111 ** a list of values, the LHS must be a scalar. 4112 ** 4113 ** The IN operator is true if the LHS value is contained within the RHS. 4114 ** The result is false if the LHS is definitely not in the RHS. The 4115 ** result is NULL if the presence of the LHS in the RHS cannot be 4116 ** determined due to NULLs. 4117 ** 4118 ** This routine generates code that jumps to destIfFalse if the LHS is not 4119 ** contained within the RHS. If due to NULLs we cannot determine if the LHS 4120 ** is contained in the RHS then jump to destIfNull. If the LHS is contained 4121 ** within the RHS then fall through. 4122 ** 4123 ** See the separate in-operator.md documentation file in the canonical 4124 ** SQLite source tree for additional information. 4125 */ 4126 static void sqlite3ExprCodeIN( 4127 Parse *pParse, /* Parsing and code generating context */ 4128 Expr *pExpr, /* The IN expression */ 4129 int destIfFalse, /* Jump here if LHS is not contained in the RHS */ 4130 int destIfNull /* Jump here if the results are unknown due to NULLs */ 4131 ){ 4132 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ 4133 int eType; /* Type of the RHS */ 4134 int rLhs; /* Register(s) holding the LHS values */ 4135 Vdbe *v; /* Statement under construction */ 4136 int *aiMap = 0; /* Map from vector field to index column */ 4137 char *zAff = 0; /* Affinity string for comparisons */ 4138 int nVector; /* Size of vectors for this IN operator */ 4139 int iDummy; /* Dummy parameter to exprCodeVector() */ 4140 Expr *pLeft; /* The LHS of the IN operator */ 4141 int i; /* loop counter */ 4142 int destStep2; /* Where to jump when NULLs seen in step 2 */ 4143 int destStep6 = 0; /* Start of code for Step 6 */ 4144 int addrTruthOp; /* Address of opcode that determines the IN is true */ 4145 int destNotNull; /* Jump here if a comparison is not true in step 6 */ 4146 int addrTop; /* Top of the step-6 loop */ 4147 int iTab = 0; /* Index to use */ 4148 u8 okConstFactor = pParse->okConstFactor; 4149 4150 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 4151 pLeft = pExpr->pLeft; 4152 if( sqlite3ExprCheckIN(pParse, pExpr) ) return; 4153 zAff = exprINAffinity(pParse, pExpr); 4154 nVector = sqlite3ExprVectorSize(pExpr->pLeft); 4155 aiMap = (int*)sqlite3DbMallocZero(pParse->db, nVector*sizeof(int)); 4156 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; 4157 4158 /* Attempt to compute the RHS. After this step, if anything other than 4159 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab 4160 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, 4161 ** the RHS has not yet been coded. */ 4162 v = pParse->pVdbe; 4163 assert( v!=0 ); /* OOM detected prior to this routine */ 4164 VdbeNoopComment((v, "begin IN expr")); 4165 eType = sqlite3FindInIndex(pParse, pExpr, 4166 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, 4167 destIfFalse==destIfNull ? 0 : &rRhsHasNull, 4168 aiMap, &iTab); 4169 4170 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH 4171 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 4172 ); 4173 #ifdef SQLITE_DEBUG 4174 /* Confirm that aiMap[] contains nVector integer values between 0 and 4175 ** nVector-1. */ 4176 for(i=0; i from " IN (...)". If the LHS is a 4184 ** vector, then it is stored in an array of nVector registers starting 4185 ** at r1. 4186 ** 4187 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector 4188 ** so that the fields are in the same order as an existing index. The 4189 ** aiMap[] array contains a mapping from the original LHS field order to 4190 ** the field order that matches the RHS index. 4191 ** 4192 ** Avoid factoring the LHS of the IN(...) expression out of the loop, 4193 ** even if it is constant, as OP_Affinity may be used on the register 4194 ** by code generated below. */ 4195 assert( pParse->okConstFactor==okConstFactor ); 4196 pParse->okConstFactor = 0; 4197 rLhs = exprCodeVector(pParse, pLeft, &iDummy); 4198 pParse->okConstFactor = okConstFactor; 4199 4200 /* If sqlite3FindInIndex() did not find or create an index that is 4201 ** suitable for evaluating the IN operator, then evaluate using a 4202 ** sequence of comparisons. 4203 ** 4204 ** This is step (1) in the in-operator.md optimized algorithm. 4205 */ 4206 if( eType==IN_INDEX_NOOP ){ 4207 ExprList *pList; 4208 CollSeq *pColl; 4209 int labelOk = sqlite3VdbeMakeLabel(pParse); 4210 int r2, regToFree; 4211 int regCkNull = 0; 4212 int ii; 4213 assert( nVector==1 ); 4214 assert( ExprUseXList(pExpr) ); 4215 pList = pExpr->x.pList; 4216 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 4217 if( destIfNull!=destIfFalse ){ 4218 regCkNull = sqlite3GetTempReg(pParse); 4219 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); 4220 } 4221 for(ii=0; iinExpr; ii++){ 4222 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); 4223 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ 4224 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); 4225 } 4226 sqlite3ReleaseTempReg(pParse, regToFree); 4227 if( iinExpr-1 || destIfNull!=destIfFalse ){ 4228 int op = rLhs!=r2 ? OP_Eq : OP_NotNull; 4229 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2, 4230 (void*)pColl, P4_COLLSEQ); 4231 VdbeCoverageIf(v, iinExpr-1 && op==OP_Eq); 4232 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq); 4233 VdbeCoverageIf(v, iinExpr-1 && op==OP_NotNull); 4234 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull); 4235 sqlite3VdbeChangeP5(v, zAff[0]); 4236 }else{ 4237 int op = rLhs!=r2 ? OP_Ne : OP_IsNull; 4238 assert( destIfNull==destIfFalse ); 4239 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2, 4240 (void*)pColl, P4_COLLSEQ); 4241 VdbeCoverageIf(v, op==OP_Ne); 4242 VdbeCoverageIf(v, op==OP_IsNull); 4243 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); 4244 } 4245 } 4246 if( regCkNull ){ 4247 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); 4248 sqlite3VdbeGoto(v, destIfFalse); 4249 } 4250 sqlite3VdbeResolveLabel(v, labelOk); 4251 sqlite3ReleaseTempReg(pParse, regCkNull); 4252 goto sqlite3ExprCodeIN_finished; 4253 } 4254 4255 if( eType!=IN_INDEX_ROWID ){ 4256 /* If this IN operator will use an index, then the order of columns in the 4257 ** vector might be different from the order in the index. In that case, 4258 ** we need to reorder the LHS values to be in index order. Run Affinity 4259 ** before reordering the columns, so that the affinity is correct. 4260 */ 4261 if( nVector==1 ){ 4262 char aff = zAff[0]; 4263 if( aff>=SQLITE_AFF_TEXT && aff!=sqlite3ExprAffinity(pLeft) ){ 4264 /* The OP_Affinity below may change the value. In this case, create a 4265 ** copy of rLhs to run OP_Affinity on, in case the original register 4266 ** is used again (e.g. if it is TK_AGG_COLUMN). */ 4267 int rTmp = sqlite3GetTempReg(pParse); 4268 sqlite3VdbeAddOp3(v, OP_Copy, rLhs, rTmp, 0); 4269 rLhs = rTmp; 4270 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, 1, 0, zAff, 1); 4271 } 4272 }else{ 4273 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); 4274 } 4275 4276 for(i=0; ipLeft, i); 4300 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error; 4301 if( sqlite3ExprCanBeNull(p) ){ 4302 testcase( aiMap[i]!=i ); 4303 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+aiMap[i], destStep2); 4304 VdbeCoverage(v); 4305 } 4306 } 4307 4308 /* Step 3. The LHS is now known to be non-NULL. Do the binary search 4309 ** of the RHS using the LHS as a probe. If found, the result is 4310 ** true. 4311 */ 4312 if( eType==IN_INDEX_ROWID ){ 4313 /* In this case, the RHS is the ROWID of table b-tree and so we also 4314 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 4315 ** into a single opcode. */ 4316 assert( nVector==1 ); 4317 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs); 4318 VdbeCoverage(v); 4319 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ 4320 }else{ 4321 if( destIfFalse==destIfNull ){ 4322 /* Combine Step 3 and Step 5 into a single opcode */ 4323 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 4324 const VdbeOp *pOp = sqlite3VdbeGetOp(v, pExpr->y.sub.iAddr); 4325 assert( pOp->opcode==OP_Once || pParse->nErr ); 4326 if( pOp->p3>0 ){ /* tag-`202407032019` */ 4327 assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) 4328 || pParse->nErr ); 4329 sqlite3VdbeAddOp4Int(v, OP_Filter, pOp->p3, destIfFalse, 4330 rLhs, nVector); VdbeCoverage(v); 4331 } 4332 } 4333 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse, 4334 rLhs, nVector); VdbeCoverage(v); 4335 goto sqlite3ExprCodeIN_finished; 4336 } 4337 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ 4338 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0, 4339 rLhs, nVector); VdbeCoverage(v); 4340 } 4341 4342 /* Step 4. If the RHS is known to be non-NULL and we did not find 4343 ** an match on the search above, then the result must be FALSE. 4344 */ 4345 if( rRhsHasNull && nVector==1 ){ 4346 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); 4347 VdbeCoverage(v); 4348 } 4349 4350 /* Step 5. If we do not care about the difference between NULL and 4351 ** FALSE, then just return false. 4352 */ 4353 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); 4354 4355 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. 4356 ** If any comparison is NULL, then the result is NULL. If all 4357 ** comparisons are FALSE then the final result is FALSE. 4358 ** 4359 ** For a scalar LHS, it is sufficient to check just the first row 4360 ** of the RHS. 4361 */ 4362 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); 4363 if( eType==IN_INDEX_INDEX_DESC && nVector==1 ){ 4364 addrTop = sqlite3VdbeAddOp2(v, OP_Last, iTab, destIfFalse); 4365 }else{ 4366 testcase( eType==IN_INDEX_INDEX_DESC ); 4367 testcase( eType==IN_INDEX_EPH ); 4368 testcase( eType==IN_INDEX_ROWID ); 4369 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); 4370 } 4371 VdbeCoverage(v); 4372 if( nVector>1 ){ 4373 destNotNull = sqlite3VdbeMakeLabel(pParse); 4374 }else{ 4375 /* For nVector==1, combine steps 6 and 7 by immediately returning 4376 ** FALSE if the first comparison is not NULL */ 4377 destNotNull = destIfFalse; 4378 } 4379 for(i=0; ix.pSelect->pEList->a[i].pExpr; 4386 pColl = sqlite3BinaryCompareCollSeq(pParse, p, pRhs); 4387 }else{ 4388 /* If the RHS of the IN(...) expression are scalar expressions, do 4389 ** not consider their collation sequences. The documentation says 4390 ** "The collating sequence used for expressions of the form "x IN (y, z, 4391 ** ...)" is the collating sequence of x.". */ 4392 pColl = sqlite3ExprCollSeq(pParse, p); 4393 } 4394 testcase( aiMap[i]!=i ); 4395 sqlite3VdbeAddOp3(v, OP_Column, iTab, aiMap[i], r3); 4396 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+aiMap[i], destNotNull, r3, 4397 (void*)pColl, P4_COLLSEQ); 4398 VdbeCoverage(v); 4399 sqlite3ReleaseTempReg(pParse, r3); 4400 } 4401 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); 4402 if( nVector>1 ){ 4403 sqlite3VdbeResolveLabel(v, destNotNull); 4404 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1); 4405 VdbeCoverage(v); 4406 4407 /* Step 7: If we reach this point, we know that the result must 4408 ** be false. */ 4409 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); 4410 } 4411 4412 /* Jumps here in order to return true. */ 4413 sqlite3VdbeJumpHere(v, addrTruthOp); 4414 4415 sqlite3ExprCodeIN_finished: 4416 VdbeComment((v, "end IN expr")); 4417 sqlite3ExprCodeIN_oom_error: 4418 sqlite3DbFree(pParse->db, aiMap); 4419 sqlite3DbFree(pParse->db, zAff); 4420 } 4421 #endif /* SQLITE_OMIT_SUBQUERY */ 4422 4423 #ifndef SQLITE_OMIT_FLOATING_POINT 4424 /* 4425 ** Generate an instruction that will put the floating point 4426 ** value described by z[0..n-1] into register iMem. 4427 ** 4428 ** The z[] string will probably not be zero-terminated. But the 4429 ** z[n] character is guaranteed to be something that does not look 4430 ** like the continuation of the number. 4431 */ 4432 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ 4433 if( ALWAYS(z!=0) ){ 4434 double value; 4435 sqlite3AtoF(z, &value); 4436 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ 4437 if( negateFlag ) value = -value; 4438 sqlite3VdbeAddDouble(v, iMem, value); 4439 } 4440 } 4441 #endif 4442 4443 4444 /* 4445 ** Generate an instruction that will put the integer describe by 4446 ** text z[0..n-1] into register iMem. 4447 ** 4448 ** Expr.u.zToken is always UTF8 and zero-terminated. 4449 */ 4450 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ 4451 Vdbe *v = pParse->pVdbe; 4452 if( pExpr->flags & EP_IntValue ){ 4453 int i = pExpr->u.iValue; 4454 assert( i>=0 ); 4455 if( negFlag ) i = -i; 4456 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); 4457 }else{ 4458 int c; 4459 i64 value; 4460 const char *z = pExpr->u.zToken; 4461 assert( z!=0 ); 4462 c = sqlite3DecOrHexToI64(z, &value); 4463 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){ 4464 #ifdef SQLITE_OMIT_FLOATING_POINT 4465 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr); 4466 #else 4467 #ifndef SQLITE_OMIT_HEX_INTEGER 4468 if( sqlite3_strnicmp(z,"0x",2)==0 ){ 4469 sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T", 4470 negFlag?"-":"",pExpr); 4471 }else 4472 #endif 4473 { 4474 codeReal(v, z, negFlag, iMem); 4475 } 4476 #endif 4477 }else{ 4478 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; } 4479 sqlite3VdbeAddInt64(v, iMem, value); 4480 } 4481 } 4482 } 4483 4484 4485 /* Generate code that will load into register regOut a value that is 4486 ** appropriate for the iIdxCol-th column of index pIdx. 4487 */ 4488 void sqlite3ExprCodeLoadIndexColumn( 4489 Parse *pParse, /* The parsing context */ 4490 Index *pIdx, /* The index whose column is to be loaded */ 4491 int iTabCur, /* Cursor pointing to a table row */ 4492 int iIdxCol, /* The column of the index to be loaded */ 4493 int regOut /* Store the index column value in this register */ 4494 ){ 4495 i16 iTabCol = pIdx->aiColumn[iIdxCol]; 4496 if( iTabCol==XN_EXPR ){ 4497 assert( pIdx->aColExpr ); 4498 assert( pIdx->aColExpr->nExpr>iIdxCol ); 4499 pParse->iSelfTab = iTabCur + 1; 4500 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); 4501 pParse->iSelfTab = 0; 4502 }else{ 4503 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, 4504 iTabCol, regOut); 4505 } 4506 } 4507 4508 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 4509 /* 4510 ** Generate code that will compute the value of generated column pCol 4511 ** and store the result in register regOut 4512 */ 4513 void sqlite3ExprCodeGeneratedColumn( 4514 Parse *pParse, /* Parsing context */ 4515 Table *pTab, /* Table containing the generated column */ 4516 Column *pCol, /* The generated column */ 4517 int regOut /* Put the result in this register */ 4518 ){ 4519 int iAddr; 4520 Vdbe *v = pParse->pVdbe; 4521 int nErr = pParse->nErr; 4522 assert( v!=0 ); 4523 assert( pParse->iSelfTab!=0 ); 4524 if( pParse->iSelfTab>0 ){ 4525 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut); 4526 }else{ 4527 iAddr = 0; 4528 } 4529 sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut); 4530 if( (pCol->colFlags & COLFLAG_VIRTUAL)!=0 4531 && (pTab->tabFlags & TF_Strict)!=0 4532 ){ 4533 int p3 = 2+(int)(pCol - pTab->aCol); 4534 sqlite3VdbeAddOp4(v, OP_TypeCheck, regOut, 1, p3, (char*)pTab, P4_TABLE); 4535 }else if( pCol->affinity>=SQLITE_AFF_TEXT ){ 4536 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1); 4537 } 4538 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr); 4539 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1; 4540 } 4541 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 4542 4543 /* 4544 ** Generate code to extract the value of the iCol-th column of a table. 4545 */ 4546 void sqlite3ExprCodeGetColumnOfTable( 4547 Vdbe *v, /* Parsing context */ 4548 Table *pTab, /* The table containing the value */ 4549 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ 4550 int iCol, /* Index of the column to extract */ 4551 int regOut /* Extract the value into this register */ 4552 ){ 4553 Column *pCol; 4554 assert( v!=0 ); 4555 assert( pTab!=0 ); 4556 assert( iCol!=XN_EXPR ); 4557 if( iCol<0 || iCol==pTab->iPKey ){ 4558 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); 4559 VdbeComment((v, "%s.rowid", pTab->zName)); 4560 }else{ 4561 int x; 4562 if( IsVirtual(pTab) ){ 4563 x = iCol; 4564 sqlite3VdbeAddOp3(v, OP_VColumn, iTabCur, x, regOut); 4565 return; 4566 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 4567 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){ 4568 Parse *pParse = sqlite3VdbeParser(v); 4569 if( pCol->colFlags & COLFLAG_BUSY ){ 4570 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", 4571 pCol->zCnName); 4572 }else{ 4573 int savedSelfTab = pParse->iSelfTab; 4574 pCol->colFlags |= COLFLAG_BUSY; 4575 pParse->iSelfTab = iTabCur+1; 4576 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut); 4577 pParse->iSelfTab = savedSelfTab; 4578 pCol->colFlags &= ~COLFLAG_BUSY; 4579 } 4580 return; 4581 #endif 4582 }else if( !HasRowid(pTab) ){ 4583 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) ); 4584 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol); 4585 }else{ 4586 x = sqlite3TableColumnToStorage(pTab,iCol); 4587 testcase( x!=iCol ); 4588 } 4589 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, x, regOut); 4590 sqlite3ColumnDefault(v, pTab, iCol, regOut); 4591 } 4592 } 4593 4594 /* 4595 ** Generate code that will extract the iColumn-th column from 4596 ** table pTab and store the column value in register iReg. 4597 ** 4598 ** There must be an open cursor to pTab in iTable when this routine 4599 ** is called. If iColumn<0 then code is generated that extracts the rowid. 4600 */ 4601 int sqlite3ExprCodeGetColumn( 4602 Parse *pParse, /* Parsing and code generating context */ 4603 Table *pTab, /* Description of the table we are reading from */ 4604 int iColumn, /* Index of the table column */ 4605 int iTable, /* The cursor pointing to the table */ 4606 int iReg, /* Store results here */ 4607 u8 p5 /* P5 value for OP_Column + FLAGS */ 4608 ){ 4609 assert( pParse->pVdbe!=0 ); 4610 assert( (p5 & (OPFLAG_NOCHNG|OPFLAG_TYPEOFARG|OPFLAG_LENGTHARG))==p5 ); 4611 assert( IsVirtual(pTab) || (p5 & OPFLAG_NOCHNG)==0 ); 4612 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg); 4613 if( p5 ){ 4614 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe); 4615 if( pOp->opcode==OP_Column ) pOp->p5 = p5; 4616 if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG); 4617 } 4618 return iReg; 4619 } 4620 4621 /* 4622 ** Generate code to move content from registers iFrom...iFrom+nReg-1 4623 ** over to iTo..iTo+nReg-1. 4624 */ 4625 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ 4626 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); 4627 } 4628 4629 /* 4630 ** Convert a scalar expression node to a TK_REGISTER referencing 4631 ** register iReg. The caller must ensure that iReg already contains 4632 ** the correct value for the expression. 4633 */ 4634 void sqlite3ExprToRegister(Expr *pExpr, int iReg){ 4635 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr); 4636 if( NEVER(p==0) ) return; 4637 if( p->op==TK_REGISTER ){ 4638 assert( p->iTable==iReg ); 4639 }else{ 4640 p->op2 = p->op; 4641 p->op = TK_REGISTER; 4642 p->iTable = iReg; 4643 ExprClearProperty(p, EP_Skip); 4644 } 4645 } 4646 4647 /* 4648 ** Evaluate an expression (either a vector or a scalar expression) and store 4649 ** the result in contiguous temporary registers. Return the index of 4650 ** the first register used to store the result. 4651 ** 4652 ** If the returned result register is a temporary scalar, then also write 4653 ** that register number into *piFreeable. If the returned result register 4654 ** is not a temporary or if the expression is a vector set *piFreeable 4655 ** to 0. 4656 */ 4657 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ 4658 int iResult; 4659 int nResult = sqlite3ExprVectorSize(p); 4660 if( nResult==1 ){ 4661 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); 4662 }else{ 4663 *piFreeable = 0; 4664 if( p->op==TK_SELECT ){ 4665 #if SQLITE_OMIT_SUBQUERY 4666 iResult = 0; 4667 #else 4668 iResult = sqlite3CodeSubselect(pParse, p); 4669 #endif 4670 }else{ 4671 int i; 4672 iResult = pParse->nMem+1; 4673 pParse->nMem += nResult; 4674 assert( ExprUseXList(p) ); 4675 for(i=0; ix.pList->a[i].pExpr, i+iResult); 4677 } 4678 } 4679 } 4680 return iResult; 4681 } 4682 4683 /* 4684 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5) 4685 ** so that a subsequent copy will not be merged into this one. 4686 */ 4687 static void setDoNotMergeFlagOnCopy(Vdbe *v){ 4688 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){ 4689 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergeable */ 4690 } 4691 } 4692 4693 /* 4694 ** Generate code to implement special SQL functions that are implemented 4695 ** in-line rather than by using the usual callbacks. 4696 */ 4697 static int exprCodeInlineFunction( 4698 Parse *pParse, /* Parsing context */ 4699 ExprList *pFarg, /* List of function arguments */ 4700 int iFuncId, /* Function ID. One of the INTFUNC_... values */ 4701 int target /* Store function result in this register */ 4702 ){ 4703 int nFarg; 4704 Vdbe *v = pParse->pVdbe; 4705 assert( v!=0 ); 4706 assert( pFarg!=0 ); 4707 nFarg = pFarg->nExpr; 4708 assert( nFarg>0 ); /* All in-line functions have at least one argument */ 4709 switch( iFuncId ){ 4710 case INLINEFUNC_coalesce: { 4711 /* Attempt a direct implementation of the built-in COALESCE() and 4712 ** IFNULL() functions. This avoids unnecessary evaluation of 4713 ** arguments past the first non-NULL argument. 4714 */ 4715 int endCoalesce = sqlite3VdbeMakeLabel(pParse); 4716 int i; 4717 assert( nFarg>=2 ); 4718 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); 4719 for(i=1; ia[i].pExpr, target); 4723 } 4724 setDoNotMergeFlagOnCopy(v); 4725 sqlite3VdbeResolveLabel(v, endCoalesce); 4726 break; 4727 } 4728 case INLINEFUNC_iif: { 4729 Expr caseExpr; 4730 memset(&caseExpr, 0, sizeof(caseExpr)); 4731 caseExpr.op = TK_CASE; 4732 caseExpr.x.pList = pFarg; 4733 return sqlite3ExprCodeTarget(pParse, &caseExpr, target); 4734 } 4735 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 4736 case INLINEFUNC_sqlite_offset: { 4737 Expr *pArg = pFarg->a[0].pExpr; 4738 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){ 4739 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target); 4740 }else{ 4741 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 4742 } 4743 break; 4744 } 4745 #endif 4746 default: { 4747 /* The UNLIKELY() function is a no-op. The result is the value 4748 ** of the first argument. 4749 */ 4750 assert( nFarg==1 || nFarg==2 ); 4751 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); 4752 break; 4753 } 4754 4755 /*********************************************************************** 4756 ** Test-only SQL functions that are only usable if enabled 4757 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 4758 */ 4759 #if !defined(SQLITE_UNTESTABLE) 4760 case INLINEFUNC_expr_compare: { 4761 /* Compare two expressions using sqlite3ExprCompare() */ 4762 assert( nFarg==2 ); 4763 sqlite3VdbeAddOp2(v, OP_Integer, 4764 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), 4765 target); 4766 break; 4767 } 4768 4769 case INLINEFUNC_expr_implies_expr: { 4770 /* Compare two expressions using sqlite3ExprImpliesExpr() */ 4771 assert( nFarg==2 ); 4772 sqlite3VdbeAddOp2(v, OP_Integer, 4773 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), 4774 target); 4775 break; 4776 } 4777 4778 case INLINEFUNC_implies_nonnull_row: { 4779 /* Result of sqlite3ExprImpliesNonNullRow() */ 4780 Expr *pA1; 4781 assert( nFarg==2 ); 4782 pA1 = pFarg->a[1].pExpr; 4783 if( pA1->op==TK_COLUMN ){ 4784 sqlite3VdbeAddOp2(v, OP_Integer, 4785 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1), 4786 target); 4787 }else{ 4788 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 4789 } 4790 break; 4791 } 4792 4793 case INLINEFUNC_affinity: { 4794 /* The AFFINITY() function evaluates to a string that describes 4795 ** the type affinity of the argument. This is used for testing of 4796 ** the SQLite type logic. 4797 */ 4798 const char *azAff[] = { "blob", "text", "numeric", "integer", 4799 "real", "flexnum" }; 4800 char aff; 4801 assert( nFarg==1 ); 4802 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr); 4803 assert( aff<=SQLITE_AFF_NONE 4804 || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) ); 4805 sqlite3VdbeLoadString(v, target, 4806 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]); 4807 break; 4808 } 4809 #endif /* !defined(SQLITE_UNTESTABLE) */ 4810 } 4811 return target; 4812 } 4813 4814 /* 4815 ** Expression Node callback for sqlite3ExprCanReturnSubtype(). If 4816 ** pExpr is able to return a subtype, set pWalker->eCode and abort 4817 ** the search. If pExpr can never return a subtype, prune search. 4818 ** 4819 ** The only expressions that can return a subtype are: 4820 ** 4821 ** 1. A function, including an aggregate function 4822 ** 2. The no-op "+" operator 4823 ** 3. A CASE...END expression 4824 ** 4. A CAST() expression 4825 ** 5. A "expr COLLATE colseq" expression. 4826 ** 4827 ** For any other kind of expression, prune the search. 4828 ** 4829 ** For case 1, the expression can yield a subtype if the function has 4830 ** the SQLITE_RESULT_SUBTYPE property. Functions can also return 4831 ** a subtype (via sqlite3_result_value()) if any of the arguments can 4832 ** return a subtype. 4833 ** 4834 ** In all cases 1 through 5, the expression might also return a subtype 4835 ** if any operand can return a subtype. 4836 */ 4837 static int exprNodeCanReturnSubtype(Walker *pWalker, Expr *pExpr){ 4838 int n; 4839 FuncDef *pDef; 4840 sqlite3 *db; 4841 if( pExpr->op==TK_CASE || pExpr->op==TK_UPLUS 4842 || pExpr->op==TK_COLLATE || pExpr->op==TK_CAST 4843 ){ 4844 return WRC_Continue; 4845 } 4846 if( pExpr->op!=TK_FUNCTION && pExpr->op!=TK_AGG_FUNCTION ){ 4847 return WRC_Prune; 4848 } 4849 assert( ExprUseXList(pExpr) ); 4850 db = pWalker->pParse->db; 4851 n = pExpr->x.pList ? pExpr->x.pList->nExpr : 0; 4852 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0); 4853 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 4854 if( pDef==0 ) return WRC_Continue; 4855 #else 4856 assert( pDef!=0 ); 4857 #endif 4858 if( (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){ 4859 pWalker->eCode = 1; 4860 return WRC_Abort; 4861 } 4862 return WRC_Continue; 4863 } 4864 4865 /* 4866 ** Return TRUE if expression pExpr is able to return a subtype. 4867 ** 4868 ** A TRUE return does not guarantee that a subtype will be returned. 4869 ** It only indicates that a subtype return is possible. False positives 4870 ** are acceptable as they only disable an optimization. False negatives, 4871 ** on the other hand, can lead to incorrect answers. 4872 */ 4873 int sqlite3ExprCanReturnSubtype(Parse *pParse, Expr *pExpr){ 4874 Walker w; 4875 memset(&w, 0, sizeof(w)); 4876 w.pParse = pParse; 4877 w.xExprCallback = exprNodeCanReturnSubtype; 4878 sqlite3WalkExpr(&w, pExpr); 4879 return w.eCode; 4880 } 4881 4882 /* 4883 ** Return 0 iff the expression in IndexedExpr object p is identical to 4884 ** expression pExpr, and the affinity is such that an entry read from 4885 ** the index may be substituted for pExpr in any context. Otherwise 4886 ** return non-zero. 4887 */ 4888 static int indexedExprCompare( 4889 IndexedExpr *p, /* Indexed expression */ 4890 Expr *pExpr, /* Expression to compare to p */ 4891 int iDataCur /* iTab argument for ExprCompare() */ 4892 ){ 4893 u8 exprAff; 4894 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) return 1; 4895 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC ); 4896 exprAff = sqlite3ExprAffinity(pExpr); 4897 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB) 4898 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT) 4899 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC) 4900 ){ 4901 /* Affinity mismatch on a generated column */ 4902 return 1; 4903 } 4904 return 0; 4905 } 4906 4907 /* 4908 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr. 4909 ** If it is, then resolve the expression by reading from the index and 4910 ** return the register into which the value has been read. If pExpr is 4911 ** not an indexed expression, then return negative. 4912 */ 4913 static SQLITE_NOINLINE int sqlite3IndexedExprLookup( 4914 Parse *pParse, /* The parsing context */ 4915 Expr *pExpr, /* The expression to potentially bypass */ 4916 int target /* Where to store the result of the expression */ 4917 ){ 4918 IndexedExpr *p; 4919 Vdbe *v; 4920 4921 for(p=pParse->pIdxEpr; p; p=p->pIENext){ 4922 int iDataCur = p->iDataCur; 4923 if( iDataCur<0 ) continue; 4924 if( pParse->iSelfTab ){ 4925 if( p->iDataCur!=pParse->iSelfTab-1 ) continue; 4926 iDataCur = -1; 4927 } 4928 if( indexedExprCompare(p, pExpr, iDataCur)!=0 ) continue; 4929 4930 /* Functions that might set a subtype should not be replaced by the 4931 ** value taken from an expression index if they are themselves an 4932 ** argument to another scalar function or aggregate. 4933 ** https://sqlite.org/forum/forumpost/`68d284c86b082c3e` */ 4934 if( ExprHasProperty(pExpr, EP_SubtArg) 4935 && sqlite3ExprCanReturnSubtype(pParse, pExpr) 4936 ){ 4937 continue; 4938 } 4939 4940 /* Do not read the value from an index if the expression is a constant. 4941 ** This prevents an attempt to use an index value outside of the loop that 4942 ** uses the index. (Bugs 2026-10-11T19:26:40Z and 2026-11-03T02:12:43Z). */ 4943 if( sqlite3ExprIsConstant(pParse, pExpr) ){ 4944 return -1; 4945 } 4946 4947 v = pParse->pVdbe; 4948 assert( v!=0 ); 4949 if( p->bMaybeNullRow ){ 4950 /* The value of pExpr should be computed from the original expression, 4951 ** not from the index, if the index might be on a NULL row due to an 4952 ** outer join. */ 4953 int addr = sqlite3VdbeCurrentAddr(v); 4954 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target); 4955 VdbeCoverage(v); 4956 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target); 4957 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol)); 4958 sqlite3VdbeGoto(v, 0); 4959 p = pParse->pIdxEpr; 4960 pParse->pIdxEpr = 0; 4961 sqlite3ExprCode(pParse, pExpr, target); 4962 pParse->pIdxEpr = p; 4963 sqlite3VdbeJumpHere(v, addr+2); 4964 }else{ 4965 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target); 4966 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol)); 4967 } 4968 return target; 4969 } 4970 return -1; /* Not found */ 4971 } 4972 4973 4974 /* 4975 ** Expression pExpr is guaranteed to be a TK_COLUMN or equivalent. This 4976 ** function checks the Parse.pIdxPartExpr list to see if this column 4977 ** can be replaced with a constant value. If so, it generates code to 4978 ** put the constant value in a register (ideally, but not necessarily, 4979 ** register iTarget) and returns the register number. 4980 ** 4981 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is 4982 ** returned. 4983 */ 4984 static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){ 4985 IndexedExpr *p; 4986 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){ 4987 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){ 4988 Vdbe *v = pParse->pVdbe; 4989 int addr = 0; 4990 int ret; 4991 u8 okConstFactor = pParse->okConstFactor; 4992 4993 if( p->bMaybeNullRow ){ 4994 /* OP_IfNullRow can overwrite the result register with NULL, so the 4995 ** value must be recomputed each time, not factored out. */ 4996 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur); 4997 pParse->okConstFactor = 0; 4998 } 4999 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget); 5000 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0, 5001 (const char*)&p->aff, 1); 5002 if( sqlite3ExprCanReturnSubtype(pParse, p->pExpr) ){ 5003 /* If the expression value may have a sub-type, clear it. Values 5004 ** read from columns do not have subtypes. */ 5005 sqlite3VdbeAddOp1(pParse->pVdbe, OP_ClrSubtype, ret); 5006 } 5007 if( addr ){ 5008 pParse->okConstFactor = okConstFactor; 5009 sqlite3VdbeJumpHere(v, addr); 5010 sqlite3VdbeChangeP3(v, addr, ret); 5011 } 5012 return ret; 5013 } 5014 } 5015 return 0; 5016 } 5017 5018 /* 5019 ** Generate code that evaluates an AND or OR operator leaving a 5020 ** boolean result in a register. pExpr is the AND/OR expression. 5021 ** Store the result in the "target" register. Use short-circuit 5022 ** evaluation to avoid computing both operands, if possible. 5023 ** 5024 ** The code generated might require the use of a temporary register. 5025 ** If it does, then write the number of that temporary register 5026 ** into *pTmpReg. If not, leave *pTmpReg unchanged. 5027 */ 5028 static SQLITE_NOINLINE int exprCodeTargetAndOr( 5029 Parse *pParse, /* Parsing context */ 5030 Expr *pExpr, /* AND or OR expression to be coded */ 5031 int target, /* Put result in this register, guaranteed */ 5032 int *pTmpReg /* Write a temporary register here */ 5033 ){ 5034 int op; /* The opcode. TK_AND or TK_OR */ 5035 int skipOp; /* Opcode for the branch that skips one operand */ 5036 int addrSkip; /* Branch instruction that skips one of the operands */ 5037 int regSS = 0; /* Register holding computed operand when other omitted */ 5038 int r1, r2; /* Registers for left and right operands, respectively */ 5039 Expr *pAlt; /* Alternative, simplified expression */ 5040 Vdbe *v; /* statement being coded */ 5041 5042 assert( pExpr!=0 ); 5043 op = pExpr->op; 5044 assert( op==TK_AND || op==TK_OR ); 5045 assert( TK_AND==OP_And ); testcase( op==TK_AND ); 5046 assert( TK_OR==OP_Or ); testcase( op==TK_OR ); 5047 assert( pParse->pVdbe!=0 ); 5048 v = pParse->pVdbe; 5049 pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 5050 if( pAlt!=pExpr ){ 5051 r1 = sqlite3ExprCodeTarget(pParse, pAlt, target); 5052 sqlite3VdbeAddOp3(v, OP_And, r1, r1, target); 5053 return target; 5054 } 5055 skipOp = op==TK_AND ? OP_IfNot : OP_If; 5056 if( exprEvalRhsFirst(pExpr) ){ 5057 /* Compute the right operand first. Skip the computation of the left 5058 ** operand if the right operand fully determines the result */ 5059 r2 = regSS = sqlite3ExprCodeTarget(pParse, pExpr->pRight, target); 5060 addrSkip = sqlite3VdbeAddOp1(v, skipOp, r2); 5061 VdbeComment((v, "skip left operand")); 5062 VdbeCoverage(v); 5063 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, pTmpReg); 5064 }else{ 5065 /* Compute the left operand first */ 5066 r1 = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); 5067 if( ExprHasProperty(pExpr->pRight, EP_Subquery) ){ 5068 /* Skip over the computation of the right operand if the right 5069 ** operand is a subquery and the left operand completely determines 5070 ** the result */ 5071 regSS = r1; 5072 addrSkip = sqlite3VdbeAddOp1(v, skipOp, r1); 5073 VdbeComment((v, "skip right operand")); 5074 VdbeCoverage(v); 5075 }else{ 5076 addrSkip = regSS = 0; 5077 } 5078 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, pTmpReg); 5079 } 5080 sqlite3VdbeAddOp3(v, op, r2, r1, target); 5081 testcase( (*pTmpReg)==0 ); 5082 if( addrSkip ){ 5083 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); 5084 sqlite3VdbeJumpHere(v, addrSkip); 5085 sqlite3VdbeAddOp3(v, OP_Or, regSS, regSS, target); 5086 VdbeComment((v, "short-circut value")); 5087 } 5088 return target; 5089 } 5090 5091 5092 5093 /* 5094 ** Generate code into the current Vdbe to evaluate the given 5095 ** expression. Attempt to store the results in register "target". 5096 ** Return the register where results are stored. 5097 ** 5098 ** With this routine, there is no guarantee that results will 5099 ** be stored in target. The result might be stored in some other 5100 ** register if it is convenient to do so. The calling function 5101 ** must check the return code and move the results to the desired 5102 ** register. 5103 */ 5104 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ 5105 Vdbe *v = pParse->pVdbe; /* The VM under construction */ 5106 int op; /* The opcode being coded */ 5107 int inReg = target; /* Results stored in register inReg */ 5108 int regFree1 = 0; /* If non-zero free this temporary register */ 5109 int regFree2 = 0; /* If non-zero free this temporary register */ 5110 int r1, r2; /* Various register numbers */ 5111 Expr tempX; /* Temporary expression node */ 5112 int p5 = 0; 5113 5114 assert( target>0 && target<=pParse->nMem ); 5115 assert( v!=0 ); 5116 5117 expr_code_doover: 5118 if( pExpr==0 ){ 5119 op = TK_NULL; 5120 }else if( pParse->pIdxEpr!=0 5121 && !ExprHasProperty(pExpr, EP_Leaf) 5122 && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0 5123 ){ 5124 return r1; 5125 }else{ 5126 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 5127 op = pExpr->op; 5128 } 5129 assert( op!=TK_ORDER ); 5130 switch( op ){ 5131 case TK_AGG_COLUMN: { 5132 AggInfo *pAggInfo = pExpr->pAggInfo; 5133 struct AggInfo_col *pCol; 5134 assert( pAggInfo!=0 ); 5135 assert( pExpr->iAgg>=0 ); 5136 if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ){ 5137 /* Happens when the left table of a RIGHT JOIN is null and 5138 ** is using an expression index */ 5139 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 5140 #ifdef SQLITE_VDBE_COVERAGE 5141 /* Verify that the OP_Null above is exercised by tests 5142 ** tag-`20230325`-2 */ 5143 sqlite3VdbeAddOp3(v, OP_NotNull, target, 1, `20230325`); 5144 VdbeCoverageNeverTaken(v); 5145 #endif 5146 break; 5147 } 5148 pCol = &pAggInfo->aCol[pExpr->iAgg]; 5149 if( !pAggInfo->directMode ){ 5150 return AggInfoColumnReg(pAggInfo, pExpr->iAgg); 5151 }else if( pAggInfo->useSortingIdx ){ 5152 Table *pTab = pCol->pTab; 5153 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, 5154 pCol->iSorterColumn, target); 5155 if( pTab==0 ){ 5156 /* No comment added */ 5157 }else if( pCol->iColumn<0 ){ 5158 VdbeComment((v,"%s.rowid",pTab->zName)); 5159 }else{ 5160 VdbeComment((v,"%s.%s", 5161 pTab->zName, pTab->aCol[pCol->iColumn].zCnName)); 5162 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){ 5163 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 5164 } 5165 } 5166 return target; 5167 }else if( pExpr->y.pTab==0 ){ 5168 /* This case happens when the argument to an aggregate function 5169 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */ 5170 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target); 5171 return target; 5172 } 5173 /* Otherwise, fall thru into the TK_COLUMN case */ 5174 /* no break */ deliberate_fall_through 5175 } 5176 case TK_COLUMN: { 5177 int iTab = pExpr->iTable; 5178 int iReg; 5179 if( ExprHasProperty(pExpr, EP_FixedCol) ){ 5180 /* This COLUMN expression is really a constant due to WHERE clause 5181 ** constraints, and that constant is coded by the pExpr->pLeft 5182 ** expression. However, make sure the constant has the correct 5183 ** datatype by applying the Affinity of the table column to the 5184 ** constant. 5185 */ 5186 int aff; 5187 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target); 5188 assert( ExprUseYTab(pExpr) ); 5189 assert( pExpr->y.pTab!=0 ); 5190 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 5191 if( aff>SQLITE_AFF_BLOB ){ 5192 static const char zAff[] = "B\000C\000D\000E\000F"; 5193 assert( SQLITE_AFF_BLOB=='A' ); 5194 assert( SQLITE_AFF_TEXT=='B' ); 5195 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0, 5196 &zAff[(aff-'B')*2], P4_STATIC); 5197 } 5198 return iReg; 5199 } 5200 if( iTab<0 ){ 5201 if( pParse->iSelfTab<0 ){ 5202 /* Other columns in the same row for CHECK constraints or 5203 ** generated columns or for inserting into partial index. 5204 ** The row is unpacked into registers beginning at 5205 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register 5206 ** immediately prior to the first column. 5207 */ 5208 Column *pCol; 5209 Table *pTab; 5210 int iSrc; 5211 int iCol = pExpr->iColumn; 5212 assert( ExprUseYTab(pExpr) ); 5213 pTab = pExpr->y.pTab; 5214 assert( pTab!=0 ); 5215 assert( iCol>=XN_ROWID ); 5216 assert( iColnCol ); 5217 if( iCol<0 ){ 5218 return -1-pParse->iSelfTab; 5219 } 5220 pCol = pTab->aCol + iCol; 5221 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) ); 5222 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab; 5223 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 5224 if( pCol->colFlags & COLFLAG_GENERATED ){ 5225 if( pCol->colFlags & COLFLAG_BUSY ){ 5226 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", 5227 pCol->zCnName); 5228 return 0; 5229 } 5230 pCol->colFlags |= COLFLAG_BUSY; 5231 if( pCol->colFlags & COLFLAG_NOTAVAIL ){ 5232 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc); 5233 } 5234 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL); 5235 return iSrc; 5236 }else 5237 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 5238 if( pCol->affinity==SQLITE_AFF_REAL ){ 5239 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target); 5240 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 5241 return target; 5242 }else{ 5243 return iSrc; 5244 } 5245 }else{ 5246 /* Coding an expression that is part of an index where column names 5247 ** in the index refer to the table to which the index belongs */ 5248 iTab = pParse->iSelfTab - 1; 5249 } 5250 } 5251 else if( pParse->pIdxPartExpr 5252 && 0!=(r1 = exprPartidxExprLookup(pParse, pExpr, target)) 5253 ){ 5254 return r1; 5255 } 5256 assert( ExprUseYTab(pExpr) ); 5257 assert( pExpr->y.pTab!=0 ); 5258 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab, 5259 pExpr->iColumn, iTab, target, 5260 pExpr->op2); 5261 return iReg; 5262 } 5263 case TK_INTEGER: { 5264 codeInteger(pParse, pExpr, 0, target); 5265 return target; 5266 } 5267 case TK_TRUEFALSE: { 5268 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target); 5269 return target; 5270 } 5271 #ifndef SQLITE_OMIT_FLOATING_POINT 5272 case TK_FLOAT: { 5273 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5274 codeReal(v, pExpr->u.zToken, 0, target); 5275 return target; 5276 } 5277 #endif 5278 case TK_STRING: { 5279 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5280 sqlite3VdbeLoadString(v, target, pExpr->u.zToken); 5281 return target; 5282 } 5283 case TK_NULLS: { 5284 /* Set a range of registers to NULL. pExpr->y.nReg registers starting 5285 ** with target */ 5286 sqlite3VdbeAddOp3(v, OP_Null, 0, target, target + pExpr->y.nReg - 1); 5287 return target; 5288 } 5289 default: { 5290 /* Make NULL the default case so that if a bug causes an illegal 5291 ** Expr node to be passed into this function, it will be handled 5292 ** sanely and not crash. But keep the assert() to bring the problem 5293 ** to the attention of the developers. */ 5294 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed ); 5295 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 5296 return target; 5297 } 5298 #ifndef SQLITE_OMIT_BLOB_LITERAL 5299 case TK_BLOB: { 5300 int n; 5301 const char *z; 5302 char *zBlob; 5303 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5304 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); 5305 assert( pExpr->u.zToken[1]=='\'' ); 5306 z = &pExpr->u.zToken[2]; 5307 n = sqlite3Strlen30(z) - 1; 5308 assert( z[n]=='\'' ); 5309 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); 5310 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); 5311 return target; 5312 } 5313 #endif 5314 case TK_VARIABLE: { 5315 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5316 assert( pExpr->u.zToken!=0 ); 5317 assert( pExpr->u.zToken[0]!=0 ); 5318 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); 5319 return target; 5320 } 5321 case TK_REGISTER: { 5322 return pExpr->iTable; 5323 } 5324 #ifndef SQLITE_OMIT_CAST 5325 case TK_CAST: { 5326 /* Expressions of the form: CAST(pLeft AS token) */ 5327 sqlite3ExprCode(pParse, pExpr->pLeft, target); 5328 assert( inReg==target ); 5329 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5330 sqlite3VdbeAddOp2(v, OP_Cast, target, 5331 sqlite3AffinityType(pExpr->u.zToken, 0)); 5332 return inReg; 5333 } 5334 #endif /* SQLITE_OMIT_CAST */ 5335 case TK_IS: 5336 case TK_ISNOT: 5337 op = (op==TK_IS) ? TK_EQ : TK_NE; 5338 p5 = SQLITE_NULLEQ; 5339 /* no break */ deliberate_fall_through 5340 case TK_LT: 5341 case TK_LE: 5342 case TK_GT: 5343 case TK_GE: 5344 case TK_NE: 5345 case TK_EQ: { 5346 Expr *pLeft = pExpr->pLeft; 5347 int addrIsNull = 0; 5348 if( sqlite3ExprIsVector(pLeft) ){ 5349 codeVectorCompare(pParse, pExpr, target, op, p5); 5350 }else{ 5351 if( ExprHasProperty(pExpr, EP_Subquery) && p5!=SQLITE_NULLEQ ){ 5352 addrIsNull = exprComputeOperands(pParse, pExpr, 5353 &r1, &r2, ®Free1, ®Free2); 5354 }else{ 5355 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5356 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 5357 } 5358 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg); 5359 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2, 5360 sqlite3VdbeCurrentAddr(v)+2, p5, 5361 ExprHasProperty(pExpr,EP_Commuted)); 5362 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 5363 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 5364 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 5365 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 5366 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); 5367 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); 5368 if( p5==SQLITE_NULLEQ ){ 5369 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg); 5370 }else{ 5371 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2); 5372 if( addrIsNull ){ 5373 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); 5374 sqlite3VdbeJumpHere(v, addrIsNull); 5375 sqlite3VdbeAddOp2(v, OP_Null, 0, inReg); 5376 } 5377 } 5378 testcase( regFree1==0 ); 5379 testcase( regFree2==0 ); 5380 } 5381 break; 5382 } 5383 case TK_AND: 5384 case TK_OR: { 5385 inReg = exprCodeTargetAndOr(pParse, pExpr, target, ®Free1); 5386 break; 5387 } 5388 case TK_PLUS: 5389 case TK_STAR: 5390 case TK_MINUS: 5391 case TK_REM: 5392 case TK_BITAND: 5393 case TK_BITOR: 5394 case TK_SLASH: 5395 case TK_LSHIFT: 5396 case TK_RSHIFT: 5397 case TK_CONCAT: { 5398 int addrIsNull; 5399 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); 5400 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); 5401 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); 5402 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND ); 5403 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR ); 5404 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH ); 5405 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); 5406 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); 5407 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); 5408 if( ExprHasProperty(pExpr, EP_Subquery) ){ 5409 addrIsNull = exprComputeOperands(pParse, pExpr, 5410 &r1, &r2, ®Free1, ®Free2); 5411 }else{ 5412 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5413 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 5414 addrIsNull = 0; 5415 } 5416 sqlite3VdbeAddOp3(v, op, r2, r1, target); 5417 testcase( regFree1==0 ); 5418 testcase( regFree2==0 ); 5419 if( addrIsNull ){ 5420 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); 5421 sqlite3VdbeJumpHere(v, addrIsNull); 5422 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 5423 VdbeComment((v, "short-circut value")); 5424 } 5425 break; 5426 } 5427 case TK_UMINUS: { 5428 Expr *pLeft = pExpr->pLeft; 5429 assert( pLeft ); 5430 if( pLeft->op==TK_INTEGER ){ 5431 codeInteger(pParse, pLeft, 1, target); 5432 return target; 5433 #ifndef SQLITE_OMIT_FLOATING_POINT 5434 }else if( pLeft->op==TK_FLOAT ){ 5435 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5436 codeReal(v, pLeft->u.zToken, 1, target); 5437 return target; 5438 #endif 5439 }else{ 5440 tempX.op = TK_INTEGER; 5441 tempX.flags = EP_IntValue|EP_TokenOnly; 5442 tempX.u.iValue = 0; 5443 ExprClearVVAProperties(&tempX); 5444 r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1); 5445 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); 5446 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); 5447 testcase( regFree2==0 ); 5448 } 5449 break; 5450 } 5451 case TK_BITNOT: 5452 case TK_NOT: { 5453 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); 5454 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); 5455 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5456 testcase( regFree1==0 ); 5457 sqlite3VdbeAddOp2(v, op, r1, inReg); 5458 break; 5459 } 5460 case TK_TRUTH: { 5461 int isTrue; /* IS TRUE or IS NOT TRUE */ 5462 int bNormal; /* IS TRUE or IS FALSE */ 5463 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5464 testcase( regFree1==0 ); 5465 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 5466 bNormal = pExpr->op2==TK_IS; 5467 testcase( isTrue && bNormal); 5468 testcase( !isTrue && bNormal); 5469 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal); 5470 break; 5471 } 5472 case TK_ISNULL: 5473 case TK_NOTNULL: { 5474 int addr; 5475 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 5476 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 5477 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 5478 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5479 testcase( regFree1==0 ); 5480 addr = sqlite3VdbeAddOp1(v, op, r1); 5481 VdbeCoverageIf(v, op==TK_ISNULL); 5482 VdbeCoverageIf(v, op==TK_NOTNULL); 5483 sqlite3VdbeAddOp2(v, OP_Integer, 0, target); 5484 sqlite3VdbeJumpHere(v, addr); 5485 break; 5486 } 5487 case TK_AGG_FUNCTION: { 5488 AggInfo *pInfo = pExpr->pAggInfo; 5489 if( pInfo==0 5490 || NEVER(pExpr->iAgg<0) 5491 || NEVER(pExpr->iAgg>=pInfo->nFunc) 5492 ){ 5493 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5494 sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr); 5495 }else{ 5496 return AggInfoFuncReg(pInfo, pExpr->iAgg); 5497 } 5498 break; 5499 } 5500 case TK_FUNCTION: { 5501 ExprList *pFarg; /* List of function arguments */ 5502 int nFarg; /* Number of function arguments */ 5503 FuncDef *pDef; /* The function definition object */ 5504 const char *zId; /* The function name */ 5505 u32 constMask = 0; /* Mask of function arguments that are constant */ 5506 int i; /* Loop counter */ 5507 sqlite3 *db = pParse->db; /* The database connection */ 5508 u8 enc = ENC(db); /* The text encoding used by this database */ 5509 CollSeq *pColl = 0; /* A collating sequence */ 5510 5511 #ifndef SQLITE_OMIT_WINDOWFUNC 5512 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 5513 return pExpr->y.pWin->regResult; 5514 } 5515 #endif 5516 5517 if( ConstFactorOk(pParse) 5518 && sqlite3ExprIsConstantNotJoin(pParse,pExpr) 5519 ){ 5520 /* SQL functions can be expensive. So try to avoid running them 5521 ** multiple times if we know they always give the same result */ 5522 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); 5523 } 5524 assert( !ExprHasProperty(pExpr, EP_TokenOnly) ); 5525 assert( ExprUseXList(pExpr) ); 5526 pFarg = pExpr->x.pList; 5527 nFarg = pFarg ? pFarg->nExpr : 0; 5528 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5529 zId = pExpr->u.zToken; 5530 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); 5531 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 5532 if( pDef==0 && pParse->explain ){ 5533 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); 5534 } 5535 #endif 5536 if( pDef==0 5537 || pDef->xFinalize!=0 5538 || ((pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0 && 5539 !pParse->nested && 5540 (db->mDbFlags & DBFLAG_InternalFunc)==0) 5541 ){ 5542 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr); 5543 break; 5544 } 5545 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){ 5546 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 ); 5547 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 ); 5548 return exprCodeInlineFunction(pParse, pFarg, 5549 SQLITE_PTR_TO_INT(pDef->pUserData), target); 5550 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){ 5551 sqlite3ExprFunctionUsable(pParse, pExpr, pDef); 5552 } 5553 5554 for(i=0; ia[i].pExpr) ){ 5556 testcase( i==31 ); 5557 constMask |= MASKBIT32(i); 5558 } 5559 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ 5560 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); 5561 } 5562 } 5563 if( pFarg ){ 5564 if( constMask ){ 5565 r1 = pParse->nMem+1; 5566 pParse->nMem += nFarg; 5567 }else{ 5568 r1 = sqlite3GetTempRange(pParse, nFarg); 5569 } 5570 5571 /* For length() and typeof() and octet_length() functions, 5572 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG 5573 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid 5574 ** unnecessary data loading. 5575 */ 5576 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ 5577 u8 exprOp; 5578 assert( nFarg==1 ); 5579 assert( pFarg->a[0].pExpr!=0 ); 5580 exprOp = pFarg->a[0].pExpr->op; 5581 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ 5582 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); 5583 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); 5584 assert( SQLITE_FUNC_BYTELEN==OPFLAG_BYTELENARG ); 5585 assert( (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG)==OPFLAG_BYTELENARG ); 5586 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG ); 5587 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG ); 5588 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG); 5589 pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG; 5590 } 5591 } 5592 5593 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_FACTOR); 5594 }else{ 5595 r1 = 0; 5596 } 5597 #ifndef SQLITE_OMIT_VIRTUALTABLE 5598 /* Possibly overload the function if the first argument is 5599 ** a virtual table column. 5600 ** 5601 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the 5602 ** second argument, not the first, as the argument to test to 5603 ** see if it is a column in a virtual table. This is done because 5604 ** the left operand of infix functions (the operand we want to 5605 ** control overloading) ends up as the second argument to the 5606 ** function. The expression "A glob B" is equivalent to 5607 ** "glob(B,A). We want to use the A in "A glob B" to test 5608 ** for function overloading. But we use the B term in "glob(B,A)". 5609 */ 5610 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){ 5611 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); 5612 }else if( nFarg>0 ){ 5613 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); 5614 } 5615 #endif 5616 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 5617 if( !pColl ) pColl = db->pDfltColl; 5618 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 5619 } 5620 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg, 5621 pDef, pExpr->op2); 5622 if( nFarg ){ 5623 if( constMask==0 ){ 5624 sqlite3ReleaseTempRange(pParse, r1, nFarg); 5625 }else{ 5626 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1); 5627 } 5628 } 5629 return target; 5630 } 5631 #ifndef SQLITE_OMIT_SUBQUERY 5632 case TK_EXISTS: 5633 case TK_SELECT: { 5634 int nCol; 5635 testcase( op==TK_EXISTS ); 5636 testcase( op==TK_SELECT ); 5637 if( pParse->db->mallocFailed ){ 5638 return 0; 5639 }else if( op==TK_SELECT 5640 && ALWAYS( ExprUseXSelect(pExpr) ) 5641 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 5642 ){ 5643 sqlite3SubselectError(pParse, nCol, 1); 5644 }else{ 5645 return sqlite3CodeSubselect(pParse, pExpr); 5646 } 5647 break; 5648 } 5649 case TK_SELECT_COLUMN: { 5650 int n; 5651 Expr *pLeft = pExpr->pLeft; 5652 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){ 5653 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft); 5654 pLeft->op2 = pParse->withinRJSubrtn; 5655 } 5656 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR ); 5657 n = sqlite3ExprVectorSize(pLeft); 5658 if( pExpr->iTable!=n ){ 5659 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 5660 pExpr->iTable, n); 5661 } 5662 return pLeft->iTable + pExpr->iColumn; 5663 } 5664 case TK_IN: { 5665 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 5666 int destIfNull = sqlite3VdbeMakeLabel(pParse); 5667 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 5668 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 5669 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 5670 sqlite3VdbeResolveLabel(v, destIfFalse); 5671 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); 5672 sqlite3VdbeResolveLabel(v, destIfNull); 5673 return target; 5674 } 5675 #endif /* SQLITE_OMIT_SUBQUERY */ 5676 5677 5678 /* 5679 ** x BETWEEN y AND z 5680 ** 5681 ** This is equivalent to 5682 ** 5683 ** x>=y AND x<=z 5684 ** 5685 ** X is stored in pExpr->pLeft. 5686 ** Y is stored in pExpr->pList->a[0].pExpr. 5687 ** Z is stored in pExpr->pList->a[1].pExpr. 5688 */ 5689 case TK_BETWEEN: { 5690 exprCodeBetween(pParse, pExpr, target, 0, 0); 5691 return target; 5692 } 5693 case TK_COLLATE: { 5694 if( !ExprHasProperty(pExpr, EP_Collate) ){ 5695 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called 5696 ** "SOFT-COLLATE" that is added to constraints that are pushed down 5697 ** from outer queries into sub-queries by the WHERE-clause push-down 5698 ** optimization. Clear subtypes as subtypes may not cross a subquery 5699 ** boundary. 5700 */ 5701 assert( pExpr->pLeft ); 5702 sqlite3ExprCode(pParse, pExpr->pLeft, target); 5703 sqlite3VdbeAddOp1(v, OP_ClrSubtype, target); 5704 return target; 5705 }else{ 5706 pExpr = pExpr->pLeft; 5707 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */ 5708 } 5709 } 5710 case TK_SPAN: 5711 case TK_UPLUS: { 5712 pExpr = pExpr->pLeft; 5713 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */ 5714 } 5715 5716 case TK_TRIGGER: { 5717 /* If the opcode is TK_TRIGGER, then the expression is a reference 5718 ** to a column in the new.* or old.* pseudo-tables available to 5719 ** trigger programs. In this case Expr.iTable is set to 1 for the 5720 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn 5721 ** is set to the column of the pseudo-table to read, or to -1 to 5722 ** read the rowid field. 5723 ** 5724 ** The expression is implemented using an OP_Param opcode. The p1 5725 ** parameter is set to 0 for an old.rowid reference, or to (i+1) 5726 ** to reference another column of the old.* pseudo-table, where 5727 ** i is the index of the column. For a new.rowid reference, p1 is 5728 ** set to (n+1), where n is the number of columns in each pseudo-table. 5729 ** For a reference to any other column in the new.* pseudo-table, p1 5730 ** is set to (n+2+i), where n and i are as defined previously. For 5731 ** example, if the table on which triggers are being fired is 5732 ** declared as: 5733 ** 5734 ** CREATE TABLE t1(a, b); 5735 ** 5736 ** Then p1 is interpreted as follows: 5737 ** 5738 ** p1==0 -> old.rowid p1==3 -> new.rowid 5739 ** p1==1 -> old.a p1==4 -> new.a 5740 ** p1==2 -> old.b p1==5 -> new.b 5741 */ 5742 Table *pTab; 5743 int iCol; 5744 int p1; 5745 5746 assert( ExprUseYTab(pExpr) ); 5747 pTab = pExpr->y.pTab; 5748 iCol = pExpr->iColumn; 5749 p1 = pExpr->iTable * (pTab->nCol+1) + 1 5750 + sqlite3TableColumnToStorage(pTab, iCol); 5751 5752 assert( pExpr->iTable==0 || pExpr->iTable==1 ); 5753 assert( iCol>=-1 && iColnCol ); 5754 assert( pTab->iPKey<0 || iCol!=pTab->iPKey ); 5755 assert( p1>=0 && p1<(pTab->nCol*2+2) ); 5756 5757 sqlite3VdbeAddOp2(v, OP_Param, p1, target); 5758 VdbeComment((v, "r[%d]=%s.%s", target, 5759 (pExpr->iTable ? "new" : "old"), 5760 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName) 5761 )); 5762 5763 #ifndef SQLITE_OMIT_FLOATING_POINT 5764 /* If the column has REAL affinity, it may currently be stored as an 5765 ** integer. Use OP_RealAffinity to make sure it is really real. 5766 ** 5767 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to 5768 ** floating point when extracting it from the record. */ 5769 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){ 5770 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 5771 } 5772 #endif 5773 break; 5774 } 5775 5776 case TK_VECTOR: { 5777 sqlite3ErrorMsg(pParse, "row value misused"); 5778 break; 5779 } 5780 5781 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions 5782 ** that derive from the right-hand table of a LEFT JOIN. The 5783 ** Expr.iTable value is the table number for the right-hand table. 5784 ** The expression is only evaluated if that table is not currently 5785 ** on a LEFT JOIN NULL row. 5786 */ 5787 case TK_IF_NULL_ROW: { 5788 int addrINR; 5789 u8 okConstFactor = pParse->okConstFactor; 5790 AggInfo *pAggInfo = pExpr->pAggInfo; 5791 if( pAggInfo ){ 5792 assert( pExpr->iAgg>=0 && pExpr->iAggnColumn ); 5793 if( !pAggInfo->directMode ){ 5794 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg); 5795 break; 5796 } 5797 if( pExpr->pAggInfo->useSortingIdx ){ 5798 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, 5799 pAggInfo->aCol[pExpr->iAgg].iSorterColumn, 5800 target); 5801 inReg = target; 5802 break; 5803 } 5804 } 5805 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target); 5806 /* The OP_IfNullRow opcode above can overwrite the result register with 5807 ** NULL. So we have to ensure that the result register is not a value 5808 ** that is suppose to be a constant. Two defenses are needed: 5809 ** (1) Temporarily disable factoring of constant expressions 5810 ** (2) Make sure the computed value really is stored in register 5811 ** "target" and not someplace else. 5812 */ 5813 pParse->okConstFactor = 0; /* note (1) above */ 5814 sqlite3ExprCode(pParse, pExpr->pLeft, target); 5815 assert( target==inReg ); 5816 pParse->okConstFactor = okConstFactor; 5817 sqlite3VdbeJumpHere(v, addrINR); 5818 break; 5819 } 5820 5821 /* 5822 ** Form A: 5823 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 5824 ** 5825 ** Form B: 5826 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 5827 ** 5828 ** Form A is can be transformed into the equivalent form B as follows: 5829 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... 5830 ** WHEN x=eN THEN rN ELSE y END 5831 ** 5832 ** X (if it exists) is in pExpr->pLeft. 5833 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is 5834 ** odd. The Y is also optional. If the number of elements in x.pList 5835 ** is even, then Y is omitted and the "otherwise" result is NULL. 5836 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. 5837 ** 5838 ** The result of the expression is the Ri for the first matching Ei, 5839 ** or if there is no matching Ei, the ELSE term Y, or if there is 5840 ** no ELSE term, NULL. 5841 */ 5842 case TK_CASE: { 5843 int endLabel; /* GOTO label for end of CASE stmt */ 5844 int nextCase; /* GOTO label for next WHEN clause */ 5845 int nExpr; /* 2x number of WHEN terms */ 5846 int i; /* Loop counter */ 5847 ExprList *pEList; /* List of WHEN terms */ 5848 struct ExprList_item *aListelem; /* Array of WHEN terms */ 5849 Expr opCompare; /* The X==Ei expression */ 5850 Expr *pX; /* The X expression */ 5851 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ 5852 Expr *pDel = 0; 5853 sqlite3 *db = pParse->db; 5854 5855 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 ); 5856 assert(pExpr->x.pList->nExpr > 0); 5857 pEList = pExpr->x.pList; 5858 aListelem = pEList->a; 5859 nExpr = pEList->nExpr; 5860 endLabel = sqlite3VdbeMakeLabel(pParse); 5861 if( (pX = pExpr->pLeft)!=0 ){ 5862 pDel = sqlite3ExprDup(db, pX, 0); 5863 if( db->mallocFailed ){ 5864 sqlite3ExprDelete(db, pDel); 5865 break; 5866 } 5867 testcase( pX->op==TK_COLUMN ); 5868 sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 5869 testcase( regFree1==0 ); 5870 memset(&opCompare, 0, sizeof(opCompare)); 5871 opCompare.op = TK_EQ; 5872 opCompare.pLeft = pDel; 5873 pTest = &opCompare; 5874 /* Ticket `b351d95f9cd5ef17e9d9dbae18f5ca8611190001`: 5875 ** The value in regFree1 might get SCopy-ed into the file result. 5876 ** So make sure that the regFree1 register is not reused for other 5877 ** purposes and possibly overwritten. */ 5878 regFree1 = 0; 5879 } 5880 for(i=0; iop==TK_COLUMN ); 5889 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); 5890 testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); 5891 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); 5892 sqlite3VdbeGoto(v, endLabel); 5893 sqlite3VdbeResolveLabel(v, nextCase); 5894 } 5895 if( (nExpr&1)!=0 ){ 5896 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); 5897 }else{ 5898 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 5899 } 5900 sqlite3ExprDelete(db, pDel); 5901 setDoNotMergeFlagOnCopy(v); 5902 sqlite3VdbeResolveLabel(v, endLabel); 5903 break; 5904 } 5905 #ifndef SQLITE_OMIT_TRIGGER 5906 case TK_RAISE: { 5907 assert( pExpr->affExpr==OE_Rollback 5908 || pExpr->affExpr==OE_Abort 5909 || pExpr->affExpr==OE_Fail 5910 || pExpr->affExpr==OE_Ignore 5911 ); 5912 if( !pParse->pTriggerTab ){ 5913 sqlite3ErrorMsg(pParse, 5914 "RAISE() may only be used within a trigger-program"); 5915 return 0; 5916 } 5917 if( pExpr->affExpr==OE_Abort ){ 5918 sqlite3MayAbort(pParse); 5919 } 5920 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 5921 if( pExpr->affExpr==OE_Ignore ){ 5922 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, OE_Ignore); 5923 VdbeCoverage(v); 5924 }else{ 5925 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 5926 sqlite3VdbeAddOp3(v, OP_Halt, SQLITE_CONSTRAINT_TRIGGER, 5927 pExpr->affExpr, r1); 5928 } 5929 break; 5930 } 5931 #endif 5932 } 5933 sqlite3ReleaseTempReg(pParse, regFree1); 5934 sqlite3ReleaseTempReg(pParse, regFree2); 5935 return inReg; 5936 } 5937 5938 /* 5939 ** Generate code that will evaluate expression pExpr just one time 5940 ** per prepared statement execution. 5941 ** 5942 ** If the expression uses functions (that might throw an exception) then 5943 ** guard them with an OP_Once opcode to ensure that the code is only executed 5944 ** once. If no functions are involved, then factor the code out and put it at 5945 ** the end of the prepared statement in the initialization section. 5946 ** 5947 ** If regDest>0 then the result is always stored in that register and the 5948 ** result is not reusable. If regDest<0 then this routine is free to 5949 ** store the value wherever it wants. The register where the expression 5950 ** is stored is returned. When regDest<0, two identical expressions might 5951 ** code to the same register, if they do not contain function calls and hence 5952 ** are factored out into the initialization section at the end of the 5953 ** prepared statement. 5954 */ 5955 int sqlite3ExprCodeRunJustOnce( 5956 Parse *pParse, /* Parsing context */ 5957 Expr *pExpr, /* The expression to code when the VDBE initializes */ 5958 int regDest /* Store the value in this register */ 5959 ){ 5960 ExprList *p; 5961 assert( ConstFactorOk(pParse) ); 5962 assert( regDest!=0 ); 5963 p = pParse->pConstExpr; 5964 if( regDest<0 && p ){ 5965 struct ExprList_item *pItem; 5966 int i; 5967 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ 5968 if( pItem->fg.reusable 5969 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 5970 ){ 5971 return pItem->u.iConstExprReg; 5972 } 5973 } 5974 } 5975 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); 5976 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){ 5977 Vdbe *v = pParse->pVdbe; 5978 int addr; 5979 assert( v ); 5980 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 5981 pParse->okConstFactor = 0; 5982 if( !pParse->db->mallocFailed ){ 5983 if( regDest<0 ) regDest = ++pParse->nMem; 5984 sqlite3ExprCode(pParse, pExpr, regDest); 5985 } 5986 pParse->okConstFactor = 1; 5987 sqlite3ExprDelete(pParse->db, pExpr); 5988 sqlite3VdbeJumpHere(v, addr); 5989 }else{ 5990 p = sqlite3ExprListAppend(pParse, p, pExpr); 5991 if( p ){ 5992 struct ExprList_item *pItem = &p->a[p->nExpr-1]; 5993 pItem->fg.reusable = regDest<0; 5994 if( regDest<0 ) regDest = ++pParse->nMem; 5995 pItem->u.iConstExprReg = regDest; 5996 } 5997 pParse->pConstExpr = p; 5998 } 5999 return regDest; 6000 } 6001 6002 /* 6003 ** Make arrangements to invoke OP_Null on a range of registers 6004 ** during initialization. 6005 */ 6006 SQLITE_NOINLINE void sqlite3ExprNullRegisterRange( 6007 Parse *pParse, /* Parsing context */ 6008 int iReg, /* First register to set to NULL */ 6009 int nReg /* Number of sequential registers to NULL out */ 6010 ){ 6011 u8 okConstFactor = pParse->okConstFactor; 6012 Expr t; 6013 memset(&t, 0, sizeof(t)); 6014 t.op = TK_NULLS; 6015 t.y.nReg = nReg; 6016 pParse->okConstFactor = 1; 6017 sqlite3ExprCodeRunJustOnce(pParse, &t, iReg); 6018 pParse->okConstFactor = okConstFactor; 6019 } 6020 6021 /* 6022 ** Generate code to evaluate an expression and store the results 6023 ** into a register. Return the register number where the results 6024 ** are stored. 6025 ** 6026 ** If the register is a temporary register that can be deallocated, 6027 ** then write its number into *pReg. If the result register is not 6028 ** a temporary, then set *pReg to zero. 6029 ** 6030 ** If pExpr is a constant, then this routine might generate this 6031 ** code to fill the register in the initialization section of the 6032 ** VDBE program, in order to factor it out of the evaluation loop. 6033 */ 6034 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ 6035 int r2; 6036 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr); 6037 if( ConstFactorOk(pParse) 6038 && ALWAYS(pExpr!=0) 6039 && pExpr->op!=TK_REGISTER 6040 && sqlite3ExprIsConstantNotJoin(pParse, pExpr) 6041 ){ 6042 *pReg = 0; 6043 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); 6044 }else{ 6045 int r1 = sqlite3GetTempReg(pParse); 6046 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); 6047 if( r2==r1 ){ 6048 *pReg = r1; 6049 }else{ 6050 sqlite3ReleaseTempReg(pParse, r1); 6051 *pReg = 0; 6052 } 6053 } 6054 return r2; 6055 } 6056 6057 /* 6058 ** Generate code that will evaluate expression pExpr and store the 6059 ** results in register target. The results are guaranteed to appear 6060 ** in register target. 6061 */ 6062 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ 6063 int inReg; 6064 6065 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) ); 6066 assert( target>0 && target<=pParse->nMem ); 6067 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); 6068 if( pParse->pVdbe==0 ) return; 6069 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); 6070 if( inReg!=target ){ 6071 u8 op; 6072 Expr *pX = sqlite3ExprSkipCollateAndLikely(pExpr); 6073 testcase( pX!=pExpr ); 6074 if( ALWAYS(pX) 6075 && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER) 6076 ){ 6077 op = OP_Copy; 6078 }else{ 6079 op = OP_SCopy; 6080 } 6081 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target); 6082 } 6083 } 6084 6085 /* 6086 ** Make a transient copy of expression pExpr and then code it using 6087 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() 6088 ** except that the input expression is guaranteed to be unchanged. 6089 */ 6090 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ 6091 sqlite3 *db = pParse->db; 6092 pExpr = sqlite3ExprDup(db, pExpr, 0); 6093 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); 6094 sqlite3ExprDelete(db, pExpr); 6095 } 6096 6097 /* 6098 ** Generate code that will evaluate expression pExpr and store the 6099 ** results in register target. The results are guaranteed to appear 6100 ** in register target. If the expression is constant, then this routine 6101 ** might choose to code the expression at initialization time. 6102 */ 6103 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ 6104 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pParse,pExpr) ){ 6105 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target); 6106 }else{ 6107 sqlite3ExprCodeCopy(pParse, pExpr, target); 6108 } 6109 } 6110 6111 /* 6112 ** Generate code that pushes the value of every element of the given 6113 ** expression list into a sequence of registers beginning at target. 6114 ** 6115 ** Return the number of elements evaluated. The number returned will 6116 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF 6117 ** is defined. 6118 ** 6119 ** The SQLITE_ECEL_DUP flag prevents the arguments from being 6120 ** filled using OP_SCopy. OP_Copy must be used instead. 6121 ** 6122 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be 6123 ** factored out into initialization code. 6124 ** 6125 ** The SQLITE_ECEL_REF flag means that expressions in the list with 6126 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored 6127 ** in registers at srcReg, and so the value can be copied from there. 6128 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0 6129 ** are simply omitted rather than being copied from srcReg. 6130 */ 6131 int sqlite3ExprCodeExprList( 6132 Parse *pParse, /* Parsing context */ 6133 ExprList *pList, /* The expression list to be coded */ 6134 int target, /* Where to write results */ 6135 int srcReg, /* Source registers if SQLITE_ECEL_REF */ 6136 u8 flags /* SQLITE_ECEL_* flags */ 6137 ){ 6138 struct ExprList_item *pItem; 6139 int i, j, n; 6140 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy; 6141 Vdbe *v = pParse->pVdbe; 6142 assert( pList!=0 ); 6143 assert( target>0 ); 6144 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ 6145 n = pList->nExpr; 6146 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; 6147 for(pItem=pList->a, i=0; ipExpr; 6149 #ifdef SQLITE_ENABLE_SORTER_REFERENCES 6150 if( pItem->fg.bSorterRef ){ 6151 i--; 6152 n--; 6153 }else 6154 #endif 6155 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){ 6156 if( flags & SQLITE_ECEL_OMITREF ){ 6157 i--; 6158 n--; 6159 }else{ 6160 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); 6161 } 6162 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 6163 && sqlite3ExprIsConstantNotJoin(pParse,pExpr) 6164 ){ 6165 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i); 6166 }else{ 6167 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); 6168 if( inReg!=target+i ){ 6169 VdbeOp *pOp; 6170 if( copyOp==OP_Copy 6171 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy 6172 && pOp->p1+pOp->p3+1==inReg 6173 && pOp->p2+pOp->p3+1==target+i 6174 && pOp->p5==0 /* The do-not-merge flag must be clear */ 6175 ){ 6176 pOp->p3++; 6177 }else{ 6178 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); 6179 } 6180 } 6181 } 6182 } 6183 return n; 6184 } 6185 6186 /* 6187 ** Generate code for a BETWEEN operator. 6188 ** 6189 ** x BETWEEN y AND z 6190 ** 6191 ** The above is equivalent to 6192 ** 6193 ** x>=y AND x<=z 6194 ** 6195 ** Code it as such, taking care to do the common subexpression 6196 ** elimination of x. 6197 ** 6198 ** The xJumpIf parameter determines details: 6199 ** 6200 ** NULL: Store the boolean result in reg[dest] 6201 ** sqlite3ExprIfTrue: Jump to dest if true 6202 ** sqlite3ExprIfFalse: Jump to dest if false 6203 ** 6204 ** The jumpIfNull parameter is ignored if xJumpIf is NULL. 6205 */ 6206 static void exprCodeBetween( 6207 Parse *pParse, /* Parsing and code generating context */ 6208 Expr *pExpr, /* The BETWEEN expression */ 6209 int dest, /* Jump destination or storage location */ 6210 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ 6211 int jumpIfNull /* Take the jump if the BETWEEN is NULL */ 6212 ){ 6213 Expr exprAnd; /* The AND operator in x>=y AND x<=z */ 6214 Expr compLeft; /* The x>=y term */ 6215 Expr compRight; /* The x<=z term */ 6216 int regFree1 = 0; /* Temporary use register */ 6217 Expr *pDel = 0; 6218 sqlite3 *db = pParse->db; 6219 6220 memset(&compLeft, 0, sizeof(Expr)); 6221 memset(&compRight, 0, sizeof(Expr)); 6222 memset(&exprAnd, 0, sizeof(Expr)); 6223 6224 assert( ExprUseXList(pExpr) ); 6225 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0); 6226 if( db->mallocFailed==0 ){ 6227 exprAnd.op = TK_AND; 6228 exprAnd.pLeft = &compLeft; 6229 exprAnd.pRight = &compRight; 6230 compLeft.op = TK_GE; 6231 compLeft.pLeft = pDel; 6232 compLeft.pRight = pExpr->x.pList->a[0].pExpr; 6233 compRight.op = TK_LE; 6234 compRight.pLeft = pDel; 6235 compRight.pRight = pExpr->x.pList->a[1].pExpr; 6236 sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 6237 if( xJump ){ 6238 xJump(pParse, &exprAnd, dest, jumpIfNull); 6239 }else{ 6240 /* Mark the expression is being from the ON or USING clause of a join 6241 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move 6242 ** it into the Parse.pConstExpr list. We should use a new bit for this, 6243 ** for clarity, but we are out of bits in the Expr.flags field so we 6244 ** have to reuse the EP_OuterON bit. Bummer. */ 6245 pDel->flags |= EP_OuterON; 6246 sqlite3ExprCodeTarget(pParse, &exprAnd, dest); 6247 } 6248 sqlite3ReleaseTempReg(pParse, regFree1); 6249 } 6250 sqlite3ExprDelete(db, pDel); 6251 6252 /* Ensure adequate test coverage */ 6253 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); 6254 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); 6255 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); 6256 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); 6257 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); 6258 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); 6259 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); 6260 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); 6261 testcase( xJump==0 ); 6262 } 6263 6264 /* 6265 ** Generate code for a boolean expression such that a jump is made 6266 ** to the label "dest" if the expression is true but execution 6267 ** continues straight thru if the expression is false. 6268 ** 6269 ** If the expression evaluates to NULL (neither true nor false), then 6270 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. 6271 ** 6272 ** This code depends on the fact that certain token values (ex: TK_EQ) 6273 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding 6274 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in 6275 ** the make process cause these values to align. Assert()s in the code 6276 ** below verify that the numbers are aligned correctly. 6277 */ 6278 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 6279 Vdbe *v = pParse->pVdbe; 6280 int op = 0; 6281 int regFree1 = 0; 6282 int regFree2 = 0; 6283 int r1, r2; 6284 6285 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 6286 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 6287 if( NEVER(pExpr==0) ) return; /* No way this can happen */ 6288 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) ); 6289 op = pExpr->op; 6290 switch( op ){ 6291 case TK_AND: 6292 case TK_OR: { 6293 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 6294 if( pAlt!=pExpr ){ 6295 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull); 6296 }else{ 6297 Expr *pFirst, *pSecond; 6298 if( exprEvalRhsFirst(pExpr) ){ 6299 pFirst = pExpr->pRight; 6300 pSecond = pExpr->pLeft; 6301 }else{ 6302 pFirst = pExpr->pLeft; 6303 pSecond = pExpr->pRight; 6304 } 6305 if( op==TK_AND ){ 6306 int d2 = sqlite3VdbeMakeLabel(pParse); 6307 testcase( jumpIfNull==0 ); 6308 sqlite3ExprIfFalse(pParse, pFirst, d2, 6309 jumpIfNull^SQLITE_JUMPIFNULL); 6310 sqlite3ExprIfTrue(pParse, pSecond, dest, jumpIfNull); 6311 sqlite3VdbeResolveLabel(v, d2); 6312 }else{ 6313 testcase( jumpIfNull==0 ); 6314 sqlite3ExprIfTrue(pParse, pFirst, dest, jumpIfNull); 6315 sqlite3ExprIfTrue(pParse, pSecond, dest, jumpIfNull); 6316 } 6317 } 6318 break; 6319 } 6320 case TK_NOT: { 6321 testcase( jumpIfNull==0 ); 6322 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 6323 break; 6324 } 6325 case TK_TRUTH: { 6326 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 6327 int isTrue; /* IS TRUE or IS NOT TRUE */ 6328 testcase( jumpIfNull==0 ); 6329 isNot = pExpr->op2==TK_ISNOT; 6330 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 6331 testcase( isTrue && isNot ); 6332 testcase( !isTrue && isNot ); 6333 if( isTrue ^ isNot ){ 6334 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 6335 isNot ? SQLITE_JUMPIFNULL : 0); 6336 }else{ 6337 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 6338 isNot ? SQLITE_JUMPIFNULL : 0); 6339 } 6340 break; 6341 } 6342 case TK_IS: 6343 case TK_ISNOT: 6344 testcase( op==TK_IS ); 6345 testcase( op==TK_ISNOT ); 6346 op = (op==TK_IS) ? TK_EQ : TK_NE; 6347 jumpIfNull = SQLITE_NULLEQ; 6348 /* no break */ deliberate_fall_through 6349 case TK_LT: 6350 case TK_LE: 6351 case TK_GT: 6352 case TK_GE: 6353 case TK_NE: 6354 case TK_EQ: { 6355 int addrIsNull; 6356 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 6357 if( ExprHasProperty(pExpr, EP_Subquery) && jumpIfNull!=SQLITE_NULLEQ ){ 6358 addrIsNull = exprComputeOperands(pParse, pExpr, 6359 &r1, &r2, ®Free1, ®Free2); 6360 }else{ 6361 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 6362 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 6363 addrIsNull = 0; 6364 } 6365 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 6366 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted)); 6367 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 6368 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 6369 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 6370 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 6371 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 6372 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 6373 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 6374 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 6375 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 6376 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 6377 testcase( regFree1==0 ); 6378 testcase( regFree2==0 ); 6379 if( addrIsNull ){ 6380 if( jumpIfNull ){ 6381 sqlite3VdbeChangeP2(v, addrIsNull, dest); 6382 }else{ 6383 sqlite3VdbeJumpHere(v, addrIsNull); 6384 } 6385 } 6386 break; 6387 } 6388 case TK_ISNULL: 6389 case TK_NOTNULL: { 6390 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 6391 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 6392 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 6393 assert( regFree1==0 || regFree1==r1 ); 6394 if( regFree1 ) sqlite3VdbeTypeofColumn(v, r1); 6395 sqlite3VdbeAddOp2(v, op, r1, dest); 6396 VdbeCoverageIf(v, op==TK_ISNULL); 6397 VdbeCoverageIf(v, op==TK_NOTNULL); 6398 break; 6399 } 6400 case TK_BETWEEN: { 6401 testcase( jumpIfNull==0 ); 6402 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); 6403 break; 6404 } 6405 #ifndef SQLITE_OMIT_SUBQUERY 6406 case TK_IN: { 6407 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 6408 int destIfNull = jumpIfNull ? dest : destIfFalse; 6409 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 6410 sqlite3VdbeGoto(v, dest); 6411 sqlite3VdbeResolveLabel(v, destIfFalse); 6412 break; 6413 } 6414 #endif 6415 default: { 6416 default_expr: 6417 if( ExprAlwaysTrue(pExpr) ){ 6418 sqlite3VdbeGoto(v, dest); 6419 }else if( ExprAlwaysFalse(pExpr) ){ 6420 /* No-op */ 6421 }else{ 6422 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 6423 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); 6424 VdbeCoverage(v); 6425 testcase( regFree1==0 ); 6426 testcase( jumpIfNull==0 ); 6427 } 6428 break; 6429 } 6430 } 6431 sqlite3ReleaseTempReg(pParse, regFree1); 6432 sqlite3ReleaseTempReg(pParse, regFree2); 6433 } 6434 6435 /* 6436 ** Generate code for a boolean expression such that a jump is made 6437 ** to the label "dest" if the expression is false but execution 6438 ** continues straight thru if the expression is true. 6439 ** 6440 ** If the expression evaluates to NULL (neither true nor false) then 6441 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull 6442 ** is 0. 6443 */ 6444 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 6445 Vdbe *v = pParse->pVdbe; 6446 int op = 0; 6447 int regFree1 = 0; 6448 int regFree2 = 0; 6449 int r1, r2; 6450 6451 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 6452 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 6453 if( pExpr==0 ) return; 6454 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 6455 6456 /* The value of pExpr->op and op are related as follows: 6457 ** 6458 ** pExpr->op op 6459 ** --------- ---------- 6460 ** TK_ISNULL OP_NotNull 6461 ** TK_NOTNULL OP_IsNull 6462 ** TK_NE OP_Eq 6463 ** TK_EQ OP_Ne 6464 ** TK_GT OP_Le 6465 ** TK_LE OP_Gt 6466 ** TK_GE OP_Lt 6467 ** TK_LT OP_Ge 6468 ** 6469 ** For other values of pExpr->op, op is undefined and unused. 6470 ** The value of TK_ and OP_ constants are arranged such that we 6471 ** can compute the mapping above using the following expression. 6472 ** Assert()s verify that the computation is correct. 6473 */ 6474 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); 6475 6476 /* Verify correct alignment of TK_ and OP_ constants 6477 */ 6478 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); 6479 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); 6480 assert( pExpr->op!=TK_NE || op==OP_Eq ); 6481 assert( pExpr->op!=TK_EQ || op==OP_Ne ); 6482 assert( pExpr->op!=TK_LT || op==OP_Ge ); 6483 assert( pExpr->op!=TK_LE || op==OP_Gt ); 6484 assert( pExpr->op!=TK_GT || op==OP_Le ); 6485 assert( pExpr->op!=TK_GE || op==OP_Lt ); 6486 6487 switch( pExpr->op ){ 6488 case TK_AND: 6489 case TK_OR: { 6490 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 6491 if( pAlt!=pExpr ){ 6492 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull); 6493 }else{ 6494 Expr *pFirst, *pSecond; 6495 if( exprEvalRhsFirst(pExpr) ){ 6496 pFirst = pExpr->pRight; 6497 pSecond = pExpr->pLeft; 6498 }else{ 6499 pFirst = pExpr->pLeft; 6500 pSecond = pExpr->pRight; 6501 } 6502 if( pExpr->op==TK_AND ){ 6503 testcase( jumpIfNull==0 ); 6504 sqlite3ExprIfFalse(pParse, pFirst, dest, jumpIfNull); 6505 sqlite3ExprIfFalse(pParse, pSecond, dest, jumpIfNull); 6506 }else{ 6507 int d2 = sqlite3VdbeMakeLabel(pParse); 6508 testcase( jumpIfNull==0 ); 6509 sqlite3ExprIfTrue(pParse, pFirst, d2, 6510 jumpIfNull^SQLITE_JUMPIFNULL); 6511 sqlite3ExprIfFalse(pParse, pSecond, dest, jumpIfNull); 6512 sqlite3VdbeResolveLabel(v, d2); 6513 } 6514 } 6515 break; 6516 } 6517 case TK_NOT: { 6518 testcase( jumpIfNull==0 ); 6519 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 6520 break; 6521 } 6522 case TK_TRUTH: { 6523 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 6524 int isTrue; /* IS TRUE or IS NOT TRUE */ 6525 testcase( jumpIfNull==0 ); 6526 isNot = pExpr->op2==TK_ISNOT; 6527 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 6528 testcase( isTrue && isNot ); 6529 testcase( !isTrue && isNot ); 6530 if( isTrue ^ isNot ){ 6531 /* IS TRUE and IS NOT FALSE */ 6532 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 6533 isNot ? 0 : SQLITE_JUMPIFNULL); 6534 6535 }else{ 6536 /* IS FALSE and IS NOT TRUE */ 6537 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 6538 isNot ? 0 : SQLITE_JUMPIFNULL); 6539 } 6540 break; 6541 } 6542 case TK_IS: 6543 case TK_ISNOT: 6544 testcase( pExpr->op==TK_IS ); 6545 testcase( pExpr->op==TK_ISNOT ); 6546 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; 6547 jumpIfNull = SQLITE_NULLEQ; 6548 /* no break */ deliberate_fall_through 6549 case TK_LT: 6550 case TK_LE: 6551 case TK_GT: 6552 case TK_GE: 6553 case TK_NE: 6554 case TK_EQ: { 6555 int addrIsNull; 6556 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 6557 if( ExprHasProperty(pExpr, EP_Subquery) && jumpIfNull!=SQLITE_NULLEQ ){ 6558 addrIsNull = exprComputeOperands(pParse, pExpr, 6559 &r1, &r2, ®Free1, ®Free2); 6560 }else{ 6561 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 6562 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 6563 addrIsNull = 0; 6564 } 6565 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 6566 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted)); 6567 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 6568 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 6569 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 6570 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 6571 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 6572 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 6573 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 6574 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 6575 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 6576 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 6577 testcase( regFree1==0 ); 6578 testcase( regFree2==0 ); 6579 if( addrIsNull ){ 6580 if( jumpIfNull ){ 6581 sqlite3VdbeChangeP2(v, addrIsNull, dest); 6582 }else{ 6583 sqlite3VdbeJumpHere(v, addrIsNull); 6584 } 6585 } 6586 break; 6587 } 6588 case TK_ISNULL: 6589 case TK_NOTNULL: { 6590 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 6591 assert( regFree1==0 || regFree1==r1 ); 6592 if( regFree1 ) sqlite3VdbeTypeofColumn(v, r1); 6593 sqlite3VdbeAddOp2(v, op, r1, dest); 6594 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); 6595 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); 6596 break; 6597 } 6598 case TK_BETWEEN: { 6599 testcase( jumpIfNull==0 ); 6600 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); 6601 break; 6602 } 6603 #ifndef SQLITE_OMIT_SUBQUERY 6604 case TK_IN: { 6605 if( jumpIfNull ){ 6606 sqlite3ExprCodeIN(pParse, pExpr, dest, dest); 6607 }else{ 6608 int destIfNull = sqlite3VdbeMakeLabel(pParse); 6609 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); 6610 sqlite3VdbeResolveLabel(v, destIfNull); 6611 } 6612 break; 6613 } 6614 #endif 6615 default: { 6616 default_expr: 6617 if( ExprAlwaysFalse(pExpr) ){ 6618 sqlite3VdbeGoto(v, dest); 6619 }else if( ExprAlwaysTrue(pExpr) ){ 6620 /* no-op */ 6621 }else{ 6622 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 6623 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); 6624 VdbeCoverage(v); 6625 testcase( regFree1==0 ); 6626 testcase( jumpIfNull==0 ); 6627 } 6628 break; 6629 } 6630 } 6631 sqlite3ReleaseTempReg(pParse, regFree1); 6632 sqlite3ReleaseTempReg(pParse, regFree2); 6633 } 6634 6635 /* 6636 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before 6637 ** code generation, and that copy is deleted after code generation. This 6638 ** ensures that the original pExpr is unchanged. 6639 */ 6640 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ 6641 sqlite3 *db = pParse->db; 6642 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); 6643 if( db->mallocFailed==0 ){ 6644 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); 6645 } 6646 sqlite3ExprDelete(db, pCopy); 6647 } 6648 6649 /* 6650 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any 6651 ** type of expression. 6652 ** 6653 ** If pExpr is a simple SQL value - an integer, real, string, blob 6654 ** or NULL value - then the VDBE currently being prepared is configured 6655 ** to re-prepare each time a new value is bound to variable pVar. 6656 ** 6657 ** Additionally, if pExpr is a simple SQL value and the value is the 6658 ** same as that currently bound to variable pVar, non-zero is returned. 6659 ** Otherwise, if the values are not the same or if pExpr is not a simple 6660 ** SQL value, zero is returned. 6661 ** 6662 ** If the SQLITE_EnableQPSG flag is set on the database connection, then 6663 ** this routine always returns false. 6664 */ 6665 static SQLITE_NOINLINE int exprCompareVariable( 6666 const Parse *pParse, 6667 const Expr *pVar, 6668 const Expr *pExpr 6669 ){ 6670 int res = 2; 6671 int iVar; 6672 sqlite3_value *pL, *pR = 0; 6673 6674 if( pExpr->op==TK_VARIABLE && pVar->iColumn==pExpr->iColumn ){ 6675 return 0; 6676 } 6677 if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) return 2; 6678 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR); 6679 if( pR ){ 6680 iVar = pVar->iColumn; 6681 sqlite3VdbeReprepareOnBind(pParse->pVdbe, iVar, 0); 6682 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB); 6683 if( pL ){ 6684 if( sqlite3_value_type(pL)==SQLITE_TEXT ){ 6685 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */ 6686 } 6687 res = sqlite3MemCompare(pL, pR, 0) ? 2 : 0; 6688 } 6689 sqlite3ValueFree(pR); 6690 sqlite3ValueFree(pL); 6691 } 6692 return res; 6693 } 6694 6695 /* 6696 ** Do a deep comparison of two expression trees. Return 0 if the two 6697 ** expressions are completely identical. Return 1 if they differ only 6698 ** by a COLLATE operator at the top level. Return 2 if there are differences 6699 ** other than the top-level COLLATE operator. 6700 ** 6701 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 6702 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 6703 ** 6704 ** The pA side might be using TK_REGISTER. If that is the case and pB is 6705 ** not using TK_REGISTER but is otherwise equivalent, then still return 0. 6706 ** 6707 ** Sometimes this routine will return 2 even if the two expressions 6708 ** really are equivalent. If we cannot prove that the expressions are 6709 ** identical, we return 2 just to be safe. So if this routine 6710 ** returns 2, then you do not really know for certain if the two 6711 ** expressions are the same. But if you get a 0 or 1 return, then you 6712 ** can be sure the expressions are the same. In the places where 6713 ** this routine is used, it does not hurt to get an extra 2 - that 6714 ** just might result in some slightly slower code. But returning 6715 ** an incorrect 0 or 1 could lead to a malfunction. 6716 ** 6717 ** If pParse is not NULL and SQLITE_EnableQPSG is off then TK_VARIABLE 6718 ** terms in pA with bindings in pParse->pReprepare can be matched against 6719 ** literals in pB. The pParse->pVdbe->expmask bitmask is updated for 6720 ** each variable referenced. 6721 */ 6722 int sqlite3ExprCompare( 6723 const Parse *pParse, 6724 const Expr *pA, 6725 const Expr *pB, 6726 int iTab 6727 ){ 6728 u32 combinedFlags; 6729 if( pA==0 || pB==0 ){ 6730 return pB==pA ? 0 : 2; 6731 } 6732 if( pParse && pA->op==TK_VARIABLE ){ 6733 return exprCompareVariable(pParse, pA, pB); 6734 } 6735 combinedFlags = pA->flags | pB->flags; 6736 if( combinedFlags & EP_IntValue ){ 6737 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ 6738 return 0; 6739 } 6740 return 2; 6741 } 6742 if( pA->op!=pB->op || pA->op==TK_RAISE ){ 6743 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){ 6744 return 1; 6745 } 6746 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){ 6747 return 1; 6748 } 6749 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN 6750 && pB->iTable<0 && pA->iTable==iTab 6751 ){ 6752 /* fall through */ 6753 }else{ 6754 return 2; 6755 } 6756 } 6757 assert( !ExprHasProperty(pA, EP_IntValue) ); 6758 assert( !ExprHasProperty(pB, EP_IntValue) ); 6759 if( pA->u.zToken ){ 6760 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){ 6761 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 6762 #ifndef SQLITE_OMIT_WINDOWFUNC 6763 assert( pA->op==pB->op ); 6764 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){ 6765 return 2; 6766 } 6767 if( ExprHasProperty(pA,EP_WinFunc) ){ 6768 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){ 6769 return 2; 6770 } 6771 } 6772 #endif 6773 }else if( pA->op==TK_NULL ){ 6774 return 0; 6775 }else if( pA->op==TK_COLLATE ){ 6776 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 6777 }else 6778 if( pB->u.zToken!=0 6779 && pA->op!=TK_COLUMN 6780 && pA->op!=TK_AGG_COLUMN 6781 && strcmp(pA->u.zToken,pB->u.zToken)!=0 6782 ){ 6783 return 2; 6784 } 6785 } 6786 if( (pA->flags & (EP_Distinct|EP_Commuted)) 6787 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2; 6788 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ 6789 if( combinedFlags & EP_xIsSelect ) return 2; 6790 if( (combinedFlags & EP_FixedCol)==0 6791 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2; 6792 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2; 6793 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; 6794 if( pA->op!=TK_STRING 6795 && pA->op!=TK_TRUEFALSE 6796 && ALWAYS((combinedFlags & EP_Reduced)==0) 6797 ){ 6798 if( pA->iColumn!=pB->iColumn ) return 2; 6799 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2; 6800 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){ 6801 return 2; 6802 } 6803 } 6804 } 6805 return 0; 6806 } 6807 6808 /* 6809 ** Compare two ExprList objects. Return 0 if they are identical, 1 6810 ** if they are certainly different, or 2 if it is not possible to 6811 ** determine if they are identical or not. 6812 ** 6813 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 6814 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 6815 ** 6816 ** This routine might return non-zero for equivalent ExprLists. The 6817 ** only consequence will be disabled optimizations. But this routine 6818 ** must never return 0 if the two ExprList objects are different, or 6819 ** a malfunction will result. 6820 ** 6821 ** Two NULL pointers are considered to be the same. But a NULL pointer 6822 ** always differs from a non-NULL pointer. 6823 */ 6824 int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){ 6825 int i; 6826 if( pA==0 && pB==0 ) return 0; 6827 if( pA==0 || pB==0 ) return 1; 6828 if( pA->nExpr!=pB->nExpr ) return 1; 6829 for(i=0; inExpr; i++){ 6830 int res; 6831 Expr *pExprA = pA->a[i].pExpr; 6832 Expr *pExprB = pB->a[i].pExpr; 6833 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1; 6834 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res; 6835 } 6836 return 0; 6837 } 6838 6839 /* 6840 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level 6841 ** are ignored. 6842 */ 6843 int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){ 6844 return sqlite3ExprCompare(0, 6845 sqlite3ExprSkipCollate(pA), 6846 sqlite3ExprSkipCollate(pB), 6847 iTab); 6848 } 6849 6850 /* 6851 ** Return non-zero if Expr p can only be true if pNN is not NULL. 6852 ** 6853 ** Or if seenNot is true, return non-zero if Expr p can only be 6854 ** non-NULL if pNN is not NULL 6855 */ 6856 static int exprImpliesNotNull( 6857 const Parse *pParse,/* Parsing context */ 6858 const Expr *p, /* The expression to be checked */ 6859 const Expr *pNN, /* The expression that is NOT NULL */ 6860 int iTab, /* Table being evaluated */ 6861 int seenNot /* Return true only if p can be any non-NULL value */ 6862 ){ 6863 assert( p ); 6864 assert( pNN ); 6865 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){ 6866 return pNN->op!=TK_NULL; 6867 } 6868 switch( p->op ){ 6869 case TK_IN: { 6870 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0; 6871 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) ); 6872 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 6873 } 6874 case TK_BETWEEN: { 6875 ExprList *pList; 6876 assert( ExprUseXList(p) ); 6877 pList = p->x.pList; 6878 assert( pList!=0 ); 6879 assert( pList->nExpr==2 ); 6880 if( seenNot ) return 0; 6881 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1) 6882 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1) 6883 ){ 6884 return 1; 6885 } 6886 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 6887 } 6888 case TK_EQ: 6889 case TK_NE: 6890 case TK_LT: 6891 case TK_LE: 6892 case TK_GT: 6893 case TK_GE: 6894 case TK_PLUS: 6895 case TK_MINUS: 6896 case TK_BITOR: 6897 case TK_LSHIFT: 6898 case TK_RSHIFT: 6899 case TK_CONCAT: 6900 seenNot = 1; 6901 /* no break */ deliberate_fall_through 6902 case TK_STAR: 6903 case TK_REM: 6904 case TK_BITAND: 6905 case TK_SLASH: { 6906 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1; 6907 /* no break */ deliberate_fall_through 6908 } 6909 case TK_SPAN: 6910 case TK_COLLATE: 6911 case TK_UPLUS: 6912 case TK_UMINUS: { 6913 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); 6914 } 6915 case TK_TRUTH: { 6916 if( seenNot ) return 0; 6917 if( p->op2!=TK_IS ) return 0; 6918 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 6919 } 6920 case TK_BITNOT: 6921 case TK_NOT: { 6922 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 6923 } 6924 } 6925 return 0; 6926 } 6927 6928 /* 6929 ** Return true if the boolean value of the expression is always either 6930 ** FALSE or NULL. 6931 */ 6932 static int sqlite3ExprIsNotTrue(Expr *pExpr){ 6933 int v; 6934 if( pExpr->op==TK_NULL ) return 1; 6935 if( pExpr->op==TK_TRUEFALSE && sqlite3ExprTruthValue(pExpr)==0 ) return 1; 6936 v = 1; 6937 if( sqlite3ExprIsInteger(pExpr, &v, 0, 0) && v==0 ) return 1; 6938 return 0; 6939 } 6940 6941 /* 6942 ** Return true if the expression is one of the following: 6943 ** 6944 ** CASE WHEN x THEN y END 6945 ** CASE WHEN x THEN y ELSE NULL END 6946 ** CASE WHEN x THEN y ELSE false END 6947 ** iif(x,y) 6948 ** iif(x,y,NULL) 6949 ** iif(x,y,false) 6950 */ 6951 static int sqlite3ExprIsIIF(sqlite3 *db, const Expr *pExpr){ 6952 ExprList *pList; 6953 if( pExpr->op==TK_FUNCTION ){ 6954 const char *z = pExpr->u.zToken; 6955 FuncDef *pDef; 6956 if( (z[0]!='i' && z[0]!='I') ) return 0; 6957 if( pExpr->x.pList==0 ) return 0; 6958 pDef = sqlite3FindFunction(db, z, pExpr->x.pList->nExpr, ENC(db), 0); 6959 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 6960 if( pDef==0 ) return 0; 6961 #else 6962 if( NEVER(pDef==0) ) return 0; 6963 #endif 6964 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)==0 ) return 0; 6965 if( SQLITE_PTR_TO_INT(pDef->pUserData)!=INLINEFUNC_iif ) return 0; 6966 }else if( pExpr->op==TK_CASE ){ 6967 if( pExpr->pLeft!=0 ) return 0; 6968 }else{ 6969 return 0; 6970 } 6971 pList = pExpr->x.pList; 6972 assert( pList!=0 ); 6973 if( pList->nExpr==2 ) return 1; 6974 if( pList->nExpr==3 && sqlite3ExprIsNotTrue(pList->a[2].pExpr) ) return 1; 6975 return 0; 6976 } 6977 6978 /* 6979 ** Return true if we can prove the pE2 will always be true if pE1 is 6980 ** true. Return false if we cannot complete the proof or if pE2 might 6981 ** be false. Examples: 6982 ** 6983 ** pE1: x==5 pE2: x==5 Result: true 6984 ** pE1: x>0 pE2: x==5 Result: false 6985 ** pE1: x=21 pE2: x=21 OR y=43 Result: true 6986 ** pE1: x!=123 pE2: x IS NOT NULL Result: true 6987 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true 6988 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false 6989 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false 6990 ** pE1: iif(x,y) pE2: x Result: true 6991 ** PE1: iif(x,y,0) pE2: x Result: true 6992 ** 6993 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has 6994 ** Expr.iTable<0 then assume a table number given by iTab. 6995 ** 6996 ** If pParse is not NULL, then the values of bound variables in pE1 are 6997 ** compared against literal values in pE2 and pParse->pVdbe->expmask is 6998 ** modified to record which bound variables are referenced. If pParse 6999 ** is NULL, then false will be returned if pE1 contains any bound variables. 7000 ** 7001 ** When in doubt, return false. Returning true might give a performance 7002 ** improvement. Returning false might cause a performance reduction, but 7003 ** it will always give the correct answer and is hence always safe. 7004 */ 7005 int sqlite3ExprImpliesExpr( 7006 const Parse *pParse, 7007 const Expr *pE1, 7008 const Expr *pE2, 7009 int iTab 7010 ){ 7011 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){ 7012 return 1; 7013 } 7014 if( pE2->op==TK_OR 7015 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab) 7016 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) ) 7017 ){ 7018 return 1; 7019 } 7020 if( pE2->op==TK_NOTNULL 7021 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0) 7022 ){ 7023 return 1; 7024 } 7025 if( sqlite3ExprIsIIF(pParse->db, pE1) ){ 7026 return sqlite3ExprImpliesExpr(pParse,pE1->x.pList->a[0].pExpr,pE2,iTab); 7027 } 7028 return 0; 7029 } 7030 7031 /* This is a helper function to impliesNotNullRow(). In this routine, 7032 ** set pWalker->eCode to one only if *both* of the input expressions 7033 ** separately have the implies-not-null-row property. 7034 */ 7035 static void bothImplyNotNullRow(Walker *pWalker, Expr *pE1, Expr *pE2){ 7036 if( pWalker->eCode==0 ){ 7037 sqlite3WalkExpr(pWalker, pE1); 7038 if( pWalker->eCode ){ 7039 pWalker->eCode = 0; 7040 sqlite3WalkExpr(pWalker, pE2); 7041 } 7042 } 7043 } 7044 7045 /* 7046 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow(). 7047 ** If the expression node requires that the table at pWalker->iCur 7048 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort. 7049 ** 7050 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on 7051 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when 7052 ** evaluating terms in the ON clause of an inner join. 7053 ** 7054 ** This routine controls an optimization. False positives (setting 7055 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives 7056 ** (never setting pWalker->eCode) is a harmless missed optimization. 7057 */ 7058 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){ 7059 testcase( pExpr->op==TK_AGG_COLUMN ); 7060 testcase( pExpr->op==TK_AGG_FUNCTION ); 7061 if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune; 7062 if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){ 7063 /* If iCur is used in an inner-join ON clause to the left of a 7064 ** RIGHT JOIN, that does *not* mean that the table must be non-null. 7065 ** But it is difficult to check for that condition precisely. 7066 ** To keep things simple, any use of iCur from any inner-join is 7067 ** ignored while attempting to simplify a RIGHT JOIN. */ 7068 return WRC_Prune; 7069 } 7070 switch( pExpr->op ){ 7071 case TK_ISNOT: 7072 case TK_ISNULL: 7073 case TK_NOTNULL: 7074 case TK_IS: 7075 case TK_VECTOR: 7076 case TK_FUNCTION: 7077 case TK_TRUTH: 7078 case TK_CASE: 7079 testcase( pExpr->op==TK_ISNOT ); 7080 testcase( pExpr->op==TK_ISNULL ); 7081 testcase( pExpr->op==TK_NOTNULL ); 7082 testcase( pExpr->op==TK_IS ); 7083 testcase( pExpr->op==TK_VECTOR ); 7084 testcase( pExpr->op==TK_FUNCTION ); 7085 testcase( pExpr->op==TK_TRUTH ); 7086 testcase( pExpr->op==TK_CASE ); 7087 return WRC_Prune; 7088 7089 case TK_COLUMN: 7090 if( pWalker->u.iCur==pExpr->iTable ){ 7091 pWalker->eCode = 1; 7092 return WRC_Abort; 7093 } 7094 return WRC_Prune; 7095 7096 case TK_OR: 7097 case TK_AND: 7098 /* Both sides of an AND or OR must separately imply non-null-row. 7099 ** Consider these cases: 7100 ** 1. NOT (x AND y) 7101 ** 2. x OR y 7102 ** If only one of x or y is non-null-row, then the overall expression 7103 ** can be true if the other arm is false (case 1) or true (case 2). 7104 */ 7105 testcase( pExpr->op==TK_OR ); 7106 testcase( pExpr->op==TK_AND ); 7107 bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight); 7108 return WRC_Prune; 7109 7110 case TK_IN: 7111 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)", 7112 ** both of which can be true. But apart from these cases, if 7113 ** the left-hand side of the IN is NULL then the IN itself will be 7114 ** NULL. */ 7115 if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){ 7116 sqlite3WalkExpr(pWalker, pExpr->pLeft); 7117 } 7118 return WRC_Prune; 7119 7120 case TK_BETWEEN: 7121 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else 7122 ** both y and z must be non-null row */ 7123 assert( ExprUseXList(pExpr) ); 7124 assert( pExpr->x.pList->nExpr==2 ); 7125 sqlite3WalkExpr(pWalker, pExpr->pLeft); 7126 bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr, 7127 pExpr->x.pList->a[1].pExpr); 7128 return WRC_Prune; 7129 7130 /* Virtual tables are allowed to use constraints like x=NULL. So 7131 ** a term of the form x=y does not prove that y is not null if x 7132 ** is the column of a virtual table */ 7133 case TK_EQ: 7134 case TK_NE: 7135 case TK_LT: 7136 case TK_LE: 7137 case TK_GT: 7138 case TK_GE: { 7139 Expr *pLeft = pExpr->pLeft; 7140 Expr *pRight = pExpr->pRight; 7141 testcase( pExpr->op==TK_EQ ); 7142 testcase( pExpr->op==TK_NE ); 7143 testcase( pExpr->op==TK_LT ); 7144 testcase( pExpr->op==TK_LE ); 7145 testcase( pExpr->op==TK_GT ); 7146 testcase( pExpr->op==TK_GE ); 7147 /* The y.pTab=0 assignment in wherecode.c always happens after the 7148 ** impliesNotNullRow() test */ 7149 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) ); 7150 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) ); 7151 if( (pLeft->op==TK_COLUMN 7152 && ALWAYS(pLeft->y.pTab!=0) 7153 && IsVirtual(pLeft->y.pTab)) 7154 || (pRight->op==TK_COLUMN 7155 && ALWAYS(pRight->y.pTab!=0) 7156 && IsVirtual(pRight->y.pTab)) 7157 ){ 7158 return WRC_Prune; 7159 } 7160 /* no break */ deliberate_fall_through 7161 } 7162 default: 7163 return WRC_Continue; 7164 } 7165 } 7166 7167 /* 7168 ** Return true (non-zero) if expression p can only be true if at least 7169 ** one column of table iTab is non-null. In other words, return true 7170 ** if expression p will always be NULL or false if every column of iTab 7171 ** is NULL. 7172 ** 7173 ** False negatives are acceptable. In other words, it is ok to return 7174 ** zero even if expression p will never be true of every column of iTab 7175 ** is NULL. A false negative is merely a missed optimization opportunity. 7176 ** 7177 ** False positives are not allowed, however. A false positive may result 7178 ** in an incorrect answer. 7179 ** 7180 ** Terms of p that are marked with EP_OuterON (and hence that come from 7181 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis. 7182 ** 7183 ** This routine is used to check if a LEFT JOIN can be converted into 7184 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE 7185 ** clause requires that some column of the right table of the LEFT JOIN 7186 ** be non-NULL, then the LEFT JOIN can be safely converted into an 7187 ** ordinary join. 7188 */ 7189 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab, int isRJ){ 7190 Walker w; 7191 p = sqlite3ExprSkipCollateAndLikely(p); 7192 if( p==0 ) return 0; 7193 if( p->op==TK_NOTNULL ){ 7194 p = p->pLeft; 7195 }else{ 7196 while( p->op==TK_AND ){ 7197 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1; 7198 p = p->pRight; 7199 } 7200 } 7201 w.xExprCallback = impliesNotNullRow; 7202 w.xSelectCallback = 0; 7203 w.xSelectCallback2 = 0; 7204 w.eCode = 0; 7205 w.mWFlags = isRJ!=0; 7206 w.u.iCur = iTab; 7207 sqlite3WalkExpr(&w, p); 7208 return w.eCode; 7209 } 7210 7211 /* 7212 ** An instance of the following structure is used by the tree walker 7213 ** to determine if an expression can be evaluated by reference to the 7214 ** index only, without having to do a search for the corresponding 7215 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur 7216 ** is the cursor for the table. 7217 */ 7218 struct IdxCover { 7219 Index *pIdx; /* The index to be tested for coverage */ 7220 int iCur; /* Cursor number for the table corresponding to the index */ 7221 }; 7222 7223 /* 7224 ** Check to see if there are references to columns in table 7225 ** pWalker->u.pIdxCover->iCur can be satisfied using the index 7226 ** pWalker->u.pIdxCover->pIdx. 7227 */ 7228 static int exprIdxCover(Walker *pWalker, Expr *pExpr){ 7229 if( pExpr->op==TK_COLUMN 7230 && pExpr->iTable==pWalker->u.pIdxCover->iCur 7231 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 7232 ){ 7233 pWalker->eCode = 1; 7234 return WRC_Abort; 7235 } 7236 return WRC_Continue; 7237 } 7238 7239 /* 7240 ** Determine if an index pIdx on table with cursor iCur contains will 7241 ** the expression pExpr. Return true if the index does cover the 7242 ** expression and false if the pExpr expression references table columns 7243 ** that are not found in the index pIdx. 7244 ** 7245 ** An index covering an expression means that the expression can be 7246 ** evaluated using only the index and without having to lookup the 7247 ** corresponding table entry. 7248 */ 7249 int sqlite3ExprCoveredByIndex( 7250 Expr *pExpr, /* The index to be tested */ 7251 int iCur, /* The cursor number for the corresponding table */ 7252 Index *pIdx /* The index that might be used for coverage */ 7253 ){ 7254 Walker w; 7255 struct IdxCover xcov; 7256 memset(&w, 0, sizeof(w)); 7257 xcov.iCur = iCur; 7258 xcov.pIdx = pIdx; 7259 w.xExprCallback = exprIdxCover; 7260 w.u.pIdxCover = &xcov; 7261 sqlite3WalkExpr(&w, pExpr); 7262 return !w.eCode; 7263 } 7264 7265 7266 /* Structure used to pass information throughout the Walker in order to 7267 ** implement sqlite3ReferencesSrcList(). 7268 */ 7269 struct RefSrcList { 7270 sqlite3 *db; /* Database connection used for sqlite3DbRealloc() */ 7271 SrcList *pRef; /* Looking for references to these tables */ 7272 i64 nExclude; /* Number of tables to exclude from the search */ 7273 int *aiExclude; /* Cursor IDs for tables to exclude from the search */ 7274 }; 7275 7276 /* 7277 ** Walker SELECT callbacks for sqlite3ReferencesSrcList(). 7278 ** 7279 ** When entering a new subquery on the pExpr argument, add all FROM clause 7280 ** entries for that subquery to the exclude list. 7281 ** 7282 ** When leaving the subquery, remove those entries from the exclude list. 7283 */ 7284 static int selectRefEnter(Walker *pWalker, Select *pSelect){ 7285 struct RefSrcList *p = pWalker->u.pRefSrcList; 7286 SrcList *pSrc = pSelect->pSrc; 7287 i64 i, j; 7288 int *piNew; 7289 if( pSrc->nSrc==0 ) return WRC_Continue; 7290 j = p->nExclude; 7291 p->nExclude += pSrc->nSrc; 7292 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int)); 7293 if( piNew==0 ){ 7294 p->nExclude = 0; 7295 return WRC_Abort; 7296 }else{ 7297 p->aiExclude = piNew; 7298 } 7299 for(i=0; inSrc; i++, j++){ 7300 p->aiExclude[j] = pSrc->a[i].iCursor; 7301 } 7302 return WRC_Continue; 7303 } 7304 static void selectRefLeave(Walker *pWalker, Select *pSelect){ 7305 struct RefSrcList *p = pWalker->u.pRefSrcList; 7306 SrcList *pSrc = pSelect->pSrc; 7307 if( p->nExclude ){ 7308 assert( p->nExclude>=pSrc->nSrc ); 7309 p->nExclude -= pSrc->nSrc; 7310 } 7311 } 7312 7313 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList(). 7314 ** 7315 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any 7316 ** of the tables shown in RefSrcList.pRef. 7317 ** 7318 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a 7319 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude. 7320 */ 7321 static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){ 7322 if( pExpr->op==TK_COLUMN 7323 || pExpr->op==TK_AGG_COLUMN 7324 ){ 7325 int i; 7326 struct RefSrcList *p = pWalker->u.pRefSrcList; 7327 SrcList *pSrc = p->pRef; 7328 int nSrc = pSrc ? pSrc->nSrc : 0; 7329 for(i=0; iiTable==pSrc->a[i].iCursor ){ 7331 pWalker->eCode |= 1; 7332 return WRC_Continue; 7333 } 7334 } 7335 for(i=0; inExclude && p->aiExclude[i]!=pExpr->iTable; i++){} 7336 if( i>=p->nExclude ){ 7337 pWalker->eCode |= 2; 7338 } 7339 } 7340 return WRC_Continue; 7341 } 7342 7343 /* 7344 ** Check to see if pExpr references any tables in pSrcList. 7345 ** Possible return values: 7346 ** 7347 ** 1 pExpr does references a table in pSrcList. 7348 ** 7349 ** 0 pExpr references some table that is not defined in either 7350 ** pSrcList or in subqueries of pExpr itself. 7351 ** 7352 ** -1 pExpr only references no tables at all, or it only 7353 ** references tables defined in subqueries of pExpr itself. 7354 ** 7355 ** As currently used, pExpr is always an aggregate function call. That 7356 ** fact is exploited for efficiency. 7357 */ 7358 int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){ 7359 Walker w; 7360 struct RefSrcList x; 7361 assert( pParse->db!=0 ); 7362 memset(&w, 0, sizeof(w)); 7363 memset(&x, 0, sizeof(x)); 7364 w.xExprCallback = exprRefToSrcList; 7365 w.xSelectCallback = selectRefEnter; 7366 w.xSelectCallback2 = selectRefLeave; 7367 w.u.pRefSrcList = &x; 7368 x.db = pParse->db; 7369 x.pRef = pSrcList; 7370 assert( pExpr->op==TK_AGG_FUNCTION ); 7371 assert( ExprUseXList(pExpr) ); 7372 sqlite3WalkExprList(&w, pExpr->x.pList); 7373 if( pExpr->pLeft ){ 7374 assert( pExpr->pLeft->op==TK_ORDER ); 7375 assert( ExprUseXList(pExpr->pLeft) ); 7376 assert( pExpr->pLeft->x.pList!=0 ); 7377 sqlite3WalkExprList(&w, pExpr->pLeft->x.pList); 7378 } 7379 #ifndef SQLITE_OMIT_WINDOWFUNC 7380 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 7381 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter); 7382 } 7383 #endif 7384 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude); 7385 if( w.eCode & 0x01 ){ 7386 return 1; 7387 }else if( w.eCode ){ 7388 return 0; 7389 }else{ 7390 return -1; 7391 } 7392 } 7393 7394 /* 7395 ** This is a Walker expression node callback. 7396 ** 7397 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo 7398 ** object that is referenced does not refer directly to the Expr. If 7399 ** it does, make a copy. This is done because the pExpr argument is 7400 ** subject to change. 7401 ** 7402 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete() 7403 ** which builds on the sqlite3ParserAddCleanup() mechanism. 7404 */ 7405 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){ 7406 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced)) 7407 && pExpr->pAggInfo!=0 7408 ){ 7409 AggInfo *pAggInfo = pExpr->pAggInfo; 7410 int iAgg = pExpr->iAgg; 7411 Parse *pParse = pWalker->pParse; 7412 sqlite3 *db = pParse->db; 7413 assert( iAgg>=0 ); 7414 if( pExpr->op!=TK_AGG_FUNCTION ){ 7415 if( iAggnColumn 7416 && pAggInfo->aCol[iAgg].pCExpr==pExpr 7417 ){ 7418 pExpr = sqlite3ExprDup(db, pExpr, 0); 7419 if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){ 7420 pAggInfo->aCol[iAgg].pCExpr = pExpr; 7421 } 7422 } 7423 }else{ 7424 assert( pExpr->op==TK_AGG_FUNCTION ); 7425 if( ALWAYS(iAggnFunc) 7426 && pAggInfo->aFunc[iAgg].pFExpr==pExpr 7427 ){ 7428 pExpr = sqlite3ExprDup(db, pExpr, 0); 7429 if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){ 7430 pAggInfo->aFunc[iAgg].pFExpr = pExpr; 7431 } 7432 } 7433 } 7434 } 7435 return WRC_Continue; 7436 } 7437 7438 /* 7439 ** Initialize a Walker object so that will persist AggInfo entries referenced 7440 ** by the tree that is walked. 7441 */ 7442 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){ 7443 memset(pWalker, 0, sizeof(*pWalker)); 7444 pWalker->pParse = pParse; 7445 pWalker->xExprCallback = agginfoPersistExprCb; 7446 pWalker->xSelectCallback = sqlite3SelectWalkNoop; 7447 } 7448 7449 /* 7450 ** Add a new element to the pAggInfo->aCol[] array. Return the index of 7451 ** the new element. Return a negative number if malloc fails. 7452 */ 7453 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ 7454 int i; 7455 pInfo->aCol = sqlite3ArrayAllocate( 7456 db, 7457 pInfo->aCol, 7458 sizeof(pInfo->aCol[0]), 7459 &pInfo->nColumn, 7460 &i 7461 ); 7462 return i; 7463 } 7464 7465 /* 7466 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of 7467 ** the new element. Return a negative number if malloc fails. 7468 */ 7469 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ 7470 int i; 7471 pInfo->aFunc = sqlite3ArrayAllocate( 7472 db, 7473 pInfo->aFunc, 7474 sizeof(pInfo->aFunc[0]), 7475 &pInfo->nFunc, 7476 &i 7477 ); 7478 return i; 7479 } 7480 7481 /* 7482 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn. 7483 ** Return the index in aCol[] of the entry that describes that column. 7484 ** 7485 ** If no prior entry is found, create a new one and return -1. The 7486 ** new column will have an index of pAggInfo->nColumn-1. 7487 */ 7488 static void findOrCreateAggInfoColumn( 7489 Parse *pParse, /* Parsing context */ 7490 AggInfo *pAggInfo, /* The AggInfo object to search and/or modify */ 7491 Expr *pExpr /* Expr describing the column to find or insert */ 7492 ){ 7493 struct AggInfo_col *pCol; 7494 int k; 7495 int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; 7496 7497 assert( mxTerm <= SMXV(i16) ); 7498 assert( pAggInfo->iFirstReg==0 ); 7499 pCol = pAggInfo->aCol; 7500 for(k=0; knColumn; k++, pCol++){ 7501 if( pCol->pCExpr==pExpr ) return; 7502 if( pCol->iTable==pExpr->iTable 7503 && pCol->iColumn==pExpr->iColumn 7504 && pExpr->op!=TK_IF_NULL_ROW 7505 ){ 7506 goto fix_up_expr; 7507 } 7508 } 7509 k = addAggInfoColumn(pParse->db, pAggInfo); 7510 if( k<0 ){ 7511 /* OOM on resize */ 7512 assert( pParse->db->mallocFailed ); 7513 return; 7514 } 7515 if( k>mxTerm ){ 7516 sqlite3ErrorMsg(pParse, "more than %d aggregate terms", mxTerm); 7517 k = mxTerm; 7518 } 7519 pCol = &pAggInfo->aCol[k]; 7520 assert( ExprUseYTab(pExpr) ); 7521 pCol->pTab = pExpr->y.pTab; 7522 pCol->iTable = pExpr->iTable; 7523 pCol->iColumn = pExpr->iColumn; 7524 pCol->iSorterColumn = -1; 7525 pCol->pCExpr = pExpr; 7526 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){ 7527 int j, n; 7528 ExprList *pGB = pAggInfo->pGroupBy; 7529 struct ExprList_item *pTerm = pGB->a; 7530 n = pGB->nExpr; 7531 for(j=0; jpExpr; 7533 if( pE->op==TK_COLUMN 7534 && pE->iTable==pExpr->iTable 7535 && pE->iColumn==pExpr->iColumn 7536 ){ 7537 pCol->iSorterColumn = j; 7538 break; 7539 } 7540 } 7541 } 7542 if( pCol->iSorterColumn<0 ){ 7543 pCol->iSorterColumn = pAggInfo->nSortingColumn++; 7544 } 7545 fix_up_expr: 7546 ExprSetVVAProperty(pExpr, EP_NoReduce); 7547 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo ); 7548 pExpr->pAggInfo = pAggInfo; 7549 if( pExpr->op==TK_COLUMN ){ 7550 pExpr->op = TK_AGG_COLUMN; 7551 } 7552 assert( k <= SMXV(pExpr->iAgg) ); 7553 pExpr->iAgg = (i16)k; 7554 } 7555 7556 /* 7557 ** This is the xExprCallback for a tree walker. It is used to 7558 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates 7559 ** for additional information. 7560 */ 7561 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ 7562 int i; 7563 NameContext *pNC = pWalker->u.pNC; 7564 Parse *pParse = pNC->pParse; 7565 SrcList *pSrcList = pNC->pSrcList; 7566 AggInfo *pAggInfo = pNC->uNC.pAggInfo; 7567 7568 assert( pNC->ncFlags & NC_UAggInfo ); 7569 assert( pAggInfo->iFirstReg==0 ); 7570 switch( pExpr->op ){ 7571 default: { 7572 IndexedExpr *pIEpr; 7573 Expr tmp; 7574 assert( pParse->iSelfTab==0 ); 7575 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break; 7576 if( pParse->pIdxEpr==0 ) break; 7577 if( pWalker->walkerDepth>0 ){ 7578 break; /* See bug report 2026-11-07T18:33:11Z */ 7579 } 7580 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){ 7581 int iDataCur = pIEpr->iDataCur; 7582 if( iDataCur<0 ) continue; 7583 /* If the index might be on the NULL row of an outer join, then the 7584 ** expression must not be replaced by a plain read of the index 7585 ** column, as the value of the expression on the NULL row is not 7586 ** necessarily NULL. In many cases (when the GROUP BY is not 7587 ** using temp b-tree to sort), sqlite3IndexedExprLookup() will make 7588 ** the same substitution later on anyway. */ 7589 if( pIEpr->bMaybeNullRow ) continue; 7590 if( indexedExprCompare(pIEpr, pExpr, iDataCur)==0 ) break; 7591 } 7592 if( pIEpr==0 ) break; 7593 if( NEVER(!ExprUseYTab(pExpr)) ) break; 7594 for(i=0; inSrc; i++){ 7595 if( pSrcList->a[i].iCursor==pIEpr->iDataCur ){ 7596 testcase( i>0 ); 7597 break; 7598 } 7599 } 7600 if( i>=pSrcList->nSrc ) break; 7601 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */ 7602 if( ExprHasProperty(pExpr, EP_SubtArg) 7603 && sqlite3ExprCanReturnSubtype(pParse, pExpr) 7604 ){ 7605 break; 7606 } 7607 if( pParse->nErr ){ return WRC_Abort; } 7608 7609 /* If we reach this point, it means that expression pExpr can be 7610 ** translated into a reference to an index column as described by 7611 ** pIEpr. 7612 */ 7613 memset(&tmp, 0, sizeof(tmp)); 7614 tmp.op = TK_AGG_COLUMN; 7615 tmp.iTable = pIEpr->iIdxCur; 7616 tmp.iColumn = pIEpr->iIdxCol; 7617 findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp); 7618 if( pParse->nErr ){ return WRC_Abort; } 7619 assert( pAggInfo->aCol!=0 ); 7620 assert( tmp.iAggnColumn ); 7621 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr; 7622 pExpr->pAggInfo = pAggInfo; 7623 pExpr->iAgg = tmp.iAgg; 7624 return WRC_Prune; 7625 } 7626 case TK_IF_NULL_ROW: 7627 case TK_AGG_COLUMN: 7628 case TK_COLUMN: { 7629 testcase( pExpr->op==TK_AGG_COLUMN ); 7630 testcase( pExpr->op==TK_COLUMN ); 7631 testcase( pExpr->op==TK_IF_NULL_ROW ); 7632 /* Check to see if the column is in one of the tables in the FROM 7633 ** clause of the aggregate query */ 7634 if( ALWAYS(pSrcList!=0) ){ 7635 SrcItem *pItem = pSrcList->a; 7636 for(i=0; inSrc; i++, pItem++){ 7637 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 7638 if( pExpr->iTable==pItem->iCursor ){ 7639 findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr); 7640 break; 7641 } /* endif pExpr->iTable==pItem->iCursor */ 7642 } /* end loop over pSrcList */ 7643 } 7644 return WRC_Continue; 7645 } 7646 case TK_AGG_FUNCTION: { 7647 if( (pNC->ncFlags & NC_InAggFunc)==0 7648 && pWalker->walkerDepth==pExpr->op2 7649 && pExpr->pAggInfo==0 7650 ){ 7651 /* Check to see if pExpr is a duplicate of another aggregate 7652 ** function that is already in the pAggInfo structure 7653 */ 7654 struct AggInfo_func *pItem = pAggInfo->aFunc; 7655 int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; 7656 assert( mxTerm <= SMXV(i16) ); 7657 for(i=0; inFunc; i++, pItem++){ 7658 if( NEVER(pItem->pFExpr==pExpr) ) break; 7659 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){ 7660 break; 7661 } 7662 } 7663 if( i>mxTerm ){ 7664 sqlite3ErrorMsg(pParse, "more than %d aggregate terms", mxTerm); 7665 i = mxTerm; 7666 assert( inFunc ); 7667 }else if( i>=pAggInfo->nFunc ){ 7668 /* pExpr is original. Make a new entry in pAggInfo->aFunc[] 7669 */ 7670 u8 enc = ENC(pParse->db); 7671 i = addAggInfoFunc(pParse->db, pAggInfo); 7672 if( i>=0 ){ 7673 int nArg; 7674 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 7675 pItem = &pAggInfo->aFunc[i]; 7676 pItem->pFExpr = pExpr; 7677 assert( ExprUseUToken(pExpr) ); 7678 nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0; 7679 pItem->pFunc = sqlite3FindFunction(pParse->db, 7680 pExpr->u.zToken, nArg, enc, 0); 7681 assert( pItem->bOBUnique==0 ); 7682 if( pExpr->pLeft 7683 && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0 7684 ){ 7685 /* The NEEDCOLL test above causes any ORDER BY clause on 7686 ** aggregate min() or max() to be ignored. */ 7687 ExprList *pOBList; 7688 assert( nArg>0 ); 7689 assert( pExpr->pLeft->op==TK_ORDER ); 7690 assert( ExprUseXList(pExpr->pLeft) ); 7691 pItem->iOBTab = pParse->nTab++; 7692 pOBList = pExpr->pLeft->x.pList; 7693 assert( pOBList->nExpr>0 ); 7694 assert( pItem->bOBUnique==0 ); 7695 if( pOBList->nExpr==1 7696 && nArg==1 7697 && sqlite3ExprCompare(0,pOBList->a[0].pExpr, 7698 pExpr->x.pList->a[0].pExpr,-1)==0 7699 ){ 7700 pItem->bOBPayload = 0; 7701 pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct); 7702 }else{ 7703 pItem->bOBPayload = 1; 7704 } 7705 pItem->bUseSubtype = 7706 (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0; 7707 }else{ 7708 pItem->iOBTab = -1; 7709 } 7710 if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){ 7711 pItem->iDistinct = pParse->nTab++; 7712 }else{ 7713 pItem->iDistinct = -1; 7714 } 7715 } 7716 } 7717 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry 7718 */ 7719 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 7720 ExprSetVVAProperty(pExpr, EP_NoReduce); 7721 assert( i <= SMXV(pExpr->iAgg) ); 7722 pExpr->iAgg = (i16)i; 7723 pExpr->pAggInfo = pAggInfo; 7724 return WRC_Prune; 7725 }else{ 7726 return WRC_Continue; 7727 } 7728 } 7729 } 7730 return WRC_Continue; 7731 } 7732 7733 /* 7734 ** Analyze the pExpr expression looking for aggregate functions and 7735 ** for variables that need to be added to AggInfo object that pNC->pAggInfo 7736 ** points to. Additional entries are made on the AggInfo object as 7737 ** necessary. 7738 ** 7739 ** This routine should only be called after the expression has been 7740 ** analyzed by sqlite3ResolveExprNames(). 7741 */ 7742 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ 7743 Walker w; 7744 w.xExprCallback = analyzeAggregate; 7745 w.xSelectCallback = sqlite3WalkerDepthIncrease; 7746 w.xSelectCallback2 = sqlite3WalkerDepthDecrease; 7747 w.walkerDepth = 0; 7748 w.u.pNC = pNC; 7749 w.pParse = 0; 7750 assert( pNC->pSrcList!=0 ); 7751 sqlite3WalkExpr(&w, pExpr); 7752 } 7753 7754 /* 7755 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an 7756 ** expression list. Return the number of errors. 7757 ** 7758 ** If an error is found, the analysis is cut short. 7759 */ 7760 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ 7761 struct ExprList_item *pItem; 7762 int i; 7763 if( pList ){ 7764 for(pItem=pList->a, i=0; inExpr; i++, pItem++){ 7765 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); 7766 } 7767 } 7768 } 7769 7770 /* 7771 ** Allocate a single new register for use to hold some intermediate result. 7772 */ 7773 int sqlite3GetTempReg(Parse *pParse){ 7774 if( pParse->nTempReg==0 ){ 7775 return ++pParse->nMem; 7776 } 7777 return pParse->aTempReg[--pParse->nTempReg]; 7778 } 7779 7780 /* 7781 ** Deallocate a register, making available for reuse for some other 7782 ** purpose. 7783 */ 7784 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ 7785 if( iReg ){ 7786 #ifdef SQLITE_DEBUG 7787 /* Verify that iReg is not already on the unused register list */ 7788 int kk; 7789 for(kk=0; kknTempReg; kk++){ 7790 assert( pParse->aTempReg[kk]!=iReg ); 7791 } 7792 #endif 7793 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0); 7794 if( pParse->nTempRegaTempReg) ){ 7795 pParse->aTempReg[pParse->nTempReg++] = iReg; 7796 } 7797 } 7798 } 7799 7800 /* 7801 ** Allocate or deallocate a block of nReg consecutive registers. 7802 */ 7803 int sqlite3GetTempRange(Parse *pParse, int nReg){ 7804 int i, n; 7805 if( nReg==1 ) return sqlite3GetTempReg(pParse); 7806 i = pParse->iRangeReg; 7807 n = pParse->nRangeReg; 7808 if( nReg<=n ){ 7809 pParse->iRangeReg += nReg; 7810 pParse->nRangeReg -= nReg; 7811 }else{ 7812 i = pParse->nMem+1; 7813 pParse->nMem += nReg; 7814 } 7815 return i; 7816 } 7817 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ 7818 if( nReg==1 ){ 7819 sqlite3ReleaseTempReg(pParse, iReg); 7820 return; 7821 } 7822 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0); 7823 if( nReg>pParse->nRangeReg ){ 7824 pParse->nRangeReg = nReg; 7825 pParse->iRangeReg = iReg; 7826 } 7827 } 7828 7829 /* 7830 ** Mark all temporary registers as being unavailable for reuse. 7831 ** 7832 ** Always invoke this procedure after coding a subroutine or co-routine 7833 ** that might be invoked from other parts of the code, to ensure that 7834 ** the sub/co-routine does not use registers in common with the code that 7835 ** invokes the sub/co-routine. 7836 */ 7837 void sqlite3ClearTempRegCache(Parse *pParse){ 7838 pParse->nTempReg = 0; 7839 pParse->nRangeReg = 0; 7840 } 7841 7842 /* 7843 ** Make sure sufficient registers have been allocated so that 7844 ** iReg is a valid register number. 7845 */ 7846 void sqlite3TouchRegister(Parse *pParse, int iReg){ 7847 if( pParse->nMemnMem = iReg; 7848 } 7849 7850 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG) 7851 /* 7852 ** Return the latest reusable register in the set of all registers. 7853 ** The value returned is no less than iMin. If any register iMin or 7854 ** greater is in permanent use, then return one more than that last 7855 ** permanent register. 7856 */ 7857 int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){ 7858 const ExprList *pList = pParse->pConstExpr; 7859 if( pList ){ 7860 int i; 7861 for(i=0; inExpr; i++){ 7862 if( pList->a[i].u.iConstExprReg>=iMin ){ 7863 iMin = pList->a[i].u.iConstExprReg + 1; 7864 } 7865 } 7866 } 7867 pParse->nTempReg = 0; 7868 pParse->nRangeReg = 0; 7869 return iMin; 7870 } 7871 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */ 7872 7873 /* 7874 ** Validate that no temporary register falls within the range of 7875 ** iFirst..iLast, inclusive. This routine is only call from within assert() 7876 ** statements. 7877 */ 7878 #ifdef SQLITE_DEBUG 7879 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ 7880 int i; 7881 if( pParse->nRangeReg>0 7882 && pParse->iRangeReg+pParse->nRangeReg > iFirst 7883 && pParse->iRangeReg <= iLast 7884 ){ 7885 return 0; 7886 } 7887 for(i=0; inTempReg; i++){ 7888 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){ 7889 return 0; 7890 } 7891 } 7892 if( pParse->pConstExpr ){ 7893 ExprList *pList = pParse->pConstExpr; 7894 for(i=0; inExpr; i++){ 7895 int iReg = pList->a[i].u.iConstExprReg; 7896 if( iReg==0 ) continue; 7897 if( iReg>=iFirst && iReg<=iLast ) return 0; 7898 } 7899 } 7900 return 1; 7901 } 7902 #endif /* SQLITE_DEBUG */