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