000001 /* 000002 ** 2001 September 15 000003 ** 000004 ** The author disclaims copyright to this source code. In place of 000005 ** a legal notice, here is a blessing: 000006 ** 000007 ** May you do good and not evil. 000008 ** May you find forgiveness for yourself and forgive others. 000009 ** May you share freely, never taking more than you give. 000010 ** 000011 ************************************************************************* 000012 ** This file contains routines used for analyzing expressions and 000013 ** for generating VDBE code that evaluates expressions in SQLite. 000014 */ 000015 #include "sqliteInt.h" 000016 000017 /* Forward declarations */ 000018 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int); 000019 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree); 000020 000021 /* 000022 ** Return the affinity character for a single column of a table. 000023 */ 000024 char sqlite3TableColumnAffinity(const Table *pTab, int iCol){ 000025 if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER; 000026 return pTab->aCol[iCol].affinity; 000027 } 000028 000029 /* 000030 ** Return the 'affinity' of the expression pExpr if any. 000031 ** 000032 ** If pExpr is a column, a reference to a column via an 'AS' alias, 000033 ** or a sub-select with a column as the return value, then the 000034 ** affinity of that column is returned. Otherwise, 0x00 is returned, 000035 ** indicating no affinity for the expression. 000036 ** 000037 ** i.e. the WHERE clause expressions in the following statements all 000038 ** have an affinity: 000039 ** 000040 ** CREATE TABLE t1(a); 000041 ** SELECT * FROM t1 WHERE a; 000042 ** SELECT a AS b FROM t1 WHERE b; 000043 ** SELECT * FROM t1 WHERE (select a from t1); 000044 */ 000045 char sqlite3ExprAffinity(const Expr *pExpr){ 000046 int op; 000047 op = pExpr->op; 000048 while( 1 /* exit-by-break */ ){ 000049 if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){ 000050 assert( ExprUseYTab(pExpr) ); 000051 assert( pExpr->y.pTab!=0 ); 000052 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 000053 } 000054 if( op==TK_SELECT ){ 000055 assert( ExprUseXSelect(pExpr) ); 000056 assert( pExpr->x.pSelect!=0 ); 000057 assert( pExpr->x.pSelect->pEList!=0 ); 000058 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 ); 000059 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr); 000060 } 000061 #ifndef SQLITE_OMIT_CAST 000062 if( op==TK_CAST ){ 000063 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 000064 return sqlite3AffinityType(pExpr->u.zToken, 0); 000065 } 000066 #endif 000067 if( op==TK_SELECT_COLUMN ){ 000068 assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) ); 000069 assert( pExpr->iColumn < pExpr->iTable ); 000070 assert( pExpr->iColumn >= 0 ); 000071 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr ); 000072 return sqlite3ExprAffinity( 000073 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr 000074 ); 000075 } 000076 if( op==TK_VECTOR ){ 000077 assert( ExprUseXList(pExpr) ); 000078 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr); 000079 } 000080 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){ 000081 assert( pExpr->op==TK_COLLATE 000082 || pExpr->op==TK_IF_NULL_ROW 000083 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) ); 000084 pExpr = pExpr->pLeft; 000085 op = pExpr->op; 000086 continue; 000087 } 000088 if( op!=TK_REGISTER || (op = pExpr->op2)==TK_REGISTER ) break; 000089 } 000090 return pExpr->affExpr; 000091 } 000092 000093 /* 000094 ** Make a guess at all the possible datatypes of the result that could 000095 ** be returned by an expression. Return a bitmask indicating the answer: 000096 ** 000097 ** 0x01 Numeric 000098 ** 0x02 Text 000099 ** 0x04 Blob 000100 ** 000101 ** If the expression must return NULL, then 0x00 is returned. 000102 */ 000103 int sqlite3ExprDataType(const Expr *pExpr){ 000104 while( pExpr ){ 000105 switch( pExpr->op ){ 000106 case TK_COLLATE: 000107 case TK_IF_NULL_ROW: 000108 case TK_UPLUS: { 000109 pExpr = pExpr->pLeft; 000110 break; 000111 } 000112 case TK_NULL: { 000113 pExpr = 0; 000114 break; 000115 } 000116 case TK_STRING: { 000117 return 0x02; 000118 } 000119 case TK_BLOB: { 000120 return 0x04; 000121 } 000122 case TK_CONCAT: { 000123 return 0x06; 000124 } 000125 case TK_VARIABLE: 000126 case TK_AGG_FUNCTION: 000127 case TK_FUNCTION: { 000128 return 0x07; 000129 } 000130 case TK_COLUMN: 000131 case TK_AGG_COLUMN: 000132 case TK_SELECT: 000133 case TK_CAST: 000134 case TK_SELECT_COLUMN: 000135 case TK_VECTOR: { 000136 int aff = sqlite3ExprAffinity(pExpr); 000137 if( aff>=SQLITE_AFF_NUMERIC ) return 0x05; 000138 if( aff==SQLITE_AFF_TEXT ) return 0x06; 000139 return 0x07; 000140 } 000141 case TK_CASE: { 000142 int res = 0; 000143 int ii; 000144 ExprList *pList = pExpr->x.pList; 000145 assert( ExprUseXList(pExpr) && pList!=0 ); 000146 assert( pList->nExpr > 0); 000147 for(ii=1; ii<pList->nExpr; ii+=2){ 000148 res |= sqlite3ExprDataType(pList->a[ii].pExpr); 000149 } 000150 if( pList->nExpr % 2 ){ 000151 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr); 000152 } 000153 return res; 000154 } 000155 default: { 000156 return 0x01; 000157 } 000158 } /* End of switch(op) */ 000159 } /* End of while(pExpr) */ 000160 return 0x00; 000161 } 000162 000163 /* 000164 ** Set the collating sequence for expression pExpr to be the collating 000165 ** sequence named by pToken. Return a pointer to a new Expr node that 000166 ** implements the COLLATE operator. 000167 ** 000168 ** If a memory allocation error occurs, that fact is recorded in pParse->db 000169 ** and the pExpr parameter is returned unchanged. 000170 */ 000171 Expr *sqlite3ExprAddCollateToken( 000172 const Parse *pParse, /* Parsing context */ 000173 Expr *pExpr, /* Add the "COLLATE" clause to this expression */ 000174 const Token *pCollName, /* Name of collating sequence */ 000175 int dequote /* True to dequote pCollName */ 000176 ){ 000177 if( pCollName->n>0 ){ 000178 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote); 000179 if( pNew ){ 000180 pNew->pLeft = pExpr; 000181 pNew->flags |= EP_Collate|EP_Skip; 000182 pExpr = pNew; 000183 } 000184 } 000185 return pExpr; 000186 } 000187 Expr *sqlite3ExprAddCollateString( 000188 const Parse *pParse, /* Parsing context */ 000189 Expr *pExpr, /* Add the "COLLATE" clause to this expression */ 000190 const char *zC /* The collating sequence name */ 000191 ){ 000192 Token s; 000193 assert( zC!=0 ); 000194 sqlite3TokenInit(&s, (char*)zC); 000195 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0); 000196 } 000197 000198 /* 000199 ** Skip over any TK_COLLATE operators. 000200 */ 000201 Expr *sqlite3ExprSkipCollate(Expr *pExpr){ 000202 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){ 000203 assert( pExpr->op==TK_COLLATE ); 000204 pExpr = pExpr->pLeft; 000205 } 000206 return pExpr; 000207 } 000208 000209 /* 000210 ** Skip over any TK_COLLATE operators and/or any unlikely() 000211 ** or likelihood() or likely() functions at the root of an 000212 ** expression. 000213 */ 000214 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){ 000215 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){ 000216 if( ExprHasProperty(pExpr, EP_Unlikely) ){ 000217 assert( ExprUseXList(pExpr) ); 000218 assert( pExpr->x.pList->nExpr>0 ); 000219 assert( pExpr->op==TK_FUNCTION ); 000220 pExpr = pExpr->x.pList->a[0].pExpr; 000221 }else{ 000222 assert( pExpr->op==TK_COLLATE ); 000223 pExpr = pExpr->pLeft; 000224 } 000225 } 000226 return pExpr; 000227 } 000228 000229 /* 000230 ** Return the collation sequence for the expression pExpr. If 000231 ** there is no defined collating sequence, return NULL. 000232 ** 000233 ** See also: sqlite3ExprNNCollSeq() 000234 ** 000235 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the 000236 ** default collation if pExpr has no defined collation. 000237 ** 000238 ** The collating sequence might be determined by a COLLATE operator 000239 ** or by the presence of a column with a defined collating sequence. 000240 ** COLLATE operators take first precedence. Left operands take 000241 ** precedence over right operands. 000242 */ 000243 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){ 000244 sqlite3 *db = pParse->db; 000245 CollSeq *pColl = 0; 000246 const Expr *p = pExpr; 000247 while( p ){ 000248 int op = p->op; 000249 if( op==TK_REGISTER ) op = p->op2; 000250 if( (op==TK_AGG_COLUMN && p->y.pTab!=0) 000251 || op==TK_COLUMN || op==TK_TRIGGER 000252 ){ 000253 int j; 000254 assert( ExprUseYTab(p) ); 000255 assert( p->y.pTab!=0 ); 000256 if( (j = p->iColumn)>=0 ){ 000257 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]); 000258 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0); 000259 } 000260 break; 000261 } 000262 if( op==TK_CAST || op==TK_UPLUS ){ 000263 p = p->pLeft; 000264 continue; 000265 } 000266 if( op==TK_VECTOR ){ 000267 assert( ExprUseXList(p) ); 000268 p = p->x.pList->a[0].pExpr; 000269 continue; 000270 } 000271 if( op==TK_COLLATE ){ 000272 assert( !ExprHasProperty(p, EP_IntValue) ); 000273 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken); 000274 break; 000275 } 000276 if( p->flags & EP_Collate ){ 000277 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){ 000278 p = p->pLeft; 000279 }else{ 000280 Expr *pNext = p->pRight; 000281 /* The Expr.x union is never used at the same time as Expr.pRight */ 000282 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 ); 000283 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){ 000284 int i; 000285 for(i=0; i<p->x.pList->nExpr; i++){ 000286 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){ 000287 pNext = p->x.pList->a[i].pExpr; 000288 break; 000289 } 000290 } 000291 } 000292 p = pNext; 000293 } 000294 }else{ 000295 break; 000296 } 000297 } 000298 if( sqlite3CheckCollSeq(pParse, pColl) ){ 000299 pColl = 0; 000300 } 000301 return pColl; 000302 } 000303 000304 /* 000305 ** Return the collation sequence for the expression pExpr. If 000306 ** there is no defined collating sequence, return a pointer to the 000307 ** default collation sequence. 000308 ** 000309 ** See also: sqlite3ExprCollSeq() 000310 ** 000311 ** The sqlite3ExprCollSeq() routine works the same except that it 000312 ** returns NULL if there is no defined collation. 000313 */ 000314 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){ 000315 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr); 000316 if( p==0 ) p = pParse->db->pDfltColl; 000317 assert( p!=0 ); 000318 return p; 000319 } 000320 000321 /* 000322 ** Return TRUE if the two expressions have equivalent collating sequences. 000323 */ 000324 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){ 000325 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1); 000326 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2); 000327 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0; 000328 } 000329 000330 /* 000331 ** pExpr is an operand of a comparison operator. aff2 is the 000332 ** type affinity of the other operand. This routine returns the 000333 ** type affinity that should be used for the comparison operator. 000334 */ 000335 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){ 000336 char aff1 = sqlite3ExprAffinity(pExpr); 000337 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){ 000338 /* Both sides of the comparison are columns. If one has numeric 000339 ** affinity, use that. Otherwise use no affinity. 000340 */ 000341 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){ 000342 return SQLITE_AFF_NUMERIC; 000343 }else{ 000344 return SQLITE_AFF_BLOB; 000345 } 000346 }else{ 000347 /* One side is a column, the other is not. Use the columns affinity. */ 000348 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE ); 000349 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE; 000350 } 000351 } 000352 000353 /* 000354 ** pExpr is a comparison operator. Return the type affinity that should 000355 ** be applied to both operands prior to doing the comparison. 000356 */ 000357 static char comparisonAffinity(const Expr *pExpr){ 000358 char aff; 000359 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT || 000360 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE || 000361 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT ); 000362 assert( pExpr->pLeft ); 000363 aff = sqlite3ExprAffinity(pExpr->pLeft); 000364 if( pExpr->pRight ){ 000365 aff = sqlite3CompareAffinity(pExpr->pRight, aff); 000366 }else if( ExprUseXSelect(pExpr) ){ 000367 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff); 000368 }else if( aff==0 ){ 000369 aff = SQLITE_AFF_BLOB; 000370 } 000371 return aff; 000372 } 000373 000374 /* 000375 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc. 000376 ** idx_affinity is the affinity of an indexed column. Return true 000377 ** if the index with affinity idx_affinity may be used to implement 000378 ** the comparison in pExpr. 000379 */ 000380 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){ 000381 char aff = comparisonAffinity(pExpr); 000382 if( aff<SQLITE_AFF_TEXT ){ 000383 return 1; 000384 } 000385 if( aff==SQLITE_AFF_TEXT ){ 000386 return idx_affinity==SQLITE_AFF_TEXT; 000387 } 000388 return sqlite3IsNumericAffinity(idx_affinity); 000389 } 000390 000391 /* 000392 ** Return the P5 value that should be used for a binary comparison 000393 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. 000394 */ 000395 static u8 binaryCompareP5( 000396 const Expr *pExpr1, /* Left operand */ 000397 const Expr *pExpr2, /* Right operand */ 000398 int jumpIfNull /* Extra flags added to P5 */ 000399 ){ 000400 u8 aff = (char)sqlite3ExprAffinity(pExpr2); 000401 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull; 000402 return aff; 000403 } 000404 000405 /* 000406 ** Return a pointer to the collation sequence that should be used by 000407 ** a binary comparison operator comparing pLeft and pRight. 000408 ** 000409 ** If the left hand expression has a collating sequence type, then it is 000410 ** used. Otherwise the collation sequence for the right hand expression 000411 ** is used, or the default (BINARY) if neither expression has a collating 000412 ** type. 000413 ** 000414 ** Argument pRight (but not pLeft) may be a null pointer. In this case, 000415 ** it is not considered. 000416 */ 000417 CollSeq *sqlite3BinaryCompareCollSeq( 000418 Parse *pParse, 000419 const Expr *pLeft, 000420 const Expr *pRight 000421 ){ 000422 CollSeq *pColl; 000423 assert( pLeft ); 000424 if( pLeft->flags & EP_Collate ){ 000425 pColl = sqlite3ExprCollSeq(pParse, pLeft); 000426 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){ 000427 pColl = sqlite3ExprCollSeq(pParse, pRight); 000428 }else{ 000429 pColl = sqlite3ExprCollSeq(pParse, pLeft); 000430 if( !pColl ){ 000431 pColl = sqlite3ExprCollSeq(pParse, pRight); 000432 } 000433 } 000434 return pColl; 000435 } 000436 000437 /* Expression p is a comparison operator. Return a collation sequence 000438 ** appropriate for the comparison operator. 000439 ** 000440 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq(). 000441 ** However, if the OP_Commuted flag is set, then the order of the operands 000442 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the 000443 ** correct collating sequence is found. 000444 */ 000445 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){ 000446 if( ExprHasProperty(p, EP_Commuted) ){ 000447 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft); 000448 }else{ 000449 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight); 000450 } 000451 } 000452 000453 /* 000454 ** Generate code for a comparison operator. 000455 */ 000456 static int codeCompare( 000457 Parse *pParse, /* The parsing (and code generating) context */ 000458 Expr *pLeft, /* The left operand */ 000459 Expr *pRight, /* The right operand */ 000460 int opcode, /* The comparison opcode */ 000461 int in1, int in2, /* Register holding operands */ 000462 int dest, /* Jump here if true. */ 000463 int jumpIfNull, /* If true, jump if either operand is NULL */ 000464 int isCommuted /* The comparison has been commuted */ 000465 ){ 000466 int p5; 000467 int addr; 000468 CollSeq *p4; 000469 000470 if( pParse->nErr ) return 0; 000471 if( isCommuted ){ 000472 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft); 000473 }else{ 000474 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); 000475 } 000476 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); 000477 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, 000478 (void*)p4, P4_COLLSEQ); 000479 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5); 000480 return addr; 000481 } 000482 000483 /* 000484 ** Return true if expression pExpr is a vector, or false otherwise. 000485 ** 000486 ** A vector is defined as any expression that results in two or more 000487 ** columns of result. Every TK_VECTOR node is an vector because the 000488 ** parser will not generate a TK_VECTOR with fewer than two entries. 000489 ** But a TK_SELECT might be either a vector or a scalar. It is only 000490 ** considered a vector if it has two or more result columns. 000491 */ 000492 int sqlite3ExprIsVector(const Expr *pExpr){ 000493 return sqlite3ExprVectorSize(pExpr)>1; 000494 } 000495 000496 /* 000497 ** If the expression passed as the only argument is of type TK_VECTOR 000498 ** return the number of expressions in the vector. Or, if the expression 000499 ** is a sub-select, return the number of columns in the sub-select. For 000500 ** any other type of expression, return 1. 000501 */ 000502 int sqlite3ExprVectorSize(const Expr *pExpr){ 000503 u8 op = pExpr->op; 000504 if( op==TK_REGISTER ) op = pExpr->op2; 000505 if( op==TK_VECTOR ){ 000506 assert( ExprUseXList(pExpr) ); 000507 return pExpr->x.pList->nExpr; 000508 }else if( op==TK_SELECT ){ 000509 assert( ExprUseXSelect(pExpr) ); 000510 return pExpr->x.pSelect->pEList->nExpr; 000511 }else{ 000512 return 1; 000513 } 000514 } 000515 000516 /* 000517 ** Return a pointer to a subexpression of pVector that is the i-th 000518 ** column of the vector (numbered starting with 0). The caller must 000519 ** ensure that i is within range. 000520 ** 000521 ** If pVector is really a scalar (and "scalar" here includes subqueries 000522 ** that return a single column!) then return pVector unmodified. 000523 ** 000524 ** pVector retains ownership of the returned subexpression. 000525 ** 000526 ** If the vector is a (SELECT ...) then the expression returned is 000527 ** just the expression for the i-th term of the result set, and may 000528 ** not be ready for evaluation because the table cursor has not yet 000529 ** been positioned. 000530 */ 000531 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){ 000532 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR ); 000533 if( sqlite3ExprIsVector(pVector) ){ 000534 assert( pVector->op2==0 || pVector->op==TK_REGISTER ); 000535 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){ 000536 assert( ExprUseXSelect(pVector) ); 000537 return pVector->x.pSelect->pEList->a[i].pExpr; 000538 }else{ 000539 assert( ExprUseXList(pVector) ); 000540 return pVector->x.pList->a[i].pExpr; 000541 } 000542 } 000543 return pVector; 000544 } 000545 000546 /* 000547 ** Compute and return a new Expr object which when passed to 000548 ** sqlite3ExprCode() will generate all necessary code to compute 000549 ** the iField-th column of the vector expression pVector. 000550 ** 000551 ** It is ok for pVector to be a scalar (as long as iField==0). 000552 ** In that case, this routine works like sqlite3ExprDup(). 000553 ** 000554 ** The caller owns the returned Expr object and is responsible for 000555 ** ensuring that the returned value eventually gets freed. 000556 ** 000557 ** The caller retains ownership of pVector. If pVector is a TK_SELECT, 000558 ** then the returned object will reference pVector and so pVector must remain 000559 ** valid for the life of the returned object. If pVector is a TK_VECTOR 000560 ** or a scalar expression, then it can be deleted as soon as this routine 000561 ** returns. 000562 ** 000563 ** A trick to cause a TK_SELECT pVector to be deleted together with 000564 ** the returned Expr object is to attach the pVector to the pRight field 000565 ** of the returned TK_SELECT_COLUMN Expr object. 000566 */ 000567 Expr *sqlite3ExprForVectorField( 000568 Parse *pParse, /* Parsing context */ 000569 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */ 000570 int iField, /* Which column of the vector to return */ 000571 int nField /* Total number of columns in the vector */ 000572 ){ 000573 Expr *pRet; 000574 if( pVector->op==TK_SELECT ){ 000575 assert( ExprUseXSelect(pVector) ); 000576 /* The TK_SELECT_COLUMN Expr node: 000577 ** 000578 ** pLeft: pVector containing TK_SELECT. Not deleted. 000579 ** pRight: not used. But recursively deleted. 000580 ** iColumn: Index of a column in pVector 000581 ** iTable: 0 or the number of columns on the LHS of an assignment 000582 ** pLeft->iTable: First in an array of register holding result, or 0 000583 ** if the result is not yet computed. 000584 ** 000585 ** sqlite3ExprDelete() specifically skips the recursive delete of 000586 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector 000587 ** can be attached to pRight to cause this node to take ownership of 000588 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes 000589 ** with the same pLeft pointer to the pVector, but only one of them 000590 ** will own the pVector. 000591 */ 000592 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0); 000593 if( pRet ){ 000594 ExprSetProperty(pRet, EP_FullSize); 000595 pRet->iTable = nField; 000596 pRet->iColumn = iField; 000597 pRet->pLeft = pVector; 000598 } 000599 }else{ 000600 if( pVector->op==TK_VECTOR ){ 000601 Expr **ppVector; 000602 assert( ExprUseXList(pVector) ); 000603 ppVector = &pVector->x.pList->a[iField].pExpr; 000604 pVector = *ppVector; 000605 if( IN_RENAME_OBJECT ){ 000606 /* This must be a vector UPDATE inside a trigger */ 000607 *ppVector = 0; 000608 return pVector; 000609 } 000610 } 000611 pRet = sqlite3ExprDup(pParse->db, pVector, 0); 000612 } 000613 return pRet; 000614 } 000615 000616 /* 000617 ** If expression pExpr is of type TK_SELECT, generate code to evaluate 000618 ** it. Return the register in which the result is stored (or, if the 000619 ** sub-select returns more than one column, the first in an array 000620 ** of registers in which the result is stored). 000621 ** 000622 ** If pExpr is not a TK_SELECT expression, return 0. 000623 */ 000624 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){ 000625 int reg = 0; 000626 #ifndef SQLITE_OMIT_SUBQUERY 000627 if( pExpr->op==TK_SELECT ){ 000628 reg = sqlite3CodeSubselect(pParse, pExpr); 000629 } 000630 #endif 000631 return reg; 000632 } 000633 000634 /* 000635 ** Argument pVector points to a vector expression - either a TK_VECTOR 000636 ** or TK_SELECT that returns more than one column. This function returns 000637 ** the register number of a register that contains the value of 000638 ** element iField of the vector. 000639 ** 000640 ** If pVector is a TK_SELECT expression, then code for it must have 000641 ** already been generated using the exprCodeSubselect() routine. In this 000642 ** case parameter regSelect should be the first in an array of registers 000643 ** containing the results of the sub-select. 000644 ** 000645 ** If pVector is of type TK_VECTOR, then code for the requested field 000646 ** is generated. In this case (*pRegFree) may be set to the number of 000647 ** a temporary register to be freed by the caller before returning. 000648 ** 000649 ** Before returning, output parameter (*ppExpr) is set to point to the 000650 ** Expr object corresponding to element iElem of the vector. 000651 */ 000652 static int exprVectorRegister( 000653 Parse *pParse, /* Parse context */ 000654 Expr *pVector, /* Vector to extract element from */ 000655 int iField, /* Field to extract from pVector */ 000656 int regSelect, /* First in array of registers */ 000657 Expr **ppExpr, /* OUT: Expression element */ 000658 int *pRegFree /* OUT: Temp register to free */ 000659 ){ 000660 u8 op = pVector->op; 000661 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR ); 000662 if( op==TK_REGISTER ){ 000663 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField); 000664 return pVector->iTable+iField; 000665 } 000666 if( op==TK_SELECT ){ 000667 assert( ExprUseXSelect(pVector) ); 000668 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr; 000669 return regSelect+iField; 000670 } 000671 if( op==TK_VECTOR ){ 000672 assert( ExprUseXList(pVector) ); 000673 *ppExpr = pVector->x.pList->a[iField].pExpr; 000674 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree); 000675 } 000676 return 0; 000677 } 000678 000679 /* 000680 ** Expression pExpr is a comparison between two vector values. Compute 000681 ** the result of the comparison (1, 0, or NULL) and write that 000682 ** result into register dest. 000683 ** 000684 ** The caller must satisfy the following preconditions: 000685 ** 000686 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ 000687 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ 000688 ** otherwise: op==pExpr->op and p5==0 000689 */ 000690 static void codeVectorCompare( 000691 Parse *pParse, /* Code generator context */ 000692 Expr *pExpr, /* The comparison operation */ 000693 int dest, /* Write results into this register */ 000694 u8 op, /* Comparison operator */ 000695 u8 p5 /* SQLITE_NULLEQ or zero */ 000696 ){ 000697 Vdbe *v = pParse->pVdbe; 000698 Expr *pLeft = pExpr->pLeft; 000699 Expr *pRight = pExpr->pRight; 000700 int nLeft = sqlite3ExprVectorSize(pLeft); 000701 int i; 000702 int regLeft = 0; 000703 int regRight = 0; 000704 u8 opx = op; 000705 int addrCmp = 0; 000706 int addrDone = sqlite3VdbeMakeLabel(pParse); 000707 int isCommuted = ExprHasProperty(pExpr,EP_Commuted); 000708 000709 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 000710 if( pParse->nErr ) return; 000711 if( nLeft!=sqlite3ExprVectorSize(pRight) ){ 000712 sqlite3ErrorMsg(pParse, "row value misused"); 000713 return; 000714 } 000715 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE 000716 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT 000717 || pExpr->op==TK_LT || pExpr->op==TK_GT 000718 || pExpr->op==TK_LE || pExpr->op==TK_GE 000719 ); 000720 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ) 000721 || (pExpr->op==TK_ISNOT && op==TK_NE) ); 000722 assert( p5==0 || pExpr->op!=op ); 000723 assert( p5==SQLITE_NULLEQ || pExpr->op==op ); 000724 000725 if( op==TK_LE ) opx = TK_LT; 000726 if( op==TK_GE ) opx = TK_GT; 000727 if( op==TK_NE ) opx = TK_EQ; 000728 000729 regLeft = exprCodeSubselect(pParse, pLeft); 000730 regRight = exprCodeSubselect(pParse, pRight); 000731 000732 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest); 000733 for(i=0; 1 /*Loop exits by "break"*/; i++){ 000734 int regFree1 = 0, regFree2 = 0; 000735 Expr *pL = 0, *pR = 0; 000736 int r1, r2; 000737 assert( i>=0 && i<nLeft ); 000738 if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp); 000739 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, ®Free1); 000740 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, ®Free2); 000741 addrCmp = sqlite3VdbeCurrentAddr(v); 000742 codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted); 000743 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 000744 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 000745 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 000746 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 000747 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); 000748 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); 000749 sqlite3ReleaseTempReg(pParse, regFree1); 000750 sqlite3ReleaseTempReg(pParse, regFree2); 000751 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){ 000752 addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq); 000753 testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT); 000754 testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT); 000755 } 000756 if( p5==SQLITE_NULLEQ ){ 000757 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest); 000758 }else{ 000759 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2); 000760 } 000761 if( i==nLeft-1 ){ 000762 break; 000763 } 000764 if( opx==TK_EQ ){ 000765 sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v); 000766 }else{ 000767 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE ); 000768 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone); 000769 if( i==nLeft-2 ) opx = op; 000770 } 000771 } 000772 sqlite3VdbeJumpHere(v, addrCmp); 000773 sqlite3VdbeResolveLabel(v, addrDone); 000774 if( op==TK_NE ){ 000775 sqlite3VdbeAddOp2(v, OP_Not, dest, dest); 000776 } 000777 } 000778 000779 #if SQLITE_MAX_EXPR_DEPTH>0 000780 /* 000781 ** Check that argument nHeight is less than or equal to the maximum 000782 ** expression depth allowed. If it is not, leave an error message in 000783 ** pParse. 000784 */ 000785 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){ 000786 int rc = SQLITE_OK; 000787 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH]; 000788 if( nHeight>mxHeight ){ 000789 sqlite3ErrorMsg(pParse, 000790 "Expression tree is too large (maximum depth %d)", mxHeight 000791 ); 000792 rc = SQLITE_ERROR; 000793 } 000794 return rc; 000795 } 000796 000797 /* The following three functions, heightOfExpr(), heightOfExprList() 000798 ** and heightOfSelect(), are used to determine the maximum height 000799 ** of any expression tree referenced by the structure passed as the 000800 ** first argument. 000801 ** 000802 ** If this maximum height is greater than the current value pointed 000803 ** to by pnHeight, the second parameter, then set *pnHeight to that 000804 ** value. 000805 */ 000806 static void heightOfExpr(const Expr *p, int *pnHeight){ 000807 if( p ){ 000808 if( p->nHeight>*pnHeight ){ 000809 *pnHeight = p->nHeight; 000810 } 000811 } 000812 } 000813 static void heightOfExprList(const ExprList *p, int *pnHeight){ 000814 if( p ){ 000815 int i; 000816 for(i=0; i<p->nExpr; i++){ 000817 heightOfExpr(p->a[i].pExpr, pnHeight); 000818 } 000819 } 000820 } 000821 static void heightOfSelect(const Select *pSelect, int *pnHeight){ 000822 const Select *p; 000823 for(p=pSelect; p; p=p->pPrior){ 000824 heightOfExpr(p->pWhere, pnHeight); 000825 heightOfExpr(p->pHaving, pnHeight); 000826 heightOfExpr(p->pLimit, pnHeight); 000827 heightOfExprList(p->pEList, pnHeight); 000828 heightOfExprList(p->pGroupBy, pnHeight); 000829 heightOfExprList(p->pOrderBy, pnHeight); 000830 } 000831 } 000832 000833 /* 000834 ** Set the Expr.nHeight variable in the structure passed as an 000835 ** argument. An expression with no children, Expr.pList or 000836 ** Expr.pSelect member has a height of 1. Any other expression 000837 ** has a height equal to the maximum height of any other 000838 ** referenced Expr plus one. 000839 ** 000840 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags, 000841 ** if appropriate. 000842 */ 000843 static void exprSetHeight(Expr *p){ 000844 int nHeight = p->pLeft ? p->pLeft->nHeight : 0; 000845 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){ 000846 nHeight = p->pRight->nHeight; 000847 } 000848 if( ExprUseXSelect(p) ){ 000849 heightOfSelect(p->x.pSelect, &nHeight); 000850 }else if( p->x.pList ){ 000851 heightOfExprList(p->x.pList, &nHeight); 000852 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 000853 } 000854 p->nHeight = nHeight + 1; 000855 } 000856 000857 /* 000858 ** Set the Expr.nHeight variable using the exprSetHeight() function. If 000859 ** the height is greater than the maximum allowed expression depth, 000860 ** leave an error in pParse. 000861 ** 000862 ** Also propagate all EP_Propagate flags from the Expr.x.pList into 000863 ** Expr.flags. 000864 */ 000865 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 000866 if( pParse->nErr ) return; 000867 exprSetHeight(p); 000868 sqlite3ExprCheckHeight(pParse, p->nHeight); 000869 } 000870 000871 /* 000872 ** Return the maximum height of any expression tree referenced 000873 ** by the select statement passed as an argument. 000874 */ 000875 int sqlite3SelectExprHeight(const Select *p){ 000876 int nHeight = 0; 000877 heightOfSelect(p, &nHeight); 000878 return nHeight; 000879 } 000880 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */ 000881 /* 000882 ** Propagate all EP_Propagate flags from the Expr.x.pList into 000883 ** Expr.flags. 000884 */ 000885 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){ 000886 if( pParse->nErr ) return; 000887 if( p && ExprUseXList(p) && p->x.pList ){ 000888 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList); 000889 } 000890 } 000891 #define exprSetHeight(y) 000892 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */ 000893 000894 /* 000895 ** Set the error offset for an Expr node, if possible. 000896 */ 000897 void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){ 000898 if( pExpr==0 ) return; 000899 if( NEVER(ExprUseWJoin(pExpr)) ) return; 000900 pExpr->w.iOfst = iOfst; 000901 } 000902 000903 /* 000904 ** This routine is the core allocator for Expr nodes. 000905 ** 000906 ** Construct a new expression node and return a pointer to it. Memory 000907 ** for this node and for the pToken argument is a single allocation 000908 ** obtained from sqlite3DbMalloc(). The calling function 000909 ** is responsible for making sure the node eventually gets freed. 000910 ** 000911 ** If dequote is true, then the token (if it exists) is dequoted. 000912 ** If dequote is false, no dequoting is performed. The deQuote 000913 ** parameter is ignored if pToken is NULL or if the token does not 000914 ** appear to be quoted. If the quotes were of the form "..." (double-quotes) 000915 ** then the EP_DblQuoted flag is set on the expression node. 000916 ** 000917 ** Special case: If op==TK_INTEGER and pToken points to a string that 000918 ** can be translated into a 32-bit integer, then the token is not 000919 ** stored in u.zToken. Instead, the integer values is written 000920 ** into u.iValue and the EP_IntValue flag is set. No extra storage 000921 ** is allocated to hold the integer text and the dequote flag is ignored. 000922 */ 000923 Expr *sqlite3ExprAlloc( 000924 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */ 000925 int op, /* Expression opcode */ 000926 const Token *pToken, /* Token argument. Might be NULL */ 000927 int dequote /* True to dequote */ 000928 ){ 000929 Expr *pNew; 000930 int nExtra = 0; 000931 int iValue = 0; 000932 000933 assert( db!=0 ); 000934 if( pToken ){ 000935 if( op!=TK_INTEGER || pToken->z==0 000936 || sqlite3GetInt32(pToken->z, &iValue)==0 ){ 000937 nExtra = pToken->n+1; 000938 assert( iValue>=0 ); 000939 } 000940 } 000941 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra); 000942 if( pNew ){ 000943 memset(pNew, 0, sizeof(Expr)); 000944 pNew->op = (u8)op; 000945 pNew->iAgg = -1; 000946 if( pToken ){ 000947 if( nExtra==0 ){ 000948 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse); 000949 pNew->u.iValue = iValue; 000950 }else{ 000951 pNew->u.zToken = (char*)&pNew[1]; 000952 assert( pToken->z!=0 || pToken->n==0 ); 000953 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n); 000954 pNew->u.zToken[pToken->n] = 0; 000955 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){ 000956 sqlite3DequoteExpr(pNew); 000957 } 000958 } 000959 } 000960 #if SQLITE_MAX_EXPR_DEPTH>0 000961 pNew->nHeight = 1; 000962 #endif 000963 } 000964 return pNew; 000965 } 000966 000967 /* 000968 ** Allocate a new expression node from a zero-terminated token that has 000969 ** already been dequoted. 000970 */ 000971 Expr *sqlite3Expr( 000972 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */ 000973 int op, /* Expression opcode */ 000974 const char *zToken /* Token argument. Might be NULL */ 000975 ){ 000976 Token x; 000977 x.z = zToken; 000978 x.n = sqlite3Strlen30(zToken); 000979 return sqlite3ExprAlloc(db, op, &x, 0); 000980 } 000981 000982 /* 000983 ** Attach subtrees pLeft and pRight to the Expr node pRoot. 000984 ** 000985 ** If pRoot==NULL that means that a memory allocation error has occurred. 000986 ** In that case, delete the subtrees pLeft and pRight. 000987 */ 000988 void sqlite3ExprAttachSubtrees( 000989 sqlite3 *db, 000990 Expr *pRoot, 000991 Expr *pLeft, 000992 Expr *pRight 000993 ){ 000994 if( pRoot==0 ){ 000995 assert( db->mallocFailed ); 000996 sqlite3ExprDelete(db, pLeft); 000997 sqlite3ExprDelete(db, pRight); 000998 }else{ 000999 assert( ExprUseXList(pRoot) ); 001000 assert( pRoot->x.pSelect==0 ); 001001 if( pRight ){ 001002 pRoot->pRight = pRight; 001003 pRoot->flags |= EP_Propagate & pRight->flags; 001004 #if SQLITE_MAX_EXPR_DEPTH>0 001005 pRoot->nHeight = pRight->nHeight+1; 001006 }else{ 001007 pRoot->nHeight = 1; 001008 #endif 001009 } 001010 if( pLeft ){ 001011 pRoot->pLeft = pLeft; 001012 pRoot->flags |= EP_Propagate & pLeft->flags; 001013 #if SQLITE_MAX_EXPR_DEPTH>0 001014 if( pLeft->nHeight>=pRoot->nHeight ){ 001015 pRoot->nHeight = pLeft->nHeight+1; 001016 } 001017 #endif 001018 } 001019 } 001020 } 001021 001022 /* 001023 ** Allocate an Expr node which joins as many as two subtrees. 001024 ** 001025 ** One or both of the subtrees can be NULL. Return a pointer to the new 001026 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed, 001027 ** free the subtrees and return NULL. 001028 */ 001029 Expr *sqlite3PExpr( 001030 Parse *pParse, /* Parsing context */ 001031 int op, /* Expression opcode */ 001032 Expr *pLeft, /* Left operand */ 001033 Expr *pRight /* Right operand */ 001034 ){ 001035 Expr *p; 001036 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)); 001037 if( p ){ 001038 memset(p, 0, sizeof(Expr)); 001039 p->op = op & 0xff; 001040 p->iAgg = -1; 001041 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight); 001042 sqlite3ExprCheckHeight(pParse, p->nHeight); 001043 }else{ 001044 sqlite3ExprDelete(pParse->db, pLeft); 001045 sqlite3ExprDelete(pParse->db, pRight); 001046 } 001047 return p; 001048 } 001049 001050 /* 001051 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due 001052 ** do a memory allocation failure) then delete the pSelect object. 001053 */ 001054 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){ 001055 if( pExpr ){ 001056 pExpr->x.pSelect = pSelect; 001057 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery); 001058 sqlite3ExprSetHeightAndFlags(pParse, pExpr); 001059 }else{ 001060 assert( pParse->db->mallocFailed ); 001061 sqlite3SelectDelete(pParse->db, pSelect); 001062 } 001063 } 001064 001065 /* 001066 ** Expression list pEList is a list of vector values. This function 001067 ** converts the contents of pEList to a VALUES(...) Select statement 001068 ** returning 1 row for each element of the list. For example, the 001069 ** expression list: 001070 ** 001071 ** ( (1,2), (3,4) (5,6) ) 001072 ** 001073 ** is translated to the equivalent of: 001074 ** 001075 ** VALUES(1,2), (3,4), (5,6) 001076 ** 001077 ** Each of the vector values in pEList must contain exactly nElem terms. 001078 ** If a list element that is not a vector or does not contain nElem terms, 001079 ** an error message is left in pParse. 001080 ** 001081 ** This is used as part of processing IN(...) expressions with a list 001082 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))". 001083 */ 001084 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){ 001085 int ii; 001086 Select *pRet = 0; 001087 assert( nElem>1 ); 001088 for(ii=0; ii<pEList->nExpr; ii++){ 001089 Select *pSel; 001090 Expr *pExpr = pEList->a[ii].pExpr; 001091 int nExprElem; 001092 if( pExpr->op==TK_VECTOR ){ 001093 assert( ExprUseXList(pExpr) ); 001094 nExprElem = pExpr->x.pList->nExpr; 001095 }else{ 001096 nExprElem = 1; 001097 } 001098 if( nExprElem!=nElem ){ 001099 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d", 001100 nExprElem, nExprElem>1?"s":"", nElem 001101 ); 001102 break; 001103 } 001104 assert( ExprUseXList(pExpr) ); 001105 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0); 001106 pExpr->x.pList = 0; 001107 if( pSel ){ 001108 if( pRet ){ 001109 pSel->op = TK_ALL; 001110 pSel->pPrior = pRet; 001111 } 001112 pRet = pSel; 001113 } 001114 } 001115 001116 if( pRet && pRet->pPrior ){ 001117 pRet->selFlags |= SF_MultiValue; 001118 } 001119 sqlite3ExprListDelete(pParse->db, pEList); 001120 return pRet; 001121 } 001122 001123 /* 001124 ** Join two expressions using an AND operator. If either expression is 001125 ** NULL, then just return the other expression. 001126 ** 001127 ** If one side or the other of the AND is known to be false, and neither side 001128 ** is part of an ON clause, then instead of returning an AND expression, 001129 ** just return a constant expression with a value of false. 001130 */ 001131 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){ 001132 sqlite3 *db = pParse->db; 001133 if( pLeft==0 ){ 001134 return pRight; 001135 }else if( pRight==0 ){ 001136 return pLeft; 001137 }else{ 001138 u32 f = pLeft->flags | pRight->flags; 001139 if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse 001140 && !IN_RENAME_OBJECT 001141 ){ 001142 sqlite3ExprDeferredDelete(pParse, pLeft); 001143 sqlite3ExprDeferredDelete(pParse, pRight); 001144 return sqlite3Expr(db, TK_INTEGER, "0"); 001145 }else{ 001146 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight); 001147 } 001148 } 001149 } 001150 001151 /* 001152 ** Construct a new expression node for a function with multiple 001153 ** arguments. 001154 */ 001155 Expr *sqlite3ExprFunction( 001156 Parse *pParse, /* Parsing context */ 001157 ExprList *pList, /* Argument list */ 001158 const Token *pToken, /* Name of the function */ 001159 int eDistinct /* SF_Distinct or SF_ALL or 0 */ 001160 ){ 001161 Expr *pNew; 001162 sqlite3 *db = pParse->db; 001163 assert( pToken ); 001164 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1); 001165 if( pNew==0 ){ 001166 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */ 001167 return 0; 001168 } 001169 assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) ); 001170 pNew->w.iOfst = (int)(pToken->z - pParse->zTail); 001171 if( pList 001172 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] 001173 && !pParse->nested 001174 ){ 001175 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken); 001176 } 001177 pNew->x.pList = pList; 001178 ExprSetProperty(pNew, EP_HasFunc); 001179 assert( ExprUseXList(pNew) ); 001180 sqlite3ExprSetHeightAndFlags(pParse, pNew); 001181 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct); 001182 return pNew; 001183 } 001184 001185 /* 001186 ** Report an error when attempting to use an ORDER BY clause within 001187 ** the arguments of a non-aggregate function. 001188 */ 001189 void sqlite3ExprOrderByAggregateError(Parse *pParse, Expr *p){ 001190 sqlite3ErrorMsg(pParse, 001191 "ORDER BY may not be used with non-aggregate %#T()", p 001192 ); 001193 } 001194 001195 /* 001196 ** Attach an ORDER BY clause to a function call. 001197 ** 001198 ** functionname( arguments ORDER BY sortlist ) 001199 ** \_____________________/ \______/ 001200 ** pExpr pOrderBy 001201 ** 001202 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER 001203 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node. 001204 */ 001205 void sqlite3ExprAddFunctionOrderBy( 001206 Parse *pParse, /* Parsing context */ 001207 Expr *pExpr, /* The function call to which ORDER BY is to be added */ 001208 ExprList *pOrderBy /* The ORDER BY clause to add */ 001209 ){ 001210 Expr *pOB; 001211 sqlite3 *db = pParse->db; 001212 if( NEVER(pOrderBy==0) ){ 001213 assert( db->mallocFailed ); 001214 return; 001215 } 001216 if( pExpr==0 ){ 001217 assert( db->mallocFailed ); 001218 sqlite3ExprListDelete(db, pOrderBy); 001219 return; 001220 } 001221 assert( pExpr->op==TK_FUNCTION ); 001222 assert( pExpr->pLeft==0 ); 001223 assert( ExprUseXList(pExpr) ); 001224 if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){ 001225 /* Ignore ORDER BY on zero-argument aggregates */ 001226 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pOrderBy); 001227 return; 001228 } 001229 if( IsWindowFunc(pExpr) ){ 001230 sqlite3ExprOrderByAggregateError(pParse, pExpr); 001231 sqlite3ExprListDelete(db, pOrderBy); 001232 return; 001233 } 001234 001235 pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0); 001236 if( pOB==0 ){ 001237 sqlite3ExprListDelete(db, pOrderBy); 001238 return; 001239 } 001240 pOB->x.pList = pOrderBy; 001241 assert( ExprUseXList(pOB) ); 001242 pExpr->pLeft = pOB; 001243 ExprSetProperty(pOB, EP_FullSize); 001244 } 001245 001246 /* 001247 ** Check to see if a function is usable according to current access 001248 ** rules: 001249 ** 001250 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL 001251 ** 001252 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from 001253 ** top-level SQL 001254 ** 001255 ** If the function is not usable, create an error. 001256 */ 001257 void sqlite3ExprFunctionUsable( 001258 Parse *pParse, /* Parsing and code generating context */ 001259 const Expr *pExpr, /* The function invocation */ 001260 const FuncDef *pDef /* The function being invoked */ 001261 ){ 001262 assert( !IN_RENAME_OBJECT ); 001263 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 ); 001264 if( ExprHasProperty(pExpr, EP_FromDDL) ){ 001265 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0 001266 || (pParse->db->flags & SQLITE_TrustedSchema)==0 001267 ){ 001268 /* Functions prohibited in triggers and views if: 001269 ** (1) tagged with SQLITE_DIRECTONLY 001270 ** (2) not tagged with SQLITE_INNOCUOUS (which means it 001271 ** is tagged with SQLITE_FUNC_UNSAFE) and 001272 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning 001273 ** that the schema is possibly tainted). 001274 */ 001275 sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr); 001276 } 001277 } 001278 } 001279 001280 /* 001281 ** Assign a variable number to an expression that encodes a wildcard 001282 ** in the original SQL statement. 001283 ** 001284 ** Wildcards consisting of a single "?" are assigned the next sequential 001285 ** variable number. 001286 ** 001287 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make 001288 ** sure "nnn" is not too big to avoid a denial of service attack when 001289 ** the SQL statement comes from an external source. 001290 ** 001291 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number 001292 ** as the previous instance of the same wildcard. Or if this is the first 001293 ** instance of the wildcard, the next sequential variable number is 001294 ** assigned. 001295 */ 001296 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){ 001297 sqlite3 *db = pParse->db; 001298 const char *z; 001299 ynVar x; 001300 001301 if( pExpr==0 ) return; 001302 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) ); 001303 z = pExpr->u.zToken; 001304 assert( z!=0 ); 001305 assert( z[0]!=0 ); 001306 assert( n==(u32)sqlite3Strlen30(z) ); 001307 if( z[1]==0 ){ 001308 /* Wildcard of the form "?". Assign the next variable number */ 001309 assert( z[0]=='?' ); 001310 x = (ynVar)(++pParse->nVar); 001311 }else{ 001312 int doAdd = 0; 001313 if( z[0]=='?' ){ 001314 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and 001315 ** use it as the variable number */ 001316 i64 i; 001317 int bOk; 001318 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/ 001319 i = z[1]-'0'; /* The common case of ?N for a single digit N */ 001320 bOk = 1; 001321 }else{ 001322 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8); 001323 } 001324 testcase( i==0 ); 001325 testcase( i==1 ); 001326 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 ); 001327 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ); 001328 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 001329 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d", 001330 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]); 001331 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr); 001332 return; 001333 } 001334 x = (ynVar)i; 001335 if( x>pParse->nVar ){ 001336 pParse->nVar = (int)x; 001337 doAdd = 1; 001338 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){ 001339 doAdd = 1; 001340 } 001341 }else{ 001342 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable 001343 ** number as the prior appearance of the same name, or if the name 001344 ** has never appeared before, reuse the same variable number 001345 */ 001346 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n); 001347 if( x==0 ){ 001348 x = (ynVar)(++pParse->nVar); 001349 doAdd = 1; 001350 } 001351 } 001352 if( doAdd ){ 001353 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x); 001354 } 001355 } 001356 pExpr->iColumn = x; 001357 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){ 001358 sqlite3ErrorMsg(pParse, "too many SQL variables"); 001359 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr); 001360 } 001361 } 001362 001363 /* 001364 ** Recursively delete an expression tree. 001365 */ 001366 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){ 001367 assert( p!=0 ); 001368 assert( db!=0 ); 001369 assert( !ExprUseUValue(p) || p->u.iValue>=0 ); 001370 assert( !ExprUseYWin(p) || !ExprUseYSub(p) ); 001371 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed ); 001372 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) ); 001373 #ifdef SQLITE_DEBUG 001374 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){ 001375 assert( p->pLeft==0 ); 001376 assert( p->pRight==0 ); 001377 assert( !ExprUseXSelect(p) || p->x.pSelect==0 ); 001378 assert( !ExprUseXList(p) || p->x.pList==0 ); 001379 } 001380 #endif 001381 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){ 001382 /* The Expr.x union is never used at the same time as Expr.pRight */ 001383 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 ); 001384 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft); 001385 if( p->pRight ){ 001386 assert( !ExprHasProperty(p, EP_WinFunc) ); 001387 sqlite3ExprDeleteNN(db, p->pRight); 001388 }else if( ExprUseXSelect(p) ){ 001389 assert( !ExprHasProperty(p, EP_WinFunc) ); 001390 sqlite3SelectDelete(db, p->x.pSelect); 001391 }else{ 001392 sqlite3ExprListDelete(db, p->x.pList); 001393 #ifndef SQLITE_OMIT_WINDOWFUNC 001394 if( ExprHasProperty(p, EP_WinFunc) ){ 001395 sqlite3WindowDelete(db, p->y.pWin); 001396 } 001397 #endif 001398 } 001399 } 001400 if( !ExprHasProperty(p, EP_Static) ){ 001401 sqlite3DbNNFreeNN(db, p); 001402 } 001403 } 001404 void sqlite3ExprDelete(sqlite3 *db, Expr *p){ 001405 if( p ) sqlite3ExprDeleteNN(db, p); 001406 } 001407 void sqlite3ExprDeleteGeneric(sqlite3 *db, void *p){ 001408 if( ALWAYS(p) ) sqlite3ExprDeleteNN(db, (Expr*)p); 001409 } 001410 001411 /* 001412 ** Clear both elements of an OnOrUsing object 001413 */ 001414 void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){ 001415 if( p==0 ){ 001416 /* Nothing to clear */ 001417 }else if( p->pOn ){ 001418 sqlite3ExprDeleteNN(db, p->pOn); 001419 }else if( p->pUsing ){ 001420 sqlite3IdListDelete(db, p->pUsing); 001421 } 001422 } 001423 001424 /* 001425 ** Arrange to cause pExpr to be deleted when the pParse is deleted. 001426 ** This is similar to sqlite3ExprDelete() except that the delete is 001427 ** deferred until the pParse is deleted. 001428 ** 001429 ** The pExpr might be deleted immediately on an OOM error. 001430 ** 001431 ** The deferred delete is (currently) implemented by adding the 001432 ** pExpr to the pParse->pConstExpr list with a register number of 0. 001433 */ 001434 void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){ 001435 sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr); 001436 } 001437 001438 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the 001439 ** expression. 001440 */ 001441 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){ 001442 if( p ){ 001443 if( IN_RENAME_OBJECT ){ 001444 sqlite3RenameExprUnmap(pParse, p); 001445 } 001446 sqlite3ExprDeleteNN(pParse->db, p); 001447 } 001448 } 001449 001450 /* 001451 ** Return the number of bytes allocated for the expression structure 001452 ** passed as the first argument. This is always one of EXPR_FULLSIZE, 001453 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE. 001454 */ 001455 static int exprStructSize(const Expr *p){ 001456 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE; 001457 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE; 001458 return EXPR_FULLSIZE; 001459 } 001460 001461 /* 001462 ** The dupedExpr*Size() routines each return the number of bytes required 001463 ** to store a copy of an expression or expression tree. They differ in 001464 ** how much of the tree is measured. 001465 ** 001466 ** dupedExprStructSize() Size of only the Expr structure 001467 ** dupedExprNodeSize() Size of Expr + space for token 001468 ** dupedExprSize() Expr + token + subtree components 001469 ** 001470 *************************************************************************** 001471 ** 001472 ** The dupedExprStructSize() function returns two values OR-ed together: 001473 ** (1) the space required for a copy of the Expr structure only and 001474 ** (2) the EP_xxx flags that indicate what the structure size should be. 001475 ** The return values is always one of: 001476 ** 001477 ** EXPR_FULLSIZE 001478 ** EXPR_REDUCEDSIZE | EP_Reduced 001479 ** EXPR_TOKENONLYSIZE | EP_TokenOnly 001480 ** 001481 ** The size of the structure can be found by masking the return value 001482 ** of this routine with 0xfff. The flags can be found by masking the 001483 ** return value with EP_Reduced|EP_TokenOnly. 001484 ** 001485 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size 001486 ** (unreduced) Expr objects as they or originally constructed by the parser. 001487 ** During expression analysis, extra information is computed and moved into 001488 ** later parts of the Expr object and that extra information might get chopped 001489 ** off if the expression is reduced. Note also that it does not work to 001490 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal 001491 ** to reduce a pristine expression tree from the parser. The implementation 001492 ** of dupedExprStructSize() contain multiple assert() statements that attempt 001493 ** to enforce this constraint. 001494 */ 001495 static int dupedExprStructSize(const Expr *p, int flags){ 001496 int nSize; 001497 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */ 001498 assert( EXPR_FULLSIZE<=0xfff ); 001499 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 ); 001500 if( 0==flags || ExprHasProperty(p, EP_FullSize) ){ 001501 nSize = EXPR_FULLSIZE; 001502 }else{ 001503 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) ); 001504 assert( !ExprHasProperty(p, EP_OuterON) ); 001505 assert( !ExprHasVVAProperty(p, EP_NoReduce) ); 001506 if( p->pLeft || p->x.pList ){ 001507 nSize = EXPR_REDUCEDSIZE | EP_Reduced; 001508 }else{ 001509 assert( p->pRight==0 ); 001510 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly; 001511 } 001512 } 001513 return nSize; 001514 } 001515 001516 /* 001517 ** This function returns the space in bytes required to store the copy 001518 ** of the Expr structure and a copy of the Expr.u.zToken string (if that 001519 ** string is defined.) 001520 */ 001521 static int dupedExprNodeSize(const Expr *p, int flags){ 001522 int nByte = dupedExprStructSize(p, flags) & 0xfff; 001523 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 001524 nByte += sqlite3Strlen30NN(p->u.zToken)+1; 001525 } 001526 return ROUND8(nByte); 001527 } 001528 001529 /* 001530 ** Return the number of bytes required to create a duplicate of the 001531 ** expression passed as the first argument. 001532 ** 001533 ** The value returned includes space to create a copy of the Expr struct 001534 ** itself and the buffer referred to by Expr.u.zToken, if any. 001535 ** 001536 ** The return value includes space to duplicate all Expr nodes in the 001537 ** tree formed by Expr.pLeft and Expr.pRight, but not any other 001538 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin. 001539 */ 001540 static int dupedExprSize(const Expr *p){ 001541 int nByte; 001542 assert( p!=0 ); 001543 nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE); 001544 if( p->pLeft ) nByte += dupedExprSize(p->pLeft); 001545 if( p->pRight ) nByte += dupedExprSize(p->pRight); 001546 assert( nByte==ROUND8(nByte) ); 001547 return nByte; 001548 } 001549 001550 /* 001551 ** An EdupBuf is a memory allocation used to stored multiple Expr objects 001552 ** together with their Expr.zToken content. This is used to help implement 001553 ** compression while doing sqlite3ExprDup(). The top-level Expr does the 001554 ** allocation for itself and many of its decendents, then passes an instance 001555 ** of the structure down into exprDup() so that they decendents can have 001556 ** access to that memory. 001557 */ 001558 typedef struct EdupBuf EdupBuf; 001559 struct EdupBuf { 001560 u8 *zAlloc; /* Memory space available for storage */ 001561 #ifdef SQLITE_DEBUG 001562 u8 *zEnd; /* First byte past the end of memory */ 001563 #endif 001564 }; 001565 001566 /* 001567 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf 001568 ** is not NULL then it points to memory that can be used to store a copy 001569 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf 001570 ** is updated with the new buffer tail prior to returning. 001571 */ 001572 static Expr *exprDup( 001573 sqlite3 *db, /* Database connection (for memory allocation) */ 001574 const Expr *p, /* Expr tree to be duplicated */ 001575 int dupFlags, /* EXPRDUP_REDUCE for compression. 0 if not */ 001576 EdupBuf *pEdupBuf /* Preallocated storage space, or NULL */ 001577 ){ 001578 Expr *pNew; /* Value to return */ 001579 EdupBuf sEdupBuf; /* Memory space from which to build Expr object */ 001580 u32 staticFlag; /* EP_Static if space not obtained from malloc */ 001581 int nToken = -1; /* Space needed for p->u.zToken. -1 means unknown */ 001582 001583 assert( db!=0 ); 001584 assert( p ); 001585 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE ); 001586 assert( pEdupBuf==0 || dupFlags==EXPRDUP_REDUCE ); 001587 001588 /* Figure out where to write the new Expr structure. */ 001589 if( pEdupBuf ){ 001590 sEdupBuf.zAlloc = pEdupBuf->zAlloc; 001591 #ifdef SQLITE_DEBUG 001592 sEdupBuf.zEnd = pEdupBuf->zEnd; 001593 #endif 001594 staticFlag = EP_Static; 001595 assert( sEdupBuf.zAlloc!=0 ); 001596 assert( dupFlags==EXPRDUP_REDUCE ); 001597 }else{ 001598 int nAlloc; 001599 if( dupFlags ){ 001600 nAlloc = dupedExprSize(p); 001601 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 001602 nToken = sqlite3Strlen30NN(p->u.zToken)+1; 001603 nAlloc = ROUND8(EXPR_FULLSIZE + nToken); 001604 }else{ 001605 nToken = 0; 001606 nAlloc = ROUND8(EXPR_FULLSIZE); 001607 } 001608 assert( nAlloc==ROUND8(nAlloc) ); 001609 sEdupBuf.zAlloc = sqlite3DbMallocRawNN(db, nAlloc); 001610 #ifdef SQLITE_DEBUG 001611 sEdupBuf.zEnd = sEdupBuf.zAlloc ? sEdupBuf.zAlloc+nAlloc : 0; 001612 #endif 001613 001614 staticFlag = 0; 001615 } 001616 pNew = (Expr *)sEdupBuf.zAlloc; 001617 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); 001618 001619 if( pNew ){ 001620 /* Set nNewSize to the size allocated for the structure pointed to 001621 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or 001622 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed 001623 ** by the copy of the p->u.zToken string (if any). 001624 */ 001625 const unsigned nStructSize = dupedExprStructSize(p, dupFlags); 001626 int nNewSize = nStructSize & 0xfff; 001627 if( nToken<0 ){ 001628 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){ 001629 nToken = sqlite3Strlen30(p->u.zToken) + 1; 001630 }else{ 001631 nToken = 0; 001632 } 001633 } 001634 if( dupFlags ){ 001635 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken ); 001636 assert( ExprHasProperty(p, EP_Reduced)==0 ); 001637 memcpy(sEdupBuf.zAlloc, p, nNewSize); 001638 }else{ 001639 u32 nSize = (u32)exprStructSize(p); 001640 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= 001641 (int)EXPR_FULLSIZE+nToken ); 001642 memcpy(sEdupBuf.zAlloc, p, nSize); 001643 if( nSize<EXPR_FULLSIZE ){ 001644 memset(&sEdupBuf.zAlloc[nSize], 0, EXPR_FULLSIZE-nSize); 001645 } 001646 nNewSize = EXPR_FULLSIZE; 001647 } 001648 001649 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */ 001650 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static); 001651 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly); 001652 pNew->flags |= staticFlag; 001653 ExprClearVVAProperties(pNew); 001654 if( dupFlags ){ 001655 ExprSetVVAProperty(pNew, EP_Immutable); 001656 } 001657 001658 /* Copy the p->u.zToken string, if any. */ 001659 assert( nToken>=0 ); 001660 if( nToken>0 ){ 001661 char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize]; 001662 memcpy(zToken, p->u.zToken, nToken); 001663 nNewSize += nToken; 001664 } 001665 sEdupBuf.zAlloc += ROUND8(nNewSize); 001666 001667 if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){ 001668 001669 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */ 001670 if( ExprUseXSelect(p) ){ 001671 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags); 001672 }else{ 001673 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, 001674 p->op!=TK_ORDER ? dupFlags : 0); 001675 } 001676 001677 #ifndef SQLITE_OMIT_WINDOWFUNC 001678 if( ExprHasProperty(p, EP_WinFunc) ){ 001679 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin); 001680 assert( ExprHasProperty(pNew, EP_WinFunc) ); 001681 } 001682 #endif /* SQLITE_OMIT_WINDOWFUNC */ 001683 001684 /* Fill in pNew->pLeft and pNew->pRight. */ 001685 if( dupFlags ){ 001686 if( p->op==TK_SELECT_COLUMN ){ 001687 pNew->pLeft = p->pLeft; 001688 assert( p->pRight==0 001689 || p->pRight==p->pLeft 001690 || ExprHasProperty(p->pLeft, EP_Subquery) ); 001691 }else{ 001692 pNew->pLeft = p->pLeft ? 001693 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0; 001694 } 001695 pNew->pRight = p->pRight ? 001696 exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0; 001697 }else{ 001698 if( p->op==TK_SELECT_COLUMN ){ 001699 pNew->pLeft = p->pLeft; 001700 assert( p->pRight==0 001701 || p->pRight==p->pLeft 001702 || ExprHasProperty(p->pLeft, EP_Subquery) ); 001703 }else{ 001704 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0); 001705 } 001706 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0); 001707 } 001708 } 001709 } 001710 if( pEdupBuf ) memcpy(pEdupBuf, &sEdupBuf, sizeof(sEdupBuf)); 001711 assert( sEdupBuf.zAlloc <= sEdupBuf.zEnd ); 001712 return pNew; 001713 } 001714 001715 /* 001716 ** Create and return a deep copy of the object passed as the second 001717 ** argument. If an OOM condition is encountered, NULL is returned 001718 ** and the db->mallocFailed flag set. 001719 */ 001720 #ifndef SQLITE_OMIT_CTE 001721 With *sqlite3WithDup(sqlite3 *db, With *p){ 001722 With *pRet = 0; 001723 if( p ){ 001724 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1); 001725 pRet = sqlite3DbMallocZero(db, nByte); 001726 if( pRet ){ 001727 int i; 001728 pRet->nCte = p->nCte; 001729 for(i=0; i<p->nCte; i++){ 001730 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0); 001731 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0); 001732 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName); 001733 pRet->a[i].eM10d = p->a[i].eM10d; 001734 } 001735 } 001736 } 001737 return pRet; 001738 } 001739 #else 001740 # define sqlite3WithDup(x,y) 0 001741 #endif 001742 001743 #ifndef SQLITE_OMIT_WINDOWFUNC 001744 /* 001745 ** The gatherSelectWindows() procedure and its helper routine 001746 ** gatherSelectWindowsCallback() are used to scan all the expressions 001747 ** an a newly duplicated SELECT statement and gather all of the Window 001748 ** objects found there, assembling them onto the linked list at Select->pWin. 001749 */ 001750 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){ 001751 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){ 001752 Select *pSelect = pWalker->u.pSelect; 001753 Window *pWin = pExpr->y.pWin; 001754 assert( pWin ); 001755 assert( IsWindowFunc(pExpr) ); 001756 assert( pWin->ppThis==0 ); 001757 sqlite3WindowLink(pSelect, pWin); 001758 } 001759 return WRC_Continue; 001760 } 001761 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){ 001762 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune; 001763 } 001764 static void gatherSelectWindows(Select *p){ 001765 Walker w; 001766 w.xExprCallback = gatherSelectWindowsCallback; 001767 w.xSelectCallback = gatherSelectWindowsSelectCallback; 001768 w.xSelectCallback2 = 0; 001769 w.pParse = 0; 001770 w.u.pSelect = p; 001771 sqlite3WalkSelect(&w, p); 001772 } 001773 #endif 001774 001775 001776 /* 001777 ** The following group of routines make deep copies of expressions, 001778 ** expression lists, ID lists, and select statements. The copies can 001779 ** be deleted (by being passed to their respective ...Delete() routines) 001780 ** without effecting the originals. 001781 ** 001782 ** The expression list, ID, and source lists return by sqlite3ExprListDup(), 001783 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 001784 ** by subsequent calls to sqlite*ListAppend() routines. 001785 ** 001786 ** Any tables that the SrcList might point to are not duplicated. 001787 ** 001788 ** The flags parameter contains a combination of the EXPRDUP_XXX flags. 001789 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a 001790 ** truncated version of the usual Expr structure that will be stored as 001791 ** part of the in-memory representation of the database schema. 001792 */ 001793 Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){ 001794 assert( flags==0 || flags==EXPRDUP_REDUCE ); 001795 return p ? exprDup(db, p, flags, 0) : 0; 001796 } 001797 ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){ 001798 ExprList *pNew; 001799 struct ExprList_item *pItem; 001800 const struct ExprList_item *pOldItem; 001801 int i; 001802 Expr *pPriorSelectColOld = 0; 001803 Expr *pPriorSelectColNew = 0; 001804 assert( db!=0 ); 001805 if( p==0 ) return 0; 001806 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p)); 001807 if( pNew==0 ) return 0; 001808 pNew->nExpr = p->nExpr; 001809 pNew->nAlloc = p->nAlloc; 001810 pItem = pNew->a; 001811 pOldItem = p->a; 001812 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){ 001813 Expr *pOldExpr = pOldItem->pExpr; 001814 Expr *pNewExpr; 001815 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags); 001816 if( pOldExpr 001817 && pOldExpr->op==TK_SELECT_COLUMN 001818 && (pNewExpr = pItem->pExpr)!=0 001819 ){ 001820 if( pNewExpr->pRight ){ 001821 pPriorSelectColOld = pOldExpr->pRight; 001822 pPriorSelectColNew = pNewExpr->pRight; 001823 pNewExpr->pLeft = pNewExpr->pRight; 001824 }else{ 001825 if( pOldExpr->pLeft!=pPriorSelectColOld ){ 001826 pPriorSelectColOld = pOldExpr->pLeft; 001827 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags); 001828 pNewExpr->pRight = pPriorSelectColNew; 001829 } 001830 pNewExpr->pLeft = pPriorSelectColNew; 001831 } 001832 } 001833 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName); 001834 pItem->fg = pOldItem->fg; 001835 pItem->fg.done = 0; 001836 pItem->u = pOldItem->u; 001837 } 001838 return pNew; 001839 } 001840 001841 /* 001842 ** If cursors, triggers, views and subqueries are all omitted from 001843 ** the build, then none of the following routines, except for 001844 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes 001845 ** called with a NULL argument. 001846 */ 001847 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \ 001848 || !defined(SQLITE_OMIT_SUBQUERY) 001849 SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){ 001850 SrcList *pNew; 001851 int i; 001852 int nByte; 001853 assert( db!=0 ); 001854 if( p==0 ) return 0; 001855 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0); 001856 pNew = sqlite3DbMallocRawNN(db, nByte ); 001857 if( pNew==0 ) return 0; 001858 pNew->nSrc = pNew->nAlloc = p->nSrc; 001859 for(i=0; i<p->nSrc; i++){ 001860 SrcItem *pNewItem = &pNew->a[i]; 001861 const SrcItem *pOldItem = &p->a[i]; 001862 Table *pTab; 001863 pNewItem->pSchema = pOldItem->pSchema; 001864 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase); 001865 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 001866 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias); 001867 pNewItem->fg = pOldItem->fg; 001868 pNewItem->iCursor = pOldItem->iCursor; 001869 pNewItem->addrFillSub = pOldItem->addrFillSub; 001870 pNewItem->regReturn = pOldItem->regReturn; 001871 if( pNewItem->fg.isIndexedBy ){ 001872 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy); 001873 } 001874 pNewItem->u2 = pOldItem->u2; 001875 if( pNewItem->fg.isCte ){ 001876 pNewItem->u2.pCteUse->nUse++; 001877 } 001878 if( pNewItem->fg.isTabFunc ){ 001879 pNewItem->u1.pFuncArg = 001880 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags); 001881 } 001882 pTab = pNewItem->pTab = pOldItem->pTab; 001883 if( pTab ){ 001884 pTab->nTabRef++; 001885 } 001886 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags); 001887 if( pOldItem->fg.isUsing ){ 001888 assert( pNewItem->fg.isUsing ); 001889 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing); 001890 }else{ 001891 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags); 001892 } 001893 pNewItem->colUsed = pOldItem->colUsed; 001894 } 001895 return pNew; 001896 } 001897 IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){ 001898 IdList *pNew; 001899 int i; 001900 assert( db!=0 ); 001901 if( p==0 ) return 0; 001902 assert( p->eU4!=EU4_EXPR ); 001903 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) ); 001904 if( pNew==0 ) return 0; 001905 pNew->nId = p->nId; 001906 pNew->eU4 = p->eU4; 001907 for(i=0; i<p->nId; i++){ 001908 struct IdList_item *pNewItem = &pNew->a[i]; 001909 const struct IdList_item *pOldItem = &p->a[i]; 001910 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName); 001911 pNewItem->u4 = pOldItem->u4; 001912 } 001913 return pNew; 001914 } 001915 Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){ 001916 Select *pRet = 0; 001917 Select *pNext = 0; 001918 Select **pp = &pRet; 001919 const Select *p; 001920 001921 assert( db!=0 ); 001922 for(p=pDup; p; p=p->pPrior){ 001923 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) ); 001924 if( pNew==0 ) break; 001925 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags); 001926 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags); 001927 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags); 001928 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags); 001929 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags); 001930 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags); 001931 pNew->op = p->op; 001932 pNew->pNext = pNext; 001933 pNew->pPrior = 0; 001934 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags); 001935 pNew->iLimit = 0; 001936 pNew->iOffset = 0; 001937 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral; 001938 pNew->addrOpenEphm[0] = -1; 001939 pNew->addrOpenEphm[1] = -1; 001940 pNew->nSelectRow = p->nSelectRow; 001941 pNew->pWith = sqlite3WithDup(db, p->pWith); 001942 #ifndef SQLITE_OMIT_WINDOWFUNC 001943 pNew->pWin = 0; 001944 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn); 001945 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew); 001946 #endif 001947 pNew->selId = p->selId; 001948 if( db->mallocFailed ){ 001949 /* Any prior OOM might have left the Select object incomplete. 001950 ** Delete the whole thing rather than allow an incomplete Select 001951 ** to be used by the code generator. */ 001952 pNew->pNext = 0; 001953 sqlite3SelectDelete(db, pNew); 001954 break; 001955 } 001956 *pp = pNew; 001957 pp = &pNew->pPrior; 001958 pNext = pNew; 001959 } 001960 001961 return pRet; 001962 } 001963 #else 001964 Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){ 001965 assert( p==0 ); 001966 return 0; 001967 } 001968 #endif 001969 001970 001971 /* 001972 ** Add a new element to the end of an expression list. If pList is 001973 ** initially NULL, then create a new expression list. 001974 ** 001975 ** The pList argument must be either NULL or a pointer to an ExprList 001976 ** obtained from a prior call to sqlite3ExprListAppend(). 001977 ** 001978 ** If a memory allocation error occurs, the entire list is freed and 001979 ** NULL is returned. If non-NULL is returned, then it is guaranteed 001980 ** that the new entry was successfully appended. 001981 */ 001982 static const struct ExprList_item zeroItem = {0}; 001983 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew( 001984 sqlite3 *db, /* Database handle. Used for memory allocation */ 001985 Expr *pExpr /* Expression to be appended. Might be NULL */ 001986 ){ 001987 struct ExprList_item *pItem; 001988 ExprList *pList; 001989 001990 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 ); 001991 if( pList==0 ){ 001992 sqlite3ExprDelete(db, pExpr); 001993 return 0; 001994 } 001995 pList->nAlloc = 4; 001996 pList->nExpr = 1; 001997 pItem = &pList->a[0]; 001998 *pItem = zeroItem; 001999 pItem->pExpr = pExpr; 002000 return pList; 002001 } 002002 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow( 002003 sqlite3 *db, /* Database handle. Used for memory allocation */ 002004 ExprList *pList, /* List to which to append. Might be NULL */ 002005 Expr *pExpr /* Expression to be appended. Might be NULL */ 002006 ){ 002007 struct ExprList_item *pItem; 002008 ExprList *pNew; 002009 pList->nAlloc *= 2; 002010 pNew = sqlite3DbRealloc(db, pList, 002011 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0])); 002012 if( pNew==0 ){ 002013 sqlite3ExprListDelete(db, pList); 002014 sqlite3ExprDelete(db, pExpr); 002015 return 0; 002016 }else{ 002017 pList = pNew; 002018 } 002019 pItem = &pList->a[pList->nExpr++]; 002020 *pItem = zeroItem; 002021 pItem->pExpr = pExpr; 002022 return pList; 002023 } 002024 ExprList *sqlite3ExprListAppend( 002025 Parse *pParse, /* Parsing context */ 002026 ExprList *pList, /* List to which to append. Might be NULL */ 002027 Expr *pExpr /* Expression to be appended. Might be NULL */ 002028 ){ 002029 struct ExprList_item *pItem; 002030 if( pList==0 ){ 002031 return sqlite3ExprListAppendNew(pParse->db,pExpr); 002032 } 002033 if( pList->nAlloc<pList->nExpr+1 ){ 002034 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr); 002035 } 002036 pItem = &pList->a[pList->nExpr++]; 002037 *pItem = zeroItem; 002038 pItem->pExpr = pExpr; 002039 return pList; 002040 } 002041 002042 /* 002043 ** pColumns and pExpr form a vector assignment which is part of the SET 002044 ** clause of an UPDATE statement. Like this: 002045 ** 002046 ** (a,b,c) = (expr1,expr2,expr3) 002047 ** Or: (a,b,c) = (SELECT x,y,z FROM ....) 002048 ** 002049 ** For each term of the vector assignment, append new entries to the 002050 ** expression list pList. In the case of a subquery on the RHS, append 002051 ** TK_SELECT_COLUMN expressions. 002052 */ 002053 ExprList *sqlite3ExprListAppendVector( 002054 Parse *pParse, /* Parsing context */ 002055 ExprList *pList, /* List to which to append. Might be NULL */ 002056 IdList *pColumns, /* List of names of LHS of the assignment */ 002057 Expr *pExpr /* Vector expression to be appended. Might be NULL */ 002058 ){ 002059 sqlite3 *db = pParse->db; 002060 int n; 002061 int i; 002062 int iFirst = pList ? pList->nExpr : 0; 002063 /* pColumns can only be NULL due to an OOM but an OOM will cause an 002064 ** exit prior to this routine being invoked */ 002065 if( NEVER(pColumns==0) ) goto vector_append_error; 002066 if( pExpr==0 ) goto vector_append_error; 002067 002068 /* If the RHS is a vector, then we can immediately check to see that 002069 ** the size of the RHS and LHS match. But if the RHS is a SELECT, 002070 ** wildcards ("*") in the result set of the SELECT must be expanded before 002071 ** we can do the size check, so defer the size check until code generation. 002072 */ 002073 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){ 002074 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 002075 pColumns->nId, n); 002076 goto vector_append_error; 002077 } 002078 002079 for(i=0; i<pColumns->nId; i++){ 002080 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId); 002081 assert( pSubExpr!=0 || db->mallocFailed ); 002082 if( pSubExpr==0 ) continue; 002083 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr); 002084 if( pList ){ 002085 assert( pList->nExpr==iFirst+i+1 ); 002086 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName; 002087 pColumns->a[i].zName = 0; 002088 } 002089 } 002090 002091 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){ 002092 Expr *pFirst = pList->a[iFirst].pExpr; 002093 assert( pFirst!=0 ); 002094 assert( pFirst->op==TK_SELECT_COLUMN ); 002095 002096 /* Store the SELECT statement in pRight so it will be deleted when 002097 ** sqlite3ExprListDelete() is called */ 002098 pFirst->pRight = pExpr; 002099 pExpr = 0; 002100 002101 /* Remember the size of the LHS in iTable so that we can check that 002102 ** the RHS and LHS sizes match during code generation. */ 002103 pFirst->iTable = pColumns->nId; 002104 } 002105 002106 vector_append_error: 002107 sqlite3ExprUnmapAndDelete(pParse, pExpr); 002108 sqlite3IdListDelete(db, pColumns); 002109 return pList; 002110 } 002111 002112 /* 002113 ** Set the sort order for the last element on the given ExprList. 002114 */ 002115 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){ 002116 struct ExprList_item *pItem; 002117 if( p==0 ) return; 002118 assert( p->nExpr>0 ); 002119 002120 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 ); 002121 assert( iSortOrder==SQLITE_SO_UNDEFINED 002122 || iSortOrder==SQLITE_SO_ASC 002123 || iSortOrder==SQLITE_SO_DESC 002124 ); 002125 assert( eNulls==SQLITE_SO_UNDEFINED 002126 || eNulls==SQLITE_SO_ASC 002127 || eNulls==SQLITE_SO_DESC 002128 ); 002129 002130 pItem = &p->a[p->nExpr-1]; 002131 assert( pItem->fg.bNulls==0 ); 002132 if( iSortOrder==SQLITE_SO_UNDEFINED ){ 002133 iSortOrder = SQLITE_SO_ASC; 002134 } 002135 pItem->fg.sortFlags = (u8)iSortOrder; 002136 002137 if( eNulls!=SQLITE_SO_UNDEFINED ){ 002138 pItem->fg.bNulls = 1; 002139 if( iSortOrder!=eNulls ){ 002140 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL; 002141 } 002142 } 002143 } 002144 002145 /* 002146 ** Set the ExprList.a[].zEName element of the most recently added item 002147 ** on the expression list. 002148 ** 002149 ** pList might be NULL following an OOM error. But pName should never be 002150 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 002151 ** is set. 002152 */ 002153 void sqlite3ExprListSetName( 002154 Parse *pParse, /* Parsing context */ 002155 ExprList *pList, /* List to which to add the span. */ 002156 const Token *pName, /* Name to be added */ 002157 int dequote /* True to cause the name to be dequoted */ 002158 ){ 002159 assert( pList!=0 || pParse->db->mallocFailed!=0 ); 002160 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 ); 002161 if( pList ){ 002162 struct ExprList_item *pItem; 002163 assert( pList->nExpr>0 ); 002164 pItem = &pList->a[pList->nExpr-1]; 002165 assert( pItem->zEName==0 ); 002166 assert( pItem->fg.eEName==ENAME_NAME ); 002167 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n); 002168 if( dequote ){ 002169 /* If dequote==0, then pName->z does not point to part of a DDL 002170 ** statement handled by the parser. And so no token need be added 002171 ** to the token-map. */ 002172 sqlite3Dequote(pItem->zEName); 002173 if( IN_RENAME_OBJECT ){ 002174 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName); 002175 } 002176 } 002177 } 002178 } 002179 002180 /* 002181 ** Set the ExprList.a[].zSpan element of the most recently added item 002182 ** on the expression list. 002183 ** 002184 ** pList might be NULL following an OOM error. But pSpan should never be 002185 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag 002186 ** is set. 002187 */ 002188 void sqlite3ExprListSetSpan( 002189 Parse *pParse, /* Parsing context */ 002190 ExprList *pList, /* List to which to add the span. */ 002191 const char *zStart, /* Start of the span */ 002192 const char *zEnd /* End of the span */ 002193 ){ 002194 sqlite3 *db = pParse->db; 002195 assert( pList!=0 || db->mallocFailed!=0 ); 002196 if( pList ){ 002197 struct ExprList_item *pItem = &pList->a[pList->nExpr-1]; 002198 assert( pList->nExpr>0 ); 002199 if( pItem->zEName==0 ){ 002200 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd); 002201 pItem->fg.eEName = ENAME_SPAN; 002202 } 002203 } 002204 } 002205 002206 /* 002207 ** If the expression list pEList contains more than iLimit elements, 002208 ** leave an error message in pParse. 002209 */ 002210 void sqlite3ExprListCheckLength( 002211 Parse *pParse, 002212 ExprList *pEList, 002213 const char *zObject 002214 ){ 002215 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN]; 002216 testcase( pEList && pEList->nExpr==mx ); 002217 testcase( pEList && pEList->nExpr==mx+1 ); 002218 if( pEList && pEList->nExpr>mx ){ 002219 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject); 002220 } 002221 } 002222 002223 /* 002224 ** Delete an entire expression list. 002225 */ 002226 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){ 002227 int i = pList->nExpr; 002228 struct ExprList_item *pItem = pList->a; 002229 assert( pList->nExpr>0 ); 002230 assert( db!=0 ); 002231 do{ 002232 sqlite3ExprDelete(db, pItem->pExpr); 002233 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName); 002234 pItem++; 002235 }while( --i>0 ); 002236 sqlite3DbNNFreeNN(db, pList); 002237 } 002238 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){ 002239 if( pList ) exprListDeleteNN(db, pList); 002240 } 002241 void sqlite3ExprListDeleteGeneric(sqlite3 *db, void *pList){ 002242 if( ALWAYS(pList) ) exprListDeleteNN(db, (ExprList*)pList); 002243 } 002244 002245 /* 002246 ** Return the bitwise-OR of all Expr.flags fields in the given 002247 ** ExprList. 002248 */ 002249 u32 sqlite3ExprListFlags(const ExprList *pList){ 002250 int i; 002251 u32 m = 0; 002252 assert( pList!=0 ); 002253 for(i=0; i<pList->nExpr; i++){ 002254 Expr *pExpr = pList->a[i].pExpr; 002255 assert( pExpr!=0 ); 002256 m |= pExpr->flags; 002257 } 002258 return m; 002259 } 002260 002261 /* 002262 ** This is a SELECT-node callback for the expression walker that 002263 ** always "fails". By "fail" in this case, we mean set 002264 ** pWalker->eCode to zero and abort. 002265 ** 002266 ** This callback is used by multiple expression walkers. 002267 */ 002268 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){ 002269 UNUSED_PARAMETER(NotUsed); 002270 pWalker->eCode = 0; 002271 return WRC_Abort; 002272 } 002273 002274 /* 002275 ** Check the input string to see if it is "true" or "false" (in any case). 002276 ** 002277 ** If the string is.... Return 002278 ** "true" EP_IsTrue 002279 ** "false" EP_IsFalse 002280 ** anything else 0 002281 */ 002282 u32 sqlite3IsTrueOrFalse(const char *zIn){ 002283 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue; 002284 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse; 002285 return 0; 002286 } 002287 002288 002289 /* 002290 ** If the input expression is an ID with the name "true" or "false" 002291 ** then convert it into an TK_TRUEFALSE term. Return non-zero if 002292 ** the conversion happened, and zero if the expression is unaltered. 002293 */ 002294 int sqlite3ExprIdToTrueFalse(Expr *pExpr){ 002295 u32 v; 002296 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING ); 002297 if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue) 002298 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0 002299 ){ 002300 pExpr->op = TK_TRUEFALSE; 002301 ExprSetProperty(pExpr, v); 002302 return 1; 002303 } 002304 return 0; 002305 } 002306 002307 /* 002308 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE 002309 ** and 0 if it is FALSE. 002310 */ 002311 int sqlite3ExprTruthValue(const Expr *pExpr){ 002312 pExpr = sqlite3ExprSkipCollateAndLikely((Expr*)pExpr); 002313 assert( pExpr->op==TK_TRUEFALSE ); 002314 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 002315 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0 002316 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 ); 002317 return pExpr->u.zToken[4]==0; 002318 } 002319 002320 /* 002321 ** If pExpr is an AND or OR expression, try to simplify it by eliminating 002322 ** terms that are always true or false. Return the simplified expression. 002323 ** Or return the original expression if no simplification is possible. 002324 ** 002325 ** Examples: 002326 ** 002327 ** (x<10) AND true => (x<10) 002328 ** (x<10) AND false => false 002329 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22) 002330 ** (x<10) AND (y=22 OR true) => (x<10) 002331 ** (y=22) OR true => true 002332 */ 002333 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){ 002334 assert( pExpr!=0 ); 002335 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){ 002336 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight); 002337 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft); 002338 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){ 002339 pExpr = pExpr->op==TK_AND ? pRight : pLeft; 002340 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){ 002341 pExpr = pExpr->op==TK_AND ? pLeft : pRight; 002342 } 002343 } 002344 return pExpr; 002345 } 002346 002347 002348 /* 002349 ** These routines are Walker callbacks used to check expressions to 002350 ** see if they are "constant" for some definition of constant. The 002351 ** Walker.eCode value determines the type of "constant" we are looking 002352 ** for. 002353 ** 002354 ** These callback routines are used to implement the following: 002355 ** 002356 ** sqlite3ExprIsConstant() pWalker->eCode==1 002357 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2 002358 ** sqlite3ExprIsTableConstant() pWalker->eCode==3 002359 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5 002360 ** 002361 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression 002362 ** is found to not be a constant. 002363 ** 002364 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT 002365 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5 002366 ** when parsing an existing schema out of the sqlite_schema table and 4 002367 ** when processing a new CREATE TABLE statement. A bound parameter raises 002368 ** an error for new statements, but is silently converted 002369 ** to NULL for existing schemas. This allows sqlite_schema tables that 002370 ** contain a bound parameter because they were generated by older versions 002371 ** of SQLite to be parsed by newer versions of SQLite without raising a 002372 ** malformed schema error. 002373 */ 002374 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){ 002375 002376 /* If pWalker->eCode is 2 then any term of the expression that comes from 002377 ** the ON or USING clauses of an outer join disqualifies the expression 002378 ** from being considered constant. */ 002379 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){ 002380 pWalker->eCode = 0; 002381 return WRC_Abort; 002382 } 002383 002384 switch( pExpr->op ){ 002385 /* Consider functions to be constant if all their arguments are constant 002386 ** and either pWalker->eCode==4 or 5 or the function has the 002387 ** SQLITE_FUNC_CONST flag. */ 002388 case TK_FUNCTION: 002389 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc)) 002390 && !ExprHasProperty(pExpr, EP_WinFunc) 002391 ){ 002392 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL); 002393 return WRC_Continue; 002394 }else{ 002395 pWalker->eCode = 0; 002396 return WRC_Abort; 002397 } 002398 case TK_ID: 002399 /* Convert "true" or "false" in a DEFAULT clause into the 002400 ** appropriate TK_TRUEFALSE operator */ 002401 if( sqlite3ExprIdToTrueFalse(pExpr) ){ 002402 return WRC_Prune; 002403 } 002404 /* no break */ deliberate_fall_through 002405 case TK_COLUMN: 002406 case TK_AGG_FUNCTION: 002407 case TK_AGG_COLUMN: 002408 testcase( pExpr->op==TK_ID ); 002409 testcase( pExpr->op==TK_COLUMN ); 002410 testcase( pExpr->op==TK_AGG_FUNCTION ); 002411 testcase( pExpr->op==TK_AGG_COLUMN ); 002412 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){ 002413 return WRC_Continue; 002414 } 002415 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){ 002416 return WRC_Continue; 002417 } 002418 /* no break */ deliberate_fall_through 002419 case TK_IF_NULL_ROW: 002420 case TK_REGISTER: 002421 case TK_DOT: 002422 testcase( pExpr->op==TK_REGISTER ); 002423 testcase( pExpr->op==TK_IF_NULL_ROW ); 002424 testcase( pExpr->op==TK_DOT ); 002425 pWalker->eCode = 0; 002426 return WRC_Abort; 002427 case TK_VARIABLE: 002428 if( pWalker->eCode==5 ){ 002429 /* Silently convert bound parameters that appear inside of CREATE 002430 ** statements into a NULL when parsing the CREATE statement text out 002431 ** of the sqlite_schema table */ 002432 pExpr->op = TK_NULL; 002433 }else if( pWalker->eCode==4 ){ 002434 /* A bound parameter in a CREATE statement that originates from 002435 ** sqlite3_prepare() causes an error */ 002436 pWalker->eCode = 0; 002437 return WRC_Abort; 002438 } 002439 /* no break */ deliberate_fall_through 002440 default: 002441 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */ 002442 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */ 002443 return WRC_Continue; 002444 } 002445 } 002446 static int exprIsConst(Expr *p, int initFlag, int iCur){ 002447 Walker w; 002448 w.eCode = initFlag; 002449 w.xExprCallback = exprNodeIsConstant; 002450 w.xSelectCallback = sqlite3SelectWalkFail; 002451 #ifdef SQLITE_DEBUG 002452 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 002453 #endif 002454 w.u.iCur = iCur; 002455 sqlite3WalkExpr(&w, p); 002456 return w.eCode; 002457 } 002458 002459 /* 002460 ** Walk an expression tree. Return non-zero if the expression is constant 002461 ** and 0 if it involves variables or function calls. 002462 ** 002463 ** For the purposes of this function, a double-quoted string (ex: "abc") 002464 ** is considered a variable but a single-quoted string (ex: 'abc') is 002465 ** a constant. 002466 */ 002467 int sqlite3ExprIsConstant(Expr *p){ 002468 return exprIsConst(p, 1, 0); 002469 } 002470 002471 /* 002472 ** Walk an expression tree. Return non-zero if 002473 ** 002474 ** (1) the expression is constant, and 002475 ** (2) the expression does originate in the ON or USING clause 002476 ** of a LEFT JOIN, and 002477 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN 002478 ** operands created by the constant propagation optimization. 002479 ** 002480 ** When this routine returns true, it indicates that the expression 002481 ** can be added to the pParse->pConstExpr list and evaluated once when 002482 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce(). 002483 */ 002484 int sqlite3ExprIsConstantNotJoin(Expr *p){ 002485 return exprIsConst(p, 2, 0); 002486 } 002487 002488 /* 002489 ** Walk an expression tree. Return non-zero if the expression is constant 002490 ** for any single row of the table with cursor iCur. In other words, the 002491 ** expression must not refer to any non-deterministic function nor any 002492 ** table other than iCur. 002493 */ 002494 int sqlite3ExprIsTableConstant(Expr *p, int iCur){ 002495 return exprIsConst(p, 3, iCur); 002496 } 002497 002498 /* 002499 ** Check pExpr to see if it is an constraint on the single data source 002500 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr 002501 ** constrains pSrc but does not depend on any other tables or data 002502 ** sources anywhere else in the query. Return true (non-zero) if pExpr 002503 ** is a constraint on pSrc only. 002504 ** 002505 ** This is an optimization. False negatives will perhaps cause slower 002506 ** queries, but false positives will yield incorrect answers. So when in 002507 ** doubt, return 0. 002508 ** 002509 ** To be an single-source constraint, the following must be true: 002510 ** 002511 ** (1) pExpr cannot refer to any table other than pSrc->iCursor. 002512 ** 002513 ** (2) pExpr cannot use subqueries or non-deterministic functions. 002514 ** 002515 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN. 002516 ** (Is there some way to relax this constraint?) 002517 ** 002518 ** (4) If pSrc is the right operand of a LEFT JOIN, then... 002519 ** (4a) pExpr must come from an ON clause.. 002520 ** (4b) and specifically the ON clause associated with the LEFT JOIN. 002521 ** 002522 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left 002523 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE 002524 ** clause, not an ON clause. 002525 ** 002526 ** (6) Either: 002527 ** 002528 ** (6a) pExpr does not originate in an ON or USING clause, or 002529 ** 002530 ** (6b) The ON or USING clause from which pExpr is derived is 002531 ** not to the left of a RIGHT JOIN (or FULL JOIN). 002532 ** 002533 ** Without this restriction, accepting pExpr as a single-table 002534 ** constraint might move the the ON/USING filter expression 002535 ** from the left side of a RIGHT JOIN over to the right side, 002536 ** which leads to incorrect answers. See also restriction (9) 002537 ** on push-down. 002538 */ 002539 int sqlite3ExprIsSingleTableConstraint( 002540 Expr *pExpr, /* The constraint */ 002541 const SrcList *pSrcList, /* Complete FROM clause */ 002542 int iSrc /* Which element of pSrcList to use */ 002543 ){ 002544 const SrcItem *pSrc = &pSrcList->a[iSrc]; 002545 if( pSrc->fg.jointype & JT_LTORJ ){ 002546 return 0; /* rule (3) */ 002547 } 002548 if( pSrc->fg.jointype & JT_LEFT ){ 002549 if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (4a) */ 002550 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */ 002551 }else{ 002552 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (5) */ 002553 } 002554 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) /* (6a) */ 002555 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */ 002556 ){ 002557 int jj; 002558 for(jj=0; jj<iSrc; jj++){ 002559 if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){ 002560 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){ 002561 return 0; /* restriction (6) */ 002562 } 002563 break; 002564 } 002565 } 002566 } 002567 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor); /* rules (1), (2) */ 002568 } 002569 002570 002571 /* 002572 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy(). 002573 */ 002574 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){ 002575 ExprList *pGroupBy = pWalker->u.pGroupBy; 002576 int i; 002577 002578 /* Check if pExpr is identical to any GROUP BY term. If so, consider 002579 ** it constant. */ 002580 for(i=0; i<pGroupBy->nExpr; i++){ 002581 Expr *p = pGroupBy->a[i].pExpr; 002582 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){ 002583 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p); 002584 if( sqlite3IsBinary(pColl) ){ 002585 return WRC_Prune; 002586 } 002587 } 002588 } 002589 002590 /* Check if pExpr is a sub-select. If so, consider it variable. */ 002591 if( ExprUseXSelect(pExpr) ){ 002592 pWalker->eCode = 0; 002593 return WRC_Abort; 002594 } 002595 002596 return exprNodeIsConstant(pWalker, pExpr); 002597 } 002598 002599 /* 002600 ** Walk the expression tree passed as the first argument. Return non-zero 002601 ** if the expression consists entirely of constants or copies of terms 002602 ** in pGroupBy that sort with the BINARY collation sequence. 002603 ** 002604 ** This routine is used to determine if a term of the HAVING clause can 002605 ** be promoted into the WHERE clause. In order for such a promotion to work, 002606 ** the value of the HAVING clause term must be the same for all members of 002607 ** a "group". The requirement that the GROUP BY term must be BINARY 002608 ** assumes that no other collating sequence will have a finer-grained 002609 ** grouping than binary. In other words (A=B COLLATE binary) implies 002610 ** A=B in every other collating sequence. The requirement that the 002611 ** GROUP BY be BINARY is stricter than necessary. It would also work 002612 ** to promote HAVING clauses that use the same alternative collating 002613 ** sequence as the GROUP BY term, but that is much harder to check, 002614 ** alternative collating sequences are uncommon, and this is only an 002615 ** optimization, so we take the easy way out and simply require the 002616 ** GROUP BY to use the BINARY collating sequence. 002617 */ 002618 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){ 002619 Walker w; 002620 w.eCode = 1; 002621 w.xExprCallback = exprNodeIsConstantOrGroupBy; 002622 w.xSelectCallback = 0; 002623 w.u.pGroupBy = pGroupBy; 002624 w.pParse = pParse; 002625 sqlite3WalkExpr(&w, p); 002626 return w.eCode; 002627 } 002628 002629 /* 002630 ** Walk an expression tree for the DEFAULT field of a column definition 002631 ** in a CREATE TABLE statement. Return non-zero if the expression is 002632 ** acceptable for use as a DEFAULT. That is to say, return non-zero if 002633 ** the expression is constant or a function call with constant arguments. 002634 ** Return and 0 if there are any variables. 002635 ** 002636 ** isInit is true when parsing from sqlite_schema. isInit is false when 002637 ** processing a new CREATE TABLE statement. When isInit is true, parameters 002638 ** (such as ? or $abc) in the expression are converted into NULL. When 002639 ** isInit is false, parameters raise an error. Parameters should not be 002640 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite 002641 ** allowed it, so we need to support it when reading sqlite_schema for 002642 ** backwards compatibility. 002643 ** 002644 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node. 002645 ** 002646 ** For the purposes of this function, a double-quoted string (ex: "abc") 002647 ** is considered a variable but a single-quoted string (ex: 'abc') is 002648 ** a constant. 002649 */ 002650 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){ 002651 assert( isInit==0 || isInit==1 ); 002652 return exprIsConst(p, 4+isInit, 0); 002653 } 002654 002655 #ifdef SQLITE_ENABLE_CURSOR_HINTS 002656 /* 002657 ** Walk an expression tree. Return 1 if the expression contains a 002658 ** subquery of some kind. Return 0 if there are no subqueries. 002659 */ 002660 int sqlite3ExprContainsSubquery(Expr *p){ 002661 Walker w; 002662 w.eCode = 1; 002663 w.xExprCallback = sqlite3ExprWalkNoop; 002664 w.xSelectCallback = sqlite3SelectWalkFail; 002665 #ifdef SQLITE_DEBUG 002666 w.xSelectCallback2 = sqlite3SelectWalkAssert2; 002667 #endif 002668 sqlite3WalkExpr(&w, p); 002669 return w.eCode==0; 002670 } 002671 #endif 002672 002673 /* 002674 ** If the expression p codes a constant integer that is small enough 002675 ** to fit in a 32-bit integer, return 1 and put the value of the integer 002676 ** in *pValue. If the expression is not an integer or if it is too big 002677 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged. 002678 */ 002679 int sqlite3ExprIsInteger(const Expr *p, int *pValue){ 002680 int rc = 0; 002681 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */ 002682 002683 /* If an expression is an integer literal that fits in a signed 32-bit 002684 ** integer, then the EP_IntValue flag will have already been set */ 002685 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0 002686 || sqlite3GetInt32(p->u.zToken, &rc)==0 ); 002687 002688 if( p->flags & EP_IntValue ){ 002689 *pValue = p->u.iValue; 002690 return 1; 002691 } 002692 switch( p->op ){ 002693 case TK_UPLUS: { 002694 rc = sqlite3ExprIsInteger(p->pLeft, pValue); 002695 break; 002696 } 002697 case TK_UMINUS: { 002698 int v = 0; 002699 if( sqlite3ExprIsInteger(p->pLeft, &v) ){ 002700 assert( ((unsigned int)v)!=0x80000000 ); 002701 *pValue = -v; 002702 rc = 1; 002703 } 002704 break; 002705 } 002706 default: break; 002707 } 002708 return rc; 002709 } 002710 002711 /* 002712 ** Return FALSE if there is no chance that the expression can be NULL. 002713 ** 002714 ** If the expression might be NULL or if the expression is too complex 002715 ** to tell return TRUE. 002716 ** 002717 ** This routine is used as an optimization, to skip OP_IsNull opcodes 002718 ** when we know that a value cannot be NULL. Hence, a false positive 002719 ** (returning TRUE when in fact the expression can never be NULL) might 002720 ** be a small performance hit but is otherwise harmless. On the other 002721 ** hand, a false negative (returning FALSE when the result could be NULL) 002722 ** will likely result in an incorrect answer. So when in doubt, return 002723 ** TRUE. 002724 */ 002725 int sqlite3ExprCanBeNull(const Expr *p){ 002726 u8 op; 002727 assert( p!=0 ); 002728 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ 002729 p = p->pLeft; 002730 assert( p!=0 ); 002731 } 002732 op = p->op; 002733 if( op==TK_REGISTER ) op = p->op2; 002734 switch( op ){ 002735 case TK_INTEGER: 002736 case TK_STRING: 002737 case TK_FLOAT: 002738 case TK_BLOB: 002739 return 0; 002740 case TK_COLUMN: 002741 assert( ExprUseYTab(p) ); 002742 return ExprHasProperty(p, EP_CanBeNull) || 002743 NEVER(p->y.pTab==0) || /* Reference to column of index on expr */ 002744 (p->iColumn>=0 002745 && p->y.pTab->aCol!=0 /* Possible due to prior error */ 002746 && ALWAYS(p->iColumn<p->y.pTab->nCol) 002747 && p->y.pTab->aCol[p->iColumn].notNull==0); 002748 default: 002749 return 1; 002750 } 002751 } 002752 002753 /* 002754 ** Return TRUE if the given expression is a constant which would be 002755 ** unchanged by OP_Affinity with the affinity given in the second 002756 ** argument. 002757 ** 002758 ** This routine is used to determine if the OP_Affinity operation 002759 ** can be omitted. When in doubt return FALSE. A false negative 002760 ** is harmless. A false positive, however, can result in the wrong 002761 ** answer. 002762 */ 002763 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){ 002764 u8 op; 002765 int unaryMinus = 0; 002766 if( aff==SQLITE_AFF_BLOB ) return 1; 002767 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ 002768 if( p->op==TK_UMINUS ) unaryMinus = 1; 002769 p = p->pLeft; 002770 } 002771 op = p->op; 002772 if( op==TK_REGISTER ) op = p->op2; 002773 switch( op ){ 002774 case TK_INTEGER: { 002775 return aff>=SQLITE_AFF_NUMERIC; 002776 } 002777 case TK_FLOAT: { 002778 return aff>=SQLITE_AFF_NUMERIC; 002779 } 002780 case TK_STRING: { 002781 return !unaryMinus && aff==SQLITE_AFF_TEXT; 002782 } 002783 case TK_BLOB: { 002784 return !unaryMinus; 002785 } 002786 case TK_COLUMN: { 002787 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */ 002788 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0; 002789 } 002790 default: { 002791 return 0; 002792 } 002793 } 002794 } 002795 002796 /* 002797 ** Return TRUE if the given string is a row-id column name. 002798 */ 002799 int sqlite3IsRowid(const char *z){ 002800 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1; 002801 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1; 002802 if( sqlite3StrICmp(z, "OID")==0 ) return 1; 002803 return 0; 002804 } 002805 002806 /* 002807 ** Return a pointer to a buffer containing a usable rowid alias for table 002808 ** pTab. An alias is usable if there is not an explicit user-defined column 002809 ** of the same name. 002810 */ 002811 const char *sqlite3RowidAlias(Table *pTab){ 002812 const char *azOpt[] = {"_ROWID_", "ROWID", "OID"}; 002813 int ii; 002814 assert( VisibleRowid(pTab) ); 002815 for(ii=0; ii<ArraySize(azOpt); ii++){ 002816 int iCol; 002817 for(iCol=0; iCol<pTab->nCol; iCol++){ 002818 if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break; 002819 } 002820 if( iCol==pTab->nCol ){ 002821 return azOpt[ii]; 002822 } 002823 } 002824 return 0; 002825 } 002826 002827 /* 002828 ** pX is the RHS of an IN operator. If pX is a SELECT statement 002829 ** that can be simplified to a direct table access, then return 002830 ** a pointer to the SELECT statement. If pX is not a SELECT statement, 002831 ** or if the SELECT statement needs to be materialized into a transient 002832 ** table, then return NULL. 002833 */ 002834 #ifndef SQLITE_OMIT_SUBQUERY 002835 static Select *isCandidateForInOpt(const Expr *pX){ 002836 Select *p; 002837 SrcList *pSrc; 002838 ExprList *pEList; 002839 Table *pTab; 002840 int i; 002841 if( !ExprUseXSelect(pX) ) return 0; /* Not a subquery */ 002842 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */ 002843 p = pX->x.pSelect; 002844 if( p->pPrior ) return 0; /* Not a compound SELECT */ 002845 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){ 002846 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ); 002847 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate ); 002848 return 0; /* No DISTINCT keyword and no aggregate functions */ 002849 } 002850 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */ 002851 if( p->pLimit ) return 0; /* Has no LIMIT clause */ 002852 if( p->pWhere ) return 0; /* Has no WHERE clause */ 002853 pSrc = p->pSrc; 002854 assert( pSrc!=0 ); 002855 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */ 002856 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */ 002857 pTab = pSrc->a[0].pTab; 002858 assert( pTab!=0 ); 002859 assert( !IsView(pTab) ); /* FROM clause is not a view */ 002860 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ 002861 pEList = p->pEList; 002862 assert( pEList!=0 ); 002863 /* All SELECT results must be columns. */ 002864 for(i=0; i<pEList->nExpr; i++){ 002865 Expr *pRes = pEList->a[i].pExpr; 002866 if( pRes->op!=TK_COLUMN ) return 0; 002867 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */ 002868 } 002869 return p; 002870 } 002871 #endif /* SQLITE_OMIT_SUBQUERY */ 002872 002873 #ifndef SQLITE_OMIT_SUBQUERY 002874 /* 002875 ** Generate code that checks the left-most column of index table iCur to see if 002876 ** it contains any NULL entries. Cause the register at regHasNull to be set 002877 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull 002878 ** to be set to NULL if iCur contains one or more NULL values. 002879 */ 002880 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){ 002881 int addr1; 002882 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull); 002883 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); 002884 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull); 002885 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); 002886 VdbeComment((v, "first_entry_in(%d)", iCur)); 002887 sqlite3VdbeJumpHere(v, addr1); 002888 } 002889 #endif 002890 002891 002892 #ifndef SQLITE_OMIT_SUBQUERY 002893 /* 002894 ** The argument is an IN operator with a list (not a subquery) on the 002895 ** right-hand side. Return TRUE if that list is constant. 002896 */ 002897 static int sqlite3InRhsIsConstant(Expr *pIn){ 002898 Expr *pLHS; 002899 int res; 002900 assert( !ExprHasProperty(pIn, EP_xIsSelect) ); 002901 pLHS = pIn->pLeft; 002902 pIn->pLeft = 0; 002903 res = sqlite3ExprIsConstant(pIn); 002904 pIn->pLeft = pLHS; 002905 return res; 002906 } 002907 #endif 002908 002909 /* 002910 ** This function is used by the implementation of the IN (...) operator. 002911 ** The pX parameter is the expression on the RHS of the IN operator, which 002912 ** might be either a list of expressions or a subquery. 002913 ** 002914 ** The job of this routine is to find or create a b-tree object that can 002915 ** be used either to test for membership in the RHS set or to iterate through 002916 ** all members of the RHS set, skipping duplicates. 002917 ** 002918 ** A cursor is opened on the b-tree object that is the RHS of the IN operator 002919 ** and the *piTab parameter is set to the index of that cursor. 002920 ** 002921 ** The returned value of this function indicates the b-tree type, as follows: 002922 ** 002923 ** IN_INDEX_ROWID - The cursor was opened on a database table. 002924 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index. 002925 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index. 002926 ** IN_INDEX_EPH - The cursor was opened on a specially created and 002927 ** populated ephemeral table. 002928 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be 002929 ** implemented as a sequence of comparisons. 002930 ** 002931 ** An existing b-tree might be used if the RHS expression pX is a simple 002932 ** subquery such as: 002933 ** 002934 ** SELECT <column1>, <column2>... FROM <table> 002935 ** 002936 ** If the RHS of the IN operator is a list or a more complex subquery, then 002937 ** an ephemeral table might need to be generated from the RHS and then 002938 ** pX->iTable made to point to the ephemeral table instead of an 002939 ** existing table. In this case, the creation and initialization of the 002940 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag 002941 ** will be set on pX and the pX->y.sub fields will be set to show where 002942 ** the subroutine is coded. 002943 ** 002944 ** The inFlags parameter must contain, at a minimum, one of the bits 002945 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains 002946 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast 002947 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will 002948 ** be used to loop over all values of the RHS of the IN operator. 002949 ** 002950 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate 002951 ** through the set members) then the b-tree must not contain duplicates. 002952 ** An ephemeral table will be created unless the selected columns are guaranteed 002953 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to 002954 ** a UNIQUE constraint or index. 002955 ** 002956 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 002957 ** for fast set membership tests) then an ephemeral table must 002958 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an 002959 ** index can be found with the specified <columns> as its left-most. 002960 ** 002961 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and 002962 ** if the RHS of the IN operator is a list (not a subquery) then this 002963 ** routine might decide that creating an ephemeral b-tree for membership 002964 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the 002965 ** calling routine should implement the IN operator using a sequence 002966 ** of Eq or Ne comparison operations. 002967 ** 002968 ** When the b-tree is being used for membership tests, the calling function 002969 ** might need to know whether or not the RHS side of the IN operator 002970 ** contains a NULL. If prRhsHasNull is not a NULL pointer and 002971 ** if there is any chance that the (...) might contain a NULL value at 002972 ** runtime, then a register is allocated and the register number written 002973 ** to *prRhsHasNull. If there is no chance that the (...) contains a 002974 ** NULL value, then *prRhsHasNull is left unchanged. 002975 ** 002976 ** If a register is allocated and its location stored in *prRhsHasNull, then 002977 ** the value in that register will be NULL if the b-tree contains one or more 002978 ** NULL values, and it will be some non-NULL value if the b-tree contains no 002979 ** NULL values. 002980 ** 002981 ** If the aiMap parameter is not NULL, it must point to an array containing 002982 ** one element for each column returned by the SELECT statement on the RHS 002983 ** of the IN(...) operator. The i'th entry of the array is populated with the 002984 ** offset of the index column that matches the i'th column returned by the 002985 ** SELECT. For example, if the expression and selected index are: 002986 ** 002987 ** (?,?,?) IN (SELECT a, b, c FROM t1) 002988 ** CREATE INDEX i1 ON t1(b, c, a); 002989 ** 002990 ** then aiMap[] is populated with {2, 0, 1}. 002991 */ 002992 #ifndef SQLITE_OMIT_SUBQUERY 002993 int sqlite3FindInIndex( 002994 Parse *pParse, /* Parsing context */ 002995 Expr *pX, /* The IN expression */ 002996 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */ 002997 int *prRhsHasNull, /* Register holding NULL status. See notes */ 002998 int *aiMap, /* Mapping from Index fields to RHS fields */ 002999 int *piTab /* OUT: index to use */ 003000 ){ 003001 Select *p; /* SELECT to the right of IN operator */ 003002 int eType = 0; /* Type of RHS table. IN_INDEX_* */ 003003 int iTab; /* Cursor of the RHS table */ 003004 int mustBeUnique; /* True if RHS must be unique */ 003005 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */ 003006 003007 assert( pX->op==TK_IN ); 003008 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0; 003009 iTab = pParse->nTab++; 003010 003011 /* If the RHS of this IN(...) operator is a SELECT, and if it matters 003012 ** whether or not the SELECT result contains NULL values, check whether 003013 ** or not NULL is actually possible (it may not be, for example, due 003014 ** to NOT NULL constraints in the schema). If no NULL values are possible, 003015 ** set prRhsHasNull to 0 before continuing. */ 003016 if( prRhsHasNull && ExprUseXSelect(pX) ){ 003017 int i; 003018 ExprList *pEList = pX->x.pSelect->pEList; 003019 for(i=0; i<pEList->nExpr; i++){ 003020 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break; 003021 } 003022 if( i==pEList->nExpr ){ 003023 prRhsHasNull = 0; 003024 } 003025 } 003026 003027 /* Check to see if an existing table or index can be used to 003028 ** satisfy the query. This is preferable to generating a new 003029 ** ephemeral table. */ 003030 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){ 003031 sqlite3 *db = pParse->db; /* Database connection */ 003032 Table *pTab; /* Table <table>. */ 003033 int iDb; /* Database idx for pTab */ 003034 ExprList *pEList = p->pEList; 003035 int nExpr = pEList->nExpr; 003036 003037 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */ 003038 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */ 003039 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */ 003040 pTab = p->pSrc->a[0].pTab; 003041 003042 /* Code an OP_Transaction and OP_TableLock for <table>. */ 003043 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 003044 assert( iDb>=0 && iDb<SQLITE_MAX_DB ); 003045 sqlite3CodeVerifySchema(pParse, iDb); 003046 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 003047 003048 assert(v); /* sqlite3GetVdbe() has always been previously called */ 003049 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){ 003050 /* The "x IN (SELECT rowid FROM table)" case */ 003051 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); 003052 VdbeCoverage(v); 003053 003054 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); 003055 eType = IN_INDEX_ROWID; 003056 ExplainQueryPlan((pParse, 0, 003057 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName)); 003058 sqlite3VdbeJumpHere(v, iAddr); 003059 }else{ 003060 Index *pIdx; /* Iterator variable */ 003061 int affinity_ok = 1; 003062 int i; 003063 003064 /* Check that the affinity that will be used to perform each 003065 ** comparison is the same as the affinity of each column in table 003066 ** on the RHS of the IN operator. If it not, it is not possible to 003067 ** use any index of the RHS table. */ 003068 for(i=0; i<nExpr && affinity_ok; i++){ 003069 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); 003070 int iCol = pEList->a[i].pExpr->iColumn; 003071 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */ 003072 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff); 003073 testcase( cmpaff==SQLITE_AFF_BLOB ); 003074 testcase( cmpaff==SQLITE_AFF_TEXT ); 003075 switch( cmpaff ){ 003076 case SQLITE_AFF_BLOB: 003077 break; 003078 case SQLITE_AFF_TEXT: 003079 /* sqlite3CompareAffinity() only returns TEXT if one side or the 003080 ** other has no affinity and the other side is TEXT. Hence, 003081 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT 003082 ** and for the term on the LHS of the IN to have no affinity. */ 003083 assert( idxaff==SQLITE_AFF_TEXT ); 003084 break; 003085 default: 003086 affinity_ok = sqlite3IsNumericAffinity(idxaff); 003087 } 003088 } 003089 003090 if( affinity_ok ){ 003091 /* Search for an existing index that will work for this IN operator */ 003092 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){ 003093 Bitmask colUsed; /* Columns of the index used */ 003094 Bitmask mCol; /* Mask for the current column */ 003095 if( pIdx->nColumn<nExpr ) continue; 003096 if( pIdx->pPartIdxWhere!=0 ) continue; 003097 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute 003098 ** BITMASK(nExpr) without overflowing */ 003099 testcase( pIdx->nColumn==BMS-2 ); 003100 testcase( pIdx->nColumn==BMS-1 ); 003101 if( pIdx->nColumn>=BMS-1 ) continue; 003102 if( mustBeUnique ){ 003103 if( pIdx->nKeyCol>nExpr 003104 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx)) 003105 ){ 003106 continue; /* This index is not unique over the IN RHS columns */ 003107 } 003108 } 003109 003110 colUsed = 0; /* Columns of index used so far */ 003111 for(i=0; i<nExpr; i++){ 003112 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i); 003113 Expr *pRhs = pEList->a[i].pExpr; 003114 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs); 003115 int j; 003116 003117 for(j=0; j<nExpr; j++){ 003118 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue; 003119 assert( pIdx->azColl[j] ); 003120 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){ 003121 continue; 003122 } 003123 break; 003124 } 003125 if( j==nExpr ) break; 003126 mCol = MASKBIT(j); 003127 if( mCol & colUsed ) break; /* Each column used only once */ 003128 colUsed |= mCol; 003129 if( aiMap ) aiMap[i] = j; 003130 } 003131 003132 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) ); 003133 if( colUsed==(MASKBIT(nExpr)-1) ){ 003134 /* If we reach this point, that means the index pIdx is usable */ 003135 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 003136 ExplainQueryPlan((pParse, 0, 003137 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName)); 003138 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb); 003139 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); 003140 VdbeComment((v, "%s", pIdx->zName)); 003141 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 ); 003142 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0]; 003143 003144 if( prRhsHasNull ){ 003145 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK 003146 i64 mask = (1<<nExpr)-1; 003147 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, 003148 iTab, 0, 0, (u8*)&mask, P4_INT64); 003149 #endif 003150 *prRhsHasNull = ++pParse->nMem; 003151 if( nExpr==1 ){ 003152 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull); 003153 } 003154 } 003155 sqlite3VdbeJumpHere(v, iAddr); 003156 } 003157 } /* End loop over indexes */ 003158 } /* End if( affinity_ok ) */ 003159 } /* End if not an rowid index */ 003160 } /* End attempt to optimize using an index */ 003161 003162 /* If no preexisting index is available for the IN clause 003163 ** and IN_INDEX_NOOP is an allowed reply 003164 ** and the RHS of the IN operator is a list, not a subquery 003165 ** and the RHS is not constant or has two or fewer terms, 003166 ** then it is not worth creating an ephemeral table to evaluate 003167 ** the IN operator so return IN_INDEX_NOOP. 003168 */ 003169 if( eType==0 003170 && (inFlags & IN_INDEX_NOOP_OK) 003171 && ExprUseXList(pX) 003172 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2) 003173 ){ 003174 pParse->nTab--; /* Back out the allocation of the unused cursor */ 003175 iTab = -1; /* Cursor is not allocated */ 003176 eType = IN_INDEX_NOOP; 003177 } 003178 003179 if( eType==0 ){ 003180 /* Could not find an existing table or index to use as the RHS b-tree. 003181 ** We will have to generate an ephemeral table to do the job. 003182 */ 003183 u32 savedNQueryLoop = pParse->nQueryLoop; 003184 int rMayHaveNull = 0; 003185 eType = IN_INDEX_EPH; 003186 if( inFlags & IN_INDEX_LOOP ){ 003187 pParse->nQueryLoop = 0; 003188 }else if( prRhsHasNull ){ 003189 *prRhsHasNull = rMayHaveNull = ++pParse->nMem; 003190 } 003191 assert( pX->op==TK_IN ); 003192 sqlite3CodeRhsOfIN(pParse, pX, iTab); 003193 if( rMayHaveNull ){ 003194 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull); 003195 } 003196 pParse->nQueryLoop = savedNQueryLoop; 003197 } 003198 003199 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){ 003200 int i, n; 003201 n = sqlite3ExprVectorSize(pX->pLeft); 003202 for(i=0; i<n; i++) aiMap[i] = i; 003203 } 003204 *piTab = iTab; 003205 return eType; 003206 } 003207 #endif 003208 003209 #ifndef SQLITE_OMIT_SUBQUERY 003210 /* 003211 ** Argument pExpr is an (?, ?...) IN(...) expression. This 003212 ** function allocates and returns a nul-terminated string containing 003213 ** the affinities to be used for each column of the comparison. 003214 ** 003215 ** It is the responsibility of the caller to ensure that the returned 003216 ** string is eventually freed using sqlite3DbFree(). 003217 */ 003218 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){ 003219 Expr *pLeft = pExpr->pLeft; 003220 int nVal = sqlite3ExprVectorSize(pLeft); 003221 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0; 003222 char *zRet; 003223 003224 assert( pExpr->op==TK_IN ); 003225 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1); 003226 if( zRet ){ 003227 int i; 003228 for(i=0; i<nVal; i++){ 003229 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i); 003230 char a = sqlite3ExprAffinity(pA); 003231 if( pSelect ){ 003232 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a); 003233 }else{ 003234 zRet[i] = a; 003235 } 003236 } 003237 zRet[nVal] = '\0'; 003238 } 003239 return zRet; 003240 } 003241 #endif 003242 003243 #ifndef SQLITE_OMIT_SUBQUERY 003244 /* 003245 ** Load the Parse object passed as the first argument with an error 003246 ** message of the form: 003247 ** 003248 ** "sub-select returns N columns - expected M" 003249 */ 003250 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){ 003251 if( pParse->nErr==0 ){ 003252 const char *zFmt = "sub-select returns %d columns - expected %d"; 003253 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect); 003254 } 003255 } 003256 #endif 003257 003258 /* 003259 ** Expression pExpr is a vector that has been used in a context where 003260 ** it is not permitted. If pExpr is a sub-select vector, this routine 003261 ** loads the Parse object with a message of the form: 003262 ** 003263 ** "sub-select returns N columns - expected 1" 003264 ** 003265 ** Or, if it is a regular scalar vector: 003266 ** 003267 ** "row value misused" 003268 */ 003269 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){ 003270 #ifndef SQLITE_OMIT_SUBQUERY 003271 if( ExprUseXSelect(pExpr) ){ 003272 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1); 003273 }else 003274 #endif 003275 { 003276 sqlite3ErrorMsg(pParse, "row value misused"); 003277 } 003278 } 003279 003280 #ifndef SQLITE_OMIT_SUBQUERY 003281 /* 003282 ** Generate code that will construct an ephemeral table containing all terms 003283 ** in the RHS of an IN operator. The IN operator can be in either of two 003284 ** forms: 003285 ** 003286 ** x IN (4,5,11) -- IN operator with list on right-hand side 003287 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right 003288 ** 003289 ** The pExpr parameter is the IN operator. The cursor number for the 003290 ** constructed ephemeral table is returned. The first time the ephemeral 003291 ** table is computed, the cursor number is also stored in pExpr->iTable, 003292 ** however the cursor number returned might not be the same, as it might 003293 ** have been duplicated using OP_OpenDup. 003294 ** 003295 ** If the LHS expression ("x" in the examples) is a column value, or 003296 ** the SELECT statement returns a column value, then the affinity of that 003297 ** column is used to build the index keys. If both 'x' and the 003298 ** SELECT... statement are columns, then numeric affinity is used 003299 ** if either column has NUMERIC or INTEGER affinity. If neither 003300 ** 'x' nor the SELECT... statement are columns, then numeric affinity 003301 ** is used. 003302 */ 003303 void sqlite3CodeRhsOfIN( 003304 Parse *pParse, /* Parsing context */ 003305 Expr *pExpr, /* The IN operator */ 003306 int iTab /* Use this cursor number */ 003307 ){ 003308 int addrOnce = 0; /* Address of the OP_Once instruction at top */ 003309 int addr; /* Address of OP_OpenEphemeral instruction */ 003310 Expr *pLeft; /* the LHS of the IN operator */ 003311 KeyInfo *pKeyInfo = 0; /* Key information */ 003312 int nVal; /* Size of vector pLeft */ 003313 Vdbe *v; /* The prepared statement under construction */ 003314 003315 v = pParse->pVdbe; 003316 assert( v!=0 ); 003317 003318 /* The evaluation of the IN must be repeated every time it 003319 ** is encountered if any of the following is true: 003320 ** 003321 ** * The right-hand side is a correlated subquery 003322 ** * The right-hand side is an expression list containing variables 003323 ** * We are inside a trigger 003324 ** 003325 ** If all of the above are false, then we can compute the RHS just once 003326 ** and reuse it many names. 003327 */ 003328 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){ 003329 /* Reuse of the RHS is allowed */ 003330 /* If this routine has already been coded, but the previous code 003331 ** might not have been invoked yet, so invoke it now as a subroutine. 003332 */ 003333 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 003334 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 003335 if( ExprUseXSelect(pExpr) ){ 003336 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d", 003337 pExpr->x.pSelect->selId)); 003338 } 003339 assert( ExprUseYSub(pExpr) ); 003340 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 003341 pExpr->y.sub.iAddr); 003342 assert( iTab!=pExpr->iTable ); 003343 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable); 003344 sqlite3VdbeJumpHere(v, addrOnce); 003345 return; 003346 } 003347 003348 /* Begin coding the subroutine */ 003349 assert( !ExprUseYWin(pExpr) ); 003350 ExprSetProperty(pExpr, EP_Subrtn); 003351 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 003352 pExpr->y.sub.regReturn = ++pParse->nMem; 003353 pExpr->y.sub.iAddr = 003354 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1; 003355 003356 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 003357 } 003358 003359 /* Check to see if this is a vector IN operator */ 003360 pLeft = pExpr->pLeft; 003361 nVal = sqlite3ExprVectorSize(pLeft); 003362 003363 /* Construct the ephemeral table that will contain the content of 003364 ** RHS of the IN operator. 003365 */ 003366 pExpr->iTable = iTab; 003367 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal); 003368 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS 003369 if( ExprUseXSelect(pExpr) ){ 003370 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId)); 003371 }else{ 003372 VdbeComment((v, "RHS of IN operator")); 003373 } 003374 #endif 003375 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1); 003376 003377 if( ExprUseXSelect(pExpr) ){ 003378 /* Case 1: expr IN (SELECT ...) 003379 ** 003380 ** Generate code to write the results of the select into the temporary 003381 ** table allocated and opened above. 003382 */ 003383 Select *pSelect = pExpr->x.pSelect; 003384 ExprList *pEList = pSelect->pEList; 003385 003386 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d", 003387 addrOnce?"":"CORRELATED ", pSelect->selId 003388 )); 003389 /* If the LHS and RHS of the IN operator do not match, that 003390 ** error will have been caught long before we reach this point. */ 003391 if( ALWAYS(pEList->nExpr==nVal) ){ 003392 Select *pCopy; 003393 SelectDest dest; 003394 int i; 003395 int rc; 003396 sqlite3SelectDestInit(&dest, SRT_Set, iTab); 003397 dest.zAffSdst = exprINAffinity(pParse, pExpr); 003398 pSelect->iLimit = 0; 003399 testcase( pSelect->selFlags & SF_Distinct ); 003400 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */ 003401 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0); 003402 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest); 003403 sqlite3SelectDelete(pParse->db, pCopy); 003404 sqlite3DbFree(pParse->db, dest.zAffSdst); 003405 if( rc ){ 003406 sqlite3KeyInfoUnref(pKeyInfo); 003407 return; 003408 } 003409 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */ 003410 assert( pEList!=0 ); 003411 assert( pEList->nExpr>0 ); 003412 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 003413 for(i=0; i<nVal; i++){ 003414 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i); 003415 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq( 003416 pParse, p, pEList->a[i].pExpr 003417 ); 003418 } 003419 } 003420 }else if( ALWAYS(pExpr->x.pList!=0) ){ 003421 /* Case 2: expr IN (exprlist) 003422 ** 003423 ** For each expression, build an index key from the evaluation and 003424 ** store it in the temporary table. If <expr> is a column, then use 003425 ** that columns affinity when building index keys. If <expr> is not 003426 ** a column, use numeric affinity. 003427 */ 003428 char affinity; /* Affinity of the LHS of the IN */ 003429 int i; 003430 ExprList *pList = pExpr->x.pList; 003431 struct ExprList_item *pItem; 003432 int r1, r2; 003433 affinity = sqlite3ExprAffinity(pLeft); 003434 if( affinity<=SQLITE_AFF_NONE ){ 003435 affinity = SQLITE_AFF_BLOB; 003436 }else if( affinity==SQLITE_AFF_REAL ){ 003437 affinity = SQLITE_AFF_NUMERIC; 003438 } 003439 if( pKeyInfo ){ 003440 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) ); 003441 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 003442 } 003443 003444 /* Loop through each expression in <exprlist>. */ 003445 r1 = sqlite3GetTempReg(pParse); 003446 r2 = sqlite3GetTempReg(pParse); 003447 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ 003448 Expr *pE2 = pItem->pExpr; 003449 003450 /* If the expression is not constant then we will need to 003451 ** disable the test that was generated above that makes sure 003452 ** this code only executes once. Because for a non-constant 003453 ** expression we need to rerun this code each time. 003454 */ 003455 if( addrOnce && !sqlite3ExprIsConstant(pE2) ){ 003456 sqlite3VdbeChangeToNoop(v, addrOnce-1); 003457 sqlite3VdbeChangeToNoop(v, addrOnce); 003458 ExprClearProperty(pExpr, EP_Subrtn); 003459 addrOnce = 0; 003460 } 003461 003462 /* Evaluate the expression and insert it into the temp table */ 003463 sqlite3ExprCode(pParse, pE2, r1); 003464 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1); 003465 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1); 003466 } 003467 sqlite3ReleaseTempReg(pParse, r1); 003468 sqlite3ReleaseTempReg(pParse, r2); 003469 } 003470 if( pKeyInfo ){ 003471 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO); 003472 } 003473 if( addrOnce ){ 003474 sqlite3VdbeAddOp1(v, OP_NullRow, iTab); 003475 sqlite3VdbeJumpHere(v, addrOnce); 003476 /* Subroutine return */ 003477 assert( ExprUseYSub(pExpr) ); 003478 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn 003479 || pParse->nErr ); 003480 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn, 003481 pExpr->y.sub.iAddr, 1); 003482 VdbeCoverage(v); 003483 sqlite3ClearTempRegCache(pParse); 003484 } 003485 } 003486 #endif /* SQLITE_OMIT_SUBQUERY */ 003487 003488 /* 003489 ** Generate code for scalar subqueries used as a subquery expression 003490 ** or EXISTS operator: 003491 ** 003492 ** (SELECT a FROM b) -- subquery 003493 ** EXISTS (SELECT a FROM b) -- EXISTS subquery 003494 ** 003495 ** The pExpr parameter is the SELECT or EXISTS operator to be coded. 003496 ** 003497 ** Return the register that holds the result. For a multi-column SELECT, 003498 ** the result is stored in a contiguous array of registers and the 003499 ** return value is the register of the left-most result column. 003500 ** Return 0 if an error occurs. 003501 */ 003502 #ifndef SQLITE_OMIT_SUBQUERY 003503 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ 003504 int addrOnce = 0; /* Address of OP_Once at top of subroutine */ 003505 int rReg = 0; /* Register storing resulting */ 003506 Select *pSel; /* SELECT statement to encode */ 003507 SelectDest dest; /* How to deal with SELECT result */ 003508 int nReg; /* Registers to allocate */ 003509 Expr *pLimit; /* New limit expression */ 003510 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 003511 int addrExplain; /* Address of OP_Explain instruction */ 003512 #endif 003513 003514 Vdbe *v = pParse->pVdbe; 003515 assert( v!=0 ); 003516 if( pParse->nErr ) return 0; 003517 testcase( pExpr->op==TK_EXISTS ); 003518 testcase( pExpr->op==TK_SELECT ); 003519 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT ); 003520 assert( ExprUseXSelect(pExpr) ); 003521 pSel = pExpr->x.pSelect; 003522 003523 /* If this routine has already been coded, then invoke it as a 003524 ** subroutine. */ 003525 if( ExprHasProperty(pExpr, EP_Subrtn) ){ 003526 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId)); 003527 assert( ExprUseYSub(pExpr) ); 003528 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn, 003529 pExpr->y.sub.iAddr); 003530 return pExpr->iTable; 003531 } 003532 003533 /* Begin coding the subroutine */ 003534 assert( !ExprUseYWin(pExpr) ); 003535 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) ); 003536 ExprSetProperty(pExpr, EP_Subrtn); 003537 pExpr->y.sub.regReturn = ++pParse->nMem; 003538 pExpr->y.sub.iAddr = 003539 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1; 003540 003541 /* The evaluation of the EXISTS/SELECT must be repeated every time it 003542 ** is encountered if any of the following is true: 003543 ** 003544 ** * The right-hand side is a correlated subquery 003545 ** * The right-hand side is an expression list containing variables 003546 ** * We are inside a trigger 003547 ** 003548 ** If all of the above are false, then we can run this code just once 003549 ** save the results, and reuse the same result on subsequent invocations. 003550 */ 003551 if( !ExprHasProperty(pExpr, EP_VarSelect) ){ 003552 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 003553 } 003554 003555 /* For a SELECT, generate code to put the values for all columns of 003556 ** the first row into an array of registers and return the index of 003557 ** the first register. 003558 ** 003559 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists) 003560 ** into a register and return that register number. 003561 ** 003562 ** In both cases, the query is augmented with "LIMIT 1". Any 003563 ** preexisting limit is discarded in place of the new LIMIT 1. 003564 */ 003565 ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d", 003566 addrOnce?"":"CORRELATED ", pSel->selId)); 003567 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1); 003568 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1; 003569 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1); 003570 pParse->nMem += nReg; 003571 if( pExpr->op==TK_SELECT ){ 003572 dest.eDest = SRT_Mem; 003573 dest.iSdst = dest.iSDParm; 003574 dest.nSdst = nReg; 003575 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1); 003576 VdbeComment((v, "Init subquery result")); 003577 }else{ 003578 dest.eDest = SRT_Exists; 003579 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm); 003580 VdbeComment((v, "Init EXISTS result")); 003581 } 003582 if( pSel->pLimit ){ 003583 /* The subquery already has a limit. If the pre-existing limit is X 003584 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */ 003585 sqlite3 *db = pParse->db; 003586 pLimit = sqlite3Expr(db, TK_INTEGER, "0"); 003587 if( pLimit ){ 003588 pLimit->affExpr = SQLITE_AFF_NUMERIC; 003589 pLimit = sqlite3PExpr(pParse, TK_NE, 003590 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit); 003591 } 003592 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft); 003593 pSel->pLimit->pLeft = pLimit; 003594 }else{ 003595 /* If there is no pre-existing limit add a limit of 1 */ 003596 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1"); 003597 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0); 003598 } 003599 pSel->iLimit = 0; 003600 if( sqlite3Select(pParse, pSel, &dest) ){ 003601 pExpr->op2 = pExpr->op; 003602 pExpr->op = TK_ERROR; 003603 return 0; 003604 } 003605 pExpr->iTable = rReg = dest.iSDParm; 003606 ExprSetVVAProperty(pExpr, EP_NoReduce); 003607 if( addrOnce ){ 003608 sqlite3VdbeJumpHere(v, addrOnce); 003609 } 003610 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1); 003611 003612 /* Subroutine return */ 003613 assert( ExprUseYSub(pExpr) ); 003614 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn 003615 || pParse->nErr ); 003616 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn, 003617 pExpr->y.sub.iAddr, 1); 003618 VdbeCoverage(v); 003619 sqlite3ClearTempRegCache(pParse); 003620 return rReg; 003621 } 003622 #endif /* SQLITE_OMIT_SUBQUERY */ 003623 003624 #ifndef SQLITE_OMIT_SUBQUERY 003625 /* 003626 ** Expr pIn is an IN(...) expression. This function checks that the 003627 ** sub-select on the RHS of the IN() operator has the same number of 003628 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not 003629 ** a sub-query, that the LHS is a vector of size 1. 003630 */ 003631 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){ 003632 int nVector = sqlite3ExprVectorSize(pIn->pLeft); 003633 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){ 003634 if( nVector!=pIn->x.pSelect->pEList->nExpr ){ 003635 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector); 003636 return 1; 003637 } 003638 }else if( nVector!=1 ){ 003639 sqlite3VectorErrorMsg(pParse, pIn->pLeft); 003640 return 1; 003641 } 003642 return 0; 003643 } 003644 #endif 003645 003646 #ifndef SQLITE_OMIT_SUBQUERY 003647 /* 003648 ** Generate code for an IN expression. 003649 ** 003650 ** x IN (SELECT ...) 003651 ** x IN (value, value, ...) 003652 ** 003653 ** The left-hand side (LHS) is a scalar or vector expression. The 003654 ** right-hand side (RHS) is an array of zero or more scalar values, or a 003655 ** subquery. If the RHS is a subquery, the number of result columns must 003656 ** match the number of columns in the vector on the LHS. If the RHS is 003657 ** a list of values, the LHS must be a scalar. 003658 ** 003659 ** The IN operator is true if the LHS value is contained within the RHS. 003660 ** The result is false if the LHS is definitely not in the RHS. The 003661 ** result is NULL if the presence of the LHS in the RHS cannot be 003662 ** determined due to NULLs. 003663 ** 003664 ** This routine generates code that jumps to destIfFalse if the LHS is not 003665 ** contained within the RHS. If due to NULLs we cannot determine if the LHS 003666 ** is contained in the RHS then jump to destIfNull. If the LHS is contained 003667 ** within the RHS then fall through. 003668 ** 003669 ** See the separate in-operator.md documentation file in the canonical 003670 ** SQLite source tree for additional information. 003671 */ 003672 static void sqlite3ExprCodeIN( 003673 Parse *pParse, /* Parsing and code generating context */ 003674 Expr *pExpr, /* The IN expression */ 003675 int destIfFalse, /* Jump here if LHS is not contained in the RHS */ 003676 int destIfNull /* Jump here if the results are unknown due to NULLs */ 003677 ){ 003678 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */ 003679 int eType; /* Type of the RHS */ 003680 int rLhs; /* Register(s) holding the LHS values */ 003681 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */ 003682 Vdbe *v; /* Statement under construction */ 003683 int *aiMap = 0; /* Map from vector field to index column */ 003684 char *zAff = 0; /* Affinity string for comparisons */ 003685 int nVector; /* Size of vectors for this IN operator */ 003686 int iDummy; /* Dummy parameter to exprCodeVector() */ 003687 Expr *pLeft; /* The LHS of the IN operator */ 003688 int i; /* loop counter */ 003689 int destStep2; /* Where to jump when NULLs seen in step 2 */ 003690 int destStep6 = 0; /* Start of code for Step 6 */ 003691 int addrTruthOp; /* Address of opcode that determines the IN is true */ 003692 int destNotNull; /* Jump here if a comparison is not true in step 6 */ 003693 int addrTop; /* Top of the step-6 loop */ 003694 int iTab = 0; /* Index to use */ 003695 u8 okConstFactor = pParse->okConstFactor; 003696 003697 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 003698 pLeft = pExpr->pLeft; 003699 if( sqlite3ExprCheckIN(pParse, pExpr) ) return; 003700 zAff = exprINAffinity(pParse, pExpr); 003701 nVector = sqlite3ExprVectorSize(pExpr->pLeft); 003702 aiMap = (int*)sqlite3DbMallocZero( 003703 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1 003704 ); 003705 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error; 003706 003707 /* Attempt to compute the RHS. After this step, if anything other than 003708 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab 003709 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned, 003710 ** the RHS has not yet been coded. */ 003711 v = pParse->pVdbe; 003712 assert( v!=0 ); /* OOM detected prior to this routine */ 003713 VdbeNoopComment((v, "begin IN expr")); 003714 eType = sqlite3FindInIndex(pParse, pExpr, 003715 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK, 003716 destIfFalse==destIfNull ? 0 : &rRhsHasNull, 003717 aiMap, &iTab); 003718 003719 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH 003720 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC 003721 ); 003722 #ifdef SQLITE_DEBUG 003723 /* Confirm that aiMap[] contains nVector integer values between 0 and 003724 ** nVector-1. */ 003725 for(i=0; i<nVector; i++){ 003726 int j, cnt; 003727 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++; 003728 assert( cnt==1 ); 003729 } 003730 #endif 003731 003732 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a 003733 ** vector, then it is stored in an array of nVector registers starting 003734 ** at r1. 003735 ** 003736 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector 003737 ** so that the fields are in the same order as an existing index. The 003738 ** aiMap[] array contains a mapping from the original LHS field order to 003739 ** the field order that matches the RHS index. 003740 ** 003741 ** Avoid factoring the LHS of the IN(...) expression out of the loop, 003742 ** even if it is constant, as OP_Affinity may be used on the register 003743 ** by code generated below. */ 003744 assert( pParse->okConstFactor==okConstFactor ); 003745 pParse->okConstFactor = 0; 003746 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy); 003747 pParse->okConstFactor = okConstFactor; 003748 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */ 003749 if( i==nVector ){ 003750 /* LHS fields are not reordered */ 003751 rLhs = rLhsOrig; 003752 }else{ 003753 /* Need to reorder the LHS fields according to aiMap */ 003754 rLhs = sqlite3GetTempRange(pParse, nVector); 003755 for(i=0; i<nVector; i++){ 003756 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0); 003757 } 003758 } 003759 003760 /* If sqlite3FindInIndex() did not find or create an index that is 003761 ** suitable for evaluating the IN operator, then evaluate using a 003762 ** sequence of comparisons. 003763 ** 003764 ** This is step (1) in the in-operator.md optimized algorithm. 003765 */ 003766 if( eType==IN_INDEX_NOOP ){ 003767 ExprList *pList; 003768 CollSeq *pColl; 003769 int labelOk = sqlite3VdbeMakeLabel(pParse); 003770 int r2, regToFree; 003771 int regCkNull = 0; 003772 int ii; 003773 assert( ExprUseXList(pExpr) ); 003774 pList = pExpr->x.pList; 003775 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft); 003776 if( destIfNull!=destIfFalse ){ 003777 regCkNull = sqlite3GetTempReg(pParse); 003778 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull); 003779 } 003780 for(ii=0; ii<pList->nExpr; ii++){ 003781 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree); 003782 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){ 003783 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull); 003784 } 003785 sqlite3ReleaseTempReg(pParse, regToFree); 003786 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){ 003787 int op = rLhs!=r2 ? OP_Eq : OP_NotNull; 003788 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2, 003789 (void*)pColl, P4_COLLSEQ); 003790 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq); 003791 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq); 003792 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull); 003793 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull); 003794 sqlite3VdbeChangeP5(v, zAff[0]); 003795 }else{ 003796 int op = rLhs!=r2 ? OP_Ne : OP_IsNull; 003797 assert( destIfNull==destIfFalse ); 003798 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2, 003799 (void*)pColl, P4_COLLSEQ); 003800 VdbeCoverageIf(v, op==OP_Ne); 003801 VdbeCoverageIf(v, op==OP_IsNull); 003802 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL); 003803 } 003804 } 003805 if( regCkNull ){ 003806 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v); 003807 sqlite3VdbeGoto(v, destIfFalse); 003808 } 003809 sqlite3VdbeResolveLabel(v, labelOk); 003810 sqlite3ReleaseTempReg(pParse, regCkNull); 003811 goto sqlite3ExprCodeIN_finished; 003812 } 003813 003814 /* Step 2: Check to see if the LHS contains any NULL columns. If the 003815 ** LHS does contain NULLs then the result must be either FALSE or NULL. 003816 ** We will then skip the binary search of the RHS. 003817 */ 003818 if( destIfNull==destIfFalse ){ 003819 destStep2 = destIfFalse; 003820 }else{ 003821 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse); 003822 } 003823 for(i=0; i<nVector; i++){ 003824 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i); 003825 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error; 003826 if( sqlite3ExprCanBeNull(p) ){ 003827 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2); 003828 VdbeCoverage(v); 003829 } 003830 } 003831 003832 /* Step 3. The LHS is now known to be non-NULL. Do the binary search 003833 ** of the RHS using the LHS as a probe. If found, the result is 003834 ** true. 003835 */ 003836 if( eType==IN_INDEX_ROWID ){ 003837 /* In this case, the RHS is the ROWID of table b-tree and so we also 003838 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4 003839 ** into a single opcode. */ 003840 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs); 003841 VdbeCoverage(v); 003842 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */ 003843 }else{ 003844 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector); 003845 if( destIfFalse==destIfNull ){ 003846 /* Combine Step 3 and Step 5 into a single opcode */ 003847 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse, 003848 rLhs, nVector); VdbeCoverage(v); 003849 goto sqlite3ExprCodeIN_finished; 003850 } 003851 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */ 003852 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0, 003853 rLhs, nVector); VdbeCoverage(v); 003854 } 003855 003856 /* Step 4. If the RHS is known to be non-NULL and we did not find 003857 ** an match on the search above, then the result must be FALSE. 003858 */ 003859 if( rRhsHasNull && nVector==1 ){ 003860 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse); 003861 VdbeCoverage(v); 003862 } 003863 003864 /* Step 5. If we do not care about the difference between NULL and 003865 ** FALSE, then just return false. 003866 */ 003867 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse); 003868 003869 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS. 003870 ** If any comparison is NULL, then the result is NULL. If all 003871 ** comparisons are FALSE then the final result is FALSE. 003872 ** 003873 ** For a scalar LHS, it is sufficient to check just the first row 003874 ** of the RHS. 003875 */ 003876 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6); 003877 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse); 003878 VdbeCoverage(v); 003879 if( nVector>1 ){ 003880 destNotNull = sqlite3VdbeMakeLabel(pParse); 003881 }else{ 003882 /* For nVector==1, combine steps 6 and 7 by immediately returning 003883 ** FALSE if the first comparison is not NULL */ 003884 destNotNull = destIfFalse; 003885 } 003886 for(i=0; i<nVector; i++){ 003887 Expr *p; 003888 CollSeq *pColl; 003889 int r3 = sqlite3GetTempReg(pParse); 003890 p = sqlite3VectorFieldSubexpr(pLeft, i); 003891 pColl = sqlite3ExprCollSeq(pParse, p); 003892 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3); 003893 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3, 003894 (void*)pColl, P4_COLLSEQ); 003895 VdbeCoverage(v); 003896 sqlite3ReleaseTempReg(pParse, r3); 003897 } 003898 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull); 003899 if( nVector>1 ){ 003900 sqlite3VdbeResolveLabel(v, destNotNull); 003901 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1); 003902 VdbeCoverage(v); 003903 003904 /* Step 7: If we reach this point, we know that the result must 003905 ** be false. */ 003906 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse); 003907 } 003908 003909 /* Jumps here in order to return true. */ 003910 sqlite3VdbeJumpHere(v, addrTruthOp); 003911 003912 sqlite3ExprCodeIN_finished: 003913 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs); 003914 VdbeComment((v, "end IN expr")); 003915 sqlite3ExprCodeIN_oom_error: 003916 sqlite3DbFree(pParse->db, aiMap); 003917 sqlite3DbFree(pParse->db, zAff); 003918 } 003919 #endif /* SQLITE_OMIT_SUBQUERY */ 003920 003921 #ifndef SQLITE_OMIT_FLOATING_POINT 003922 /* 003923 ** Generate an instruction that will put the floating point 003924 ** value described by z[0..n-1] into register iMem. 003925 ** 003926 ** The z[] string will probably not be zero-terminated. But the 003927 ** z[n] character is guaranteed to be something that does not look 003928 ** like the continuation of the number. 003929 */ 003930 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){ 003931 if( ALWAYS(z!=0) ){ 003932 double value; 003933 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8); 003934 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */ 003935 if( negateFlag ) value = -value; 003936 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL); 003937 } 003938 } 003939 #endif 003940 003941 003942 /* 003943 ** Generate an instruction that will put the integer describe by 003944 ** text z[0..n-1] into register iMem. 003945 ** 003946 ** Expr.u.zToken is always UTF8 and zero-terminated. 003947 */ 003948 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){ 003949 Vdbe *v = pParse->pVdbe; 003950 if( pExpr->flags & EP_IntValue ){ 003951 int i = pExpr->u.iValue; 003952 assert( i>=0 ); 003953 if( negFlag ) i = -i; 003954 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); 003955 }else{ 003956 int c; 003957 i64 value; 003958 const char *z = pExpr->u.zToken; 003959 assert( z!=0 ); 003960 c = sqlite3DecOrHexToI64(z, &value); 003961 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){ 003962 #ifdef SQLITE_OMIT_FLOATING_POINT 003963 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr); 003964 #else 003965 #ifndef SQLITE_OMIT_HEX_INTEGER 003966 if( sqlite3_strnicmp(z,"0x",2)==0 ){ 003967 sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T", 003968 negFlag?"-":"",pExpr); 003969 }else 003970 #endif 003971 { 003972 codeReal(v, z, negFlag, iMem); 003973 } 003974 #endif 003975 }else{ 003976 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; } 003977 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64); 003978 } 003979 } 003980 } 003981 003982 003983 /* Generate code that will load into register regOut a value that is 003984 ** appropriate for the iIdxCol-th column of index pIdx. 003985 */ 003986 void sqlite3ExprCodeLoadIndexColumn( 003987 Parse *pParse, /* The parsing context */ 003988 Index *pIdx, /* The index whose column is to be loaded */ 003989 int iTabCur, /* Cursor pointing to a table row */ 003990 int iIdxCol, /* The column of the index to be loaded */ 003991 int regOut /* Store the index column value in this register */ 003992 ){ 003993 i16 iTabCol = pIdx->aiColumn[iIdxCol]; 003994 if( iTabCol==XN_EXPR ){ 003995 assert( pIdx->aColExpr ); 003996 assert( pIdx->aColExpr->nExpr>iIdxCol ); 003997 pParse->iSelfTab = iTabCur + 1; 003998 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut); 003999 pParse->iSelfTab = 0; 004000 }else{ 004001 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur, 004002 iTabCol, regOut); 004003 } 004004 } 004005 004006 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 004007 /* 004008 ** Generate code that will compute the value of generated column pCol 004009 ** and store the result in register regOut 004010 */ 004011 void sqlite3ExprCodeGeneratedColumn( 004012 Parse *pParse, /* Parsing context */ 004013 Table *pTab, /* Table containing the generated column */ 004014 Column *pCol, /* The generated column */ 004015 int regOut /* Put the result in this register */ 004016 ){ 004017 int iAddr; 004018 Vdbe *v = pParse->pVdbe; 004019 int nErr = pParse->nErr; 004020 assert( v!=0 ); 004021 assert( pParse->iSelfTab!=0 ); 004022 if( pParse->iSelfTab>0 ){ 004023 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut); 004024 }else{ 004025 iAddr = 0; 004026 } 004027 sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut); 004028 if( pCol->affinity>=SQLITE_AFF_TEXT ){ 004029 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1); 004030 } 004031 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr); 004032 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1; 004033 } 004034 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 004035 004036 /* 004037 ** Generate code to extract the value of the iCol-th column of a table. 004038 */ 004039 void sqlite3ExprCodeGetColumnOfTable( 004040 Vdbe *v, /* Parsing context */ 004041 Table *pTab, /* The table containing the value */ 004042 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */ 004043 int iCol, /* Index of the column to extract */ 004044 int regOut /* Extract the value into this register */ 004045 ){ 004046 Column *pCol; 004047 assert( v!=0 ); 004048 assert( pTab!=0 ); 004049 assert( iCol!=XN_EXPR ); 004050 if( iCol<0 || iCol==pTab->iPKey ){ 004051 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut); 004052 VdbeComment((v, "%s.rowid", pTab->zName)); 004053 }else{ 004054 int op; 004055 int x; 004056 if( IsVirtual(pTab) ){ 004057 op = OP_VColumn; 004058 x = iCol; 004059 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 004060 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){ 004061 Parse *pParse = sqlite3VdbeParser(v); 004062 if( pCol->colFlags & COLFLAG_BUSY ){ 004063 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", 004064 pCol->zCnName); 004065 }else{ 004066 int savedSelfTab = pParse->iSelfTab; 004067 pCol->colFlags |= COLFLAG_BUSY; 004068 pParse->iSelfTab = iTabCur+1; 004069 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut); 004070 pParse->iSelfTab = savedSelfTab; 004071 pCol->colFlags &= ~COLFLAG_BUSY; 004072 } 004073 return; 004074 #endif 004075 }else if( !HasRowid(pTab) ){ 004076 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) ); 004077 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol); 004078 op = OP_Column; 004079 }else{ 004080 x = sqlite3TableColumnToStorage(pTab,iCol); 004081 testcase( x!=iCol ); 004082 op = OP_Column; 004083 } 004084 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut); 004085 sqlite3ColumnDefault(v, pTab, iCol, regOut); 004086 } 004087 } 004088 004089 /* 004090 ** Generate code that will extract the iColumn-th column from 004091 ** table pTab and store the column value in register iReg. 004092 ** 004093 ** There must be an open cursor to pTab in iTable when this routine 004094 ** is called. If iColumn<0 then code is generated that extracts the rowid. 004095 */ 004096 int sqlite3ExprCodeGetColumn( 004097 Parse *pParse, /* Parsing and code generating context */ 004098 Table *pTab, /* Description of the table we are reading from */ 004099 int iColumn, /* Index of the table column */ 004100 int iTable, /* The cursor pointing to the table */ 004101 int iReg, /* Store results here */ 004102 u8 p5 /* P5 value for OP_Column + FLAGS */ 004103 ){ 004104 assert( pParse->pVdbe!=0 ); 004105 assert( (p5 & (OPFLAG_NOCHNG|OPFLAG_TYPEOFARG|OPFLAG_LENGTHARG))==p5 ); 004106 assert( IsVirtual(pTab) || (p5 & OPFLAG_NOCHNG)==0 ); 004107 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg); 004108 if( p5 ){ 004109 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe); 004110 if( pOp->opcode==OP_Column ) pOp->p5 = p5; 004111 if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG); 004112 } 004113 return iReg; 004114 } 004115 004116 /* 004117 ** Generate code to move content from registers iFrom...iFrom+nReg-1 004118 ** over to iTo..iTo+nReg-1. 004119 */ 004120 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ 004121 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); 004122 } 004123 004124 /* 004125 ** Convert a scalar expression node to a TK_REGISTER referencing 004126 ** register iReg. The caller must ensure that iReg already contains 004127 ** the correct value for the expression. 004128 */ 004129 static void exprToRegister(Expr *pExpr, int iReg){ 004130 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr); 004131 if( NEVER(p==0) ) return; 004132 p->op2 = p->op; 004133 p->op = TK_REGISTER; 004134 p->iTable = iReg; 004135 ExprClearProperty(p, EP_Skip); 004136 } 004137 004138 /* 004139 ** Evaluate an expression (either a vector or a scalar expression) and store 004140 ** the result in contiguous temporary registers. Return the index of 004141 ** the first register used to store the result. 004142 ** 004143 ** If the returned result register is a temporary scalar, then also write 004144 ** that register number into *piFreeable. If the returned result register 004145 ** is not a temporary or if the expression is a vector set *piFreeable 004146 ** to 0. 004147 */ 004148 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){ 004149 int iResult; 004150 int nResult = sqlite3ExprVectorSize(p); 004151 if( nResult==1 ){ 004152 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable); 004153 }else{ 004154 *piFreeable = 0; 004155 if( p->op==TK_SELECT ){ 004156 #if SQLITE_OMIT_SUBQUERY 004157 iResult = 0; 004158 #else 004159 iResult = sqlite3CodeSubselect(pParse, p); 004160 #endif 004161 }else{ 004162 int i; 004163 iResult = pParse->nMem+1; 004164 pParse->nMem += nResult; 004165 assert( ExprUseXList(p) ); 004166 for(i=0; i<nResult; i++){ 004167 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult); 004168 } 004169 } 004170 } 004171 return iResult; 004172 } 004173 004174 /* 004175 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5) 004176 ** so that a subsequent copy will not be merged into this one. 004177 */ 004178 static void setDoNotMergeFlagOnCopy(Vdbe *v){ 004179 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){ 004180 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergeable */ 004181 } 004182 } 004183 004184 /* 004185 ** Generate code to implement special SQL functions that are implemented 004186 ** in-line rather than by using the usual callbacks. 004187 */ 004188 static int exprCodeInlineFunction( 004189 Parse *pParse, /* Parsing context */ 004190 ExprList *pFarg, /* List of function arguments */ 004191 int iFuncId, /* Function ID. One of the INTFUNC_... values */ 004192 int target /* Store function result in this register */ 004193 ){ 004194 int nFarg; 004195 Vdbe *v = pParse->pVdbe; 004196 assert( v!=0 ); 004197 assert( pFarg!=0 ); 004198 nFarg = pFarg->nExpr; 004199 assert( nFarg>0 ); /* All in-line functions have at least one argument */ 004200 switch( iFuncId ){ 004201 case INLINEFUNC_coalesce: { 004202 /* Attempt a direct implementation of the built-in COALESCE() and 004203 ** IFNULL() functions. This avoids unnecessary evaluation of 004204 ** arguments past the first non-NULL argument. 004205 */ 004206 int endCoalesce = sqlite3VdbeMakeLabel(pParse); 004207 int i; 004208 assert( nFarg>=2 ); 004209 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target); 004210 for(i=1; i<nFarg; i++){ 004211 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce); 004212 VdbeCoverage(v); 004213 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target); 004214 } 004215 setDoNotMergeFlagOnCopy(v); 004216 sqlite3VdbeResolveLabel(v, endCoalesce); 004217 break; 004218 } 004219 case INLINEFUNC_iif: { 004220 Expr caseExpr; 004221 memset(&caseExpr, 0, sizeof(caseExpr)); 004222 caseExpr.op = TK_CASE; 004223 caseExpr.x.pList = pFarg; 004224 return sqlite3ExprCodeTarget(pParse, &caseExpr, target); 004225 } 004226 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC 004227 case INLINEFUNC_sqlite_offset: { 004228 Expr *pArg = pFarg->a[0].pExpr; 004229 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){ 004230 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target); 004231 }else{ 004232 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 004233 } 004234 break; 004235 } 004236 #endif 004237 default: { 004238 /* The UNLIKELY() function is a no-op. The result is the value 004239 ** of the first argument. 004240 */ 004241 assert( nFarg==1 || nFarg==2 ); 004242 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target); 004243 break; 004244 } 004245 004246 /*********************************************************************** 004247 ** Test-only SQL functions that are only usable if enabled 004248 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 004249 */ 004250 #if !defined(SQLITE_UNTESTABLE) 004251 case INLINEFUNC_expr_compare: { 004252 /* Compare two expressions using sqlite3ExprCompare() */ 004253 assert( nFarg==2 ); 004254 sqlite3VdbeAddOp2(v, OP_Integer, 004255 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), 004256 target); 004257 break; 004258 } 004259 004260 case INLINEFUNC_expr_implies_expr: { 004261 /* Compare two expressions using sqlite3ExprImpliesExpr() */ 004262 assert( nFarg==2 ); 004263 sqlite3VdbeAddOp2(v, OP_Integer, 004264 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1), 004265 target); 004266 break; 004267 } 004268 004269 case INLINEFUNC_implies_nonnull_row: { 004270 /* Result of sqlite3ExprImpliesNonNullRow() */ 004271 Expr *pA1; 004272 assert( nFarg==2 ); 004273 pA1 = pFarg->a[1].pExpr; 004274 if( pA1->op==TK_COLUMN ){ 004275 sqlite3VdbeAddOp2(v, OP_Integer, 004276 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1), 004277 target); 004278 }else{ 004279 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 004280 } 004281 break; 004282 } 004283 004284 case INLINEFUNC_affinity: { 004285 /* The AFFINITY() function evaluates to a string that describes 004286 ** the type affinity of the argument. This is used for testing of 004287 ** the SQLite type logic. 004288 */ 004289 const char *azAff[] = { "blob", "text", "numeric", "integer", 004290 "real", "flexnum" }; 004291 char aff; 004292 assert( nFarg==1 ); 004293 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr); 004294 assert( aff<=SQLITE_AFF_NONE 004295 || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) ); 004296 sqlite3VdbeLoadString(v, target, 004297 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]); 004298 break; 004299 } 004300 #endif /* !defined(SQLITE_UNTESTABLE) */ 004301 } 004302 return target; 004303 } 004304 004305 /* 004306 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr. 004307 ** If it is, then resolve the expression by reading from the index and 004308 ** return the register into which the value has been read. If pExpr is 004309 ** not an indexed expression, then return negative. 004310 */ 004311 static SQLITE_NOINLINE int sqlite3IndexedExprLookup( 004312 Parse *pParse, /* The parsing context */ 004313 Expr *pExpr, /* The expression to potentially bypass */ 004314 int target /* Where to store the result of the expression */ 004315 ){ 004316 IndexedExpr *p; 004317 Vdbe *v; 004318 for(p=pParse->pIdxEpr; p; p=p->pIENext){ 004319 u8 exprAff; 004320 int iDataCur = p->iDataCur; 004321 if( iDataCur<0 ) continue; 004322 if( pParse->iSelfTab ){ 004323 if( p->iDataCur!=pParse->iSelfTab-1 ) continue; 004324 iDataCur = -1; 004325 } 004326 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue; 004327 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC ); 004328 exprAff = sqlite3ExprAffinity(pExpr); 004329 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB) 004330 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT) 004331 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC) 004332 ){ 004333 /* Affinity mismatch on a generated column */ 004334 continue; 004335 } 004336 004337 v = pParse->pVdbe; 004338 assert( v!=0 ); 004339 if( p->bMaybeNullRow ){ 004340 /* If the index is on a NULL row due to an outer join, then we 004341 ** cannot extract the value from the index. The value must be 004342 ** computed using the original expression. */ 004343 int addr = sqlite3VdbeCurrentAddr(v); 004344 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target); 004345 VdbeCoverage(v); 004346 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target); 004347 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol)); 004348 sqlite3VdbeGoto(v, 0); 004349 p = pParse->pIdxEpr; 004350 pParse->pIdxEpr = 0; 004351 sqlite3ExprCode(pParse, pExpr, target); 004352 pParse->pIdxEpr = p; 004353 sqlite3VdbeJumpHere(v, addr+2); 004354 }else{ 004355 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target); 004356 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol)); 004357 } 004358 return target; 004359 } 004360 return -1; /* Not found */ 004361 } 004362 004363 004364 /* 004365 ** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This 004366 ** function checks the Parse.pIdxPartExpr list to see if this column 004367 ** can be replaced with a constant value. If so, it generates code to 004368 ** put the constant value in a register (ideally, but not necessarily, 004369 ** register iTarget) and returns the register number. 004370 ** 004371 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is 004372 ** returned. 004373 */ 004374 static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){ 004375 IndexedExpr *p; 004376 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){ 004377 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){ 004378 Vdbe *v = pParse->pVdbe; 004379 int addr = 0; 004380 int ret; 004381 004382 if( p->bMaybeNullRow ){ 004383 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur); 004384 } 004385 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget); 004386 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0, 004387 (const char*)&p->aff, 1); 004388 if( addr ){ 004389 sqlite3VdbeJumpHere(v, addr); 004390 sqlite3VdbeChangeP3(v, addr, ret); 004391 } 004392 return ret; 004393 } 004394 } 004395 return 0; 004396 } 004397 004398 004399 /* 004400 ** Generate code into the current Vdbe to evaluate the given 004401 ** expression. Attempt to store the results in register "target". 004402 ** Return the register where results are stored. 004403 ** 004404 ** With this routine, there is no guarantee that results will 004405 ** be stored in target. The result might be stored in some other 004406 ** register if it is convenient to do so. The calling function 004407 ** must check the return code and move the results to the desired 004408 ** register. 004409 */ 004410 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ 004411 Vdbe *v = pParse->pVdbe; /* The VM under construction */ 004412 int op; /* The opcode being coded */ 004413 int inReg = target; /* Results stored in register inReg */ 004414 int regFree1 = 0; /* If non-zero free this temporary register */ 004415 int regFree2 = 0; /* If non-zero free this temporary register */ 004416 int r1, r2; /* Various register numbers */ 004417 Expr tempX; /* Temporary expression node */ 004418 int p5 = 0; 004419 004420 assert( target>0 && target<=pParse->nMem ); 004421 assert( v!=0 ); 004422 004423 expr_code_doover: 004424 if( pExpr==0 ){ 004425 op = TK_NULL; 004426 }else if( pParse->pIdxEpr!=0 004427 && !ExprHasProperty(pExpr, EP_Leaf) 004428 && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0 004429 ){ 004430 return r1; 004431 }else{ 004432 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 004433 op = pExpr->op; 004434 } 004435 assert( op!=TK_ORDER ); 004436 switch( op ){ 004437 case TK_AGG_COLUMN: { 004438 AggInfo *pAggInfo = pExpr->pAggInfo; 004439 struct AggInfo_col *pCol; 004440 assert( pAggInfo!=0 ); 004441 assert( pExpr->iAgg>=0 ); 004442 if( pExpr->iAgg>=pAggInfo->nColumn ){ 004443 /* Happens when the left table of a RIGHT JOIN is null and 004444 ** is using an expression index */ 004445 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 004446 #ifdef SQLITE_VDBE_COVERAGE 004447 /* Verify that the OP_Null above is exercised by tests 004448 ** tag-20230325-2 */ 004449 sqlite3VdbeAddOp3(v, OP_NotNull, target, 1, 20230325); 004450 VdbeCoverageNeverTaken(v); 004451 #endif 004452 break; 004453 } 004454 pCol = &pAggInfo->aCol[pExpr->iAgg]; 004455 if( !pAggInfo->directMode ){ 004456 return AggInfoColumnReg(pAggInfo, pExpr->iAgg); 004457 }else if( pAggInfo->useSortingIdx ){ 004458 Table *pTab = pCol->pTab; 004459 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, 004460 pCol->iSorterColumn, target); 004461 if( pTab==0 ){ 004462 /* No comment added */ 004463 }else if( pCol->iColumn<0 ){ 004464 VdbeComment((v,"%s.rowid",pTab->zName)); 004465 }else{ 004466 VdbeComment((v,"%s.%s", 004467 pTab->zName, pTab->aCol[pCol->iColumn].zCnName)); 004468 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){ 004469 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 004470 } 004471 } 004472 return target; 004473 }else if( pExpr->y.pTab==0 ){ 004474 /* This case happens when the argument to an aggregate function 004475 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */ 004476 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target); 004477 return target; 004478 } 004479 /* Otherwise, fall thru into the TK_COLUMN case */ 004480 /* no break */ deliberate_fall_through 004481 } 004482 case TK_COLUMN: { 004483 int iTab = pExpr->iTable; 004484 int iReg; 004485 if( ExprHasProperty(pExpr, EP_FixedCol) ){ 004486 /* This COLUMN expression is really a constant due to WHERE clause 004487 ** constraints, and that constant is coded by the pExpr->pLeft 004488 ** expression. However, make sure the constant has the correct 004489 ** datatype by applying the Affinity of the table column to the 004490 ** constant. 004491 */ 004492 int aff; 004493 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target); 004494 assert( ExprUseYTab(pExpr) ); 004495 assert( pExpr->y.pTab!=0 ); 004496 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn); 004497 if( aff>SQLITE_AFF_BLOB ){ 004498 static const char zAff[] = "B\000C\000D\000E\000F"; 004499 assert( SQLITE_AFF_BLOB=='A' ); 004500 assert( SQLITE_AFF_TEXT=='B' ); 004501 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0, 004502 &zAff[(aff-'B')*2], P4_STATIC); 004503 } 004504 return iReg; 004505 } 004506 if( iTab<0 ){ 004507 if( pParse->iSelfTab<0 ){ 004508 /* Other columns in the same row for CHECK constraints or 004509 ** generated columns or for inserting into partial index. 004510 ** The row is unpacked into registers beginning at 004511 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register 004512 ** immediately prior to the first column. 004513 */ 004514 Column *pCol; 004515 Table *pTab; 004516 int iSrc; 004517 int iCol = pExpr->iColumn; 004518 assert( ExprUseYTab(pExpr) ); 004519 pTab = pExpr->y.pTab; 004520 assert( pTab!=0 ); 004521 assert( iCol>=XN_ROWID ); 004522 assert( iCol<pTab->nCol ); 004523 if( iCol<0 ){ 004524 return -1-pParse->iSelfTab; 004525 } 004526 pCol = pTab->aCol + iCol; 004527 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) ); 004528 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab; 004529 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 004530 if( pCol->colFlags & COLFLAG_GENERATED ){ 004531 if( pCol->colFlags & COLFLAG_BUSY ){ 004532 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", 004533 pCol->zCnName); 004534 return 0; 004535 } 004536 pCol->colFlags |= COLFLAG_BUSY; 004537 if( pCol->colFlags & COLFLAG_NOTAVAIL ){ 004538 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc); 004539 } 004540 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL); 004541 return iSrc; 004542 }else 004543 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 004544 if( pCol->affinity==SQLITE_AFF_REAL ){ 004545 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target); 004546 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 004547 return target; 004548 }else{ 004549 return iSrc; 004550 } 004551 }else{ 004552 /* Coding an expression that is part of an index where column names 004553 ** in the index refer to the table to which the index belongs */ 004554 iTab = pParse->iSelfTab - 1; 004555 } 004556 } 004557 else if( pParse->pIdxPartExpr 004558 && 0!=(r1 = exprPartidxExprLookup(pParse, pExpr, target)) 004559 ){ 004560 return r1; 004561 } 004562 assert( ExprUseYTab(pExpr) ); 004563 assert( pExpr->y.pTab!=0 ); 004564 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab, 004565 pExpr->iColumn, iTab, target, 004566 pExpr->op2); 004567 return iReg; 004568 } 004569 case TK_INTEGER: { 004570 codeInteger(pParse, pExpr, 0, target); 004571 return target; 004572 } 004573 case TK_TRUEFALSE: { 004574 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target); 004575 return target; 004576 } 004577 #ifndef SQLITE_OMIT_FLOATING_POINT 004578 case TK_FLOAT: { 004579 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004580 codeReal(v, pExpr->u.zToken, 0, target); 004581 return target; 004582 } 004583 #endif 004584 case TK_STRING: { 004585 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004586 sqlite3VdbeLoadString(v, target, pExpr->u.zToken); 004587 return target; 004588 } 004589 default: { 004590 /* Make NULL the default case so that if a bug causes an illegal 004591 ** Expr node to be passed into this function, it will be handled 004592 ** sanely and not crash. But keep the assert() to bring the problem 004593 ** to the attention of the developers. */ 004594 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed ); 004595 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 004596 return target; 004597 } 004598 #ifndef SQLITE_OMIT_BLOB_LITERAL 004599 case TK_BLOB: { 004600 int n; 004601 const char *z; 004602 char *zBlob; 004603 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004604 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' ); 004605 assert( pExpr->u.zToken[1]=='\'' ); 004606 z = &pExpr->u.zToken[2]; 004607 n = sqlite3Strlen30(z) - 1; 004608 assert( z[n]=='\'' ); 004609 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); 004610 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); 004611 return target; 004612 } 004613 #endif 004614 case TK_VARIABLE: { 004615 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004616 assert( pExpr->u.zToken!=0 ); 004617 assert( pExpr->u.zToken[0]!=0 ); 004618 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target); 004619 if( pExpr->u.zToken[1]!=0 ){ 004620 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn); 004621 assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) ); 004622 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */ 004623 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC); 004624 } 004625 return target; 004626 } 004627 case TK_REGISTER: { 004628 return pExpr->iTable; 004629 } 004630 #ifndef SQLITE_OMIT_CAST 004631 case TK_CAST: { 004632 /* Expressions of the form: CAST(pLeft AS token) */ 004633 sqlite3ExprCode(pParse, pExpr->pLeft, target); 004634 assert( inReg==target ); 004635 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004636 sqlite3VdbeAddOp2(v, OP_Cast, target, 004637 sqlite3AffinityType(pExpr->u.zToken, 0)); 004638 return inReg; 004639 } 004640 #endif /* SQLITE_OMIT_CAST */ 004641 case TK_IS: 004642 case TK_ISNOT: 004643 op = (op==TK_IS) ? TK_EQ : TK_NE; 004644 p5 = SQLITE_NULLEQ; 004645 /* fall-through */ 004646 case TK_LT: 004647 case TK_LE: 004648 case TK_GT: 004649 case TK_GE: 004650 case TK_NE: 004651 case TK_EQ: { 004652 Expr *pLeft = pExpr->pLeft; 004653 if( sqlite3ExprIsVector(pLeft) ){ 004654 codeVectorCompare(pParse, pExpr, target, op, p5); 004655 }else{ 004656 r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); 004657 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 004658 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg); 004659 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2, 004660 sqlite3VdbeCurrentAddr(v)+2, p5, 004661 ExprHasProperty(pExpr,EP_Commuted)); 004662 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 004663 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 004664 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 004665 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 004666 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq); 004667 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne); 004668 if( p5==SQLITE_NULLEQ ){ 004669 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg); 004670 }else{ 004671 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2); 004672 } 004673 testcase( regFree1==0 ); 004674 testcase( regFree2==0 ); 004675 } 004676 break; 004677 } 004678 case TK_AND: 004679 case TK_OR: 004680 case TK_PLUS: 004681 case TK_STAR: 004682 case TK_MINUS: 004683 case TK_REM: 004684 case TK_BITAND: 004685 case TK_BITOR: 004686 case TK_SLASH: 004687 case TK_LSHIFT: 004688 case TK_RSHIFT: 004689 case TK_CONCAT: { 004690 assert( TK_AND==OP_And ); testcase( op==TK_AND ); 004691 assert( TK_OR==OP_Or ); testcase( op==TK_OR ); 004692 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS ); 004693 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS ); 004694 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM ); 004695 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND ); 004696 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR ); 004697 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH ); 004698 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT ); 004699 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT ); 004700 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT ); 004701 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 004702 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 004703 sqlite3VdbeAddOp3(v, op, r2, r1, target); 004704 testcase( regFree1==0 ); 004705 testcase( regFree2==0 ); 004706 break; 004707 } 004708 case TK_UMINUS: { 004709 Expr *pLeft = pExpr->pLeft; 004710 assert( pLeft ); 004711 if( pLeft->op==TK_INTEGER ){ 004712 codeInteger(pParse, pLeft, 1, target); 004713 return target; 004714 #ifndef SQLITE_OMIT_FLOATING_POINT 004715 }else if( pLeft->op==TK_FLOAT ){ 004716 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004717 codeReal(v, pLeft->u.zToken, 1, target); 004718 return target; 004719 #endif 004720 }else{ 004721 tempX.op = TK_INTEGER; 004722 tempX.flags = EP_IntValue|EP_TokenOnly; 004723 tempX.u.iValue = 0; 004724 ExprClearVVAProperties(&tempX); 004725 r1 = sqlite3ExprCodeTemp(pParse, &tempX, ®Free1); 004726 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); 004727 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); 004728 testcase( regFree2==0 ); 004729 } 004730 break; 004731 } 004732 case TK_BITNOT: 004733 case TK_NOT: { 004734 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT ); 004735 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT ); 004736 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 004737 testcase( regFree1==0 ); 004738 sqlite3VdbeAddOp2(v, op, r1, inReg); 004739 break; 004740 } 004741 case TK_TRUTH: { 004742 int isTrue; /* IS TRUE or IS NOT TRUE */ 004743 int bNormal; /* IS TRUE or IS FALSE */ 004744 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 004745 testcase( regFree1==0 ); 004746 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 004747 bNormal = pExpr->op2==TK_IS; 004748 testcase( isTrue && bNormal); 004749 testcase( !isTrue && bNormal); 004750 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal); 004751 break; 004752 } 004753 case TK_ISNULL: 004754 case TK_NOTNULL: { 004755 int addr; 004756 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 004757 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 004758 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 004759 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 004760 testcase( regFree1==0 ); 004761 addr = sqlite3VdbeAddOp1(v, op, r1); 004762 VdbeCoverageIf(v, op==TK_ISNULL); 004763 VdbeCoverageIf(v, op==TK_NOTNULL); 004764 sqlite3VdbeAddOp2(v, OP_Integer, 0, target); 004765 sqlite3VdbeJumpHere(v, addr); 004766 break; 004767 } 004768 case TK_AGG_FUNCTION: { 004769 AggInfo *pInfo = pExpr->pAggInfo; 004770 if( pInfo==0 004771 || NEVER(pExpr->iAgg<0) 004772 || NEVER(pExpr->iAgg>=pInfo->nFunc) 004773 ){ 004774 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004775 sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr); 004776 }else{ 004777 return AggInfoFuncReg(pInfo, pExpr->iAgg); 004778 } 004779 break; 004780 } 004781 case TK_FUNCTION: { 004782 ExprList *pFarg; /* List of function arguments */ 004783 int nFarg; /* Number of function arguments */ 004784 FuncDef *pDef; /* The function definition object */ 004785 const char *zId; /* The function name */ 004786 u32 constMask = 0; /* Mask of function arguments that are constant */ 004787 int i; /* Loop counter */ 004788 sqlite3 *db = pParse->db; /* The database connection */ 004789 u8 enc = ENC(db); /* The text encoding used by this database */ 004790 CollSeq *pColl = 0; /* A collating sequence */ 004791 004792 #ifndef SQLITE_OMIT_WINDOWFUNC 004793 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 004794 return pExpr->y.pWin->regResult; 004795 } 004796 #endif 004797 004798 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){ 004799 /* SQL functions can be expensive. So try to avoid running them 004800 ** multiple times if we know they always give the same result */ 004801 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); 004802 } 004803 assert( !ExprHasProperty(pExpr, EP_TokenOnly) ); 004804 assert( ExprUseXList(pExpr) ); 004805 pFarg = pExpr->x.pList; 004806 nFarg = pFarg ? pFarg->nExpr : 0; 004807 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 004808 zId = pExpr->u.zToken; 004809 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0); 004810 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION 004811 if( pDef==0 && pParse->explain ){ 004812 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0); 004813 } 004814 #endif 004815 if( pDef==0 || pDef->xFinalize!=0 ){ 004816 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr); 004817 break; 004818 } 004819 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){ 004820 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 ); 004821 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 ); 004822 return exprCodeInlineFunction(pParse, pFarg, 004823 SQLITE_PTR_TO_INT(pDef->pUserData), target); 004824 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){ 004825 sqlite3ExprFunctionUsable(pParse, pExpr, pDef); 004826 } 004827 004828 for(i=0; i<nFarg; i++){ 004829 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){ 004830 testcase( i==31 ); 004831 constMask |= MASKBIT32(i); 004832 } 004833 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){ 004834 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr); 004835 } 004836 } 004837 if( pFarg ){ 004838 if( constMask ){ 004839 r1 = pParse->nMem+1; 004840 pParse->nMem += nFarg; 004841 }else{ 004842 r1 = sqlite3GetTempRange(pParse, nFarg); 004843 } 004844 004845 /* For length() and typeof() and octet_length() functions, 004846 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG 004847 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid 004848 ** unnecessary data loading. 004849 */ 004850 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){ 004851 u8 exprOp; 004852 assert( nFarg==1 ); 004853 assert( pFarg->a[0].pExpr!=0 ); 004854 exprOp = pFarg->a[0].pExpr->op; 004855 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){ 004856 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG ); 004857 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG ); 004858 assert( SQLITE_FUNC_BYTELEN==OPFLAG_BYTELENARG ); 004859 assert( (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG)==OPFLAG_BYTELENARG ); 004860 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG ); 004861 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG ); 004862 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG); 004863 pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG; 004864 } 004865 } 004866 004867 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_FACTOR); 004868 }else{ 004869 r1 = 0; 004870 } 004871 #ifndef SQLITE_OMIT_VIRTUALTABLE 004872 /* Possibly overload the function if the first argument is 004873 ** a virtual table column. 004874 ** 004875 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the 004876 ** second argument, not the first, as the argument to test to 004877 ** see if it is a column in a virtual table. This is done because 004878 ** the left operand of infix functions (the operand we want to 004879 ** control overloading) ends up as the second argument to the 004880 ** function. The expression "A glob B" is equivalent to 004881 ** "glob(B,A). We want to use the A in "A glob B" to test 004882 ** for function overloading. But we use the B term in "glob(B,A)". 004883 */ 004884 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){ 004885 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr); 004886 }else if( nFarg>0 ){ 004887 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr); 004888 } 004889 #endif 004890 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){ 004891 if( !pColl ) pColl = db->pDfltColl; 004892 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); 004893 } 004894 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg, 004895 pDef, pExpr->op2); 004896 if( nFarg ){ 004897 if( constMask==0 ){ 004898 sqlite3ReleaseTempRange(pParse, r1, nFarg); 004899 }else{ 004900 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1); 004901 } 004902 } 004903 return target; 004904 } 004905 #ifndef SQLITE_OMIT_SUBQUERY 004906 case TK_EXISTS: 004907 case TK_SELECT: { 004908 int nCol; 004909 testcase( op==TK_EXISTS ); 004910 testcase( op==TK_SELECT ); 004911 if( pParse->db->mallocFailed ){ 004912 return 0; 004913 }else if( op==TK_SELECT 004914 && ALWAYS( ExprUseXSelect(pExpr) ) 004915 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 004916 ){ 004917 sqlite3SubselectError(pParse, nCol, 1); 004918 }else{ 004919 return sqlite3CodeSubselect(pParse, pExpr); 004920 } 004921 break; 004922 } 004923 case TK_SELECT_COLUMN: { 004924 int n; 004925 Expr *pLeft = pExpr->pLeft; 004926 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){ 004927 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft); 004928 pLeft->op2 = pParse->withinRJSubrtn; 004929 } 004930 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR ); 004931 n = sqlite3ExprVectorSize(pLeft); 004932 if( pExpr->iTable!=n ){ 004933 sqlite3ErrorMsg(pParse, "%d columns assigned %d values", 004934 pExpr->iTable, n); 004935 } 004936 return pLeft->iTable + pExpr->iColumn; 004937 } 004938 case TK_IN: { 004939 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 004940 int destIfNull = sqlite3VdbeMakeLabel(pParse); 004941 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 004942 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 004943 sqlite3VdbeAddOp2(v, OP_Integer, 1, target); 004944 sqlite3VdbeResolveLabel(v, destIfFalse); 004945 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0); 004946 sqlite3VdbeResolveLabel(v, destIfNull); 004947 return target; 004948 } 004949 #endif /* SQLITE_OMIT_SUBQUERY */ 004950 004951 004952 /* 004953 ** x BETWEEN y AND z 004954 ** 004955 ** This is equivalent to 004956 ** 004957 ** x>=y AND x<=z 004958 ** 004959 ** X is stored in pExpr->pLeft. 004960 ** Y is stored in pExpr->pList->a[0].pExpr. 004961 ** Z is stored in pExpr->pList->a[1].pExpr. 004962 */ 004963 case TK_BETWEEN: { 004964 exprCodeBetween(pParse, pExpr, target, 0, 0); 004965 return target; 004966 } 004967 case TK_COLLATE: { 004968 if( !ExprHasProperty(pExpr, EP_Collate) ){ 004969 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called 004970 ** "SOFT-COLLATE" that is added to constraints that are pushed down 004971 ** from outer queries into sub-queries by the push-down optimization. 004972 ** Clear subtypes as subtypes may not cross a subquery boundary. 004973 */ 004974 assert( pExpr->pLeft ); 004975 sqlite3ExprCode(pParse, pExpr->pLeft, target); 004976 sqlite3VdbeAddOp1(v, OP_ClrSubtype, target); 004977 return target; 004978 }else{ 004979 pExpr = pExpr->pLeft; 004980 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */ 004981 } 004982 } 004983 case TK_SPAN: 004984 case TK_UPLUS: { 004985 pExpr = pExpr->pLeft; 004986 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */ 004987 } 004988 004989 case TK_TRIGGER: { 004990 /* If the opcode is TK_TRIGGER, then the expression is a reference 004991 ** to a column in the new.* or old.* pseudo-tables available to 004992 ** trigger programs. In this case Expr.iTable is set to 1 for the 004993 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn 004994 ** is set to the column of the pseudo-table to read, or to -1 to 004995 ** read the rowid field. 004996 ** 004997 ** The expression is implemented using an OP_Param opcode. The p1 004998 ** parameter is set to 0 for an old.rowid reference, or to (i+1) 004999 ** to reference another column of the old.* pseudo-table, where 005000 ** i is the index of the column. For a new.rowid reference, p1 is 005001 ** set to (n+1), where n is the number of columns in each pseudo-table. 005002 ** For a reference to any other column in the new.* pseudo-table, p1 005003 ** is set to (n+2+i), where n and i are as defined previously. For 005004 ** example, if the table on which triggers are being fired is 005005 ** declared as: 005006 ** 005007 ** CREATE TABLE t1(a, b); 005008 ** 005009 ** Then p1 is interpreted as follows: 005010 ** 005011 ** p1==0 -> old.rowid p1==3 -> new.rowid 005012 ** p1==1 -> old.a p1==4 -> new.a 005013 ** p1==2 -> old.b p1==5 -> new.b 005014 */ 005015 Table *pTab; 005016 int iCol; 005017 int p1; 005018 005019 assert( ExprUseYTab(pExpr) ); 005020 pTab = pExpr->y.pTab; 005021 iCol = pExpr->iColumn; 005022 p1 = pExpr->iTable * (pTab->nCol+1) + 1 005023 + sqlite3TableColumnToStorage(pTab, iCol); 005024 005025 assert( pExpr->iTable==0 || pExpr->iTable==1 ); 005026 assert( iCol>=-1 && iCol<pTab->nCol ); 005027 assert( pTab->iPKey<0 || iCol!=pTab->iPKey ); 005028 assert( p1>=0 && p1<(pTab->nCol*2+2) ); 005029 005030 sqlite3VdbeAddOp2(v, OP_Param, p1, target); 005031 VdbeComment((v, "r[%d]=%s.%s", target, 005032 (pExpr->iTable ? "new" : "old"), 005033 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName) 005034 )); 005035 005036 #ifndef SQLITE_OMIT_FLOATING_POINT 005037 /* If the column has REAL affinity, it may currently be stored as an 005038 ** integer. Use OP_RealAffinity to make sure it is really real. 005039 ** 005040 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to 005041 ** floating point when extracting it from the record. */ 005042 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){ 005043 sqlite3VdbeAddOp1(v, OP_RealAffinity, target); 005044 } 005045 #endif 005046 break; 005047 } 005048 005049 case TK_VECTOR: { 005050 sqlite3ErrorMsg(pParse, "row value misused"); 005051 break; 005052 } 005053 005054 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions 005055 ** that derive from the right-hand table of a LEFT JOIN. The 005056 ** Expr.iTable value is the table number for the right-hand table. 005057 ** The expression is only evaluated if that table is not currently 005058 ** on a LEFT JOIN NULL row. 005059 */ 005060 case TK_IF_NULL_ROW: { 005061 int addrINR; 005062 u8 okConstFactor = pParse->okConstFactor; 005063 AggInfo *pAggInfo = pExpr->pAggInfo; 005064 if( pAggInfo ){ 005065 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn ); 005066 if( !pAggInfo->directMode ){ 005067 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg); 005068 break; 005069 } 005070 if( pExpr->pAggInfo->useSortingIdx ){ 005071 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab, 005072 pAggInfo->aCol[pExpr->iAgg].iSorterColumn, 005073 target); 005074 inReg = target; 005075 break; 005076 } 005077 } 005078 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target); 005079 /* The OP_IfNullRow opcode above can overwrite the result register with 005080 ** NULL. So we have to ensure that the result register is not a value 005081 ** that is suppose to be a constant. Two defenses are needed: 005082 ** (1) Temporarily disable factoring of constant expressions 005083 ** (2) Make sure the computed value really is stored in register 005084 ** "target" and not someplace else. 005085 */ 005086 pParse->okConstFactor = 0; /* note (1) above */ 005087 sqlite3ExprCode(pParse, pExpr->pLeft, target); 005088 assert( target==inReg ); 005089 pParse->okConstFactor = okConstFactor; 005090 sqlite3VdbeJumpHere(v, addrINR); 005091 break; 005092 } 005093 005094 /* 005095 ** Form A: 005096 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 005097 ** 005098 ** Form B: 005099 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END 005100 ** 005101 ** Form A is can be transformed into the equivalent form B as follows: 005102 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... 005103 ** WHEN x=eN THEN rN ELSE y END 005104 ** 005105 ** X (if it exists) is in pExpr->pLeft. 005106 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is 005107 ** odd. The Y is also optional. If the number of elements in x.pList 005108 ** is even, then Y is omitted and the "otherwise" result is NULL. 005109 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. 005110 ** 005111 ** The result of the expression is the Ri for the first matching Ei, 005112 ** or if there is no matching Ei, the ELSE term Y, or if there is 005113 ** no ELSE term, NULL. 005114 */ 005115 case TK_CASE: { 005116 int endLabel; /* GOTO label for end of CASE stmt */ 005117 int nextCase; /* GOTO label for next WHEN clause */ 005118 int nExpr; /* 2x number of WHEN terms */ 005119 int i; /* Loop counter */ 005120 ExprList *pEList; /* List of WHEN terms */ 005121 struct ExprList_item *aListelem; /* Array of WHEN terms */ 005122 Expr opCompare; /* The X==Ei expression */ 005123 Expr *pX; /* The X expression */ 005124 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */ 005125 Expr *pDel = 0; 005126 sqlite3 *db = pParse->db; 005127 005128 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 ); 005129 assert(pExpr->x.pList->nExpr > 0); 005130 pEList = pExpr->x.pList; 005131 aListelem = pEList->a; 005132 nExpr = pEList->nExpr; 005133 endLabel = sqlite3VdbeMakeLabel(pParse); 005134 if( (pX = pExpr->pLeft)!=0 ){ 005135 pDel = sqlite3ExprDup(db, pX, 0); 005136 if( db->mallocFailed ){ 005137 sqlite3ExprDelete(db, pDel); 005138 break; 005139 } 005140 testcase( pX->op==TK_COLUMN ); 005141 exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 005142 testcase( regFree1==0 ); 005143 memset(&opCompare, 0, sizeof(opCompare)); 005144 opCompare.op = TK_EQ; 005145 opCompare.pLeft = pDel; 005146 pTest = &opCompare; 005147 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001: 005148 ** The value in regFree1 might get SCopy-ed into the file result. 005149 ** So make sure that the regFree1 register is not reused for other 005150 ** purposes and possibly overwritten. */ 005151 regFree1 = 0; 005152 } 005153 for(i=0; i<nExpr-1; i=i+2){ 005154 if( pX ){ 005155 assert( pTest!=0 ); 005156 opCompare.pRight = aListelem[i].pExpr; 005157 }else{ 005158 pTest = aListelem[i].pExpr; 005159 } 005160 nextCase = sqlite3VdbeMakeLabel(pParse); 005161 testcase( pTest->op==TK_COLUMN ); 005162 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); 005163 testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); 005164 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); 005165 sqlite3VdbeGoto(v, endLabel); 005166 sqlite3VdbeResolveLabel(v, nextCase); 005167 } 005168 if( (nExpr&1)!=0 ){ 005169 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target); 005170 }else{ 005171 sqlite3VdbeAddOp2(v, OP_Null, 0, target); 005172 } 005173 sqlite3ExprDelete(db, pDel); 005174 setDoNotMergeFlagOnCopy(v); 005175 sqlite3VdbeResolveLabel(v, endLabel); 005176 break; 005177 } 005178 #ifndef SQLITE_OMIT_TRIGGER 005179 case TK_RAISE: { 005180 assert( pExpr->affExpr==OE_Rollback 005181 || pExpr->affExpr==OE_Abort 005182 || pExpr->affExpr==OE_Fail 005183 || pExpr->affExpr==OE_Ignore 005184 ); 005185 if( !pParse->pTriggerTab && !pParse->nested ){ 005186 sqlite3ErrorMsg(pParse, 005187 "RAISE() may only be used within a trigger-program"); 005188 return 0; 005189 } 005190 if( pExpr->affExpr==OE_Abort ){ 005191 sqlite3MayAbort(pParse); 005192 } 005193 assert( !ExprHasProperty(pExpr, EP_IntValue) ); 005194 if( pExpr->affExpr==OE_Ignore ){ 005195 sqlite3VdbeAddOp4( 005196 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0); 005197 VdbeCoverage(v); 005198 }else{ 005199 sqlite3HaltConstraint(pParse, 005200 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR, 005201 pExpr->affExpr, pExpr->u.zToken, 0, 0); 005202 } 005203 005204 break; 005205 } 005206 #endif 005207 } 005208 sqlite3ReleaseTempReg(pParse, regFree1); 005209 sqlite3ReleaseTempReg(pParse, regFree2); 005210 return inReg; 005211 } 005212 005213 /* 005214 ** Generate code that will evaluate expression pExpr just one time 005215 ** per prepared statement execution. 005216 ** 005217 ** If the expression uses functions (that might throw an exception) then 005218 ** guard them with an OP_Once opcode to ensure that the code is only executed 005219 ** once. If no functions are involved, then factor the code out and put it at 005220 ** the end of the prepared statement in the initialization section. 005221 ** 005222 ** If regDest>0 then the result is always stored in that register and the 005223 ** result is not reusable. If regDest<0 then this routine is free to 005224 ** store the value wherever it wants. The register where the expression 005225 ** is stored is returned. When regDest<0, two identical expressions might 005226 ** code to the same register, if they do not contain function calls and hence 005227 ** are factored out into the initialization section at the end of the 005228 ** prepared statement. 005229 */ 005230 int sqlite3ExprCodeRunJustOnce( 005231 Parse *pParse, /* Parsing context */ 005232 Expr *pExpr, /* The expression to code when the VDBE initializes */ 005233 int regDest /* Store the value in this register */ 005234 ){ 005235 ExprList *p; 005236 assert( ConstFactorOk(pParse) ); 005237 assert( regDest!=0 ); 005238 p = pParse->pConstExpr; 005239 if( regDest<0 && p ){ 005240 struct ExprList_item *pItem; 005241 int i; 005242 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){ 005243 if( pItem->fg.reusable 005244 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 005245 ){ 005246 return pItem->u.iConstExprReg; 005247 } 005248 } 005249 } 005250 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0); 005251 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){ 005252 Vdbe *v = pParse->pVdbe; 005253 int addr; 005254 assert( v ); 005255 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v); 005256 pParse->okConstFactor = 0; 005257 if( !pParse->db->mallocFailed ){ 005258 if( regDest<0 ) regDest = ++pParse->nMem; 005259 sqlite3ExprCode(pParse, pExpr, regDest); 005260 } 005261 pParse->okConstFactor = 1; 005262 sqlite3ExprDelete(pParse->db, pExpr); 005263 sqlite3VdbeJumpHere(v, addr); 005264 }else{ 005265 p = sqlite3ExprListAppend(pParse, p, pExpr); 005266 if( p ){ 005267 struct ExprList_item *pItem = &p->a[p->nExpr-1]; 005268 pItem->fg.reusable = regDest<0; 005269 if( regDest<0 ) regDest = ++pParse->nMem; 005270 pItem->u.iConstExprReg = regDest; 005271 } 005272 pParse->pConstExpr = p; 005273 } 005274 return regDest; 005275 } 005276 005277 /* 005278 ** Generate code to evaluate an expression and store the results 005279 ** into a register. Return the register number where the results 005280 ** are stored. 005281 ** 005282 ** If the register is a temporary register that can be deallocated, 005283 ** then write its number into *pReg. If the result register is not 005284 ** a temporary, then set *pReg to zero. 005285 ** 005286 ** If pExpr is a constant, then this routine might generate this 005287 ** code to fill the register in the initialization section of the 005288 ** VDBE program, in order to factor it out of the evaluation loop. 005289 */ 005290 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ 005291 int r2; 005292 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr); 005293 if( ConstFactorOk(pParse) 005294 && ALWAYS(pExpr!=0) 005295 && pExpr->op!=TK_REGISTER 005296 && sqlite3ExprIsConstantNotJoin(pExpr) 005297 ){ 005298 *pReg = 0; 005299 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1); 005300 }else{ 005301 int r1 = sqlite3GetTempReg(pParse); 005302 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); 005303 if( r2==r1 ){ 005304 *pReg = r1; 005305 }else{ 005306 sqlite3ReleaseTempReg(pParse, r1); 005307 *pReg = 0; 005308 } 005309 } 005310 return r2; 005311 } 005312 005313 /* 005314 ** Generate code that will evaluate expression pExpr and store the 005315 ** results in register target. The results are guaranteed to appear 005316 ** in register target. 005317 */ 005318 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ 005319 int inReg; 005320 005321 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) ); 005322 assert( target>0 && target<=pParse->nMem ); 005323 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed ); 005324 if( pParse->pVdbe==0 ) return; 005325 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); 005326 if( inReg!=target ){ 005327 u8 op; 005328 Expr *pX = sqlite3ExprSkipCollateAndLikely(pExpr); 005329 testcase( pX!=pExpr ); 005330 if( ALWAYS(pX) 005331 && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER) 005332 ){ 005333 op = OP_Copy; 005334 }else{ 005335 op = OP_SCopy; 005336 } 005337 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target); 005338 } 005339 } 005340 005341 /* 005342 ** Make a transient copy of expression pExpr and then code it using 005343 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode() 005344 ** except that the input expression is guaranteed to be unchanged. 005345 */ 005346 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){ 005347 sqlite3 *db = pParse->db; 005348 pExpr = sqlite3ExprDup(db, pExpr, 0); 005349 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target); 005350 sqlite3ExprDelete(db, pExpr); 005351 } 005352 005353 /* 005354 ** Generate code that will evaluate expression pExpr and store the 005355 ** results in register target. The results are guaranteed to appear 005356 ** in register target. If the expression is constant, then this routine 005357 ** might choose to code the expression at initialization time. 005358 */ 005359 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){ 005360 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){ 005361 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target); 005362 }else{ 005363 sqlite3ExprCodeCopy(pParse, pExpr, target); 005364 } 005365 } 005366 005367 /* 005368 ** Generate code that pushes the value of every element of the given 005369 ** expression list into a sequence of registers beginning at target. 005370 ** 005371 ** Return the number of elements evaluated. The number returned will 005372 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF 005373 ** is defined. 005374 ** 005375 ** The SQLITE_ECEL_DUP flag prevents the arguments from being 005376 ** filled using OP_SCopy. OP_Copy must be used instead. 005377 ** 005378 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be 005379 ** factored out into initialization code. 005380 ** 005381 ** The SQLITE_ECEL_REF flag means that expressions in the list with 005382 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored 005383 ** in registers at srcReg, and so the value can be copied from there. 005384 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0 005385 ** are simply omitted rather than being copied from srcReg. 005386 */ 005387 int sqlite3ExprCodeExprList( 005388 Parse *pParse, /* Parsing context */ 005389 ExprList *pList, /* The expression list to be coded */ 005390 int target, /* Where to write results */ 005391 int srcReg, /* Source registers if SQLITE_ECEL_REF */ 005392 u8 flags /* SQLITE_ECEL_* flags */ 005393 ){ 005394 struct ExprList_item *pItem; 005395 int i, j, n; 005396 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy; 005397 Vdbe *v = pParse->pVdbe; 005398 assert( pList!=0 ); 005399 assert( target>0 ); 005400 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */ 005401 n = pList->nExpr; 005402 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR; 005403 for(pItem=pList->a, i=0; i<n; i++, pItem++){ 005404 Expr *pExpr = pItem->pExpr; 005405 #ifdef SQLITE_ENABLE_SORTER_REFERENCES 005406 if( pItem->fg.bSorterRef ){ 005407 i--; 005408 n--; 005409 }else 005410 #endif 005411 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){ 005412 if( flags & SQLITE_ECEL_OMITREF ){ 005413 i--; 005414 n--; 005415 }else{ 005416 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i); 005417 } 005418 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 005419 && sqlite3ExprIsConstantNotJoin(pExpr) 005420 ){ 005421 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i); 005422 }else{ 005423 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i); 005424 if( inReg!=target+i ){ 005425 VdbeOp *pOp; 005426 if( copyOp==OP_Copy 005427 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy 005428 && pOp->p1+pOp->p3+1==inReg 005429 && pOp->p2+pOp->p3+1==target+i 005430 && pOp->p5==0 /* The do-not-merge flag must be clear */ 005431 ){ 005432 pOp->p3++; 005433 }else{ 005434 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i); 005435 } 005436 } 005437 } 005438 } 005439 return n; 005440 } 005441 005442 /* 005443 ** Generate code for a BETWEEN operator. 005444 ** 005445 ** x BETWEEN y AND z 005446 ** 005447 ** The above is equivalent to 005448 ** 005449 ** x>=y AND x<=z 005450 ** 005451 ** Code it as such, taking care to do the common subexpression 005452 ** elimination of x. 005453 ** 005454 ** The xJumpIf parameter determines details: 005455 ** 005456 ** NULL: Store the boolean result in reg[dest] 005457 ** sqlite3ExprIfTrue: Jump to dest if true 005458 ** sqlite3ExprIfFalse: Jump to dest if false 005459 ** 005460 ** The jumpIfNull parameter is ignored if xJumpIf is NULL. 005461 */ 005462 static void exprCodeBetween( 005463 Parse *pParse, /* Parsing and code generating context */ 005464 Expr *pExpr, /* The BETWEEN expression */ 005465 int dest, /* Jump destination or storage location */ 005466 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */ 005467 int jumpIfNull /* Take the jump if the BETWEEN is NULL */ 005468 ){ 005469 Expr exprAnd; /* The AND operator in x>=y AND x<=z */ 005470 Expr compLeft; /* The x>=y term */ 005471 Expr compRight; /* The x<=z term */ 005472 int regFree1 = 0; /* Temporary use register */ 005473 Expr *pDel = 0; 005474 sqlite3 *db = pParse->db; 005475 005476 memset(&compLeft, 0, sizeof(Expr)); 005477 memset(&compRight, 0, sizeof(Expr)); 005478 memset(&exprAnd, 0, sizeof(Expr)); 005479 005480 assert( ExprUseXList(pExpr) ); 005481 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0); 005482 if( db->mallocFailed==0 ){ 005483 exprAnd.op = TK_AND; 005484 exprAnd.pLeft = &compLeft; 005485 exprAnd.pRight = &compRight; 005486 compLeft.op = TK_GE; 005487 compLeft.pLeft = pDel; 005488 compLeft.pRight = pExpr->x.pList->a[0].pExpr; 005489 compRight.op = TK_LE; 005490 compRight.pLeft = pDel; 005491 compRight.pRight = pExpr->x.pList->a[1].pExpr; 005492 exprToRegister(pDel, exprCodeVector(pParse, pDel, ®Free1)); 005493 if( xJump ){ 005494 xJump(pParse, &exprAnd, dest, jumpIfNull); 005495 }else{ 005496 /* Mark the expression is being from the ON or USING clause of a join 005497 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move 005498 ** it into the Parse.pConstExpr list. We should use a new bit for this, 005499 ** for clarity, but we are out of bits in the Expr.flags field so we 005500 ** have to reuse the EP_OuterON bit. Bummer. */ 005501 pDel->flags |= EP_OuterON; 005502 sqlite3ExprCodeTarget(pParse, &exprAnd, dest); 005503 } 005504 sqlite3ReleaseTempReg(pParse, regFree1); 005505 } 005506 sqlite3ExprDelete(db, pDel); 005507 005508 /* Ensure adequate test coverage */ 005509 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 ); 005510 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 ); 005511 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 ); 005512 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 ); 005513 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 ); 005514 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 ); 005515 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 ); 005516 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 ); 005517 testcase( xJump==0 ); 005518 } 005519 005520 /* 005521 ** Generate code for a boolean expression such that a jump is made 005522 ** to the label "dest" if the expression is true but execution 005523 ** continues straight thru if the expression is false. 005524 ** 005525 ** If the expression evaluates to NULL (neither true nor false), then 005526 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. 005527 ** 005528 ** This code depends on the fact that certain token values (ex: TK_EQ) 005529 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding 005530 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in 005531 ** the make process cause these values to align. Assert()s in the code 005532 ** below verify that the numbers are aligned correctly. 005533 */ 005534 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 005535 Vdbe *v = pParse->pVdbe; 005536 int op = 0; 005537 int regFree1 = 0; 005538 int regFree2 = 0; 005539 int r1, r2; 005540 005541 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 005542 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 005543 if( NEVER(pExpr==0) ) return; /* No way this can happen */ 005544 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) ); 005545 op = pExpr->op; 005546 switch( op ){ 005547 case TK_AND: 005548 case TK_OR: { 005549 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 005550 if( pAlt!=pExpr ){ 005551 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull); 005552 }else if( op==TK_AND ){ 005553 int d2 = sqlite3VdbeMakeLabel(pParse); 005554 testcase( jumpIfNull==0 ); 005555 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, 005556 jumpIfNull^SQLITE_JUMPIFNULL); 005557 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 005558 sqlite3VdbeResolveLabel(v, d2); 005559 }else{ 005560 testcase( jumpIfNull==0 ); 005561 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 005562 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); 005563 } 005564 break; 005565 } 005566 case TK_NOT: { 005567 testcase( jumpIfNull==0 ); 005568 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 005569 break; 005570 } 005571 case TK_TRUTH: { 005572 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 005573 int isTrue; /* IS TRUE or IS NOT TRUE */ 005574 testcase( jumpIfNull==0 ); 005575 isNot = pExpr->op2==TK_ISNOT; 005576 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 005577 testcase( isTrue && isNot ); 005578 testcase( !isTrue && isNot ); 005579 if( isTrue ^ isNot ){ 005580 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 005581 isNot ? SQLITE_JUMPIFNULL : 0); 005582 }else{ 005583 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 005584 isNot ? SQLITE_JUMPIFNULL : 0); 005585 } 005586 break; 005587 } 005588 case TK_IS: 005589 case TK_ISNOT: 005590 testcase( op==TK_IS ); 005591 testcase( op==TK_ISNOT ); 005592 op = (op==TK_IS) ? TK_EQ : TK_NE; 005593 jumpIfNull = SQLITE_NULLEQ; 005594 /* no break */ deliberate_fall_through 005595 case TK_LT: 005596 case TK_LE: 005597 case TK_GT: 005598 case TK_GE: 005599 case TK_NE: 005600 case TK_EQ: { 005601 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 005602 testcase( jumpIfNull==0 ); 005603 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 005604 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 005605 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 005606 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted)); 005607 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 005608 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 005609 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 005610 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 005611 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 005612 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 005613 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 005614 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 005615 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 005616 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 005617 testcase( regFree1==0 ); 005618 testcase( regFree2==0 ); 005619 break; 005620 } 005621 case TK_ISNULL: 005622 case TK_NOTNULL: { 005623 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL ); 005624 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL ); 005625 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 005626 sqlite3VdbeTypeofColumn(v, r1); 005627 sqlite3VdbeAddOp2(v, op, r1, dest); 005628 VdbeCoverageIf(v, op==TK_ISNULL); 005629 VdbeCoverageIf(v, op==TK_NOTNULL); 005630 testcase( regFree1==0 ); 005631 break; 005632 } 005633 case TK_BETWEEN: { 005634 testcase( jumpIfNull==0 ); 005635 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull); 005636 break; 005637 } 005638 #ifndef SQLITE_OMIT_SUBQUERY 005639 case TK_IN: { 005640 int destIfFalse = sqlite3VdbeMakeLabel(pParse); 005641 int destIfNull = jumpIfNull ? dest : destIfFalse; 005642 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull); 005643 sqlite3VdbeGoto(v, dest); 005644 sqlite3VdbeResolveLabel(v, destIfFalse); 005645 break; 005646 } 005647 #endif 005648 default: { 005649 default_expr: 005650 if( ExprAlwaysTrue(pExpr) ){ 005651 sqlite3VdbeGoto(v, dest); 005652 }else if( ExprAlwaysFalse(pExpr) ){ 005653 /* No-op */ 005654 }else{ 005655 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 005656 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); 005657 VdbeCoverage(v); 005658 testcase( regFree1==0 ); 005659 testcase( jumpIfNull==0 ); 005660 } 005661 break; 005662 } 005663 } 005664 sqlite3ReleaseTempReg(pParse, regFree1); 005665 sqlite3ReleaseTempReg(pParse, regFree2); 005666 } 005667 005668 /* 005669 ** Generate code for a boolean expression such that a jump is made 005670 ** to the label "dest" if the expression is false but execution 005671 ** continues straight thru if the expression is true. 005672 ** 005673 ** If the expression evaluates to NULL (neither true nor false) then 005674 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull 005675 ** is 0. 005676 */ 005677 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ 005678 Vdbe *v = pParse->pVdbe; 005679 int op = 0; 005680 int regFree1 = 0; 005681 int regFree2 = 0; 005682 int r1, r2; 005683 005684 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); 005685 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */ 005686 if( pExpr==0 ) return; 005687 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) ); 005688 005689 /* The value of pExpr->op and op are related as follows: 005690 ** 005691 ** pExpr->op op 005692 ** --------- ---------- 005693 ** TK_ISNULL OP_NotNull 005694 ** TK_NOTNULL OP_IsNull 005695 ** TK_NE OP_Eq 005696 ** TK_EQ OP_Ne 005697 ** TK_GT OP_Le 005698 ** TK_LE OP_Gt 005699 ** TK_GE OP_Lt 005700 ** TK_LT OP_Ge 005701 ** 005702 ** For other values of pExpr->op, op is undefined and unused. 005703 ** The value of TK_ and OP_ constants are arranged such that we 005704 ** can compute the mapping above using the following expression. 005705 ** Assert()s verify that the computation is correct. 005706 */ 005707 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1); 005708 005709 /* Verify correct alignment of TK_ and OP_ constants 005710 */ 005711 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull ); 005712 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull ); 005713 assert( pExpr->op!=TK_NE || op==OP_Eq ); 005714 assert( pExpr->op!=TK_EQ || op==OP_Ne ); 005715 assert( pExpr->op!=TK_LT || op==OP_Ge ); 005716 assert( pExpr->op!=TK_LE || op==OP_Gt ); 005717 assert( pExpr->op!=TK_GT || op==OP_Le ); 005718 assert( pExpr->op!=TK_GE || op==OP_Lt ); 005719 005720 switch( pExpr->op ){ 005721 case TK_AND: 005722 case TK_OR: { 005723 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr); 005724 if( pAlt!=pExpr ){ 005725 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull); 005726 }else if( pExpr->op==TK_AND ){ 005727 testcase( jumpIfNull==0 ); 005728 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); 005729 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 005730 }else{ 005731 int d2 = sqlite3VdbeMakeLabel(pParse); 005732 testcase( jumpIfNull==0 ); 005733 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, 005734 jumpIfNull^SQLITE_JUMPIFNULL); 005735 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); 005736 sqlite3VdbeResolveLabel(v, d2); 005737 } 005738 break; 005739 } 005740 case TK_NOT: { 005741 testcase( jumpIfNull==0 ); 005742 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); 005743 break; 005744 } 005745 case TK_TRUTH: { 005746 int isNot; /* IS NOT TRUE or IS NOT FALSE */ 005747 int isTrue; /* IS TRUE or IS NOT TRUE */ 005748 testcase( jumpIfNull==0 ); 005749 isNot = pExpr->op2==TK_ISNOT; 005750 isTrue = sqlite3ExprTruthValue(pExpr->pRight); 005751 testcase( isTrue && isNot ); 005752 testcase( !isTrue && isNot ); 005753 if( isTrue ^ isNot ){ 005754 /* IS TRUE and IS NOT FALSE */ 005755 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, 005756 isNot ? 0 : SQLITE_JUMPIFNULL); 005757 005758 }else{ 005759 /* IS FALSE and IS NOT TRUE */ 005760 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, 005761 isNot ? 0 : SQLITE_JUMPIFNULL); 005762 } 005763 break; 005764 } 005765 case TK_IS: 005766 case TK_ISNOT: 005767 testcase( pExpr->op==TK_IS ); 005768 testcase( pExpr->op==TK_ISNOT ); 005769 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ; 005770 jumpIfNull = SQLITE_NULLEQ; 005771 /* no break */ deliberate_fall_through 005772 case TK_LT: 005773 case TK_LE: 005774 case TK_GT: 005775 case TK_GE: 005776 case TK_NE: 005777 case TK_EQ: { 005778 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr; 005779 testcase( jumpIfNull==0 ); 005780 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 005781 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); 005782 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 005783 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted)); 005784 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt); 005785 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le); 005786 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt); 005787 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge); 005788 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); 005789 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ); 005790 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ); 005791 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); 005792 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ); 005793 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ); 005794 testcase( regFree1==0 ); 005795 testcase( regFree2==0 ); 005796 break; 005797 } 005798 case TK_ISNULL: 005799 case TK_NOTNULL: { 005800 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); 005801 sqlite3VdbeTypeofColumn(v, r1); 005802 sqlite3VdbeAddOp2(v, op, r1, dest); 005803 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL); 005804 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL); 005805 testcase( regFree1==0 ); 005806 break; 005807 } 005808 case TK_BETWEEN: { 005809 testcase( jumpIfNull==0 ); 005810 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull); 005811 break; 005812 } 005813 #ifndef SQLITE_OMIT_SUBQUERY 005814 case TK_IN: { 005815 if( jumpIfNull ){ 005816 sqlite3ExprCodeIN(pParse, pExpr, dest, dest); 005817 }else{ 005818 int destIfNull = sqlite3VdbeMakeLabel(pParse); 005819 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull); 005820 sqlite3VdbeResolveLabel(v, destIfNull); 005821 } 005822 break; 005823 } 005824 #endif 005825 default: { 005826 default_expr: 005827 if( ExprAlwaysFalse(pExpr) ){ 005828 sqlite3VdbeGoto(v, dest); 005829 }else if( ExprAlwaysTrue(pExpr) ){ 005830 /* no-op */ 005831 }else{ 005832 r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); 005833 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); 005834 VdbeCoverage(v); 005835 testcase( regFree1==0 ); 005836 testcase( jumpIfNull==0 ); 005837 } 005838 break; 005839 } 005840 } 005841 sqlite3ReleaseTempReg(pParse, regFree1); 005842 sqlite3ReleaseTempReg(pParse, regFree2); 005843 } 005844 005845 /* 005846 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before 005847 ** code generation, and that copy is deleted after code generation. This 005848 ** ensures that the original pExpr is unchanged. 005849 */ 005850 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){ 005851 sqlite3 *db = pParse->db; 005852 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0); 005853 if( db->mallocFailed==0 ){ 005854 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull); 005855 } 005856 sqlite3ExprDelete(db, pCopy); 005857 } 005858 005859 /* 005860 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any 005861 ** type of expression. 005862 ** 005863 ** If pExpr is a simple SQL value - an integer, real, string, blob 005864 ** or NULL value - then the VDBE currently being prepared is configured 005865 ** to re-prepare each time a new value is bound to variable pVar. 005866 ** 005867 ** Additionally, if pExpr is a simple SQL value and the value is the 005868 ** same as that currently bound to variable pVar, non-zero is returned. 005869 ** Otherwise, if the values are not the same or if pExpr is not a simple 005870 ** SQL value, zero is returned. 005871 */ 005872 static int exprCompareVariable( 005873 const Parse *pParse, 005874 const Expr *pVar, 005875 const Expr *pExpr 005876 ){ 005877 int res = 0; 005878 int iVar; 005879 sqlite3_value *pL, *pR = 0; 005880 005881 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR); 005882 if( pR ){ 005883 iVar = pVar->iColumn; 005884 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); 005885 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB); 005886 if( pL ){ 005887 if( sqlite3_value_type(pL)==SQLITE_TEXT ){ 005888 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */ 005889 } 005890 res = 0==sqlite3MemCompare(pL, pR, 0); 005891 } 005892 sqlite3ValueFree(pR); 005893 sqlite3ValueFree(pL); 005894 } 005895 005896 return res; 005897 } 005898 005899 /* 005900 ** Do a deep comparison of two expression trees. Return 0 if the two 005901 ** expressions are completely identical. Return 1 if they differ only 005902 ** by a COLLATE operator at the top level. Return 2 if there are differences 005903 ** other than the top-level COLLATE operator. 005904 ** 005905 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 005906 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 005907 ** 005908 ** The pA side might be using TK_REGISTER. If that is the case and pB is 005909 ** not using TK_REGISTER but is otherwise equivalent, then still return 0. 005910 ** 005911 ** Sometimes this routine will return 2 even if the two expressions 005912 ** really are equivalent. If we cannot prove that the expressions are 005913 ** identical, we return 2 just to be safe. So if this routine 005914 ** returns 2, then you do not really know for certain if the two 005915 ** expressions are the same. But if you get a 0 or 1 return, then you 005916 ** can be sure the expressions are the same. In the places where 005917 ** this routine is used, it does not hurt to get an extra 2 - that 005918 ** just might result in some slightly slower code. But returning 005919 ** an incorrect 0 or 1 could lead to a malfunction. 005920 ** 005921 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in 005922 ** pParse->pReprepare can be matched against literals in pB. The 005923 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced. 005924 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in 005925 ** Argument pParse should normally be NULL. If it is not NULL and pA or 005926 ** pB causes a return value of 2. 005927 */ 005928 int sqlite3ExprCompare( 005929 const Parse *pParse, 005930 const Expr *pA, 005931 const Expr *pB, 005932 int iTab 005933 ){ 005934 u32 combinedFlags; 005935 if( pA==0 || pB==0 ){ 005936 return pB==pA ? 0 : 2; 005937 } 005938 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){ 005939 return 0; 005940 } 005941 combinedFlags = pA->flags | pB->flags; 005942 if( combinedFlags & EP_IntValue ){ 005943 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){ 005944 return 0; 005945 } 005946 return 2; 005947 } 005948 if( pA->op!=pB->op || pA->op==TK_RAISE ){ 005949 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){ 005950 return 1; 005951 } 005952 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){ 005953 return 1; 005954 } 005955 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN 005956 && pB->iTable<0 && pA->iTable==iTab 005957 ){ 005958 /* fall through */ 005959 }else{ 005960 return 2; 005961 } 005962 } 005963 assert( !ExprHasProperty(pA, EP_IntValue) ); 005964 assert( !ExprHasProperty(pB, EP_IntValue) ); 005965 if( pA->u.zToken ){ 005966 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){ 005967 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 005968 #ifndef SQLITE_OMIT_WINDOWFUNC 005969 assert( pA->op==pB->op ); 005970 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){ 005971 return 2; 005972 } 005973 if( ExprHasProperty(pA,EP_WinFunc) ){ 005974 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){ 005975 return 2; 005976 } 005977 } 005978 #endif 005979 }else if( pA->op==TK_NULL ){ 005980 return 0; 005981 }else if( pA->op==TK_COLLATE ){ 005982 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2; 005983 }else 005984 if( pB->u.zToken!=0 005985 && pA->op!=TK_COLUMN 005986 && pA->op!=TK_AGG_COLUMN 005987 && strcmp(pA->u.zToken,pB->u.zToken)!=0 005988 ){ 005989 return 2; 005990 } 005991 } 005992 if( (pA->flags & (EP_Distinct|EP_Commuted)) 005993 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2; 005994 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){ 005995 if( combinedFlags & EP_xIsSelect ) return 2; 005996 if( (combinedFlags & EP_FixedCol)==0 005997 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2; 005998 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2; 005999 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2; 006000 if( pA->op!=TK_STRING 006001 && pA->op!=TK_TRUEFALSE 006002 && ALWAYS((combinedFlags & EP_Reduced)==0) 006003 ){ 006004 if( pA->iColumn!=pB->iColumn ) return 2; 006005 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2; 006006 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){ 006007 return 2; 006008 } 006009 } 006010 } 006011 return 0; 006012 } 006013 006014 /* 006015 ** Compare two ExprList objects. Return 0 if they are identical, 1 006016 ** if they are certainly different, or 2 if it is not possible to 006017 ** determine if they are identical or not. 006018 ** 006019 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed 006020 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab. 006021 ** 006022 ** This routine might return non-zero for equivalent ExprLists. The 006023 ** only consequence will be disabled optimizations. But this routine 006024 ** must never return 0 if the two ExprList objects are different, or 006025 ** a malfunction will result. 006026 ** 006027 ** Two NULL pointers are considered to be the same. But a NULL pointer 006028 ** always differs from a non-NULL pointer. 006029 */ 006030 int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){ 006031 int i; 006032 if( pA==0 && pB==0 ) return 0; 006033 if( pA==0 || pB==0 ) return 1; 006034 if( pA->nExpr!=pB->nExpr ) return 1; 006035 for(i=0; i<pA->nExpr; i++){ 006036 int res; 006037 Expr *pExprA = pA->a[i].pExpr; 006038 Expr *pExprB = pB->a[i].pExpr; 006039 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1; 006040 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res; 006041 } 006042 return 0; 006043 } 006044 006045 /* 006046 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level 006047 ** are ignored. 006048 */ 006049 int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){ 006050 return sqlite3ExprCompare(0, 006051 sqlite3ExprSkipCollate(pA), 006052 sqlite3ExprSkipCollate(pB), 006053 iTab); 006054 } 006055 006056 /* 006057 ** Return non-zero if Expr p can only be true if pNN is not NULL. 006058 ** 006059 ** Or if seenNot is true, return non-zero if Expr p can only be 006060 ** non-NULL if pNN is not NULL 006061 */ 006062 static int exprImpliesNotNull( 006063 const Parse *pParse,/* Parsing context */ 006064 const Expr *p, /* The expression to be checked */ 006065 const Expr *pNN, /* The expression that is NOT NULL */ 006066 int iTab, /* Table being evaluated */ 006067 int seenNot /* Return true only if p can be any non-NULL value */ 006068 ){ 006069 assert( p ); 006070 assert( pNN ); 006071 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){ 006072 return pNN->op!=TK_NULL; 006073 } 006074 switch( p->op ){ 006075 case TK_IN: { 006076 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0; 006077 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) ); 006078 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 006079 } 006080 case TK_BETWEEN: { 006081 ExprList *pList; 006082 assert( ExprUseXList(p) ); 006083 pList = p->x.pList; 006084 assert( pList!=0 ); 006085 assert( pList->nExpr==2 ); 006086 if( seenNot ) return 0; 006087 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1) 006088 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1) 006089 ){ 006090 return 1; 006091 } 006092 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 006093 } 006094 case TK_EQ: 006095 case TK_NE: 006096 case TK_LT: 006097 case TK_LE: 006098 case TK_GT: 006099 case TK_GE: 006100 case TK_PLUS: 006101 case TK_MINUS: 006102 case TK_BITOR: 006103 case TK_LSHIFT: 006104 case TK_RSHIFT: 006105 case TK_CONCAT: 006106 seenNot = 1; 006107 /* no break */ deliberate_fall_through 006108 case TK_STAR: 006109 case TK_REM: 006110 case TK_BITAND: 006111 case TK_SLASH: { 006112 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1; 006113 /* no break */ deliberate_fall_through 006114 } 006115 case TK_SPAN: 006116 case TK_COLLATE: 006117 case TK_UPLUS: 006118 case TK_UMINUS: { 006119 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot); 006120 } 006121 case TK_TRUTH: { 006122 if( seenNot ) return 0; 006123 if( p->op2!=TK_IS ) return 0; 006124 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 006125 } 006126 case TK_BITNOT: 006127 case TK_NOT: { 006128 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1); 006129 } 006130 } 006131 return 0; 006132 } 006133 006134 /* 006135 ** Return true if we can prove the pE2 will always be true if pE1 is 006136 ** true. Return false if we cannot complete the proof or if pE2 might 006137 ** be false. Examples: 006138 ** 006139 ** pE1: x==5 pE2: x==5 Result: true 006140 ** pE1: x>0 pE2: x==5 Result: false 006141 ** pE1: x=21 pE2: x=21 OR y=43 Result: true 006142 ** pE1: x!=123 pE2: x IS NOT NULL Result: true 006143 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true 006144 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false 006145 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false 006146 ** 006147 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has 006148 ** Expr.iTable<0 then assume a table number given by iTab. 006149 ** 006150 ** If pParse is not NULL, then the values of bound variables in pE1 are 006151 ** compared against literal values in pE2 and pParse->pVdbe->expmask is 006152 ** modified to record which bound variables are referenced. If pParse 006153 ** is NULL, then false will be returned if pE1 contains any bound variables. 006154 ** 006155 ** When in doubt, return false. Returning true might give a performance 006156 ** improvement. Returning false might cause a performance reduction, but 006157 ** it will always give the correct answer and is hence always safe. 006158 */ 006159 int sqlite3ExprImpliesExpr( 006160 const Parse *pParse, 006161 const Expr *pE1, 006162 const Expr *pE2, 006163 int iTab 006164 ){ 006165 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){ 006166 return 1; 006167 } 006168 if( pE2->op==TK_OR 006169 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab) 006170 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) ) 006171 ){ 006172 return 1; 006173 } 006174 if( pE2->op==TK_NOTNULL 006175 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0) 006176 ){ 006177 return 1; 006178 } 006179 return 0; 006180 } 006181 006182 /* This is a helper function to impliesNotNullRow(). In this routine, 006183 ** set pWalker->eCode to one only if *both* of the input expressions 006184 ** separately have the implies-not-null-row property. 006185 */ 006186 static void bothImplyNotNullRow(Walker *pWalker, Expr *pE1, Expr *pE2){ 006187 if( pWalker->eCode==0 ){ 006188 sqlite3WalkExpr(pWalker, pE1); 006189 if( pWalker->eCode ){ 006190 pWalker->eCode = 0; 006191 sqlite3WalkExpr(pWalker, pE2); 006192 } 006193 } 006194 } 006195 006196 /* 006197 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow(). 006198 ** If the expression node requires that the table at pWalker->iCur 006199 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort. 006200 ** 006201 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on 006202 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when 006203 ** evaluating terms in the ON clause of an inner join. 006204 ** 006205 ** This routine controls an optimization. False positives (setting 006206 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives 006207 ** (never setting pWalker->eCode) is a harmless missed optimization. 006208 */ 006209 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){ 006210 testcase( pExpr->op==TK_AGG_COLUMN ); 006211 testcase( pExpr->op==TK_AGG_FUNCTION ); 006212 if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune; 006213 if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){ 006214 /* If iCur is used in an inner-join ON clause to the left of a 006215 ** RIGHT JOIN, that does *not* mean that the table must be non-null. 006216 ** But it is difficult to check for that condition precisely. 006217 ** To keep things simple, any use of iCur from any inner-join is 006218 ** ignored while attempting to simplify a RIGHT JOIN. */ 006219 return WRC_Prune; 006220 } 006221 switch( pExpr->op ){ 006222 case TK_ISNOT: 006223 case TK_ISNULL: 006224 case TK_NOTNULL: 006225 case TK_IS: 006226 case TK_VECTOR: 006227 case TK_FUNCTION: 006228 case TK_TRUTH: 006229 case TK_CASE: 006230 testcase( pExpr->op==TK_ISNOT ); 006231 testcase( pExpr->op==TK_ISNULL ); 006232 testcase( pExpr->op==TK_NOTNULL ); 006233 testcase( pExpr->op==TK_IS ); 006234 testcase( pExpr->op==TK_VECTOR ); 006235 testcase( pExpr->op==TK_FUNCTION ); 006236 testcase( pExpr->op==TK_TRUTH ); 006237 testcase( pExpr->op==TK_CASE ); 006238 return WRC_Prune; 006239 006240 case TK_COLUMN: 006241 if( pWalker->u.iCur==pExpr->iTable ){ 006242 pWalker->eCode = 1; 006243 return WRC_Abort; 006244 } 006245 return WRC_Prune; 006246 006247 case TK_OR: 006248 case TK_AND: 006249 /* Both sides of an AND or OR must separately imply non-null-row. 006250 ** Consider these cases: 006251 ** 1. NOT (x AND y) 006252 ** 2. x OR y 006253 ** If only one of x or y is non-null-row, then the overall expression 006254 ** can be true if the other arm is false (case 1) or true (case 2). 006255 */ 006256 testcase( pExpr->op==TK_OR ); 006257 testcase( pExpr->op==TK_AND ); 006258 bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight); 006259 return WRC_Prune; 006260 006261 case TK_IN: 006262 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)", 006263 ** both of which can be true. But apart from these cases, if 006264 ** the left-hand side of the IN is NULL then the IN itself will be 006265 ** NULL. */ 006266 if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){ 006267 sqlite3WalkExpr(pWalker, pExpr->pLeft); 006268 } 006269 return WRC_Prune; 006270 006271 case TK_BETWEEN: 006272 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else 006273 ** both y and z must be non-null row */ 006274 assert( ExprUseXList(pExpr) ); 006275 assert( pExpr->x.pList->nExpr==2 ); 006276 sqlite3WalkExpr(pWalker, pExpr->pLeft); 006277 bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr, 006278 pExpr->x.pList->a[1].pExpr); 006279 return WRC_Prune; 006280 006281 /* Virtual tables are allowed to use constraints like x=NULL. So 006282 ** a term of the form x=y does not prove that y is not null if x 006283 ** is the column of a virtual table */ 006284 case TK_EQ: 006285 case TK_NE: 006286 case TK_LT: 006287 case TK_LE: 006288 case TK_GT: 006289 case TK_GE: { 006290 Expr *pLeft = pExpr->pLeft; 006291 Expr *pRight = pExpr->pRight; 006292 testcase( pExpr->op==TK_EQ ); 006293 testcase( pExpr->op==TK_NE ); 006294 testcase( pExpr->op==TK_LT ); 006295 testcase( pExpr->op==TK_LE ); 006296 testcase( pExpr->op==TK_GT ); 006297 testcase( pExpr->op==TK_GE ); 006298 /* The y.pTab=0 assignment in wherecode.c always happens after the 006299 ** impliesNotNullRow() test */ 006300 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) ); 006301 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) ); 006302 if( (pLeft->op==TK_COLUMN 006303 && ALWAYS(pLeft->y.pTab!=0) 006304 && IsVirtual(pLeft->y.pTab)) 006305 || (pRight->op==TK_COLUMN 006306 && ALWAYS(pRight->y.pTab!=0) 006307 && IsVirtual(pRight->y.pTab)) 006308 ){ 006309 return WRC_Prune; 006310 } 006311 /* no break */ deliberate_fall_through 006312 } 006313 default: 006314 return WRC_Continue; 006315 } 006316 } 006317 006318 /* 006319 ** Return true (non-zero) if expression p can only be true if at least 006320 ** one column of table iTab is non-null. In other words, return true 006321 ** if expression p will always be NULL or false if every column of iTab 006322 ** is NULL. 006323 ** 006324 ** False negatives are acceptable. In other words, it is ok to return 006325 ** zero even if expression p will never be true of every column of iTab 006326 ** is NULL. A false negative is merely a missed optimization opportunity. 006327 ** 006328 ** False positives are not allowed, however. A false positive may result 006329 ** in an incorrect answer. 006330 ** 006331 ** Terms of p that are marked with EP_OuterON (and hence that come from 006332 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis. 006333 ** 006334 ** This routine is used to check if a LEFT JOIN can be converted into 006335 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE 006336 ** clause requires that some column of the right table of the LEFT JOIN 006337 ** be non-NULL, then the LEFT JOIN can be safely converted into an 006338 ** ordinary join. 006339 */ 006340 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab, int isRJ){ 006341 Walker w; 006342 p = sqlite3ExprSkipCollateAndLikely(p); 006343 if( p==0 ) return 0; 006344 if( p->op==TK_NOTNULL ){ 006345 p = p->pLeft; 006346 }else{ 006347 while( p->op==TK_AND ){ 006348 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1; 006349 p = p->pRight; 006350 } 006351 } 006352 w.xExprCallback = impliesNotNullRow; 006353 w.xSelectCallback = 0; 006354 w.xSelectCallback2 = 0; 006355 w.eCode = 0; 006356 w.mWFlags = isRJ!=0; 006357 w.u.iCur = iTab; 006358 sqlite3WalkExpr(&w, p); 006359 return w.eCode; 006360 } 006361 006362 /* 006363 ** An instance of the following structure is used by the tree walker 006364 ** to determine if an expression can be evaluated by reference to the 006365 ** index only, without having to do a search for the corresponding 006366 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur 006367 ** is the cursor for the table. 006368 */ 006369 struct IdxCover { 006370 Index *pIdx; /* The index to be tested for coverage */ 006371 int iCur; /* Cursor number for the table corresponding to the index */ 006372 }; 006373 006374 /* 006375 ** Check to see if there are references to columns in table 006376 ** pWalker->u.pIdxCover->iCur can be satisfied using the index 006377 ** pWalker->u.pIdxCover->pIdx. 006378 */ 006379 static int exprIdxCover(Walker *pWalker, Expr *pExpr){ 006380 if( pExpr->op==TK_COLUMN 006381 && pExpr->iTable==pWalker->u.pIdxCover->iCur 006382 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0 006383 ){ 006384 pWalker->eCode = 1; 006385 return WRC_Abort; 006386 } 006387 return WRC_Continue; 006388 } 006389 006390 /* 006391 ** Determine if an index pIdx on table with cursor iCur contains will 006392 ** the expression pExpr. Return true if the index does cover the 006393 ** expression and false if the pExpr expression references table columns 006394 ** that are not found in the index pIdx. 006395 ** 006396 ** An index covering an expression means that the expression can be 006397 ** evaluated using only the index and without having to lookup the 006398 ** corresponding table entry. 006399 */ 006400 int sqlite3ExprCoveredByIndex( 006401 Expr *pExpr, /* The index to be tested */ 006402 int iCur, /* The cursor number for the corresponding table */ 006403 Index *pIdx /* The index that might be used for coverage */ 006404 ){ 006405 Walker w; 006406 struct IdxCover xcov; 006407 memset(&w, 0, sizeof(w)); 006408 xcov.iCur = iCur; 006409 xcov.pIdx = pIdx; 006410 w.xExprCallback = exprIdxCover; 006411 w.u.pIdxCover = &xcov; 006412 sqlite3WalkExpr(&w, pExpr); 006413 return !w.eCode; 006414 } 006415 006416 006417 /* Structure used to pass information throughout the Walker in order to 006418 ** implement sqlite3ReferencesSrcList(). 006419 */ 006420 struct RefSrcList { 006421 sqlite3 *db; /* Database connection used for sqlite3DbRealloc() */ 006422 SrcList *pRef; /* Looking for references to these tables */ 006423 i64 nExclude; /* Number of tables to exclude from the search */ 006424 int *aiExclude; /* Cursor IDs for tables to exclude from the search */ 006425 }; 006426 006427 /* 006428 ** Walker SELECT callbacks for sqlite3ReferencesSrcList(). 006429 ** 006430 ** When entering a new subquery on the pExpr argument, add all FROM clause 006431 ** entries for that subquery to the exclude list. 006432 ** 006433 ** When leaving the subquery, remove those entries from the exclude list. 006434 */ 006435 static int selectRefEnter(Walker *pWalker, Select *pSelect){ 006436 struct RefSrcList *p = pWalker->u.pRefSrcList; 006437 SrcList *pSrc = pSelect->pSrc; 006438 i64 i, j; 006439 int *piNew; 006440 if( pSrc->nSrc==0 ) return WRC_Continue; 006441 j = p->nExclude; 006442 p->nExclude += pSrc->nSrc; 006443 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int)); 006444 if( piNew==0 ){ 006445 p->nExclude = 0; 006446 return WRC_Abort; 006447 }else{ 006448 p->aiExclude = piNew; 006449 } 006450 for(i=0; i<pSrc->nSrc; i++, j++){ 006451 p->aiExclude[j] = pSrc->a[i].iCursor; 006452 } 006453 return WRC_Continue; 006454 } 006455 static void selectRefLeave(Walker *pWalker, Select *pSelect){ 006456 struct RefSrcList *p = pWalker->u.pRefSrcList; 006457 SrcList *pSrc = pSelect->pSrc; 006458 if( p->nExclude ){ 006459 assert( p->nExclude>=pSrc->nSrc ); 006460 p->nExclude -= pSrc->nSrc; 006461 } 006462 } 006463 006464 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList(). 006465 ** 006466 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any 006467 ** of the tables shown in RefSrcList.pRef. 006468 ** 006469 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a 006470 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude. 006471 */ 006472 static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){ 006473 if( pExpr->op==TK_COLUMN 006474 || pExpr->op==TK_AGG_COLUMN 006475 ){ 006476 int i; 006477 struct RefSrcList *p = pWalker->u.pRefSrcList; 006478 SrcList *pSrc = p->pRef; 006479 int nSrc = pSrc ? pSrc->nSrc : 0; 006480 for(i=0; i<nSrc; i++){ 006481 if( pExpr->iTable==pSrc->a[i].iCursor ){ 006482 pWalker->eCode |= 1; 006483 return WRC_Continue; 006484 } 006485 } 006486 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){} 006487 if( i>=p->nExclude ){ 006488 pWalker->eCode |= 2; 006489 } 006490 } 006491 return WRC_Continue; 006492 } 006493 006494 /* 006495 ** Check to see if pExpr references any tables in pSrcList. 006496 ** Possible return values: 006497 ** 006498 ** 1 pExpr does references a table in pSrcList. 006499 ** 006500 ** 0 pExpr references some table that is not defined in either 006501 ** pSrcList or in subqueries of pExpr itself. 006502 ** 006503 ** -1 pExpr only references no tables at all, or it only 006504 ** references tables defined in subqueries of pExpr itself. 006505 ** 006506 ** As currently used, pExpr is always an aggregate function call. That 006507 ** fact is exploited for efficiency. 006508 */ 006509 int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){ 006510 Walker w; 006511 struct RefSrcList x; 006512 assert( pParse->db!=0 ); 006513 memset(&w, 0, sizeof(w)); 006514 memset(&x, 0, sizeof(x)); 006515 w.xExprCallback = exprRefToSrcList; 006516 w.xSelectCallback = selectRefEnter; 006517 w.xSelectCallback2 = selectRefLeave; 006518 w.u.pRefSrcList = &x; 006519 x.db = pParse->db; 006520 x.pRef = pSrcList; 006521 assert( pExpr->op==TK_AGG_FUNCTION ); 006522 assert( ExprUseXList(pExpr) ); 006523 sqlite3WalkExprList(&w, pExpr->x.pList); 006524 if( pExpr->pLeft ){ 006525 assert( pExpr->pLeft->op==TK_ORDER ); 006526 assert( ExprUseXList(pExpr->pLeft) ); 006527 assert( pExpr->pLeft->x.pList!=0 ); 006528 sqlite3WalkExprList(&w, pExpr->pLeft->x.pList); 006529 } 006530 #ifndef SQLITE_OMIT_WINDOWFUNC 006531 if( ExprHasProperty(pExpr, EP_WinFunc) ){ 006532 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter); 006533 } 006534 #endif 006535 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude); 006536 if( w.eCode & 0x01 ){ 006537 return 1; 006538 }else if( w.eCode ){ 006539 return 0; 006540 }else{ 006541 return -1; 006542 } 006543 } 006544 006545 /* 006546 ** This is a Walker expression node callback. 006547 ** 006548 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo 006549 ** object that is referenced does not refer directly to the Expr. If 006550 ** it does, make a copy. This is done because the pExpr argument is 006551 ** subject to change. 006552 ** 006553 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete() 006554 ** which builds on the sqlite3ParserAddCleanup() mechanism. 006555 */ 006556 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){ 006557 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced)) 006558 && pExpr->pAggInfo!=0 006559 ){ 006560 AggInfo *pAggInfo = pExpr->pAggInfo; 006561 int iAgg = pExpr->iAgg; 006562 Parse *pParse = pWalker->pParse; 006563 sqlite3 *db = pParse->db; 006564 assert( iAgg>=0 ); 006565 if( pExpr->op!=TK_AGG_FUNCTION ){ 006566 if( iAgg<pAggInfo->nColumn 006567 && pAggInfo->aCol[iAgg].pCExpr==pExpr 006568 ){ 006569 pExpr = sqlite3ExprDup(db, pExpr, 0); 006570 if( pExpr ){ 006571 pAggInfo->aCol[iAgg].pCExpr = pExpr; 006572 sqlite3ExprDeferredDelete(pParse, pExpr); 006573 } 006574 } 006575 }else{ 006576 assert( pExpr->op==TK_AGG_FUNCTION ); 006577 if( ALWAYS(iAgg<pAggInfo->nFunc) 006578 && pAggInfo->aFunc[iAgg].pFExpr==pExpr 006579 ){ 006580 pExpr = sqlite3ExprDup(db, pExpr, 0); 006581 if( pExpr ){ 006582 pAggInfo->aFunc[iAgg].pFExpr = pExpr; 006583 sqlite3ExprDeferredDelete(pParse, pExpr); 006584 } 006585 } 006586 } 006587 } 006588 return WRC_Continue; 006589 } 006590 006591 /* 006592 ** Initialize a Walker object so that will persist AggInfo entries referenced 006593 ** by the tree that is walked. 006594 */ 006595 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){ 006596 memset(pWalker, 0, sizeof(*pWalker)); 006597 pWalker->pParse = pParse; 006598 pWalker->xExprCallback = agginfoPersistExprCb; 006599 pWalker->xSelectCallback = sqlite3SelectWalkNoop; 006600 } 006601 006602 /* 006603 ** Add a new element to the pAggInfo->aCol[] array. Return the index of 006604 ** the new element. Return a negative number if malloc fails. 006605 */ 006606 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){ 006607 int i; 006608 pInfo->aCol = sqlite3ArrayAllocate( 006609 db, 006610 pInfo->aCol, 006611 sizeof(pInfo->aCol[0]), 006612 &pInfo->nColumn, 006613 &i 006614 ); 006615 return i; 006616 } 006617 006618 /* 006619 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of 006620 ** the new element. Return a negative number if malloc fails. 006621 */ 006622 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){ 006623 int i; 006624 pInfo->aFunc = sqlite3ArrayAllocate( 006625 db, 006626 pInfo->aFunc, 006627 sizeof(pInfo->aFunc[0]), 006628 &pInfo->nFunc, 006629 &i 006630 ); 006631 return i; 006632 } 006633 006634 /* 006635 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn. 006636 ** Return the index in aCol[] of the entry that describes that column. 006637 ** 006638 ** If no prior entry is found, create a new one and return -1. The 006639 ** new column will have an index of pAggInfo->nColumn-1. 006640 */ 006641 static void findOrCreateAggInfoColumn( 006642 Parse *pParse, /* Parsing context */ 006643 AggInfo *pAggInfo, /* The AggInfo object to search and/or modify */ 006644 Expr *pExpr /* Expr describing the column to find or insert */ 006645 ){ 006646 struct AggInfo_col *pCol; 006647 int k; 006648 006649 assert( pAggInfo->iFirstReg==0 ); 006650 pCol = pAggInfo->aCol; 006651 for(k=0; k<pAggInfo->nColumn; k++, pCol++){ 006652 if( pCol->pCExpr==pExpr ) return; 006653 if( pCol->iTable==pExpr->iTable 006654 && pCol->iColumn==pExpr->iColumn 006655 && pExpr->op!=TK_IF_NULL_ROW 006656 ){ 006657 goto fix_up_expr; 006658 } 006659 } 006660 k = addAggInfoColumn(pParse->db, pAggInfo); 006661 if( k<0 ){ 006662 /* OOM on resize */ 006663 assert( pParse->db->mallocFailed ); 006664 return; 006665 } 006666 pCol = &pAggInfo->aCol[k]; 006667 assert( ExprUseYTab(pExpr) ); 006668 pCol->pTab = pExpr->y.pTab; 006669 pCol->iTable = pExpr->iTable; 006670 pCol->iColumn = pExpr->iColumn; 006671 pCol->iSorterColumn = -1; 006672 pCol->pCExpr = pExpr; 006673 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){ 006674 int j, n; 006675 ExprList *pGB = pAggInfo->pGroupBy; 006676 struct ExprList_item *pTerm = pGB->a; 006677 n = pGB->nExpr; 006678 for(j=0; j<n; j++, pTerm++){ 006679 Expr *pE = pTerm->pExpr; 006680 if( pE->op==TK_COLUMN 006681 && pE->iTable==pExpr->iTable 006682 && pE->iColumn==pExpr->iColumn 006683 ){ 006684 pCol->iSorterColumn = j; 006685 break; 006686 } 006687 } 006688 } 006689 if( pCol->iSorterColumn<0 ){ 006690 pCol->iSorterColumn = pAggInfo->nSortingColumn++; 006691 } 006692 fix_up_expr: 006693 ExprSetVVAProperty(pExpr, EP_NoReduce); 006694 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo ); 006695 pExpr->pAggInfo = pAggInfo; 006696 if( pExpr->op==TK_COLUMN ){ 006697 pExpr->op = TK_AGG_COLUMN; 006698 } 006699 pExpr->iAgg = (i16)k; 006700 } 006701 006702 /* 006703 ** This is the xExprCallback for a tree walker. It is used to 006704 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates 006705 ** for additional information. 006706 */ 006707 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){ 006708 int i; 006709 NameContext *pNC = pWalker->u.pNC; 006710 Parse *pParse = pNC->pParse; 006711 SrcList *pSrcList = pNC->pSrcList; 006712 AggInfo *pAggInfo = pNC->uNC.pAggInfo; 006713 006714 assert( pNC->ncFlags & NC_UAggInfo ); 006715 assert( pAggInfo->iFirstReg==0 ); 006716 switch( pExpr->op ){ 006717 default: { 006718 IndexedExpr *pIEpr; 006719 Expr tmp; 006720 assert( pParse->iSelfTab==0 ); 006721 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break; 006722 if( pParse->pIdxEpr==0 ) break; 006723 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){ 006724 int iDataCur = pIEpr->iDataCur; 006725 if( iDataCur<0 ) continue; 006726 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break; 006727 } 006728 if( pIEpr==0 ) break; 006729 if( NEVER(!ExprUseYTab(pExpr)) ) break; 006730 for(i=0; i<pSrcList->nSrc; i++){ 006731 if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break; 006732 } 006733 if( i>=pSrcList->nSrc ) break; 006734 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */ 006735 if( pParse->nErr ){ return WRC_Abort; } 006736 006737 /* If we reach this point, it means that expression pExpr can be 006738 ** translated into a reference to an index column as described by 006739 ** pIEpr. 006740 */ 006741 memset(&tmp, 0, sizeof(tmp)); 006742 tmp.op = TK_AGG_COLUMN; 006743 tmp.iTable = pIEpr->iIdxCur; 006744 tmp.iColumn = pIEpr->iIdxCol; 006745 findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp); 006746 if( pParse->nErr ){ return WRC_Abort; } 006747 assert( pAggInfo->aCol!=0 ); 006748 assert( tmp.iAgg<pAggInfo->nColumn ); 006749 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr; 006750 pExpr->pAggInfo = pAggInfo; 006751 pExpr->iAgg = tmp.iAgg; 006752 return WRC_Prune; 006753 } 006754 case TK_IF_NULL_ROW: 006755 case TK_AGG_COLUMN: 006756 case TK_COLUMN: { 006757 testcase( pExpr->op==TK_AGG_COLUMN ); 006758 testcase( pExpr->op==TK_COLUMN ); 006759 testcase( pExpr->op==TK_IF_NULL_ROW ); 006760 /* Check to see if the column is in one of the tables in the FROM 006761 ** clause of the aggregate query */ 006762 if( ALWAYS(pSrcList!=0) ){ 006763 SrcItem *pItem = pSrcList->a; 006764 for(i=0; i<pSrcList->nSrc; i++, pItem++){ 006765 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 006766 if( pExpr->iTable==pItem->iCursor ){ 006767 findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr); 006768 break; 006769 } /* endif pExpr->iTable==pItem->iCursor */ 006770 } /* end loop over pSrcList */ 006771 } 006772 return WRC_Continue; 006773 } 006774 case TK_AGG_FUNCTION: { 006775 if( (pNC->ncFlags & NC_InAggFunc)==0 006776 && pWalker->walkerDepth==pExpr->op2 006777 && pExpr->pAggInfo==0 006778 ){ 006779 /* Check to see if pExpr is a duplicate of another aggregate 006780 ** function that is already in the pAggInfo structure 006781 */ 006782 struct AggInfo_func *pItem = pAggInfo->aFunc; 006783 for(i=0; i<pAggInfo->nFunc; i++, pItem++){ 006784 if( NEVER(pItem->pFExpr==pExpr) ) break; 006785 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){ 006786 break; 006787 } 006788 } 006789 if( i>=pAggInfo->nFunc ){ 006790 /* pExpr is original. Make a new entry in pAggInfo->aFunc[] 006791 */ 006792 u8 enc = ENC(pParse->db); 006793 i = addAggInfoFunc(pParse->db, pAggInfo); 006794 if( i>=0 ){ 006795 int nArg; 006796 assert( !ExprHasProperty(pExpr, EP_xIsSelect) ); 006797 pItem = &pAggInfo->aFunc[i]; 006798 pItem->pFExpr = pExpr; 006799 assert( ExprUseUToken(pExpr) ); 006800 nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0; 006801 pItem->pFunc = sqlite3FindFunction(pParse->db, 006802 pExpr->u.zToken, nArg, enc, 0); 006803 assert( pItem->bOBUnique==0 ); 006804 if( pExpr->pLeft 006805 && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0 006806 ){ 006807 /* The NEEDCOLL test above causes any ORDER BY clause on 006808 ** aggregate min() or max() to be ignored. */ 006809 ExprList *pOBList; 006810 assert( nArg>0 ); 006811 assert( pExpr->pLeft->op==TK_ORDER ); 006812 assert( ExprUseXList(pExpr->pLeft) ); 006813 pItem->iOBTab = pParse->nTab++; 006814 pOBList = pExpr->pLeft->x.pList; 006815 assert( pOBList->nExpr>0 ); 006816 assert( pItem->bOBUnique==0 ); 006817 if( pOBList->nExpr==1 006818 && nArg==1 006819 && sqlite3ExprCompare(0,pOBList->a[0].pExpr, 006820 pExpr->x.pList->a[0].pExpr,0)==0 006821 ){ 006822 pItem->bOBPayload = 0; 006823 pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct); 006824 }else{ 006825 pItem->bOBPayload = 1; 006826 } 006827 pItem->bUseSubtype = 006828 (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0; 006829 }else{ 006830 pItem->iOBTab = -1; 006831 } 006832 if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){ 006833 pItem->iDistinct = pParse->nTab++; 006834 }else{ 006835 pItem->iDistinct = -1; 006836 } 006837 } 006838 } 006839 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry 006840 */ 006841 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); 006842 ExprSetVVAProperty(pExpr, EP_NoReduce); 006843 pExpr->iAgg = (i16)i; 006844 pExpr->pAggInfo = pAggInfo; 006845 return WRC_Prune; 006846 }else{ 006847 return WRC_Continue; 006848 } 006849 } 006850 } 006851 return WRC_Continue; 006852 } 006853 006854 /* 006855 ** Analyze the pExpr expression looking for aggregate functions and 006856 ** for variables that need to be added to AggInfo object that pNC->pAggInfo 006857 ** points to. Additional entries are made on the AggInfo object as 006858 ** necessary. 006859 ** 006860 ** This routine should only be called after the expression has been 006861 ** analyzed by sqlite3ResolveExprNames(). 006862 */ 006863 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ 006864 Walker w; 006865 w.xExprCallback = analyzeAggregate; 006866 w.xSelectCallback = sqlite3WalkerDepthIncrease; 006867 w.xSelectCallback2 = sqlite3WalkerDepthDecrease; 006868 w.walkerDepth = 0; 006869 w.u.pNC = pNC; 006870 w.pParse = 0; 006871 assert( pNC->pSrcList!=0 ); 006872 sqlite3WalkExpr(&w, pExpr); 006873 } 006874 006875 /* 006876 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an 006877 ** expression list. Return the number of errors. 006878 ** 006879 ** If an error is found, the analysis is cut short. 006880 */ 006881 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ 006882 struct ExprList_item *pItem; 006883 int i; 006884 if( pList ){ 006885 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ 006886 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); 006887 } 006888 } 006889 } 006890 006891 /* 006892 ** Allocate a single new register for use to hold some intermediate result. 006893 */ 006894 int sqlite3GetTempReg(Parse *pParse){ 006895 if( pParse->nTempReg==0 ){ 006896 return ++pParse->nMem; 006897 } 006898 return pParse->aTempReg[--pParse->nTempReg]; 006899 } 006900 006901 /* 006902 ** Deallocate a register, making available for reuse for some other 006903 ** purpose. 006904 */ 006905 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ 006906 if( iReg ){ 006907 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0); 006908 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){ 006909 pParse->aTempReg[pParse->nTempReg++] = iReg; 006910 } 006911 } 006912 } 006913 006914 /* 006915 ** Allocate or deallocate a block of nReg consecutive registers. 006916 */ 006917 int sqlite3GetTempRange(Parse *pParse, int nReg){ 006918 int i, n; 006919 if( nReg==1 ) return sqlite3GetTempReg(pParse); 006920 i = pParse->iRangeReg; 006921 n = pParse->nRangeReg; 006922 if( nReg<=n ){ 006923 pParse->iRangeReg += nReg; 006924 pParse->nRangeReg -= nReg; 006925 }else{ 006926 i = pParse->nMem+1; 006927 pParse->nMem += nReg; 006928 } 006929 return i; 006930 } 006931 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ 006932 if( nReg==1 ){ 006933 sqlite3ReleaseTempReg(pParse, iReg); 006934 return; 006935 } 006936 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0); 006937 if( nReg>pParse->nRangeReg ){ 006938 pParse->nRangeReg = nReg; 006939 pParse->iRangeReg = iReg; 006940 } 006941 } 006942 006943 /* 006944 ** Mark all temporary registers as being unavailable for reuse. 006945 ** 006946 ** Always invoke this procedure after coding a subroutine or co-routine 006947 ** that might be invoked from other parts of the code, to ensure that 006948 ** the sub/co-routine does not use registers in common with the code that 006949 ** invokes the sub/co-routine. 006950 */ 006951 void sqlite3ClearTempRegCache(Parse *pParse){ 006952 pParse->nTempReg = 0; 006953 pParse->nRangeReg = 0; 006954 } 006955 006956 /* 006957 ** Make sure sufficient registers have been allocated so that 006958 ** iReg is a valid register number. 006959 */ 006960 void sqlite3TouchRegister(Parse *pParse, int iReg){ 006961 if( pParse->nMem<iReg ) pParse->nMem = iReg; 006962 } 006963 006964 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG) 006965 /* 006966 ** Return the latest reusable register in the set of all registers. 006967 ** The value returned is no less than iMin. If any register iMin or 006968 ** greater is in permanent use, then return one more than that last 006969 ** permanent register. 006970 */ 006971 int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){ 006972 const ExprList *pList = pParse->pConstExpr; 006973 if( pList ){ 006974 int i; 006975 for(i=0; i<pList->nExpr; i++){ 006976 if( pList->a[i].u.iConstExprReg>=iMin ){ 006977 iMin = pList->a[i].u.iConstExprReg + 1; 006978 } 006979 } 006980 } 006981 pParse->nTempReg = 0; 006982 pParse->nRangeReg = 0; 006983 return iMin; 006984 } 006985 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */ 006986 006987 /* 006988 ** Validate that no temporary register falls within the range of 006989 ** iFirst..iLast, inclusive. This routine is only call from within assert() 006990 ** statements. 006991 */ 006992 #ifdef SQLITE_DEBUG 006993 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){ 006994 int i; 006995 if( pParse->nRangeReg>0 006996 && pParse->iRangeReg+pParse->nRangeReg > iFirst 006997 && pParse->iRangeReg <= iLast 006998 ){ 006999 return 0; 007000 } 007001 for(i=0; i<pParse->nTempReg; i++){ 007002 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){ 007003 return 0; 007004 } 007005 } 007006 if( pParse->pConstExpr ){ 007007 ExprList *pList = pParse->pConstExpr; 007008 for(i=0; i<pList->nExpr; i++){ 007009 int iReg = pList->a[i].u.iConstExprReg; 007010 if( iReg==0 ) continue; 007011 if( iReg>=iFirst && iReg<=iLast ) return 0; 007012 } 007013 } 007014 return 1; 007015 } 007016 #endif /* SQLITE_DEBUG */