Snapshot of upstream SQLite 3.42.0
[sqlcipher.git] / src / expr.c
bloba81b4595bb8e456673dd038bfd3f9c66394bb9c8
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
15 #include "sqliteInt.h"
17 /* Forward declarations */
18 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
22 ** Return the affinity character for a single column of a table.
24 char sqlite3TableColumnAffinity(const Table *pTab, int iCol){
25 if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;
26 return pTab->aCol[iCol].affinity;
30 ** Return the 'affinity' of the expression pExpr if any.
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
37 ** i.e. the WHERE clause expressions in the following statements all
38 ** have an affinity:
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
45 char sqlite3ExprAffinity(const Expr *pExpr){
46 int op;
47 op = pExpr->op;
48 while( 1 /* exit-by-break */ ){
49 if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){
50 assert( ExprUseYTab(pExpr) );
51 assert( pExpr->y.pTab!=0 );
52 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
54 if( op==TK_SELECT ){
55 assert( ExprUseXSelect(pExpr) );
56 assert( pExpr->x.pSelect!=0 );
57 assert( pExpr->x.pSelect->pEList!=0 );
58 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
59 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
61 #ifndef SQLITE_OMIT_CAST
62 if( op==TK_CAST ){
63 assert( !ExprHasProperty(pExpr, EP_IntValue) );
64 return sqlite3AffinityType(pExpr->u.zToken, 0);
66 #endif
67 if( op==TK_SELECT_COLUMN ){
68 assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );
69 assert( pExpr->iColumn < pExpr->iTable );
70 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
71 return sqlite3ExprAffinity(
72 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
75 if( op==TK_VECTOR ){
76 assert( ExprUseXList(pExpr) );
77 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
79 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
80 assert( pExpr->op==TK_COLLATE
81 || pExpr->op==TK_IF_NULL_ROW
82 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
83 pExpr = pExpr->pLeft;
84 op = pExpr->op;
85 continue;
87 if( op!=TK_REGISTER || (op = pExpr->op2)==TK_REGISTER ) break;
89 return pExpr->affExpr;
93 ** Make a guess at all the possible datatypes of the result that could
94 ** be returned by an expression. Return a bitmask indicating the answer:
96 ** 0x01 Numeric
97 ** 0x02 Text
98 ** 0x04 Blob
100 ** If the expression must return NULL, then 0x00 is returned.
102 int sqlite3ExprDataType(const Expr *pExpr){
103 while( pExpr ){
104 switch( pExpr->op ){
105 case TK_COLLATE:
106 case TK_IF_NULL_ROW:
107 case TK_UPLUS: {
108 pExpr = pExpr->pLeft;
109 break;
111 case TK_NULL: {
112 pExpr = 0;
113 break;
115 case TK_STRING: {
116 return 0x02;
118 case TK_BLOB: {
119 return 0x04;
121 case TK_CONCAT: {
122 return 0x06;
124 case TK_VARIABLE:
125 case TK_AGG_FUNCTION:
126 case TK_FUNCTION: {
127 return 0x07;
129 case TK_COLUMN:
130 case TK_AGG_COLUMN:
131 case TK_SELECT:
132 case TK_CAST:
133 case TK_SELECT_COLUMN:
134 case TK_VECTOR: {
135 int aff = sqlite3ExprAffinity(pExpr);
136 if( aff>=SQLITE_AFF_NUMERIC ) return 0x05;
137 if( aff==SQLITE_AFF_TEXT ) return 0x06;
138 return 0x07;
140 case TK_CASE: {
141 int res = 0;
142 int ii;
143 ExprList *pList = pExpr->x.pList;
144 assert( ExprUseXList(pExpr) && pList!=0 );
145 assert( pList->nExpr > 0);
146 for(ii=1; ii<pList->nExpr; ii+=2){
147 res |= sqlite3ExprDataType(pList->a[ii].pExpr);
149 if( pList->nExpr % 2 ){
150 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);
152 return res;
154 default: {
155 return 0x01;
157 } /* End of switch(op) */
158 } /* End of while(pExpr) */
159 return 0x00;
163 ** Set the collating sequence for expression pExpr to be the collating
164 ** sequence named by pToken. Return a pointer to a new Expr node that
165 ** implements the COLLATE operator.
167 ** If a memory allocation error occurs, that fact is recorded in pParse->db
168 ** and the pExpr parameter is returned unchanged.
170 Expr *sqlite3ExprAddCollateToken(
171 const Parse *pParse, /* Parsing context */
172 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
173 const Token *pCollName, /* Name of collating sequence */
174 int dequote /* True to dequote pCollName */
176 if( pCollName->n>0 ){
177 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
178 if( pNew ){
179 pNew->pLeft = pExpr;
180 pNew->flags |= EP_Collate|EP_Skip;
181 pExpr = pNew;
184 return pExpr;
186 Expr *sqlite3ExprAddCollateString(
187 const Parse *pParse, /* Parsing context */
188 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
189 const char *zC /* The collating sequence name */
191 Token s;
192 assert( zC!=0 );
193 sqlite3TokenInit(&s, (char*)zC);
194 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
198 ** Skip over any TK_COLLATE operators.
200 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
201 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
202 assert( pExpr->op==TK_COLLATE );
203 pExpr = pExpr->pLeft;
205 return pExpr;
209 ** Skip over any TK_COLLATE operators and/or any unlikely()
210 ** or likelihood() or likely() functions at the root of an
211 ** expression.
213 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
214 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
215 if( ExprHasProperty(pExpr, EP_Unlikely) ){
216 assert( ExprUseXList(pExpr) );
217 assert( pExpr->x.pList->nExpr>0 );
218 assert( pExpr->op==TK_FUNCTION );
219 pExpr = pExpr->x.pList->a[0].pExpr;
220 }else{
221 assert( pExpr->op==TK_COLLATE );
222 pExpr = pExpr->pLeft;
225 return pExpr;
229 ** Return the collation sequence for the expression pExpr. If
230 ** there is no defined collating sequence, return NULL.
232 ** See also: sqlite3ExprNNCollSeq()
234 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
235 ** default collation if pExpr has no defined collation.
237 ** The collating sequence might be determined by a COLLATE operator
238 ** or by the presence of a column with a defined collating sequence.
239 ** COLLATE operators take first precedence. Left operands take
240 ** precedence over right operands.
242 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
243 sqlite3 *db = pParse->db;
244 CollSeq *pColl = 0;
245 const Expr *p = pExpr;
246 while( p ){
247 int op = p->op;
248 if( op==TK_REGISTER ) op = p->op2;
249 if( (op==TK_AGG_COLUMN && p->y.pTab!=0)
250 || op==TK_COLUMN || op==TK_TRIGGER
252 int j;
253 assert( ExprUseYTab(p) );
254 assert( p->y.pTab!=0 );
255 if( (j = p->iColumn)>=0 ){
256 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
257 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
259 break;
261 if( op==TK_CAST || op==TK_UPLUS ){
262 p = p->pLeft;
263 continue;
265 if( op==TK_VECTOR ){
266 assert( ExprUseXList(p) );
267 p = p->x.pList->a[0].pExpr;
268 continue;
270 if( op==TK_COLLATE ){
271 assert( !ExprHasProperty(p, EP_IntValue) );
272 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
273 break;
275 if( p->flags & EP_Collate ){
276 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
277 p = p->pLeft;
278 }else{
279 Expr *pNext = p->pRight;
280 /* The Expr.x union is never used at the same time as Expr.pRight */
281 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
282 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
283 int i;
284 for(i=0; i<p->x.pList->nExpr; i++){
285 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
286 pNext = p->x.pList->a[i].pExpr;
287 break;
291 p = pNext;
293 }else{
294 break;
297 if( sqlite3CheckCollSeq(pParse, pColl) ){
298 pColl = 0;
300 return pColl;
304 ** Return the collation sequence for the expression pExpr. If
305 ** there is no defined collating sequence, return a pointer to the
306 ** defautl collation sequence.
308 ** See also: sqlite3ExprCollSeq()
310 ** The sqlite3ExprCollSeq() routine works the same except that it
311 ** returns NULL if there is no defined collation.
313 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
314 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
315 if( p==0 ) p = pParse->db->pDfltColl;
316 assert( p!=0 );
317 return p;
321 ** Return TRUE if the two expressions have equivalent collating sequences.
323 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
324 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
325 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
326 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
330 ** pExpr is an operand of a comparison operator. aff2 is the
331 ** type affinity of the other operand. This routine returns the
332 ** type affinity that should be used for the comparison operator.
334 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
335 char aff1 = sqlite3ExprAffinity(pExpr);
336 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
337 /* Both sides of the comparison are columns. If one has numeric
338 ** affinity, use that. Otherwise use no affinity.
340 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
341 return SQLITE_AFF_NUMERIC;
342 }else{
343 return SQLITE_AFF_BLOB;
345 }else{
346 /* One side is a column, the other is not. Use the columns affinity. */
347 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
348 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
353 ** pExpr is a comparison operator. Return the type affinity that should
354 ** be applied to both operands prior to doing the comparison.
356 static char comparisonAffinity(const Expr *pExpr){
357 char aff;
358 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
359 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
360 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
361 assert( pExpr->pLeft );
362 aff = sqlite3ExprAffinity(pExpr->pLeft);
363 if( pExpr->pRight ){
364 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
365 }else if( ExprUseXSelect(pExpr) ){
366 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
367 }else if( aff==0 ){
368 aff = SQLITE_AFF_BLOB;
370 return aff;
374 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
375 ** idx_affinity is the affinity of an indexed column. Return true
376 ** if the index with affinity idx_affinity may be used to implement
377 ** the comparison in pExpr.
379 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
380 char aff = comparisonAffinity(pExpr);
381 if( aff<SQLITE_AFF_TEXT ){
382 return 1;
384 if( aff==SQLITE_AFF_TEXT ){
385 return idx_affinity==SQLITE_AFF_TEXT;
387 return sqlite3IsNumericAffinity(idx_affinity);
391 ** Return the P5 value that should be used for a binary comparison
392 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
394 static u8 binaryCompareP5(
395 const Expr *pExpr1, /* Left operand */
396 const Expr *pExpr2, /* Right operand */
397 int jumpIfNull /* Extra flags added to P5 */
399 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
400 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
401 return aff;
405 ** Return a pointer to the collation sequence that should be used by
406 ** a binary comparison operator comparing pLeft and pRight.
408 ** If the left hand expression has a collating sequence type, then it is
409 ** used. Otherwise the collation sequence for the right hand expression
410 ** is used, or the default (BINARY) if neither expression has a collating
411 ** type.
413 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
414 ** it is not considered.
416 CollSeq *sqlite3BinaryCompareCollSeq(
417 Parse *pParse,
418 const Expr *pLeft,
419 const Expr *pRight
421 CollSeq *pColl;
422 assert( pLeft );
423 if( pLeft->flags & EP_Collate ){
424 pColl = sqlite3ExprCollSeq(pParse, pLeft);
425 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
426 pColl = sqlite3ExprCollSeq(pParse, pRight);
427 }else{
428 pColl = sqlite3ExprCollSeq(pParse, pLeft);
429 if( !pColl ){
430 pColl = sqlite3ExprCollSeq(pParse, pRight);
433 return pColl;
436 /* Expresssion p is a comparison operator. Return a collation sequence
437 ** appropriate for the comparison operator.
439 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
440 ** However, if the OP_Commuted flag is set, then the order of the operands
441 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
442 ** correct collating sequence is found.
444 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
445 if( ExprHasProperty(p, EP_Commuted) ){
446 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
447 }else{
448 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
453 ** Generate code for a comparison operator.
455 static int codeCompare(
456 Parse *pParse, /* The parsing (and code generating) context */
457 Expr *pLeft, /* The left operand */
458 Expr *pRight, /* The right operand */
459 int opcode, /* The comparison opcode */
460 int in1, int in2, /* Register holding operands */
461 int dest, /* Jump here if true. */
462 int jumpIfNull, /* If true, jump if either operand is NULL */
463 int isCommuted /* The comparison has been commuted */
465 int p5;
466 int addr;
467 CollSeq *p4;
469 if( pParse->nErr ) return 0;
470 if( isCommuted ){
471 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
472 }else{
473 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
475 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
476 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
477 (void*)p4, P4_COLLSEQ);
478 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
479 return addr;
483 ** Return true if expression pExpr is a vector, or false otherwise.
485 ** A vector is defined as any expression that results in two or more
486 ** columns of result. Every TK_VECTOR node is an vector because the
487 ** parser will not generate a TK_VECTOR with fewer than two entries.
488 ** But a TK_SELECT might be either a vector or a scalar. It is only
489 ** considered a vector if it has two or more result columns.
491 int sqlite3ExprIsVector(const Expr *pExpr){
492 return sqlite3ExprVectorSize(pExpr)>1;
496 ** If the expression passed as the only argument is of type TK_VECTOR
497 ** return the number of expressions in the vector. Or, if the expression
498 ** is a sub-select, return the number of columns in the sub-select. For
499 ** any other type of expression, return 1.
501 int sqlite3ExprVectorSize(const Expr *pExpr){
502 u8 op = pExpr->op;
503 if( op==TK_REGISTER ) op = pExpr->op2;
504 if( op==TK_VECTOR ){
505 assert( ExprUseXList(pExpr) );
506 return pExpr->x.pList->nExpr;
507 }else if( op==TK_SELECT ){
508 assert( ExprUseXSelect(pExpr) );
509 return pExpr->x.pSelect->pEList->nExpr;
510 }else{
511 return 1;
516 ** Return a pointer to a subexpression of pVector that is the i-th
517 ** column of the vector (numbered starting with 0). The caller must
518 ** ensure that i is within range.
520 ** If pVector is really a scalar (and "scalar" here includes subqueries
521 ** that return a single column!) then return pVector unmodified.
523 ** pVector retains ownership of the returned subexpression.
525 ** If the vector is a (SELECT ...) then the expression returned is
526 ** just the expression for the i-th term of the result set, and may
527 ** not be ready for evaluation because the table cursor has not yet
528 ** been positioned.
530 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
531 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
532 if( sqlite3ExprIsVector(pVector) ){
533 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
534 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
535 assert( ExprUseXSelect(pVector) );
536 return pVector->x.pSelect->pEList->a[i].pExpr;
537 }else{
538 assert( ExprUseXList(pVector) );
539 return pVector->x.pList->a[i].pExpr;
542 return pVector;
546 ** Compute and return a new Expr object which when passed to
547 ** sqlite3ExprCode() will generate all necessary code to compute
548 ** the iField-th column of the vector expression pVector.
550 ** It is ok for pVector to be a scalar (as long as iField==0).
551 ** In that case, this routine works like sqlite3ExprDup().
553 ** The caller owns the returned Expr object and is responsible for
554 ** ensuring that the returned value eventually gets freed.
556 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
557 ** then the returned object will reference pVector and so pVector must remain
558 ** valid for the life of the returned object. If pVector is a TK_VECTOR
559 ** or a scalar expression, then it can be deleted as soon as this routine
560 ** returns.
562 ** A trick to cause a TK_SELECT pVector to be deleted together with
563 ** the returned Expr object is to attach the pVector to the pRight field
564 ** of the returned TK_SELECT_COLUMN Expr object.
566 Expr *sqlite3ExprForVectorField(
567 Parse *pParse, /* Parsing context */
568 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
569 int iField, /* Which column of the vector to return */
570 int nField /* Total number of columns in the vector */
572 Expr *pRet;
573 if( pVector->op==TK_SELECT ){
574 assert( ExprUseXSelect(pVector) );
575 /* The TK_SELECT_COLUMN Expr node:
577 ** pLeft: pVector containing TK_SELECT. Not deleted.
578 ** pRight: not used. But recursively deleted.
579 ** iColumn: Index of a column in pVector
580 ** iTable: 0 or the number of columns on the LHS of an assignment
581 ** pLeft->iTable: First in an array of register holding result, or 0
582 ** if the result is not yet computed.
584 ** sqlite3ExprDelete() specifically skips the recursive delete of
585 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
586 ** can be attached to pRight to cause this node to take ownership of
587 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
588 ** with the same pLeft pointer to the pVector, but only one of them
589 ** will own the pVector.
591 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
592 if( pRet ){
593 pRet->iTable = nField;
594 pRet->iColumn = iField;
595 pRet->pLeft = pVector;
597 }else{
598 if( pVector->op==TK_VECTOR ){
599 Expr **ppVector;
600 assert( ExprUseXList(pVector) );
601 ppVector = &pVector->x.pList->a[iField].pExpr;
602 pVector = *ppVector;
603 if( IN_RENAME_OBJECT ){
604 /* This must be a vector UPDATE inside a trigger */
605 *ppVector = 0;
606 return pVector;
609 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
611 return pRet;
615 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
616 ** it. Return the register in which the result is stored (or, if the
617 ** sub-select returns more than one column, the first in an array
618 ** of registers in which the result is stored).
620 ** If pExpr is not a TK_SELECT expression, return 0.
622 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
623 int reg = 0;
624 #ifndef SQLITE_OMIT_SUBQUERY
625 if( pExpr->op==TK_SELECT ){
626 reg = sqlite3CodeSubselect(pParse, pExpr);
628 #endif
629 return reg;
633 ** Argument pVector points to a vector expression - either a TK_VECTOR
634 ** or TK_SELECT that returns more than one column. This function returns
635 ** the register number of a register that contains the value of
636 ** element iField of the vector.
638 ** If pVector is a TK_SELECT expression, then code for it must have
639 ** already been generated using the exprCodeSubselect() routine. In this
640 ** case parameter regSelect should be the first in an array of registers
641 ** containing the results of the sub-select.
643 ** If pVector is of type TK_VECTOR, then code for the requested field
644 ** is generated. In this case (*pRegFree) may be set to the number of
645 ** a temporary register to be freed by the caller before returning.
647 ** Before returning, output parameter (*ppExpr) is set to point to the
648 ** Expr object corresponding to element iElem of the vector.
650 static int exprVectorRegister(
651 Parse *pParse, /* Parse context */
652 Expr *pVector, /* Vector to extract element from */
653 int iField, /* Field to extract from pVector */
654 int regSelect, /* First in array of registers */
655 Expr **ppExpr, /* OUT: Expression element */
656 int *pRegFree /* OUT: Temp register to free */
658 u8 op = pVector->op;
659 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
660 if( op==TK_REGISTER ){
661 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
662 return pVector->iTable+iField;
664 if( op==TK_SELECT ){
665 assert( ExprUseXSelect(pVector) );
666 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
667 return regSelect+iField;
669 if( op==TK_VECTOR ){
670 assert( ExprUseXList(pVector) );
671 *ppExpr = pVector->x.pList->a[iField].pExpr;
672 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
674 return 0;
678 ** Expression pExpr is a comparison between two vector values. Compute
679 ** the result of the comparison (1, 0, or NULL) and write that
680 ** result into register dest.
682 ** The caller must satisfy the following preconditions:
684 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
685 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
686 ** otherwise: op==pExpr->op and p5==0
688 static void codeVectorCompare(
689 Parse *pParse, /* Code generator context */
690 Expr *pExpr, /* The comparison operation */
691 int dest, /* Write results into this register */
692 u8 op, /* Comparison operator */
693 u8 p5 /* SQLITE_NULLEQ or zero */
695 Vdbe *v = pParse->pVdbe;
696 Expr *pLeft = pExpr->pLeft;
697 Expr *pRight = pExpr->pRight;
698 int nLeft = sqlite3ExprVectorSize(pLeft);
699 int i;
700 int regLeft = 0;
701 int regRight = 0;
702 u8 opx = op;
703 int addrCmp = 0;
704 int addrDone = sqlite3VdbeMakeLabel(pParse);
705 int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
707 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
708 if( pParse->nErr ) return;
709 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
710 sqlite3ErrorMsg(pParse, "row value misused");
711 return;
713 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
714 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
715 || pExpr->op==TK_LT || pExpr->op==TK_GT
716 || pExpr->op==TK_LE || pExpr->op==TK_GE
718 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
719 || (pExpr->op==TK_ISNOT && op==TK_NE) );
720 assert( p5==0 || pExpr->op!=op );
721 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
723 if( op==TK_LE ) opx = TK_LT;
724 if( op==TK_GE ) opx = TK_GT;
725 if( op==TK_NE ) opx = TK_EQ;
727 regLeft = exprCodeSubselect(pParse, pLeft);
728 regRight = exprCodeSubselect(pParse, pRight);
730 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
731 for(i=0; 1 /*Loop exits by "break"*/; i++){
732 int regFree1 = 0, regFree2 = 0;
733 Expr *pL = 0, *pR = 0;
734 int r1, r2;
735 assert( i>=0 && i<nLeft );
736 if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
737 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
738 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
739 addrCmp = sqlite3VdbeCurrentAddr(v);
740 codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
741 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
742 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
743 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
744 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
745 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
746 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
747 sqlite3ReleaseTempReg(pParse, regFree1);
748 sqlite3ReleaseTempReg(pParse, regFree2);
749 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
750 addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
751 testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
752 testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
754 if( p5==SQLITE_NULLEQ ){
755 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
756 }else{
757 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
759 if( i==nLeft-1 ){
760 break;
762 if( opx==TK_EQ ){
763 sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
764 }else{
765 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
766 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
767 if( i==nLeft-2 ) opx = op;
770 sqlite3VdbeJumpHere(v, addrCmp);
771 sqlite3VdbeResolveLabel(v, addrDone);
772 if( op==TK_NE ){
773 sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
777 #if SQLITE_MAX_EXPR_DEPTH>0
779 ** Check that argument nHeight is less than or equal to the maximum
780 ** expression depth allowed. If it is not, leave an error message in
781 ** pParse.
783 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
784 int rc = SQLITE_OK;
785 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
786 if( nHeight>mxHeight ){
787 sqlite3ErrorMsg(pParse,
788 "Expression tree is too large (maximum depth %d)", mxHeight
790 rc = SQLITE_ERROR;
792 return rc;
795 /* The following three functions, heightOfExpr(), heightOfExprList()
796 ** and heightOfSelect(), are used to determine the maximum height
797 ** of any expression tree referenced by the structure passed as the
798 ** first argument.
800 ** If this maximum height is greater than the current value pointed
801 ** to by pnHeight, the second parameter, then set *pnHeight to that
802 ** value.
804 static void heightOfExpr(const Expr *p, int *pnHeight){
805 if( p ){
806 if( p->nHeight>*pnHeight ){
807 *pnHeight = p->nHeight;
811 static void heightOfExprList(const ExprList *p, int *pnHeight){
812 if( p ){
813 int i;
814 for(i=0; i<p->nExpr; i++){
815 heightOfExpr(p->a[i].pExpr, pnHeight);
819 static void heightOfSelect(const Select *pSelect, int *pnHeight){
820 const Select *p;
821 for(p=pSelect; p; p=p->pPrior){
822 heightOfExpr(p->pWhere, pnHeight);
823 heightOfExpr(p->pHaving, pnHeight);
824 heightOfExpr(p->pLimit, pnHeight);
825 heightOfExprList(p->pEList, pnHeight);
826 heightOfExprList(p->pGroupBy, pnHeight);
827 heightOfExprList(p->pOrderBy, pnHeight);
832 ** Set the Expr.nHeight variable in the structure passed as an
833 ** argument. An expression with no children, Expr.pList or
834 ** Expr.pSelect member has a height of 1. Any other expression
835 ** has a height equal to the maximum height of any other
836 ** referenced Expr plus one.
838 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
839 ** if appropriate.
841 static void exprSetHeight(Expr *p){
842 int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
843 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
844 nHeight = p->pRight->nHeight;
846 if( ExprUseXSelect(p) ){
847 heightOfSelect(p->x.pSelect, &nHeight);
848 }else if( p->x.pList ){
849 heightOfExprList(p->x.pList, &nHeight);
850 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
852 p->nHeight = nHeight + 1;
856 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
857 ** the height is greater than the maximum allowed expression depth,
858 ** leave an error in pParse.
860 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
861 ** Expr.flags.
863 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
864 if( pParse->nErr ) return;
865 exprSetHeight(p);
866 sqlite3ExprCheckHeight(pParse, p->nHeight);
870 ** Return the maximum height of any expression tree referenced
871 ** by the select statement passed as an argument.
873 int sqlite3SelectExprHeight(const Select *p){
874 int nHeight = 0;
875 heightOfSelect(p, &nHeight);
876 return nHeight;
878 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
880 ** Propagate all EP_Propagate flags from the Expr.x.pList into
881 ** Expr.flags.
883 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
884 if( pParse->nErr ) return;
885 if( p && ExprUseXList(p) && p->x.pList ){
886 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
889 #define exprSetHeight(y)
890 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
893 ** This routine is the core allocator for Expr nodes.
895 ** Construct a new expression node and return a pointer to it. Memory
896 ** for this node and for the pToken argument is a single allocation
897 ** obtained from sqlite3DbMalloc(). The calling function
898 ** is responsible for making sure the node eventually gets freed.
900 ** If dequote is true, then the token (if it exists) is dequoted.
901 ** If dequote is false, no dequoting is performed. The deQuote
902 ** parameter is ignored if pToken is NULL or if the token does not
903 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
904 ** then the EP_DblQuoted flag is set on the expression node.
906 ** Special case: If op==TK_INTEGER and pToken points to a string that
907 ** can be translated into a 32-bit integer, then the token is not
908 ** stored in u.zToken. Instead, the integer values is written
909 ** into u.iValue and the EP_IntValue flag is set. No extra storage
910 ** is allocated to hold the integer text and the dequote flag is ignored.
912 Expr *sqlite3ExprAlloc(
913 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
914 int op, /* Expression opcode */
915 const Token *pToken, /* Token argument. Might be NULL */
916 int dequote /* True to dequote */
918 Expr *pNew;
919 int nExtra = 0;
920 int iValue = 0;
922 assert( db!=0 );
923 if( pToken ){
924 if( op!=TK_INTEGER || pToken->z==0
925 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
926 nExtra = pToken->n+1;
927 assert( iValue>=0 );
930 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
931 if( pNew ){
932 memset(pNew, 0, sizeof(Expr));
933 pNew->op = (u8)op;
934 pNew->iAgg = -1;
935 if( pToken ){
936 if( nExtra==0 ){
937 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
938 pNew->u.iValue = iValue;
939 }else{
940 pNew->u.zToken = (char*)&pNew[1];
941 assert( pToken->z!=0 || pToken->n==0 );
942 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
943 pNew->u.zToken[pToken->n] = 0;
944 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
945 sqlite3DequoteExpr(pNew);
949 #if SQLITE_MAX_EXPR_DEPTH>0
950 pNew->nHeight = 1;
951 #endif
953 return pNew;
957 ** Allocate a new expression node from a zero-terminated token that has
958 ** already been dequoted.
960 Expr *sqlite3Expr(
961 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
962 int op, /* Expression opcode */
963 const char *zToken /* Token argument. Might be NULL */
965 Token x;
966 x.z = zToken;
967 x.n = sqlite3Strlen30(zToken);
968 return sqlite3ExprAlloc(db, op, &x, 0);
972 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
974 ** If pRoot==NULL that means that a memory allocation error has occurred.
975 ** In that case, delete the subtrees pLeft and pRight.
977 void sqlite3ExprAttachSubtrees(
978 sqlite3 *db,
979 Expr *pRoot,
980 Expr *pLeft,
981 Expr *pRight
983 if( pRoot==0 ){
984 assert( db->mallocFailed );
985 sqlite3ExprDelete(db, pLeft);
986 sqlite3ExprDelete(db, pRight);
987 }else{
988 assert( ExprUseXList(pRoot) );
989 assert( pRoot->x.pSelect==0 );
990 if( pRight ){
991 pRoot->pRight = pRight;
992 pRoot->flags |= EP_Propagate & pRight->flags;
993 #if SQLITE_MAX_EXPR_DEPTH>0
994 pRoot->nHeight = pRight->nHeight+1;
995 }else{
996 pRoot->nHeight = 1;
997 #endif
999 if( pLeft ){
1000 pRoot->pLeft = pLeft;
1001 pRoot->flags |= EP_Propagate & pLeft->flags;
1002 #if SQLITE_MAX_EXPR_DEPTH>0
1003 if( pLeft->nHeight>=pRoot->nHeight ){
1004 pRoot->nHeight = pLeft->nHeight+1;
1006 #endif
1012 ** Allocate an Expr node which joins as many as two subtrees.
1014 ** One or both of the subtrees can be NULL. Return a pointer to the new
1015 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1016 ** free the subtrees and return NULL.
1018 Expr *sqlite3PExpr(
1019 Parse *pParse, /* Parsing context */
1020 int op, /* Expression opcode */
1021 Expr *pLeft, /* Left operand */
1022 Expr *pRight /* Right operand */
1024 Expr *p;
1025 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
1026 if( p ){
1027 memset(p, 0, sizeof(Expr));
1028 p->op = op & 0xff;
1029 p->iAgg = -1;
1030 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
1031 sqlite3ExprCheckHeight(pParse, p->nHeight);
1032 }else{
1033 sqlite3ExprDelete(pParse->db, pLeft);
1034 sqlite3ExprDelete(pParse->db, pRight);
1036 return p;
1040 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1041 ** do a memory allocation failure) then delete the pSelect object.
1043 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
1044 if( pExpr ){
1045 pExpr->x.pSelect = pSelect;
1046 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
1047 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
1048 }else{
1049 assert( pParse->db->mallocFailed );
1050 sqlite3SelectDelete(pParse->db, pSelect);
1055 ** Expression list pEList is a list of vector values. This function
1056 ** converts the contents of pEList to a VALUES(...) Select statement
1057 ** returning 1 row for each element of the list. For example, the
1058 ** expression list:
1060 ** ( (1,2), (3,4) (5,6) )
1062 ** is translated to the equivalent of:
1064 ** VALUES(1,2), (3,4), (5,6)
1066 ** Each of the vector values in pEList must contain exactly nElem terms.
1067 ** If a list element that is not a vector or does not contain nElem terms,
1068 ** an error message is left in pParse.
1070 ** This is used as part of processing IN(...) expressions with a list
1071 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1073 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){
1074 int ii;
1075 Select *pRet = 0;
1076 assert( nElem>1 );
1077 for(ii=0; ii<pEList->nExpr; ii++){
1078 Select *pSel;
1079 Expr *pExpr = pEList->a[ii].pExpr;
1080 int nExprElem;
1081 if( pExpr->op==TK_VECTOR ){
1082 assert( ExprUseXList(pExpr) );
1083 nExprElem = pExpr->x.pList->nExpr;
1084 }else{
1085 nExprElem = 1;
1087 if( nExprElem!=nElem ){
1088 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
1089 nExprElem, nExprElem>1?"s":"", nElem
1091 break;
1093 assert( ExprUseXList(pExpr) );
1094 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
1095 pExpr->x.pList = 0;
1096 if( pSel ){
1097 if( pRet ){
1098 pSel->op = TK_ALL;
1099 pSel->pPrior = pRet;
1101 pRet = pSel;
1105 if( pRet && pRet->pPrior ){
1106 pRet->selFlags |= SF_MultiValue;
1108 sqlite3ExprListDelete(pParse->db, pEList);
1109 return pRet;
1113 ** Join two expressions using an AND operator. If either expression is
1114 ** NULL, then just return the other expression.
1116 ** If one side or the other of the AND is known to be false, and neither side
1117 ** is part of an ON clause, then instead of returning an AND expression,
1118 ** just return a constant expression with a value of false.
1120 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
1121 sqlite3 *db = pParse->db;
1122 if( pLeft==0 ){
1123 return pRight;
1124 }else if( pRight==0 ){
1125 return pLeft;
1126 }else{
1127 u32 f = pLeft->flags | pRight->flags;
1128 if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse
1129 && !IN_RENAME_OBJECT
1131 sqlite3ExprDeferredDelete(pParse, pLeft);
1132 sqlite3ExprDeferredDelete(pParse, pRight);
1133 return sqlite3Expr(db, TK_INTEGER, "0");
1134 }else{
1135 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
1141 ** Construct a new expression node for a function with multiple
1142 ** arguments.
1144 Expr *sqlite3ExprFunction(
1145 Parse *pParse, /* Parsing context */
1146 ExprList *pList, /* Argument list */
1147 const Token *pToken, /* Name of the function */
1148 int eDistinct /* SF_Distinct or SF_ALL or 0 */
1150 Expr *pNew;
1151 sqlite3 *db = pParse->db;
1152 assert( pToken );
1153 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
1154 if( pNew==0 ){
1155 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
1156 return 0;
1158 assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) );
1159 pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
1160 if( pList
1161 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
1162 && !pParse->nested
1164 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
1166 pNew->x.pList = pList;
1167 ExprSetProperty(pNew, EP_HasFunc);
1168 assert( ExprUseXList(pNew) );
1169 sqlite3ExprSetHeightAndFlags(pParse, pNew);
1170 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
1171 return pNew;
1175 ** Check to see if a function is usable according to current access
1176 ** rules:
1178 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1180 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1181 ** top-level SQL
1183 ** If the function is not usable, create an error.
1185 void sqlite3ExprFunctionUsable(
1186 Parse *pParse, /* Parsing and code generating context */
1187 const Expr *pExpr, /* The function invocation */
1188 const FuncDef *pDef /* The function being invoked */
1190 assert( !IN_RENAME_OBJECT );
1191 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
1192 if( ExprHasProperty(pExpr, EP_FromDDL) ){
1193 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
1194 || (pParse->db->flags & SQLITE_TrustedSchema)==0
1196 /* Functions prohibited in triggers and views if:
1197 ** (1) tagged with SQLITE_DIRECTONLY
1198 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1199 ** is tagged with SQLITE_FUNC_UNSAFE) and
1200 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1201 ** that the schema is possibly tainted).
1203 sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr);
1209 ** Assign a variable number to an expression that encodes a wildcard
1210 ** in the original SQL statement.
1212 ** Wildcards consisting of a single "?" are assigned the next sequential
1213 ** variable number.
1215 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1216 ** sure "nnn" is not too big to avoid a denial of service attack when
1217 ** the SQL statement comes from an external source.
1219 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1220 ** as the previous instance of the same wildcard. Or if this is the first
1221 ** instance of the wildcard, the next sequential variable number is
1222 ** assigned.
1224 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1225 sqlite3 *db = pParse->db;
1226 const char *z;
1227 ynVar x;
1229 if( pExpr==0 ) return;
1230 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1231 z = pExpr->u.zToken;
1232 assert( z!=0 );
1233 assert( z[0]!=0 );
1234 assert( n==(u32)sqlite3Strlen30(z) );
1235 if( z[1]==0 ){
1236 /* Wildcard of the form "?". Assign the next variable number */
1237 assert( z[0]=='?' );
1238 x = (ynVar)(++pParse->nVar);
1239 }else{
1240 int doAdd = 0;
1241 if( z[0]=='?' ){
1242 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1243 ** use it as the variable number */
1244 i64 i;
1245 int bOk;
1246 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1247 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1248 bOk = 1;
1249 }else{
1250 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1252 testcase( i==0 );
1253 testcase( i==1 );
1254 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1255 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1256 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1257 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1258 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1259 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1260 return;
1262 x = (ynVar)i;
1263 if( x>pParse->nVar ){
1264 pParse->nVar = (int)x;
1265 doAdd = 1;
1266 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1267 doAdd = 1;
1269 }else{
1270 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1271 ** number as the prior appearance of the same name, or if the name
1272 ** has never appeared before, reuse the same variable number
1274 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1275 if( x==0 ){
1276 x = (ynVar)(++pParse->nVar);
1277 doAdd = 1;
1280 if( doAdd ){
1281 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1284 pExpr->iColumn = x;
1285 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1286 sqlite3ErrorMsg(pParse, "too many SQL variables");
1287 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1292 ** Recursively delete an expression tree.
1294 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1295 assert( p!=0 );
1296 assert( db!=0 );
1297 assert( !ExprUseUValue(p) || p->u.iValue>=0 );
1298 assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
1299 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
1300 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
1301 #ifdef SQLITE_DEBUG
1302 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1303 assert( p->pLeft==0 );
1304 assert( p->pRight==0 );
1305 assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
1306 assert( !ExprUseXList(p) || p->x.pList==0 );
1308 #endif
1309 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1310 /* The Expr.x union is never used at the same time as Expr.pRight */
1311 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
1312 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1313 if( p->pRight ){
1314 assert( !ExprHasProperty(p, EP_WinFunc) );
1315 sqlite3ExprDeleteNN(db, p->pRight);
1316 }else if( ExprUseXSelect(p) ){
1317 assert( !ExprHasProperty(p, EP_WinFunc) );
1318 sqlite3SelectDelete(db, p->x.pSelect);
1319 }else{
1320 sqlite3ExprListDelete(db, p->x.pList);
1321 #ifndef SQLITE_OMIT_WINDOWFUNC
1322 if( ExprHasProperty(p, EP_WinFunc) ){
1323 sqlite3WindowDelete(db, p->y.pWin);
1325 #endif
1328 if( !ExprHasProperty(p, EP_Static) ){
1329 sqlite3DbNNFreeNN(db, p);
1332 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1333 if( p ) sqlite3ExprDeleteNN(db, p);
1337 ** Clear both elements of an OnOrUsing object
1339 void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){
1340 if( p==0 ){
1341 /* Nothing to clear */
1342 }else if( p->pOn ){
1343 sqlite3ExprDeleteNN(db, p->pOn);
1344 }else if( p->pUsing ){
1345 sqlite3IdListDelete(db, p->pUsing);
1350 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1351 ** This is similar to sqlite3ExprDelete() except that the delete is
1352 ** deferred untilthe pParse is deleted.
1354 ** The pExpr might be deleted immediately on an OOM error.
1356 ** The deferred delete is (currently) implemented by adding the
1357 ** pExpr to the pParse->pConstExpr list with a register number of 0.
1359 void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
1360 sqlite3ParserAddCleanup(pParse,
1361 (void(*)(sqlite3*,void*))sqlite3ExprDelete,
1362 pExpr);
1365 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1366 ** expression.
1368 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1369 if( p ){
1370 if( IN_RENAME_OBJECT ){
1371 sqlite3RenameExprUnmap(pParse, p);
1373 sqlite3ExprDeleteNN(pParse->db, p);
1378 ** Return the number of bytes allocated for the expression structure
1379 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1380 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1382 static int exprStructSize(const Expr *p){
1383 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1384 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1385 return EXPR_FULLSIZE;
1389 ** The dupedExpr*Size() routines each return the number of bytes required
1390 ** to store a copy of an expression or expression tree. They differ in
1391 ** how much of the tree is measured.
1393 ** dupedExprStructSize() Size of only the Expr structure
1394 ** dupedExprNodeSize() Size of Expr + space for token
1395 ** dupedExprSize() Expr + token + subtree components
1397 ***************************************************************************
1399 ** The dupedExprStructSize() function returns two values OR-ed together:
1400 ** (1) the space required for a copy of the Expr structure only and
1401 ** (2) the EP_xxx flags that indicate what the structure size should be.
1402 ** The return values is always one of:
1404 ** EXPR_FULLSIZE
1405 ** EXPR_REDUCEDSIZE | EP_Reduced
1406 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1408 ** The size of the structure can be found by masking the return value
1409 ** of this routine with 0xfff. The flags can be found by masking the
1410 ** return value with EP_Reduced|EP_TokenOnly.
1412 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1413 ** (unreduced) Expr objects as they or originally constructed by the parser.
1414 ** During expression analysis, extra information is computed and moved into
1415 ** later parts of the Expr object and that extra information might get chopped
1416 ** off if the expression is reduced. Note also that it does not work to
1417 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1418 ** to reduce a pristine expression tree from the parser. The implementation
1419 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1420 ** to enforce this constraint.
1422 static int dupedExprStructSize(const Expr *p, int flags){
1423 int nSize;
1424 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1425 assert( EXPR_FULLSIZE<=0xfff );
1426 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1427 if( 0==flags || p->op==TK_SELECT_COLUMN
1428 #ifndef SQLITE_OMIT_WINDOWFUNC
1429 || ExprHasProperty(p, EP_WinFunc)
1430 #endif
1432 nSize = EXPR_FULLSIZE;
1433 }else{
1434 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1435 assert( !ExprHasProperty(p, EP_OuterON) );
1436 assert( !ExprHasVVAProperty(p, EP_NoReduce) );
1437 if( p->pLeft || p->x.pList ){
1438 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1439 }else{
1440 assert( p->pRight==0 );
1441 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1444 return nSize;
1448 ** This function returns the space in bytes required to store the copy
1449 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1450 ** string is defined.)
1452 static int dupedExprNodeSize(const Expr *p, int flags){
1453 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1454 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1455 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1457 return ROUND8(nByte);
1461 ** Return the number of bytes required to create a duplicate of the
1462 ** expression passed as the first argument. The second argument is a
1463 ** mask containing EXPRDUP_XXX flags.
1465 ** The value returned includes space to create a copy of the Expr struct
1466 ** itself and the buffer referred to by Expr.u.zToken, if any.
1468 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1469 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1470 ** and Expr.pRight variables (but not for any structures pointed to or
1471 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1473 static int dupedExprSize(const Expr *p, int flags){
1474 int nByte = 0;
1475 if( p ){
1476 nByte = dupedExprNodeSize(p, flags);
1477 if( flags&EXPRDUP_REDUCE ){
1478 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
1481 return nByte;
1485 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1486 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1487 ** to store the copy of expression p, the copies of p->u.zToken
1488 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1489 ** if any. Before returning, *pzBuffer is set to the first byte past the
1490 ** portion of the buffer copied into by this function.
1492 static Expr *exprDup(sqlite3 *db, const Expr *p, int dupFlags, u8 **pzBuffer){
1493 Expr *pNew; /* Value to return */
1494 u8 *zAlloc; /* Memory space from which to build Expr object */
1495 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1497 assert( db!=0 );
1498 assert( p );
1499 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1500 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
1502 /* Figure out where to write the new Expr structure. */
1503 if( pzBuffer ){
1504 zAlloc = *pzBuffer;
1505 staticFlag = EP_Static;
1506 assert( zAlloc!=0 );
1507 }else{
1508 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1509 staticFlag = 0;
1511 pNew = (Expr *)zAlloc;
1513 if( pNew ){
1514 /* Set nNewSize to the size allocated for the structure pointed to
1515 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1516 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1517 ** by the copy of the p->u.zToken string (if any).
1519 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1520 const int nNewSize = nStructSize & 0xfff;
1521 int nToken;
1522 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1523 nToken = sqlite3Strlen30(p->u.zToken) + 1;
1524 }else{
1525 nToken = 0;
1527 if( dupFlags ){
1528 assert( ExprHasProperty(p, EP_Reduced)==0 );
1529 memcpy(zAlloc, p, nNewSize);
1530 }else{
1531 u32 nSize = (u32)exprStructSize(p);
1532 memcpy(zAlloc, p, nSize);
1533 if( nSize<EXPR_FULLSIZE ){
1534 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1538 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1539 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
1540 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1541 pNew->flags |= staticFlag;
1542 ExprClearVVAProperties(pNew);
1543 if( dupFlags ){
1544 ExprSetVVAProperty(pNew, EP_Immutable);
1547 /* Copy the p->u.zToken string, if any. */
1548 if( nToken ){
1549 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1550 memcpy(zToken, p->u.zToken, nToken);
1553 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
1554 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1555 if( ExprUseXSelect(p) ){
1556 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1557 }else{
1558 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1562 /* Fill in pNew->pLeft and pNew->pRight. */
1563 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
1564 zAlloc += dupedExprNodeSize(p, dupFlags);
1565 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
1566 pNew->pLeft = p->pLeft ?
1567 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1568 pNew->pRight = p->pRight ?
1569 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
1571 #ifndef SQLITE_OMIT_WINDOWFUNC
1572 if( ExprHasProperty(p, EP_WinFunc) ){
1573 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1574 assert( ExprHasProperty(pNew, EP_WinFunc) );
1576 #endif /* SQLITE_OMIT_WINDOWFUNC */
1577 if( pzBuffer ){
1578 *pzBuffer = zAlloc;
1580 }else{
1581 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1582 if( pNew->op==TK_SELECT_COLUMN ){
1583 pNew->pLeft = p->pLeft;
1584 assert( p->pRight==0 || p->pRight==p->pLeft
1585 || ExprHasProperty(p->pLeft, EP_Subquery) );
1586 }else{
1587 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1589 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1593 return pNew;
1597 ** Create and return a deep copy of the object passed as the second
1598 ** argument. If an OOM condition is encountered, NULL is returned
1599 ** and the db->mallocFailed flag set.
1601 #ifndef SQLITE_OMIT_CTE
1602 With *sqlite3WithDup(sqlite3 *db, With *p){
1603 With *pRet = 0;
1604 if( p ){
1605 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1606 pRet = sqlite3DbMallocZero(db, nByte);
1607 if( pRet ){
1608 int i;
1609 pRet->nCte = p->nCte;
1610 for(i=0; i<p->nCte; i++){
1611 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1612 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1613 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1614 pRet->a[i].eM10d = p->a[i].eM10d;
1618 return pRet;
1620 #else
1621 # define sqlite3WithDup(x,y) 0
1622 #endif
1624 #ifndef SQLITE_OMIT_WINDOWFUNC
1626 ** The gatherSelectWindows() procedure and its helper routine
1627 ** gatherSelectWindowsCallback() are used to scan all the expressions
1628 ** an a newly duplicated SELECT statement and gather all of the Window
1629 ** objects found there, assembling them onto the linked list at Select->pWin.
1631 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1632 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1633 Select *pSelect = pWalker->u.pSelect;
1634 Window *pWin = pExpr->y.pWin;
1635 assert( pWin );
1636 assert( IsWindowFunc(pExpr) );
1637 assert( pWin->ppThis==0 );
1638 sqlite3WindowLink(pSelect, pWin);
1640 return WRC_Continue;
1642 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1643 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1645 static void gatherSelectWindows(Select *p){
1646 Walker w;
1647 w.xExprCallback = gatherSelectWindowsCallback;
1648 w.xSelectCallback = gatherSelectWindowsSelectCallback;
1649 w.xSelectCallback2 = 0;
1650 w.pParse = 0;
1651 w.u.pSelect = p;
1652 sqlite3WalkSelect(&w, p);
1654 #endif
1658 ** The following group of routines make deep copies of expressions,
1659 ** expression lists, ID lists, and select statements. The copies can
1660 ** be deleted (by being passed to their respective ...Delete() routines)
1661 ** without effecting the originals.
1663 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1664 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1665 ** by subsequent calls to sqlite*ListAppend() routines.
1667 ** Any tables that the SrcList might point to are not duplicated.
1669 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1670 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1671 ** truncated version of the usual Expr structure that will be stored as
1672 ** part of the in-memory representation of the database schema.
1674 Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){
1675 assert( flags==0 || flags==EXPRDUP_REDUCE );
1676 return p ? exprDup(db, p, flags, 0) : 0;
1678 ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){
1679 ExprList *pNew;
1680 struct ExprList_item *pItem;
1681 const struct ExprList_item *pOldItem;
1682 int i;
1683 Expr *pPriorSelectColOld = 0;
1684 Expr *pPriorSelectColNew = 0;
1685 assert( db!=0 );
1686 if( p==0 ) return 0;
1687 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1688 if( pNew==0 ) return 0;
1689 pNew->nExpr = p->nExpr;
1690 pNew->nAlloc = p->nAlloc;
1691 pItem = pNew->a;
1692 pOldItem = p->a;
1693 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1694 Expr *pOldExpr = pOldItem->pExpr;
1695 Expr *pNewExpr;
1696 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1697 if( pOldExpr
1698 && pOldExpr->op==TK_SELECT_COLUMN
1699 && (pNewExpr = pItem->pExpr)!=0
1701 if( pNewExpr->pRight ){
1702 pPriorSelectColOld = pOldExpr->pRight;
1703 pPriorSelectColNew = pNewExpr->pRight;
1704 pNewExpr->pLeft = pNewExpr->pRight;
1705 }else{
1706 if( pOldExpr->pLeft!=pPriorSelectColOld ){
1707 pPriorSelectColOld = pOldExpr->pLeft;
1708 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
1709 pNewExpr->pRight = pPriorSelectColNew;
1711 pNewExpr->pLeft = pPriorSelectColNew;
1714 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1715 pItem->fg = pOldItem->fg;
1716 pItem->fg.done = 0;
1717 pItem->u = pOldItem->u;
1719 return pNew;
1723 ** If cursors, triggers, views and subqueries are all omitted from
1724 ** the build, then none of the following routines, except for
1725 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1726 ** called with a NULL argument.
1728 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1729 || !defined(SQLITE_OMIT_SUBQUERY)
1730 SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){
1731 SrcList *pNew;
1732 int i;
1733 int nByte;
1734 assert( db!=0 );
1735 if( p==0 ) return 0;
1736 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1737 pNew = sqlite3DbMallocRawNN(db, nByte );
1738 if( pNew==0 ) return 0;
1739 pNew->nSrc = pNew->nAlloc = p->nSrc;
1740 for(i=0; i<p->nSrc; i++){
1741 SrcItem *pNewItem = &pNew->a[i];
1742 const SrcItem *pOldItem = &p->a[i];
1743 Table *pTab;
1744 pNewItem->pSchema = pOldItem->pSchema;
1745 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1746 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1747 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1748 pNewItem->fg = pOldItem->fg;
1749 pNewItem->iCursor = pOldItem->iCursor;
1750 pNewItem->addrFillSub = pOldItem->addrFillSub;
1751 pNewItem->regReturn = pOldItem->regReturn;
1752 if( pNewItem->fg.isIndexedBy ){
1753 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1755 pNewItem->u2 = pOldItem->u2;
1756 if( pNewItem->fg.isCte ){
1757 pNewItem->u2.pCteUse->nUse++;
1759 if( pNewItem->fg.isTabFunc ){
1760 pNewItem->u1.pFuncArg =
1761 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1763 pTab = pNewItem->pTab = pOldItem->pTab;
1764 if( pTab ){
1765 pTab->nTabRef++;
1767 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1768 if( pOldItem->fg.isUsing ){
1769 assert( pNewItem->fg.isUsing );
1770 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
1771 }else{
1772 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
1774 pNewItem->colUsed = pOldItem->colUsed;
1776 return pNew;
1778 IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){
1779 IdList *pNew;
1780 int i;
1781 assert( db!=0 );
1782 if( p==0 ) return 0;
1783 assert( p->eU4!=EU4_EXPR );
1784 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );
1785 if( pNew==0 ) return 0;
1786 pNew->nId = p->nId;
1787 pNew->eU4 = p->eU4;
1788 for(i=0; i<p->nId; i++){
1789 struct IdList_item *pNewItem = &pNew->a[i];
1790 const struct IdList_item *pOldItem = &p->a[i];
1791 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1792 pNewItem->u4 = pOldItem->u4;
1794 return pNew;
1796 Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){
1797 Select *pRet = 0;
1798 Select *pNext = 0;
1799 Select **pp = &pRet;
1800 const Select *p;
1802 assert( db!=0 );
1803 for(p=pDup; p; p=p->pPrior){
1804 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1805 if( pNew==0 ) break;
1806 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1807 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1808 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1809 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1810 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1811 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1812 pNew->op = p->op;
1813 pNew->pNext = pNext;
1814 pNew->pPrior = 0;
1815 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1816 pNew->iLimit = 0;
1817 pNew->iOffset = 0;
1818 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1819 pNew->addrOpenEphm[0] = -1;
1820 pNew->addrOpenEphm[1] = -1;
1821 pNew->nSelectRow = p->nSelectRow;
1822 pNew->pWith = sqlite3WithDup(db, p->pWith);
1823 #ifndef SQLITE_OMIT_WINDOWFUNC
1824 pNew->pWin = 0;
1825 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1826 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1827 #endif
1828 pNew->selId = p->selId;
1829 if( db->mallocFailed ){
1830 /* Any prior OOM might have left the Select object incomplete.
1831 ** Delete the whole thing rather than allow an incomplete Select
1832 ** to be used by the code generator. */
1833 pNew->pNext = 0;
1834 sqlite3SelectDelete(db, pNew);
1835 break;
1837 *pp = pNew;
1838 pp = &pNew->pPrior;
1839 pNext = pNew;
1842 return pRet;
1844 #else
1845 Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){
1846 assert( p==0 );
1847 return 0;
1849 #endif
1853 ** Add a new element to the end of an expression list. If pList is
1854 ** initially NULL, then create a new expression list.
1856 ** The pList argument must be either NULL or a pointer to an ExprList
1857 ** obtained from a prior call to sqlite3ExprListAppend(). This routine
1858 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
1859 ** Reason: This routine assumes that the number of slots in pList->a[]
1860 ** is a power of two. That is true for sqlite3ExprListAppend() returns
1861 ** but is not necessarily true from the return value of sqlite3ExprListDup().
1863 ** If a memory allocation error occurs, the entire list is freed and
1864 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1865 ** that the new entry was successfully appended.
1867 static const struct ExprList_item zeroItem = {0};
1868 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
1869 sqlite3 *db, /* Database handle. Used for memory allocation */
1870 Expr *pExpr /* Expression to be appended. Might be NULL */
1872 struct ExprList_item *pItem;
1873 ExprList *pList;
1875 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
1876 if( pList==0 ){
1877 sqlite3ExprDelete(db, pExpr);
1878 return 0;
1880 pList->nAlloc = 4;
1881 pList->nExpr = 1;
1882 pItem = &pList->a[0];
1883 *pItem = zeroItem;
1884 pItem->pExpr = pExpr;
1885 return pList;
1887 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
1888 sqlite3 *db, /* Database handle. Used for memory allocation */
1889 ExprList *pList, /* List to which to append. Might be NULL */
1890 Expr *pExpr /* Expression to be appended. Might be NULL */
1892 struct ExprList_item *pItem;
1893 ExprList *pNew;
1894 pList->nAlloc *= 2;
1895 pNew = sqlite3DbRealloc(db, pList,
1896 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
1897 if( pNew==0 ){
1898 sqlite3ExprListDelete(db, pList);
1899 sqlite3ExprDelete(db, pExpr);
1900 return 0;
1901 }else{
1902 pList = pNew;
1904 pItem = &pList->a[pList->nExpr++];
1905 *pItem = zeroItem;
1906 pItem->pExpr = pExpr;
1907 return pList;
1909 ExprList *sqlite3ExprListAppend(
1910 Parse *pParse, /* Parsing context */
1911 ExprList *pList, /* List to which to append. Might be NULL */
1912 Expr *pExpr /* Expression to be appended. Might be NULL */
1914 struct ExprList_item *pItem;
1915 if( pList==0 ){
1916 return sqlite3ExprListAppendNew(pParse->db,pExpr);
1918 if( pList->nAlloc<pList->nExpr+1 ){
1919 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
1921 pItem = &pList->a[pList->nExpr++];
1922 *pItem = zeroItem;
1923 pItem->pExpr = pExpr;
1924 return pList;
1928 ** pColumns and pExpr form a vector assignment which is part of the SET
1929 ** clause of an UPDATE statement. Like this:
1931 ** (a,b,c) = (expr1,expr2,expr3)
1932 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1934 ** For each term of the vector assignment, append new entries to the
1935 ** expression list pList. In the case of a subquery on the RHS, append
1936 ** TK_SELECT_COLUMN expressions.
1938 ExprList *sqlite3ExprListAppendVector(
1939 Parse *pParse, /* Parsing context */
1940 ExprList *pList, /* List to which to append. Might be NULL */
1941 IdList *pColumns, /* List of names of LHS of the assignment */
1942 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1944 sqlite3 *db = pParse->db;
1945 int n;
1946 int i;
1947 int iFirst = pList ? pList->nExpr : 0;
1948 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1949 ** exit prior to this routine being invoked */
1950 if( NEVER(pColumns==0) ) goto vector_append_error;
1951 if( pExpr==0 ) goto vector_append_error;
1953 /* If the RHS is a vector, then we can immediately check to see that
1954 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
1955 ** wildcards ("*") in the result set of the SELECT must be expanded before
1956 ** we can do the size check, so defer the size check until code generation.
1958 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1959 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1960 pColumns->nId, n);
1961 goto vector_append_error;
1964 for(i=0; i<pColumns->nId; i++){
1965 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
1966 assert( pSubExpr!=0 || db->mallocFailed );
1967 if( pSubExpr==0 ) continue;
1968 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1969 if( pList ){
1970 assert( pList->nExpr==iFirst+i+1 );
1971 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
1972 pColumns->a[i].zName = 0;
1976 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
1977 Expr *pFirst = pList->a[iFirst].pExpr;
1978 assert( pFirst!=0 );
1979 assert( pFirst->op==TK_SELECT_COLUMN );
1981 /* Store the SELECT statement in pRight so it will be deleted when
1982 ** sqlite3ExprListDelete() is called */
1983 pFirst->pRight = pExpr;
1984 pExpr = 0;
1986 /* Remember the size of the LHS in iTable so that we can check that
1987 ** the RHS and LHS sizes match during code generation. */
1988 pFirst->iTable = pColumns->nId;
1991 vector_append_error:
1992 sqlite3ExprUnmapAndDelete(pParse, pExpr);
1993 sqlite3IdListDelete(db, pColumns);
1994 return pList;
1998 ** Set the sort order for the last element on the given ExprList.
2000 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
2001 struct ExprList_item *pItem;
2002 if( p==0 ) return;
2003 assert( p->nExpr>0 );
2005 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
2006 assert( iSortOrder==SQLITE_SO_UNDEFINED
2007 || iSortOrder==SQLITE_SO_ASC
2008 || iSortOrder==SQLITE_SO_DESC
2010 assert( eNulls==SQLITE_SO_UNDEFINED
2011 || eNulls==SQLITE_SO_ASC
2012 || eNulls==SQLITE_SO_DESC
2015 pItem = &p->a[p->nExpr-1];
2016 assert( pItem->fg.bNulls==0 );
2017 if( iSortOrder==SQLITE_SO_UNDEFINED ){
2018 iSortOrder = SQLITE_SO_ASC;
2020 pItem->fg.sortFlags = (u8)iSortOrder;
2022 if( eNulls!=SQLITE_SO_UNDEFINED ){
2023 pItem->fg.bNulls = 1;
2024 if( iSortOrder!=eNulls ){
2025 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
2031 ** Set the ExprList.a[].zEName element of the most recently added item
2032 ** on the expression list.
2034 ** pList might be NULL following an OOM error. But pName should never be
2035 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2036 ** is set.
2038 void sqlite3ExprListSetName(
2039 Parse *pParse, /* Parsing context */
2040 ExprList *pList, /* List to which to add the span. */
2041 const Token *pName, /* Name to be added */
2042 int dequote /* True to cause the name to be dequoted */
2044 assert( pList!=0 || pParse->db->mallocFailed!=0 );
2045 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
2046 if( pList ){
2047 struct ExprList_item *pItem;
2048 assert( pList->nExpr>0 );
2049 pItem = &pList->a[pList->nExpr-1];
2050 assert( pItem->zEName==0 );
2051 assert( pItem->fg.eEName==ENAME_NAME );
2052 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
2053 if( dequote ){
2054 /* If dequote==0, then pName->z does not point to part of a DDL
2055 ** statement handled by the parser. And so no token need be added
2056 ** to the token-map. */
2057 sqlite3Dequote(pItem->zEName);
2058 if( IN_RENAME_OBJECT ){
2059 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
2066 ** Set the ExprList.a[].zSpan element of the most recently added item
2067 ** on the expression list.
2069 ** pList might be NULL following an OOM error. But pSpan should never be
2070 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2071 ** is set.
2073 void sqlite3ExprListSetSpan(
2074 Parse *pParse, /* Parsing context */
2075 ExprList *pList, /* List to which to add the span. */
2076 const char *zStart, /* Start of the span */
2077 const char *zEnd /* End of the span */
2079 sqlite3 *db = pParse->db;
2080 assert( pList!=0 || db->mallocFailed!=0 );
2081 if( pList ){
2082 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
2083 assert( pList->nExpr>0 );
2084 if( pItem->zEName==0 ){
2085 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
2086 pItem->fg.eEName = ENAME_SPAN;
2092 ** If the expression list pEList contains more than iLimit elements,
2093 ** leave an error message in pParse.
2095 void sqlite3ExprListCheckLength(
2096 Parse *pParse,
2097 ExprList *pEList,
2098 const char *zObject
2100 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
2101 testcase( pEList && pEList->nExpr==mx );
2102 testcase( pEList && pEList->nExpr==mx+1 );
2103 if( pEList && pEList->nExpr>mx ){
2104 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
2109 ** Delete an entire expression list.
2111 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
2112 int i = pList->nExpr;
2113 struct ExprList_item *pItem = pList->a;
2114 assert( pList->nExpr>0 );
2115 assert( db!=0 );
2117 sqlite3ExprDelete(db, pItem->pExpr);
2118 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
2119 pItem++;
2120 }while( --i>0 );
2121 sqlite3DbNNFreeNN(db, pList);
2123 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
2124 if( pList ) exprListDeleteNN(db, pList);
2128 ** Return the bitwise-OR of all Expr.flags fields in the given
2129 ** ExprList.
2131 u32 sqlite3ExprListFlags(const ExprList *pList){
2132 int i;
2133 u32 m = 0;
2134 assert( pList!=0 );
2135 for(i=0; i<pList->nExpr; i++){
2136 Expr *pExpr = pList->a[i].pExpr;
2137 assert( pExpr!=0 );
2138 m |= pExpr->flags;
2140 return m;
2144 ** This is a SELECT-node callback for the expression walker that
2145 ** always "fails". By "fail" in this case, we mean set
2146 ** pWalker->eCode to zero and abort.
2148 ** This callback is used by multiple expression walkers.
2150 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
2151 UNUSED_PARAMETER(NotUsed);
2152 pWalker->eCode = 0;
2153 return WRC_Abort;
2157 ** Check the input string to see if it is "true" or "false" (in any case).
2159 ** If the string is.... Return
2160 ** "true" EP_IsTrue
2161 ** "false" EP_IsFalse
2162 ** anything else 0
2164 u32 sqlite3IsTrueOrFalse(const char *zIn){
2165 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
2166 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
2167 return 0;
2172 ** If the input expression is an ID with the name "true" or "false"
2173 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2174 ** the conversion happened, and zero if the expression is unaltered.
2176 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
2177 u32 v;
2178 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
2179 if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue)
2180 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
2182 pExpr->op = TK_TRUEFALSE;
2183 ExprSetProperty(pExpr, v);
2184 return 1;
2186 return 0;
2190 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2191 ** and 0 if it is FALSE.
2193 int sqlite3ExprTruthValue(const Expr *pExpr){
2194 pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
2195 assert( pExpr->op==TK_TRUEFALSE );
2196 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2197 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
2198 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
2199 return pExpr->u.zToken[4]==0;
2203 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2204 ** terms that are always true or false. Return the simplified expression.
2205 ** Or return the original expression if no simplification is possible.
2207 ** Examples:
2209 ** (x<10) AND true => (x<10)
2210 ** (x<10) AND false => false
2211 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2212 ** (x<10) AND (y=22 OR true) => (x<10)
2213 ** (y=22) OR true => true
2215 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
2216 assert( pExpr!=0 );
2217 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
2218 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
2219 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
2220 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
2221 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
2222 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
2223 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
2226 return pExpr;
2231 ** These routines are Walker callbacks used to check expressions to
2232 ** see if they are "constant" for some definition of constant. The
2233 ** Walker.eCode value determines the type of "constant" we are looking
2234 ** for.
2236 ** These callback routines are used to implement the following:
2238 ** sqlite3ExprIsConstant() pWalker->eCode==1
2239 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2240 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2241 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2243 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2244 ** is found to not be a constant.
2246 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2247 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2248 ** when parsing an existing schema out of the sqlite_schema table and 4
2249 ** when processing a new CREATE TABLE statement. A bound parameter raises
2250 ** an error for new statements, but is silently converted
2251 ** to NULL for existing schemas. This allows sqlite_schema tables that
2252 ** contain a bound parameter because they were generated by older versions
2253 ** of SQLite to be parsed by newer versions of SQLite without raising a
2254 ** malformed schema error.
2256 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
2258 /* If pWalker->eCode is 2 then any term of the expression that comes from
2259 ** the ON or USING clauses of an outer join disqualifies the expression
2260 ** from being considered constant. */
2261 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
2262 pWalker->eCode = 0;
2263 return WRC_Abort;
2266 switch( pExpr->op ){
2267 /* Consider functions to be constant if all their arguments are constant
2268 ** and either pWalker->eCode==4 or 5 or the function has the
2269 ** SQLITE_FUNC_CONST flag. */
2270 case TK_FUNCTION:
2271 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2272 && !ExprHasProperty(pExpr, EP_WinFunc)
2274 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2275 return WRC_Continue;
2276 }else{
2277 pWalker->eCode = 0;
2278 return WRC_Abort;
2280 case TK_ID:
2281 /* Convert "true" or "false" in a DEFAULT clause into the
2282 ** appropriate TK_TRUEFALSE operator */
2283 if( sqlite3ExprIdToTrueFalse(pExpr) ){
2284 return WRC_Prune;
2286 /* no break */ deliberate_fall_through
2287 case TK_COLUMN:
2288 case TK_AGG_FUNCTION:
2289 case TK_AGG_COLUMN:
2290 testcase( pExpr->op==TK_ID );
2291 testcase( pExpr->op==TK_COLUMN );
2292 testcase( pExpr->op==TK_AGG_FUNCTION );
2293 testcase( pExpr->op==TK_AGG_COLUMN );
2294 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2295 return WRC_Continue;
2297 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2298 return WRC_Continue;
2300 /* no break */ deliberate_fall_through
2301 case TK_IF_NULL_ROW:
2302 case TK_REGISTER:
2303 case TK_DOT:
2304 testcase( pExpr->op==TK_REGISTER );
2305 testcase( pExpr->op==TK_IF_NULL_ROW );
2306 testcase( pExpr->op==TK_DOT );
2307 pWalker->eCode = 0;
2308 return WRC_Abort;
2309 case TK_VARIABLE:
2310 if( pWalker->eCode==5 ){
2311 /* Silently convert bound parameters that appear inside of CREATE
2312 ** statements into a NULL when parsing the CREATE statement text out
2313 ** of the sqlite_schema table */
2314 pExpr->op = TK_NULL;
2315 }else if( pWalker->eCode==4 ){
2316 /* A bound parameter in a CREATE statement that originates from
2317 ** sqlite3_prepare() causes an error */
2318 pWalker->eCode = 0;
2319 return WRC_Abort;
2321 /* no break */ deliberate_fall_through
2322 default:
2323 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2324 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2325 return WRC_Continue;
2328 static int exprIsConst(Expr *p, int initFlag, int iCur){
2329 Walker w;
2330 w.eCode = initFlag;
2331 w.xExprCallback = exprNodeIsConstant;
2332 w.xSelectCallback = sqlite3SelectWalkFail;
2333 #ifdef SQLITE_DEBUG
2334 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2335 #endif
2336 w.u.iCur = iCur;
2337 sqlite3WalkExpr(&w, p);
2338 return w.eCode;
2342 ** Walk an expression tree. Return non-zero if the expression is constant
2343 ** and 0 if it involves variables or function calls.
2345 ** For the purposes of this function, a double-quoted string (ex: "abc")
2346 ** is considered a variable but a single-quoted string (ex: 'abc') is
2347 ** a constant.
2349 int sqlite3ExprIsConstant(Expr *p){
2350 return exprIsConst(p, 1, 0);
2354 ** Walk an expression tree. Return non-zero if
2356 ** (1) the expression is constant, and
2357 ** (2) the expression does originate in the ON or USING clause
2358 ** of a LEFT JOIN, and
2359 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2360 ** operands created by the constant propagation optimization.
2362 ** When this routine returns true, it indicates that the expression
2363 ** can be added to the pParse->pConstExpr list and evaluated once when
2364 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2366 int sqlite3ExprIsConstantNotJoin(Expr *p){
2367 return exprIsConst(p, 2, 0);
2371 ** Walk an expression tree. Return non-zero if the expression is constant
2372 ** for any single row of the table with cursor iCur. In other words, the
2373 ** expression must not refer to any non-deterministic function nor any
2374 ** table other than iCur.
2376 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2377 return exprIsConst(p, 3, iCur);
2381 ** Check pExpr to see if it is an constraint on the single data source
2382 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2383 ** constrains pSrc but does not depend on any other tables or data
2384 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2385 ** is a constraint on pSrc only.
2387 ** This is an optimization. False negatives will perhaps cause slower
2388 ** queries, but false positives will yield incorrect answers. So when in
2389 ** doubt, return 0.
2391 ** To be an single-source constraint, the following must be true:
2393 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2395 ** (2) pExpr cannot use subqueries or non-deterministic functions.
2397 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2398 ** (Is there some way to relax this constraint?)
2400 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2401 ** (4a) pExpr must come from an ON clause..
2402 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2404 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2405 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2406 ** clause, not an ON clause.
2408 ** (6) Either:
2410 ** (6a) pExpr does not originate in an ON or USING clause, or
2412 ** (6b) The ON or USING clause from which pExpr is derived is
2413 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2415 ** Without this restriction, accepting pExpr as a single-table
2416 ** constraint might move the the ON/USING filter expression
2417 ** from the left side of a RIGHT JOIN over to the right side,
2418 ** which leads to incorrect answers. See also restriction (9)
2419 ** on push-down.
2421 int sqlite3ExprIsSingleTableConstraint(
2422 Expr *pExpr, /* The constraint */
2423 const SrcList *pSrcList, /* Complete FROM clause */
2424 int iSrc /* Which element of pSrcList to use */
2426 const SrcItem *pSrc = &pSrcList->a[iSrc];
2427 if( pSrc->fg.jointype & JT_LTORJ ){
2428 return 0; /* rule (3) */
2430 if( pSrc->fg.jointype & JT_LEFT ){
2431 if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (4a) */
2432 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */
2433 }else{
2434 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (5) */
2436 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) /* (6a) */
2437 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */
2439 int jj;
2440 for(jj=0; jj<iSrc; jj++){
2441 if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
2442 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
2443 return 0; /* restriction (6) */
2445 break;
2449 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor); /* rules (1), (2) */
2454 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2456 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2457 ExprList *pGroupBy = pWalker->u.pGroupBy;
2458 int i;
2460 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2461 ** it constant. */
2462 for(i=0; i<pGroupBy->nExpr; i++){
2463 Expr *p = pGroupBy->a[i].pExpr;
2464 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2465 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2466 if( sqlite3IsBinary(pColl) ){
2467 return WRC_Prune;
2472 /* Check if pExpr is a sub-select. If so, consider it variable. */
2473 if( ExprUseXSelect(pExpr) ){
2474 pWalker->eCode = 0;
2475 return WRC_Abort;
2478 return exprNodeIsConstant(pWalker, pExpr);
2482 ** Walk the expression tree passed as the first argument. Return non-zero
2483 ** if the expression consists entirely of constants or copies of terms
2484 ** in pGroupBy that sort with the BINARY collation sequence.
2486 ** This routine is used to determine if a term of the HAVING clause can
2487 ** be promoted into the WHERE clause. In order for such a promotion to work,
2488 ** the value of the HAVING clause term must be the same for all members of
2489 ** a "group". The requirement that the GROUP BY term must be BINARY
2490 ** assumes that no other collating sequence will have a finer-grained
2491 ** grouping than binary. In other words (A=B COLLATE binary) implies
2492 ** A=B in every other collating sequence. The requirement that the
2493 ** GROUP BY be BINARY is stricter than necessary. It would also work
2494 ** to promote HAVING clauses that use the same alternative collating
2495 ** sequence as the GROUP BY term, but that is much harder to check,
2496 ** alternative collating sequences are uncommon, and this is only an
2497 ** optimization, so we take the easy way out and simply require the
2498 ** GROUP BY to use the BINARY collating sequence.
2500 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2501 Walker w;
2502 w.eCode = 1;
2503 w.xExprCallback = exprNodeIsConstantOrGroupBy;
2504 w.xSelectCallback = 0;
2505 w.u.pGroupBy = pGroupBy;
2506 w.pParse = pParse;
2507 sqlite3WalkExpr(&w, p);
2508 return w.eCode;
2512 ** Walk an expression tree for the DEFAULT field of a column definition
2513 ** in a CREATE TABLE statement. Return non-zero if the expression is
2514 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2515 ** the expression is constant or a function call with constant arguments.
2516 ** Return and 0 if there are any variables.
2518 ** isInit is true when parsing from sqlite_schema. isInit is false when
2519 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2520 ** (such as ? or $abc) in the expression are converted into NULL. When
2521 ** isInit is false, parameters raise an error. Parameters should not be
2522 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2523 ** allowed it, so we need to support it when reading sqlite_schema for
2524 ** backwards compatibility.
2526 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2528 ** For the purposes of this function, a double-quoted string (ex: "abc")
2529 ** is considered a variable but a single-quoted string (ex: 'abc') is
2530 ** a constant.
2532 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2533 assert( isInit==0 || isInit==1 );
2534 return exprIsConst(p, 4+isInit, 0);
2537 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2539 ** Walk an expression tree. Return 1 if the expression contains a
2540 ** subquery of some kind. Return 0 if there are no subqueries.
2542 int sqlite3ExprContainsSubquery(Expr *p){
2543 Walker w;
2544 w.eCode = 1;
2545 w.xExprCallback = sqlite3ExprWalkNoop;
2546 w.xSelectCallback = sqlite3SelectWalkFail;
2547 #ifdef SQLITE_DEBUG
2548 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2549 #endif
2550 sqlite3WalkExpr(&w, p);
2551 return w.eCode==0;
2553 #endif
2556 ** If the expression p codes a constant integer that is small enough
2557 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2558 ** in *pValue. If the expression is not an integer or if it is too big
2559 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2561 int sqlite3ExprIsInteger(const Expr *p, int *pValue){
2562 int rc = 0;
2563 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
2565 /* If an expression is an integer literal that fits in a signed 32-bit
2566 ** integer, then the EP_IntValue flag will have already been set */
2567 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2568 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2570 if( p->flags & EP_IntValue ){
2571 *pValue = p->u.iValue;
2572 return 1;
2574 switch( p->op ){
2575 case TK_UPLUS: {
2576 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
2577 break;
2579 case TK_UMINUS: {
2580 int v = 0;
2581 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
2582 assert( ((unsigned int)v)!=0x80000000 );
2583 *pValue = -v;
2584 rc = 1;
2586 break;
2588 default: break;
2590 return rc;
2594 ** Return FALSE if there is no chance that the expression can be NULL.
2596 ** If the expression might be NULL or if the expression is too complex
2597 ** to tell return TRUE.
2599 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2600 ** when we know that a value cannot be NULL. Hence, a false positive
2601 ** (returning TRUE when in fact the expression can never be NULL) might
2602 ** be a small performance hit but is otherwise harmless. On the other
2603 ** hand, a false negative (returning FALSE when the result could be NULL)
2604 ** will likely result in an incorrect answer. So when in doubt, return
2605 ** TRUE.
2607 int sqlite3ExprCanBeNull(const Expr *p){
2608 u8 op;
2609 assert( p!=0 );
2610 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2611 p = p->pLeft;
2612 assert( p!=0 );
2614 op = p->op;
2615 if( op==TK_REGISTER ) op = p->op2;
2616 switch( op ){
2617 case TK_INTEGER:
2618 case TK_STRING:
2619 case TK_FLOAT:
2620 case TK_BLOB:
2621 return 0;
2622 case TK_COLUMN:
2623 assert( ExprUseYTab(p) );
2624 return ExprHasProperty(p, EP_CanBeNull) ||
2625 p->y.pTab==0 || /* Reference to column of index on expression */
2626 (p->iColumn>=0
2627 && p->y.pTab->aCol!=0 /* Possible due to prior error */
2628 && p->y.pTab->aCol[p->iColumn].notNull==0);
2629 default:
2630 return 1;
2635 ** Return TRUE if the given expression is a constant which would be
2636 ** unchanged by OP_Affinity with the affinity given in the second
2637 ** argument.
2639 ** This routine is used to determine if the OP_Affinity operation
2640 ** can be omitted. When in doubt return FALSE. A false negative
2641 ** is harmless. A false positive, however, can result in the wrong
2642 ** answer.
2644 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2645 u8 op;
2646 int unaryMinus = 0;
2647 if( aff==SQLITE_AFF_BLOB ) return 1;
2648 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2649 if( p->op==TK_UMINUS ) unaryMinus = 1;
2650 p = p->pLeft;
2652 op = p->op;
2653 if( op==TK_REGISTER ) op = p->op2;
2654 switch( op ){
2655 case TK_INTEGER: {
2656 return aff>=SQLITE_AFF_NUMERIC;
2658 case TK_FLOAT: {
2659 return aff>=SQLITE_AFF_NUMERIC;
2661 case TK_STRING: {
2662 return !unaryMinus && aff==SQLITE_AFF_TEXT;
2664 case TK_BLOB: {
2665 return !unaryMinus;
2667 case TK_COLUMN: {
2668 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2669 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2671 default: {
2672 return 0;
2678 ** Return TRUE if the given string is a row-id column name.
2680 int sqlite3IsRowid(const char *z){
2681 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2682 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2683 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2684 return 0;
2688 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2689 ** that can be simplified to a direct table access, then return
2690 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2691 ** or if the SELECT statement needs to be materialized into a transient
2692 ** table, then return NULL.
2694 #ifndef SQLITE_OMIT_SUBQUERY
2695 static Select *isCandidateForInOpt(const Expr *pX){
2696 Select *p;
2697 SrcList *pSrc;
2698 ExprList *pEList;
2699 Table *pTab;
2700 int i;
2701 if( !ExprUseXSelect(pX) ) return 0; /* Not a subquery */
2702 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
2703 p = pX->x.pSelect;
2704 if( p->pPrior ) return 0; /* Not a compound SELECT */
2705 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2706 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2707 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2708 return 0; /* No DISTINCT keyword and no aggregate functions */
2710 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
2711 if( p->pLimit ) return 0; /* Has no LIMIT clause */
2712 if( p->pWhere ) return 0; /* Has no WHERE clause */
2713 pSrc = p->pSrc;
2714 assert( pSrc!=0 );
2715 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
2716 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
2717 pTab = pSrc->a[0].pTab;
2718 assert( pTab!=0 );
2719 assert( !IsView(pTab) ); /* FROM clause is not a view */
2720 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
2721 pEList = p->pEList;
2722 assert( pEList!=0 );
2723 /* All SELECT results must be columns. */
2724 for(i=0; i<pEList->nExpr; i++){
2725 Expr *pRes = pEList->a[i].pExpr;
2726 if( pRes->op!=TK_COLUMN ) return 0;
2727 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
2729 return p;
2731 #endif /* SQLITE_OMIT_SUBQUERY */
2733 #ifndef SQLITE_OMIT_SUBQUERY
2735 ** Generate code that checks the left-most column of index table iCur to see if
2736 ** it contains any NULL entries. Cause the register at regHasNull to be set
2737 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2738 ** to be set to NULL if iCur contains one or more NULL values.
2740 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2741 int addr1;
2742 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2743 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2744 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2745 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2746 VdbeComment((v, "first_entry_in(%d)", iCur));
2747 sqlite3VdbeJumpHere(v, addr1);
2749 #endif
2752 #ifndef SQLITE_OMIT_SUBQUERY
2754 ** The argument is an IN operator with a list (not a subquery) on the
2755 ** right-hand side. Return TRUE if that list is constant.
2757 static int sqlite3InRhsIsConstant(Expr *pIn){
2758 Expr *pLHS;
2759 int res;
2760 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2761 pLHS = pIn->pLeft;
2762 pIn->pLeft = 0;
2763 res = sqlite3ExprIsConstant(pIn);
2764 pIn->pLeft = pLHS;
2765 return res;
2767 #endif
2770 ** This function is used by the implementation of the IN (...) operator.
2771 ** The pX parameter is the expression on the RHS of the IN operator, which
2772 ** might be either a list of expressions or a subquery.
2774 ** The job of this routine is to find or create a b-tree object that can
2775 ** be used either to test for membership in the RHS set or to iterate through
2776 ** all members of the RHS set, skipping duplicates.
2778 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2779 ** and the *piTab parameter is set to the index of that cursor.
2781 ** The returned value of this function indicates the b-tree type, as follows:
2783 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2784 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2785 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2786 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2787 ** populated epheremal table.
2788 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2789 ** implemented as a sequence of comparisons.
2791 ** An existing b-tree might be used if the RHS expression pX is a simple
2792 ** subquery such as:
2794 ** SELECT <column1>, <column2>... FROM <table>
2796 ** If the RHS of the IN operator is a list or a more complex subquery, then
2797 ** an ephemeral table might need to be generated from the RHS and then
2798 ** pX->iTable made to point to the ephemeral table instead of an
2799 ** existing table. In this case, the creation and initialization of the
2800 ** ephmeral table might be put inside of a subroutine, the EP_Subrtn flag
2801 ** will be set on pX and the pX->y.sub fields will be set to show where
2802 ** the subroutine is coded.
2804 ** The inFlags parameter must contain, at a minimum, one of the bits
2805 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2806 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2807 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2808 ** be used to loop over all values of the RHS of the IN operator.
2810 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2811 ** through the set members) then the b-tree must not contain duplicates.
2812 ** An epheremal table will be created unless the selected columns are guaranteed
2813 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2814 ** a UNIQUE constraint or index.
2816 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2817 ** for fast set membership tests) then an epheremal table must
2818 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2819 ** index can be found with the specified <columns> as its left-most.
2821 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2822 ** if the RHS of the IN operator is a list (not a subquery) then this
2823 ** routine might decide that creating an ephemeral b-tree for membership
2824 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2825 ** calling routine should implement the IN operator using a sequence
2826 ** of Eq or Ne comparison operations.
2828 ** When the b-tree is being used for membership tests, the calling function
2829 ** might need to know whether or not the RHS side of the IN operator
2830 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2831 ** if there is any chance that the (...) might contain a NULL value at
2832 ** runtime, then a register is allocated and the register number written
2833 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2834 ** NULL value, then *prRhsHasNull is left unchanged.
2836 ** If a register is allocated and its location stored in *prRhsHasNull, then
2837 ** the value in that register will be NULL if the b-tree contains one or more
2838 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2839 ** NULL values.
2841 ** If the aiMap parameter is not NULL, it must point to an array containing
2842 ** one element for each column returned by the SELECT statement on the RHS
2843 ** of the IN(...) operator. The i'th entry of the array is populated with the
2844 ** offset of the index column that matches the i'th column returned by the
2845 ** SELECT. For example, if the expression and selected index are:
2847 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2848 ** CREATE INDEX i1 ON t1(b, c, a);
2850 ** then aiMap[] is populated with {2, 0, 1}.
2852 #ifndef SQLITE_OMIT_SUBQUERY
2853 int sqlite3FindInIndex(
2854 Parse *pParse, /* Parsing context */
2855 Expr *pX, /* The IN expression */
2856 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2857 int *prRhsHasNull, /* Register holding NULL status. See notes */
2858 int *aiMap, /* Mapping from Index fields to RHS fields */
2859 int *piTab /* OUT: index to use */
2861 Select *p; /* SELECT to the right of IN operator */
2862 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2863 int iTab; /* Cursor of the RHS table */
2864 int mustBeUnique; /* True if RHS must be unique */
2865 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
2867 assert( pX->op==TK_IN );
2868 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
2869 iTab = pParse->nTab++;
2871 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2872 ** whether or not the SELECT result contains NULL values, check whether
2873 ** or not NULL is actually possible (it may not be, for example, due
2874 ** to NOT NULL constraints in the schema). If no NULL values are possible,
2875 ** set prRhsHasNull to 0 before continuing. */
2876 if( prRhsHasNull && ExprUseXSelect(pX) ){
2877 int i;
2878 ExprList *pEList = pX->x.pSelect->pEList;
2879 for(i=0; i<pEList->nExpr; i++){
2880 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2882 if( i==pEList->nExpr ){
2883 prRhsHasNull = 0;
2887 /* Check to see if an existing table or index can be used to
2888 ** satisfy the query. This is preferable to generating a new
2889 ** ephemeral table. */
2890 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2891 sqlite3 *db = pParse->db; /* Database connection */
2892 Table *pTab; /* Table <table>. */
2893 int iDb; /* Database idx for pTab */
2894 ExprList *pEList = p->pEList;
2895 int nExpr = pEList->nExpr;
2897 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2898 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2899 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2900 pTab = p->pSrc->a[0].pTab;
2902 /* Code an OP_Transaction and OP_TableLock for <table>. */
2903 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2904 assert( iDb>=0 && iDb<SQLITE_MAX_DB );
2905 sqlite3CodeVerifySchema(pParse, iDb);
2906 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2908 assert(v); /* sqlite3GetVdbe() has always been previously called */
2909 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
2910 /* The "x IN (SELECT rowid FROM table)" case */
2911 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
2912 VdbeCoverage(v);
2914 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2915 eType = IN_INDEX_ROWID;
2916 ExplainQueryPlan((pParse, 0,
2917 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
2918 sqlite3VdbeJumpHere(v, iAddr);
2919 }else{
2920 Index *pIdx; /* Iterator variable */
2921 int affinity_ok = 1;
2922 int i;
2924 /* Check that the affinity that will be used to perform each
2925 ** comparison is the same as the affinity of each column in table
2926 ** on the RHS of the IN operator. If it not, it is not possible to
2927 ** use any index of the RHS table. */
2928 for(i=0; i<nExpr && affinity_ok; i++){
2929 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2930 int iCol = pEList->a[i].pExpr->iColumn;
2931 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2932 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2933 testcase( cmpaff==SQLITE_AFF_BLOB );
2934 testcase( cmpaff==SQLITE_AFF_TEXT );
2935 switch( cmpaff ){
2936 case SQLITE_AFF_BLOB:
2937 break;
2938 case SQLITE_AFF_TEXT:
2939 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2940 ** other has no affinity and the other side is TEXT. Hence,
2941 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2942 ** and for the term on the LHS of the IN to have no affinity. */
2943 assert( idxaff==SQLITE_AFF_TEXT );
2944 break;
2945 default:
2946 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2950 if( affinity_ok ){
2951 /* Search for an existing index that will work for this IN operator */
2952 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2953 Bitmask colUsed; /* Columns of the index used */
2954 Bitmask mCol; /* Mask for the current column */
2955 if( pIdx->nColumn<nExpr ) continue;
2956 if( pIdx->pPartIdxWhere!=0 ) continue;
2957 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2958 ** BITMASK(nExpr) without overflowing */
2959 testcase( pIdx->nColumn==BMS-2 );
2960 testcase( pIdx->nColumn==BMS-1 );
2961 if( pIdx->nColumn>=BMS-1 ) continue;
2962 if( mustBeUnique ){
2963 if( pIdx->nKeyCol>nExpr
2964 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2966 continue; /* This index is not unique over the IN RHS columns */
2970 colUsed = 0; /* Columns of index used so far */
2971 for(i=0; i<nExpr; i++){
2972 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2973 Expr *pRhs = pEList->a[i].pExpr;
2974 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2975 int j;
2977 for(j=0; j<nExpr; j++){
2978 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2979 assert( pIdx->azColl[j] );
2980 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2981 continue;
2983 break;
2985 if( j==nExpr ) break;
2986 mCol = MASKBIT(j);
2987 if( mCol & colUsed ) break; /* Each column used only once */
2988 colUsed |= mCol;
2989 if( aiMap ) aiMap[i] = j;
2992 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2993 if( colUsed==(MASKBIT(nExpr)-1) ){
2994 /* If we reach this point, that means the index pIdx is usable */
2995 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2996 ExplainQueryPlan((pParse, 0,
2997 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
2998 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2999 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
3000 VdbeComment((v, "%s", pIdx->zName));
3001 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
3002 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
3004 if( prRhsHasNull ){
3005 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3006 i64 mask = (1<<nExpr)-1;
3007 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
3008 iTab, 0, 0, (u8*)&mask, P4_INT64);
3009 #endif
3010 *prRhsHasNull = ++pParse->nMem;
3011 if( nExpr==1 ){
3012 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
3015 sqlite3VdbeJumpHere(v, iAddr);
3017 } /* End loop over indexes */
3018 } /* End if( affinity_ok ) */
3019 } /* End if not an rowid index */
3020 } /* End attempt to optimize using an index */
3022 /* If no preexisting index is available for the IN clause
3023 ** and IN_INDEX_NOOP is an allowed reply
3024 ** and the RHS of the IN operator is a list, not a subquery
3025 ** and the RHS is not constant or has two or fewer terms,
3026 ** then it is not worth creating an ephemeral table to evaluate
3027 ** the IN operator so return IN_INDEX_NOOP.
3029 if( eType==0
3030 && (inFlags & IN_INDEX_NOOP_OK)
3031 && ExprUseXList(pX)
3032 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
3034 pParse->nTab--; /* Back out the allocation of the unused cursor */
3035 iTab = -1; /* Cursor is not allocated */
3036 eType = IN_INDEX_NOOP;
3039 if( eType==0 ){
3040 /* Could not find an existing table or index to use as the RHS b-tree.
3041 ** We will have to generate an ephemeral table to do the job.
3043 u32 savedNQueryLoop = pParse->nQueryLoop;
3044 int rMayHaveNull = 0;
3045 eType = IN_INDEX_EPH;
3046 if( inFlags & IN_INDEX_LOOP ){
3047 pParse->nQueryLoop = 0;
3048 }else if( prRhsHasNull ){
3049 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
3051 assert( pX->op==TK_IN );
3052 sqlite3CodeRhsOfIN(pParse, pX, iTab);
3053 if( rMayHaveNull ){
3054 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
3056 pParse->nQueryLoop = savedNQueryLoop;
3059 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
3060 int i, n;
3061 n = sqlite3ExprVectorSize(pX->pLeft);
3062 for(i=0; i<n; i++) aiMap[i] = i;
3064 *piTab = iTab;
3065 return eType;
3067 #endif
3069 #ifndef SQLITE_OMIT_SUBQUERY
3071 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3072 ** function allocates and returns a nul-terminated string containing
3073 ** the affinities to be used for each column of the comparison.
3075 ** It is the responsibility of the caller to ensure that the returned
3076 ** string is eventually freed using sqlite3DbFree().
3078 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
3079 Expr *pLeft = pExpr->pLeft;
3080 int nVal = sqlite3ExprVectorSize(pLeft);
3081 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
3082 char *zRet;
3084 assert( pExpr->op==TK_IN );
3085 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
3086 if( zRet ){
3087 int i;
3088 for(i=0; i<nVal; i++){
3089 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
3090 char a = sqlite3ExprAffinity(pA);
3091 if( pSelect ){
3092 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
3093 }else{
3094 zRet[i] = a;
3097 zRet[nVal] = '\0';
3099 return zRet;
3101 #endif
3103 #ifndef SQLITE_OMIT_SUBQUERY
3105 ** Load the Parse object passed as the first argument with an error
3106 ** message of the form:
3108 ** "sub-select returns N columns - expected M"
3110 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
3111 if( pParse->nErr==0 ){
3112 const char *zFmt = "sub-select returns %d columns - expected %d";
3113 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
3116 #endif
3119 ** Expression pExpr is a vector that has been used in a context where
3120 ** it is not permitted. If pExpr is a sub-select vector, this routine
3121 ** loads the Parse object with a message of the form:
3123 ** "sub-select returns N columns - expected 1"
3125 ** Or, if it is a regular scalar vector:
3127 ** "row value misused"
3129 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
3130 #ifndef SQLITE_OMIT_SUBQUERY
3131 if( ExprUseXSelect(pExpr) ){
3132 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
3133 }else
3134 #endif
3136 sqlite3ErrorMsg(pParse, "row value misused");
3140 #ifndef SQLITE_OMIT_SUBQUERY
3142 ** Generate code that will construct an ephemeral table containing all terms
3143 ** in the RHS of an IN operator. The IN operator can be in either of two
3144 ** forms:
3146 ** x IN (4,5,11) -- IN operator with list on right-hand side
3147 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3149 ** The pExpr parameter is the IN operator. The cursor number for the
3150 ** constructed ephermeral table is returned. The first time the ephemeral
3151 ** table is computed, the cursor number is also stored in pExpr->iTable,
3152 ** however the cursor number returned might not be the same, as it might
3153 ** have been duplicated using OP_OpenDup.
3155 ** If the LHS expression ("x" in the examples) is a column value, or
3156 ** the SELECT statement returns a column value, then the affinity of that
3157 ** column is used to build the index keys. If both 'x' and the
3158 ** SELECT... statement are columns, then numeric affinity is used
3159 ** if either column has NUMERIC or INTEGER affinity. If neither
3160 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3161 ** is used.
3163 void sqlite3CodeRhsOfIN(
3164 Parse *pParse, /* Parsing context */
3165 Expr *pExpr, /* The IN operator */
3166 int iTab /* Use this cursor number */
3168 int addrOnce = 0; /* Address of the OP_Once instruction at top */
3169 int addr; /* Address of OP_OpenEphemeral instruction */
3170 Expr *pLeft; /* the LHS of the IN operator */
3171 KeyInfo *pKeyInfo = 0; /* Key information */
3172 int nVal; /* Size of vector pLeft */
3173 Vdbe *v; /* The prepared statement under construction */
3175 v = pParse->pVdbe;
3176 assert( v!=0 );
3178 /* The evaluation of the IN must be repeated every time it
3179 ** is encountered if any of the following is true:
3181 ** * The right-hand side is a correlated subquery
3182 ** * The right-hand side is an expression list containing variables
3183 ** * We are inside a trigger
3185 ** If all of the above are false, then we can compute the RHS just once
3186 ** and reuse it many names.
3188 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
3189 /* Reuse of the RHS is allowed */
3190 /* If this routine has already been coded, but the previous code
3191 ** might not have been invoked yet, so invoke it now as a subroutine.
3193 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3194 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3195 if( ExprUseXSelect(pExpr) ){
3196 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
3197 pExpr->x.pSelect->selId));
3199 assert( ExprUseYSub(pExpr) );
3200 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3201 pExpr->y.sub.iAddr);
3202 assert( iTab!=pExpr->iTable );
3203 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
3204 sqlite3VdbeJumpHere(v, addrOnce);
3205 return;
3208 /* Begin coding the subroutine */
3209 assert( !ExprUseYWin(pExpr) );
3210 ExprSetProperty(pExpr, EP_Subrtn);
3211 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3212 pExpr->y.sub.regReturn = ++pParse->nMem;
3213 pExpr->y.sub.iAddr =
3214 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3216 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3219 /* Check to see if this is a vector IN operator */
3220 pLeft = pExpr->pLeft;
3221 nVal = sqlite3ExprVectorSize(pLeft);
3223 /* Construct the ephemeral table that will contain the content of
3224 ** RHS of the IN operator.
3226 pExpr->iTable = iTab;
3227 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
3228 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3229 if( ExprUseXSelect(pExpr) ){
3230 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
3231 }else{
3232 VdbeComment((v, "RHS of IN operator"));
3234 #endif
3235 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
3237 if( ExprUseXSelect(pExpr) ){
3238 /* Case 1: expr IN (SELECT ...)
3240 ** Generate code to write the results of the select into the temporary
3241 ** table allocated and opened above.
3243 Select *pSelect = pExpr->x.pSelect;
3244 ExprList *pEList = pSelect->pEList;
3246 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
3247 addrOnce?"":"CORRELATED ", pSelect->selId
3249 /* If the LHS and RHS of the IN operator do not match, that
3250 ** error will have been caught long before we reach this point. */
3251 if( ALWAYS(pEList->nExpr==nVal) ){
3252 Select *pCopy;
3253 SelectDest dest;
3254 int i;
3255 int rc;
3256 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
3257 dest.zAffSdst = exprINAffinity(pParse, pExpr);
3258 pSelect->iLimit = 0;
3259 testcase( pSelect->selFlags & SF_Distinct );
3260 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3261 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
3262 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
3263 sqlite3SelectDelete(pParse->db, pCopy);
3264 sqlite3DbFree(pParse->db, dest.zAffSdst);
3265 if( rc ){
3266 sqlite3KeyInfoUnref(pKeyInfo);
3267 return;
3269 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
3270 assert( pEList!=0 );
3271 assert( pEList->nExpr>0 );
3272 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3273 for(i=0; i<nVal; i++){
3274 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
3275 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
3276 pParse, p, pEList->a[i].pExpr
3280 }else if( ALWAYS(pExpr->x.pList!=0) ){
3281 /* Case 2: expr IN (exprlist)
3283 ** For each expression, build an index key from the evaluation and
3284 ** store it in the temporary table. If <expr> is a column, then use
3285 ** that columns affinity when building index keys. If <expr> is not
3286 ** a column, use numeric affinity.
3288 char affinity; /* Affinity of the LHS of the IN */
3289 int i;
3290 ExprList *pList = pExpr->x.pList;
3291 struct ExprList_item *pItem;
3292 int r1, r2;
3293 affinity = sqlite3ExprAffinity(pLeft);
3294 if( affinity<=SQLITE_AFF_NONE ){
3295 affinity = SQLITE_AFF_BLOB;
3296 }else if( affinity==SQLITE_AFF_REAL ){
3297 affinity = SQLITE_AFF_NUMERIC;
3299 if( pKeyInfo ){
3300 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3301 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3304 /* Loop through each expression in <exprlist>. */
3305 r1 = sqlite3GetTempReg(pParse);
3306 r2 = sqlite3GetTempReg(pParse);
3307 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
3308 Expr *pE2 = pItem->pExpr;
3310 /* If the expression is not constant then we will need to
3311 ** disable the test that was generated above that makes sure
3312 ** this code only executes once. Because for a non-constant
3313 ** expression we need to rerun this code each time.
3315 if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
3316 sqlite3VdbeChangeToNoop(v, addrOnce-1);
3317 sqlite3VdbeChangeToNoop(v, addrOnce);
3318 ExprClearProperty(pExpr, EP_Subrtn);
3319 addrOnce = 0;
3322 /* Evaluate the expression and insert it into the temp table */
3323 sqlite3ExprCode(pParse, pE2, r1);
3324 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
3325 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
3327 sqlite3ReleaseTempReg(pParse, r1);
3328 sqlite3ReleaseTempReg(pParse, r2);
3330 if( pKeyInfo ){
3331 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
3333 if( addrOnce ){
3334 sqlite3VdbeAddOp1(v, OP_NullRow, iTab);
3335 sqlite3VdbeJumpHere(v, addrOnce);
3336 /* Subroutine return */
3337 assert( ExprUseYSub(pExpr) );
3338 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3339 || pParse->nErr );
3340 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3341 pExpr->y.sub.iAddr, 1);
3342 VdbeCoverage(v);
3343 sqlite3ClearTempRegCache(pParse);
3346 #endif /* SQLITE_OMIT_SUBQUERY */
3349 ** Generate code for scalar subqueries used as a subquery expression
3350 ** or EXISTS operator:
3352 ** (SELECT a FROM b) -- subquery
3353 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3355 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3357 ** Return the register that holds the result. For a multi-column SELECT,
3358 ** the result is stored in a contiguous array of registers and the
3359 ** return value is the register of the left-most result column.
3360 ** Return 0 if an error occurs.
3362 #ifndef SQLITE_OMIT_SUBQUERY
3363 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
3364 int addrOnce = 0; /* Address of OP_Once at top of subroutine */
3365 int rReg = 0; /* Register storing resulting */
3366 Select *pSel; /* SELECT statement to encode */
3367 SelectDest dest; /* How to deal with SELECT result */
3368 int nReg; /* Registers to allocate */
3369 Expr *pLimit; /* New limit expression */
3370 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3371 int addrExplain; /* Address of OP_Explain instruction */
3372 #endif
3374 Vdbe *v = pParse->pVdbe;
3375 assert( v!=0 );
3376 if( pParse->nErr ) return 0;
3377 testcase( pExpr->op==TK_EXISTS );
3378 testcase( pExpr->op==TK_SELECT );
3379 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3380 assert( ExprUseXSelect(pExpr) );
3381 pSel = pExpr->x.pSelect;
3383 /* If this routine has already been coded, then invoke it as a
3384 ** subroutine. */
3385 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3386 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3387 assert( ExprUseYSub(pExpr) );
3388 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3389 pExpr->y.sub.iAddr);
3390 return pExpr->iTable;
3393 /* Begin coding the subroutine */
3394 assert( !ExprUseYWin(pExpr) );
3395 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
3396 ExprSetProperty(pExpr, EP_Subrtn);
3397 pExpr->y.sub.regReturn = ++pParse->nMem;
3398 pExpr->y.sub.iAddr =
3399 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3401 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3402 ** is encountered if any of the following is true:
3404 ** * The right-hand side is a correlated subquery
3405 ** * The right-hand side is an expression list containing variables
3406 ** * We are inside a trigger
3408 ** If all of the above are false, then we can run this code just once
3409 ** save the results, and reuse the same result on subsequent invocations.
3411 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3412 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3415 /* For a SELECT, generate code to put the values for all columns of
3416 ** the first row into an array of registers and return the index of
3417 ** the first register.
3419 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3420 ** into a register and return that register number.
3422 ** In both cases, the query is augmented with "LIMIT 1". Any
3423 ** preexisting limit is discarded in place of the new LIMIT 1.
3425 ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d",
3426 addrOnce?"":"CORRELATED ", pSel->selId));
3427 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1);
3428 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3429 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3430 pParse->nMem += nReg;
3431 if( pExpr->op==TK_SELECT ){
3432 dest.eDest = SRT_Mem;
3433 dest.iSdst = dest.iSDParm;
3434 dest.nSdst = nReg;
3435 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3436 VdbeComment((v, "Init subquery result"));
3437 }else{
3438 dest.eDest = SRT_Exists;
3439 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3440 VdbeComment((v, "Init EXISTS result"));
3442 if( pSel->pLimit ){
3443 /* The subquery already has a limit. If the pre-existing limit is X
3444 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3445 sqlite3 *db = pParse->db;
3446 pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3447 if( pLimit ){
3448 pLimit->affExpr = SQLITE_AFF_NUMERIC;
3449 pLimit = sqlite3PExpr(pParse, TK_NE,
3450 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3452 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
3453 pSel->pLimit->pLeft = pLimit;
3454 }else{
3455 /* If there is no pre-existing limit add a limit of 1 */
3456 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3457 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3459 pSel->iLimit = 0;
3460 if( sqlite3Select(pParse, pSel, &dest) ){
3461 pExpr->op2 = pExpr->op;
3462 pExpr->op = TK_ERROR;
3463 return 0;
3465 pExpr->iTable = rReg = dest.iSDParm;
3466 ExprSetVVAProperty(pExpr, EP_NoReduce);
3467 if( addrOnce ){
3468 sqlite3VdbeJumpHere(v, addrOnce);
3470 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
3472 /* Subroutine return */
3473 assert( ExprUseYSub(pExpr) );
3474 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3475 || pParse->nErr );
3476 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3477 pExpr->y.sub.iAddr, 1);
3478 VdbeCoverage(v);
3479 sqlite3ClearTempRegCache(pParse);
3480 return rReg;
3482 #endif /* SQLITE_OMIT_SUBQUERY */
3484 #ifndef SQLITE_OMIT_SUBQUERY
3486 ** Expr pIn is an IN(...) expression. This function checks that the
3487 ** sub-select on the RHS of the IN() operator has the same number of
3488 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3489 ** a sub-query, that the LHS is a vector of size 1.
3491 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3492 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3493 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
3494 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3495 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3496 return 1;
3498 }else if( nVector!=1 ){
3499 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3500 return 1;
3502 return 0;
3504 #endif
3506 #ifndef SQLITE_OMIT_SUBQUERY
3508 ** Generate code for an IN expression.
3510 ** x IN (SELECT ...)
3511 ** x IN (value, value, ...)
3513 ** The left-hand side (LHS) is a scalar or vector expression. The
3514 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3515 ** subquery. If the RHS is a subquery, the number of result columns must
3516 ** match the number of columns in the vector on the LHS. If the RHS is
3517 ** a list of values, the LHS must be a scalar.
3519 ** The IN operator is true if the LHS value is contained within the RHS.
3520 ** The result is false if the LHS is definitely not in the RHS. The
3521 ** result is NULL if the presence of the LHS in the RHS cannot be
3522 ** determined due to NULLs.
3524 ** This routine generates code that jumps to destIfFalse if the LHS is not
3525 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3526 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3527 ** within the RHS then fall through.
3529 ** See the separate in-operator.md documentation file in the canonical
3530 ** SQLite source tree for additional information.
3532 static void sqlite3ExprCodeIN(
3533 Parse *pParse, /* Parsing and code generating context */
3534 Expr *pExpr, /* The IN expression */
3535 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
3536 int destIfNull /* Jump here if the results are unknown due to NULLs */
3538 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
3539 int eType; /* Type of the RHS */
3540 int rLhs; /* Register(s) holding the LHS values */
3541 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
3542 Vdbe *v; /* Statement under construction */
3543 int *aiMap = 0; /* Map from vector field to index column */
3544 char *zAff = 0; /* Affinity string for comparisons */
3545 int nVector; /* Size of vectors for this IN operator */
3546 int iDummy; /* Dummy parameter to exprCodeVector() */
3547 Expr *pLeft; /* The LHS of the IN operator */
3548 int i; /* loop counter */
3549 int destStep2; /* Where to jump when NULLs seen in step 2 */
3550 int destStep6 = 0; /* Start of code for Step 6 */
3551 int addrTruthOp; /* Address of opcode that determines the IN is true */
3552 int destNotNull; /* Jump here if a comparison is not true in step 6 */
3553 int addrTop; /* Top of the step-6 loop */
3554 int iTab = 0; /* Index to use */
3555 u8 okConstFactor = pParse->okConstFactor;
3557 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3558 pLeft = pExpr->pLeft;
3559 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3560 zAff = exprINAffinity(pParse, pExpr);
3561 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3562 aiMap = (int*)sqlite3DbMallocZero(
3563 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3565 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3567 /* Attempt to compute the RHS. After this step, if anything other than
3568 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3569 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3570 ** the RHS has not yet been coded. */
3571 v = pParse->pVdbe;
3572 assert( v!=0 ); /* OOM detected prior to this routine */
3573 VdbeNoopComment((v, "begin IN expr"));
3574 eType = sqlite3FindInIndex(pParse, pExpr,
3575 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3576 destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3577 aiMap, &iTab);
3579 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3580 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3582 #ifdef SQLITE_DEBUG
3583 /* Confirm that aiMap[] contains nVector integer values between 0 and
3584 ** nVector-1. */
3585 for(i=0; i<nVector; i++){
3586 int j, cnt;
3587 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3588 assert( cnt==1 );
3590 #endif
3592 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3593 ** vector, then it is stored in an array of nVector registers starting
3594 ** at r1.
3596 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3597 ** so that the fields are in the same order as an existing index. The
3598 ** aiMap[] array contains a mapping from the original LHS field order to
3599 ** the field order that matches the RHS index.
3601 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3602 ** even if it is constant, as OP_Affinity may be used on the register
3603 ** by code generated below. */
3604 assert( pParse->okConstFactor==okConstFactor );
3605 pParse->okConstFactor = 0;
3606 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3607 pParse->okConstFactor = okConstFactor;
3608 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3609 if( i==nVector ){
3610 /* LHS fields are not reordered */
3611 rLhs = rLhsOrig;
3612 }else{
3613 /* Need to reorder the LHS fields according to aiMap */
3614 rLhs = sqlite3GetTempRange(pParse, nVector);
3615 for(i=0; i<nVector; i++){
3616 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3620 /* If sqlite3FindInIndex() did not find or create an index that is
3621 ** suitable for evaluating the IN operator, then evaluate using a
3622 ** sequence of comparisons.
3624 ** This is step (1) in the in-operator.md optimized algorithm.
3626 if( eType==IN_INDEX_NOOP ){
3627 ExprList *pList;
3628 CollSeq *pColl;
3629 int labelOk = sqlite3VdbeMakeLabel(pParse);
3630 int r2, regToFree;
3631 int regCkNull = 0;
3632 int ii;
3633 assert( ExprUseXList(pExpr) );
3634 pList = pExpr->x.pList;
3635 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3636 if( destIfNull!=destIfFalse ){
3637 regCkNull = sqlite3GetTempReg(pParse);
3638 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3640 for(ii=0; ii<pList->nExpr; ii++){
3641 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3642 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3643 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3645 sqlite3ReleaseTempReg(pParse, regToFree);
3646 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3647 int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
3648 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
3649 (void*)pColl, P4_COLLSEQ);
3650 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
3651 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
3652 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
3653 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
3654 sqlite3VdbeChangeP5(v, zAff[0]);
3655 }else{
3656 int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
3657 assert( destIfNull==destIfFalse );
3658 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
3659 (void*)pColl, P4_COLLSEQ);
3660 VdbeCoverageIf(v, op==OP_Ne);
3661 VdbeCoverageIf(v, op==OP_IsNull);
3662 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3665 if( regCkNull ){
3666 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3667 sqlite3VdbeGoto(v, destIfFalse);
3669 sqlite3VdbeResolveLabel(v, labelOk);
3670 sqlite3ReleaseTempReg(pParse, regCkNull);
3671 goto sqlite3ExprCodeIN_finished;
3674 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3675 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3676 ** We will then skip the binary search of the RHS.
3678 if( destIfNull==destIfFalse ){
3679 destStep2 = destIfFalse;
3680 }else{
3681 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3683 for(i=0; i<nVector; i++){
3684 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3685 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
3686 if( sqlite3ExprCanBeNull(p) ){
3687 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3688 VdbeCoverage(v);
3692 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3693 ** of the RHS using the LHS as a probe. If found, the result is
3694 ** true.
3696 if( eType==IN_INDEX_ROWID ){
3697 /* In this case, the RHS is the ROWID of table b-tree and so we also
3698 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3699 ** into a single opcode. */
3700 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3701 VdbeCoverage(v);
3702 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
3703 }else{
3704 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3705 if( destIfFalse==destIfNull ){
3706 /* Combine Step 3 and Step 5 into a single opcode */
3707 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3708 rLhs, nVector); VdbeCoverage(v);
3709 goto sqlite3ExprCodeIN_finished;
3711 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3712 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3713 rLhs, nVector); VdbeCoverage(v);
3716 /* Step 4. If the RHS is known to be non-NULL and we did not find
3717 ** an match on the search above, then the result must be FALSE.
3719 if( rRhsHasNull && nVector==1 ){
3720 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3721 VdbeCoverage(v);
3724 /* Step 5. If we do not care about the difference between NULL and
3725 ** FALSE, then just return false.
3727 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3729 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3730 ** If any comparison is NULL, then the result is NULL. If all
3731 ** comparisons are FALSE then the final result is FALSE.
3733 ** For a scalar LHS, it is sufficient to check just the first row
3734 ** of the RHS.
3736 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3737 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
3738 VdbeCoverage(v);
3739 if( nVector>1 ){
3740 destNotNull = sqlite3VdbeMakeLabel(pParse);
3741 }else{
3742 /* For nVector==1, combine steps 6 and 7 by immediately returning
3743 ** FALSE if the first comparison is not NULL */
3744 destNotNull = destIfFalse;
3746 for(i=0; i<nVector; i++){
3747 Expr *p;
3748 CollSeq *pColl;
3749 int r3 = sqlite3GetTempReg(pParse);
3750 p = sqlite3VectorFieldSubexpr(pLeft, i);
3751 pColl = sqlite3ExprCollSeq(pParse, p);
3752 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
3753 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3754 (void*)pColl, P4_COLLSEQ);
3755 VdbeCoverage(v);
3756 sqlite3ReleaseTempReg(pParse, r3);
3758 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3759 if( nVector>1 ){
3760 sqlite3VdbeResolveLabel(v, destNotNull);
3761 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
3762 VdbeCoverage(v);
3764 /* Step 7: If we reach this point, we know that the result must
3765 ** be false. */
3766 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3769 /* Jumps here in order to return true. */
3770 sqlite3VdbeJumpHere(v, addrTruthOp);
3772 sqlite3ExprCodeIN_finished:
3773 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3774 VdbeComment((v, "end IN expr"));
3775 sqlite3ExprCodeIN_oom_error:
3776 sqlite3DbFree(pParse->db, aiMap);
3777 sqlite3DbFree(pParse->db, zAff);
3779 #endif /* SQLITE_OMIT_SUBQUERY */
3781 #ifndef SQLITE_OMIT_FLOATING_POINT
3783 ** Generate an instruction that will put the floating point
3784 ** value described by z[0..n-1] into register iMem.
3786 ** The z[] string will probably not be zero-terminated. But the
3787 ** z[n] character is guaranteed to be something that does not look
3788 ** like the continuation of the number.
3790 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3791 if( ALWAYS(z!=0) ){
3792 double value;
3793 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3794 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3795 if( negateFlag ) value = -value;
3796 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3799 #endif
3803 ** Generate an instruction that will put the integer describe by
3804 ** text z[0..n-1] into register iMem.
3806 ** Expr.u.zToken is always UTF8 and zero-terminated.
3808 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3809 Vdbe *v = pParse->pVdbe;
3810 if( pExpr->flags & EP_IntValue ){
3811 int i = pExpr->u.iValue;
3812 assert( i>=0 );
3813 if( negFlag ) i = -i;
3814 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3815 }else{
3816 int c;
3817 i64 value;
3818 const char *z = pExpr->u.zToken;
3819 assert( z!=0 );
3820 c = sqlite3DecOrHexToI64(z, &value);
3821 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
3822 #ifdef SQLITE_OMIT_FLOATING_POINT
3823 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
3824 #else
3825 #ifndef SQLITE_OMIT_HEX_INTEGER
3826 if( sqlite3_strnicmp(z,"0x",2)==0 ){
3827 sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T",
3828 negFlag?"-":"",pExpr);
3829 }else
3830 #endif
3832 codeReal(v, z, negFlag, iMem);
3834 #endif
3835 }else{
3836 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
3837 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3843 /* Generate code that will load into register regOut a value that is
3844 ** appropriate for the iIdxCol-th column of index pIdx.
3846 void sqlite3ExprCodeLoadIndexColumn(
3847 Parse *pParse, /* The parsing context */
3848 Index *pIdx, /* The index whose column is to be loaded */
3849 int iTabCur, /* Cursor pointing to a table row */
3850 int iIdxCol, /* The column of the index to be loaded */
3851 int regOut /* Store the index column value in this register */
3853 i16 iTabCol = pIdx->aiColumn[iIdxCol];
3854 if( iTabCol==XN_EXPR ){
3855 assert( pIdx->aColExpr );
3856 assert( pIdx->aColExpr->nExpr>iIdxCol );
3857 pParse->iSelfTab = iTabCur + 1;
3858 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
3859 pParse->iSelfTab = 0;
3860 }else{
3861 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3862 iTabCol, regOut);
3866 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3868 ** Generate code that will compute the value of generated column pCol
3869 ** and store the result in register regOut
3871 void sqlite3ExprCodeGeneratedColumn(
3872 Parse *pParse, /* Parsing context */
3873 Table *pTab, /* Table containing the generated column */
3874 Column *pCol, /* The generated column */
3875 int regOut /* Put the result in this register */
3877 int iAddr;
3878 Vdbe *v = pParse->pVdbe;
3879 int nErr = pParse->nErr;
3880 assert( v!=0 );
3881 assert( pParse->iSelfTab!=0 );
3882 if( pParse->iSelfTab>0 ){
3883 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
3884 }else{
3885 iAddr = 0;
3887 sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
3888 if( pCol->affinity>=SQLITE_AFF_TEXT ){
3889 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
3891 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
3892 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
3894 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3897 ** Generate code to extract the value of the iCol-th column of a table.
3899 void sqlite3ExprCodeGetColumnOfTable(
3900 Vdbe *v, /* Parsing context */
3901 Table *pTab, /* The table containing the value */
3902 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
3903 int iCol, /* Index of the column to extract */
3904 int regOut /* Extract the value into this register */
3906 Column *pCol;
3907 assert( v!=0 );
3908 assert( pTab!=0 );
3909 assert( iCol!=XN_EXPR );
3910 if( iCol<0 || iCol==pTab->iPKey ){
3911 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3912 VdbeComment((v, "%s.rowid", pTab->zName));
3913 }else{
3914 int op;
3915 int x;
3916 if( IsVirtual(pTab) ){
3917 op = OP_VColumn;
3918 x = iCol;
3919 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3920 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
3921 Parse *pParse = sqlite3VdbeParser(v);
3922 if( pCol->colFlags & COLFLAG_BUSY ){
3923 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
3924 pCol->zCnName);
3925 }else{
3926 int savedSelfTab = pParse->iSelfTab;
3927 pCol->colFlags |= COLFLAG_BUSY;
3928 pParse->iSelfTab = iTabCur+1;
3929 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut);
3930 pParse->iSelfTab = savedSelfTab;
3931 pCol->colFlags &= ~COLFLAG_BUSY;
3933 return;
3934 #endif
3935 }else if( !HasRowid(pTab) ){
3936 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
3937 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3938 op = OP_Column;
3939 }else{
3940 x = sqlite3TableColumnToStorage(pTab,iCol);
3941 testcase( x!=iCol );
3942 op = OP_Column;
3944 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
3945 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3950 ** Generate code that will extract the iColumn-th column from
3951 ** table pTab and store the column value in register iReg.
3953 ** There must be an open cursor to pTab in iTable when this routine
3954 ** is called. If iColumn<0 then code is generated that extracts the rowid.
3956 int sqlite3ExprCodeGetColumn(
3957 Parse *pParse, /* Parsing and code generating context */
3958 Table *pTab, /* Description of the table we are reading from */
3959 int iColumn, /* Index of the table column */
3960 int iTable, /* The cursor pointing to the table */
3961 int iReg, /* Store results here */
3962 u8 p5 /* P5 value for OP_Column + FLAGS */
3964 assert( pParse->pVdbe!=0 );
3965 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
3966 if( p5 ){
3967 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
3968 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
3970 return iReg;
3974 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3975 ** over to iTo..iTo+nReg-1.
3977 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3978 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3982 ** Convert a scalar expression node to a TK_REGISTER referencing
3983 ** register iReg. The caller must ensure that iReg already contains
3984 ** the correct value for the expression.
3986 static void exprToRegister(Expr *pExpr, int iReg){
3987 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
3988 if( NEVER(p==0) ) return;
3989 p->op2 = p->op;
3990 p->op = TK_REGISTER;
3991 p->iTable = iReg;
3992 ExprClearProperty(p, EP_Skip);
3996 ** Evaluate an expression (either a vector or a scalar expression) and store
3997 ** the result in continguous temporary registers. Return the index of
3998 ** the first register used to store the result.
4000 ** If the returned result register is a temporary scalar, then also write
4001 ** that register number into *piFreeable. If the returned result register
4002 ** is not a temporary or if the expression is a vector set *piFreeable
4003 ** to 0.
4005 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
4006 int iResult;
4007 int nResult = sqlite3ExprVectorSize(p);
4008 if( nResult==1 ){
4009 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
4010 }else{
4011 *piFreeable = 0;
4012 if( p->op==TK_SELECT ){
4013 #if SQLITE_OMIT_SUBQUERY
4014 iResult = 0;
4015 #else
4016 iResult = sqlite3CodeSubselect(pParse, p);
4017 #endif
4018 }else{
4019 int i;
4020 iResult = pParse->nMem+1;
4021 pParse->nMem += nResult;
4022 assert( ExprUseXList(p) );
4023 for(i=0; i<nResult; i++){
4024 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
4028 return iResult;
4032 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4033 ** so that a subsequent copy will not be merged into this one.
4035 static void setDoNotMergeFlagOnCopy(Vdbe *v){
4036 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
4037 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergable */
4042 ** Generate code to implement special SQL functions that are implemented
4043 ** in-line rather than by using the usual callbacks.
4045 static int exprCodeInlineFunction(
4046 Parse *pParse, /* Parsing context */
4047 ExprList *pFarg, /* List of function arguments */
4048 int iFuncId, /* Function ID. One of the INTFUNC_... values */
4049 int target /* Store function result in this register */
4051 int nFarg;
4052 Vdbe *v = pParse->pVdbe;
4053 assert( v!=0 );
4054 assert( pFarg!=0 );
4055 nFarg = pFarg->nExpr;
4056 assert( nFarg>0 ); /* All in-line functions have at least one argument */
4057 switch( iFuncId ){
4058 case INLINEFUNC_coalesce: {
4059 /* Attempt a direct implementation of the built-in COALESCE() and
4060 ** IFNULL() functions. This avoids unnecessary evaluation of
4061 ** arguments past the first non-NULL argument.
4063 int endCoalesce = sqlite3VdbeMakeLabel(pParse);
4064 int i;
4065 assert( nFarg>=2 );
4066 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
4067 for(i=1; i<nFarg; i++){
4068 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
4069 VdbeCoverage(v);
4070 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
4072 setDoNotMergeFlagOnCopy(v);
4073 sqlite3VdbeResolveLabel(v, endCoalesce);
4074 break;
4076 case INLINEFUNC_iif: {
4077 Expr caseExpr;
4078 memset(&caseExpr, 0, sizeof(caseExpr));
4079 caseExpr.op = TK_CASE;
4080 caseExpr.x.pList = pFarg;
4081 return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
4083 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4084 case INLINEFUNC_sqlite_offset: {
4085 Expr *pArg = pFarg->a[0].pExpr;
4086 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
4087 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4088 }else{
4089 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4091 break;
4093 #endif
4094 default: {
4095 /* The UNLIKELY() function is a no-op. The result is the value
4096 ** of the first argument.
4098 assert( nFarg==1 || nFarg==2 );
4099 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
4100 break;
4103 /***********************************************************************
4104 ** Test-only SQL functions that are only usable if enabled
4105 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4107 #if !defined(SQLITE_UNTESTABLE)
4108 case INLINEFUNC_expr_compare: {
4109 /* Compare two expressions using sqlite3ExprCompare() */
4110 assert( nFarg==2 );
4111 sqlite3VdbeAddOp2(v, OP_Integer,
4112 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4113 target);
4114 break;
4117 case INLINEFUNC_expr_implies_expr: {
4118 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4119 assert( nFarg==2 );
4120 sqlite3VdbeAddOp2(v, OP_Integer,
4121 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4122 target);
4123 break;
4126 case INLINEFUNC_implies_nonnull_row: {
4127 /* REsult of sqlite3ExprImpliesNonNullRow() */
4128 Expr *pA1;
4129 assert( nFarg==2 );
4130 pA1 = pFarg->a[1].pExpr;
4131 if( pA1->op==TK_COLUMN ){
4132 sqlite3VdbeAddOp2(v, OP_Integer,
4133 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
4134 target);
4135 }else{
4136 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4138 break;
4141 case INLINEFUNC_affinity: {
4142 /* The AFFINITY() function evaluates to a string that describes
4143 ** the type affinity of the argument. This is used for testing of
4144 ** the SQLite type logic.
4146 const char *azAff[] = { "blob", "text", "numeric", "integer",
4147 "real", "flexnum" };
4148 char aff;
4149 assert( nFarg==1 );
4150 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
4151 assert( aff<=SQLITE_AFF_NONE
4152 || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) );
4153 sqlite3VdbeLoadString(v, target,
4154 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
4155 break;
4157 #endif /* !defined(SQLITE_UNTESTABLE) */
4159 return target;
4163 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4164 ** If it is, then resolve the expression by reading from the index and
4165 ** return the register into which the value has been read. If pExpr is
4166 ** not an indexed expression, then return negative.
4168 static SQLITE_NOINLINE int sqlite3IndexedExprLookup(
4169 Parse *pParse, /* The parsing context */
4170 Expr *pExpr, /* The expression to potentially bypass */
4171 int target /* Where to store the result of the expression */
4173 IndexedExpr *p;
4174 Vdbe *v;
4175 for(p=pParse->pIdxEpr; p; p=p->pIENext){
4176 u8 exprAff;
4177 int iDataCur = p->iDataCur;
4178 if( iDataCur<0 ) continue;
4179 if( pParse->iSelfTab ){
4180 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
4181 iDataCur = -1;
4183 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
4184 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
4185 exprAff = sqlite3ExprAffinity(pExpr);
4186 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
4187 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
4188 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
4190 /* Affinity mismatch on a generated column */
4191 continue;
4194 v = pParse->pVdbe;
4195 assert( v!=0 );
4196 if( p->bMaybeNullRow ){
4197 /* If the index is on a NULL row due to an outer join, then we
4198 ** cannot extract the value from the index. The value must be
4199 ** computed using the original expression. */
4200 int addr = sqlite3VdbeCurrentAddr(v);
4201 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
4202 VdbeCoverage(v);
4203 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4204 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4205 sqlite3VdbeGoto(v, 0);
4206 p = pParse->pIdxEpr;
4207 pParse->pIdxEpr = 0;
4208 sqlite3ExprCode(pParse, pExpr, target);
4209 pParse->pIdxEpr = p;
4210 sqlite3VdbeJumpHere(v, addr+2);
4211 }else{
4212 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4213 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4215 return target;
4217 return -1; /* Not found */
4222 ** Generate code into the current Vdbe to evaluate the given
4223 ** expression. Attempt to store the results in register "target".
4224 ** Return the register where results are stored.
4226 ** With this routine, there is no guarantee that results will
4227 ** be stored in target. The result might be stored in some other
4228 ** register if it is convenient to do so. The calling function
4229 ** must check the return code and move the results to the desired
4230 ** register.
4232 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
4233 Vdbe *v = pParse->pVdbe; /* The VM under construction */
4234 int op; /* The opcode being coded */
4235 int inReg = target; /* Results stored in register inReg */
4236 int regFree1 = 0; /* If non-zero free this temporary register */
4237 int regFree2 = 0; /* If non-zero free this temporary register */
4238 int r1, r2; /* Various register numbers */
4239 Expr tempX; /* Temporary expression node */
4240 int p5 = 0;
4242 assert( target>0 && target<=pParse->nMem );
4243 assert( v!=0 );
4245 expr_code_doover:
4246 if( pExpr==0 ){
4247 op = TK_NULL;
4248 }else if( pParse->pIdxEpr!=0
4249 && !ExprHasProperty(pExpr, EP_Leaf)
4250 && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0
4252 return r1;
4253 }else{
4254 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
4255 op = pExpr->op;
4257 switch( op ){
4258 case TK_AGG_COLUMN: {
4259 AggInfo *pAggInfo = pExpr->pAggInfo;
4260 struct AggInfo_col *pCol;
4261 assert( pAggInfo!=0 );
4262 assert( pExpr->iAgg>=0 );
4263 if( pExpr->iAgg>=pAggInfo->nColumn ){
4264 /* Happens when the left table of a RIGHT JOIN is null and
4265 ** is using an expression index */
4266 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4267 #ifdef SQLITE_VDBE_COVERAGE
4268 /* Verify that the OP_Null above is exercised by tests
4269 ** tag-20230325-2 */
4270 sqlite3VdbeAddOp2(v, OP_NotNull, target, 1);
4271 VdbeCoverageNeverTaken(v);
4272 #endif
4273 break;
4275 pCol = &pAggInfo->aCol[pExpr->iAgg];
4276 if( !pAggInfo->directMode ){
4277 return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
4278 }else if( pAggInfo->useSortingIdx ){
4279 Table *pTab = pCol->pTab;
4280 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
4281 pCol->iSorterColumn, target);
4282 if( pTab==0 ){
4283 /* No comment added */
4284 }else if( pCol->iColumn<0 ){
4285 VdbeComment((v,"%s.rowid",pTab->zName));
4286 }else{
4287 VdbeComment((v,"%s.%s",
4288 pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
4289 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
4290 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4293 return target;
4294 }else if( pExpr->y.pTab==0 ){
4295 /* This case happens when the argument to an aggregate function
4296 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4297 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target);
4298 return target;
4300 /* Otherwise, fall thru into the TK_COLUMN case */
4301 /* no break */ deliberate_fall_through
4303 case TK_COLUMN: {
4304 int iTab = pExpr->iTable;
4305 int iReg;
4306 if( ExprHasProperty(pExpr, EP_FixedCol) ){
4307 /* This COLUMN expression is really a constant due to WHERE clause
4308 ** constraints, and that constant is coded by the pExpr->pLeft
4309 ** expresssion. However, make sure the constant has the correct
4310 ** datatype by applying the Affinity of the table column to the
4311 ** constant.
4313 int aff;
4314 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
4315 assert( ExprUseYTab(pExpr) );
4316 assert( pExpr->y.pTab!=0 );
4317 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
4318 if( aff>SQLITE_AFF_BLOB ){
4319 static const char zAff[] = "B\000C\000D\000E\000F";
4320 assert( SQLITE_AFF_BLOB=='A' );
4321 assert( SQLITE_AFF_TEXT=='B' );
4322 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
4323 &zAff[(aff-'B')*2], P4_STATIC);
4325 return iReg;
4327 if( iTab<0 ){
4328 if( pParse->iSelfTab<0 ){
4329 /* Other columns in the same row for CHECK constraints or
4330 ** generated columns or for inserting into partial index.
4331 ** The row is unpacked into registers beginning at
4332 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4333 ** immediately prior to the first column.
4335 Column *pCol;
4336 Table *pTab;
4337 int iSrc;
4338 int iCol = pExpr->iColumn;
4339 assert( ExprUseYTab(pExpr) );
4340 pTab = pExpr->y.pTab;
4341 assert( pTab!=0 );
4342 assert( iCol>=XN_ROWID );
4343 assert( iCol<pTab->nCol );
4344 if( iCol<0 ){
4345 return -1-pParse->iSelfTab;
4347 pCol = pTab->aCol + iCol;
4348 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
4349 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
4350 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4351 if( pCol->colFlags & COLFLAG_GENERATED ){
4352 if( pCol->colFlags & COLFLAG_BUSY ){
4353 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4354 pCol->zCnName);
4355 return 0;
4357 pCol->colFlags |= COLFLAG_BUSY;
4358 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
4359 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc);
4361 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
4362 return iSrc;
4363 }else
4364 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4365 if( pCol->affinity==SQLITE_AFF_REAL ){
4366 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
4367 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4368 return target;
4369 }else{
4370 return iSrc;
4372 }else{
4373 /* Coding an expression that is part of an index where column names
4374 ** in the index refer to the table to which the index belongs */
4375 iTab = pParse->iSelfTab - 1;
4378 assert( ExprUseYTab(pExpr) );
4379 assert( pExpr->y.pTab!=0 );
4380 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
4381 pExpr->iColumn, iTab, target,
4382 pExpr->op2);
4383 return iReg;
4385 case TK_INTEGER: {
4386 codeInteger(pParse, pExpr, 0, target);
4387 return target;
4389 case TK_TRUEFALSE: {
4390 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
4391 return target;
4393 #ifndef SQLITE_OMIT_FLOATING_POINT
4394 case TK_FLOAT: {
4395 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4396 codeReal(v, pExpr->u.zToken, 0, target);
4397 return target;
4399 #endif
4400 case TK_STRING: {
4401 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4402 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
4403 return target;
4405 default: {
4406 /* Make NULL the default case so that if a bug causes an illegal
4407 ** Expr node to be passed into this function, it will be handled
4408 ** sanely and not crash. But keep the assert() to bring the problem
4409 ** to the attention of the developers. */
4410 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
4411 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4412 return target;
4414 #ifndef SQLITE_OMIT_BLOB_LITERAL
4415 case TK_BLOB: {
4416 int n;
4417 const char *z;
4418 char *zBlob;
4419 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4420 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
4421 assert( pExpr->u.zToken[1]=='\'' );
4422 z = &pExpr->u.zToken[2];
4423 n = sqlite3Strlen30(z) - 1;
4424 assert( z[n]=='\'' );
4425 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
4426 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
4427 return target;
4429 #endif
4430 case TK_VARIABLE: {
4431 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4432 assert( pExpr->u.zToken!=0 );
4433 assert( pExpr->u.zToken[0]!=0 );
4434 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
4435 if( pExpr->u.zToken[1]!=0 ){
4436 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
4437 assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
4438 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
4439 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
4441 return target;
4443 case TK_REGISTER: {
4444 return pExpr->iTable;
4446 #ifndef SQLITE_OMIT_CAST
4447 case TK_CAST: {
4448 /* Expressions of the form: CAST(pLeft AS token) */
4449 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4450 assert( inReg==target );
4451 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4452 sqlite3VdbeAddOp2(v, OP_Cast, target,
4453 sqlite3AffinityType(pExpr->u.zToken, 0));
4454 return inReg;
4456 #endif /* SQLITE_OMIT_CAST */
4457 case TK_IS:
4458 case TK_ISNOT:
4459 op = (op==TK_IS) ? TK_EQ : TK_NE;
4460 p5 = SQLITE_NULLEQ;
4461 /* fall-through */
4462 case TK_LT:
4463 case TK_LE:
4464 case TK_GT:
4465 case TK_GE:
4466 case TK_NE:
4467 case TK_EQ: {
4468 Expr *pLeft = pExpr->pLeft;
4469 if( sqlite3ExprIsVector(pLeft) ){
4470 codeVectorCompare(pParse, pExpr, target, op, p5);
4471 }else{
4472 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
4473 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4474 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
4475 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
4476 sqlite3VdbeCurrentAddr(v)+2, p5,
4477 ExprHasProperty(pExpr,EP_Commuted));
4478 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4479 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4480 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4481 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4482 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
4483 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
4484 if( p5==SQLITE_NULLEQ ){
4485 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
4486 }else{
4487 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
4489 testcase( regFree1==0 );
4490 testcase( regFree2==0 );
4492 break;
4494 case TK_AND:
4495 case TK_OR:
4496 case TK_PLUS:
4497 case TK_STAR:
4498 case TK_MINUS:
4499 case TK_REM:
4500 case TK_BITAND:
4501 case TK_BITOR:
4502 case TK_SLASH:
4503 case TK_LSHIFT:
4504 case TK_RSHIFT:
4505 case TK_CONCAT: {
4506 assert( TK_AND==OP_And ); testcase( op==TK_AND );
4507 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
4508 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
4509 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
4510 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
4511 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
4512 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
4513 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
4514 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
4515 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
4516 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
4517 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4518 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4519 sqlite3VdbeAddOp3(v, op, r2, r1, target);
4520 testcase( regFree1==0 );
4521 testcase( regFree2==0 );
4522 break;
4524 case TK_UMINUS: {
4525 Expr *pLeft = pExpr->pLeft;
4526 assert( pLeft );
4527 if( pLeft->op==TK_INTEGER ){
4528 codeInteger(pParse, pLeft, 1, target);
4529 return target;
4530 #ifndef SQLITE_OMIT_FLOATING_POINT
4531 }else if( pLeft->op==TK_FLOAT ){
4532 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4533 codeReal(v, pLeft->u.zToken, 1, target);
4534 return target;
4535 #endif
4536 }else{
4537 tempX.op = TK_INTEGER;
4538 tempX.flags = EP_IntValue|EP_TokenOnly;
4539 tempX.u.iValue = 0;
4540 ExprClearVVAProperties(&tempX);
4541 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
4542 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
4543 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
4544 testcase( regFree2==0 );
4546 break;
4548 case TK_BITNOT:
4549 case TK_NOT: {
4550 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
4551 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
4552 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4553 testcase( regFree1==0 );
4554 sqlite3VdbeAddOp2(v, op, r1, inReg);
4555 break;
4557 case TK_TRUTH: {
4558 int isTrue; /* IS TRUE or IS NOT TRUE */
4559 int bNormal; /* IS TRUE or IS FALSE */
4560 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4561 testcase( regFree1==0 );
4562 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4563 bNormal = pExpr->op2==TK_IS;
4564 testcase( isTrue && bNormal);
4565 testcase( !isTrue && bNormal);
4566 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
4567 break;
4569 case TK_ISNULL:
4570 case TK_NOTNULL: {
4571 int addr;
4572 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4573 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4574 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4575 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4576 testcase( regFree1==0 );
4577 addr = sqlite3VdbeAddOp1(v, op, r1);
4578 VdbeCoverageIf(v, op==TK_ISNULL);
4579 VdbeCoverageIf(v, op==TK_NOTNULL);
4580 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
4581 sqlite3VdbeJumpHere(v, addr);
4582 break;
4584 case TK_AGG_FUNCTION: {
4585 AggInfo *pInfo = pExpr->pAggInfo;
4586 if( pInfo==0
4587 || NEVER(pExpr->iAgg<0)
4588 || NEVER(pExpr->iAgg>=pInfo->nFunc)
4590 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4591 sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr);
4592 }else{
4593 return AggInfoFuncReg(pInfo, pExpr->iAgg);
4595 break;
4597 case TK_FUNCTION: {
4598 ExprList *pFarg; /* List of function arguments */
4599 int nFarg; /* Number of function arguments */
4600 FuncDef *pDef; /* The function definition object */
4601 const char *zId; /* The function name */
4602 u32 constMask = 0; /* Mask of function arguments that are constant */
4603 int i; /* Loop counter */
4604 sqlite3 *db = pParse->db; /* The database connection */
4605 u8 enc = ENC(db); /* The text encoding used by this database */
4606 CollSeq *pColl = 0; /* A collating sequence */
4608 #ifndef SQLITE_OMIT_WINDOWFUNC
4609 if( ExprHasProperty(pExpr, EP_WinFunc) ){
4610 return pExpr->y.pWin->regResult;
4612 #endif
4614 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
4615 /* SQL functions can be expensive. So try to avoid running them
4616 ** multiple times if we know they always give the same result */
4617 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4619 assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
4620 assert( ExprUseXList(pExpr) );
4621 pFarg = pExpr->x.pList;
4622 nFarg = pFarg ? pFarg->nExpr : 0;
4623 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4624 zId = pExpr->u.zToken;
4625 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
4626 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4627 if( pDef==0 && pParse->explain ){
4628 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
4630 #endif
4631 if( pDef==0 || pDef->xFinalize!=0 ){
4632 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
4633 break;
4635 if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
4636 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
4637 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
4638 return exprCodeInlineFunction(pParse, pFarg,
4639 SQLITE_PTR_TO_INT(pDef->pUserData), target);
4640 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
4641 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
4644 for(i=0; i<nFarg; i++){
4645 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
4646 testcase( i==31 );
4647 constMask |= MASKBIT32(i);
4649 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
4650 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
4653 if( pFarg ){
4654 if( constMask ){
4655 r1 = pParse->nMem+1;
4656 pParse->nMem += nFarg;
4657 }else{
4658 r1 = sqlite3GetTempRange(pParse, nFarg);
4661 /* For length() and typeof() functions with a column argument,
4662 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4663 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
4664 ** loading.
4666 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
4667 u8 exprOp;
4668 assert( nFarg==1 );
4669 assert( pFarg->a[0].pExpr!=0 );
4670 exprOp = pFarg->a[0].pExpr->op;
4671 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
4672 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
4673 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
4674 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
4675 pFarg->a[0].pExpr->op2 =
4676 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
4680 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
4681 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
4682 }else{
4683 r1 = 0;
4685 #ifndef SQLITE_OMIT_VIRTUALTABLE
4686 /* Possibly overload the function if the first argument is
4687 ** a virtual table column.
4689 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4690 ** second argument, not the first, as the argument to test to
4691 ** see if it is a column in a virtual table. This is done because
4692 ** the left operand of infix functions (the operand we want to
4693 ** control overloading) ends up as the second argument to the
4694 ** function. The expression "A glob B" is equivalent to
4695 ** "glob(B,A). We want to use the A in "A glob B" to test
4696 ** for function overloading. But we use the B term in "glob(B,A)".
4698 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
4699 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
4700 }else if( nFarg>0 ){
4701 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
4703 #endif
4704 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4705 if( !pColl ) pColl = db->pDfltColl;
4706 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
4708 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
4709 pDef, pExpr->op2);
4710 if( nFarg ){
4711 if( constMask==0 ){
4712 sqlite3ReleaseTempRange(pParse, r1, nFarg);
4713 }else{
4714 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
4717 return target;
4719 #ifndef SQLITE_OMIT_SUBQUERY
4720 case TK_EXISTS:
4721 case TK_SELECT: {
4722 int nCol;
4723 testcase( op==TK_EXISTS );
4724 testcase( op==TK_SELECT );
4725 if( pParse->db->mallocFailed ){
4726 return 0;
4727 }else if( op==TK_SELECT
4728 && ALWAYS( ExprUseXSelect(pExpr) )
4729 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
4731 sqlite3SubselectError(pParse, nCol, 1);
4732 }else{
4733 return sqlite3CodeSubselect(pParse, pExpr);
4735 break;
4737 case TK_SELECT_COLUMN: {
4738 int n;
4739 Expr *pLeft = pExpr->pLeft;
4740 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
4741 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
4742 pLeft->op2 = pParse->withinRJSubrtn;
4744 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
4745 n = sqlite3ExprVectorSize(pLeft);
4746 if( pExpr->iTable!=n ){
4747 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
4748 pExpr->iTable, n);
4750 return pLeft->iTable + pExpr->iColumn;
4752 case TK_IN: {
4753 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4754 int destIfNull = sqlite3VdbeMakeLabel(pParse);
4755 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4756 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4757 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4758 sqlite3VdbeResolveLabel(v, destIfFalse);
4759 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
4760 sqlite3VdbeResolveLabel(v, destIfNull);
4761 return target;
4763 #endif /* SQLITE_OMIT_SUBQUERY */
4767 ** x BETWEEN y AND z
4769 ** This is equivalent to
4771 ** x>=y AND x<=z
4773 ** X is stored in pExpr->pLeft.
4774 ** Y is stored in pExpr->pList->a[0].pExpr.
4775 ** Z is stored in pExpr->pList->a[1].pExpr.
4777 case TK_BETWEEN: {
4778 exprCodeBetween(pParse, pExpr, target, 0, 0);
4779 return target;
4781 case TK_COLLATE: {
4782 if( !ExprHasProperty(pExpr, EP_Collate) ){
4783 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
4784 ** "SOFT-COLLATE" that is added to constraints that are pushed down
4785 ** from outer queries into sub-queries by the push-down optimization.
4786 ** Clear subtypes as subtypes may not cross a subquery boundary.
4788 assert( pExpr->pLeft );
4789 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4790 sqlite3VdbeAddOp1(v, OP_ClrSubtype, target);
4791 return target;
4792 }else{
4793 pExpr = pExpr->pLeft;
4794 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
4797 case TK_SPAN:
4798 case TK_UPLUS: {
4799 pExpr = pExpr->pLeft;
4800 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4803 case TK_TRIGGER: {
4804 /* If the opcode is TK_TRIGGER, then the expression is a reference
4805 ** to a column in the new.* or old.* pseudo-tables available to
4806 ** trigger programs. In this case Expr.iTable is set to 1 for the
4807 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4808 ** is set to the column of the pseudo-table to read, or to -1 to
4809 ** read the rowid field.
4811 ** The expression is implemented using an OP_Param opcode. The p1
4812 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4813 ** to reference another column of the old.* pseudo-table, where
4814 ** i is the index of the column. For a new.rowid reference, p1 is
4815 ** set to (n+1), where n is the number of columns in each pseudo-table.
4816 ** For a reference to any other column in the new.* pseudo-table, p1
4817 ** is set to (n+2+i), where n and i are as defined previously. For
4818 ** example, if the table on which triggers are being fired is
4819 ** declared as:
4821 ** CREATE TABLE t1(a, b);
4823 ** Then p1 is interpreted as follows:
4825 ** p1==0 -> old.rowid p1==3 -> new.rowid
4826 ** p1==1 -> old.a p1==4 -> new.a
4827 ** p1==2 -> old.b p1==5 -> new.b
4829 Table *pTab;
4830 int iCol;
4831 int p1;
4833 assert( ExprUseYTab(pExpr) );
4834 pTab = pExpr->y.pTab;
4835 iCol = pExpr->iColumn;
4836 p1 = pExpr->iTable * (pTab->nCol+1) + 1
4837 + sqlite3TableColumnToStorage(pTab, iCol);
4839 assert( pExpr->iTable==0 || pExpr->iTable==1 );
4840 assert( iCol>=-1 && iCol<pTab->nCol );
4841 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
4842 assert( p1>=0 && p1<(pTab->nCol*2+2) );
4844 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
4845 VdbeComment((v, "r[%d]=%s.%s", target,
4846 (pExpr->iTable ? "new" : "old"),
4847 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
4850 #ifndef SQLITE_OMIT_FLOATING_POINT
4851 /* If the column has REAL affinity, it may currently be stored as an
4852 ** integer. Use OP_RealAffinity to make sure it is really real.
4854 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
4855 ** floating point when extracting it from the record. */
4856 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
4857 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4859 #endif
4860 break;
4863 case TK_VECTOR: {
4864 sqlite3ErrorMsg(pParse, "row value misused");
4865 break;
4868 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
4869 ** that derive from the right-hand table of a LEFT JOIN. The
4870 ** Expr.iTable value is the table number for the right-hand table.
4871 ** The expression is only evaluated if that table is not currently
4872 ** on a LEFT JOIN NULL row.
4874 case TK_IF_NULL_ROW: {
4875 int addrINR;
4876 u8 okConstFactor = pParse->okConstFactor;
4877 AggInfo *pAggInfo = pExpr->pAggInfo;
4878 if( pAggInfo ){
4879 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
4880 if( !pAggInfo->directMode ){
4881 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg);
4882 break;
4884 if( pExpr->pAggInfo->useSortingIdx ){
4885 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
4886 pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
4887 target);
4888 inReg = target;
4889 break;
4892 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target);
4893 /* The OP_IfNullRow opcode above can overwrite the result register with
4894 ** NULL. So we have to ensure that the result register is not a value
4895 ** that is suppose to be a constant. Two defenses are needed:
4896 ** (1) Temporarily disable factoring of constant expressions
4897 ** (2) Make sure the computed value really is stored in register
4898 ** "target" and not someplace else.
4900 pParse->okConstFactor = 0; /* note (1) above */
4901 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4902 assert( target==inReg );
4903 pParse->okConstFactor = okConstFactor;
4904 sqlite3VdbeJumpHere(v, addrINR);
4905 break;
4909 ** Form A:
4910 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4912 ** Form B:
4913 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4915 ** Form A is can be transformed into the equivalent form B as follows:
4916 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
4917 ** WHEN x=eN THEN rN ELSE y END
4919 ** X (if it exists) is in pExpr->pLeft.
4920 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4921 ** odd. The Y is also optional. If the number of elements in x.pList
4922 ** is even, then Y is omitted and the "otherwise" result is NULL.
4923 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4925 ** The result of the expression is the Ri for the first matching Ei,
4926 ** or if there is no matching Ei, the ELSE term Y, or if there is
4927 ** no ELSE term, NULL.
4929 case TK_CASE: {
4930 int endLabel; /* GOTO label for end of CASE stmt */
4931 int nextCase; /* GOTO label for next WHEN clause */
4932 int nExpr; /* 2x number of WHEN terms */
4933 int i; /* Loop counter */
4934 ExprList *pEList; /* List of WHEN terms */
4935 struct ExprList_item *aListelem; /* Array of WHEN terms */
4936 Expr opCompare; /* The X==Ei expression */
4937 Expr *pX; /* The X expression */
4938 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
4939 Expr *pDel = 0;
4940 sqlite3 *db = pParse->db;
4942 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
4943 assert(pExpr->x.pList->nExpr > 0);
4944 pEList = pExpr->x.pList;
4945 aListelem = pEList->a;
4946 nExpr = pEList->nExpr;
4947 endLabel = sqlite3VdbeMakeLabel(pParse);
4948 if( (pX = pExpr->pLeft)!=0 ){
4949 pDel = sqlite3ExprDup(db, pX, 0);
4950 if( db->mallocFailed ){
4951 sqlite3ExprDelete(db, pDel);
4952 break;
4954 testcase( pX->op==TK_COLUMN );
4955 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4956 testcase( regFree1==0 );
4957 memset(&opCompare, 0, sizeof(opCompare));
4958 opCompare.op = TK_EQ;
4959 opCompare.pLeft = pDel;
4960 pTest = &opCompare;
4961 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4962 ** The value in regFree1 might get SCopy-ed into the file result.
4963 ** So make sure that the regFree1 register is not reused for other
4964 ** purposes and possibly overwritten. */
4965 regFree1 = 0;
4967 for(i=0; i<nExpr-1; i=i+2){
4968 if( pX ){
4969 assert( pTest!=0 );
4970 opCompare.pRight = aListelem[i].pExpr;
4971 }else{
4972 pTest = aListelem[i].pExpr;
4974 nextCase = sqlite3VdbeMakeLabel(pParse);
4975 testcase( pTest->op==TK_COLUMN );
4976 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
4977 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
4978 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
4979 sqlite3VdbeGoto(v, endLabel);
4980 sqlite3VdbeResolveLabel(v, nextCase);
4982 if( (nExpr&1)!=0 ){
4983 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
4984 }else{
4985 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4987 sqlite3ExprDelete(db, pDel);
4988 setDoNotMergeFlagOnCopy(v);
4989 sqlite3VdbeResolveLabel(v, endLabel);
4990 break;
4992 #ifndef SQLITE_OMIT_TRIGGER
4993 case TK_RAISE: {
4994 assert( pExpr->affExpr==OE_Rollback
4995 || pExpr->affExpr==OE_Abort
4996 || pExpr->affExpr==OE_Fail
4997 || pExpr->affExpr==OE_Ignore
4999 if( !pParse->pTriggerTab && !pParse->nested ){
5000 sqlite3ErrorMsg(pParse,
5001 "RAISE() may only be used within a trigger-program");
5002 return 0;
5004 if( pExpr->affExpr==OE_Abort ){
5005 sqlite3MayAbort(pParse);
5007 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5008 if( pExpr->affExpr==OE_Ignore ){
5009 sqlite3VdbeAddOp4(
5010 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
5011 VdbeCoverage(v);
5012 }else{
5013 sqlite3HaltConstraint(pParse,
5014 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
5015 pExpr->affExpr, pExpr->u.zToken, 0, 0);
5018 break;
5020 #endif
5022 sqlite3ReleaseTempReg(pParse, regFree1);
5023 sqlite3ReleaseTempReg(pParse, regFree2);
5024 return inReg;
5028 ** Generate code that will evaluate expression pExpr just one time
5029 ** per prepared statement execution.
5031 ** If the expression uses functions (that might throw an exception) then
5032 ** guard them with an OP_Once opcode to ensure that the code is only executed
5033 ** once. If no functions are involved, then factor the code out and put it at
5034 ** the end of the prepared statement in the initialization section.
5036 ** If regDest>=0 then the result is always stored in that register and the
5037 ** result is not reusable. If regDest<0 then this routine is free to
5038 ** store the value whereever it wants. The register where the expression
5039 ** is stored is returned. When regDest<0, two identical expressions might
5040 ** code to the same register, if they do not contain function calls and hence
5041 ** are factored out into the initialization section at the end of the
5042 ** prepared statement.
5044 int sqlite3ExprCodeRunJustOnce(
5045 Parse *pParse, /* Parsing context */
5046 Expr *pExpr, /* The expression to code when the VDBE initializes */
5047 int regDest /* Store the value in this register */
5049 ExprList *p;
5050 assert( ConstFactorOk(pParse) );
5051 p = pParse->pConstExpr;
5052 if( regDest<0 && p ){
5053 struct ExprList_item *pItem;
5054 int i;
5055 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
5056 if( pItem->fg.reusable
5057 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
5059 return pItem->u.iConstExprReg;
5063 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5064 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
5065 Vdbe *v = pParse->pVdbe;
5066 int addr;
5067 assert( v );
5068 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
5069 pParse->okConstFactor = 0;
5070 if( !pParse->db->mallocFailed ){
5071 if( regDest<0 ) regDest = ++pParse->nMem;
5072 sqlite3ExprCode(pParse, pExpr, regDest);
5074 pParse->okConstFactor = 1;
5075 sqlite3ExprDelete(pParse->db, pExpr);
5076 sqlite3VdbeJumpHere(v, addr);
5077 }else{
5078 p = sqlite3ExprListAppend(pParse, p, pExpr);
5079 if( p ){
5080 struct ExprList_item *pItem = &p->a[p->nExpr-1];
5081 pItem->fg.reusable = regDest<0;
5082 if( regDest<0 ) regDest = ++pParse->nMem;
5083 pItem->u.iConstExprReg = regDest;
5085 pParse->pConstExpr = p;
5087 return regDest;
5091 ** Generate code to evaluate an expression and store the results
5092 ** into a register. Return the register number where the results
5093 ** are stored.
5095 ** If the register is a temporary register that can be deallocated,
5096 ** then write its number into *pReg. If the result register is not
5097 ** a temporary, then set *pReg to zero.
5099 ** If pExpr is a constant, then this routine might generate this
5100 ** code to fill the register in the initialization section of the
5101 ** VDBE program, in order to factor it out of the evaluation loop.
5103 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
5104 int r2;
5105 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
5106 if( ConstFactorOk(pParse)
5107 && ALWAYS(pExpr!=0)
5108 && pExpr->op!=TK_REGISTER
5109 && sqlite3ExprIsConstantNotJoin(pExpr)
5111 *pReg = 0;
5112 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
5113 }else{
5114 int r1 = sqlite3GetTempReg(pParse);
5115 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
5116 if( r2==r1 ){
5117 *pReg = r1;
5118 }else{
5119 sqlite3ReleaseTempReg(pParse, r1);
5120 *pReg = 0;
5123 return r2;
5127 ** Generate code that will evaluate expression pExpr and store the
5128 ** results in register target. The results are guaranteed to appear
5129 ** in register target.
5131 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
5132 int inReg;
5134 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
5135 assert( target>0 && target<=pParse->nMem );
5136 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
5137 if( pParse->pVdbe==0 ) return;
5138 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
5139 if( inReg!=target ){
5140 u8 op;
5141 if( ALWAYS(pExpr)
5142 && (ExprHasProperty(pExpr,EP_Subquery) || pExpr->op==TK_REGISTER)
5144 op = OP_Copy;
5145 }else{
5146 op = OP_SCopy;
5148 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
5153 ** Make a transient copy of expression pExpr and then code it using
5154 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5155 ** except that the input expression is guaranteed to be unchanged.
5157 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
5158 sqlite3 *db = pParse->db;
5159 pExpr = sqlite3ExprDup(db, pExpr, 0);
5160 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
5161 sqlite3ExprDelete(db, pExpr);
5165 ** Generate code that will evaluate expression pExpr and store the
5166 ** results in register target. The results are guaranteed to appear
5167 ** in register target. If the expression is constant, then this routine
5168 ** might choose to code the expression at initialization time.
5170 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
5171 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
5172 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
5173 }else{
5174 sqlite3ExprCodeCopy(pParse, pExpr, target);
5179 ** Generate code that pushes the value of every element of the given
5180 ** expression list into a sequence of registers beginning at target.
5182 ** Return the number of elements evaluated. The number returned will
5183 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5184 ** is defined.
5186 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5187 ** filled using OP_SCopy. OP_Copy must be used instead.
5189 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5190 ** factored out into initialization code.
5192 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5193 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5194 ** in registers at srcReg, and so the value can be copied from there.
5195 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5196 ** are simply omitted rather than being copied from srcReg.
5198 int sqlite3ExprCodeExprList(
5199 Parse *pParse, /* Parsing context */
5200 ExprList *pList, /* The expression list to be coded */
5201 int target, /* Where to write results */
5202 int srcReg, /* Source registers if SQLITE_ECEL_REF */
5203 u8 flags /* SQLITE_ECEL_* flags */
5205 struct ExprList_item *pItem;
5206 int i, j, n;
5207 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
5208 Vdbe *v = pParse->pVdbe;
5209 assert( pList!=0 );
5210 assert( target>0 );
5211 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
5212 n = pList->nExpr;
5213 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
5214 for(pItem=pList->a, i=0; i<n; i++, pItem++){
5215 Expr *pExpr = pItem->pExpr;
5216 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5217 if( pItem->fg.bSorterRef ){
5218 i--;
5219 n--;
5220 }else
5221 #endif
5222 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
5223 if( flags & SQLITE_ECEL_OMITREF ){
5224 i--;
5225 n--;
5226 }else{
5227 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
5229 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
5230 && sqlite3ExprIsConstantNotJoin(pExpr)
5232 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
5233 }else{
5234 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
5235 if( inReg!=target+i ){
5236 VdbeOp *pOp;
5237 if( copyOp==OP_Copy
5238 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
5239 && pOp->p1+pOp->p3+1==inReg
5240 && pOp->p2+pOp->p3+1==target+i
5241 && pOp->p5==0 /* The do-not-merge flag must be clear */
5243 pOp->p3++;
5244 }else{
5245 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
5250 return n;
5254 ** Generate code for a BETWEEN operator.
5256 ** x BETWEEN y AND z
5258 ** The above is equivalent to
5260 ** x>=y AND x<=z
5262 ** Code it as such, taking care to do the common subexpression
5263 ** elimination of x.
5265 ** The xJumpIf parameter determines details:
5267 ** NULL: Store the boolean result in reg[dest]
5268 ** sqlite3ExprIfTrue: Jump to dest if true
5269 ** sqlite3ExprIfFalse: Jump to dest if false
5271 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5273 static void exprCodeBetween(
5274 Parse *pParse, /* Parsing and code generating context */
5275 Expr *pExpr, /* The BETWEEN expression */
5276 int dest, /* Jump destination or storage location */
5277 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
5278 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
5280 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
5281 Expr compLeft; /* The x>=y term */
5282 Expr compRight; /* The x<=z term */
5283 int regFree1 = 0; /* Temporary use register */
5284 Expr *pDel = 0;
5285 sqlite3 *db = pParse->db;
5287 memset(&compLeft, 0, sizeof(Expr));
5288 memset(&compRight, 0, sizeof(Expr));
5289 memset(&exprAnd, 0, sizeof(Expr));
5291 assert( ExprUseXList(pExpr) );
5292 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
5293 if( db->mallocFailed==0 ){
5294 exprAnd.op = TK_AND;
5295 exprAnd.pLeft = &compLeft;
5296 exprAnd.pRight = &compRight;
5297 compLeft.op = TK_GE;
5298 compLeft.pLeft = pDel;
5299 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
5300 compRight.op = TK_LE;
5301 compRight.pLeft = pDel;
5302 compRight.pRight = pExpr->x.pList->a[1].pExpr;
5303 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5304 if( xJump ){
5305 xJump(pParse, &exprAnd, dest, jumpIfNull);
5306 }else{
5307 /* Mark the expression is being from the ON or USING clause of a join
5308 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5309 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5310 ** for clarity, but we are out of bits in the Expr.flags field so we
5311 ** have to reuse the EP_OuterON bit. Bummer. */
5312 pDel->flags |= EP_OuterON;
5313 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
5315 sqlite3ReleaseTempReg(pParse, regFree1);
5317 sqlite3ExprDelete(db, pDel);
5319 /* Ensure adequate test coverage */
5320 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
5321 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
5322 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
5323 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
5324 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
5325 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
5326 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
5327 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
5328 testcase( xJump==0 );
5332 ** Generate code for a boolean expression such that a jump is made
5333 ** to the label "dest" if the expression is true but execution
5334 ** continues straight thru if the expression is false.
5336 ** If the expression evaluates to NULL (neither true nor false), then
5337 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5339 ** This code depends on the fact that certain token values (ex: TK_EQ)
5340 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5341 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5342 ** the make process cause these values to align. Assert()s in the code
5343 ** below verify that the numbers are aligned correctly.
5345 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5346 Vdbe *v = pParse->pVdbe;
5347 int op = 0;
5348 int regFree1 = 0;
5349 int regFree2 = 0;
5350 int r1, r2;
5352 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5353 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5354 if( NEVER(pExpr==0) ) return; /* No way this can happen */
5355 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
5356 op = pExpr->op;
5357 switch( op ){
5358 case TK_AND:
5359 case TK_OR: {
5360 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5361 if( pAlt!=pExpr ){
5362 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
5363 }else if( op==TK_AND ){
5364 int d2 = sqlite3VdbeMakeLabel(pParse);
5365 testcase( jumpIfNull==0 );
5366 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
5367 jumpIfNull^SQLITE_JUMPIFNULL);
5368 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5369 sqlite3VdbeResolveLabel(v, d2);
5370 }else{
5371 testcase( jumpIfNull==0 );
5372 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5373 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5375 break;
5377 case TK_NOT: {
5378 testcase( jumpIfNull==0 );
5379 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5380 break;
5382 case TK_TRUTH: {
5383 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5384 int isTrue; /* IS TRUE or IS NOT TRUE */
5385 testcase( jumpIfNull==0 );
5386 isNot = pExpr->op2==TK_ISNOT;
5387 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5388 testcase( isTrue && isNot );
5389 testcase( !isTrue && isNot );
5390 if( isTrue ^ isNot ){
5391 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5392 isNot ? SQLITE_JUMPIFNULL : 0);
5393 }else{
5394 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5395 isNot ? SQLITE_JUMPIFNULL : 0);
5397 break;
5399 case TK_IS:
5400 case TK_ISNOT:
5401 testcase( op==TK_IS );
5402 testcase( op==TK_ISNOT );
5403 op = (op==TK_IS) ? TK_EQ : TK_NE;
5404 jumpIfNull = SQLITE_NULLEQ;
5405 /* no break */ deliberate_fall_through
5406 case TK_LT:
5407 case TK_LE:
5408 case TK_GT:
5409 case TK_GE:
5410 case TK_NE:
5411 case TK_EQ: {
5412 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5413 testcase( jumpIfNull==0 );
5414 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5415 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5416 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5417 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
5418 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5419 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5420 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5421 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5422 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5423 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5424 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5425 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5426 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5427 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5428 testcase( regFree1==0 );
5429 testcase( regFree2==0 );
5430 break;
5432 case TK_ISNULL:
5433 case TK_NOTNULL: {
5434 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
5435 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
5436 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5437 sqlite3VdbeTypeofColumn(v, r1);
5438 sqlite3VdbeAddOp2(v, op, r1, dest);
5439 VdbeCoverageIf(v, op==TK_ISNULL);
5440 VdbeCoverageIf(v, op==TK_NOTNULL);
5441 testcase( regFree1==0 );
5442 break;
5444 case TK_BETWEEN: {
5445 testcase( jumpIfNull==0 );
5446 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
5447 break;
5449 #ifndef SQLITE_OMIT_SUBQUERY
5450 case TK_IN: {
5451 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5452 int destIfNull = jumpIfNull ? dest : destIfFalse;
5453 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5454 sqlite3VdbeGoto(v, dest);
5455 sqlite3VdbeResolveLabel(v, destIfFalse);
5456 break;
5458 #endif
5459 default: {
5460 default_expr:
5461 if( ExprAlwaysTrue(pExpr) ){
5462 sqlite3VdbeGoto(v, dest);
5463 }else if( ExprAlwaysFalse(pExpr) ){
5464 /* No-op */
5465 }else{
5466 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5467 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
5468 VdbeCoverage(v);
5469 testcase( regFree1==0 );
5470 testcase( jumpIfNull==0 );
5472 break;
5475 sqlite3ReleaseTempReg(pParse, regFree1);
5476 sqlite3ReleaseTempReg(pParse, regFree2);
5480 ** Generate code for a boolean expression such that a jump is made
5481 ** to the label "dest" if the expression is false but execution
5482 ** continues straight thru if the expression is true.
5484 ** If the expression evaluates to NULL (neither true nor false) then
5485 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5486 ** is 0.
5488 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5489 Vdbe *v = pParse->pVdbe;
5490 int op = 0;
5491 int regFree1 = 0;
5492 int regFree2 = 0;
5493 int r1, r2;
5495 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5496 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5497 if( pExpr==0 ) return;
5498 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
5500 /* The value of pExpr->op and op are related as follows:
5502 ** pExpr->op op
5503 ** --------- ----------
5504 ** TK_ISNULL OP_NotNull
5505 ** TK_NOTNULL OP_IsNull
5506 ** TK_NE OP_Eq
5507 ** TK_EQ OP_Ne
5508 ** TK_GT OP_Le
5509 ** TK_LE OP_Gt
5510 ** TK_GE OP_Lt
5511 ** TK_LT OP_Ge
5513 ** For other values of pExpr->op, op is undefined and unused.
5514 ** The value of TK_ and OP_ constants are arranged such that we
5515 ** can compute the mapping above using the following expression.
5516 ** Assert()s verify that the computation is correct.
5518 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
5520 /* Verify correct alignment of TK_ and OP_ constants
5522 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
5523 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
5524 assert( pExpr->op!=TK_NE || op==OP_Eq );
5525 assert( pExpr->op!=TK_EQ || op==OP_Ne );
5526 assert( pExpr->op!=TK_LT || op==OP_Ge );
5527 assert( pExpr->op!=TK_LE || op==OP_Gt );
5528 assert( pExpr->op!=TK_GT || op==OP_Le );
5529 assert( pExpr->op!=TK_GE || op==OP_Lt );
5531 switch( pExpr->op ){
5532 case TK_AND:
5533 case TK_OR: {
5534 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5535 if( pAlt!=pExpr ){
5536 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
5537 }else if( pExpr->op==TK_AND ){
5538 testcase( jumpIfNull==0 );
5539 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5540 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5541 }else{
5542 int d2 = sqlite3VdbeMakeLabel(pParse);
5543 testcase( jumpIfNull==0 );
5544 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
5545 jumpIfNull^SQLITE_JUMPIFNULL);
5546 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5547 sqlite3VdbeResolveLabel(v, d2);
5549 break;
5551 case TK_NOT: {
5552 testcase( jumpIfNull==0 );
5553 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5554 break;
5556 case TK_TRUTH: {
5557 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5558 int isTrue; /* IS TRUE or IS NOT TRUE */
5559 testcase( jumpIfNull==0 );
5560 isNot = pExpr->op2==TK_ISNOT;
5561 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5562 testcase( isTrue && isNot );
5563 testcase( !isTrue && isNot );
5564 if( isTrue ^ isNot ){
5565 /* IS TRUE and IS NOT FALSE */
5566 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5567 isNot ? 0 : SQLITE_JUMPIFNULL);
5569 }else{
5570 /* IS FALSE and IS NOT TRUE */
5571 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5572 isNot ? 0 : SQLITE_JUMPIFNULL);
5574 break;
5576 case TK_IS:
5577 case TK_ISNOT:
5578 testcase( pExpr->op==TK_IS );
5579 testcase( pExpr->op==TK_ISNOT );
5580 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
5581 jumpIfNull = SQLITE_NULLEQ;
5582 /* no break */ deliberate_fall_through
5583 case TK_LT:
5584 case TK_LE:
5585 case TK_GT:
5586 case TK_GE:
5587 case TK_NE:
5588 case TK_EQ: {
5589 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5590 testcase( jumpIfNull==0 );
5591 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5592 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5593 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5594 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
5595 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5596 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5597 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5598 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5599 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5600 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5601 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5602 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5603 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5604 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5605 testcase( regFree1==0 );
5606 testcase( regFree2==0 );
5607 break;
5609 case TK_ISNULL:
5610 case TK_NOTNULL: {
5611 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5612 sqlite3VdbeTypeofColumn(v, r1);
5613 sqlite3VdbeAddOp2(v, op, r1, dest);
5614 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
5615 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
5616 testcase( regFree1==0 );
5617 break;
5619 case TK_BETWEEN: {
5620 testcase( jumpIfNull==0 );
5621 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
5622 break;
5624 #ifndef SQLITE_OMIT_SUBQUERY
5625 case TK_IN: {
5626 if( jumpIfNull ){
5627 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
5628 }else{
5629 int destIfNull = sqlite3VdbeMakeLabel(pParse);
5630 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
5631 sqlite3VdbeResolveLabel(v, destIfNull);
5633 break;
5635 #endif
5636 default: {
5637 default_expr:
5638 if( ExprAlwaysFalse(pExpr) ){
5639 sqlite3VdbeGoto(v, dest);
5640 }else if( ExprAlwaysTrue(pExpr) ){
5641 /* no-op */
5642 }else{
5643 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5644 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
5645 VdbeCoverage(v);
5646 testcase( regFree1==0 );
5647 testcase( jumpIfNull==0 );
5649 break;
5652 sqlite3ReleaseTempReg(pParse, regFree1);
5653 sqlite3ReleaseTempReg(pParse, regFree2);
5657 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5658 ** code generation, and that copy is deleted after code generation. This
5659 ** ensures that the original pExpr is unchanged.
5661 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
5662 sqlite3 *db = pParse->db;
5663 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
5664 if( db->mallocFailed==0 ){
5665 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
5667 sqlite3ExprDelete(db, pCopy);
5671 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5672 ** type of expression.
5674 ** If pExpr is a simple SQL value - an integer, real, string, blob
5675 ** or NULL value - then the VDBE currently being prepared is configured
5676 ** to re-prepare each time a new value is bound to variable pVar.
5678 ** Additionally, if pExpr is a simple SQL value and the value is the
5679 ** same as that currently bound to variable pVar, non-zero is returned.
5680 ** Otherwise, if the values are not the same or if pExpr is not a simple
5681 ** SQL value, zero is returned.
5683 static int exprCompareVariable(
5684 const Parse *pParse,
5685 const Expr *pVar,
5686 const Expr *pExpr
5688 int res = 0;
5689 int iVar;
5690 sqlite3_value *pL, *pR = 0;
5692 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
5693 if( pR ){
5694 iVar = pVar->iColumn;
5695 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
5696 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
5697 if( pL ){
5698 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
5699 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
5701 res = 0==sqlite3MemCompare(pL, pR, 0);
5703 sqlite3ValueFree(pR);
5704 sqlite3ValueFree(pL);
5707 return res;
5711 ** Do a deep comparison of two expression trees. Return 0 if the two
5712 ** expressions are completely identical. Return 1 if they differ only
5713 ** by a COLLATE operator at the top level. Return 2 if there are differences
5714 ** other than the top-level COLLATE operator.
5716 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5717 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5719 ** The pA side might be using TK_REGISTER. If that is the case and pB is
5720 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5722 ** Sometimes this routine will return 2 even if the two expressions
5723 ** really are equivalent. If we cannot prove that the expressions are
5724 ** identical, we return 2 just to be safe. So if this routine
5725 ** returns 2, then you do not really know for certain if the two
5726 ** expressions are the same. But if you get a 0 or 1 return, then you
5727 ** can be sure the expressions are the same. In the places where
5728 ** this routine is used, it does not hurt to get an extra 2 - that
5729 ** just might result in some slightly slower code. But returning
5730 ** an incorrect 0 or 1 could lead to a malfunction.
5732 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5733 ** pParse->pReprepare can be matched against literals in pB. The
5734 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5735 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5736 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5737 ** pB causes a return value of 2.
5739 int sqlite3ExprCompare(
5740 const Parse *pParse,
5741 const Expr *pA,
5742 const Expr *pB,
5743 int iTab
5745 u32 combinedFlags;
5746 if( pA==0 || pB==0 ){
5747 return pB==pA ? 0 : 2;
5749 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
5750 return 0;
5752 combinedFlags = pA->flags | pB->flags;
5753 if( combinedFlags & EP_IntValue ){
5754 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
5755 return 0;
5757 return 2;
5759 if( pA->op!=pB->op || pA->op==TK_RAISE ){
5760 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
5761 return 1;
5763 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
5764 return 1;
5766 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
5767 && pB->iTable<0 && pA->iTable==iTab
5769 /* fall through */
5770 }else{
5771 return 2;
5774 assert( !ExprHasProperty(pA, EP_IntValue) );
5775 assert( !ExprHasProperty(pB, EP_IntValue) );
5776 if( pA->u.zToken ){
5777 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
5778 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5779 #ifndef SQLITE_OMIT_WINDOWFUNC
5780 assert( pA->op==pB->op );
5781 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
5782 return 2;
5784 if( ExprHasProperty(pA,EP_WinFunc) ){
5785 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
5786 return 2;
5789 #endif
5790 }else if( pA->op==TK_NULL ){
5791 return 0;
5792 }else if( pA->op==TK_COLLATE ){
5793 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5794 }else
5795 if( pB->u.zToken!=0
5796 && pA->op!=TK_COLUMN
5797 && pA->op!=TK_AGG_COLUMN
5798 && strcmp(pA->u.zToken,pB->u.zToken)!=0
5800 return 2;
5803 if( (pA->flags & (EP_Distinct|EP_Commuted))
5804 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
5805 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
5806 if( combinedFlags & EP_xIsSelect ) return 2;
5807 if( (combinedFlags & EP_FixedCol)==0
5808 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
5809 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
5810 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
5811 if( pA->op!=TK_STRING
5812 && pA->op!=TK_TRUEFALSE
5813 && ALWAYS((combinedFlags & EP_Reduced)==0)
5815 if( pA->iColumn!=pB->iColumn ) return 2;
5816 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
5817 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
5818 return 2;
5822 return 0;
5826 ** Compare two ExprList objects. Return 0 if they are identical, 1
5827 ** if they are certainly different, or 2 if it is not possible to
5828 ** determine if they are identical or not.
5830 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5831 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5833 ** This routine might return non-zero for equivalent ExprLists. The
5834 ** only consequence will be disabled optimizations. But this routine
5835 ** must never return 0 if the two ExprList objects are different, or
5836 ** a malfunction will result.
5838 ** Two NULL pointers are considered to be the same. But a NULL pointer
5839 ** always differs from a non-NULL pointer.
5841 int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){
5842 int i;
5843 if( pA==0 && pB==0 ) return 0;
5844 if( pA==0 || pB==0 ) return 1;
5845 if( pA->nExpr!=pB->nExpr ) return 1;
5846 for(i=0; i<pA->nExpr; i++){
5847 int res;
5848 Expr *pExprA = pA->a[i].pExpr;
5849 Expr *pExprB = pB->a[i].pExpr;
5850 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
5851 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
5853 return 0;
5857 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
5858 ** are ignored.
5860 int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
5861 return sqlite3ExprCompare(0,
5862 sqlite3ExprSkipCollateAndLikely(pA),
5863 sqlite3ExprSkipCollateAndLikely(pB),
5864 iTab);
5868 ** Return non-zero if Expr p can only be true if pNN is not NULL.
5870 ** Or if seenNot is true, return non-zero if Expr p can only be
5871 ** non-NULL if pNN is not NULL
5873 static int exprImpliesNotNull(
5874 const Parse *pParse,/* Parsing context */
5875 const Expr *p, /* The expression to be checked */
5876 const Expr *pNN, /* The expression that is NOT NULL */
5877 int iTab, /* Table being evaluated */
5878 int seenNot /* Return true only if p can be any non-NULL value */
5880 assert( p );
5881 assert( pNN );
5882 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
5883 return pNN->op!=TK_NULL;
5885 switch( p->op ){
5886 case TK_IN: {
5887 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
5888 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
5889 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5891 case TK_BETWEEN: {
5892 ExprList *pList;
5893 assert( ExprUseXList(p) );
5894 pList = p->x.pList;
5895 assert( pList!=0 );
5896 assert( pList->nExpr==2 );
5897 if( seenNot ) return 0;
5898 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
5899 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
5901 return 1;
5903 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5905 case TK_EQ:
5906 case TK_NE:
5907 case TK_LT:
5908 case TK_LE:
5909 case TK_GT:
5910 case TK_GE:
5911 case TK_PLUS:
5912 case TK_MINUS:
5913 case TK_BITOR:
5914 case TK_LSHIFT:
5915 case TK_RSHIFT:
5916 case TK_CONCAT:
5917 seenNot = 1;
5918 /* no break */ deliberate_fall_through
5919 case TK_STAR:
5920 case TK_REM:
5921 case TK_BITAND:
5922 case TK_SLASH: {
5923 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
5924 /* no break */ deliberate_fall_through
5926 case TK_SPAN:
5927 case TK_COLLATE:
5928 case TK_UPLUS:
5929 case TK_UMINUS: {
5930 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
5932 case TK_TRUTH: {
5933 if( seenNot ) return 0;
5934 if( p->op2!=TK_IS ) return 0;
5935 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5937 case TK_BITNOT:
5938 case TK_NOT: {
5939 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5942 return 0;
5946 ** Return true if we can prove the pE2 will always be true if pE1 is
5947 ** true. Return false if we cannot complete the proof or if pE2 might
5948 ** be false. Examples:
5950 ** pE1: x==5 pE2: x==5 Result: true
5951 ** pE1: x>0 pE2: x==5 Result: false
5952 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
5953 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
5954 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
5955 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
5956 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
5958 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
5959 ** Expr.iTable<0 then assume a table number given by iTab.
5961 ** If pParse is not NULL, then the values of bound variables in pE1 are
5962 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
5963 ** modified to record which bound variables are referenced. If pParse
5964 ** is NULL, then false will be returned if pE1 contains any bound variables.
5966 ** When in doubt, return false. Returning true might give a performance
5967 ** improvement. Returning false might cause a performance reduction, but
5968 ** it will always give the correct answer and is hence always safe.
5970 int sqlite3ExprImpliesExpr(
5971 const Parse *pParse,
5972 const Expr *pE1,
5973 const Expr *pE2,
5974 int iTab
5976 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
5977 return 1;
5979 if( pE2->op==TK_OR
5980 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
5981 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
5983 return 1;
5985 if( pE2->op==TK_NOTNULL
5986 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
5988 return 1;
5990 return 0;
5994 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
5995 ** If the expression node requires that the table at pWalker->iCur
5996 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
5998 ** This routine controls an optimization. False positives (setting
5999 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6000 ** (never setting pWalker->eCode) is a harmless missed optimization.
6002 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
6003 testcase( pExpr->op==TK_AGG_COLUMN );
6004 testcase( pExpr->op==TK_AGG_FUNCTION );
6005 if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune;
6006 switch( pExpr->op ){
6007 case TK_ISNOT:
6008 case TK_ISNULL:
6009 case TK_NOTNULL:
6010 case TK_IS:
6011 case TK_OR:
6012 case TK_VECTOR:
6013 case TK_CASE:
6014 case TK_IN:
6015 case TK_FUNCTION:
6016 case TK_TRUTH:
6017 testcase( pExpr->op==TK_ISNOT );
6018 testcase( pExpr->op==TK_ISNULL );
6019 testcase( pExpr->op==TK_NOTNULL );
6020 testcase( pExpr->op==TK_IS );
6021 testcase( pExpr->op==TK_OR );
6022 testcase( pExpr->op==TK_VECTOR );
6023 testcase( pExpr->op==TK_CASE );
6024 testcase( pExpr->op==TK_IN );
6025 testcase( pExpr->op==TK_FUNCTION );
6026 testcase( pExpr->op==TK_TRUTH );
6027 return WRC_Prune;
6028 case TK_COLUMN:
6029 if( pWalker->u.iCur==pExpr->iTable ){
6030 pWalker->eCode = 1;
6031 return WRC_Abort;
6033 return WRC_Prune;
6035 case TK_AND:
6036 if( pWalker->eCode==0 ){
6037 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6038 if( pWalker->eCode ){
6039 pWalker->eCode = 0;
6040 sqlite3WalkExpr(pWalker, pExpr->pRight);
6043 return WRC_Prune;
6045 case TK_BETWEEN:
6046 if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
6047 assert( pWalker->eCode );
6048 return WRC_Abort;
6050 return WRC_Prune;
6052 /* Virtual tables are allowed to use constraints like x=NULL. So
6053 ** a term of the form x=y does not prove that y is not null if x
6054 ** is the column of a virtual table */
6055 case TK_EQ:
6056 case TK_NE:
6057 case TK_LT:
6058 case TK_LE:
6059 case TK_GT:
6060 case TK_GE: {
6061 Expr *pLeft = pExpr->pLeft;
6062 Expr *pRight = pExpr->pRight;
6063 testcase( pExpr->op==TK_EQ );
6064 testcase( pExpr->op==TK_NE );
6065 testcase( pExpr->op==TK_LT );
6066 testcase( pExpr->op==TK_LE );
6067 testcase( pExpr->op==TK_GT );
6068 testcase( pExpr->op==TK_GE );
6069 /* The y.pTab=0 assignment in wherecode.c always happens after the
6070 ** impliesNotNullRow() test */
6071 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
6072 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
6073 if( (pLeft->op==TK_COLUMN
6074 && ALWAYS(pLeft->y.pTab!=0)
6075 && IsVirtual(pLeft->y.pTab))
6076 || (pRight->op==TK_COLUMN
6077 && ALWAYS(pRight->y.pTab!=0)
6078 && IsVirtual(pRight->y.pTab))
6080 return WRC_Prune;
6082 /* no break */ deliberate_fall_through
6084 default:
6085 return WRC_Continue;
6090 ** Return true (non-zero) if expression p can only be true if at least
6091 ** one column of table iTab is non-null. In other words, return true
6092 ** if expression p will always be NULL or false if every column of iTab
6093 ** is NULL.
6095 ** False negatives are acceptable. In other words, it is ok to return
6096 ** zero even if expression p will never be true of every column of iTab
6097 ** is NULL. A false negative is merely a missed optimization opportunity.
6099 ** False positives are not allowed, however. A false positive may result
6100 ** in an incorrect answer.
6102 ** Terms of p that are marked with EP_OuterON (and hence that come from
6103 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6105 ** This routine is used to check if a LEFT JOIN can be converted into
6106 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6107 ** clause requires that some column of the right table of the LEFT JOIN
6108 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6109 ** ordinary join.
6111 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
6112 Walker w;
6113 p = sqlite3ExprSkipCollateAndLikely(p);
6114 if( p==0 ) return 0;
6115 if( p->op==TK_NOTNULL ){
6116 p = p->pLeft;
6117 }else{
6118 while( p->op==TK_AND ){
6119 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
6120 p = p->pRight;
6123 w.xExprCallback = impliesNotNullRow;
6124 w.xSelectCallback = 0;
6125 w.xSelectCallback2 = 0;
6126 w.eCode = 0;
6127 w.u.iCur = iTab;
6128 sqlite3WalkExpr(&w, p);
6129 return w.eCode;
6133 ** An instance of the following structure is used by the tree walker
6134 ** to determine if an expression can be evaluated by reference to the
6135 ** index only, without having to do a search for the corresponding
6136 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6137 ** is the cursor for the table.
6139 struct IdxCover {
6140 Index *pIdx; /* The index to be tested for coverage */
6141 int iCur; /* Cursor number for the table corresponding to the index */
6145 ** Check to see if there are references to columns in table
6146 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6147 ** pWalker->u.pIdxCover->pIdx.
6149 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
6150 if( pExpr->op==TK_COLUMN
6151 && pExpr->iTable==pWalker->u.pIdxCover->iCur
6152 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
6154 pWalker->eCode = 1;
6155 return WRC_Abort;
6157 return WRC_Continue;
6161 ** Determine if an index pIdx on table with cursor iCur contains will
6162 ** the expression pExpr. Return true if the index does cover the
6163 ** expression and false if the pExpr expression references table columns
6164 ** that are not found in the index pIdx.
6166 ** An index covering an expression means that the expression can be
6167 ** evaluated using only the index and without having to lookup the
6168 ** corresponding table entry.
6170 int sqlite3ExprCoveredByIndex(
6171 Expr *pExpr, /* The index to be tested */
6172 int iCur, /* The cursor number for the corresponding table */
6173 Index *pIdx /* The index that might be used for coverage */
6175 Walker w;
6176 struct IdxCover xcov;
6177 memset(&w, 0, sizeof(w));
6178 xcov.iCur = iCur;
6179 xcov.pIdx = pIdx;
6180 w.xExprCallback = exprIdxCover;
6181 w.u.pIdxCover = &xcov;
6182 sqlite3WalkExpr(&w, pExpr);
6183 return !w.eCode;
6187 /* Structure used to pass information throught the Walker in order to
6188 ** implement sqlite3ReferencesSrcList().
6190 struct RefSrcList {
6191 sqlite3 *db; /* Database connection used for sqlite3DbRealloc() */
6192 SrcList *pRef; /* Looking for references to these tables */
6193 i64 nExclude; /* Number of tables to exclude from the search */
6194 int *aiExclude; /* Cursor IDs for tables to exclude from the search */
6198 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6200 ** When entering a new subquery on the pExpr argument, add all FROM clause
6201 ** entries for that subquery to the exclude list.
6203 ** When leaving the subquery, remove those entries from the exclude list.
6205 static int selectRefEnter(Walker *pWalker, Select *pSelect){
6206 struct RefSrcList *p = pWalker->u.pRefSrcList;
6207 SrcList *pSrc = pSelect->pSrc;
6208 i64 i, j;
6209 int *piNew;
6210 if( pSrc->nSrc==0 ) return WRC_Continue;
6211 j = p->nExclude;
6212 p->nExclude += pSrc->nSrc;
6213 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
6214 if( piNew==0 ){
6215 p->nExclude = 0;
6216 return WRC_Abort;
6217 }else{
6218 p->aiExclude = piNew;
6220 for(i=0; i<pSrc->nSrc; i++, j++){
6221 p->aiExclude[j] = pSrc->a[i].iCursor;
6223 return WRC_Continue;
6225 static void selectRefLeave(Walker *pWalker, Select *pSelect){
6226 struct RefSrcList *p = pWalker->u.pRefSrcList;
6227 SrcList *pSrc = pSelect->pSrc;
6228 if( p->nExclude ){
6229 assert( p->nExclude>=pSrc->nSrc );
6230 p->nExclude -= pSrc->nSrc;
6234 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6236 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6237 ** of the tables shown in RefSrcList.pRef.
6239 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6240 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6242 static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){
6243 if( pExpr->op==TK_COLUMN
6244 || pExpr->op==TK_AGG_COLUMN
6246 int i;
6247 struct RefSrcList *p = pWalker->u.pRefSrcList;
6248 SrcList *pSrc = p->pRef;
6249 int nSrc = pSrc ? pSrc->nSrc : 0;
6250 for(i=0; i<nSrc; i++){
6251 if( pExpr->iTable==pSrc->a[i].iCursor ){
6252 pWalker->eCode |= 1;
6253 return WRC_Continue;
6256 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
6257 if( i>=p->nExclude ){
6258 pWalker->eCode |= 2;
6261 return WRC_Continue;
6265 ** Check to see if pExpr references any tables in pSrcList.
6266 ** Possible return values:
6268 ** 1 pExpr does references a table in pSrcList.
6270 ** 0 pExpr references some table that is not defined in either
6271 ** pSrcList or in subqueries of pExpr itself.
6273 ** -1 pExpr only references no tables at all, or it only
6274 ** references tables defined in subqueries of pExpr itself.
6276 ** As currently used, pExpr is always an aggregate function call. That
6277 ** fact is exploited for efficiency.
6279 int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){
6280 Walker w;
6281 struct RefSrcList x;
6282 assert( pParse->db!=0 );
6283 memset(&w, 0, sizeof(w));
6284 memset(&x, 0, sizeof(x));
6285 w.xExprCallback = exprRefToSrcList;
6286 w.xSelectCallback = selectRefEnter;
6287 w.xSelectCallback2 = selectRefLeave;
6288 w.u.pRefSrcList = &x;
6289 x.db = pParse->db;
6290 x.pRef = pSrcList;
6291 assert( pExpr->op==TK_AGG_FUNCTION );
6292 assert( ExprUseXList(pExpr) );
6293 sqlite3WalkExprList(&w, pExpr->x.pList);
6294 #ifndef SQLITE_OMIT_WINDOWFUNC
6295 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6296 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
6298 #endif
6299 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
6300 if( w.eCode & 0x01 ){
6301 return 1;
6302 }else if( w.eCode ){
6303 return 0;
6304 }else{
6305 return -1;
6310 ** This is a Walker expression node callback.
6312 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6313 ** object that is referenced does not refer directly to the Expr. If
6314 ** it does, make a copy. This is done because the pExpr argument is
6315 ** subject to change.
6317 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6318 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6320 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
6321 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
6322 && pExpr->pAggInfo!=0
6324 AggInfo *pAggInfo = pExpr->pAggInfo;
6325 int iAgg = pExpr->iAgg;
6326 Parse *pParse = pWalker->pParse;
6327 sqlite3 *db = pParse->db;
6328 assert( iAgg>=0 );
6329 if( pExpr->op!=TK_AGG_FUNCTION ){
6330 if( iAgg<pAggInfo->nColumn
6331 && pAggInfo->aCol[iAgg].pCExpr==pExpr
6333 pExpr = sqlite3ExprDup(db, pExpr, 0);
6334 if( pExpr ){
6335 pAggInfo->aCol[iAgg].pCExpr = pExpr;
6336 sqlite3ExprDeferredDelete(pParse, pExpr);
6339 }else{
6340 assert( pExpr->op==TK_AGG_FUNCTION );
6341 if( ALWAYS(iAgg<pAggInfo->nFunc)
6342 && pAggInfo->aFunc[iAgg].pFExpr==pExpr
6344 pExpr = sqlite3ExprDup(db, pExpr, 0);
6345 if( pExpr ){
6346 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
6347 sqlite3ExprDeferredDelete(pParse, pExpr);
6352 return WRC_Continue;
6356 ** Initialize a Walker object so that will persist AggInfo entries referenced
6357 ** by the tree that is walked.
6359 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
6360 memset(pWalker, 0, sizeof(*pWalker));
6361 pWalker->pParse = pParse;
6362 pWalker->xExprCallback = agginfoPersistExprCb;
6363 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
6367 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6368 ** the new element. Return a negative number if malloc fails.
6370 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
6371 int i;
6372 pInfo->aCol = sqlite3ArrayAllocate(
6374 pInfo->aCol,
6375 sizeof(pInfo->aCol[0]),
6376 &pInfo->nColumn,
6379 return i;
6383 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6384 ** the new element. Return a negative number if malloc fails.
6386 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
6387 int i;
6388 pInfo->aFunc = sqlite3ArrayAllocate(
6389 db,
6390 pInfo->aFunc,
6391 sizeof(pInfo->aFunc[0]),
6392 &pInfo->nFunc,
6395 return i;
6399 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6400 ** Return the index in aCol[] of the entry that describes that column.
6402 ** If no prior entry is found, create a new one and return -1. The
6403 ** new column will have an idex of pAggInfo->nColumn-1.
6405 static void findOrCreateAggInfoColumn(
6406 Parse *pParse, /* Parsing context */
6407 AggInfo *pAggInfo, /* The AggInfo object to search and/or modify */
6408 Expr *pExpr /* Expr describing the column to find or insert */
6410 struct AggInfo_col *pCol;
6411 int k;
6413 assert( pAggInfo->iFirstReg==0 );
6414 pCol = pAggInfo->aCol;
6415 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
6416 if( pCol->iTable==pExpr->iTable
6417 && pCol->iColumn==pExpr->iColumn
6418 && pExpr->op!=TK_IF_NULL_ROW
6420 goto fix_up_expr;
6423 k = addAggInfoColumn(pParse->db, pAggInfo);
6424 if( k<0 ){
6425 /* OOM on resize */
6426 assert( pParse->db->mallocFailed );
6427 return;
6429 pCol = &pAggInfo->aCol[k];
6430 assert( ExprUseYTab(pExpr) );
6431 pCol->pTab = pExpr->y.pTab;
6432 pCol->iTable = pExpr->iTable;
6433 pCol->iColumn = pExpr->iColumn;
6434 pCol->iSorterColumn = -1;
6435 pCol->pCExpr = pExpr;
6436 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
6437 int j, n;
6438 ExprList *pGB = pAggInfo->pGroupBy;
6439 struct ExprList_item *pTerm = pGB->a;
6440 n = pGB->nExpr;
6441 for(j=0; j<n; j++, pTerm++){
6442 Expr *pE = pTerm->pExpr;
6443 if( pE->op==TK_COLUMN
6444 && pE->iTable==pExpr->iTable
6445 && pE->iColumn==pExpr->iColumn
6447 pCol->iSorterColumn = j;
6448 break;
6452 if( pCol->iSorterColumn<0 ){
6453 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
6455 fix_up_expr:
6456 ExprSetVVAProperty(pExpr, EP_NoReduce);
6457 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo );
6458 pExpr->pAggInfo = pAggInfo;
6459 if( pExpr->op==TK_COLUMN ){
6460 pExpr->op = TK_AGG_COLUMN;
6462 pExpr->iAgg = (i16)k;
6466 ** This is the xExprCallback for a tree walker. It is used to
6467 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6468 ** for additional information.
6470 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
6471 int i;
6472 NameContext *pNC = pWalker->u.pNC;
6473 Parse *pParse = pNC->pParse;
6474 SrcList *pSrcList = pNC->pSrcList;
6475 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
6477 assert( pNC->ncFlags & NC_UAggInfo );
6478 assert( pAggInfo->iFirstReg==0 );
6479 switch( pExpr->op ){
6480 default: {
6481 IndexedExpr *pIEpr;
6482 Expr tmp;
6483 assert( pParse->iSelfTab==0 );
6484 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
6485 if( pParse->pIdxEpr==0 ) break;
6486 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6487 int iDataCur = pIEpr->iDataCur;
6488 if( iDataCur<0 ) continue;
6489 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
6491 if( pIEpr==0 ) break;
6492 if( NEVER(!ExprUseYTab(pExpr)) ) break;
6493 for(i=0; i<pSrcList->nSrc; i++){
6494 if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
6496 if( i>=pSrcList->nSrc ) break;
6497 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
6498 if( pParse->nErr ){ return WRC_Abort; }
6500 /* If we reach this point, it means that expression pExpr can be
6501 ** translated into a reference to an index column as described by
6502 ** pIEpr.
6504 memset(&tmp, 0, sizeof(tmp));
6505 tmp.op = TK_AGG_COLUMN;
6506 tmp.iTable = pIEpr->iIdxCur;
6507 tmp.iColumn = pIEpr->iIdxCol;
6508 findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);
6509 if( pParse->nErr ){ return WRC_Abort; }
6510 assert( pAggInfo->aCol!=0 );
6511 assert( tmp.iAgg<pAggInfo->nColumn );
6512 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
6513 pExpr->pAggInfo = pAggInfo;
6514 pExpr->iAgg = tmp.iAgg;
6515 return WRC_Prune;
6517 case TK_IF_NULL_ROW:
6518 case TK_AGG_COLUMN:
6519 case TK_COLUMN: {
6520 testcase( pExpr->op==TK_AGG_COLUMN );
6521 testcase( pExpr->op==TK_COLUMN );
6522 testcase( pExpr->op==TK_IF_NULL_ROW );
6523 /* Check to see if the column is in one of the tables in the FROM
6524 ** clause of the aggregate query */
6525 if( ALWAYS(pSrcList!=0) ){
6526 SrcItem *pItem = pSrcList->a;
6527 for(i=0; i<pSrcList->nSrc; i++, pItem++){
6528 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6529 if( pExpr->iTable==pItem->iCursor ){
6530 findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
6531 break;
6532 } /* endif pExpr->iTable==pItem->iCursor */
6533 } /* end loop over pSrcList */
6535 return WRC_Continue;
6537 case TK_AGG_FUNCTION: {
6538 if( (pNC->ncFlags & NC_InAggFunc)==0
6539 && pWalker->walkerDepth==pExpr->op2
6541 /* Check to see if pExpr is a duplicate of another aggregate
6542 ** function that is already in the pAggInfo structure
6544 struct AggInfo_func *pItem = pAggInfo->aFunc;
6545 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
6546 if( pItem->pFExpr==pExpr ) break;
6547 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
6548 break;
6551 if( i>=pAggInfo->nFunc ){
6552 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6554 u8 enc = ENC(pParse->db);
6555 i = addAggInfoFunc(pParse->db, pAggInfo);
6556 if( i>=0 ){
6557 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
6558 pItem = &pAggInfo->aFunc[i];
6559 pItem->pFExpr = pExpr;
6560 assert( ExprUseUToken(pExpr) );
6561 pItem->pFunc = sqlite3FindFunction(pParse->db,
6562 pExpr->u.zToken,
6563 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
6564 if( pExpr->flags & EP_Distinct ){
6565 pItem->iDistinct = pParse->nTab++;
6566 }else{
6567 pItem->iDistinct = -1;
6571 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6573 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6574 ExprSetVVAProperty(pExpr, EP_NoReduce);
6575 pExpr->iAgg = (i16)i;
6576 pExpr->pAggInfo = pAggInfo;
6577 return WRC_Prune;
6578 }else{
6579 return WRC_Continue;
6583 return WRC_Continue;
6587 ** Analyze the pExpr expression looking for aggregate functions and
6588 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6589 ** points to. Additional entries are made on the AggInfo object as
6590 ** necessary.
6592 ** This routine should only be called after the expression has been
6593 ** analyzed by sqlite3ResolveExprNames().
6595 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
6596 Walker w;
6597 w.xExprCallback = analyzeAggregate;
6598 w.xSelectCallback = sqlite3WalkerDepthIncrease;
6599 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
6600 w.walkerDepth = 0;
6601 w.u.pNC = pNC;
6602 w.pParse = 0;
6603 assert( pNC->pSrcList!=0 );
6604 sqlite3WalkExpr(&w, pExpr);
6608 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6609 ** expression list. Return the number of errors.
6611 ** If an error is found, the analysis is cut short.
6613 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
6614 struct ExprList_item *pItem;
6615 int i;
6616 if( pList ){
6617 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
6618 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
6624 ** Allocate a single new register for use to hold some intermediate result.
6626 int sqlite3GetTempReg(Parse *pParse){
6627 if( pParse->nTempReg==0 ){
6628 return ++pParse->nMem;
6630 return pParse->aTempReg[--pParse->nTempReg];
6634 ** Deallocate a register, making available for reuse for some other
6635 ** purpose.
6637 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
6638 if( iReg ){
6639 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
6640 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
6641 pParse->aTempReg[pParse->nTempReg++] = iReg;
6647 ** Allocate or deallocate a block of nReg consecutive registers.
6649 int sqlite3GetTempRange(Parse *pParse, int nReg){
6650 int i, n;
6651 if( nReg==1 ) return sqlite3GetTempReg(pParse);
6652 i = pParse->iRangeReg;
6653 n = pParse->nRangeReg;
6654 if( nReg<=n ){
6655 pParse->iRangeReg += nReg;
6656 pParse->nRangeReg -= nReg;
6657 }else{
6658 i = pParse->nMem+1;
6659 pParse->nMem += nReg;
6661 return i;
6663 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
6664 if( nReg==1 ){
6665 sqlite3ReleaseTempReg(pParse, iReg);
6666 return;
6668 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
6669 if( nReg>pParse->nRangeReg ){
6670 pParse->nRangeReg = nReg;
6671 pParse->iRangeReg = iReg;
6676 ** Mark all temporary registers as being unavailable for reuse.
6678 ** Always invoke this procedure after coding a subroutine or co-routine
6679 ** that might be invoked from other parts of the code, to ensure that
6680 ** the sub/co-routine does not use registers in common with the code that
6681 ** invokes the sub/co-routine.
6683 void sqlite3ClearTempRegCache(Parse *pParse){
6684 pParse->nTempReg = 0;
6685 pParse->nRangeReg = 0;
6689 ** Make sure sufficient registers have been allocated so that
6690 ** iReg is a valid register number.
6692 void sqlite3TouchRegister(Parse *pParse, int iReg){
6693 if( pParse->nMem<iReg ) pParse->nMem = iReg;
6696 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
6698 ** Return the latest reusable register in the set of all registers.
6699 ** The value returned is no less than iMin. If any register iMin or
6700 ** greater is in permanent use, then return one more than that last
6701 ** permanent register.
6703 int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){
6704 const ExprList *pList = pParse->pConstExpr;
6705 if( pList ){
6706 int i;
6707 for(i=0; i<pList->nExpr; i++){
6708 if( pList->a[i].u.iConstExprReg>=iMin ){
6709 iMin = pList->a[i].u.iConstExprReg + 1;
6713 pParse->nTempReg = 0;
6714 pParse->nRangeReg = 0;
6715 return iMin;
6717 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
6720 ** Validate that no temporary register falls within the range of
6721 ** iFirst..iLast, inclusive. This routine is only call from within assert()
6722 ** statements.
6724 #ifdef SQLITE_DEBUG
6725 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
6726 int i;
6727 if( pParse->nRangeReg>0
6728 && pParse->iRangeReg+pParse->nRangeReg > iFirst
6729 && pParse->iRangeReg <= iLast
6731 return 0;
6733 for(i=0; i<pParse->nTempReg; i++){
6734 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
6735 return 0;
6738 if( pParse->pConstExpr ){
6739 ExprList *pList = pParse->pConstExpr;
6740 for(i=0; i<pList->nExpr; i++){
6741 int iReg = pList->a[i].u.iConstExprReg;
6742 if( iReg==0 ) continue;
6743 if( iReg>=iFirst && iReg<=iLast ) return 0;
6746 return 1;
6748 #endif /* SQLITE_DEBUG */