Minor JNI cleanups.
[sqlite.git] / src / expr.c
blobd96f362856b19d4380f3b87a5dc96ae333147531
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->iColumn >= 0 );
71 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
72 return sqlite3ExprAffinity(
73 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
76 if( op==TK_VECTOR ){
77 assert( ExprUseXList(pExpr) );
78 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
80 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
81 assert( pExpr->op==TK_COLLATE
82 || pExpr->op==TK_IF_NULL_ROW
83 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
84 pExpr = pExpr->pLeft;
85 op = pExpr->op;
86 continue;
88 if( op!=TK_REGISTER || (op = pExpr->op2)==TK_REGISTER ) break;
90 return pExpr->affExpr;
94 ** Make a guess at all the possible datatypes of the result that could
95 ** be returned by an expression. Return a bitmask indicating the answer:
97 ** 0x01 Numeric
98 ** 0x02 Text
99 ** 0x04 Blob
101 ** If the expression must return NULL, then 0x00 is returned.
103 int sqlite3ExprDataType(const Expr *pExpr){
104 while( pExpr ){
105 switch( pExpr->op ){
106 case TK_COLLATE:
107 case TK_IF_NULL_ROW:
108 case TK_UPLUS: {
109 pExpr = pExpr->pLeft;
110 break;
112 case TK_NULL: {
113 pExpr = 0;
114 break;
116 case TK_STRING: {
117 return 0x02;
119 case TK_BLOB: {
120 return 0x04;
122 case TK_CONCAT: {
123 return 0x06;
125 case TK_VARIABLE:
126 case TK_AGG_FUNCTION:
127 case TK_FUNCTION: {
128 return 0x07;
130 case TK_COLUMN:
131 case TK_AGG_COLUMN:
132 case TK_SELECT:
133 case TK_CAST:
134 case TK_SELECT_COLUMN:
135 case TK_VECTOR: {
136 int aff = sqlite3ExprAffinity(pExpr);
137 if( aff>=SQLITE_AFF_NUMERIC ) return 0x05;
138 if( aff==SQLITE_AFF_TEXT ) return 0x06;
139 return 0x07;
141 case TK_CASE: {
142 int res = 0;
143 int ii;
144 ExprList *pList = pExpr->x.pList;
145 assert( ExprUseXList(pExpr) && pList!=0 );
146 assert( pList->nExpr > 0);
147 for(ii=1; ii<pList->nExpr; ii+=2){
148 res |= sqlite3ExprDataType(pList->a[ii].pExpr);
150 if( pList->nExpr % 2 ){
151 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);
153 return res;
155 default: {
156 return 0x01;
158 } /* End of switch(op) */
159 } /* End of while(pExpr) */
160 return 0x00;
164 ** Set the collating sequence for expression pExpr to be the collating
165 ** sequence named by pToken. Return a pointer to a new Expr node that
166 ** implements the COLLATE operator.
168 ** If a memory allocation error occurs, that fact is recorded in pParse->db
169 ** and the pExpr parameter is returned unchanged.
171 Expr *sqlite3ExprAddCollateToken(
172 const Parse *pParse, /* Parsing context */
173 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
174 const Token *pCollName, /* Name of collating sequence */
175 int dequote /* True to dequote pCollName */
177 if( pCollName->n>0 ){
178 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
179 if( pNew ){
180 pNew->pLeft = pExpr;
181 pNew->flags |= EP_Collate|EP_Skip;
182 pExpr = pNew;
185 return pExpr;
187 Expr *sqlite3ExprAddCollateString(
188 const Parse *pParse, /* Parsing context */
189 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
190 const char *zC /* The collating sequence name */
192 Token s;
193 assert( zC!=0 );
194 sqlite3TokenInit(&s, (char*)zC);
195 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
199 ** Skip over any TK_COLLATE operators.
201 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
202 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
203 assert( pExpr->op==TK_COLLATE );
204 pExpr = pExpr->pLeft;
206 return pExpr;
210 ** Skip over any TK_COLLATE operators and/or any unlikely()
211 ** or likelihood() or likely() functions at the root of an
212 ** expression.
214 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
215 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
216 if( ExprHasProperty(pExpr, EP_Unlikely) ){
217 assert( ExprUseXList(pExpr) );
218 assert( pExpr->x.pList->nExpr>0 );
219 assert( pExpr->op==TK_FUNCTION );
220 pExpr = pExpr->x.pList->a[0].pExpr;
221 }else{
222 assert( pExpr->op==TK_COLLATE );
223 pExpr = pExpr->pLeft;
226 return pExpr;
230 ** Return the collation sequence for the expression pExpr. If
231 ** there is no defined collating sequence, return NULL.
233 ** See also: sqlite3ExprNNCollSeq()
235 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
236 ** default collation if pExpr has no defined collation.
238 ** The collating sequence might be determined by a COLLATE operator
239 ** or by the presence of a column with a defined collating sequence.
240 ** COLLATE operators take first precedence. Left operands take
241 ** precedence over right operands.
243 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
244 sqlite3 *db = pParse->db;
245 CollSeq *pColl = 0;
246 const Expr *p = pExpr;
247 while( p ){
248 int op = p->op;
249 if( op==TK_REGISTER ) op = p->op2;
250 if( (op==TK_AGG_COLUMN && p->y.pTab!=0)
251 || op==TK_COLUMN || op==TK_TRIGGER
253 int j;
254 assert( ExprUseYTab(p) );
255 assert( p->y.pTab!=0 );
256 if( (j = p->iColumn)>=0 ){
257 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
258 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
260 break;
262 if( op==TK_CAST || op==TK_UPLUS ){
263 p = p->pLeft;
264 continue;
266 if( op==TK_VECTOR ){
267 assert( ExprUseXList(p) );
268 p = p->x.pList->a[0].pExpr;
269 continue;
271 if( op==TK_COLLATE ){
272 assert( !ExprHasProperty(p, EP_IntValue) );
273 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
274 break;
276 if( p->flags & EP_Collate ){
277 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
278 p = p->pLeft;
279 }else{
280 Expr *pNext = p->pRight;
281 /* The Expr.x union is never used at the same time as Expr.pRight */
282 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
283 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
284 int i;
285 for(i=0; i<p->x.pList->nExpr; i++){
286 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
287 pNext = p->x.pList->a[i].pExpr;
288 break;
292 p = pNext;
294 }else{
295 break;
298 if( sqlite3CheckCollSeq(pParse, pColl) ){
299 pColl = 0;
301 return pColl;
305 ** Return the collation sequence for the expression pExpr. If
306 ** there is no defined collating sequence, return a pointer to the
307 ** default collation sequence.
309 ** See also: sqlite3ExprCollSeq()
311 ** The sqlite3ExprCollSeq() routine works the same except that it
312 ** returns NULL if there is no defined collation.
314 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
315 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
316 if( p==0 ) p = pParse->db->pDfltColl;
317 assert( p!=0 );
318 return p;
322 ** Return TRUE if the two expressions have equivalent collating sequences.
324 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
325 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
326 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
327 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
331 ** pExpr is an operand of a comparison operator. aff2 is the
332 ** type affinity of the other operand. This routine returns the
333 ** type affinity that should be used for the comparison operator.
335 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
336 char aff1 = sqlite3ExprAffinity(pExpr);
337 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
338 /* Both sides of the comparison are columns. If one has numeric
339 ** affinity, use that. Otherwise use no affinity.
341 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
342 return SQLITE_AFF_NUMERIC;
343 }else{
344 return SQLITE_AFF_BLOB;
346 }else{
347 /* One side is a column, the other is not. Use the columns affinity. */
348 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
349 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
354 ** pExpr is a comparison operator. Return the type affinity that should
355 ** be applied to both operands prior to doing the comparison.
357 static char comparisonAffinity(const Expr *pExpr){
358 char aff;
359 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
360 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
361 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
362 assert( pExpr->pLeft );
363 aff = sqlite3ExprAffinity(pExpr->pLeft);
364 if( pExpr->pRight ){
365 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
366 }else if( ExprUseXSelect(pExpr) ){
367 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
368 }else if( aff==0 ){
369 aff = SQLITE_AFF_BLOB;
371 return aff;
375 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
376 ** idx_affinity is the affinity of an indexed column. Return true
377 ** if the index with affinity idx_affinity may be used to implement
378 ** the comparison in pExpr.
380 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
381 char aff = comparisonAffinity(pExpr);
382 if( aff<SQLITE_AFF_TEXT ){
383 return 1;
385 if( aff==SQLITE_AFF_TEXT ){
386 return idx_affinity==SQLITE_AFF_TEXT;
388 return sqlite3IsNumericAffinity(idx_affinity);
392 ** Return the P5 value that should be used for a binary comparison
393 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
395 static u8 binaryCompareP5(
396 const Expr *pExpr1, /* Left operand */
397 const Expr *pExpr2, /* Right operand */
398 int jumpIfNull /* Extra flags added to P5 */
400 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
401 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
402 return aff;
406 ** Return a pointer to the collation sequence that should be used by
407 ** a binary comparison operator comparing pLeft and pRight.
409 ** If the left hand expression has a collating sequence type, then it is
410 ** used. Otherwise the collation sequence for the right hand expression
411 ** is used, or the default (BINARY) if neither expression has a collating
412 ** type.
414 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
415 ** it is not considered.
417 CollSeq *sqlite3BinaryCompareCollSeq(
418 Parse *pParse,
419 const Expr *pLeft,
420 const Expr *pRight
422 CollSeq *pColl;
423 assert( pLeft );
424 if( pLeft->flags & EP_Collate ){
425 pColl = sqlite3ExprCollSeq(pParse, pLeft);
426 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
427 pColl = sqlite3ExprCollSeq(pParse, pRight);
428 }else{
429 pColl = sqlite3ExprCollSeq(pParse, pLeft);
430 if( !pColl ){
431 pColl = sqlite3ExprCollSeq(pParse, pRight);
434 return pColl;
437 /* Expression p is a comparison operator. Return a collation sequence
438 ** appropriate for the comparison operator.
440 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
441 ** However, if the OP_Commuted flag is set, then the order of the operands
442 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
443 ** correct collating sequence is found.
445 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
446 if( ExprHasProperty(p, EP_Commuted) ){
447 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
448 }else{
449 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
454 ** Generate code for a comparison operator.
456 static int codeCompare(
457 Parse *pParse, /* The parsing (and code generating) context */
458 Expr *pLeft, /* The left operand */
459 Expr *pRight, /* The right operand */
460 int opcode, /* The comparison opcode */
461 int in1, int in2, /* Register holding operands */
462 int dest, /* Jump here if true. */
463 int jumpIfNull, /* If true, jump if either operand is NULL */
464 int isCommuted /* The comparison has been commuted */
466 int p5;
467 int addr;
468 CollSeq *p4;
470 if( pParse->nErr ) return 0;
471 if( isCommuted ){
472 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
473 }else{
474 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
476 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
477 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
478 (void*)p4, P4_COLLSEQ);
479 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
480 return addr;
484 ** Return true if expression pExpr is a vector, or false otherwise.
486 ** A vector is defined as any expression that results in two or more
487 ** columns of result. Every TK_VECTOR node is an vector because the
488 ** parser will not generate a TK_VECTOR with fewer than two entries.
489 ** But a TK_SELECT might be either a vector or a scalar. It is only
490 ** considered a vector if it has two or more result columns.
492 int sqlite3ExprIsVector(const Expr *pExpr){
493 return sqlite3ExprVectorSize(pExpr)>1;
497 ** If the expression passed as the only argument is of type TK_VECTOR
498 ** return the number of expressions in the vector. Or, if the expression
499 ** is a sub-select, return the number of columns in the sub-select. For
500 ** any other type of expression, return 1.
502 int sqlite3ExprVectorSize(const Expr *pExpr){
503 u8 op = pExpr->op;
504 if( op==TK_REGISTER ) op = pExpr->op2;
505 if( op==TK_VECTOR ){
506 assert( ExprUseXList(pExpr) );
507 return pExpr->x.pList->nExpr;
508 }else if( op==TK_SELECT ){
509 assert( ExprUseXSelect(pExpr) );
510 return pExpr->x.pSelect->pEList->nExpr;
511 }else{
512 return 1;
517 ** Return a pointer to a subexpression of pVector that is the i-th
518 ** column of the vector (numbered starting with 0). The caller must
519 ** ensure that i is within range.
521 ** If pVector is really a scalar (and "scalar" here includes subqueries
522 ** that return a single column!) then return pVector unmodified.
524 ** pVector retains ownership of the returned subexpression.
526 ** If the vector is a (SELECT ...) then the expression returned is
527 ** just the expression for the i-th term of the result set, and may
528 ** not be ready for evaluation because the table cursor has not yet
529 ** been positioned.
531 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
532 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
533 if( sqlite3ExprIsVector(pVector) ){
534 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
535 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
536 assert( ExprUseXSelect(pVector) );
537 return pVector->x.pSelect->pEList->a[i].pExpr;
538 }else{
539 assert( ExprUseXList(pVector) );
540 return pVector->x.pList->a[i].pExpr;
543 return pVector;
547 ** Compute and return a new Expr object which when passed to
548 ** sqlite3ExprCode() will generate all necessary code to compute
549 ** the iField-th column of the vector expression pVector.
551 ** It is ok for pVector to be a scalar (as long as iField==0).
552 ** In that case, this routine works like sqlite3ExprDup().
554 ** The caller owns the returned Expr object and is responsible for
555 ** ensuring that the returned value eventually gets freed.
557 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
558 ** then the returned object will reference pVector and so pVector must remain
559 ** valid for the life of the returned object. If pVector is a TK_VECTOR
560 ** or a scalar expression, then it can be deleted as soon as this routine
561 ** returns.
563 ** A trick to cause a TK_SELECT pVector to be deleted together with
564 ** the returned Expr object is to attach the pVector to the pRight field
565 ** of the returned TK_SELECT_COLUMN Expr object.
567 Expr *sqlite3ExprForVectorField(
568 Parse *pParse, /* Parsing context */
569 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
570 int iField, /* Which column of the vector to return */
571 int nField /* Total number of columns in the vector */
573 Expr *pRet;
574 if( pVector->op==TK_SELECT ){
575 assert( ExprUseXSelect(pVector) );
576 /* The TK_SELECT_COLUMN Expr node:
578 ** pLeft: pVector containing TK_SELECT. Not deleted.
579 ** pRight: not used. But recursively deleted.
580 ** iColumn: Index of a column in pVector
581 ** iTable: 0 or the number of columns on the LHS of an assignment
582 ** pLeft->iTable: First in an array of register holding result, or 0
583 ** if the result is not yet computed.
585 ** sqlite3ExprDelete() specifically skips the recursive delete of
586 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
587 ** can be attached to pRight to cause this node to take ownership of
588 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
589 ** with the same pLeft pointer to the pVector, but only one of them
590 ** will own the pVector.
592 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
593 if( pRet ){
594 pRet->iTable = nField;
595 pRet->iColumn = iField;
596 pRet->pLeft = pVector;
598 }else{
599 if( pVector->op==TK_VECTOR ){
600 Expr **ppVector;
601 assert( ExprUseXList(pVector) );
602 ppVector = &pVector->x.pList->a[iField].pExpr;
603 pVector = *ppVector;
604 if( IN_RENAME_OBJECT ){
605 /* This must be a vector UPDATE inside a trigger */
606 *ppVector = 0;
607 return pVector;
610 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
612 return pRet;
616 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
617 ** it. Return the register in which the result is stored (or, if the
618 ** sub-select returns more than one column, the first in an array
619 ** of registers in which the result is stored).
621 ** If pExpr is not a TK_SELECT expression, return 0.
623 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
624 int reg = 0;
625 #ifndef SQLITE_OMIT_SUBQUERY
626 if( pExpr->op==TK_SELECT ){
627 reg = sqlite3CodeSubselect(pParse, pExpr);
629 #endif
630 return reg;
634 ** Argument pVector points to a vector expression - either a TK_VECTOR
635 ** or TK_SELECT that returns more than one column. This function returns
636 ** the register number of a register that contains the value of
637 ** element iField of the vector.
639 ** If pVector is a TK_SELECT expression, then code for it must have
640 ** already been generated using the exprCodeSubselect() routine. In this
641 ** case parameter regSelect should be the first in an array of registers
642 ** containing the results of the sub-select.
644 ** If pVector is of type TK_VECTOR, then code for the requested field
645 ** is generated. In this case (*pRegFree) may be set to the number of
646 ** a temporary register to be freed by the caller before returning.
648 ** Before returning, output parameter (*ppExpr) is set to point to the
649 ** Expr object corresponding to element iElem of the vector.
651 static int exprVectorRegister(
652 Parse *pParse, /* Parse context */
653 Expr *pVector, /* Vector to extract element from */
654 int iField, /* Field to extract from pVector */
655 int regSelect, /* First in array of registers */
656 Expr **ppExpr, /* OUT: Expression element */
657 int *pRegFree /* OUT: Temp register to free */
659 u8 op = pVector->op;
660 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
661 if( op==TK_REGISTER ){
662 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
663 return pVector->iTable+iField;
665 if( op==TK_SELECT ){
666 assert( ExprUseXSelect(pVector) );
667 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
668 return regSelect+iField;
670 if( op==TK_VECTOR ){
671 assert( ExprUseXList(pVector) );
672 *ppExpr = pVector->x.pList->a[iField].pExpr;
673 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
675 return 0;
679 ** Expression pExpr is a comparison between two vector values. Compute
680 ** the result of the comparison (1, 0, or NULL) and write that
681 ** result into register dest.
683 ** The caller must satisfy the following preconditions:
685 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
686 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
687 ** otherwise: op==pExpr->op and p5==0
689 static void codeVectorCompare(
690 Parse *pParse, /* Code generator context */
691 Expr *pExpr, /* The comparison operation */
692 int dest, /* Write results into this register */
693 u8 op, /* Comparison operator */
694 u8 p5 /* SQLITE_NULLEQ or zero */
696 Vdbe *v = pParse->pVdbe;
697 Expr *pLeft = pExpr->pLeft;
698 Expr *pRight = pExpr->pRight;
699 int nLeft = sqlite3ExprVectorSize(pLeft);
700 int i;
701 int regLeft = 0;
702 int regRight = 0;
703 u8 opx = op;
704 int addrCmp = 0;
705 int addrDone = sqlite3VdbeMakeLabel(pParse);
706 int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
708 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
709 if( pParse->nErr ) return;
710 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
711 sqlite3ErrorMsg(pParse, "row value misused");
712 return;
714 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
715 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
716 || pExpr->op==TK_LT || pExpr->op==TK_GT
717 || pExpr->op==TK_LE || pExpr->op==TK_GE
719 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
720 || (pExpr->op==TK_ISNOT && op==TK_NE) );
721 assert( p5==0 || pExpr->op!=op );
722 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
724 if( op==TK_LE ) opx = TK_LT;
725 if( op==TK_GE ) opx = TK_GT;
726 if( op==TK_NE ) opx = TK_EQ;
728 regLeft = exprCodeSubselect(pParse, pLeft);
729 regRight = exprCodeSubselect(pParse, pRight);
731 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
732 for(i=0; 1 /*Loop exits by "break"*/; i++){
733 int regFree1 = 0, regFree2 = 0;
734 Expr *pL = 0, *pR = 0;
735 int r1, r2;
736 assert( i>=0 && i<nLeft );
737 if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
738 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
739 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
740 addrCmp = sqlite3VdbeCurrentAddr(v);
741 codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
742 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
743 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
744 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
745 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
746 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
747 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
748 sqlite3ReleaseTempReg(pParse, regFree1);
749 sqlite3ReleaseTempReg(pParse, regFree2);
750 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
751 addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
752 testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
753 testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
755 if( p5==SQLITE_NULLEQ ){
756 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
757 }else{
758 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
760 if( i==nLeft-1 ){
761 break;
763 if( opx==TK_EQ ){
764 sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
765 }else{
766 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
767 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
768 if( i==nLeft-2 ) opx = op;
771 sqlite3VdbeJumpHere(v, addrCmp);
772 sqlite3VdbeResolveLabel(v, addrDone);
773 if( op==TK_NE ){
774 sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
778 #if SQLITE_MAX_EXPR_DEPTH>0
780 ** Check that argument nHeight is less than or equal to the maximum
781 ** expression depth allowed. If it is not, leave an error message in
782 ** pParse.
784 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
785 int rc = SQLITE_OK;
786 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
787 if( nHeight>mxHeight ){
788 sqlite3ErrorMsg(pParse,
789 "Expression tree is too large (maximum depth %d)", mxHeight
791 rc = SQLITE_ERROR;
793 return rc;
796 /* The following three functions, heightOfExpr(), heightOfExprList()
797 ** and heightOfSelect(), are used to determine the maximum height
798 ** of any expression tree referenced by the structure passed as the
799 ** first argument.
801 ** If this maximum height is greater than the current value pointed
802 ** to by pnHeight, the second parameter, then set *pnHeight to that
803 ** value.
805 static void heightOfExpr(const Expr *p, int *pnHeight){
806 if( p ){
807 if( p->nHeight>*pnHeight ){
808 *pnHeight = p->nHeight;
812 static void heightOfExprList(const ExprList *p, int *pnHeight){
813 if( p ){
814 int i;
815 for(i=0; i<p->nExpr; i++){
816 heightOfExpr(p->a[i].pExpr, pnHeight);
820 static void heightOfSelect(const Select *pSelect, int *pnHeight){
821 const Select *p;
822 for(p=pSelect; p; p=p->pPrior){
823 heightOfExpr(p->pWhere, pnHeight);
824 heightOfExpr(p->pHaving, pnHeight);
825 heightOfExpr(p->pLimit, pnHeight);
826 heightOfExprList(p->pEList, pnHeight);
827 heightOfExprList(p->pGroupBy, pnHeight);
828 heightOfExprList(p->pOrderBy, pnHeight);
833 ** Set the Expr.nHeight variable in the structure passed as an
834 ** argument. An expression with no children, Expr.pList or
835 ** Expr.pSelect member has a height of 1. Any other expression
836 ** has a height equal to the maximum height of any other
837 ** referenced Expr plus one.
839 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
840 ** if appropriate.
842 static void exprSetHeight(Expr *p){
843 int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
844 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
845 nHeight = p->pRight->nHeight;
847 if( ExprUseXSelect(p) ){
848 heightOfSelect(p->x.pSelect, &nHeight);
849 }else if( p->x.pList ){
850 heightOfExprList(p->x.pList, &nHeight);
851 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
853 p->nHeight = nHeight + 1;
857 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
858 ** the height is greater than the maximum allowed expression depth,
859 ** leave an error in pParse.
861 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
862 ** Expr.flags.
864 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
865 if( pParse->nErr ) return;
866 exprSetHeight(p);
867 sqlite3ExprCheckHeight(pParse, p->nHeight);
871 ** Return the maximum height of any expression tree referenced
872 ** by the select statement passed as an argument.
874 int sqlite3SelectExprHeight(const Select *p){
875 int nHeight = 0;
876 heightOfSelect(p, &nHeight);
877 return nHeight;
879 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
881 ** Propagate all EP_Propagate flags from the Expr.x.pList into
882 ** Expr.flags.
884 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
885 if( pParse->nErr ) return;
886 if( p && ExprUseXList(p) && p->x.pList ){
887 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
890 #define exprSetHeight(y)
891 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
894 ** Set the error offset for an Expr node, if possible.
896 void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){
897 if( pExpr==0 ) return;
898 if( NEVER(ExprUseWJoin(pExpr)) ) return;
899 pExpr->w.iOfst = iOfst;
903 ** This routine is the core allocator for Expr nodes.
905 ** Construct a new expression node and return a pointer to it. Memory
906 ** for this node and for the pToken argument is a single allocation
907 ** obtained from sqlite3DbMalloc(). The calling function
908 ** is responsible for making sure the node eventually gets freed.
910 ** If dequote is true, then the token (if it exists) is dequoted.
911 ** If dequote is false, no dequoting is performed. The deQuote
912 ** parameter is ignored if pToken is NULL or if the token does not
913 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
914 ** then the EP_DblQuoted flag is set on the expression node.
916 ** Special case: If op==TK_INTEGER and pToken points to a string that
917 ** can be translated into a 32-bit integer, then the token is not
918 ** stored in u.zToken. Instead, the integer values is written
919 ** into u.iValue and the EP_IntValue flag is set. No extra storage
920 ** is allocated to hold the integer text and the dequote flag is ignored.
922 Expr *sqlite3ExprAlloc(
923 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
924 int op, /* Expression opcode */
925 const Token *pToken, /* Token argument. Might be NULL */
926 int dequote /* True to dequote */
928 Expr *pNew;
929 int nExtra = 0;
930 int iValue = 0;
932 assert( db!=0 );
933 if( pToken ){
934 if( op!=TK_INTEGER || pToken->z==0
935 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
936 nExtra = pToken->n+1;
937 assert( iValue>=0 );
940 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
941 if( pNew ){
942 memset(pNew, 0, sizeof(Expr));
943 pNew->op = (u8)op;
944 pNew->iAgg = -1;
945 if( pToken ){
946 if( nExtra==0 ){
947 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
948 pNew->u.iValue = iValue;
949 }else{
950 pNew->u.zToken = (char*)&pNew[1];
951 assert( pToken->z!=0 || pToken->n==0 );
952 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
953 pNew->u.zToken[pToken->n] = 0;
954 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
955 sqlite3DequoteExpr(pNew);
959 #if SQLITE_MAX_EXPR_DEPTH>0
960 pNew->nHeight = 1;
961 #endif
963 return pNew;
967 ** Allocate a new expression node from a zero-terminated token that has
968 ** already been dequoted.
970 Expr *sqlite3Expr(
971 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
972 int op, /* Expression opcode */
973 const char *zToken /* Token argument. Might be NULL */
975 Token x;
976 x.z = zToken;
977 x.n = sqlite3Strlen30(zToken);
978 return sqlite3ExprAlloc(db, op, &x, 0);
982 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
984 ** If pRoot==NULL that means that a memory allocation error has occurred.
985 ** In that case, delete the subtrees pLeft and pRight.
987 void sqlite3ExprAttachSubtrees(
988 sqlite3 *db,
989 Expr *pRoot,
990 Expr *pLeft,
991 Expr *pRight
993 if( pRoot==0 ){
994 assert( db->mallocFailed );
995 sqlite3ExprDelete(db, pLeft);
996 sqlite3ExprDelete(db, pRight);
997 }else{
998 assert( ExprUseXList(pRoot) );
999 assert( pRoot->x.pSelect==0 );
1000 if( pRight ){
1001 pRoot->pRight = pRight;
1002 pRoot->flags |= EP_Propagate & pRight->flags;
1003 #if SQLITE_MAX_EXPR_DEPTH>0
1004 pRoot->nHeight = pRight->nHeight+1;
1005 }else{
1006 pRoot->nHeight = 1;
1007 #endif
1009 if( pLeft ){
1010 pRoot->pLeft = pLeft;
1011 pRoot->flags |= EP_Propagate & pLeft->flags;
1012 #if SQLITE_MAX_EXPR_DEPTH>0
1013 if( pLeft->nHeight>=pRoot->nHeight ){
1014 pRoot->nHeight = pLeft->nHeight+1;
1016 #endif
1022 ** Allocate an Expr node which joins as many as two subtrees.
1024 ** One or both of the subtrees can be NULL. Return a pointer to the new
1025 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1026 ** free the subtrees and return NULL.
1028 Expr *sqlite3PExpr(
1029 Parse *pParse, /* Parsing context */
1030 int op, /* Expression opcode */
1031 Expr *pLeft, /* Left operand */
1032 Expr *pRight /* Right operand */
1034 Expr *p;
1035 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
1036 if( p ){
1037 memset(p, 0, sizeof(Expr));
1038 p->op = op & 0xff;
1039 p->iAgg = -1;
1040 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
1041 sqlite3ExprCheckHeight(pParse, p->nHeight);
1042 }else{
1043 sqlite3ExprDelete(pParse->db, pLeft);
1044 sqlite3ExprDelete(pParse->db, pRight);
1046 return p;
1050 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1051 ** do a memory allocation failure) then delete the pSelect object.
1053 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
1054 if( pExpr ){
1055 pExpr->x.pSelect = pSelect;
1056 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
1057 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
1058 }else{
1059 assert( pParse->db->mallocFailed );
1060 sqlite3SelectDelete(pParse->db, pSelect);
1065 ** Expression list pEList is a list of vector values. This function
1066 ** converts the contents of pEList to a VALUES(...) Select statement
1067 ** returning 1 row for each element of the list. For example, the
1068 ** expression list:
1070 ** ( (1,2), (3,4) (5,6) )
1072 ** is translated to the equivalent of:
1074 ** VALUES(1,2), (3,4), (5,6)
1076 ** Each of the vector values in pEList must contain exactly nElem terms.
1077 ** If a list element that is not a vector or does not contain nElem terms,
1078 ** an error message is left in pParse.
1080 ** This is used as part of processing IN(...) expressions with a list
1081 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1083 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){
1084 int ii;
1085 Select *pRet = 0;
1086 assert( nElem>1 );
1087 for(ii=0; ii<pEList->nExpr; ii++){
1088 Select *pSel;
1089 Expr *pExpr = pEList->a[ii].pExpr;
1090 int nExprElem;
1091 if( pExpr->op==TK_VECTOR ){
1092 assert( ExprUseXList(pExpr) );
1093 nExprElem = pExpr->x.pList->nExpr;
1094 }else{
1095 nExprElem = 1;
1097 if( nExprElem!=nElem ){
1098 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
1099 nExprElem, nExprElem>1?"s":"", nElem
1101 break;
1103 assert( ExprUseXList(pExpr) );
1104 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
1105 pExpr->x.pList = 0;
1106 if( pSel ){
1107 if( pRet ){
1108 pSel->op = TK_ALL;
1109 pSel->pPrior = pRet;
1111 pRet = pSel;
1115 if( pRet && pRet->pPrior ){
1116 pRet->selFlags |= SF_MultiValue;
1118 sqlite3ExprListDelete(pParse->db, pEList);
1119 return pRet;
1123 ** Join two expressions using an AND operator. If either expression is
1124 ** NULL, then just return the other expression.
1126 ** If one side or the other of the AND is known to be false, and neither side
1127 ** is part of an ON clause, then instead of returning an AND expression,
1128 ** just return a constant expression with a value of false.
1130 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
1131 sqlite3 *db = pParse->db;
1132 if( pLeft==0 ){
1133 return pRight;
1134 }else if( pRight==0 ){
1135 return pLeft;
1136 }else{
1137 u32 f = pLeft->flags | pRight->flags;
1138 if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse
1139 && !IN_RENAME_OBJECT
1141 sqlite3ExprDeferredDelete(pParse, pLeft);
1142 sqlite3ExprDeferredDelete(pParse, pRight);
1143 return sqlite3Expr(db, TK_INTEGER, "0");
1144 }else{
1145 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
1151 ** Construct a new expression node for a function with multiple
1152 ** arguments.
1154 Expr *sqlite3ExprFunction(
1155 Parse *pParse, /* Parsing context */
1156 ExprList *pList, /* Argument list */
1157 const Token *pToken, /* Name of the function */
1158 int eDistinct /* SF_Distinct or SF_ALL or 0 */
1160 Expr *pNew;
1161 sqlite3 *db = pParse->db;
1162 assert( pToken );
1163 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
1164 if( pNew==0 ){
1165 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
1166 return 0;
1168 assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) );
1169 pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
1170 if( pList
1171 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
1172 && !pParse->nested
1174 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
1176 pNew->x.pList = pList;
1177 ExprSetProperty(pNew, EP_HasFunc);
1178 assert( ExprUseXList(pNew) );
1179 sqlite3ExprSetHeightAndFlags(pParse, pNew);
1180 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
1181 return pNew;
1185 ** Check to see if a function is usable according to current access
1186 ** rules:
1188 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1190 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1191 ** top-level SQL
1193 ** If the function is not usable, create an error.
1195 void sqlite3ExprFunctionUsable(
1196 Parse *pParse, /* Parsing and code generating context */
1197 const Expr *pExpr, /* The function invocation */
1198 const FuncDef *pDef /* The function being invoked */
1200 assert( !IN_RENAME_OBJECT );
1201 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
1202 if( ExprHasProperty(pExpr, EP_FromDDL) ){
1203 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
1204 || (pParse->db->flags & SQLITE_TrustedSchema)==0
1206 /* Functions prohibited in triggers and views if:
1207 ** (1) tagged with SQLITE_DIRECTONLY
1208 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1209 ** is tagged with SQLITE_FUNC_UNSAFE) and
1210 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1211 ** that the schema is possibly tainted).
1213 sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr);
1219 ** Assign a variable number to an expression that encodes a wildcard
1220 ** in the original SQL statement.
1222 ** Wildcards consisting of a single "?" are assigned the next sequential
1223 ** variable number.
1225 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1226 ** sure "nnn" is not too big to avoid a denial of service attack when
1227 ** the SQL statement comes from an external source.
1229 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1230 ** as the previous instance of the same wildcard. Or if this is the first
1231 ** instance of the wildcard, the next sequential variable number is
1232 ** assigned.
1234 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1235 sqlite3 *db = pParse->db;
1236 const char *z;
1237 ynVar x;
1239 if( pExpr==0 ) return;
1240 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1241 z = pExpr->u.zToken;
1242 assert( z!=0 );
1243 assert( z[0]!=0 );
1244 assert( n==(u32)sqlite3Strlen30(z) );
1245 if( z[1]==0 ){
1246 /* Wildcard of the form "?". Assign the next variable number */
1247 assert( z[0]=='?' );
1248 x = (ynVar)(++pParse->nVar);
1249 }else{
1250 int doAdd = 0;
1251 if( z[0]=='?' ){
1252 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1253 ** use it as the variable number */
1254 i64 i;
1255 int bOk;
1256 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1257 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1258 bOk = 1;
1259 }else{
1260 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1262 testcase( i==0 );
1263 testcase( i==1 );
1264 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1265 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1266 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1267 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1268 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1269 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1270 return;
1272 x = (ynVar)i;
1273 if( x>pParse->nVar ){
1274 pParse->nVar = (int)x;
1275 doAdd = 1;
1276 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1277 doAdd = 1;
1279 }else{
1280 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1281 ** number as the prior appearance of the same name, or if the name
1282 ** has never appeared before, reuse the same variable number
1284 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1285 if( x==0 ){
1286 x = (ynVar)(++pParse->nVar);
1287 doAdd = 1;
1290 if( doAdd ){
1291 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1294 pExpr->iColumn = x;
1295 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1296 sqlite3ErrorMsg(pParse, "too many SQL variables");
1297 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1302 ** Recursively delete an expression tree.
1304 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1305 assert( p!=0 );
1306 assert( db!=0 );
1307 assert( !ExprUseUValue(p) || p->u.iValue>=0 );
1308 assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
1309 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
1310 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
1311 #ifdef SQLITE_DEBUG
1312 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1313 assert( p->pLeft==0 );
1314 assert( p->pRight==0 );
1315 assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
1316 assert( !ExprUseXList(p) || p->x.pList==0 );
1318 #endif
1319 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1320 /* The Expr.x union is never used at the same time as Expr.pRight */
1321 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
1322 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1323 if( p->pRight ){
1324 assert( !ExprHasProperty(p, EP_WinFunc) );
1325 sqlite3ExprDeleteNN(db, p->pRight);
1326 }else if( ExprUseXSelect(p) ){
1327 assert( !ExprHasProperty(p, EP_WinFunc) );
1328 sqlite3SelectDelete(db, p->x.pSelect);
1329 }else{
1330 sqlite3ExprListDelete(db, p->x.pList);
1331 #ifndef SQLITE_OMIT_WINDOWFUNC
1332 if( ExprHasProperty(p, EP_WinFunc) ){
1333 sqlite3WindowDelete(db, p->y.pWin);
1335 #endif
1338 if( !ExprHasProperty(p, EP_Static) ){
1339 sqlite3DbNNFreeNN(db, p);
1342 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1343 if( p ) sqlite3ExprDeleteNN(db, p);
1347 ** Clear both elements of an OnOrUsing object
1349 void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){
1350 if( p==0 ){
1351 /* Nothing to clear */
1352 }else if( p->pOn ){
1353 sqlite3ExprDeleteNN(db, p->pOn);
1354 }else if( p->pUsing ){
1355 sqlite3IdListDelete(db, p->pUsing);
1360 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1361 ** This is similar to sqlite3ExprDelete() except that the delete is
1362 ** deferred until the pParse is deleted.
1364 ** The pExpr might be deleted immediately on an OOM error.
1366 ** The deferred delete is (currently) implemented by adding the
1367 ** pExpr to the pParse->pConstExpr list with a register number of 0.
1369 void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
1370 sqlite3ParserAddCleanup(pParse,
1371 (void(*)(sqlite3*,void*))sqlite3ExprDelete,
1372 pExpr);
1375 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1376 ** expression.
1378 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1379 if( p ){
1380 if( IN_RENAME_OBJECT ){
1381 sqlite3RenameExprUnmap(pParse, p);
1383 sqlite3ExprDeleteNN(pParse->db, p);
1388 ** Return the number of bytes allocated for the expression structure
1389 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1390 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1392 static int exprStructSize(const Expr *p){
1393 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1394 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1395 return EXPR_FULLSIZE;
1399 ** The dupedExpr*Size() routines each return the number of bytes required
1400 ** to store a copy of an expression or expression tree. They differ in
1401 ** how much of the tree is measured.
1403 ** dupedExprStructSize() Size of only the Expr structure
1404 ** dupedExprNodeSize() Size of Expr + space for token
1405 ** dupedExprSize() Expr + token + subtree components
1407 ***************************************************************************
1409 ** The dupedExprStructSize() function returns two values OR-ed together:
1410 ** (1) the space required for a copy of the Expr structure only and
1411 ** (2) the EP_xxx flags that indicate what the structure size should be.
1412 ** The return values is always one of:
1414 ** EXPR_FULLSIZE
1415 ** EXPR_REDUCEDSIZE | EP_Reduced
1416 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1418 ** The size of the structure can be found by masking the return value
1419 ** of this routine with 0xfff. The flags can be found by masking the
1420 ** return value with EP_Reduced|EP_TokenOnly.
1422 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1423 ** (unreduced) Expr objects as they or originally constructed by the parser.
1424 ** During expression analysis, extra information is computed and moved into
1425 ** later parts of the Expr object and that extra information might get chopped
1426 ** off if the expression is reduced. Note also that it does not work to
1427 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1428 ** to reduce a pristine expression tree from the parser. The implementation
1429 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1430 ** to enforce this constraint.
1432 static int dupedExprStructSize(const Expr *p, int flags){
1433 int nSize;
1434 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1435 assert( EXPR_FULLSIZE<=0xfff );
1436 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1437 if( 0==flags || p->op==TK_SELECT_COLUMN
1438 #ifndef SQLITE_OMIT_WINDOWFUNC
1439 || ExprHasProperty(p, EP_WinFunc)
1440 #endif
1442 nSize = EXPR_FULLSIZE;
1443 }else{
1444 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1445 assert( !ExprHasProperty(p, EP_OuterON) );
1446 assert( !ExprHasVVAProperty(p, EP_NoReduce) );
1447 if( p->pLeft || p->x.pList ){
1448 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1449 }else{
1450 assert( p->pRight==0 );
1451 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1454 return nSize;
1458 ** This function returns the space in bytes required to store the copy
1459 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1460 ** string is defined.)
1462 static int dupedExprNodeSize(const Expr *p, int flags){
1463 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1464 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1465 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1467 return ROUND8(nByte);
1471 ** Return the number of bytes required to create a duplicate of the
1472 ** expression passed as the first argument. The second argument is a
1473 ** mask containing EXPRDUP_XXX flags.
1475 ** The value returned includes space to create a copy of the Expr struct
1476 ** itself and the buffer referred to by Expr.u.zToken, if any.
1478 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1479 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1480 ** and Expr.pRight variables (but not for any structures pointed to or
1481 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1483 static int dupedExprSize(const Expr *p, int flags){
1484 int nByte = 0;
1485 if( p ){
1486 nByte = dupedExprNodeSize(p, flags);
1487 if( flags&EXPRDUP_REDUCE ){
1488 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
1491 return nByte;
1495 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1496 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1497 ** to store the copy of expression p, the copies of p->u.zToken
1498 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1499 ** if any. Before returning, *pzBuffer is set to the first byte past the
1500 ** portion of the buffer copied into by this function.
1502 static Expr *exprDup(sqlite3 *db, const Expr *p, int dupFlags, u8 **pzBuffer){
1503 Expr *pNew; /* Value to return */
1504 u8 *zAlloc; /* Memory space from which to build Expr object */
1505 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1507 assert( db!=0 );
1508 assert( p );
1509 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1510 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
1512 /* Figure out where to write the new Expr structure. */
1513 if( pzBuffer ){
1514 zAlloc = *pzBuffer;
1515 staticFlag = EP_Static;
1516 assert( zAlloc!=0 );
1517 }else{
1518 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1519 staticFlag = 0;
1521 pNew = (Expr *)zAlloc;
1523 if( pNew ){
1524 /* Set nNewSize to the size allocated for the structure pointed to
1525 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1526 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1527 ** by the copy of the p->u.zToken string (if any).
1529 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1530 const int nNewSize = nStructSize & 0xfff;
1531 int nToken;
1532 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1533 nToken = sqlite3Strlen30(p->u.zToken) + 1;
1534 }else{
1535 nToken = 0;
1537 if( dupFlags ){
1538 assert( ExprHasProperty(p, EP_Reduced)==0 );
1539 memcpy(zAlloc, p, nNewSize);
1540 }else{
1541 u32 nSize = (u32)exprStructSize(p);
1542 memcpy(zAlloc, p, nSize);
1543 if( nSize<EXPR_FULLSIZE ){
1544 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1548 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1549 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
1550 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1551 pNew->flags |= staticFlag;
1552 ExprClearVVAProperties(pNew);
1553 if( dupFlags ){
1554 ExprSetVVAProperty(pNew, EP_Immutable);
1557 /* Copy the p->u.zToken string, if any. */
1558 if( nToken ){
1559 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1560 memcpy(zToken, p->u.zToken, nToken);
1563 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
1564 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1565 if( ExprUseXSelect(p) ){
1566 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1567 }else{
1568 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1572 /* Fill in pNew->pLeft and pNew->pRight. */
1573 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
1574 zAlloc += dupedExprNodeSize(p, dupFlags);
1575 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
1576 pNew->pLeft = p->pLeft ?
1577 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1578 pNew->pRight = p->pRight ?
1579 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
1581 #ifndef SQLITE_OMIT_WINDOWFUNC
1582 if( ExprHasProperty(p, EP_WinFunc) ){
1583 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1584 assert( ExprHasProperty(pNew, EP_WinFunc) );
1586 #endif /* SQLITE_OMIT_WINDOWFUNC */
1587 if( pzBuffer ){
1588 *pzBuffer = zAlloc;
1590 }else{
1591 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1592 if( pNew->op==TK_SELECT_COLUMN ){
1593 pNew->pLeft = p->pLeft;
1594 assert( p->pRight==0 || p->pRight==p->pLeft
1595 || ExprHasProperty(p->pLeft, EP_Subquery) );
1596 }else{
1597 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1599 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1603 return pNew;
1607 ** Create and return a deep copy of the object passed as the second
1608 ** argument. If an OOM condition is encountered, NULL is returned
1609 ** and the db->mallocFailed flag set.
1611 #ifndef SQLITE_OMIT_CTE
1612 With *sqlite3WithDup(sqlite3 *db, With *p){
1613 With *pRet = 0;
1614 if( p ){
1615 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1616 pRet = sqlite3DbMallocZero(db, nByte);
1617 if( pRet ){
1618 int i;
1619 pRet->nCte = p->nCte;
1620 for(i=0; i<p->nCte; i++){
1621 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1622 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1623 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1624 pRet->a[i].eM10d = p->a[i].eM10d;
1628 return pRet;
1630 #else
1631 # define sqlite3WithDup(x,y) 0
1632 #endif
1634 #ifndef SQLITE_OMIT_WINDOWFUNC
1636 ** The gatherSelectWindows() procedure and its helper routine
1637 ** gatherSelectWindowsCallback() are used to scan all the expressions
1638 ** an a newly duplicated SELECT statement and gather all of the Window
1639 ** objects found there, assembling them onto the linked list at Select->pWin.
1641 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1642 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1643 Select *pSelect = pWalker->u.pSelect;
1644 Window *pWin = pExpr->y.pWin;
1645 assert( pWin );
1646 assert( IsWindowFunc(pExpr) );
1647 assert( pWin->ppThis==0 );
1648 sqlite3WindowLink(pSelect, pWin);
1650 return WRC_Continue;
1652 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1653 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1655 static void gatherSelectWindows(Select *p){
1656 Walker w;
1657 w.xExprCallback = gatherSelectWindowsCallback;
1658 w.xSelectCallback = gatherSelectWindowsSelectCallback;
1659 w.xSelectCallback2 = 0;
1660 w.pParse = 0;
1661 w.u.pSelect = p;
1662 sqlite3WalkSelect(&w, p);
1664 #endif
1668 ** The following group of routines make deep copies of expressions,
1669 ** expression lists, ID lists, and select statements. The copies can
1670 ** be deleted (by being passed to their respective ...Delete() routines)
1671 ** without effecting the originals.
1673 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1674 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1675 ** by subsequent calls to sqlite*ListAppend() routines.
1677 ** Any tables that the SrcList might point to are not duplicated.
1679 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1680 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1681 ** truncated version of the usual Expr structure that will be stored as
1682 ** part of the in-memory representation of the database schema.
1684 Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){
1685 assert( flags==0 || flags==EXPRDUP_REDUCE );
1686 return p ? exprDup(db, p, flags, 0) : 0;
1688 ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){
1689 ExprList *pNew;
1690 struct ExprList_item *pItem;
1691 const struct ExprList_item *pOldItem;
1692 int i;
1693 Expr *pPriorSelectColOld = 0;
1694 Expr *pPriorSelectColNew = 0;
1695 assert( db!=0 );
1696 if( p==0 ) return 0;
1697 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1698 if( pNew==0 ) return 0;
1699 pNew->nExpr = p->nExpr;
1700 pNew->nAlloc = p->nAlloc;
1701 pItem = pNew->a;
1702 pOldItem = p->a;
1703 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1704 Expr *pOldExpr = pOldItem->pExpr;
1705 Expr *pNewExpr;
1706 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1707 if( pOldExpr
1708 && pOldExpr->op==TK_SELECT_COLUMN
1709 && (pNewExpr = pItem->pExpr)!=0
1711 if( pNewExpr->pRight ){
1712 pPriorSelectColOld = pOldExpr->pRight;
1713 pPriorSelectColNew = pNewExpr->pRight;
1714 pNewExpr->pLeft = pNewExpr->pRight;
1715 }else{
1716 if( pOldExpr->pLeft!=pPriorSelectColOld ){
1717 pPriorSelectColOld = pOldExpr->pLeft;
1718 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
1719 pNewExpr->pRight = pPriorSelectColNew;
1721 pNewExpr->pLeft = pPriorSelectColNew;
1724 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1725 pItem->fg = pOldItem->fg;
1726 pItem->fg.done = 0;
1727 pItem->u = pOldItem->u;
1729 return pNew;
1733 ** If cursors, triggers, views and subqueries are all omitted from
1734 ** the build, then none of the following routines, except for
1735 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1736 ** called with a NULL argument.
1738 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1739 || !defined(SQLITE_OMIT_SUBQUERY)
1740 SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){
1741 SrcList *pNew;
1742 int i;
1743 int nByte;
1744 assert( db!=0 );
1745 if( p==0 ) return 0;
1746 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1747 pNew = sqlite3DbMallocRawNN(db, nByte );
1748 if( pNew==0 ) return 0;
1749 pNew->nSrc = pNew->nAlloc = p->nSrc;
1750 for(i=0; i<p->nSrc; i++){
1751 SrcItem *pNewItem = &pNew->a[i];
1752 const SrcItem *pOldItem = &p->a[i];
1753 Table *pTab;
1754 pNewItem->pSchema = pOldItem->pSchema;
1755 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1756 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1757 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1758 pNewItem->fg = pOldItem->fg;
1759 pNewItem->iCursor = pOldItem->iCursor;
1760 pNewItem->addrFillSub = pOldItem->addrFillSub;
1761 pNewItem->regReturn = pOldItem->regReturn;
1762 if( pNewItem->fg.isIndexedBy ){
1763 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1765 pNewItem->u2 = pOldItem->u2;
1766 if( pNewItem->fg.isCte ){
1767 pNewItem->u2.pCteUse->nUse++;
1769 if( pNewItem->fg.isTabFunc ){
1770 pNewItem->u1.pFuncArg =
1771 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1773 pTab = pNewItem->pTab = pOldItem->pTab;
1774 if( pTab ){
1775 pTab->nTabRef++;
1777 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1778 if( pOldItem->fg.isUsing ){
1779 assert( pNewItem->fg.isUsing );
1780 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
1781 }else{
1782 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
1784 pNewItem->colUsed = pOldItem->colUsed;
1786 return pNew;
1788 IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){
1789 IdList *pNew;
1790 int i;
1791 assert( db!=0 );
1792 if( p==0 ) return 0;
1793 assert( p->eU4!=EU4_EXPR );
1794 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );
1795 if( pNew==0 ) return 0;
1796 pNew->nId = p->nId;
1797 pNew->eU4 = p->eU4;
1798 for(i=0; i<p->nId; i++){
1799 struct IdList_item *pNewItem = &pNew->a[i];
1800 const struct IdList_item *pOldItem = &p->a[i];
1801 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1802 pNewItem->u4 = pOldItem->u4;
1804 return pNew;
1806 Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){
1807 Select *pRet = 0;
1808 Select *pNext = 0;
1809 Select **pp = &pRet;
1810 const Select *p;
1812 assert( db!=0 );
1813 for(p=pDup; p; p=p->pPrior){
1814 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1815 if( pNew==0 ) break;
1816 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1817 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1818 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1819 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1820 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1821 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1822 pNew->op = p->op;
1823 pNew->pNext = pNext;
1824 pNew->pPrior = 0;
1825 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1826 pNew->iLimit = 0;
1827 pNew->iOffset = 0;
1828 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1829 pNew->addrOpenEphm[0] = -1;
1830 pNew->addrOpenEphm[1] = -1;
1831 pNew->nSelectRow = p->nSelectRow;
1832 pNew->pWith = sqlite3WithDup(db, p->pWith);
1833 #ifndef SQLITE_OMIT_WINDOWFUNC
1834 pNew->pWin = 0;
1835 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1836 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1837 #endif
1838 pNew->selId = p->selId;
1839 if( db->mallocFailed ){
1840 /* Any prior OOM might have left the Select object incomplete.
1841 ** Delete the whole thing rather than allow an incomplete Select
1842 ** to be used by the code generator. */
1843 pNew->pNext = 0;
1844 sqlite3SelectDelete(db, pNew);
1845 break;
1847 *pp = pNew;
1848 pp = &pNew->pPrior;
1849 pNext = pNew;
1852 return pRet;
1854 #else
1855 Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){
1856 assert( p==0 );
1857 return 0;
1859 #endif
1863 ** Add a new element to the end of an expression list. If pList is
1864 ** initially NULL, then create a new expression list.
1866 ** The pList argument must be either NULL or a pointer to an ExprList
1867 ** obtained from a prior call to sqlite3ExprListAppend(). This routine
1868 ** may not be used with an ExprList obtained from sqlite3ExprListDup().
1869 ** Reason: This routine assumes that the number of slots in pList->a[]
1870 ** is a power of two. That is true for sqlite3ExprListAppend() returns
1871 ** but is not necessarily true from the return value of sqlite3ExprListDup().
1873 ** If a memory allocation error occurs, the entire list is freed and
1874 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1875 ** that the new entry was successfully appended.
1877 static const struct ExprList_item zeroItem = {0};
1878 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
1879 sqlite3 *db, /* Database handle. Used for memory allocation */
1880 Expr *pExpr /* Expression to be appended. Might be NULL */
1882 struct ExprList_item *pItem;
1883 ExprList *pList;
1885 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
1886 if( pList==0 ){
1887 sqlite3ExprDelete(db, pExpr);
1888 return 0;
1890 pList->nAlloc = 4;
1891 pList->nExpr = 1;
1892 pItem = &pList->a[0];
1893 *pItem = zeroItem;
1894 pItem->pExpr = pExpr;
1895 return pList;
1897 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
1898 sqlite3 *db, /* Database handle. Used for memory allocation */
1899 ExprList *pList, /* List to which to append. Might be NULL */
1900 Expr *pExpr /* Expression to be appended. Might be NULL */
1902 struct ExprList_item *pItem;
1903 ExprList *pNew;
1904 pList->nAlloc *= 2;
1905 pNew = sqlite3DbRealloc(db, pList,
1906 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
1907 if( pNew==0 ){
1908 sqlite3ExprListDelete(db, pList);
1909 sqlite3ExprDelete(db, pExpr);
1910 return 0;
1911 }else{
1912 pList = pNew;
1914 pItem = &pList->a[pList->nExpr++];
1915 *pItem = zeroItem;
1916 pItem->pExpr = pExpr;
1917 return pList;
1919 ExprList *sqlite3ExprListAppend(
1920 Parse *pParse, /* Parsing context */
1921 ExprList *pList, /* List to which to append. Might be NULL */
1922 Expr *pExpr /* Expression to be appended. Might be NULL */
1924 struct ExprList_item *pItem;
1925 if( pList==0 ){
1926 return sqlite3ExprListAppendNew(pParse->db,pExpr);
1928 if( pList->nAlloc<pList->nExpr+1 ){
1929 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
1931 pItem = &pList->a[pList->nExpr++];
1932 *pItem = zeroItem;
1933 pItem->pExpr = pExpr;
1934 return pList;
1938 ** pColumns and pExpr form a vector assignment which is part of the SET
1939 ** clause of an UPDATE statement. Like this:
1941 ** (a,b,c) = (expr1,expr2,expr3)
1942 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1944 ** For each term of the vector assignment, append new entries to the
1945 ** expression list pList. In the case of a subquery on the RHS, append
1946 ** TK_SELECT_COLUMN expressions.
1948 ExprList *sqlite3ExprListAppendVector(
1949 Parse *pParse, /* Parsing context */
1950 ExprList *pList, /* List to which to append. Might be NULL */
1951 IdList *pColumns, /* List of names of LHS of the assignment */
1952 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1954 sqlite3 *db = pParse->db;
1955 int n;
1956 int i;
1957 int iFirst = pList ? pList->nExpr : 0;
1958 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1959 ** exit prior to this routine being invoked */
1960 if( NEVER(pColumns==0) ) goto vector_append_error;
1961 if( pExpr==0 ) goto vector_append_error;
1963 /* If the RHS is a vector, then we can immediately check to see that
1964 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
1965 ** wildcards ("*") in the result set of the SELECT must be expanded before
1966 ** we can do the size check, so defer the size check until code generation.
1968 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1969 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1970 pColumns->nId, n);
1971 goto vector_append_error;
1974 for(i=0; i<pColumns->nId; i++){
1975 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
1976 assert( pSubExpr!=0 || db->mallocFailed );
1977 if( pSubExpr==0 ) continue;
1978 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1979 if( pList ){
1980 assert( pList->nExpr==iFirst+i+1 );
1981 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
1982 pColumns->a[i].zName = 0;
1986 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
1987 Expr *pFirst = pList->a[iFirst].pExpr;
1988 assert( pFirst!=0 );
1989 assert( pFirst->op==TK_SELECT_COLUMN );
1991 /* Store the SELECT statement in pRight so it will be deleted when
1992 ** sqlite3ExprListDelete() is called */
1993 pFirst->pRight = pExpr;
1994 pExpr = 0;
1996 /* Remember the size of the LHS in iTable so that we can check that
1997 ** the RHS and LHS sizes match during code generation. */
1998 pFirst->iTable = pColumns->nId;
2001 vector_append_error:
2002 sqlite3ExprUnmapAndDelete(pParse, pExpr);
2003 sqlite3IdListDelete(db, pColumns);
2004 return pList;
2008 ** Set the sort order for the last element on the given ExprList.
2010 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
2011 struct ExprList_item *pItem;
2012 if( p==0 ) return;
2013 assert( p->nExpr>0 );
2015 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
2016 assert( iSortOrder==SQLITE_SO_UNDEFINED
2017 || iSortOrder==SQLITE_SO_ASC
2018 || iSortOrder==SQLITE_SO_DESC
2020 assert( eNulls==SQLITE_SO_UNDEFINED
2021 || eNulls==SQLITE_SO_ASC
2022 || eNulls==SQLITE_SO_DESC
2025 pItem = &p->a[p->nExpr-1];
2026 assert( pItem->fg.bNulls==0 );
2027 if( iSortOrder==SQLITE_SO_UNDEFINED ){
2028 iSortOrder = SQLITE_SO_ASC;
2030 pItem->fg.sortFlags = (u8)iSortOrder;
2032 if( eNulls!=SQLITE_SO_UNDEFINED ){
2033 pItem->fg.bNulls = 1;
2034 if( iSortOrder!=eNulls ){
2035 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
2041 ** Set the ExprList.a[].zEName element of the most recently added item
2042 ** on the expression list.
2044 ** pList might be NULL following an OOM error. But pName should never be
2045 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2046 ** is set.
2048 void sqlite3ExprListSetName(
2049 Parse *pParse, /* Parsing context */
2050 ExprList *pList, /* List to which to add the span. */
2051 const Token *pName, /* Name to be added */
2052 int dequote /* True to cause the name to be dequoted */
2054 assert( pList!=0 || pParse->db->mallocFailed!=0 );
2055 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
2056 if( pList ){
2057 struct ExprList_item *pItem;
2058 assert( pList->nExpr>0 );
2059 pItem = &pList->a[pList->nExpr-1];
2060 assert( pItem->zEName==0 );
2061 assert( pItem->fg.eEName==ENAME_NAME );
2062 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
2063 if( dequote ){
2064 /* If dequote==0, then pName->z does not point to part of a DDL
2065 ** statement handled by the parser. And so no token need be added
2066 ** to the token-map. */
2067 sqlite3Dequote(pItem->zEName);
2068 if( IN_RENAME_OBJECT ){
2069 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
2076 ** Set the ExprList.a[].zSpan element of the most recently added item
2077 ** on the expression list.
2079 ** pList might be NULL following an OOM error. But pSpan should never be
2080 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2081 ** is set.
2083 void sqlite3ExprListSetSpan(
2084 Parse *pParse, /* Parsing context */
2085 ExprList *pList, /* List to which to add the span. */
2086 const char *zStart, /* Start of the span */
2087 const char *zEnd /* End of the span */
2089 sqlite3 *db = pParse->db;
2090 assert( pList!=0 || db->mallocFailed!=0 );
2091 if( pList ){
2092 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
2093 assert( pList->nExpr>0 );
2094 if( pItem->zEName==0 ){
2095 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
2096 pItem->fg.eEName = ENAME_SPAN;
2102 ** If the expression list pEList contains more than iLimit elements,
2103 ** leave an error message in pParse.
2105 void sqlite3ExprListCheckLength(
2106 Parse *pParse,
2107 ExprList *pEList,
2108 const char *zObject
2110 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
2111 testcase( pEList && pEList->nExpr==mx );
2112 testcase( pEList && pEList->nExpr==mx+1 );
2113 if( pEList && pEList->nExpr>mx ){
2114 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
2119 ** Delete an entire expression list.
2121 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
2122 int i = pList->nExpr;
2123 struct ExprList_item *pItem = pList->a;
2124 assert( pList->nExpr>0 );
2125 assert( db!=0 );
2127 sqlite3ExprDelete(db, pItem->pExpr);
2128 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
2129 pItem++;
2130 }while( --i>0 );
2131 sqlite3DbNNFreeNN(db, pList);
2133 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
2134 if( pList ) exprListDeleteNN(db, pList);
2138 ** Return the bitwise-OR of all Expr.flags fields in the given
2139 ** ExprList.
2141 u32 sqlite3ExprListFlags(const ExprList *pList){
2142 int i;
2143 u32 m = 0;
2144 assert( pList!=0 );
2145 for(i=0; i<pList->nExpr; i++){
2146 Expr *pExpr = pList->a[i].pExpr;
2147 assert( pExpr!=0 );
2148 m |= pExpr->flags;
2150 return m;
2154 ** This is a SELECT-node callback for the expression walker that
2155 ** always "fails". By "fail" in this case, we mean set
2156 ** pWalker->eCode to zero and abort.
2158 ** This callback is used by multiple expression walkers.
2160 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
2161 UNUSED_PARAMETER(NotUsed);
2162 pWalker->eCode = 0;
2163 return WRC_Abort;
2167 ** Check the input string to see if it is "true" or "false" (in any case).
2169 ** If the string is.... Return
2170 ** "true" EP_IsTrue
2171 ** "false" EP_IsFalse
2172 ** anything else 0
2174 u32 sqlite3IsTrueOrFalse(const char *zIn){
2175 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
2176 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
2177 return 0;
2182 ** If the input expression is an ID with the name "true" or "false"
2183 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2184 ** the conversion happened, and zero if the expression is unaltered.
2186 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
2187 u32 v;
2188 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
2189 if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue)
2190 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
2192 pExpr->op = TK_TRUEFALSE;
2193 ExprSetProperty(pExpr, v);
2194 return 1;
2196 return 0;
2200 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2201 ** and 0 if it is FALSE.
2203 int sqlite3ExprTruthValue(const Expr *pExpr){
2204 pExpr = sqlite3ExprSkipCollateAndLikely((Expr*)pExpr);
2205 assert( pExpr->op==TK_TRUEFALSE );
2206 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2207 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
2208 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
2209 return pExpr->u.zToken[4]==0;
2213 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2214 ** terms that are always true or false. Return the simplified expression.
2215 ** Or return the original expression if no simplification is possible.
2217 ** Examples:
2219 ** (x<10) AND true => (x<10)
2220 ** (x<10) AND false => false
2221 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2222 ** (x<10) AND (y=22 OR true) => (x<10)
2223 ** (y=22) OR true => true
2225 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
2226 assert( pExpr!=0 );
2227 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
2228 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
2229 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
2230 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
2231 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
2232 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
2233 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
2236 return pExpr;
2241 ** These routines are Walker callbacks used to check expressions to
2242 ** see if they are "constant" for some definition of constant. The
2243 ** Walker.eCode value determines the type of "constant" we are looking
2244 ** for.
2246 ** These callback routines are used to implement the following:
2248 ** sqlite3ExprIsConstant() pWalker->eCode==1
2249 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2250 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2251 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2253 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2254 ** is found to not be a constant.
2256 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2257 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2258 ** when parsing an existing schema out of the sqlite_schema table and 4
2259 ** when processing a new CREATE TABLE statement. A bound parameter raises
2260 ** an error for new statements, but is silently converted
2261 ** to NULL for existing schemas. This allows sqlite_schema tables that
2262 ** contain a bound parameter because they were generated by older versions
2263 ** of SQLite to be parsed by newer versions of SQLite without raising a
2264 ** malformed schema error.
2266 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
2268 /* If pWalker->eCode is 2 then any term of the expression that comes from
2269 ** the ON or USING clauses of an outer join disqualifies the expression
2270 ** from being considered constant. */
2271 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
2272 pWalker->eCode = 0;
2273 return WRC_Abort;
2276 switch( pExpr->op ){
2277 /* Consider functions to be constant if all their arguments are constant
2278 ** and either pWalker->eCode==4 or 5 or the function has the
2279 ** SQLITE_FUNC_CONST flag. */
2280 case TK_FUNCTION:
2281 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2282 && !ExprHasProperty(pExpr, EP_WinFunc)
2284 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2285 return WRC_Continue;
2286 }else{
2287 pWalker->eCode = 0;
2288 return WRC_Abort;
2290 case TK_ID:
2291 /* Convert "true" or "false" in a DEFAULT clause into the
2292 ** appropriate TK_TRUEFALSE operator */
2293 if( sqlite3ExprIdToTrueFalse(pExpr) ){
2294 return WRC_Prune;
2296 /* no break */ deliberate_fall_through
2297 case TK_COLUMN:
2298 case TK_AGG_FUNCTION:
2299 case TK_AGG_COLUMN:
2300 testcase( pExpr->op==TK_ID );
2301 testcase( pExpr->op==TK_COLUMN );
2302 testcase( pExpr->op==TK_AGG_FUNCTION );
2303 testcase( pExpr->op==TK_AGG_COLUMN );
2304 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2305 return WRC_Continue;
2307 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2308 return WRC_Continue;
2310 /* no break */ deliberate_fall_through
2311 case TK_IF_NULL_ROW:
2312 case TK_REGISTER:
2313 case TK_DOT:
2314 testcase( pExpr->op==TK_REGISTER );
2315 testcase( pExpr->op==TK_IF_NULL_ROW );
2316 testcase( pExpr->op==TK_DOT );
2317 pWalker->eCode = 0;
2318 return WRC_Abort;
2319 case TK_VARIABLE:
2320 if( pWalker->eCode==5 ){
2321 /* Silently convert bound parameters that appear inside of CREATE
2322 ** statements into a NULL when parsing the CREATE statement text out
2323 ** of the sqlite_schema table */
2324 pExpr->op = TK_NULL;
2325 }else if( pWalker->eCode==4 ){
2326 /* A bound parameter in a CREATE statement that originates from
2327 ** sqlite3_prepare() causes an error */
2328 pWalker->eCode = 0;
2329 return WRC_Abort;
2331 /* no break */ deliberate_fall_through
2332 default:
2333 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2334 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2335 return WRC_Continue;
2338 static int exprIsConst(Expr *p, int initFlag, int iCur){
2339 Walker w;
2340 w.eCode = initFlag;
2341 w.xExprCallback = exprNodeIsConstant;
2342 w.xSelectCallback = sqlite3SelectWalkFail;
2343 #ifdef SQLITE_DEBUG
2344 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2345 #endif
2346 w.u.iCur = iCur;
2347 sqlite3WalkExpr(&w, p);
2348 return w.eCode;
2352 ** Walk an expression tree. Return non-zero if the expression is constant
2353 ** and 0 if it involves variables or function calls.
2355 ** For the purposes of this function, a double-quoted string (ex: "abc")
2356 ** is considered a variable but a single-quoted string (ex: 'abc') is
2357 ** a constant.
2359 int sqlite3ExprIsConstant(Expr *p){
2360 return exprIsConst(p, 1, 0);
2364 ** Walk an expression tree. Return non-zero if
2366 ** (1) the expression is constant, and
2367 ** (2) the expression does originate in the ON or USING clause
2368 ** of a LEFT JOIN, and
2369 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2370 ** operands created by the constant propagation optimization.
2372 ** When this routine returns true, it indicates that the expression
2373 ** can be added to the pParse->pConstExpr list and evaluated once when
2374 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2376 int sqlite3ExprIsConstantNotJoin(Expr *p){
2377 return exprIsConst(p, 2, 0);
2381 ** Walk an expression tree. Return non-zero if the expression is constant
2382 ** for any single row of the table with cursor iCur. In other words, the
2383 ** expression must not refer to any non-deterministic function nor any
2384 ** table other than iCur.
2386 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2387 return exprIsConst(p, 3, iCur);
2391 ** Check pExpr to see if it is an constraint on the single data source
2392 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2393 ** constrains pSrc but does not depend on any other tables or data
2394 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2395 ** is a constraint on pSrc only.
2397 ** This is an optimization. False negatives will perhaps cause slower
2398 ** queries, but false positives will yield incorrect answers. So when in
2399 ** doubt, return 0.
2401 ** To be an single-source constraint, the following must be true:
2403 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2405 ** (2) pExpr cannot use subqueries or non-deterministic functions.
2407 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2408 ** (Is there some way to relax this constraint?)
2410 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2411 ** (4a) pExpr must come from an ON clause..
2412 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2414 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2415 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2416 ** clause, not an ON clause.
2418 ** (6) Either:
2420 ** (6a) pExpr does not originate in an ON or USING clause, or
2422 ** (6b) The ON or USING clause from which pExpr is derived is
2423 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2425 ** Without this restriction, accepting pExpr as a single-table
2426 ** constraint might move the the ON/USING filter expression
2427 ** from the left side of a RIGHT JOIN over to the right side,
2428 ** which leads to incorrect answers. See also restriction (9)
2429 ** on push-down.
2431 int sqlite3ExprIsSingleTableConstraint(
2432 Expr *pExpr, /* The constraint */
2433 const SrcList *pSrcList, /* Complete FROM clause */
2434 int iSrc /* Which element of pSrcList to use */
2436 const SrcItem *pSrc = &pSrcList->a[iSrc];
2437 if( pSrc->fg.jointype & JT_LTORJ ){
2438 return 0; /* rule (3) */
2440 if( pSrc->fg.jointype & JT_LEFT ){
2441 if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (4a) */
2442 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */
2443 }else{
2444 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (5) */
2446 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) /* (6a) */
2447 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */
2449 int jj;
2450 for(jj=0; jj<iSrc; jj++){
2451 if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
2452 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
2453 return 0; /* restriction (6) */
2455 break;
2459 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor); /* rules (1), (2) */
2464 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2466 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2467 ExprList *pGroupBy = pWalker->u.pGroupBy;
2468 int i;
2470 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2471 ** it constant. */
2472 for(i=0; i<pGroupBy->nExpr; i++){
2473 Expr *p = pGroupBy->a[i].pExpr;
2474 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2475 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2476 if( sqlite3IsBinary(pColl) ){
2477 return WRC_Prune;
2482 /* Check if pExpr is a sub-select. If so, consider it variable. */
2483 if( ExprUseXSelect(pExpr) ){
2484 pWalker->eCode = 0;
2485 return WRC_Abort;
2488 return exprNodeIsConstant(pWalker, pExpr);
2492 ** Walk the expression tree passed as the first argument. Return non-zero
2493 ** if the expression consists entirely of constants or copies of terms
2494 ** in pGroupBy that sort with the BINARY collation sequence.
2496 ** This routine is used to determine if a term of the HAVING clause can
2497 ** be promoted into the WHERE clause. In order for such a promotion to work,
2498 ** the value of the HAVING clause term must be the same for all members of
2499 ** a "group". The requirement that the GROUP BY term must be BINARY
2500 ** assumes that no other collating sequence will have a finer-grained
2501 ** grouping than binary. In other words (A=B COLLATE binary) implies
2502 ** A=B in every other collating sequence. The requirement that the
2503 ** GROUP BY be BINARY is stricter than necessary. It would also work
2504 ** to promote HAVING clauses that use the same alternative collating
2505 ** sequence as the GROUP BY term, but that is much harder to check,
2506 ** alternative collating sequences are uncommon, and this is only an
2507 ** optimization, so we take the easy way out and simply require the
2508 ** GROUP BY to use the BINARY collating sequence.
2510 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2511 Walker w;
2512 w.eCode = 1;
2513 w.xExprCallback = exprNodeIsConstantOrGroupBy;
2514 w.xSelectCallback = 0;
2515 w.u.pGroupBy = pGroupBy;
2516 w.pParse = pParse;
2517 sqlite3WalkExpr(&w, p);
2518 return w.eCode;
2522 ** Walk an expression tree for the DEFAULT field of a column definition
2523 ** in a CREATE TABLE statement. Return non-zero if the expression is
2524 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2525 ** the expression is constant or a function call with constant arguments.
2526 ** Return and 0 if there are any variables.
2528 ** isInit is true when parsing from sqlite_schema. isInit is false when
2529 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2530 ** (such as ? or $abc) in the expression are converted into NULL. When
2531 ** isInit is false, parameters raise an error. Parameters should not be
2532 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2533 ** allowed it, so we need to support it when reading sqlite_schema for
2534 ** backwards compatibility.
2536 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2538 ** For the purposes of this function, a double-quoted string (ex: "abc")
2539 ** is considered a variable but a single-quoted string (ex: 'abc') is
2540 ** a constant.
2542 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2543 assert( isInit==0 || isInit==1 );
2544 return exprIsConst(p, 4+isInit, 0);
2547 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2549 ** Walk an expression tree. Return 1 if the expression contains a
2550 ** subquery of some kind. Return 0 if there are no subqueries.
2552 int sqlite3ExprContainsSubquery(Expr *p){
2553 Walker w;
2554 w.eCode = 1;
2555 w.xExprCallback = sqlite3ExprWalkNoop;
2556 w.xSelectCallback = sqlite3SelectWalkFail;
2557 #ifdef SQLITE_DEBUG
2558 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2559 #endif
2560 sqlite3WalkExpr(&w, p);
2561 return w.eCode==0;
2563 #endif
2566 ** If the expression p codes a constant integer that is small enough
2567 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2568 ** in *pValue. If the expression is not an integer or if it is too big
2569 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2571 int sqlite3ExprIsInteger(const Expr *p, int *pValue){
2572 int rc = 0;
2573 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
2575 /* If an expression is an integer literal that fits in a signed 32-bit
2576 ** integer, then the EP_IntValue flag will have already been set */
2577 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2578 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2580 if( p->flags & EP_IntValue ){
2581 *pValue = p->u.iValue;
2582 return 1;
2584 switch( p->op ){
2585 case TK_UPLUS: {
2586 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
2587 break;
2589 case TK_UMINUS: {
2590 int v = 0;
2591 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
2592 assert( ((unsigned int)v)!=0x80000000 );
2593 *pValue = -v;
2594 rc = 1;
2596 break;
2598 default: break;
2600 return rc;
2604 ** Return FALSE if there is no chance that the expression can be NULL.
2606 ** If the expression might be NULL or if the expression is too complex
2607 ** to tell return TRUE.
2609 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2610 ** when we know that a value cannot be NULL. Hence, a false positive
2611 ** (returning TRUE when in fact the expression can never be NULL) might
2612 ** be a small performance hit but is otherwise harmless. On the other
2613 ** hand, a false negative (returning FALSE when the result could be NULL)
2614 ** will likely result in an incorrect answer. So when in doubt, return
2615 ** TRUE.
2617 int sqlite3ExprCanBeNull(const Expr *p){
2618 u8 op;
2619 assert( p!=0 );
2620 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2621 p = p->pLeft;
2622 assert( p!=0 );
2624 op = p->op;
2625 if( op==TK_REGISTER ) op = p->op2;
2626 switch( op ){
2627 case TK_INTEGER:
2628 case TK_STRING:
2629 case TK_FLOAT:
2630 case TK_BLOB:
2631 return 0;
2632 case TK_COLUMN:
2633 assert( ExprUseYTab(p) );
2634 return ExprHasProperty(p, EP_CanBeNull) ||
2635 p->y.pTab==0 || /* Reference to column of index on expression */
2636 (p->iColumn>=0
2637 && p->y.pTab->aCol!=0 /* Possible due to prior error */
2638 && p->y.pTab->aCol[p->iColumn].notNull==0);
2639 default:
2640 return 1;
2645 ** Return TRUE if the given expression is a constant which would be
2646 ** unchanged by OP_Affinity with the affinity given in the second
2647 ** argument.
2649 ** This routine is used to determine if the OP_Affinity operation
2650 ** can be omitted. When in doubt return FALSE. A false negative
2651 ** is harmless. A false positive, however, can result in the wrong
2652 ** answer.
2654 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2655 u8 op;
2656 int unaryMinus = 0;
2657 if( aff==SQLITE_AFF_BLOB ) return 1;
2658 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2659 if( p->op==TK_UMINUS ) unaryMinus = 1;
2660 p = p->pLeft;
2662 op = p->op;
2663 if( op==TK_REGISTER ) op = p->op2;
2664 switch( op ){
2665 case TK_INTEGER: {
2666 return aff>=SQLITE_AFF_NUMERIC;
2668 case TK_FLOAT: {
2669 return aff>=SQLITE_AFF_NUMERIC;
2671 case TK_STRING: {
2672 return !unaryMinus && aff==SQLITE_AFF_TEXT;
2674 case TK_BLOB: {
2675 return !unaryMinus;
2677 case TK_COLUMN: {
2678 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2679 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2681 default: {
2682 return 0;
2688 ** Return TRUE if the given string is a row-id column name.
2690 int sqlite3IsRowid(const char *z){
2691 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2692 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2693 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2694 return 0;
2698 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2699 ** that can be simplified to a direct table access, then return
2700 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2701 ** or if the SELECT statement needs to be materialized into a transient
2702 ** table, then return NULL.
2704 #ifndef SQLITE_OMIT_SUBQUERY
2705 static Select *isCandidateForInOpt(const Expr *pX){
2706 Select *p;
2707 SrcList *pSrc;
2708 ExprList *pEList;
2709 Table *pTab;
2710 int i;
2711 if( !ExprUseXSelect(pX) ) return 0; /* Not a subquery */
2712 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
2713 p = pX->x.pSelect;
2714 if( p->pPrior ) return 0; /* Not a compound SELECT */
2715 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2716 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2717 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2718 return 0; /* No DISTINCT keyword and no aggregate functions */
2720 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
2721 if( p->pLimit ) return 0; /* Has no LIMIT clause */
2722 if( p->pWhere ) return 0; /* Has no WHERE clause */
2723 pSrc = p->pSrc;
2724 assert( pSrc!=0 );
2725 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
2726 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
2727 pTab = pSrc->a[0].pTab;
2728 assert( pTab!=0 );
2729 assert( !IsView(pTab) ); /* FROM clause is not a view */
2730 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
2731 pEList = p->pEList;
2732 assert( pEList!=0 );
2733 /* All SELECT results must be columns. */
2734 for(i=0; i<pEList->nExpr; i++){
2735 Expr *pRes = pEList->a[i].pExpr;
2736 if( pRes->op!=TK_COLUMN ) return 0;
2737 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
2739 return p;
2741 #endif /* SQLITE_OMIT_SUBQUERY */
2743 #ifndef SQLITE_OMIT_SUBQUERY
2745 ** Generate code that checks the left-most column of index table iCur to see if
2746 ** it contains any NULL entries. Cause the register at regHasNull to be set
2747 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2748 ** to be set to NULL if iCur contains one or more NULL values.
2750 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2751 int addr1;
2752 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2753 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2754 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2755 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2756 VdbeComment((v, "first_entry_in(%d)", iCur));
2757 sqlite3VdbeJumpHere(v, addr1);
2759 #endif
2762 #ifndef SQLITE_OMIT_SUBQUERY
2764 ** The argument is an IN operator with a list (not a subquery) on the
2765 ** right-hand side. Return TRUE if that list is constant.
2767 static int sqlite3InRhsIsConstant(Expr *pIn){
2768 Expr *pLHS;
2769 int res;
2770 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2771 pLHS = pIn->pLeft;
2772 pIn->pLeft = 0;
2773 res = sqlite3ExprIsConstant(pIn);
2774 pIn->pLeft = pLHS;
2775 return res;
2777 #endif
2780 ** This function is used by the implementation of the IN (...) operator.
2781 ** The pX parameter is the expression on the RHS of the IN operator, which
2782 ** might be either a list of expressions or a subquery.
2784 ** The job of this routine is to find or create a b-tree object that can
2785 ** be used either to test for membership in the RHS set or to iterate through
2786 ** all members of the RHS set, skipping duplicates.
2788 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2789 ** and the *piTab parameter is set to the index of that cursor.
2791 ** The returned value of this function indicates the b-tree type, as follows:
2793 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2794 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2795 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2796 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2797 ** populated ephemeral table.
2798 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2799 ** implemented as a sequence of comparisons.
2801 ** An existing b-tree might be used if the RHS expression pX is a simple
2802 ** subquery such as:
2804 ** SELECT <column1>, <column2>... FROM <table>
2806 ** If the RHS of the IN operator is a list or a more complex subquery, then
2807 ** an ephemeral table might need to be generated from the RHS and then
2808 ** pX->iTable made to point to the ephemeral table instead of an
2809 ** existing table. In this case, the creation and initialization of the
2810 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
2811 ** will be set on pX and the pX->y.sub fields will be set to show where
2812 ** the subroutine is coded.
2814 ** The inFlags parameter must contain, at a minimum, one of the bits
2815 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2816 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2817 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2818 ** be used to loop over all values of the RHS of the IN operator.
2820 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2821 ** through the set members) then the b-tree must not contain duplicates.
2822 ** An ephemeral table will be created unless the selected columns are guaranteed
2823 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2824 ** a UNIQUE constraint or index.
2826 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2827 ** for fast set membership tests) then an ephemeral table must
2828 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2829 ** index can be found with the specified <columns> as its left-most.
2831 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2832 ** if the RHS of the IN operator is a list (not a subquery) then this
2833 ** routine might decide that creating an ephemeral b-tree for membership
2834 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2835 ** calling routine should implement the IN operator using a sequence
2836 ** of Eq or Ne comparison operations.
2838 ** When the b-tree is being used for membership tests, the calling function
2839 ** might need to know whether or not the RHS side of the IN operator
2840 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2841 ** if there is any chance that the (...) might contain a NULL value at
2842 ** runtime, then a register is allocated and the register number written
2843 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2844 ** NULL value, then *prRhsHasNull is left unchanged.
2846 ** If a register is allocated and its location stored in *prRhsHasNull, then
2847 ** the value in that register will be NULL if the b-tree contains one or more
2848 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2849 ** NULL values.
2851 ** If the aiMap parameter is not NULL, it must point to an array containing
2852 ** one element for each column returned by the SELECT statement on the RHS
2853 ** of the IN(...) operator. The i'th entry of the array is populated with the
2854 ** offset of the index column that matches the i'th column returned by the
2855 ** SELECT. For example, if the expression and selected index are:
2857 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2858 ** CREATE INDEX i1 ON t1(b, c, a);
2860 ** then aiMap[] is populated with {2, 0, 1}.
2862 #ifndef SQLITE_OMIT_SUBQUERY
2863 int sqlite3FindInIndex(
2864 Parse *pParse, /* Parsing context */
2865 Expr *pX, /* The IN expression */
2866 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2867 int *prRhsHasNull, /* Register holding NULL status. See notes */
2868 int *aiMap, /* Mapping from Index fields to RHS fields */
2869 int *piTab /* OUT: index to use */
2871 Select *p; /* SELECT to the right of IN operator */
2872 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2873 int iTab; /* Cursor of the RHS table */
2874 int mustBeUnique; /* True if RHS must be unique */
2875 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
2877 assert( pX->op==TK_IN );
2878 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
2879 iTab = pParse->nTab++;
2881 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2882 ** whether or not the SELECT result contains NULL values, check whether
2883 ** or not NULL is actually possible (it may not be, for example, due
2884 ** to NOT NULL constraints in the schema). If no NULL values are possible,
2885 ** set prRhsHasNull to 0 before continuing. */
2886 if( prRhsHasNull && ExprUseXSelect(pX) ){
2887 int i;
2888 ExprList *pEList = pX->x.pSelect->pEList;
2889 for(i=0; i<pEList->nExpr; i++){
2890 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2892 if( i==pEList->nExpr ){
2893 prRhsHasNull = 0;
2897 /* Check to see if an existing table or index can be used to
2898 ** satisfy the query. This is preferable to generating a new
2899 ** ephemeral table. */
2900 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2901 sqlite3 *db = pParse->db; /* Database connection */
2902 Table *pTab; /* Table <table>. */
2903 int iDb; /* Database idx for pTab */
2904 ExprList *pEList = p->pEList;
2905 int nExpr = pEList->nExpr;
2907 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2908 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2909 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2910 pTab = p->pSrc->a[0].pTab;
2912 /* Code an OP_Transaction and OP_TableLock for <table>. */
2913 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2914 assert( iDb>=0 && iDb<SQLITE_MAX_DB );
2915 sqlite3CodeVerifySchema(pParse, iDb);
2916 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2918 assert(v); /* sqlite3GetVdbe() has always been previously called */
2919 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
2920 /* The "x IN (SELECT rowid FROM table)" case */
2921 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
2922 VdbeCoverage(v);
2924 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2925 eType = IN_INDEX_ROWID;
2926 ExplainQueryPlan((pParse, 0,
2927 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
2928 sqlite3VdbeJumpHere(v, iAddr);
2929 }else{
2930 Index *pIdx; /* Iterator variable */
2931 int affinity_ok = 1;
2932 int i;
2934 /* Check that the affinity that will be used to perform each
2935 ** comparison is the same as the affinity of each column in table
2936 ** on the RHS of the IN operator. If it not, it is not possible to
2937 ** use any index of the RHS table. */
2938 for(i=0; i<nExpr && affinity_ok; i++){
2939 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2940 int iCol = pEList->a[i].pExpr->iColumn;
2941 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2942 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2943 testcase( cmpaff==SQLITE_AFF_BLOB );
2944 testcase( cmpaff==SQLITE_AFF_TEXT );
2945 switch( cmpaff ){
2946 case SQLITE_AFF_BLOB:
2947 break;
2948 case SQLITE_AFF_TEXT:
2949 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2950 ** other has no affinity and the other side is TEXT. Hence,
2951 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2952 ** and for the term on the LHS of the IN to have no affinity. */
2953 assert( idxaff==SQLITE_AFF_TEXT );
2954 break;
2955 default:
2956 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2960 if( affinity_ok ){
2961 /* Search for an existing index that will work for this IN operator */
2962 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2963 Bitmask colUsed; /* Columns of the index used */
2964 Bitmask mCol; /* Mask for the current column */
2965 if( pIdx->nColumn<nExpr ) continue;
2966 if( pIdx->pPartIdxWhere!=0 ) continue;
2967 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2968 ** BITMASK(nExpr) without overflowing */
2969 testcase( pIdx->nColumn==BMS-2 );
2970 testcase( pIdx->nColumn==BMS-1 );
2971 if( pIdx->nColumn>=BMS-1 ) continue;
2972 if( mustBeUnique ){
2973 if( pIdx->nKeyCol>nExpr
2974 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2976 continue; /* This index is not unique over the IN RHS columns */
2980 colUsed = 0; /* Columns of index used so far */
2981 for(i=0; i<nExpr; i++){
2982 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2983 Expr *pRhs = pEList->a[i].pExpr;
2984 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2985 int j;
2987 for(j=0; j<nExpr; j++){
2988 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2989 assert( pIdx->azColl[j] );
2990 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2991 continue;
2993 break;
2995 if( j==nExpr ) break;
2996 mCol = MASKBIT(j);
2997 if( mCol & colUsed ) break; /* Each column used only once */
2998 colUsed |= mCol;
2999 if( aiMap ) aiMap[i] = j;
3002 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
3003 if( colUsed==(MASKBIT(nExpr)-1) ){
3004 /* If we reach this point, that means the index pIdx is usable */
3005 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3006 ExplainQueryPlan((pParse, 0,
3007 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
3008 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
3009 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
3010 VdbeComment((v, "%s", pIdx->zName));
3011 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
3012 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
3014 if( prRhsHasNull ){
3015 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3016 i64 mask = (1<<nExpr)-1;
3017 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
3018 iTab, 0, 0, (u8*)&mask, P4_INT64);
3019 #endif
3020 *prRhsHasNull = ++pParse->nMem;
3021 if( nExpr==1 ){
3022 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
3025 sqlite3VdbeJumpHere(v, iAddr);
3027 } /* End loop over indexes */
3028 } /* End if( affinity_ok ) */
3029 } /* End if not an rowid index */
3030 } /* End attempt to optimize using an index */
3032 /* If no preexisting index is available for the IN clause
3033 ** and IN_INDEX_NOOP is an allowed reply
3034 ** and the RHS of the IN operator is a list, not a subquery
3035 ** and the RHS is not constant or has two or fewer terms,
3036 ** then it is not worth creating an ephemeral table to evaluate
3037 ** the IN operator so return IN_INDEX_NOOP.
3039 if( eType==0
3040 && (inFlags & IN_INDEX_NOOP_OK)
3041 && ExprUseXList(pX)
3042 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
3044 pParse->nTab--; /* Back out the allocation of the unused cursor */
3045 iTab = -1; /* Cursor is not allocated */
3046 eType = IN_INDEX_NOOP;
3049 if( eType==0 ){
3050 /* Could not find an existing table or index to use as the RHS b-tree.
3051 ** We will have to generate an ephemeral table to do the job.
3053 u32 savedNQueryLoop = pParse->nQueryLoop;
3054 int rMayHaveNull = 0;
3055 eType = IN_INDEX_EPH;
3056 if( inFlags & IN_INDEX_LOOP ){
3057 pParse->nQueryLoop = 0;
3058 }else if( prRhsHasNull ){
3059 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
3061 assert( pX->op==TK_IN );
3062 sqlite3CodeRhsOfIN(pParse, pX, iTab);
3063 if( rMayHaveNull ){
3064 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
3066 pParse->nQueryLoop = savedNQueryLoop;
3069 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
3070 int i, n;
3071 n = sqlite3ExprVectorSize(pX->pLeft);
3072 for(i=0; i<n; i++) aiMap[i] = i;
3074 *piTab = iTab;
3075 return eType;
3077 #endif
3079 #ifndef SQLITE_OMIT_SUBQUERY
3081 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3082 ** function allocates and returns a nul-terminated string containing
3083 ** the affinities to be used for each column of the comparison.
3085 ** It is the responsibility of the caller to ensure that the returned
3086 ** string is eventually freed using sqlite3DbFree().
3088 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
3089 Expr *pLeft = pExpr->pLeft;
3090 int nVal = sqlite3ExprVectorSize(pLeft);
3091 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
3092 char *zRet;
3094 assert( pExpr->op==TK_IN );
3095 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
3096 if( zRet ){
3097 int i;
3098 for(i=0; i<nVal; i++){
3099 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
3100 char a = sqlite3ExprAffinity(pA);
3101 if( pSelect ){
3102 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
3103 }else{
3104 zRet[i] = a;
3107 zRet[nVal] = '\0';
3109 return zRet;
3111 #endif
3113 #ifndef SQLITE_OMIT_SUBQUERY
3115 ** Load the Parse object passed as the first argument with an error
3116 ** message of the form:
3118 ** "sub-select returns N columns - expected M"
3120 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
3121 if( pParse->nErr==0 ){
3122 const char *zFmt = "sub-select returns %d columns - expected %d";
3123 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
3126 #endif
3129 ** Expression pExpr is a vector that has been used in a context where
3130 ** it is not permitted. If pExpr is a sub-select vector, this routine
3131 ** loads the Parse object with a message of the form:
3133 ** "sub-select returns N columns - expected 1"
3135 ** Or, if it is a regular scalar vector:
3137 ** "row value misused"
3139 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
3140 #ifndef SQLITE_OMIT_SUBQUERY
3141 if( ExprUseXSelect(pExpr) ){
3142 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
3143 }else
3144 #endif
3146 sqlite3ErrorMsg(pParse, "row value misused");
3150 #ifndef SQLITE_OMIT_SUBQUERY
3152 ** Generate code that will construct an ephemeral table containing all terms
3153 ** in the RHS of an IN operator. The IN operator can be in either of two
3154 ** forms:
3156 ** x IN (4,5,11) -- IN operator with list on right-hand side
3157 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3159 ** The pExpr parameter is the IN operator. The cursor number for the
3160 ** constructed ephemeral table is returned. The first time the ephemeral
3161 ** table is computed, the cursor number is also stored in pExpr->iTable,
3162 ** however the cursor number returned might not be the same, as it might
3163 ** have been duplicated using OP_OpenDup.
3165 ** If the LHS expression ("x" in the examples) is a column value, or
3166 ** the SELECT statement returns a column value, then the affinity of that
3167 ** column is used to build the index keys. If both 'x' and the
3168 ** SELECT... statement are columns, then numeric affinity is used
3169 ** if either column has NUMERIC or INTEGER affinity. If neither
3170 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3171 ** is used.
3173 void sqlite3CodeRhsOfIN(
3174 Parse *pParse, /* Parsing context */
3175 Expr *pExpr, /* The IN operator */
3176 int iTab /* Use this cursor number */
3178 int addrOnce = 0; /* Address of the OP_Once instruction at top */
3179 int addr; /* Address of OP_OpenEphemeral instruction */
3180 Expr *pLeft; /* the LHS of the IN operator */
3181 KeyInfo *pKeyInfo = 0; /* Key information */
3182 int nVal; /* Size of vector pLeft */
3183 Vdbe *v; /* The prepared statement under construction */
3185 v = pParse->pVdbe;
3186 assert( v!=0 );
3188 /* The evaluation of the IN must be repeated every time it
3189 ** is encountered if any of the following is true:
3191 ** * The right-hand side is a correlated subquery
3192 ** * The right-hand side is an expression list containing variables
3193 ** * We are inside a trigger
3195 ** If all of the above are false, then we can compute the RHS just once
3196 ** and reuse it many names.
3198 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
3199 /* Reuse of the RHS is allowed */
3200 /* If this routine has already been coded, but the previous code
3201 ** might not have been invoked yet, so invoke it now as a subroutine.
3203 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3204 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3205 if( ExprUseXSelect(pExpr) ){
3206 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
3207 pExpr->x.pSelect->selId));
3209 assert( ExprUseYSub(pExpr) );
3210 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3211 pExpr->y.sub.iAddr);
3212 assert( iTab!=pExpr->iTable );
3213 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
3214 sqlite3VdbeJumpHere(v, addrOnce);
3215 return;
3218 /* Begin coding the subroutine */
3219 assert( !ExprUseYWin(pExpr) );
3220 ExprSetProperty(pExpr, EP_Subrtn);
3221 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3222 pExpr->y.sub.regReturn = ++pParse->nMem;
3223 pExpr->y.sub.iAddr =
3224 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3226 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3229 /* Check to see if this is a vector IN operator */
3230 pLeft = pExpr->pLeft;
3231 nVal = sqlite3ExprVectorSize(pLeft);
3233 /* Construct the ephemeral table that will contain the content of
3234 ** RHS of the IN operator.
3236 pExpr->iTable = iTab;
3237 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
3238 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3239 if( ExprUseXSelect(pExpr) ){
3240 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
3241 }else{
3242 VdbeComment((v, "RHS of IN operator"));
3244 #endif
3245 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
3247 if( ExprUseXSelect(pExpr) ){
3248 /* Case 1: expr IN (SELECT ...)
3250 ** Generate code to write the results of the select into the temporary
3251 ** table allocated and opened above.
3253 Select *pSelect = pExpr->x.pSelect;
3254 ExprList *pEList = pSelect->pEList;
3256 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
3257 addrOnce?"":"CORRELATED ", pSelect->selId
3259 /* If the LHS and RHS of the IN operator do not match, that
3260 ** error will have been caught long before we reach this point. */
3261 if( ALWAYS(pEList->nExpr==nVal) ){
3262 Select *pCopy;
3263 SelectDest dest;
3264 int i;
3265 int rc;
3266 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
3267 dest.zAffSdst = exprINAffinity(pParse, pExpr);
3268 pSelect->iLimit = 0;
3269 testcase( pSelect->selFlags & SF_Distinct );
3270 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3271 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
3272 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
3273 sqlite3SelectDelete(pParse->db, pCopy);
3274 sqlite3DbFree(pParse->db, dest.zAffSdst);
3275 if( rc ){
3276 sqlite3KeyInfoUnref(pKeyInfo);
3277 return;
3279 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
3280 assert( pEList!=0 );
3281 assert( pEList->nExpr>0 );
3282 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3283 for(i=0; i<nVal; i++){
3284 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
3285 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
3286 pParse, p, pEList->a[i].pExpr
3290 }else if( ALWAYS(pExpr->x.pList!=0) ){
3291 /* Case 2: expr IN (exprlist)
3293 ** For each expression, build an index key from the evaluation and
3294 ** store it in the temporary table. If <expr> is a column, then use
3295 ** that columns affinity when building index keys. If <expr> is not
3296 ** a column, use numeric affinity.
3298 char affinity; /* Affinity of the LHS of the IN */
3299 int i;
3300 ExprList *pList = pExpr->x.pList;
3301 struct ExprList_item *pItem;
3302 int r1, r2;
3303 affinity = sqlite3ExprAffinity(pLeft);
3304 if( affinity<=SQLITE_AFF_NONE ){
3305 affinity = SQLITE_AFF_BLOB;
3306 }else if( affinity==SQLITE_AFF_REAL ){
3307 affinity = SQLITE_AFF_NUMERIC;
3309 if( pKeyInfo ){
3310 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3311 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3314 /* Loop through each expression in <exprlist>. */
3315 r1 = sqlite3GetTempReg(pParse);
3316 r2 = sqlite3GetTempReg(pParse);
3317 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
3318 Expr *pE2 = pItem->pExpr;
3320 /* If the expression is not constant then we will need to
3321 ** disable the test that was generated above that makes sure
3322 ** this code only executes once. Because for a non-constant
3323 ** expression we need to rerun this code each time.
3325 if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
3326 sqlite3VdbeChangeToNoop(v, addrOnce-1);
3327 sqlite3VdbeChangeToNoop(v, addrOnce);
3328 ExprClearProperty(pExpr, EP_Subrtn);
3329 addrOnce = 0;
3332 /* Evaluate the expression and insert it into the temp table */
3333 sqlite3ExprCode(pParse, pE2, r1);
3334 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
3335 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
3337 sqlite3ReleaseTempReg(pParse, r1);
3338 sqlite3ReleaseTempReg(pParse, r2);
3340 if( pKeyInfo ){
3341 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
3343 if( addrOnce ){
3344 sqlite3VdbeAddOp1(v, OP_NullRow, iTab);
3345 sqlite3VdbeJumpHere(v, addrOnce);
3346 /* Subroutine return */
3347 assert( ExprUseYSub(pExpr) );
3348 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3349 || pParse->nErr );
3350 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3351 pExpr->y.sub.iAddr, 1);
3352 VdbeCoverage(v);
3353 sqlite3ClearTempRegCache(pParse);
3356 #endif /* SQLITE_OMIT_SUBQUERY */
3359 ** Generate code for scalar subqueries used as a subquery expression
3360 ** or EXISTS operator:
3362 ** (SELECT a FROM b) -- subquery
3363 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3365 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3367 ** Return the register that holds the result. For a multi-column SELECT,
3368 ** the result is stored in a contiguous array of registers and the
3369 ** return value is the register of the left-most result column.
3370 ** Return 0 if an error occurs.
3372 #ifndef SQLITE_OMIT_SUBQUERY
3373 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
3374 int addrOnce = 0; /* Address of OP_Once at top of subroutine */
3375 int rReg = 0; /* Register storing resulting */
3376 Select *pSel; /* SELECT statement to encode */
3377 SelectDest dest; /* How to deal with SELECT result */
3378 int nReg; /* Registers to allocate */
3379 Expr *pLimit; /* New limit expression */
3380 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3381 int addrExplain; /* Address of OP_Explain instruction */
3382 #endif
3384 Vdbe *v = pParse->pVdbe;
3385 assert( v!=0 );
3386 if( pParse->nErr ) return 0;
3387 testcase( pExpr->op==TK_EXISTS );
3388 testcase( pExpr->op==TK_SELECT );
3389 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3390 assert( ExprUseXSelect(pExpr) );
3391 pSel = pExpr->x.pSelect;
3393 /* If this routine has already been coded, then invoke it as a
3394 ** subroutine. */
3395 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3396 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3397 assert( ExprUseYSub(pExpr) );
3398 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3399 pExpr->y.sub.iAddr);
3400 return pExpr->iTable;
3403 /* Begin coding the subroutine */
3404 assert( !ExprUseYWin(pExpr) );
3405 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
3406 ExprSetProperty(pExpr, EP_Subrtn);
3407 pExpr->y.sub.regReturn = ++pParse->nMem;
3408 pExpr->y.sub.iAddr =
3409 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3411 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3412 ** is encountered if any of the following is true:
3414 ** * The right-hand side is a correlated subquery
3415 ** * The right-hand side is an expression list containing variables
3416 ** * We are inside a trigger
3418 ** If all of the above are false, then we can run this code just once
3419 ** save the results, and reuse the same result on subsequent invocations.
3421 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3422 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3425 /* For a SELECT, generate code to put the values for all columns of
3426 ** the first row into an array of registers and return the index of
3427 ** the first register.
3429 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3430 ** into a register and return that register number.
3432 ** In both cases, the query is augmented with "LIMIT 1". Any
3433 ** preexisting limit is discarded in place of the new LIMIT 1.
3435 ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d",
3436 addrOnce?"":"CORRELATED ", pSel->selId));
3437 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1);
3438 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3439 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3440 pParse->nMem += nReg;
3441 if( pExpr->op==TK_SELECT ){
3442 dest.eDest = SRT_Mem;
3443 dest.iSdst = dest.iSDParm;
3444 dest.nSdst = nReg;
3445 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3446 VdbeComment((v, "Init subquery result"));
3447 }else{
3448 dest.eDest = SRT_Exists;
3449 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3450 VdbeComment((v, "Init EXISTS result"));
3452 if( pSel->pLimit ){
3453 /* The subquery already has a limit. If the pre-existing limit is X
3454 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3455 sqlite3 *db = pParse->db;
3456 pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3457 if( pLimit ){
3458 pLimit->affExpr = SQLITE_AFF_NUMERIC;
3459 pLimit = sqlite3PExpr(pParse, TK_NE,
3460 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3462 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
3463 pSel->pLimit->pLeft = pLimit;
3464 }else{
3465 /* If there is no pre-existing limit add a limit of 1 */
3466 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3467 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3469 pSel->iLimit = 0;
3470 if( sqlite3Select(pParse, pSel, &dest) ){
3471 pExpr->op2 = pExpr->op;
3472 pExpr->op = TK_ERROR;
3473 return 0;
3475 pExpr->iTable = rReg = dest.iSDParm;
3476 ExprSetVVAProperty(pExpr, EP_NoReduce);
3477 if( addrOnce ){
3478 sqlite3VdbeJumpHere(v, addrOnce);
3480 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
3482 /* Subroutine return */
3483 assert( ExprUseYSub(pExpr) );
3484 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3485 || pParse->nErr );
3486 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3487 pExpr->y.sub.iAddr, 1);
3488 VdbeCoverage(v);
3489 sqlite3ClearTempRegCache(pParse);
3490 return rReg;
3492 #endif /* SQLITE_OMIT_SUBQUERY */
3494 #ifndef SQLITE_OMIT_SUBQUERY
3496 ** Expr pIn is an IN(...) expression. This function checks that the
3497 ** sub-select on the RHS of the IN() operator has the same number of
3498 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3499 ** a sub-query, that the LHS is a vector of size 1.
3501 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3502 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3503 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
3504 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3505 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3506 return 1;
3508 }else if( nVector!=1 ){
3509 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3510 return 1;
3512 return 0;
3514 #endif
3516 #ifndef SQLITE_OMIT_SUBQUERY
3518 ** Generate code for an IN expression.
3520 ** x IN (SELECT ...)
3521 ** x IN (value, value, ...)
3523 ** The left-hand side (LHS) is a scalar or vector expression. The
3524 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3525 ** subquery. If the RHS is a subquery, the number of result columns must
3526 ** match the number of columns in the vector on the LHS. If the RHS is
3527 ** a list of values, the LHS must be a scalar.
3529 ** The IN operator is true if the LHS value is contained within the RHS.
3530 ** The result is false if the LHS is definitely not in the RHS. The
3531 ** result is NULL if the presence of the LHS in the RHS cannot be
3532 ** determined due to NULLs.
3534 ** This routine generates code that jumps to destIfFalse if the LHS is not
3535 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3536 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3537 ** within the RHS then fall through.
3539 ** See the separate in-operator.md documentation file in the canonical
3540 ** SQLite source tree for additional information.
3542 static void sqlite3ExprCodeIN(
3543 Parse *pParse, /* Parsing and code generating context */
3544 Expr *pExpr, /* The IN expression */
3545 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
3546 int destIfNull /* Jump here if the results are unknown due to NULLs */
3548 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
3549 int eType; /* Type of the RHS */
3550 int rLhs; /* Register(s) holding the LHS values */
3551 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
3552 Vdbe *v; /* Statement under construction */
3553 int *aiMap = 0; /* Map from vector field to index column */
3554 char *zAff = 0; /* Affinity string for comparisons */
3555 int nVector; /* Size of vectors for this IN operator */
3556 int iDummy; /* Dummy parameter to exprCodeVector() */
3557 Expr *pLeft; /* The LHS of the IN operator */
3558 int i; /* loop counter */
3559 int destStep2; /* Where to jump when NULLs seen in step 2 */
3560 int destStep6 = 0; /* Start of code for Step 6 */
3561 int addrTruthOp; /* Address of opcode that determines the IN is true */
3562 int destNotNull; /* Jump here if a comparison is not true in step 6 */
3563 int addrTop; /* Top of the step-6 loop */
3564 int iTab = 0; /* Index to use */
3565 u8 okConstFactor = pParse->okConstFactor;
3567 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3568 pLeft = pExpr->pLeft;
3569 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3570 zAff = exprINAffinity(pParse, pExpr);
3571 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3572 aiMap = (int*)sqlite3DbMallocZero(
3573 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3575 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3577 /* Attempt to compute the RHS. After this step, if anything other than
3578 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3579 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3580 ** the RHS has not yet been coded. */
3581 v = pParse->pVdbe;
3582 assert( v!=0 ); /* OOM detected prior to this routine */
3583 VdbeNoopComment((v, "begin IN expr"));
3584 eType = sqlite3FindInIndex(pParse, pExpr,
3585 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3586 destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3587 aiMap, &iTab);
3589 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3590 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3592 #ifdef SQLITE_DEBUG
3593 /* Confirm that aiMap[] contains nVector integer values between 0 and
3594 ** nVector-1. */
3595 for(i=0; i<nVector; i++){
3596 int j, cnt;
3597 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3598 assert( cnt==1 );
3600 #endif
3602 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3603 ** vector, then it is stored in an array of nVector registers starting
3604 ** at r1.
3606 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3607 ** so that the fields are in the same order as an existing index. The
3608 ** aiMap[] array contains a mapping from the original LHS field order to
3609 ** the field order that matches the RHS index.
3611 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3612 ** even if it is constant, as OP_Affinity may be used on the register
3613 ** by code generated below. */
3614 assert( pParse->okConstFactor==okConstFactor );
3615 pParse->okConstFactor = 0;
3616 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3617 pParse->okConstFactor = okConstFactor;
3618 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3619 if( i==nVector ){
3620 /* LHS fields are not reordered */
3621 rLhs = rLhsOrig;
3622 }else{
3623 /* Need to reorder the LHS fields according to aiMap */
3624 rLhs = sqlite3GetTempRange(pParse, nVector);
3625 for(i=0; i<nVector; i++){
3626 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3630 /* If sqlite3FindInIndex() did not find or create an index that is
3631 ** suitable for evaluating the IN operator, then evaluate using a
3632 ** sequence of comparisons.
3634 ** This is step (1) in the in-operator.md optimized algorithm.
3636 if( eType==IN_INDEX_NOOP ){
3637 ExprList *pList;
3638 CollSeq *pColl;
3639 int labelOk = sqlite3VdbeMakeLabel(pParse);
3640 int r2, regToFree;
3641 int regCkNull = 0;
3642 int ii;
3643 assert( ExprUseXList(pExpr) );
3644 pList = pExpr->x.pList;
3645 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3646 if( destIfNull!=destIfFalse ){
3647 regCkNull = sqlite3GetTempReg(pParse);
3648 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3650 for(ii=0; ii<pList->nExpr; ii++){
3651 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3652 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3653 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3655 sqlite3ReleaseTempReg(pParse, regToFree);
3656 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3657 int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
3658 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
3659 (void*)pColl, P4_COLLSEQ);
3660 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
3661 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
3662 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
3663 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
3664 sqlite3VdbeChangeP5(v, zAff[0]);
3665 }else{
3666 int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
3667 assert( destIfNull==destIfFalse );
3668 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
3669 (void*)pColl, P4_COLLSEQ);
3670 VdbeCoverageIf(v, op==OP_Ne);
3671 VdbeCoverageIf(v, op==OP_IsNull);
3672 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3675 if( regCkNull ){
3676 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3677 sqlite3VdbeGoto(v, destIfFalse);
3679 sqlite3VdbeResolveLabel(v, labelOk);
3680 sqlite3ReleaseTempReg(pParse, regCkNull);
3681 goto sqlite3ExprCodeIN_finished;
3684 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3685 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3686 ** We will then skip the binary search of the RHS.
3688 if( destIfNull==destIfFalse ){
3689 destStep2 = destIfFalse;
3690 }else{
3691 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3693 for(i=0; i<nVector; i++){
3694 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3695 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
3696 if( sqlite3ExprCanBeNull(p) ){
3697 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3698 VdbeCoverage(v);
3702 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3703 ** of the RHS using the LHS as a probe. If found, the result is
3704 ** true.
3706 if( eType==IN_INDEX_ROWID ){
3707 /* In this case, the RHS is the ROWID of table b-tree and so we also
3708 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3709 ** into a single opcode. */
3710 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3711 VdbeCoverage(v);
3712 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
3713 }else{
3714 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3715 if( destIfFalse==destIfNull ){
3716 /* Combine Step 3 and Step 5 into a single opcode */
3717 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3718 rLhs, nVector); VdbeCoverage(v);
3719 goto sqlite3ExprCodeIN_finished;
3721 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3722 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3723 rLhs, nVector); VdbeCoverage(v);
3726 /* Step 4. If the RHS is known to be non-NULL and we did not find
3727 ** an match on the search above, then the result must be FALSE.
3729 if( rRhsHasNull && nVector==1 ){
3730 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3731 VdbeCoverage(v);
3734 /* Step 5. If we do not care about the difference between NULL and
3735 ** FALSE, then just return false.
3737 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3739 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3740 ** If any comparison is NULL, then the result is NULL. If all
3741 ** comparisons are FALSE then the final result is FALSE.
3743 ** For a scalar LHS, it is sufficient to check just the first row
3744 ** of the RHS.
3746 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3747 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
3748 VdbeCoverage(v);
3749 if( nVector>1 ){
3750 destNotNull = sqlite3VdbeMakeLabel(pParse);
3751 }else{
3752 /* For nVector==1, combine steps 6 and 7 by immediately returning
3753 ** FALSE if the first comparison is not NULL */
3754 destNotNull = destIfFalse;
3756 for(i=0; i<nVector; i++){
3757 Expr *p;
3758 CollSeq *pColl;
3759 int r3 = sqlite3GetTempReg(pParse);
3760 p = sqlite3VectorFieldSubexpr(pLeft, i);
3761 pColl = sqlite3ExprCollSeq(pParse, p);
3762 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
3763 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3764 (void*)pColl, P4_COLLSEQ);
3765 VdbeCoverage(v);
3766 sqlite3ReleaseTempReg(pParse, r3);
3768 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3769 if( nVector>1 ){
3770 sqlite3VdbeResolveLabel(v, destNotNull);
3771 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
3772 VdbeCoverage(v);
3774 /* Step 7: If we reach this point, we know that the result must
3775 ** be false. */
3776 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3779 /* Jumps here in order to return true. */
3780 sqlite3VdbeJumpHere(v, addrTruthOp);
3782 sqlite3ExprCodeIN_finished:
3783 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3784 VdbeComment((v, "end IN expr"));
3785 sqlite3ExprCodeIN_oom_error:
3786 sqlite3DbFree(pParse->db, aiMap);
3787 sqlite3DbFree(pParse->db, zAff);
3789 #endif /* SQLITE_OMIT_SUBQUERY */
3791 #ifndef SQLITE_OMIT_FLOATING_POINT
3793 ** Generate an instruction that will put the floating point
3794 ** value described by z[0..n-1] into register iMem.
3796 ** The z[] string will probably not be zero-terminated. But the
3797 ** z[n] character is guaranteed to be something that does not look
3798 ** like the continuation of the number.
3800 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3801 if( ALWAYS(z!=0) ){
3802 double value;
3803 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3804 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3805 if( negateFlag ) value = -value;
3806 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3809 #endif
3813 ** Generate an instruction that will put the integer describe by
3814 ** text z[0..n-1] into register iMem.
3816 ** Expr.u.zToken is always UTF8 and zero-terminated.
3818 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3819 Vdbe *v = pParse->pVdbe;
3820 if( pExpr->flags & EP_IntValue ){
3821 int i = pExpr->u.iValue;
3822 assert( i>=0 );
3823 if( negFlag ) i = -i;
3824 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3825 }else{
3826 int c;
3827 i64 value;
3828 const char *z = pExpr->u.zToken;
3829 assert( z!=0 );
3830 c = sqlite3DecOrHexToI64(z, &value);
3831 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
3832 #ifdef SQLITE_OMIT_FLOATING_POINT
3833 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
3834 #else
3835 #ifndef SQLITE_OMIT_HEX_INTEGER
3836 if( sqlite3_strnicmp(z,"0x",2)==0 ){
3837 sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T",
3838 negFlag?"-":"",pExpr);
3839 }else
3840 #endif
3842 codeReal(v, z, negFlag, iMem);
3844 #endif
3845 }else{
3846 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
3847 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3853 /* Generate code that will load into register regOut a value that is
3854 ** appropriate for the iIdxCol-th column of index pIdx.
3856 void sqlite3ExprCodeLoadIndexColumn(
3857 Parse *pParse, /* The parsing context */
3858 Index *pIdx, /* The index whose column is to be loaded */
3859 int iTabCur, /* Cursor pointing to a table row */
3860 int iIdxCol, /* The column of the index to be loaded */
3861 int regOut /* Store the index column value in this register */
3863 i16 iTabCol = pIdx->aiColumn[iIdxCol];
3864 if( iTabCol==XN_EXPR ){
3865 assert( pIdx->aColExpr );
3866 assert( pIdx->aColExpr->nExpr>iIdxCol );
3867 pParse->iSelfTab = iTabCur + 1;
3868 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
3869 pParse->iSelfTab = 0;
3870 }else{
3871 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3872 iTabCol, regOut);
3876 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3878 ** Generate code that will compute the value of generated column pCol
3879 ** and store the result in register regOut
3881 void sqlite3ExprCodeGeneratedColumn(
3882 Parse *pParse, /* Parsing context */
3883 Table *pTab, /* Table containing the generated column */
3884 Column *pCol, /* The generated column */
3885 int regOut /* Put the result in this register */
3887 int iAddr;
3888 Vdbe *v = pParse->pVdbe;
3889 int nErr = pParse->nErr;
3890 assert( v!=0 );
3891 assert( pParse->iSelfTab!=0 );
3892 if( pParse->iSelfTab>0 ){
3893 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
3894 }else{
3895 iAddr = 0;
3897 sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
3898 if( pCol->affinity>=SQLITE_AFF_TEXT ){
3899 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
3901 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
3902 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
3904 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
3907 ** Generate code to extract the value of the iCol-th column of a table.
3909 void sqlite3ExprCodeGetColumnOfTable(
3910 Vdbe *v, /* Parsing context */
3911 Table *pTab, /* The table containing the value */
3912 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
3913 int iCol, /* Index of the column to extract */
3914 int regOut /* Extract the value into this register */
3916 Column *pCol;
3917 assert( v!=0 );
3918 assert( pTab!=0 );
3919 assert( iCol!=XN_EXPR );
3920 if( iCol<0 || iCol==pTab->iPKey ){
3921 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3922 VdbeComment((v, "%s.rowid", pTab->zName));
3923 }else{
3924 int op;
3925 int x;
3926 if( IsVirtual(pTab) ){
3927 op = OP_VColumn;
3928 x = iCol;
3929 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
3930 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
3931 Parse *pParse = sqlite3VdbeParser(v);
3932 if( pCol->colFlags & COLFLAG_BUSY ){
3933 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
3934 pCol->zCnName);
3935 }else{
3936 int savedSelfTab = pParse->iSelfTab;
3937 pCol->colFlags |= COLFLAG_BUSY;
3938 pParse->iSelfTab = iTabCur+1;
3939 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut);
3940 pParse->iSelfTab = savedSelfTab;
3941 pCol->colFlags &= ~COLFLAG_BUSY;
3943 return;
3944 #endif
3945 }else if( !HasRowid(pTab) ){
3946 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
3947 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3948 op = OP_Column;
3949 }else{
3950 x = sqlite3TableColumnToStorage(pTab,iCol);
3951 testcase( x!=iCol );
3952 op = OP_Column;
3954 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
3955 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3960 ** Generate code that will extract the iColumn-th column from
3961 ** table pTab and store the column value in register iReg.
3963 ** There must be an open cursor to pTab in iTable when this routine
3964 ** is called. If iColumn<0 then code is generated that extracts the rowid.
3966 int sqlite3ExprCodeGetColumn(
3967 Parse *pParse, /* Parsing and code generating context */
3968 Table *pTab, /* Description of the table we are reading from */
3969 int iColumn, /* Index of the table column */
3970 int iTable, /* The cursor pointing to the table */
3971 int iReg, /* Store results here */
3972 u8 p5 /* P5 value for OP_Column + FLAGS */
3974 assert( pParse->pVdbe!=0 );
3975 assert( (p5 & (OPFLAG_NOCHNG|OPFLAG_TYPEOFARG|OPFLAG_LENGTHARG))==p5 );
3976 assert( IsVirtual(pTab) || (p5 & OPFLAG_NOCHNG)==0 );
3977 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
3978 if( p5 ){
3979 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
3980 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
3981 if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG);
3983 return iReg;
3987 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3988 ** over to iTo..iTo+nReg-1.
3990 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3991 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3995 ** Convert a scalar expression node to a TK_REGISTER referencing
3996 ** register iReg. The caller must ensure that iReg already contains
3997 ** the correct value for the expression.
3999 static void exprToRegister(Expr *pExpr, int iReg){
4000 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
4001 if( NEVER(p==0) ) return;
4002 p->op2 = p->op;
4003 p->op = TK_REGISTER;
4004 p->iTable = iReg;
4005 ExprClearProperty(p, EP_Skip);
4009 ** Evaluate an expression (either a vector or a scalar expression) and store
4010 ** the result in contiguous temporary registers. Return the index of
4011 ** the first register used to store the result.
4013 ** If the returned result register is a temporary scalar, then also write
4014 ** that register number into *piFreeable. If the returned result register
4015 ** is not a temporary or if the expression is a vector set *piFreeable
4016 ** to 0.
4018 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
4019 int iResult;
4020 int nResult = sqlite3ExprVectorSize(p);
4021 if( nResult==1 ){
4022 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
4023 }else{
4024 *piFreeable = 0;
4025 if( p->op==TK_SELECT ){
4026 #if SQLITE_OMIT_SUBQUERY
4027 iResult = 0;
4028 #else
4029 iResult = sqlite3CodeSubselect(pParse, p);
4030 #endif
4031 }else{
4032 int i;
4033 iResult = pParse->nMem+1;
4034 pParse->nMem += nResult;
4035 assert( ExprUseXList(p) );
4036 for(i=0; i<nResult; i++){
4037 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
4041 return iResult;
4045 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4046 ** so that a subsequent copy will not be merged into this one.
4048 static void setDoNotMergeFlagOnCopy(Vdbe *v){
4049 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
4050 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergeable */
4055 ** Generate code to implement special SQL functions that are implemented
4056 ** in-line rather than by using the usual callbacks.
4058 static int exprCodeInlineFunction(
4059 Parse *pParse, /* Parsing context */
4060 ExprList *pFarg, /* List of function arguments */
4061 int iFuncId, /* Function ID. One of the INTFUNC_... values */
4062 int target /* Store function result in this register */
4064 int nFarg;
4065 Vdbe *v = pParse->pVdbe;
4066 assert( v!=0 );
4067 assert( pFarg!=0 );
4068 nFarg = pFarg->nExpr;
4069 assert( nFarg>0 ); /* All in-line functions have at least one argument */
4070 switch( iFuncId ){
4071 case INLINEFUNC_coalesce: {
4072 /* Attempt a direct implementation of the built-in COALESCE() and
4073 ** IFNULL() functions. This avoids unnecessary evaluation of
4074 ** arguments past the first non-NULL argument.
4076 int endCoalesce = sqlite3VdbeMakeLabel(pParse);
4077 int i;
4078 assert( nFarg>=2 );
4079 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
4080 for(i=1; i<nFarg; i++){
4081 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
4082 VdbeCoverage(v);
4083 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
4085 setDoNotMergeFlagOnCopy(v);
4086 sqlite3VdbeResolveLabel(v, endCoalesce);
4087 break;
4089 case INLINEFUNC_iif: {
4090 Expr caseExpr;
4091 memset(&caseExpr, 0, sizeof(caseExpr));
4092 caseExpr.op = TK_CASE;
4093 caseExpr.x.pList = pFarg;
4094 return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
4096 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4097 case INLINEFUNC_sqlite_offset: {
4098 Expr *pArg = pFarg->a[0].pExpr;
4099 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
4100 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4101 }else{
4102 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4104 break;
4106 #endif
4107 default: {
4108 /* The UNLIKELY() function is a no-op. The result is the value
4109 ** of the first argument.
4111 assert( nFarg==1 || nFarg==2 );
4112 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
4113 break;
4116 /***********************************************************************
4117 ** Test-only SQL functions that are only usable if enabled
4118 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4120 #if !defined(SQLITE_UNTESTABLE)
4121 case INLINEFUNC_expr_compare: {
4122 /* Compare two expressions using sqlite3ExprCompare() */
4123 assert( nFarg==2 );
4124 sqlite3VdbeAddOp2(v, OP_Integer,
4125 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4126 target);
4127 break;
4130 case INLINEFUNC_expr_implies_expr: {
4131 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4132 assert( nFarg==2 );
4133 sqlite3VdbeAddOp2(v, OP_Integer,
4134 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4135 target);
4136 break;
4139 case INLINEFUNC_implies_nonnull_row: {
4140 /* Result of sqlite3ExprImpliesNonNullRow() */
4141 Expr *pA1;
4142 assert( nFarg==2 );
4143 pA1 = pFarg->a[1].pExpr;
4144 if( pA1->op==TK_COLUMN ){
4145 sqlite3VdbeAddOp2(v, OP_Integer,
4146 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1),
4147 target);
4148 }else{
4149 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4151 break;
4154 case INLINEFUNC_affinity: {
4155 /* The AFFINITY() function evaluates to a string that describes
4156 ** the type affinity of the argument. This is used for testing of
4157 ** the SQLite type logic.
4159 const char *azAff[] = { "blob", "text", "numeric", "integer",
4160 "real", "flexnum" };
4161 char aff;
4162 assert( nFarg==1 );
4163 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
4164 assert( aff<=SQLITE_AFF_NONE
4165 || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) );
4166 sqlite3VdbeLoadString(v, target,
4167 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
4168 break;
4170 #endif /* !defined(SQLITE_UNTESTABLE) */
4172 return target;
4176 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4177 ** If it is, then resolve the expression by reading from the index and
4178 ** return the register into which the value has been read. If pExpr is
4179 ** not an indexed expression, then return negative.
4181 static SQLITE_NOINLINE int sqlite3IndexedExprLookup(
4182 Parse *pParse, /* The parsing context */
4183 Expr *pExpr, /* The expression to potentially bypass */
4184 int target /* Where to store the result of the expression */
4186 IndexedExpr *p;
4187 Vdbe *v;
4188 for(p=pParse->pIdxEpr; p; p=p->pIENext){
4189 u8 exprAff;
4190 int iDataCur = p->iDataCur;
4191 if( iDataCur<0 ) continue;
4192 if( pParse->iSelfTab ){
4193 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
4194 iDataCur = -1;
4196 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
4197 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
4198 exprAff = sqlite3ExprAffinity(pExpr);
4199 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
4200 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
4201 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
4203 /* Affinity mismatch on a generated column */
4204 continue;
4207 v = pParse->pVdbe;
4208 assert( v!=0 );
4209 if( p->bMaybeNullRow ){
4210 /* If the index is on a NULL row due to an outer join, then we
4211 ** cannot extract the value from the index. The value must be
4212 ** computed using the original expression. */
4213 int addr = sqlite3VdbeCurrentAddr(v);
4214 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
4215 VdbeCoverage(v);
4216 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4217 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4218 sqlite3VdbeGoto(v, 0);
4219 p = pParse->pIdxEpr;
4220 pParse->pIdxEpr = 0;
4221 sqlite3ExprCode(pParse, pExpr, target);
4222 pParse->pIdxEpr = p;
4223 sqlite3VdbeJumpHere(v, addr+2);
4224 }else{
4225 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4226 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4228 return target;
4230 return -1; /* Not found */
4235 ** Generate code into the current Vdbe to evaluate the given
4236 ** expression. Attempt to store the results in register "target".
4237 ** Return the register where results are stored.
4239 ** With this routine, there is no guarantee that results will
4240 ** be stored in target. The result might be stored in some other
4241 ** register if it is convenient to do so. The calling function
4242 ** must check the return code and move the results to the desired
4243 ** register.
4245 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
4246 Vdbe *v = pParse->pVdbe; /* The VM under construction */
4247 int op; /* The opcode being coded */
4248 int inReg = target; /* Results stored in register inReg */
4249 int regFree1 = 0; /* If non-zero free this temporary register */
4250 int regFree2 = 0; /* If non-zero free this temporary register */
4251 int r1, r2; /* Various register numbers */
4252 Expr tempX; /* Temporary expression node */
4253 int p5 = 0;
4255 assert( target>0 && target<=pParse->nMem );
4256 assert( v!=0 );
4258 expr_code_doover:
4259 if( pExpr==0 ){
4260 op = TK_NULL;
4261 }else if( pParse->pIdxEpr!=0
4262 && !ExprHasProperty(pExpr, EP_Leaf)
4263 && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0
4265 return r1;
4266 }else{
4267 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
4268 op = pExpr->op;
4270 switch( op ){
4271 case TK_AGG_COLUMN: {
4272 AggInfo *pAggInfo = pExpr->pAggInfo;
4273 struct AggInfo_col *pCol;
4274 assert( pAggInfo!=0 );
4275 assert( pExpr->iAgg>=0 );
4276 if( pExpr->iAgg>=pAggInfo->nColumn ){
4277 /* Happens when the left table of a RIGHT JOIN is null and
4278 ** is using an expression index */
4279 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4280 #ifdef SQLITE_VDBE_COVERAGE
4281 /* Verify that the OP_Null above is exercised by tests
4282 ** tag-20230325-2 */
4283 sqlite3VdbeAddOp2(v, OP_NotNull, target, 1);
4284 VdbeCoverageNeverTaken(v);
4285 #endif
4286 break;
4288 pCol = &pAggInfo->aCol[pExpr->iAgg];
4289 if( !pAggInfo->directMode ){
4290 return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
4291 }else if( pAggInfo->useSortingIdx ){
4292 Table *pTab = pCol->pTab;
4293 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
4294 pCol->iSorterColumn, target);
4295 if( pTab==0 ){
4296 /* No comment added */
4297 }else if( pCol->iColumn<0 ){
4298 VdbeComment((v,"%s.rowid",pTab->zName));
4299 }else{
4300 VdbeComment((v,"%s.%s",
4301 pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
4302 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
4303 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4306 return target;
4307 }else if( pExpr->y.pTab==0 ){
4308 /* This case happens when the argument to an aggregate function
4309 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4310 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target);
4311 return target;
4313 /* Otherwise, fall thru into the TK_COLUMN case */
4314 /* no break */ deliberate_fall_through
4316 case TK_COLUMN: {
4317 int iTab = pExpr->iTable;
4318 int iReg;
4319 if( ExprHasProperty(pExpr, EP_FixedCol) ){
4320 /* This COLUMN expression is really a constant due to WHERE clause
4321 ** constraints, and that constant is coded by the pExpr->pLeft
4322 ** expression. However, make sure the constant has the correct
4323 ** datatype by applying the Affinity of the table column to the
4324 ** constant.
4326 int aff;
4327 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
4328 assert( ExprUseYTab(pExpr) );
4329 assert( pExpr->y.pTab!=0 );
4330 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
4331 if( aff>SQLITE_AFF_BLOB ){
4332 static const char zAff[] = "B\000C\000D\000E\000F";
4333 assert( SQLITE_AFF_BLOB=='A' );
4334 assert( SQLITE_AFF_TEXT=='B' );
4335 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
4336 &zAff[(aff-'B')*2], P4_STATIC);
4338 return iReg;
4340 if( iTab<0 ){
4341 if( pParse->iSelfTab<0 ){
4342 /* Other columns in the same row for CHECK constraints or
4343 ** generated columns or for inserting into partial index.
4344 ** The row is unpacked into registers beginning at
4345 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4346 ** immediately prior to the first column.
4348 Column *pCol;
4349 Table *pTab;
4350 int iSrc;
4351 int iCol = pExpr->iColumn;
4352 assert( ExprUseYTab(pExpr) );
4353 pTab = pExpr->y.pTab;
4354 assert( pTab!=0 );
4355 assert( iCol>=XN_ROWID );
4356 assert( iCol<pTab->nCol );
4357 if( iCol<0 ){
4358 return -1-pParse->iSelfTab;
4360 pCol = pTab->aCol + iCol;
4361 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
4362 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
4363 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4364 if( pCol->colFlags & COLFLAG_GENERATED ){
4365 if( pCol->colFlags & COLFLAG_BUSY ){
4366 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4367 pCol->zCnName);
4368 return 0;
4370 pCol->colFlags |= COLFLAG_BUSY;
4371 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
4372 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc);
4374 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
4375 return iSrc;
4376 }else
4377 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4378 if( pCol->affinity==SQLITE_AFF_REAL ){
4379 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
4380 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4381 return target;
4382 }else{
4383 return iSrc;
4385 }else{
4386 /* Coding an expression that is part of an index where column names
4387 ** in the index refer to the table to which the index belongs */
4388 iTab = pParse->iSelfTab - 1;
4391 assert( ExprUseYTab(pExpr) );
4392 assert( pExpr->y.pTab!=0 );
4393 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
4394 pExpr->iColumn, iTab, target,
4395 pExpr->op2);
4396 return iReg;
4398 case TK_INTEGER: {
4399 codeInteger(pParse, pExpr, 0, target);
4400 return target;
4402 case TK_TRUEFALSE: {
4403 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
4404 return target;
4406 #ifndef SQLITE_OMIT_FLOATING_POINT
4407 case TK_FLOAT: {
4408 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4409 codeReal(v, pExpr->u.zToken, 0, target);
4410 return target;
4412 #endif
4413 case TK_STRING: {
4414 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4415 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
4416 return target;
4418 default: {
4419 /* Make NULL the default case so that if a bug causes an illegal
4420 ** Expr node to be passed into this function, it will be handled
4421 ** sanely and not crash. But keep the assert() to bring the problem
4422 ** to the attention of the developers. */
4423 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
4424 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4425 return target;
4427 #ifndef SQLITE_OMIT_BLOB_LITERAL
4428 case TK_BLOB: {
4429 int n;
4430 const char *z;
4431 char *zBlob;
4432 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4433 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
4434 assert( pExpr->u.zToken[1]=='\'' );
4435 z = &pExpr->u.zToken[2];
4436 n = sqlite3Strlen30(z) - 1;
4437 assert( z[n]=='\'' );
4438 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
4439 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
4440 return target;
4442 #endif
4443 case TK_VARIABLE: {
4444 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4445 assert( pExpr->u.zToken!=0 );
4446 assert( pExpr->u.zToken[0]!=0 );
4447 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
4448 if( pExpr->u.zToken[1]!=0 ){
4449 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
4450 assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
4451 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
4452 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
4454 return target;
4456 case TK_REGISTER: {
4457 return pExpr->iTable;
4459 #ifndef SQLITE_OMIT_CAST
4460 case TK_CAST: {
4461 /* Expressions of the form: CAST(pLeft AS token) */
4462 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4463 assert( inReg==target );
4464 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4465 sqlite3VdbeAddOp2(v, OP_Cast, target,
4466 sqlite3AffinityType(pExpr->u.zToken, 0));
4467 return inReg;
4469 #endif /* SQLITE_OMIT_CAST */
4470 case TK_IS:
4471 case TK_ISNOT:
4472 op = (op==TK_IS) ? TK_EQ : TK_NE;
4473 p5 = SQLITE_NULLEQ;
4474 /* fall-through */
4475 case TK_LT:
4476 case TK_LE:
4477 case TK_GT:
4478 case TK_GE:
4479 case TK_NE:
4480 case TK_EQ: {
4481 Expr *pLeft = pExpr->pLeft;
4482 if( sqlite3ExprIsVector(pLeft) ){
4483 codeVectorCompare(pParse, pExpr, target, op, p5);
4484 }else{
4485 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
4486 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4487 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
4488 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
4489 sqlite3VdbeCurrentAddr(v)+2, p5,
4490 ExprHasProperty(pExpr,EP_Commuted));
4491 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4492 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4493 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4494 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4495 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
4496 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
4497 if( p5==SQLITE_NULLEQ ){
4498 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
4499 }else{
4500 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
4502 testcase( regFree1==0 );
4503 testcase( regFree2==0 );
4505 break;
4507 case TK_AND:
4508 case TK_OR:
4509 case TK_PLUS:
4510 case TK_STAR:
4511 case TK_MINUS:
4512 case TK_REM:
4513 case TK_BITAND:
4514 case TK_BITOR:
4515 case TK_SLASH:
4516 case TK_LSHIFT:
4517 case TK_RSHIFT:
4518 case TK_CONCAT: {
4519 assert( TK_AND==OP_And ); testcase( op==TK_AND );
4520 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
4521 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
4522 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
4523 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
4524 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
4525 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
4526 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
4527 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
4528 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
4529 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
4530 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4531 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4532 sqlite3VdbeAddOp3(v, op, r2, r1, target);
4533 testcase( regFree1==0 );
4534 testcase( regFree2==0 );
4535 break;
4537 case TK_UMINUS: {
4538 Expr *pLeft = pExpr->pLeft;
4539 assert( pLeft );
4540 if( pLeft->op==TK_INTEGER ){
4541 codeInteger(pParse, pLeft, 1, target);
4542 return target;
4543 #ifndef SQLITE_OMIT_FLOATING_POINT
4544 }else if( pLeft->op==TK_FLOAT ){
4545 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4546 codeReal(v, pLeft->u.zToken, 1, target);
4547 return target;
4548 #endif
4549 }else{
4550 tempX.op = TK_INTEGER;
4551 tempX.flags = EP_IntValue|EP_TokenOnly;
4552 tempX.u.iValue = 0;
4553 ExprClearVVAProperties(&tempX);
4554 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
4555 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
4556 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
4557 testcase( regFree2==0 );
4559 break;
4561 case TK_BITNOT:
4562 case TK_NOT: {
4563 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
4564 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
4565 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4566 testcase( regFree1==0 );
4567 sqlite3VdbeAddOp2(v, op, r1, inReg);
4568 break;
4570 case TK_TRUTH: {
4571 int isTrue; /* IS TRUE or IS NOT TRUE */
4572 int bNormal; /* IS TRUE or IS FALSE */
4573 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4574 testcase( regFree1==0 );
4575 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4576 bNormal = pExpr->op2==TK_IS;
4577 testcase( isTrue && bNormal);
4578 testcase( !isTrue && bNormal);
4579 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
4580 break;
4582 case TK_ISNULL:
4583 case TK_NOTNULL: {
4584 int addr;
4585 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4586 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4587 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4588 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4589 testcase( regFree1==0 );
4590 addr = sqlite3VdbeAddOp1(v, op, r1);
4591 VdbeCoverageIf(v, op==TK_ISNULL);
4592 VdbeCoverageIf(v, op==TK_NOTNULL);
4593 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
4594 sqlite3VdbeJumpHere(v, addr);
4595 break;
4597 case TK_AGG_FUNCTION: {
4598 AggInfo *pInfo = pExpr->pAggInfo;
4599 if( pInfo==0
4600 || NEVER(pExpr->iAgg<0)
4601 || NEVER(pExpr->iAgg>=pInfo->nFunc)
4603 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4604 sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr);
4605 }else{
4606 return AggInfoFuncReg(pInfo, pExpr->iAgg);
4608 break;
4610 case TK_FUNCTION: {
4611 ExprList *pFarg; /* List of function arguments */
4612 int nFarg; /* Number of function arguments */
4613 FuncDef *pDef; /* The function definition object */
4614 const char *zId; /* The function name */
4615 u32 constMask = 0; /* Mask of function arguments that are constant */
4616 int i; /* Loop counter */
4617 sqlite3 *db = pParse->db; /* The database connection */
4618 u8 enc = ENC(db); /* The text encoding used by this database */
4619 CollSeq *pColl = 0; /* A collating sequence */
4621 #ifndef SQLITE_OMIT_WINDOWFUNC
4622 if( ExprHasProperty(pExpr, EP_WinFunc) ){
4623 return pExpr->y.pWin->regResult;
4625 #endif
4627 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
4628 /* SQL functions can be expensive. So try to avoid running them
4629 ** multiple times if we know they always give the same result */
4630 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4632 assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
4633 assert( ExprUseXList(pExpr) );
4634 pFarg = pExpr->x.pList;
4635 nFarg = pFarg ? pFarg->nExpr : 0;
4636 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4637 zId = pExpr->u.zToken;
4638 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
4639 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4640 if( pDef==0 && pParse->explain ){
4641 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
4643 #endif
4644 if( pDef==0 || pDef->xFinalize!=0 ){
4645 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
4646 break;
4648 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
4649 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
4650 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
4651 return exprCodeInlineFunction(pParse, pFarg,
4652 SQLITE_PTR_TO_INT(pDef->pUserData), target);
4653 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
4654 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
4657 for(i=0; i<nFarg; i++){
4658 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
4659 testcase( i==31 );
4660 constMask |= MASKBIT32(i);
4662 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
4663 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
4666 if( pFarg ){
4667 if( constMask ){
4668 r1 = pParse->nMem+1;
4669 pParse->nMem += nFarg;
4670 }else{
4671 r1 = sqlite3GetTempRange(pParse, nFarg);
4674 /* For length() and typeof() and octet_length() functions,
4675 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4676 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
4677 ** unnecessary data loading.
4679 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
4680 u8 exprOp;
4681 assert( nFarg==1 );
4682 assert( pFarg->a[0].pExpr!=0 );
4683 exprOp = pFarg->a[0].pExpr->op;
4684 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
4685 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
4686 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
4687 assert( SQLITE_FUNC_BYTELEN==OPFLAG_BYTELENARG );
4688 assert( (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG)==OPFLAG_BYTELENARG );
4689 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG );
4690 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG );
4691 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG);
4692 pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG;
4696 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_FACTOR);
4697 }else{
4698 r1 = 0;
4700 #ifndef SQLITE_OMIT_VIRTUALTABLE
4701 /* Possibly overload the function if the first argument is
4702 ** a virtual table column.
4704 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4705 ** second argument, not the first, as the argument to test to
4706 ** see if it is a column in a virtual table. This is done because
4707 ** the left operand of infix functions (the operand we want to
4708 ** control overloading) ends up as the second argument to the
4709 ** function. The expression "A glob B" is equivalent to
4710 ** "glob(B,A). We want to use the A in "A glob B" to test
4711 ** for function overloading. But we use the B term in "glob(B,A)".
4713 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
4714 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
4715 }else if( nFarg>0 ){
4716 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
4718 #endif
4719 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4720 if( !pColl ) pColl = db->pDfltColl;
4721 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
4723 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
4724 pDef, pExpr->op2);
4725 if( nFarg ){
4726 if( constMask==0 ){
4727 sqlite3ReleaseTempRange(pParse, r1, nFarg);
4728 }else{
4729 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
4732 return target;
4734 #ifndef SQLITE_OMIT_SUBQUERY
4735 case TK_EXISTS:
4736 case TK_SELECT: {
4737 int nCol;
4738 testcase( op==TK_EXISTS );
4739 testcase( op==TK_SELECT );
4740 if( pParse->db->mallocFailed ){
4741 return 0;
4742 }else if( op==TK_SELECT
4743 && ALWAYS( ExprUseXSelect(pExpr) )
4744 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
4746 sqlite3SubselectError(pParse, nCol, 1);
4747 }else{
4748 return sqlite3CodeSubselect(pParse, pExpr);
4750 break;
4752 case TK_SELECT_COLUMN: {
4753 int n;
4754 Expr *pLeft = pExpr->pLeft;
4755 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
4756 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
4757 pLeft->op2 = pParse->withinRJSubrtn;
4759 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
4760 n = sqlite3ExprVectorSize(pLeft);
4761 if( pExpr->iTable!=n ){
4762 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
4763 pExpr->iTable, n);
4765 return pLeft->iTable + pExpr->iColumn;
4767 case TK_IN: {
4768 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4769 int destIfNull = sqlite3VdbeMakeLabel(pParse);
4770 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4771 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4772 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4773 sqlite3VdbeResolveLabel(v, destIfFalse);
4774 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
4775 sqlite3VdbeResolveLabel(v, destIfNull);
4776 return target;
4778 #endif /* SQLITE_OMIT_SUBQUERY */
4782 ** x BETWEEN y AND z
4784 ** This is equivalent to
4786 ** x>=y AND x<=z
4788 ** X is stored in pExpr->pLeft.
4789 ** Y is stored in pExpr->pList->a[0].pExpr.
4790 ** Z is stored in pExpr->pList->a[1].pExpr.
4792 case TK_BETWEEN: {
4793 exprCodeBetween(pParse, pExpr, target, 0, 0);
4794 return target;
4796 case TK_COLLATE: {
4797 if( !ExprHasProperty(pExpr, EP_Collate) ){
4798 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
4799 ** "SOFT-COLLATE" that is added to constraints that are pushed down
4800 ** from outer queries into sub-queries by the push-down optimization.
4801 ** Clear subtypes as subtypes may not cross a subquery boundary.
4803 assert( pExpr->pLeft );
4804 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4805 sqlite3VdbeAddOp1(v, OP_ClrSubtype, target);
4806 return target;
4807 }else{
4808 pExpr = pExpr->pLeft;
4809 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
4812 case TK_SPAN:
4813 case TK_UPLUS: {
4814 pExpr = pExpr->pLeft;
4815 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4818 case TK_TRIGGER: {
4819 /* If the opcode is TK_TRIGGER, then the expression is a reference
4820 ** to a column in the new.* or old.* pseudo-tables available to
4821 ** trigger programs. In this case Expr.iTable is set to 1 for the
4822 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4823 ** is set to the column of the pseudo-table to read, or to -1 to
4824 ** read the rowid field.
4826 ** The expression is implemented using an OP_Param opcode. The p1
4827 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4828 ** to reference another column of the old.* pseudo-table, where
4829 ** i is the index of the column. For a new.rowid reference, p1 is
4830 ** set to (n+1), where n is the number of columns in each pseudo-table.
4831 ** For a reference to any other column in the new.* pseudo-table, p1
4832 ** is set to (n+2+i), where n and i are as defined previously. For
4833 ** example, if the table on which triggers are being fired is
4834 ** declared as:
4836 ** CREATE TABLE t1(a, b);
4838 ** Then p1 is interpreted as follows:
4840 ** p1==0 -> old.rowid p1==3 -> new.rowid
4841 ** p1==1 -> old.a p1==4 -> new.a
4842 ** p1==2 -> old.b p1==5 -> new.b
4844 Table *pTab;
4845 int iCol;
4846 int p1;
4848 assert( ExprUseYTab(pExpr) );
4849 pTab = pExpr->y.pTab;
4850 iCol = pExpr->iColumn;
4851 p1 = pExpr->iTable * (pTab->nCol+1) + 1
4852 + sqlite3TableColumnToStorage(pTab, iCol);
4854 assert( pExpr->iTable==0 || pExpr->iTable==1 );
4855 assert( iCol>=-1 && iCol<pTab->nCol );
4856 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
4857 assert( p1>=0 && p1<(pTab->nCol*2+2) );
4859 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
4860 VdbeComment((v, "r[%d]=%s.%s", target,
4861 (pExpr->iTable ? "new" : "old"),
4862 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
4865 #ifndef SQLITE_OMIT_FLOATING_POINT
4866 /* If the column has REAL affinity, it may currently be stored as an
4867 ** integer. Use OP_RealAffinity to make sure it is really real.
4869 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
4870 ** floating point when extracting it from the record. */
4871 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
4872 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4874 #endif
4875 break;
4878 case TK_VECTOR: {
4879 sqlite3ErrorMsg(pParse, "row value misused");
4880 break;
4883 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
4884 ** that derive from the right-hand table of a LEFT JOIN. The
4885 ** Expr.iTable value is the table number for the right-hand table.
4886 ** The expression is only evaluated if that table is not currently
4887 ** on a LEFT JOIN NULL row.
4889 case TK_IF_NULL_ROW: {
4890 int addrINR;
4891 u8 okConstFactor = pParse->okConstFactor;
4892 AggInfo *pAggInfo = pExpr->pAggInfo;
4893 if( pAggInfo ){
4894 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
4895 if( !pAggInfo->directMode ){
4896 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg);
4897 break;
4899 if( pExpr->pAggInfo->useSortingIdx ){
4900 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
4901 pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
4902 target);
4903 inReg = target;
4904 break;
4907 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target);
4908 /* The OP_IfNullRow opcode above can overwrite the result register with
4909 ** NULL. So we have to ensure that the result register is not a value
4910 ** that is suppose to be a constant. Two defenses are needed:
4911 ** (1) Temporarily disable factoring of constant expressions
4912 ** (2) Make sure the computed value really is stored in register
4913 ** "target" and not someplace else.
4915 pParse->okConstFactor = 0; /* note (1) above */
4916 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4917 assert( target==inReg );
4918 pParse->okConstFactor = okConstFactor;
4919 sqlite3VdbeJumpHere(v, addrINR);
4920 break;
4924 ** Form A:
4925 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4927 ** Form B:
4928 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4930 ** Form A is can be transformed into the equivalent form B as follows:
4931 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
4932 ** WHEN x=eN THEN rN ELSE y END
4934 ** X (if it exists) is in pExpr->pLeft.
4935 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4936 ** odd. The Y is also optional. If the number of elements in x.pList
4937 ** is even, then Y is omitted and the "otherwise" result is NULL.
4938 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4940 ** The result of the expression is the Ri for the first matching Ei,
4941 ** or if there is no matching Ei, the ELSE term Y, or if there is
4942 ** no ELSE term, NULL.
4944 case TK_CASE: {
4945 int endLabel; /* GOTO label for end of CASE stmt */
4946 int nextCase; /* GOTO label for next WHEN clause */
4947 int nExpr; /* 2x number of WHEN terms */
4948 int i; /* Loop counter */
4949 ExprList *pEList; /* List of WHEN terms */
4950 struct ExprList_item *aListelem; /* Array of WHEN terms */
4951 Expr opCompare; /* The X==Ei expression */
4952 Expr *pX; /* The X expression */
4953 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
4954 Expr *pDel = 0;
4955 sqlite3 *db = pParse->db;
4957 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
4958 assert(pExpr->x.pList->nExpr > 0);
4959 pEList = pExpr->x.pList;
4960 aListelem = pEList->a;
4961 nExpr = pEList->nExpr;
4962 endLabel = sqlite3VdbeMakeLabel(pParse);
4963 if( (pX = pExpr->pLeft)!=0 ){
4964 pDel = sqlite3ExprDup(db, pX, 0);
4965 if( db->mallocFailed ){
4966 sqlite3ExprDelete(db, pDel);
4967 break;
4969 testcase( pX->op==TK_COLUMN );
4970 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
4971 testcase( regFree1==0 );
4972 memset(&opCompare, 0, sizeof(opCompare));
4973 opCompare.op = TK_EQ;
4974 opCompare.pLeft = pDel;
4975 pTest = &opCompare;
4976 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4977 ** The value in regFree1 might get SCopy-ed into the file result.
4978 ** So make sure that the regFree1 register is not reused for other
4979 ** purposes and possibly overwritten. */
4980 regFree1 = 0;
4982 for(i=0; i<nExpr-1; i=i+2){
4983 if( pX ){
4984 assert( pTest!=0 );
4985 opCompare.pRight = aListelem[i].pExpr;
4986 }else{
4987 pTest = aListelem[i].pExpr;
4989 nextCase = sqlite3VdbeMakeLabel(pParse);
4990 testcase( pTest->op==TK_COLUMN );
4991 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
4992 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
4993 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
4994 sqlite3VdbeGoto(v, endLabel);
4995 sqlite3VdbeResolveLabel(v, nextCase);
4997 if( (nExpr&1)!=0 ){
4998 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
4999 }else{
5000 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
5002 sqlite3ExprDelete(db, pDel);
5003 setDoNotMergeFlagOnCopy(v);
5004 sqlite3VdbeResolveLabel(v, endLabel);
5005 break;
5007 #ifndef SQLITE_OMIT_TRIGGER
5008 case TK_RAISE: {
5009 assert( pExpr->affExpr==OE_Rollback
5010 || pExpr->affExpr==OE_Abort
5011 || pExpr->affExpr==OE_Fail
5012 || pExpr->affExpr==OE_Ignore
5014 if( !pParse->pTriggerTab && !pParse->nested ){
5015 sqlite3ErrorMsg(pParse,
5016 "RAISE() may only be used within a trigger-program");
5017 return 0;
5019 if( pExpr->affExpr==OE_Abort ){
5020 sqlite3MayAbort(pParse);
5022 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5023 if( pExpr->affExpr==OE_Ignore ){
5024 sqlite3VdbeAddOp4(
5025 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
5026 VdbeCoverage(v);
5027 }else{
5028 sqlite3HaltConstraint(pParse,
5029 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
5030 pExpr->affExpr, pExpr->u.zToken, 0, 0);
5033 break;
5035 #endif
5037 sqlite3ReleaseTempReg(pParse, regFree1);
5038 sqlite3ReleaseTempReg(pParse, regFree2);
5039 return inReg;
5043 ** Generate code that will evaluate expression pExpr just one time
5044 ** per prepared statement execution.
5046 ** If the expression uses functions (that might throw an exception) then
5047 ** guard them with an OP_Once opcode to ensure that the code is only executed
5048 ** once. If no functions are involved, then factor the code out and put it at
5049 ** the end of the prepared statement in the initialization section.
5051 ** If regDest>=0 then the result is always stored in that register and the
5052 ** result is not reusable. If regDest<0 then this routine is free to
5053 ** store the value wherever it wants. The register where the expression
5054 ** is stored is returned. When regDest<0, two identical expressions might
5055 ** code to the same register, if they do not contain function calls and hence
5056 ** are factored out into the initialization section at the end of the
5057 ** prepared statement.
5059 int sqlite3ExprCodeRunJustOnce(
5060 Parse *pParse, /* Parsing context */
5061 Expr *pExpr, /* The expression to code when the VDBE initializes */
5062 int regDest /* Store the value in this register */
5064 ExprList *p;
5065 assert( ConstFactorOk(pParse) );
5066 p = pParse->pConstExpr;
5067 if( regDest<0 && p ){
5068 struct ExprList_item *pItem;
5069 int i;
5070 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
5071 if( pItem->fg.reusable
5072 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
5074 return pItem->u.iConstExprReg;
5078 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5079 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
5080 Vdbe *v = pParse->pVdbe;
5081 int addr;
5082 assert( v );
5083 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
5084 pParse->okConstFactor = 0;
5085 if( !pParse->db->mallocFailed ){
5086 if( regDest<0 ) regDest = ++pParse->nMem;
5087 sqlite3ExprCode(pParse, pExpr, regDest);
5089 pParse->okConstFactor = 1;
5090 sqlite3ExprDelete(pParse->db, pExpr);
5091 sqlite3VdbeJumpHere(v, addr);
5092 }else{
5093 p = sqlite3ExprListAppend(pParse, p, pExpr);
5094 if( p ){
5095 struct ExprList_item *pItem = &p->a[p->nExpr-1];
5096 pItem->fg.reusable = regDest<0;
5097 if( regDest<0 ) regDest = ++pParse->nMem;
5098 pItem->u.iConstExprReg = regDest;
5100 pParse->pConstExpr = p;
5102 return regDest;
5106 ** Generate code to evaluate an expression and store the results
5107 ** into a register. Return the register number where the results
5108 ** are stored.
5110 ** If the register is a temporary register that can be deallocated,
5111 ** then write its number into *pReg. If the result register is not
5112 ** a temporary, then set *pReg to zero.
5114 ** If pExpr is a constant, then this routine might generate this
5115 ** code to fill the register in the initialization section of the
5116 ** VDBE program, in order to factor it out of the evaluation loop.
5118 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
5119 int r2;
5120 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
5121 if( ConstFactorOk(pParse)
5122 && ALWAYS(pExpr!=0)
5123 && pExpr->op!=TK_REGISTER
5124 && sqlite3ExprIsConstantNotJoin(pExpr)
5126 *pReg = 0;
5127 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
5128 }else{
5129 int r1 = sqlite3GetTempReg(pParse);
5130 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
5131 if( r2==r1 ){
5132 *pReg = r1;
5133 }else{
5134 sqlite3ReleaseTempReg(pParse, r1);
5135 *pReg = 0;
5138 return r2;
5142 ** Generate code that will evaluate expression pExpr and store the
5143 ** results in register target. The results are guaranteed to appear
5144 ** in register target.
5146 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
5147 int inReg;
5149 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
5150 assert( target>0 && target<=pParse->nMem );
5151 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
5152 if( pParse->pVdbe==0 ) return;
5153 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
5154 if( inReg!=target ){
5155 u8 op;
5156 if( ALWAYS(pExpr)
5157 && (ExprHasProperty(pExpr,EP_Subquery) || pExpr->op==TK_REGISTER)
5159 op = OP_Copy;
5160 }else{
5161 op = OP_SCopy;
5163 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
5168 ** Make a transient copy of expression pExpr and then code it using
5169 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5170 ** except that the input expression is guaranteed to be unchanged.
5172 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
5173 sqlite3 *db = pParse->db;
5174 pExpr = sqlite3ExprDup(db, pExpr, 0);
5175 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
5176 sqlite3ExprDelete(db, pExpr);
5180 ** Generate code that will evaluate expression pExpr and store the
5181 ** results in register target. The results are guaranteed to appear
5182 ** in register target. If the expression is constant, then this routine
5183 ** might choose to code the expression at initialization time.
5185 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
5186 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
5187 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
5188 }else{
5189 sqlite3ExprCodeCopy(pParse, pExpr, target);
5194 ** Generate code that pushes the value of every element of the given
5195 ** expression list into a sequence of registers beginning at target.
5197 ** Return the number of elements evaluated. The number returned will
5198 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5199 ** is defined.
5201 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5202 ** filled using OP_SCopy. OP_Copy must be used instead.
5204 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5205 ** factored out into initialization code.
5207 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5208 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5209 ** in registers at srcReg, and so the value can be copied from there.
5210 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5211 ** are simply omitted rather than being copied from srcReg.
5213 int sqlite3ExprCodeExprList(
5214 Parse *pParse, /* Parsing context */
5215 ExprList *pList, /* The expression list to be coded */
5216 int target, /* Where to write results */
5217 int srcReg, /* Source registers if SQLITE_ECEL_REF */
5218 u8 flags /* SQLITE_ECEL_* flags */
5220 struct ExprList_item *pItem;
5221 int i, j, n;
5222 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
5223 Vdbe *v = pParse->pVdbe;
5224 assert( pList!=0 );
5225 assert( target>0 );
5226 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
5227 n = pList->nExpr;
5228 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
5229 for(pItem=pList->a, i=0; i<n; i++, pItem++){
5230 Expr *pExpr = pItem->pExpr;
5231 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5232 if( pItem->fg.bSorterRef ){
5233 i--;
5234 n--;
5235 }else
5236 #endif
5237 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
5238 if( flags & SQLITE_ECEL_OMITREF ){
5239 i--;
5240 n--;
5241 }else{
5242 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
5244 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
5245 && sqlite3ExprIsConstantNotJoin(pExpr)
5247 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
5248 }else{
5249 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
5250 if( inReg!=target+i ){
5251 VdbeOp *pOp;
5252 if( copyOp==OP_Copy
5253 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
5254 && pOp->p1+pOp->p3+1==inReg
5255 && pOp->p2+pOp->p3+1==target+i
5256 && pOp->p5==0 /* The do-not-merge flag must be clear */
5258 pOp->p3++;
5259 }else{
5260 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
5265 return n;
5269 ** Generate code for a BETWEEN operator.
5271 ** x BETWEEN y AND z
5273 ** The above is equivalent to
5275 ** x>=y AND x<=z
5277 ** Code it as such, taking care to do the common subexpression
5278 ** elimination of x.
5280 ** The xJumpIf parameter determines details:
5282 ** NULL: Store the boolean result in reg[dest]
5283 ** sqlite3ExprIfTrue: Jump to dest if true
5284 ** sqlite3ExprIfFalse: Jump to dest if false
5286 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5288 static void exprCodeBetween(
5289 Parse *pParse, /* Parsing and code generating context */
5290 Expr *pExpr, /* The BETWEEN expression */
5291 int dest, /* Jump destination or storage location */
5292 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
5293 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
5295 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
5296 Expr compLeft; /* The x>=y term */
5297 Expr compRight; /* The x<=z term */
5298 int regFree1 = 0; /* Temporary use register */
5299 Expr *pDel = 0;
5300 sqlite3 *db = pParse->db;
5302 memset(&compLeft, 0, sizeof(Expr));
5303 memset(&compRight, 0, sizeof(Expr));
5304 memset(&exprAnd, 0, sizeof(Expr));
5306 assert( ExprUseXList(pExpr) );
5307 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
5308 if( db->mallocFailed==0 ){
5309 exprAnd.op = TK_AND;
5310 exprAnd.pLeft = &compLeft;
5311 exprAnd.pRight = &compRight;
5312 compLeft.op = TK_GE;
5313 compLeft.pLeft = pDel;
5314 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
5315 compRight.op = TK_LE;
5316 compRight.pLeft = pDel;
5317 compRight.pRight = pExpr->x.pList->a[1].pExpr;
5318 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5319 if( xJump ){
5320 xJump(pParse, &exprAnd, dest, jumpIfNull);
5321 }else{
5322 /* Mark the expression is being from the ON or USING clause of a join
5323 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5324 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5325 ** for clarity, but we are out of bits in the Expr.flags field so we
5326 ** have to reuse the EP_OuterON bit. Bummer. */
5327 pDel->flags |= EP_OuterON;
5328 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
5330 sqlite3ReleaseTempReg(pParse, regFree1);
5332 sqlite3ExprDelete(db, pDel);
5334 /* Ensure adequate test coverage */
5335 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
5336 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
5337 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
5338 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
5339 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
5340 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
5341 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
5342 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
5343 testcase( xJump==0 );
5347 ** Generate code for a boolean expression such that a jump is made
5348 ** to the label "dest" if the expression is true but execution
5349 ** continues straight thru if the expression is false.
5351 ** If the expression evaluates to NULL (neither true nor false), then
5352 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5354 ** This code depends on the fact that certain token values (ex: TK_EQ)
5355 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5356 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5357 ** the make process cause these values to align. Assert()s in the code
5358 ** below verify that the numbers are aligned correctly.
5360 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5361 Vdbe *v = pParse->pVdbe;
5362 int op = 0;
5363 int regFree1 = 0;
5364 int regFree2 = 0;
5365 int r1, r2;
5367 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5368 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5369 if( NEVER(pExpr==0) ) return; /* No way this can happen */
5370 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
5371 op = pExpr->op;
5372 switch( op ){
5373 case TK_AND:
5374 case TK_OR: {
5375 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5376 if( pAlt!=pExpr ){
5377 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
5378 }else if( op==TK_AND ){
5379 int d2 = sqlite3VdbeMakeLabel(pParse);
5380 testcase( jumpIfNull==0 );
5381 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
5382 jumpIfNull^SQLITE_JUMPIFNULL);
5383 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5384 sqlite3VdbeResolveLabel(v, d2);
5385 }else{
5386 testcase( jumpIfNull==0 );
5387 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5388 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5390 break;
5392 case TK_NOT: {
5393 testcase( jumpIfNull==0 );
5394 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5395 break;
5397 case TK_TRUTH: {
5398 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5399 int isTrue; /* IS TRUE or IS NOT TRUE */
5400 testcase( jumpIfNull==0 );
5401 isNot = pExpr->op2==TK_ISNOT;
5402 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5403 testcase( isTrue && isNot );
5404 testcase( !isTrue && isNot );
5405 if( isTrue ^ isNot ){
5406 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5407 isNot ? SQLITE_JUMPIFNULL : 0);
5408 }else{
5409 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5410 isNot ? SQLITE_JUMPIFNULL : 0);
5412 break;
5414 case TK_IS:
5415 case TK_ISNOT:
5416 testcase( op==TK_IS );
5417 testcase( op==TK_ISNOT );
5418 op = (op==TK_IS) ? TK_EQ : TK_NE;
5419 jumpIfNull = SQLITE_NULLEQ;
5420 /* no break */ deliberate_fall_through
5421 case TK_LT:
5422 case TK_LE:
5423 case TK_GT:
5424 case TK_GE:
5425 case TK_NE:
5426 case TK_EQ: {
5427 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5428 testcase( jumpIfNull==0 );
5429 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5430 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5431 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5432 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
5433 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5434 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5435 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5436 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5437 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5438 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5439 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5440 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5441 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5442 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5443 testcase( regFree1==0 );
5444 testcase( regFree2==0 );
5445 break;
5447 case TK_ISNULL:
5448 case TK_NOTNULL: {
5449 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
5450 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
5451 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5452 sqlite3VdbeTypeofColumn(v, r1);
5453 sqlite3VdbeAddOp2(v, op, r1, dest);
5454 VdbeCoverageIf(v, op==TK_ISNULL);
5455 VdbeCoverageIf(v, op==TK_NOTNULL);
5456 testcase( regFree1==0 );
5457 break;
5459 case TK_BETWEEN: {
5460 testcase( jumpIfNull==0 );
5461 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
5462 break;
5464 #ifndef SQLITE_OMIT_SUBQUERY
5465 case TK_IN: {
5466 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5467 int destIfNull = jumpIfNull ? dest : destIfFalse;
5468 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5469 sqlite3VdbeGoto(v, dest);
5470 sqlite3VdbeResolveLabel(v, destIfFalse);
5471 break;
5473 #endif
5474 default: {
5475 default_expr:
5476 if( ExprAlwaysTrue(pExpr) ){
5477 sqlite3VdbeGoto(v, dest);
5478 }else if( ExprAlwaysFalse(pExpr) ){
5479 /* No-op */
5480 }else{
5481 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5482 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
5483 VdbeCoverage(v);
5484 testcase( regFree1==0 );
5485 testcase( jumpIfNull==0 );
5487 break;
5490 sqlite3ReleaseTempReg(pParse, regFree1);
5491 sqlite3ReleaseTempReg(pParse, regFree2);
5495 ** Generate code for a boolean expression such that a jump is made
5496 ** to the label "dest" if the expression is false but execution
5497 ** continues straight thru if the expression is true.
5499 ** If the expression evaluates to NULL (neither true nor false) then
5500 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5501 ** is 0.
5503 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5504 Vdbe *v = pParse->pVdbe;
5505 int op = 0;
5506 int regFree1 = 0;
5507 int regFree2 = 0;
5508 int r1, r2;
5510 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5511 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5512 if( pExpr==0 ) return;
5513 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
5515 /* The value of pExpr->op and op are related as follows:
5517 ** pExpr->op op
5518 ** --------- ----------
5519 ** TK_ISNULL OP_NotNull
5520 ** TK_NOTNULL OP_IsNull
5521 ** TK_NE OP_Eq
5522 ** TK_EQ OP_Ne
5523 ** TK_GT OP_Le
5524 ** TK_LE OP_Gt
5525 ** TK_GE OP_Lt
5526 ** TK_LT OP_Ge
5528 ** For other values of pExpr->op, op is undefined and unused.
5529 ** The value of TK_ and OP_ constants are arranged such that we
5530 ** can compute the mapping above using the following expression.
5531 ** Assert()s verify that the computation is correct.
5533 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
5535 /* Verify correct alignment of TK_ and OP_ constants
5537 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
5538 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
5539 assert( pExpr->op!=TK_NE || op==OP_Eq );
5540 assert( pExpr->op!=TK_EQ || op==OP_Ne );
5541 assert( pExpr->op!=TK_LT || op==OP_Ge );
5542 assert( pExpr->op!=TK_LE || op==OP_Gt );
5543 assert( pExpr->op!=TK_GT || op==OP_Le );
5544 assert( pExpr->op!=TK_GE || op==OP_Lt );
5546 switch( pExpr->op ){
5547 case TK_AND:
5548 case TK_OR: {
5549 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5550 if( pAlt!=pExpr ){
5551 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
5552 }else if( pExpr->op==TK_AND ){
5553 testcase( jumpIfNull==0 );
5554 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5555 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5556 }else{
5557 int d2 = sqlite3VdbeMakeLabel(pParse);
5558 testcase( jumpIfNull==0 );
5559 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
5560 jumpIfNull^SQLITE_JUMPIFNULL);
5561 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5562 sqlite3VdbeResolveLabel(v, d2);
5564 break;
5566 case TK_NOT: {
5567 testcase( jumpIfNull==0 );
5568 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5569 break;
5571 case TK_TRUTH: {
5572 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5573 int isTrue; /* IS TRUE or IS NOT TRUE */
5574 testcase( jumpIfNull==0 );
5575 isNot = pExpr->op2==TK_ISNOT;
5576 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5577 testcase( isTrue && isNot );
5578 testcase( !isTrue && isNot );
5579 if( isTrue ^ isNot ){
5580 /* IS TRUE and IS NOT FALSE */
5581 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5582 isNot ? 0 : SQLITE_JUMPIFNULL);
5584 }else{
5585 /* IS FALSE and IS NOT TRUE */
5586 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5587 isNot ? 0 : SQLITE_JUMPIFNULL);
5589 break;
5591 case TK_IS:
5592 case TK_ISNOT:
5593 testcase( pExpr->op==TK_IS );
5594 testcase( pExpr->op==TK_ISNOT );
5595 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
5596 jumpIfNull = SQLITE_NULLEQ;
5597 /* no break */ deliberate_fall_through
5598 case TK_LT:
5599 case TK_LE:
5600 case TK_GT:
5601 case TK_GE:
5602 case TK_NE:
5603 case TK_EQ: {
5604 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5605 testcase( jumpIfNull==0 );
5606 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5607 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5608 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5609 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
5610 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5611 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5612 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5613 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5614 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5615 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5616 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5617 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5618 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5619 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5620 testcase( regFree1==0 );
5621 testcase( regFree2==0 );
5622 break;
5624 case TK_ISNULL:
5625 case TK_NOTNULL: {
5626 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5627 sqlite3VdbeTypeofColumn(v, r1);
5628 sqlite3VdbeAddOp2(v, op, r1, dest);
5629 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
5630 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
5631 testcase( regFree1==0 );
5632 break;
5634 case TK_BETWEEN: {
5635 testcase( jumpIfNull==0 );
5636 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
5637 break;
5639 #ifndef SQLITE_OMIT_SUBQUERY
5640 case TK_IN: {
5641 if( jumpIfNull ){
5642 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
5643 }else{
5644 int destIfNull = sqlite3VdbeMakeLabel(pParse);
5645 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
5646 sqlite3VdbeResolveLabel(v, destIfNull);
5648 break;
5650 #endif
5651 default: {
5652 default_expr:
5653 if( ExprAlwaysFalse(pExpr) ){
5654 sqlite3VdbeGoto(v, dest);
5655 }else if( ExprAlwaysTrue(pExpr) ){
5656 /* no-op */
5657 }else{
5658 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5659 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
5660 VdbeCoverage(v);
5661 testcase( regFree1==0 );
5662 testcase( jumpIfNull==0 );
5664 break;
5667 sqlite3ReleaseTempReg(pParse, regFree1);
5668 sqlite3ReleaseTempReg(pParse, regFree2);
5672 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5673 ** code generation, and that copy is deleted after code generation. This
5674 ** ensures that the original pExpr is unchanged.
5676 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
5677 sqlite3 *db = pParse->db;
5678 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
5679 if( db->mallocFailed==0 ){
5680 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
5682 sqlite3ExprDelete(db, pCopy);
5686 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5687 ** type of expression.
5689 ** If pExpr is a simple SQL value - an integer, real, string, blob
5690 ** or NULL value - then the VDBE currently being prepared is configured
5691 ** to re-prepare each time a new value is bound to variable pVar.
5693 ** Additionally, if pExpr is a simple SQL value and the value is the
5694 ** same as that currently bound to variable pVar, non-zero is returned.
5695 ** Otherwise, if the values are not the same or if pExpr is not a simple
5696 ** SQL value, zero is returned.
5698 static int exprCompareVariable(
5699 const Parse *pParse,
5700 const Expr *pVar,
5701 const Expr *pExpr
5703 int res = 0;
5704 int iVar;
5705 sqlite3_value *pL, *pR = 0;
5707 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
5708 if( pR ){
5709 iVar = pVar->iColumn;
5710 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
5711 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
5712 if( pL ){
5713 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
5714 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
5716 res = 0==sqlite3MemCompare(pL, pR, 0);
5718 sqlite3ValueFree(pR);
5719 sqlite3ValueFree(pL);
5722 return res;
5726 ** Do a deep comparison of two expression trees. Return 0 if the two
5727 ** expressions are completely identical. Return 1 if they differ only
5728 ** by a COLLATE operator at the top level. Return 2 if there are differences
5729 ** other than the top-level COLLATE operator.
5731 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5732 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5734 ** The pA side might be using TK_REGISTER. If that is the case and pB is
5735 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5737 ** Sometimes this routine will return 2 even if the two expressions
5738 ** really are equivalent. If we cannot prove that the expressions are
5739 ** identical, we return 2 just to be safe. So if this routine
5740 ** returns 2, then you do not really know for certain if the two
5741 ** expressions are the same. But if you get a 0 or 1 return, then you
5742 ** can be sure the expressions are the same. In the places where
5743 ** this routine is used, it does not hurt to get an extra 2 - that
5744 ** just might result in some slightly slower code. But returning
5745 ** an incorrect 0 or 1 could lead to a malfunction.
5747 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5748 ** pParse->pReprepare can be matched against literals in pB. The
5749 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5750 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5751 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5752 ** pB causes a return value of 2.
5754 int sqlite3ExprCompare(
5755 const Parse *pParse,
5756 const Expr *pA,
5757 const Expr *pB,
5758 int iTab
5760 u32 combinedFlags;
5761 if( pA==0 || pB==0 ){
5762 return pB==pA ? 0 : 2;
5764 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
5765 return 0;
5767 combinedFlags = pA->flags | pB->flags;
5768 if( combinedFlags & EP_IntValue ){
5769 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
5770 return 0;
5772 return 2;
5774 if( pA->op!=pB->op || pA->op==TK_RAISE ){
5775 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
5776 return 1;
5778 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
5779 return 1;
5781 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
5782 && pB->iTable<0 && pA->iTable==iTab
5784 /* fall through */
5785 }else{
5786 return 2;
5789 assert( !ExprHasProperty(pA, EP_IntValue) );
5790 assert( !ExprHasProperty(pB, EP_IntValue) );
5791 if( pA->u.zToken ){
5792 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
5793 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5794 #ifndef SQLITE_OMIT_WINDOWFUNC
5795 assert( pA->op==pB->op );
5796 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
5797 return 2;
5799 if( ExprHasProperty(pA,EP_WinFunc) ){
5800 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
5801 return 2;
5804 #endif
5805 }else if( pA->op==TK_NULL ){
5806 return 0;
5807 }else if( pA->op==TK_COLLATE ){
5808 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5809 }else
5810 if( pB->u.zToken!=0
5811 && pA->op!=TK_COLUMN
5812 && pA->op!=TK_AGG_COLUMN
5813 && strcmp(pA->u.zToken,pB->u.zToken)!=0
5815 return 2;
5818 if( (pA->flags & (EP_Distinct|EP_Commuted))
5819 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
5820 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
5821 if( combinedFlags & EP_xIsSelect ) return 2;
5822 if( (combinedFlags & EP_FixedCol)==0
5823 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
5824 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
5825 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
5826 if( pA->op!=TK_STRING
5827 && pA->op!=TK_TRUEFALSE
5828 && ALWAYS((combinedFlags & EP_Reduced)==0)
5830 if( pA->iColumn!=pB->iColumn ) return 2;
5831 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
5832 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
5833 return 2;
5837 return 0;
5841 ** Compare two ExprList objects. Return 0 if they are identical, 1
5842 ** if they are certainly different, or 2 if it is not possible to
5843 ** determine if they are identical or not.
5845 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5846 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5848 ** This routine might return non-zero for equivalent ExprLists. The
5849 ** only consequence will be disabled optimizations. But this routine
5850 ** must never return 0 if the two ExprList objects are different, or
5851 ** a malfunction will result.
5853 ** Two NULL pointers are considered to be the same. But a NULL pointer
5854 ** always differs from a non-NULL pointer.
5856 int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){
5857 int i;
5858 if( pA==0 && pB==0 ) return 0;
5859 if( pA==0 || pB==0 ) return 1;
5860 if( pA->nExpr!=pB->nExpr ) return 1;
5861 for(i=0; i<pA->nExpr; i++){
5862 int res;
5863 Expr *pExprA = pA->a[i].pExpr;
5864 Expr *pExprB = pB->a[i].pExpr;
5865 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
5866 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
5868 return 0;
5872 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
5873 ** are ignored.
5875 int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
5876 return sqlite3ExprCompare(0,
5877 sqlite3ExprSkipCollateAndLikely(pA),
5878 sqlite3ExprSkipCollateAndLikely(pB),
5879 iTab);
5883 ** Return non-zero if Expr p can only be true if pNN is not NULL.
5885 ** Or if seenNot is true, return non-zero if Expr p can only be
5886 ** non-NULL if pNN is not NULL
5888 static int exprImpliesNotNull(
5889 const Parse *pParse,/* Parsing context */
5890 const Expr *p, /* The expression to be checked */
5891 const Expr *pNN, /* The expression that is NOT NULL */
5892 int iTab, /* Table being evaluated */
5893 int seenNot /* Return true only if p can be any non-NULL value */
5895 assert( p );
5896 assert( pNN );
5897 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
5898 return pNN->op!=TK_NULL;
5900 switch( p->op ){
5901 case TK_IN: {
5902 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
5903 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
5904 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5906 case TK_BETWEEN: {
5907 ExprList *pList;
5908 assert( ExprUseXList(p) );
5909 pList = p->x.pList;
5910 assert( pList!=0 );
5911 assert( pList->nExpr==2 );
5912 if( seenNot ) return 0;
5913 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
5914 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
5916 return 1;
5918 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5920 case TK_EQ:
5921 case TK_NE:
5922 case TK_LT:
5923 case TK_LE:
5924 case TK_GT:
5925 case TK_GE:
5926 case TK_PLUS:
5927 case TK_MINUS:
5928 case TK_BITOR:
5929 case TK_LSHIFT:
5930 case TK_RSHIFT:
5931 case TK_CONCAT:
5932 seenNot = 1;
5933 /* no break */ deliberate_fall_through
5934 case TK_STAR:
5935 case TK_REM:
5936 case TK_BITAND:
5937 case TK_SLASH: {
5938 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
5939 /* no break */ deliberate_fall_through
5941 case TK_SPAN:
5942 case TK_COLLATE:
5943 case TK_UPLUS:
5944 case TK_UMINUS: {
5945 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
5947 case TK_TRUTH: {
5948 if( seenNot ) return 0;
5949 if( p->op2!=TK_IS ) return 0;
5950 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5952 case TK_BITNOT:
5953 case TK_NOT: {
5954 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
5957 return 0;
5961 ** Return true if we can prove the pE2 will always be true if pE1 is
5962 ** true. Return false if we cannot complete the proof or if pE2 might
5963 ** be false. Examples:
5965 ** pE1: x==5 pE2: x==5 Result: true
5966 ** pE1: x>0 pE2: x==5 Result: false
5967 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
5968 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
5969 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
5970 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
5971 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false
5973 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
5974 ** Expr.iTable<0 then assume a table number given by iTab.
5976 ** If pParse is not NULL, then the values of bound variables in pE1 are
5977 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
5978 ** modified to record which bound variables are referenced. If pParse
5979 ** is NULL, then false will be returned if pE1 contains any bound variables.
5981 ** When in doubt, return false. Returning true might give a performance
5982 ** improvement. Returning false might cause a performance reduction, but
5983 ** it will always give the correct answer and is hence always safe.
5985 int sqlite3ExprImpliesExpr(
5986 const Parse *pParse,
5987 const Expr *pE1,
5988 const Expr *pE2,
5989 int iTab
5991 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
5992 return 1;
5994 if( pE2->op==TK_OR
5995 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
5996 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
5998 return 1;
6000 if( pE2->op==TK_NOTNULL
6001 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
6003 return 1;
6005 return 0;
6008 /* This is a helper function to impliesNotNullRow(). In this routine,
6009 ** set pWalker->eCode to one only if *both* of the input expressions
6010 ** separately have the implies-not-null-row property.
6012 static void bothImplyNotNullRow(Walker *pWalker, Expr *pE1, Expr *pE2){
6013 if( pWalker->eCode==0 ){
6014 sqlite3WalkExpr(pWalker, pE1);
6015 if( pWalker->eCode ){
6016 pWalker->eCode = 0;
6017 sqlite3WalkExpr(pWalker, pE2);
6023 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
6024 ** If the expression node requires that the table at pWalker->iCur
6025 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
6027 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
6028 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when
6029 ** evaluating terms in the ON clause of an inner join.
6031 ** This routine controls an optimization. False positives (setting
6032 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6033 ** (never setting pWalker->eCode) is a harmless missed optimization.
6035 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
6036 testcase( pExpr->op==TK_AGG_COLUMN );
6037 testcase( pExpr->op==TK_AGG_FUNCTION );
6038 if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune;
6039 if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){
6040 /* If iCur is used in an inner-join ON clause to the left of a
6041 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
6042 ** But it is difficult to check for that condition precisely.
6043 ** To keep things simple, any use of iCur from any inner-join is
6044 ** ignored while attempting to simplify a RIGHT JOIN. */
6045 return WRC_Prune;
6047 switch( pExpr->op ){
6048 case TK_ISNOT:
6049 case TK_ISNULL:
6050 case TK_NOTNULL:
6051 case TK_IS:
6052 case TK_VECTOR:
6053 case TK_FUNCTION:
6054 case TK_TRUTH:
6055 case TK_CASE:
6056 testcase( pExpr->op==TK_ISNOT );
6057 testcase( pExpr->op==TK_ISNULL );
6058 testcase( pExpr->op==TK_NOTNULL );
6059 testcase( pExpr->op==TK_IS );
6060 testcase( pExpr->op==TK_VECTOR );
6061 testcase( pExpr->op==TK_FUNCTION );
6062 testcase( pExpr->op==TK_TRUTH );
6063 testcase( pExpr->op==TK_CASE );
6064 return WRC_Prune;
6066 case TK_COLUMN:
6067 if( pWalker->u.iCur==pExpr->iTable ){
6068 pWalker->eCode = 1;
6069 return WRC_Abort;
6071 return WRC_Prune;
6073 case TK_OR:
6074 case TK_AND:
6075 /* Both sides of an AND or OR must separately imply non-null-row.
6076 ** Consider these cases:
6077 ** 1. NOT (x AND y)
6078 ** 2. x OR y
6079 ** If only one of x or y is non-null-row, then the overall expression
6080 ** can be true if the other arm is false (case 1) or true (case 2).
6082 testcase( pExpr->op==TK_OR );
6083 testcase( pExpr->op==TK_AND );
6084 bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight);
6085 return WRC_Prune;
6087 case TK_IN:
6088 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
6089 ** both of which can be true. But apart from these cases, if
6090 ** the left-hand side of the IN is NULL then the IN itself will be
6091 ** NULL. */
6092 if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){
6093 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6095 return WRC_Prune;
6097 case TK_BETWEEN:
6098 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
6099 ** both y and z must be non-null row */
6100 assert( ExprUseXList(pExpr) );
6101 assert( pExpr->x.pList->nExpr==2 );
6102 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6103 bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr,
6104 pExpr->x.pList->a[1].pExpr);
6105 return WRC_Prune;
6107 /* Virtual tables are allowed to use constraints like x=NULL. So
6108 ** a term of the form x=y does not prove that y is not null if x
6109 ** is the column of a virtual table */
6110 case TK_EQ:
6111 case TK_NE:
6112 case TK_LT:
6113 case TK_LE:
6114 case TK_GT:
6115 case TK_GE: {
6116 Expr *pLeft = pExpr->pLeft;
6117 Expr *pRight = pExpr->pRight;
6118 testcase( pExpr->op==TK_EQ );
6119 testcase( pExpr->op==TK_NE );
6120 testcase( pExpr->op==TK_LT );
6121 testcase( pExpr->op==TK_LE );
6122 testcase( pExpr->op==TK_GT );
6123 testcase( pExpr->op==TK_GE );
6124 /* The y.pTab=0 assignment in wherecode.c always happens after the
6125 ** impliesNotNullRow() test */
6126 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
6127 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
6128 if( (pLeft->op==TK_COLUMN
6129 && ALWAYS(pLeft->y.pTab!=0)
6130 && IsVirtual(pLeft->y.pTab))
6131 || (pRight->op==TK_COLUMN
6132 && ALWAYS(pRight->y.pTab!=0)
6133 && IsVirtual(pRight->y.pTab))
6135 return WRC_Prune;
6137 /* no break */ deliberate_fall_through
6139 default:
6140 return WRC_Continue;
6145 ** Return true (non-zero) if expression p can only be true if at least
6146 ** one column of table iTab is non-null. In other words, return true
6147 ** if expression p will always be NULL or false if every column of iTab
6148 ** is NULL.
6150 ** False negatives are acceptable. In other words, it is ok to return
6151 ** zero even if expression p will never be true of every column of iTab
6152 ** is NULL. A false negative is merely a missed optimization opportunity.
6154 ** False positives are not allowed, however. A false positive may result
6155 ** in an incorrect answer.
6157 ** Terms of p that are marked with EP_OuterON (and hence that come from
6158 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6160 ** This routine is used to check if a LEFT JOIN can be converted into
6161 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6162 ** clause requires that some column of the right table of the LEFT JOIN
6163 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6164 ** ordinary join.
6166 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab, int isRJ){
6167 Walker w;
6168 p = sqlite3ExprSkipCollateAndLikely(p);
6169 if( p==0 ) return 0;
6170 if( p->op==TK_NOTNULL ){
6171 p = p->pLeft;
6172 }else{
6173 while( p->op==TK_AND ){
6174 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1;
6175 p = p->pRight;
6178 w.xExprCallback = impliesNotNullRow;
6179 w.xSelectCallback = 0;
6180 w.xSelectCallback2 = 0;
6181 w.eCode = 0;
6182 w.mWFlags = isRJ!=0;
6183 w.u.iCur = iTab;
6184 sqlite3WalkExpr(&w, p);
6185 return w.eCode;
6189 ** An instance of the following structure is used by the tree walker
6190 ** to determine if an expression can be evaluated by reference to the
6191 ** index only, without having to do a search for the corresponding
6192 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6193 ** is the cursor for the table.
6195 struct IdxCover {
6196 Index *pIdx; /* The index to be tested for coverage */
6197 int iCur; /* Cursor number for the table corresponding to the index */
6201 ** Check to see if there are references to columns in table
6202 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6203 ** pWalker->u.pIdxCover->pIdx.
6205 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
6206 if( pExpr->op==TK_COLUMN
6207 && pExpr->iTable==pWalker->u.pIdxCover->iCur
6208 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
6210 pWalker->eCode = 1;
6211 return WRC_Abort;
6213 return WRC_Continue;
6217 ** Determine if an index pIdx on table with cursor iCur contains will
6218 ** the expression pExpr. Return true if the index does cover the
6219 ** expression and false if the pExpr expression references table columns
6220 ** that are not found in the index pIdx.
6222 ** An index covering an expression means that the expression can be
6223 ** evaluated using only the index and without having to lookup the
6224 ** corresponding table entry.
6226 int sqlite3ExprCoveredByIndex(
6227 Expr *pExpr, /* The index to be tested */
6228 int iCur, /* The cursor number for the corresponding table */
6229 Index *pIdx /* The index that might be used for coverage */
6231 Walker w;
6232 struct IdxCover xcov;
6233 memset(&w, 0, sizeof(w));
6234 xcov.iCur = iCur;
6235 xcov.pIdx = pIdx;
6236 w.xExprCallback = exprIdxCover;
6237 w.u.pIdxCover = &xcov;
6238 sqlite3WalkExpr(&w, pExpr);
6239 return !w.eCode;
6243 /* Structure used to pass information throughout the Walker in order to
6244 ** implement sqlite3ReferencesSrcList().
6246 struct RefSrcList {
6247 sqlite3 *db; /* Database connection used for sqlite3DbRealloc() */
6248 SrcList *pRef; /* Looking for references to these tables */
6249 i64 nExclude; /* Number of tables to exclude from the search */
6250 int *aiExclude; /* Cursor IDs for tables to exclude from the search */
6254 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6256 ** When entering a new subquery on the pExpr argument, add all FROM clause
6257 ** entries for that subquery to the exclude list.
6259 ** When leaving the subquery, remove those entries from the exclude list.
6261 static int selectRefEnter(Walker *pWalker, Select *pSelect){
6262 struct RefSrcList *p = pWalker->u.pRefSrcList;
6263 SrcList *pSrc = pSelect->pSrc;
6264 i64 i, j;
6265 int *piNew;
6266 if( pSrc->nSrc==0 ) return WRC_Continue;
6267 j = p->nExclude;
6268 p->nExclude += pSrc->nSrc;
6269 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
6270 if( piNew==0 ){
6271 p->nExclude = 0;
6272 return WRC_Abort;
6273 }else{
6274 p->aiExclude = piNew;
6276 for(i=0; i<pSrc->nSrc; i++, j++){
6277 p->aiExclude[j] = pSrc->a[i].iCursor;
6279 return WRC_Continue;
6281 static void selectRefLeave(Walker *pWalker, Select *pSelect){
6282 struct RefSrcList *p = pWalker->u.pRefSrcList;
6283 SrcList *pSrc = pSelect->pSrc;
6284 if( p->nExclude ){
6285 assert( p->nExclude>=pSrc->nSrc );
6286 p->nExclude -= pSrc->nSrc;
6290 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6292 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6293 ** of the tables shown in RefSrcList.pRef.
6295 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6296 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6298 static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){
6299 if( pExpr->op==TK_COLUMN
6300 || pExpr->op==TK_AGG_COLUMN
6302 int i;
6303 struct RefSrcList *p = pWalker->u.pRefSrcList;
6304 SrcList *pSrc = p->pRef;
6305 int nSrc = pSrc ? pSrc->nSrc : 0;
6306 for(i=0; i<nSrc; i++){
6307 if( pExpr->iTable==pSrc->a[i].iCursor ){
6308 pWalker->eCode |= 1;
6309 return WRC_Continue;
6312 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
6313 if( i>=p->nExclude ){
6314 pWalker->eCode |= 2;
6317 return WRC_Continue;
6321 ** Check to see if pExpr references any tables in pSrcList.
6322 ** Possible return values:
6324 ** 1 pExpr does references a table in pSrcList.
6326 ** 0 pExpr references some table that is not defined in either
6327 ** pSrcList or in subqueries of pExpr itself.
6329 ** -1 pExpr only references no tables at all, or it only
6330 ** references tables defined in subqueries of pExpr itself.
6332 ** As currently used, pExpr is always an aggregate function call. That
6333 ** fact is exploited for efficiency.
6335 int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){
6336 Walker w;
6337 struct RefSrcList x;
6338 assert( pParse->db!=0 );
6339 memset(&w, 0, sizeof(w));
6340 memset(&x, 0, sizeof(x));
6341 w.xExprCallback = exprRefToSrcList;
6342 w.xSelectCallback = selectRefEnter;
6343 w.xSelectCallback2 = selectRefLeave;
6344 w.u.pRefSrcList = &x;
6345 x.db = pParse->db;
6346 x.pRef = pSrcList;
6347 assert( pExpr->op==TK_AGG_FUNCTION );
6348 assert( ExprUseXList(pExpr) );
6349 sqlite3WalkExprList(&w, pExpr->x.pList);
6350 #ifndef SQLITE_OMIT_WINDOWFUNC
6351 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6352 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
6354 #endif
6355 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
6356 if( w.eCode & 0x01 ){
6357 return 1;
6358 }else if( w.eCode ){
6359 return 0;
6360 }else{
6361 return -1;
6366 ** This is a Walker expression node callback.
6368 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6369 ** object that is referenced does not refer directly to the Expr. If
6370 ** it does, make a copy. This is done because the pExpr argument is
6371 ** subject to change.
6373 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6374 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6376 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
6377 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
6378 && pExpr->pAggInfo!=0
6380 AggInfo *pAggInfo = pExpr->pAggInfo;
6381 int iAgg = pExpr->iAgg;
6382 Parse *pParse = pWalker->pParse;
6383 sqlite3 *db = pParse->db;
6384 assert( iAgg>=0 );
6385 if( pExpr->op!=TK_AGG_FUNCTION ){
6386 if( iAgg<pAggInfo->nColumn
6387 && pAggInfo->aCol[iAgg].pCExpr==pExpr
6389 pExpr = sqlite3ExprDup(db, pExpr, 0);
6390 if( pExpr ){
6391 pAggInfo->aCol[iAgg].pCExpr = pExpr;
6392 sqlite3ExprDeferredDelete(pParse, pExpr);
6395 }else{
6396 assert( pExpr->op==TK_AGG_FUNCTION );
6397 if( ALWAYS(iAgg<pAggInfo->nFunc)
6398 && pAggInfo->aFunc[iAgg].pFExpr==pExpr
6400 pExpr = sqlite3ExprDup(db, pExpr, 0);
6401 if( pExpr ){
6402 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
6403 sqlite3ExprDeferredDelete(pParse, pExpr);
6408 return WRC_Continue;
6412 ** Initialize a Walker object so that will persist AggInfo entries referenced
6413 ** by the tree that is walked.
6415 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
6416 memset(pWalker, 0, sizeof(*pWalker));
6417 pWalker->pParse = pParse;
6418 pWalker->xExprCallback = agginfoPersistExprCb;
6419 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
6423 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6424 ** the new element. Return a negative number if malloc fails.
6426 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
6427 int i;
6428 pInfo->aCol = sqlite3ArrayAllocate(
6430 pInfo->aCol,
6431 sizeof(pInfo->aCol[0]),
6432 &pInfo->nColumn,
6435 return i;
6439 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6440 ** the new element. Return a negative number if malloc fails.
6442 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
6443 int i;
6444 pInfo->aFunc = sqlite3ArrayAllocate(
6446 pInfo->aFunc,
6447 sizeof(pInfo->aFunc[0]),
6448 &pInfo->nFunc,
6451 return i;
6455 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6456 ** Return the index in aCol[] of the entry that describes that column.
6458 ** If no prior entry is found, create a new one and return -1. The
6459 ** new column will have an index of pAggInfo->nColumn-1.
6461 static void findOrCreateAggInfoColumn(
6462 Parse *pParse, /* Parsing context */
6463 AggInfo *pAggInfo, /* The AggInfo object to search and/or modify */
6464 Expr *pExpr /* Expr describing the column to find or insert */
6466 struct AggInfo_col *pCol;
6467 int k;
6469 assert( pAggInfo->iFirstReg==0 );
6470 pCol = pAggInfo->aCol;
6471 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
6472 if( pCol->pCExpr==pExpr ) return;
6473 if( pCol->iTable==pExpr->iTable
6474 && pCol->iColumn==pExpr->iColumn
6475 && pExpr->op!=TK_IF_NULL_ROW
6477 goto fix_up_expr;
6480 k = addAggInfoColumn(pParse->db, pAggInfo);
6481 if( k<0 ){
6482 /* OOM on resize */
6483 assert( pParse->db->mallocFailed );
6484 return;
6486 pCol = &pAggInfo->aCol[k];
6487 assert( ExprUseYTab(pExpr) );
6488 pCol->pTab = pExpr->y.pTab;
6489 pCol->iTable = pExpr->iTable;
6490 pCol->iColumn = pExpr->iColumn;
6491 pCol->iSorterColumn = -1;
6492 pCol->pCExpr = pExpr;
6493 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
6494 int j, n;
6495 ExprList *pGB = pAggInfo->pGroupBy;
6496 struct ExprList_item *pTerm = pGB->a;
6497 n = pGB->nExpr;
6498 for(j=0; j<n; j++, pTerm++){
6499 Expr *pE = pTerm->pExpr;
6500 if( pE->op==TK_COLUMN
6501 && pE->iTable==pExpr->iTable
6502 && pE->iColumn==pExpr->iColumn
6504 pCol->iSorterColumn = j;
6505 break;
6509 if( pCol->iSorterColumn<0 ){
6510 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
6512 fix_up_expr:
6513 ExprSetVVAProperty(pExpr, EP_NoReduce);
6514 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo );
6515 pExpr->pAggInfo = pAggInfo;
6516 if( pExpr->op==TK_COLUMN ){
6517 pExpr->op = TK_AGG_COLUMN;
6519 pExpr->iAgg = (i16)k;
6523 ** This is the xExprCallback for a tree walker. It is used to
6524 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6525 ** for additional information.
6527 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
6528 int i;
6529 NameContext *pNC = pWalker->u.pNC;
6530 Parse *pParse = pNC->pParse;
6531 SrcList *pSrcList = pNC->pSrcList;
6532 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
6534 assert( pNC->ncFlags & NC_UAggInfo );
6535 assert( pAggInfo->iFirstReg==0 );
6536 switch( pExpr->op ){
6537 default: {
6538 IndexedExpr *pIEpr;
6539 Expr tmp;
6540 assert( pParse->iSelfTab==0 );
6541 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
6542 if( pParse->pIdxEpr==0 ) break;
6543 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6544 int iDataCur = pIEpr->iDataCur;
6545 if( iDataCur<0 ) continue;
6546 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
6548 if( pIEpr==0 ) break;
6549 if( NEVER(!ExprUseYTab(pExpr)) ) break;
6550 for(i=0; i<pSrcList->nSrc; i++){
6551 if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
6553 if( i>=pSrcList->nSrc ) break;
6554 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
6555 if( pParse->nErr ){ return WRC_Abort; }
6557 /* If we reach this point, it means that expression pExpr can be
6558 ** translated into a reference to an index column as described by
6559 ** pIEpr.
6561 memset(&tmp, 0, sizeof(tmp));
6562 tmp.op = TK_AGG_COLUMN;
6563 tmp.iTable = pIEpr->iIdxCur;
6564 tmp.iColumn = pIEpr->iIdxCol;
6565 findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);
6566 if( pParse->nErr ){ return WRC_Abort; }
6567 assert( pAggInfo->aCol!=0 );
6568 assert( tmp.iAgg<pAggInfo->nColumn );
6569 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
6570 pExpr->pAggInfo = pAggInfo;
6571 pExpr->iAgg = tmp.iAgg;
6572 return WRC_Prune;
6574 case TK_IF_NULL_ROW:
6575 case TK_AGG_COLUMN:
6576 case TK_COLUMN: {
6577 testcase( pExpr->op==TK_AGG_COLUMN );
6578 testcase( pExpr->op==TK_COLUMN );
6579 testcase( pExpr->op==TK_IF_NULL_ROW );
6580 /* Check to see if the column is in one of the tables in the FROM
6581 ** clause of the aggregate query */
6582 if( ALWAYS(pSrcList!=0) ){
6583 SrcItem *pItem = pSrcList->a;
6584 for(i=0; i<pSrcList->nSrc; i++, pItem++){
6585 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6586 if( pExpr->iTable==pItem->iCursor ){
6587 findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
6588 break;
6589 } /* endif pExpr->iTable==pItem->iCursor */
6590 } /* end loop over pSrcList */
6592 return WRC_Continue;
6594 case TK_AGG_FUNCTION: {
6595 if( (pNC->ncFlags & NC_InAggFunc)==0
6596 && pWalker->walkerDepth==pExpr->op2
6598 /* Check to see if pExpr is a duplicate of another aggregate
6599 ** function that is already in the pAggInfo structure
6601 struct AggInfo_func *pItem = pAggInfo->aFunc;
6602 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
6603 if( pItem->pFExpr==pExpr ) break;
6604 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
6605 break;
6608 if( i>=pAggInfo->nFunc ){
6609 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6611 u8 enc = ENC(pParse->db);
6612 i = addAggInfoFunc(pParse->db, pAggInfo);
6613 if( i>=0 ){
6614 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
6615 pItem = &pAggInfo->aFunc[i];
6616 pItem->pFExpr = pExpr;
6617 assert( ExprUseUToken(pExpr) );
6618 pItem->pFunc = sqlite3FindFunction(pParse->db,
6619 pExpr->u.zToken,
6620 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
6621 if( pExpr->flags & EP_Distinct ){
6622 pItem->iDistinct = pParse->nTab++;
6623 }else{
6624 pItem->iDistinct = -1;
6628 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6630 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6631 ExprSetVVAProperty(pExpr, EP_NoReduce);
6632 pExpr->iAgg = (i16)i;
6633 pExpr->pAggInfo = pAggInfo;
6634 return WRC_Prune;
6635 }else{
6636 return WRC_Continue;
6640 return WRC_Continue;
6644 ** Analyze the pExpr expression looking for aggregate functions and
6645 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6646 ** points to. Additional entries are made on the AggInfo object as
6647 ** necessary.
6649 ** This routine should only be called after the expression has been
6650 ** analyzed by sqlite3ResolveExprNames().
6652 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
6653 Walker w;
6654 w.xExprCallback = analyzeAggregate;
6655 w.xSelectCallback = sqlite3WalkerDepthIncrease;
6656 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
6657 w.walkerDepth = 0;
6658 w.u.pNC = pNC;
6659 w.pParse = 0;
6660 assert( pNC->pSrcList!=0 );
6661 sqlite3WalkExpr(&w, pExpr);
6665 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6666 ** expression list. Return the number of errors.
6668 ** If an error is found, the analysis is cut short.
6670 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
6671 struct ExprList_item *pItem;
6672 int i;
6673 if( pList ){
6674 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
6675 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
6681 ** Allocate a single new register for use to hold some intermediate result.
6683 int sqlite3GetTempReg(Parse *pParse){
6684 if( pParse->nTempReg==0 ){
6685 return ++pParse->nMem;
6687 return pParse->aTempReg[--pParse->nTempReg];
6691 ** Deallocate a register, making available for reuse for some other
6692 ** purpose.
6694 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
6695 if( iReg ){
6696 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
6697 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
6698 pParse->aTempReg[pParse->nTempReg++] = iReg;
6704 ** Allocate or deallocate a block of nReg consecutive registers.
6706 int sqlite3GetTempRange(Parse *pParse, int nReg){
6707 int i, n;
6708 if( nReg==1 ) return sqlite3GetTempReg(pParse);
6709 i = pParse->iRangeReg;
6710 n = pParse->nRangeReg;
6711 if( nReg<=n ){
6712 pParse->iRangeReg += nReg;
6713 pParse->nRangeReg -= nReg;
6714 }else{
6715 i = pParse->nMem+1;
6716 pParse->nMem += nReg;
6718 return i;
6720 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
6721 if( nReg==1 ){
6722 sqlite3ReleaseTempReg(pParse, iReg);
6723 return;
6725 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
6726 if( nReg>pParse->nRangeReg ){
6727 pParse->nRangeReg = nReg;
6728 pParse->iRangeReg = iReg;
6733 ** Mark all temporary registers as being unavailable for reuse.
6735 ** Always invoke this procedure after coding a subroutine or co-routine
6736 ** that might be invoked from other parts of the code, to ensure that
6737 ** the sub/co-routine does not use registers in common with the code that
6738 ** invokes the sub/co-routine.
6740 void sqlite3ClearTempRegCache(Parse *pParse){
6741 pParse->nTempReg = 0;
6742 pParse->nRangeReg = 0;
6746 ** Make sure sufficient registers have been allocated so that
6747 ** iReg is a valid register number.
6749 void sqlite3TouchRegister(Parse *pParse, int iReg){
6750 if( pParse->nMem<iReg ) pParse->nMem = iReg;
6753 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
6755 ** Return the latest reusable register in the set of all registers.
6756 ** The value returned is no less than iMin. If any register iMin or
6757 ** greater is in permanent use, then return one more than that last
6758 ** permanent register.
6760 int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){
6761 const ExprList *pList = pParse->pConstExpr;
6762 if( pList ){
6763 int i;
6764 for(i=0; i<pList->nExpr; i++){
6765 if( pList->a[i].u.iConstExprReg>=iMin ){
6766 iMin = pList->a[i].u.iConstExprReg + 1;
6770 pParse->nTempReg = 0;
6771 pParse->nRangeReg = 0;
6772 return iMin;
6774 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
6777 ** Validate that no temporary register falls within the range of
6778 ** iFirst..iLast, inclusive. This routine is only call from within assert()
6779 ** statements.
6781 #ifdef SQLITE_DEBUG
6782 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
6783 int i;
6784 if( pParse->nRangeReg>0
6785 && pParse->iRangeReg+pParse->nRangeReg > iFirst
6786 && pParse->iRangeReg <= iLast
6788 return 0;
6790 for(i=0; i<pParse->nTempReg; i++){
6791 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
6792 return 0;
6795 if( pParse->pConstExpr ){
6796 ExprList *pList = pParse->pConstExpr;
6797 for(i=0; i<pList->nExpr; i++){
6798 int iReg = pList->a[i].u.iConstExprReg;
6799 if( iReg==0 ) continue;
6800 if( iReg>=iFirst && iReg<=iLast ) return 0;
6803 return 1;
6805 #endif /* SQLITE_DEBUG */