Fix a typo in a comment in a test case. No changes to code.
[sqlite.git] / src / expr.c
blob6d2b6d1339097e57556c6361e7bf70b4a4365b3d
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 ) break;
89 op = pExpr->op2;
90 if( NEVER( op==TK_REGISTER ) ) break;
92 return pExpr->affExpr;
96 ** Make a guess at all the possible datatypes of the result that could
97 ** be returned by an expression. Return a bitmask indicating the answer:
99 ** 0x01 Numeric
100 ** 0x02 Text
101 ** 0x04 Blob
103 ** If the expression must return NULL, then 0x00 is returned.
105 int sqlite3ExprDataType(const Expr *pExpr){
106 while( pExpr ){
107 switch( pExpr->op ){
108 case TK_COLLATE:
109 case TK_IF_NULL_ROW:
110 case TK_UPLUS: {
111 pExpr = pExpr->pLeft;
112 break;
114 case TK_NULL: {
115 pExpr = 0;
116 break;
118 case TK_STRING: {
119 return 0x02;
121 case TK_BLOB: {
122 return 0x04;
124 case TK_CONCAT: {
125 return 0x06;
127 case TK_VARIABLE:
128 case TK_AGG_FUNCTION:
129 case TK_FUNCTION: {
130 return 0x07;
132 case TK_COLUMN:
133 case TK_AGG_COLUMN:
134 case TK_SELECT:
135 case TK_CAST:
136 case TK_SELECT_COLUMN:
137 case TK_VECTOR: {
138 int aff = sqlite3ExprAffinity(pExpr);
139 if( aff>=SQLITE_AFF_NUMERIC ) return 0x05;
140 if( aff==SQLITE_AFF_TEXT ) return 0x06;
141 return 0x07;
143 case TK_CASE: {
144 int res = 0;
145 int ii;
146 ExprList *pList = pExpr->x.pList;
147 assert( ExprUseXList(pExpr) && pList!=0 );
148 assert( pList->nExpr > 0);
149 for(ii=1; ii<pList->nExpr; ii+=2){
150 res |= sqlite3ExprDataType(pList->a[ii].pExpr);
152 if( pList->nExpr % 2 ){
153 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);
155 return res;
157 default: {
158 return 0x01;
160 } /* End of switch(op) */
161 } /* End of while(pExpr) */
162 return 0x00;
166 ** Set the collating sequence for expression pExpr to be the collating
167 ** sequence named by pToken. Return a pointer to a new Expr node that
168 ** implements the COLLATE operator.
170 ** If a memory allocation error occurs, that fact is recorded in pParse->db
171 ** and the pExpr parameter is returned unchanged.
173 Expr *sqlite3ExprAddCollateToken(
174 const Parse *pParse, /* Parsing context */
175 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
176 const Token *pCollName, /* Name of collating sequence */
177 int dequote /* True to dequote pCollName */
179 if( pCollName->n>0 ){
180 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
181 if( pNew ){
182 pNew->pLeft = pExpr;
183 pNew->flags |= EP_Collate|EP_Skip;
184 pExpr = pNew;
187 return pExpr;
189 Expr *sqlite3ExprAddCollateString(
190 const Parse *pParse, /* Parsing context */
191 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
192 const char *zC /* The collating sequence name */
194 Token s;
195 assert( zC!=0 );
196 sqlite3TokenInit(&s, (char*)zC);
197 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
201 ** Skip over any TK_COLLATE operators.
203 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
204 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
205 assert( pExpr->op==TK_COLLATE );
206 pExpr = pExpr->pLeft;
208 return pExpr;
212 ** Skip over any TK_COLLATE operators and/or any unlikely()
213 ** or likelihood() or likely() functions at the root of an
214 ** expression.
216 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
217 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
218 if( ExprHasProperty(pExpr, EP_Unlikely) ){
219 assert( ExprUseXList(pExpr) );
220 assert( pExpr->x.pList->nExpr>0 );
221 assert( pExpr->op==TK_FUNCTION );
222 pExpr = pExpr->x.pList->a[0].pExpr;
223 }else if( pExpr->op==TK_COLLATE ){
224 pExpr = pExpr->pLeft;
225 }else{
226 break;
229 return pExpr;
233 ** Return the collation sequence for the expression pExpr. If
234 ** there is no defined collating sequence, return NULL.
236 ** See also: sqlite3ExprNNCollSeq()
238 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
239 ** default collation if pExpr has no defined collation.
241 ** The collating sequence might be determined by a COLLATE operator
242 ** or by the presence of a column with a defined collating sequence.
243 ** COLLATE operators take first precedence. Left operands take
244 ** precedence over right operands.
246 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
247 sqlite3 *db = pParse->db;
248 CollSeq *pColl = 0;
249 const Expr *p = pExpr;
250 while( p ){
251 int op = p->op;
252 if( op==TK_REGISTER ) op = p->op2;
253 if( (op==TK_AGG_COLUMN && p->y.pTab!=0)
254 || op==TK_COLUMN || op==TK_TRIGGER
256 int j;
257 assert( ExprUseYTab(p) );
258 assert( p->y.pTab!=0 );
259 if( (j = p->iColumn)>=0 ){
260 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
261 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
263 break;
265 if( op==TK_CAST || op==TK_UPLUS ){
266 p = p->pLeft;
267 continue;
269 if( op==TK_VECTOR ){
270 assert( ExprUseXList(p) );
271 p = p->x.pList->a[0].pExpr;
272 continue;
274 if( op==TK_COLLATE ){
275 assert( !ExprHasProperty(p, EP_IntValue) );
276 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
277 break;
279 if( p->flags & EP_Collate ){
280 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
281 p = p->pLeft;
282 }else{
283 Expr *pNext = p->pRight;
284 /* The Expr.x union is never used at the same time as Expr.pRight */
285 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
286 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
287 int i;
288 for(i=0; i<p->x.pList->nExpr; i++){
289 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
290 pNext = p->x.pList->a[i].pExpr;
291 break;
295 p = pNext;
297 }else{
298 break;
301 if( sqlite3CheckCollSeq(pParse, pColl) ){
302 pColl = 0;
304 return pColl;
308 ** Return the collation sequence for the expression pExpr. If
309 ** there is no defined collating sequence, return a pointer to the
310 ** default collation sequence.
312 ** See also: sqlite3ExprCollSeq()
314 ** The sqlite3ExprCollSeq() routine works the same except that it
315 ** returns NULL if there is no defined collation.
317 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
318 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
319 if( p==0 ) p = pParse->db->pDfltColl;
320 assert( p!=0 );
321 return p;
325 ** Return TRUE if the two expressions have equivalent collating sequences.
327 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
328 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
329 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
330 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
334 ** pExpr is an operand of a comparison operator. aff2 is the
335 ** type affinity of the other operand. This routine returns the
336 ** type affinity that should be used for the comparison operator.
338 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
339 char aff1 = sqlite3ExprAffinity(pExpr);
340 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
341 /* Both sides of the comparison are columns. If one has numeric
342 ** affinity, use that. Otherwise use no affinity.
344 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
345 return SQLITE_AFF_NUMERIC;
346 }else{
347 return SQLITE_AFF_BLOB;
349 }else{
350 /* One side is a column, the other is not. Use the columns affinity. */
351 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
352 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
357 ** pExpr is a comparison operator. Return the type affinity that should
358 ** be applied to both operands prior to doing the comparison.
360 static char comparisonAffinity(const Expr *pExpr){
361 char aff;
362 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
363 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
364 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
365 assert( pExpr->pLeft );
366 aff = sqlite3ExprAffinity(pExpr->pLeft);
367 if( pExpr->pRight ){
368 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
369 }else if( ExprUseXSelect(pExpr) ){
370 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
371 }else if( aff==0 ){
372 aff = SQLITE_AFF_BLOB;
374 return aff;
378 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
379 ** idx_affinity is the affinity of an indexed column. Return true
380 ** if the index with affinity idx_affinity may be used to implement
381 ** the comparison in pExpr.
383 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
384 char aff = comparisonAffinity(pExpr);
385 if( aff<SQLITE_AFF_TEXT ){
386 return 1;
388 if( aff==SQLITE_AFF_TEXT ){
389 return idx_affinity==SQLITE_AFF_TEXT;
391 return sqlite3IsNumericAffinity(idx_affinity);
395 ** Return the P5 value that should be used for a binary comparison
396 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
398 static u8 binaryCompareP5(
399 const Expr *pExpr1, /* Left operand */
400 const Expr *pExpr2, /* Right operand */
401 int jumpIfNull /* Extra flags added to P5 */
403 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
404 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
405 return aff;
409 ** Return a pointer to the collation sequence that should be used by
410 ** a binary comparison operator comparing pLeft and pRight.
412 ** If the left hand expression has a collating sequence type, then it is
413 ** used. Otherwise the collation sequence for the right hand expression
414 ** is used, or the default (BINARY) if neither expression has a collating
415 ** type.
417 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
418 ** it is not considered.
420 CollSeq *sqlite3BinaryCompareCollSeq(
421 Parse *pParse,
422 const Expr *pLeft,
423 const Expr *pRight
425 CollSeq *pColl;
426 assert( pLeft );
427 if( pLeft->flags & EP_Collate ){
428 pColl = sqlite3ExprCollSeq(pParse, pLeft);
429 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
430 pColl = sqlite3ExprCollSeq(pParse, pRight);
431 }else{
432 pColl = sqlite3ExprCollSeq(pParse, pLeft);
433 if( !pColl ){
434 pColl = sqlite3ExprCollSeq(pParse, pRight);
437 return pColl;
440 /* Expression p is a comparison operator. Return a collation sequence
441 ** appropriate for the comparison operator.
443 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
444 ** However, if the OP_Commuted flag is set, then the order of the operands
445 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
446 ** correct collating sequence is found.
448 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
449 if( ExprHasProperty(p, EP_Commuted) ){
450 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
451 }else{
452 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
457 ** Generate code for a comparison operator.
459 static int codeCompare(
460 Parse *pParse, /* The parsing (and code generating) context */
461 Expr *pLeft, /* The left operand */
462 Expr *pRight, /* The right operand */
463 int opcode, /* The comparison opcode */
464 int in1, int in2, /* Register holding operands */
465 int dest, /* Jump here if true. */
466 int jumpIfNull, /* If true, jump if either operand is NULL */
467 int isCommuted /* The comparison has been commuted */
469 int p5;
470 int addr;
471 CollSeq *p4;
473 if( pParse->nErr ) return 0;
474 if( isCommuted ){
475 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
476 }else{
477 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
479 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
480 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
481 (void*)p4, P4_COLLSEQ);
482 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
483 return addr;
487 ** Return true if expression pExpr is a vector, or false otherwise.
489 ** A vector is defined as any expression that results in two or more
490 ** columns of result. Every TK_VECTOR node is an vector because the
491 ** parser will not generate a TK_VECTOR with fewer than two entries.
492 ** But a TK_SELECT might be either a vector or a scalar. It is only
493 ** considered a vector if it has two or more result columns.
495 int sqlite3ExprIsVector(const Expr *pExpr){
496 return sqlite3ExprVectorSize(pExpr)>1;
500 ** If the expression passed as the only argument is of type TK_VECTOR
501 ** return the number of expressions in the vector. Or, if the expression
502 ** is a sub-select, return the number of columns in the sub-select. For
503 ** any other type of expression, return 1.
505 int sqlite3ExprVectorSize(const Expr *pExpr){
506 u8 op = pExpr->op;
507 if( op==TK_REGISTER ) op = pExpr->op2;
508 if( op==TK_VECTOR ){
509 assert( ExprUseXList(pExpr) );
510 return pExpr->x.pList->nExpr;
511 }else if( op==TK_SELECT ){
512 assert( ExprUseXSelect(pExpr) );
513 return pExpr->x.pSelect->pEList->nExpr;
514 }else{
515 return 1;
520 ** Return a pointer to a subexpression of pVector that is the i-th
521 ** column of the vector (numbered starting with 0). The caller must
522 ** ensure that i is within range.
524 ** If pVector is really a scalar (and "scalar" here includes subqueries
525 ** that return a single column!) then return pVector unmodified.
527 ** pVector retains ownership of the returned subexpression.
529 ** If the vector is a (SELECT ...) then the expression returned is
530 ** just the expression for the i-th term of the result set, and may
531 ** not be ready for evaluation because the table cursor has not yet
532 ** been positioned.
534 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
535 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
536 if( sqlite3ExprIsVector(pVector) ){
537 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
538 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
539 assert( ExprUseXSelect(pVector) );
540 return pVector->x.pSelect->pEList->a[i].pExpr;
541 }else{
542 assert( ExprUseXList(pVector) );
543 return pVector->x.pList->a[i].pExpr;
546 return pVector;
550 ** Compute and return a new Expr object which when passed to
551 ** sqlite3ExprCode() will generate all necessary code to compute
552 ** the iField-th column of the vector expression pVector.
554 ** It is ok for pVector to be a scalar (as long as iField==0).
555 ** In that case, this routine works like sqlite3ExprDup().
557 ** The caller owns the returned Expr object and is responsible for
558 ** ensuring that the returned value eventually gets freed.
560 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
561 ** then the returned object will reference pVector and so pVector must remain
562 ** valid for the life of the returned object. If pVector is a TK_VECTOR
563 ** or a scalar expression, then it can be deleted as soon as this routine
564 ** returns.
566 ** A trick to cause a TK_SELECT pVector to be deleted together with
567 ** the returned Expr object is to attach the pVector to the pRight field
568 ** of the returned TK_SELECT_COLUMN Expr object.
570 Expr *sqlite3ExprForVectorField(
571 Parse *pParse, /* Parsing context */
572 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
573 int iField, /* Which column of the vector to return */
574 int nField /* Total number of columns in the vector */
576 Expr *pRet;
577 if( pVector->op==TK_SELECT ){
578 assert( ExprUseXSelect(pVector) );
579 /* The TK_SELECT_COLUMN Expr node:
581 ** pLeft: pVector containing TK_SELECT. Not deleted.
582 ** pRight: not used. But recursively deleted.
583 ** iColumn: Index of a column in pVector
584 ** iTable: 0 or the number of columns on the LHS of an assignment
585 ** pLeft->iTable: First in an array of register holding result, or 0
586 ** if the result is not yet computed.
588 ** sqlite3ExprDelete() specifically skips the recursive delete of
589 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
590 ** can be attached to pRight to cause this node to take ownership of
591 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
592 ** with the same pLeft pointer to the pVector, but only one of them
593 ** will own the pVector.
595 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
596 if( pRet ){
597 ExprSetProperty(pRet, EP_FullSize);
598 pRet->iTable = nField;
599 pRet->iColumn = iField;
600 pRet->pLeft = pVector;
602 }else{
603 if( pVector->op==TK_VECTOR ){
604 Expr **ppVector;
605 assert( ExprUseXList(pVector) );
606 ppVector = &pVector->x.pList->a[iField].pExpr;
607 pVector = *ppVector;
608 if( IN_RENAME_OBJECT ){
609 /* This must be a vector UPDATE inside a trigger */
610 *ppVector = 0;
611 return pVector;
614 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
616 return pRet;
620 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
621 ** it. Return the register in which the result is stored (or, if the
622 ** sub-select returns more than one column, the first in an array
623 ** of registers in which the result is stored).
625 ** If pExpr is not a TK_SELECT expression, return 0.
627 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
628 int reg = 0;
629 #ifndef SQLITE_OMIT_SUBQUERY
630 if( pExpr->op==TK_SELECT ){
631 reg = sqlite3CodeSubselect(pParse, pExpr);
633 #endif
634 return reg;
638 ** Argument pVector points to a vector expression - either a TK_VECTOR
639 ** or TK_SELECT that returns more than one column. This function returns
640 ** the register number of a register that contains the value of
641 ** element iField of the vector.
643 ** If pVector is a TK_SELECT expression, then code for it must have
644 ** already been generated using the exprCodeSubselect() routine. In this
645 ** case parameter regSelect should be the first in an array of registers
646 ** containing the results of the sub-select.
648 ** If pVector is of type TK_VECTOR, then code for the requested field
649 ** is generated. In this case (*pRegFree) may be set to the number of
650 ** a temporary register to be freed by the caller before returning.
652 ** Before returning, output parameter (*ppExpr) is set to point to the
653 ** Expr object corresponding to element iElem of the vector.
655 static int exprVectorRegister(
656 Parse *pParse, /* Parse context */
657 Expr *pVector, /* Vector to extract element from */
658 int iField, /* Field to extract from pVector */
659 int regSelect, /* First in array of registers */
660 Expr **ppExpr, /* OUT: Expression element */
661 int *pRegFree /* OUT: Temp register to free */
663 u8 op = pVector->op;
664 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
665 if( op==TK_REGISTER ){
666 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
667 return pVector->iTable+iField;
669 if( op==TK_SELECT ){
670 assert( ExprUseXSelect(pVector) );
671 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
672 return regSelect+iField;
674 if( op==TK_VECTOR ){
675 assert( ExprUseXList(pVector) );
676 *ppExpr = pVector->x.pList->a[iField].pExpr;
677 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
679 return 0;
683 ** Expression pExpr is a comparison between two vector values. Compute
684 ** the result of the comparison (1, 0, or NULL) and write that
685 ** result into register dest.
687 ** The caller must satisfy the following preconditions:
689 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
690 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
691 ** otherwise: op==pExpr->op and p5==0
693 static void codeVectorCompare(
694 Parse *pParse, /* Code generator context */
695 Expr *pExpr, /* The comparison operation */
696 int dest, /* Write results into this register */
697 u8 op, /* Comparison operator */
698 u8 p5 /* SQLITE_NULLEQ or zero */
700 Vdbe *v = pParse->pVdbe;
701 Expr *pLeft = pExpr->pLeft;
702 Expr *pRight = pExpr->pRight;
703 int nLeft = sqlite3ExprVectorSize(pLeft);
704 int i;
705 int regLeft = 0;
706 int regRight = 0;
707 u8 opx = op;
708 int addrCmp = 0;
709 int addrDone = sqlite3VdbeMakeLabel(pParse);
710 int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
712 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
713 if( pParse->nErr ) return;
714 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
715 sqlite3ErrorMsg(pParse, "row value misused");
716 return;
718 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
719 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
720 || pExpr->op==TK_LT || pExpr->op==TK_GT
721 || pExpr->op==TK_LE || pExpr->op==TK_GE
723 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
724 || (pExpr->op==TK_ISNOT && op==TK_NE) );
725 assert( p5==0 || pExpr->op!=op );
726 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
728 if( op==TK_LE ) opx = TK_LT;
729 if( op==TK_GE ) opx = TK_GT;
730 if( op==TK_NE ) opx = TK_EQ;
732 regLeft = exprCodeSubselect(pParse, pLeft);
733 regRight = exprCodeSubselect(pParse, pRight);
735 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
736 for(i=0; 1 /*Loop exits by "break"*/; i++){
737 int regFree1 = 0, regFree2 = 0;
738 Expr *pL = 0, *pR = 0;
739 int r1, r2;
740 assert( i>=0 && i<nLeft );
741 if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
742 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
743 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
744 addrCmp = sqlite3VdbeCurrentAddr(v);
745 codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
746 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
747 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
748 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
749 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
750 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
751 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
752 sqlite3ReleaseTempReg(pParse, regFree1);
753 sqlite3ReleaseTempReg(pParse, regFree2);
754 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
755 addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
756 testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
757 testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
759 if( p5==SQLITE_NULLEQ ){
760 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
761 }else{
762 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
764 if( i==nLeft-1 ){
765 break;
767 if( opx==TK_EQ ){
768 sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
769 }else{
770 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
771 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
772 if( i==nLeft-2 ) opx = op;
775 sqlite3VdbeJumpHere(v, addrCmp);
776 sqlite3VdbeResolveLabel(v, addrDone);
777 if( op==TK_NE ){
778 sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
782 #if SQLITE_MAX_EXPR_DEPTH>0
784 ** Check that argument nHeight is less than or equal to the maximum
785 ** expression depth allowed. If it is not, leave an error message in
786 ** pParse.
788 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
789 int rc = SQLITE_OK;
790 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
791 if( nHeight>mxHeight ){
792 sqlite3ErrorMsg(pParse,
793 "Expression tree is too large (maximum depth %d)", mxHeight
795 rc = SQLITE_ERROR;
797 return rc;
800 /* The following three functions, heightOfExpr(), heightOfExprList()
801 ** and heightOfSelect(), are used to determine the maximum height
802 ** of any expression tree referenced by the structure passed as the
803 ** first argument.
805 ** If this maximum height is greater than the current value pointed
806 ** to by pnHeight, the second parameter, then set *pnHeight to that
807 ** value.
809 static void heightOfExpr(const Expr *p, int *pnHeight){
810 if( p ){
811 if( p->nHeight>*pnHeight ){
812 *pnHeight = p->nHeight;
816 static void heightOfExprList(const ExprList *p, int *pnHeight){
817 if( p ){
818 int i;
819 for(i=0; i<p->nExpr; i++){
820 heightOfExpr(p->a[i].pExpr, pnHeight);
824 static void heightOfSelect(const Select *pSelect, int *pnHeight){
825 const Select *p;
826 for(p=pSelect; p; p=p->pPrior){
827 heightOfExpr(p->pWhere, pnHeight);
828 heightOfExpr(p->pHaving, pnHeight);
829 heightOfExpr(p->pLimit, pnHeight);
830 heightOfExprList(p->pEList, pnHeight);
831 heightOfExprList(p->pGroupBy, pnHeight);
832 heightOfExprList(p->pOrderBy, pnHeight);
837 ** Set the Expr.nHeight variable in the structure passed as an
838 ** argument. An expression with no children, Expr.pList or
839 ** Expr.pSelect member has a height of 1. Any other expression
840 ** has a height equal to the maximum height of any other
841 ** referenced Expr plus one.
843 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
844 ** if appropriate.
846 static void exprSetHeight(Expr *p){
847 int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
848 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
849 nHeight = p->pRight->nHeight;
851 if( ExprUseXSelect(p) ){
852 heightOfSelect(p->x.pSelect, &nHeight);
853 }else if( p->x.pList ){
854 heightOfExprList(p->x.pList, &nHeight);
855 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
857 p->nHeight = nHeight + 1;
861 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
862 ** the height is greater than the maximum allowed expression depth,
863 ** leave an error in pParse.
865 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
866 ** Expr.flags.
868 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
869 if( pParse->nErr ) return;
870 exprSetHeight(p);
871 sqlite3ExprCheckHeight(pParse, p->nHeight);
875 ** Return the maximum height of any expression tree referenced
876 ** by the select statement passed as an argument.
878 int sqlite3SelectExprHeight(const Select *p){
879 int nHeight = 0;
880 heightOfSelect(p, &nHeight);
881 return nHeight;
883 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
885 ** Propagate all EP_Propagate flags from the Expr.x.pList into
886 ** Expr.flags.
888 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
889 if( pParse->nErr ) return;
890 if( p && ExprUseXList(p) && p->x.pList ){
891 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
894 #define exprSetHeight(y)
895 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
898 ** Set the error offset for an Expr node, if possible.
900 void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){
901 if( pExpr==0 ) return;
902 if( NEVER(ExprUseWJoin(pExpr)) ) return;
903 pExpr->w.iOfst = iOfst;
907 ** This routine is the core allocator for Expr nodes.
909 ** Construct a new expression node and return a pointer to it. Memory
910 ** for this node and for the pToken argument is a single allocation
911 ** obtained from sqlite3DbMalloc(). The calling function
912 ** is responsible for making sure the node eventually gets freed.
914 ** If dequote is true, then the token (if it exists) is dequoted.
915 ** If dequote is false, no dequoting is performed. The deQuote
916 ** parameter is ignored if pToken is NULL or if the token does not
917 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
918 ** then the EP_DblQuoted flag is set on the expression node.
920 ** Special case (tag-20240227-a): If op==TK_INTEGER and pToken points to
921 ** a string that can be translated into a 32-bit integer, then the token is
922 ** not stored in u.zToken. Instead, the integer values is written
923 ** into u.iValue and the EP_IntValue flag is set. No extra storage
924 ** is allocated to hold the integer text and the dequote flag is ignored.
925 ** See also tag-20240227-b.
927 Expr *sqlite3ExprAlloc(
928 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
929 int op, /* Expression opcode */
930 const Token *pToken, /* Token argument. Might be NULL */
931 int dequote /* True to dequote */
933 Expr *pNew;
934 int nExtra = 0;
935 int iValue = 0;
937 assert( db!=0 );
938 if( pToken ){
939 if( op!=TK_INTEGER || pToken->z==0
940 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
941 nExtra = pToken->n+1; /* tag-20240227-a */
942 assert( iValue>=0 );
945 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
946 if( pNew ){
947 memset(pNew, 0, sizeof(Expr));
948 pNew->op = (u8)op;
949 pNew->iAgg = -1;
950 if( pToken ){
951 if( nExtra==0 ){
952 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
953 pNew->u.iValue = iValue;
954 }else{
955 pNew->u.zToken = (char*)&pNew[1];
956 assert( pToken->z!=0 || pToken->n==0 );
957 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
958 pNew->u.zToken[pToken->n] = 0;
959 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
960 sqlite3DequoteExpr(pNew);
964 #if SQLITE_MAX_EXPR_DEPTH>0
965 pNew->nHeight = 1;
966 #endif
968 return pNew;
972 ** Allocate a new expression node from a zero-terminated token that has
973 ** already been dequoted.
975 Expr *sqlite3Expr(
976 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
977 int op, /* Expression opcode */
978 const char *zToken /* Token argument. Might be NULL */
980 Token x;
981 x.z = zToken;
982 x.n = sqlite3Strlen30(zToken);
983 return sqlite3ExprAlloc(db, op, &x, 0);
987 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
989 ** If pRoot==NULL that means that a memory allocation error has occurred.
990 ** In that case, delete the subtrees pLeft and pRight.
992 void sqlite3ExprAttachSubtrees(
993 sqlite3 *db,
994 Expr *pRoot,
995 Expr *pLeft,
996 Expr *pRight
998 if( pRoot==0 ){
999 assert( db->mallocFailed );
1000 sqlite3ExprDelete(db, pLeft);
1001 sqlite3ExprDelete(db, pRight);
1002 }else{
1003 assert( ExprUseXList(pRoot) );
1004 assert( pRoot->x.pSelect==0 );
1005 if( pRight ){
1006 pRoot->pRight = pRight;
1007 pRoot->flags |= EP_Propagate & pRight->flags;
1008 #if SQLITE_MAX_EXPR_DEPTH>0
1009 pRoot->nHeight = pRight->nHeight+1;
1010 }else{
1011 pRoot->nHeight = 1;
1012 #endif
1014 if( pLeft ){
1015 pRoot->pLeft = pLeft;
1016 pRoot->flags |= EP_Propagate & pLeft->flags;
1017 #if SQLITE_MAX_EXPR_DEPTH>0
1018 if( pLeft->nHeight>=pRoot->nHeight ){
1019 pRoot->nHeight = pLeft->nHeight+1;
1021 #endif
1027 ** Allocate an Expr node which joins as many as two subtrees.
1029 ** One or both of the subtrees can be NULL. Return a pointer to the new
1030 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1031 ** free the subtrees and return NULL.
1033 Expr *sqlite3PExpr(
1034 Parse *pParse, /* Parsing context */
1035 int op, /* Expression opcode */
1036 Expr *pLeft, /* Left operand */
1037 Expr *pRight /* Right operand */
1039 Expr *p;
1040 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
1041 if( p ){
1042 memset(p, 0, sizeof(Expr));
1043 p->op = op & 0xff;
1044 p->iAgg = -1;
1045 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
1046 sqlite3ExprCheckHeight(pParse, p->nHeight);
1047 }else{
1048 sqlite3ExprDelete(pParse->db, pLeft);
1049 sqlite3ExprDelete(pParse->db, pRight);
1051 return p;
1055 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1056 ** do a memory allocation failure) then delete the pSelect object.
1058 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
1059 if( pExpr ){
1060 pExpr->x.pSelect = pSelect;
1061 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
1062 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
1063 }else{
1064 assert( pParse->db->mallocFailed );
1065 sqlite3SelectDelete(pParse->db, pSelect);
1070 ** Expression list pEList is a list of vector values. This function
1071 ** converts the contents of pEList to a VALUES(...) Select statement
1072 ** returning 1 row for each element of the list. For example, the
1073 ** expression list:
1075 ** ( (1,2), (3,4) (5,6) )
1077 ** is translated to the equivalent of:
1079 ** VALUES(1,2), (3,4), (5,6)
1081 ** Each of the vector values in pEList must contain exactly nElem terms.
1082 ** If a list element that is not a vector or does not contain nElem terms,
1083 ** an error message is left in pParse.
1085 ** This is used as part of processing IN(...) expressions with a list
1086 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1088 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){
1089 int ii;
1090 Select *pRet = 0;
1091 assert( nElem>1 );
1092 for(ii=0; ii<pEList->nExpr; ii++){
1093 Select *pSel;
1094 Expr *pExpr = pEList->a[ii].pExpr;
1095 int nExprElem;
1096 if( pExpr->op==TK_VECTOR ){
1097 assert( ExprUseXList(pExpr) );
1098 nExprElem = pExpr->x.pList->nExpr;
1099 }else{
1100 nExprElem = 1;
1102 if( nExprElem!=nElem ){
1103 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
1104 nExprElem, nExprElem>1?"s":"", nElem
1106 break;
1108 assert( ExprUseXList(pExpr) );
1109 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
1110 pExpr->x.pList = 0;
1111 if( pSel ){
1112 if( pRet ){
1113 pSel->op = TK_ALL;
1114 pSel->pPrior = pRet;
1116 pRet = pSel;
1120 if( pRet && pRet->pPrior ){
1121 pRet->selFlags |= SF_MultiValue;
1123 sqlite3ExprListDelete(pParse->db, pEList);
1124 return pRet;
1128 ** Join two expressions using an AND operator. If either expression is
1129 ** NULL, then just return the other expression.
1131 ** If one side or the other of the AND is known to be false, and neither side
1132 ** is part of an ON clause, then instead of returning an AND expression,
1133 ** just return a constant expression with a value of false.
1135 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
1136 sqlite3 *db = pParse->db;
1137 if( pLeft==0 ){
1138 return pRight;
1139 }else if( pRight==0 ){
1140 return pLeft;
1141 }else{
1142 u32 f = pLeft->flags | pRight->flags;
1143 if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse
1144 && !IN_RENAME_OBJECT
1146 sqlite3ExprDeferredDelete(pParse, pLeft);
1147 sqlite3ExprDeferredDelete(pParse, pRight);
1148 return sqlite3Expr(db, TK_INTEGER, "0");
1149 }else{
1150 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
1156 ** Construct a new expression node for a function with multiple
1157 ** arguments.
1159 Expr *sqlite3ExprFunction(
1160 Parse *pParse, /* Parsing context */
1161 ExprList *pList, /* Argument list */
1162 const Token *pToken, /* Name of the function */
1163 int eDistinct /* SF_Distinct or SF_ALL or 0 */
1165 Expr *pNew;
1166 sqlite3 *db = pParse->db;
1167 assert( pToken );
1168 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
1169 if( pNew==0 ){
1170 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
1171 return 0;
1173 assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) );
1174 pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
1175 if( pList
1176 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
1177 && !pParse->nested
1179 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
1181 pNew->x.pList = pList;
1182 ExprSetProperty(pNew, EP_HasFunc);
1183 assert( ExprUseXList(pNew) );
1184 sqlite3ExprSetHeightAndFlags(pParse, pNew);
1185 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
1186 return pNew;
1190 ** Report an error when attempting to use an ORDER BY clause within
1191 ** the arguments of a non-aggregate function.
1193 void sqlite3ExprOrderByAggregateError(Parse *pParse, Expr *p){
1194 sqlite3ErrorMsg(pParse,
1195 "ORDER BY may not be used with non-aggregate %#T()", p
1200 ** Attach an ORDER BY clause to a function call.
1202 ** functionname( arguments ORDER BY sortlist )
1203 ** \_____________________/ \______/
1204 ** pExpr pOrderBy
1206 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
1207 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
1209 void sqlite3ExprAddFunctionOrderBy(
1210 Parse *pParse, /* Parsing context */
1211 Expr *pExpr, /* The function call to which ORDER BY is to be added */
1212 ExprList *pOrderBy /* The ORDER BY clause to add */
1214 Expr *pOB;
1215 sqlite3 *db = pParse->db;
1216 if( NEVER(pOrderBy==0) ){
1217 assert( db->mallocFailed );
1218 return;
1220 if( pExpr==0 ){
1221 assert( db->mallocFailed );
1222 sqlite3ExprListDelete(db, pOrderBy);
1223 return;
1225 assert( pExpr->op==TK_FUNCTION );
1226 assert( pExpr->pLeft==0 );
1227 assert( ExprUseXList(pExpr) );
1228 if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){
1229 /* Ignore ORDER BY on zero-argument aggregates */
1230 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pOrderBy);
1231 return;
1233 if( IsWindowFunc(pExpr) ){
1234 sqlite3ExprOrderByAggregateError(pParse, pExpr);
1235 sqlite3ExprListDelete(db, pOrderBy);
1236 return;
1239 pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0);
1240 if( pOB==0 ){
1241 sqlite3ExprListDelete(db, pOrderBy);
1242 return;
1244 pOB->x.pList = pOrderBy;
1245 assert( ExprUseXList(pOB) );
1246 pExpr->pLeft = pOB;
1247 ExprSetProperty(pOB, EP_FullSize);
1251 ** Check to see if a function is usable according to current access
1252 ** rules:
1254 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1256 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1257 ** top-level SQL
1259 ** If the function is not usable, create an error.
1261 void sqlite3ExprFunctionUsable(
1262 Parse *pParse, /* Parsing and code generating context */
1263 const Expr *pExpr, /* The function invocation */
1264 const FuncDef *pDef /* The function being invoked */
1266 assert( !IN_RENAME_OBJECT );
1267 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
1268 if( ExprHasProperty(pExpr, EP_FromDDL) ){
1269 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
1270 || (pParse->db->flags & SQLITE_TrustedSchema)==0
1272 /* Functions prohibited in triggers and views if:
1273 ** (1) tagged with SQLITE_DIRECTONLY
1274 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1275 ** is tagged with SQLITE_FUNC_UNSAFE) and
1276 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1277 ** that the schema is possibly tainted).
1279 sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr);
1285 ** Assign a variable number to an expression that encodes a wildcard
1286 ** in the original SQL statement.
1288 ** Wildcards consisting of a single "?" are assigned the next sequential
1289 ** variable number.
1291 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1292 ** sure "nnn" is not too big to avoid a denial of service attack when
1293 ** the SQL statement comes from an external source.
1295 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1296 ** as the previous instance of the same wildcard. Or if this is the first
1297 ** instance of the wildcard, the next sequential variable number is
1298 ** assigned.
1300 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1301 sqlite3 *db = pParse->db;
1302 const char *z;
1303 ynVar x;
1305 if( pExpr==0 ) return;
1306 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1307 z = pExpr->u.zToken;
1308 assert( z!=0 );
1309 assert( z[0]!=0 );
1310 assert( n==(u32)sqlite3Strlen30(z) );
1311 if( z[1]==0 ){
1312 /* Wildcard of the form "?". Assign the next variable number */
1313 assert( z[0]=='?' );
1314 x = (ynVar)(++pParse->nVar);
1315 }else{
1316 int doAdd = 0;
1317 if( z[0]=='?' ){
1318 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1319 ** use it as the variable number */
1320 i64 i;
1321 int bOk;
1322 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1323 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1324 bOk = 1;
1325 }else{
1326 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1328 testcase( i==0 );
1329 testcase( i==1 );
1330 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1331 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1332 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1333 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1334 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1335 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1336 return;
1338 x = (ynVar)i;
1339 if( x>pParse->nVar ){
1340 pParse->nVar = (int)x;
1341 doAdd = 1;
1342 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1343 doAdd = 1;
1345 }else{
1346 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1347 ** number as the prior appearance of the same name, or if the name
1348 ** has never appeared before, reuse the same variable number
1350 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1351 if( x==0 ){
1352 x = (ynVar)(++pParse->nVar);
1353 doAdd = 1;
1356 if( doAdd ){
1357 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1360 pExpr->iColumn = x;
1361 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1362 sqlite3ErrorMsg(pParse, "too many SQL variables");
1363 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1368 ** Recursively delete an expression tree.
1370 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1371 assert( p!=0 );
1372 assert( db!=0 );
1373 exprDeleteRestart:
1374 assert( !ExprUseUValue(p) || p->u.iValue>=0 );
1375 assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
1376 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
1377 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
1378 #ifdef SQLITE_DEBUG
1379 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1380 assert( p->pLeft==0 );
1381 assert( p->pRight==0 );
1382 assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
1383 assert( !ExprUseXList(p) || p->x.pList==0 );
1385 #endif
1386 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1387 /* The Expr.x union is never used at the same time as Expr.pRight */
1388 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
1389 if( p->pRight ){
1390 assert( !ExprHasProperty(p, EP_WinFunc) );
1391 sqlite3ExprDeleteNN(db, p->pRight);
1392 }else if( ExprUseXSelect(p) ){
1393 assert( !ExprHasProperty(p, EP_WinFunc) );
1394 sqlite3SelectDelete(db, p->x.pSelect);
1395 }else{
1396 sqlite3ExprListDelete(db, p->x.pList);
1397 #ifndef SQLITE_OMIT_WINDOWFUNC
1398 if( ExprHasProperty(p, EP_WinFunc) ){
1399 sqlite3WindowDelete(db, p->y.pWin);
1401 #endif
1403 if( p->pLeft && p->op!=TK_SELECT_COLUMN ){
1404 Expr *pLeft = p->pLeft;
1405 if( !ExprHasProperty(p, EP_Static)
1406 && !ExprHasProperty(pLeft, EP_Static)
1408 /* Avoid unnecessary recursion on unary operators */
1409 sqlite3DbNNFreeNN(db, p);
1410 p = pLeft;
1411 goto exprDeleteRestart;
1412 }else{
1413 sqlite3ExprDeleteNN(db, pLeft);
1417 if( !ExprHasProperty(p, EP_Static) ){
1418 sqlite3DbNNFreeNN(db, p);
1421 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1422 if( p ) sqlite3ExprDeleteNN(db, p);
1424 void sqlite3ExprDeleteGeneric(sqlite3 *db, void *p){
1425 if( ALWAYS(p) ) sqlite3ExprDeleteNN(db, (Expr*)p);
1429 ** Clear both elements of an OnOrUsing object
1431 void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){
1432 if( p==0 ){
1433 /* Nothing to clear */
1434 }else if( p->pOn ){
1435 sqlite3ExprDeleteNN(db, p->pOn);
1436 }else if( p->pUsing ){
1437 sqlite3IdListDelete(db, p->pUsing);
1442 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1443 ** This is similar to sqlite3ExprDelete() except that the delete is
1444 ** deferred until the pParse is deleted.
1446 ** The pExpr might be deleted immediately on an OOM error.
1448 ** Return 0 if the delete was successfully deferred. Return non-zero
1449 ** if the delete happened immediately because of an OOM.
1451 int sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
1452 return 0==sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr);
1455 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1456 ** expression.
1458 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1459 if( p ){
1460 if( IN_RENAME_OBJECT ){
1461 sqlite3RenameExprUnmap(pParse, p);
1463 sqlite3ExprDeleteNN(pParse->db, p);
1468 ** Return the number of bytes allocated for the expression structure
1469 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1470 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1472 static int exprStructSize(const Expr *p){
1473 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1474 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1475 return EXPR_FULLSIZE;
1479 ** The dupedExpr*Size() routines each return the number of bytes required
1480 ** to store a copy of an expression or expression tree. They differ in
1481 ** how much of the tree is measured.
1483 ** dupedExprStructSize() Size of only the Expr structure
1484 ** dupedExprNodeSize() Size of Expr + space for token
1485 ** dupedExprSize() Expr + token + subtree components
1487 ***************************************************************************
1489 ** The dupedExprStructSize() function returns two values OR-ed together:
1490 ** (1) the space required for a copy of the Expr structure only and
1491 ** (2) the EP_xxx flags that indicate what the structure size should be.
1492 ** The return values is always one of:
1494 ** EXPR_FULLSIZE
1495 ** EXPR_REDUCEDSIZE | EP_Reduced
1496 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1498 ** The size of the structure can be found by masking the return value
1499 ** of this routine with 0xfff. The flags can be found by masking the
1500 ** return value with EP_Reduced|EP_TokenOnly.
1502 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1503 ** (unreduced) Expr objects as they or originally constructed by the parser.
1504 ** During expression analysis, extra information is computed and moved into
1505 ** later parts of the Expr object and that extra information might get chopped
1506 ** off if the expression is reduced. Note also that it does not work to
1507 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1508 ** to reduce a pristine expression tree from the parser. The implementation
1509 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1510 ** to enforce this constraint.
1512 static int dupedExprStructSize(const Expr *p, int flags){
1513 int nSize;
1514 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1515 assert( EXPR_FULLSIZE<=0xfff );
1516 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1517 if( 0==flags || ExprHasProperty(p, EP_FullSize) ){
1518 nSize = EXPR_FULLSIZE;
1519 }else{
1520 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1521 assert( !ExprHasProperty(p, EP_OuterON) );
1522 assert( !ExprHasVVAProperty(p, EP_NoReduce) );
1523 if( p->pLeft || p->x.pList ){
1524 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1525 }else{
1526 assert( p->pRight==0 );
1527 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1530 return nSize;
1534 ** This function returns the space in bytes required to store the copy
1535 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1536 ** string is defined.)
1538 static int dupedExprNodeSize(const Expr *p, int flags){
1539 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1540 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1541 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1543 return ROUND8(nByte);
1547 ** Return the number of bytes required to create a duplicate of the
1548 ** expression passed as the first argument.
1550 ** The value returned includes space to create a copy of the Expr struct
1551 ** itself and the buffer referred to by Expr.u.zToken, if any.
1553 ** The return value includes space to duplicate all Expr nodes in the
1554 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
1555 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
1557 static int dupedExprSize(const Expr *p){
1558 int nByte;
1559 assert( p!=0 );
1560 nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
1561 if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
1562 if( p->pRight ) nByte += dupedExprSize(p->pRight);
1563 assert( nByte==ROUND8(nByte) );
1564 return nByte;
1568 ** An EdupBuf is a memory allocation used to stored multiple Expr objects
1569 ** together with their Expr.zToken content. This is used to help implement
1570 ** compression while doing sqlite3ExprDup(). The top-level Expr does the
1571 ** allocation for itself and many of its decendents, then passes an instance
1572 ** of the structure down into exprDup() so that they decendents can have
1573 ** access to that memory.
1575 typedef struct EdupBuf EdupBuf;
1576 struct EdupBuf {
1577 u8 *zAlloc; /* Memory space available for storage */
1578 #ifdef SQLITE_DEBUG
1579 u8 *zEnd; /* First byte past the end of memory */
1580 #endif
1584 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
1585 ** is not NULL then it points to memory that can be used to store a copy
1586 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf
1587 ** is updated with the new buffer tail prior to returning.
1589 static Expr *exprDup(
1590 sqlite3 *db, /* Database connection (for memory allocation) */
1591 const Expr *p, /* Expr tree to be duplicated */
1592 int dupFlags, /* EXPRDUP_REDUCE for compression. 0 if not */
1593 EdupBuf *pEdupBuf /* Preallocated storage space, or NULL */
1595 Expr *pNew; /* Value to return */
1596 EdupBuf sEdupBuf; /* Memory space from which to build Expr object */
1597 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1598 int nToken = -1; /* Space needed for p->u.zToken. -1 means unknown */
1600 assert( db!=0 );
1601 assert( p );
1602 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1603 assert( pEdupBuf==0 || dupFlags==EXPRDUP_REDUCE );
1605 /* Figure out where to write the new Expr structure. */
1606 if( pEdupBuf ){
1607 sEdupBuf.zAlloc = pEdupBuf->zAlloc;
1608 #ifdef SQLITE_DEBUG
1609 sEdupBuf.zEnd = pEdupBuf->zEnd;
1610 #endif
1611 staticFlag = EP_Static;
1612 assert( sEdupBuf.zAlloc!=0 );
1613 assert( dupFlags==EXPRDUP_REDUCE );
1614 }else{
1615 int nAlloc;
1616 if( dupFlags ){
1617 nAlloc = dupedExprSize(p);
1618 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1619 nToken = sqlite3Strlen30NN(p->u.zToken)+1;
1620 nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
1621 }else{
1622 nToken = 0;
1623 nAlloc = ROUND8(EXPR_FULLSIZE);
1625 assert( nAlloc==ROUND8(nAlloc) );
1626 sEdupBuf.zAlloc = sqlite3DbMallocRawNN(db, nAlloc);
1627 #ifdef SQLITE_DEBUG
1628 sEdupBuf.zEnd = sEdupBuf.zAlloc ? sEdupBuf.zAlloc+nAlloc : 0;
1629 #endif
1631 staticFlag = 0;
1633 pNew = (Expr *)sEdupBuf.zAlloc;
1634 assert( EIGHT_BYTE_ALIGNMENT(pNew) );
1636 if( pNew ){
1637 /* Set nNewSize to the size allocated for the structure pointed to
1638 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1639 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1640 ** by the copy of the p->u.zToken string (if any).
1642 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1643 int nNewSize = nStructSize & 0xfff;
1644 if( nToken<0 ){
1645 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1646 nToken = sqlite3Strlen30(p->u.zToken) + 1;
1647 }else{
1648 nToken = 0;
1651 if( dupFlags ){
1652 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken );
1653 assert( ExprHasProperty(p, EP_Reduced)==0 );
1654 memcpy(sEdupBuf.zAlloc, p, nNewSize);
1655 }else{
1656 u32 nSize = (u32)exprStructSize(p);
1657 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >=
1658 (int)EXPR_FULLSIZE+nToken );
1659 memcpy(sEdupBuf.zAlloc, p, nSize);
1660 if( nSize<EXPR_FULLSIZE ){
1661 memset(&sEdupBuf.zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1663 nNewSize = EXPR_FULLSIZE;
1666 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1667 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
1668 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1669 pNew->flags |= staticFlag;
1670 ExprClearVVAProperties(pNew);
1671 if( dupFlags ){
1672 ExprSetVVAProperty(pNew, EP_Immutable);
1675 /* Copy the p->u.zToken string, if any. */
1676 assert( nToken>=0 );
1677 if( nToken>0 ){
1678 char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize];
1679 memcpy(zToken, p->u.zToken, nToken);
1680 nNewSize += nToken;
1682 sEdupBuf.zAlloc += ROUND8(nNewSize);
1684 if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){
1686 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1687 if( ExprUseXSelect(p) ){
1688 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1689 }else{
1690 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList,
1691 p->op!=TK_ORDER ? dupFlags : 0);
1694 #ifndef SQLITE_OMIT_WINDOWFUNC
1695 if( ExprHasProperty(p, EP_WinFunc) ){
1696 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1697 assert( ExprHasProperty(pNew, EP_WinFunc) );
1699 #endif /* SQLITE_OMIT_WINDOWFUNC */
1701 /* Fill in pNew->pLeft and pNew->pRight. */
1702 if( dupFlags ){
1703 if( p->op==TK_SELECT_COLUMN ){
1704 pNew->pLeft = p->pLeft;
1705 assert( p->pRight==0
1706 || p->pRight==p->pLeft
1707 || ExprHasProperty(p->pLeft, EP_Subquery) );
1708 }else{
1709 pNew->pLeft = p->pLeft ?
1710 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0;
1712 pNew->pRight = p->pRight ?
1713 exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0;
1714 }else{
1715 if( p->op==TK_SELECT_COLUMN ){
1716 pNew->pLeft = p->pLeft;
1717 assert( p->pRight==0
1718 || p->pRight==p->pLeft
1719 || ExprHasProperty(p->pLeft, EP_Subquery) );
1720 }else{
1721 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1723 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1727 if( pEdupBuf ) memcpy(pEdupBuf, &sEdupBuf, sizeof(sEdupBuf));
1728 assert( sEdupBuf.zAlloc <= sEdupBuf.zEnd );
1729 return pNew;
1733 ** Create and return a deep copy of the object passed as the second
1734 ** argument. If an OOM condition is encountered, NULL is returned
1735 ** and the db->mallocFailed flag set.
1737 #ifndef SQLITE_OMIT_CTE
1738 With *sqlite3WithDup(sqlite3 *db, With *p){
1739 With *pRet = 0;
1740 if( p ){
1741 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1742 pRet = sqlite3DbMallocZero(db, nByte);
1743 if( pRet ){
1744 int i;
1745 pRet->nCte = p->nCte;
1746 for(i=0; i<p->nCte; i++){
1747 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1748 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1749 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1750 pRet->a[i].eM10d = p->a[i].eM10d;
1754 return pRet;
1756 #else
1757 # define sqlite3WithDup(x,y) 0
1758 #endif
1760 #ifndef SQLITE_OMIT_WINDOWFUNC
1762 ** The gatherSelectWindows() procedure and its helper routine
1763 ** gatherSelectWindowsCallback() are used to scan all the expressions
1764 ** an a newly duplicated SELECT statement and gather all of the Window
1765 ** objects found there, assembling them onto the linked list at Select->pWin.
1767 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1768 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1769 Select *pSelect = pWalker->u.pSelect;
1770 Window *pWin = pExpr->y.pWin;
1771 assert( pWin );
1772 assert( IsWindowFunc(pExpr) );
1773 assert( pWin->ppThis==0 );
1774 sqlite3WindowLink(pSelect, pWin);
1776 return WRC_Continue;
1778 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1779 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1781 static void gatherSelectWindows(Select *p){
1782 Walker w;
1783 w.xExprCallback = gatherSelectWindowsCallback;
1784 w.xSelectCallback = gatherSelectWindowsSelectCallback;
1785 w.xSelectCallback2 = 0;
1786 w.pParse = 0;
1787 w.u.pSelect = p;
1788 sqlite3WalkSelect(&w, p);
1790 #endif
1794 ** The following group of routines make deep copies of expressions,
1795 ** expression lists, ID lists, and select statements. The copies can
1796 ** be deleted (by being passed to their respective ...Delete() routines)
1797 ** without effecting the originals.
1799 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1800 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1801 ** by subsequent calls to sqlite*ListAppend() routines.
1803 ** Any tables that the SrcList might point to are not duplicated.
1805 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1806 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1807 ** truncated version of the usual Expr structure that will be stored as
1808 ** part of the in-memory representation of the database schema.
1810 Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){
1811 assert( flags==0 || flags==EXPRDUP_REDUCE );
1812 return p ? exprDup(db, p, flags, 0) : 0;
1814 ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){
1815 ExprList *pNew;
1816 struct ExprList_item *pItem;
1817 const struct ExprList_item *pOldItem;
1818 int i;
1819 Expr *pPriorSelectColOld = 0;
1820 Expr *pPriorSelectColNew = 0;
1821 assert( db!=0 );
1822 if( p==0 ) return 0;
1823 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1824 if( pNew==0 ) return 0;
1825 pNew->nExpr = p->nExpr;
1826 pNew->nAlloc = p->nAlloc;
1827 pItem = pNew->a;
1828 pOldItem = p->a;
1829 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1830 Expr *pOldExpr = pOldItem->pExpr;
1831 Expr *pNewExpr;
1832 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1833 if( pOldExpr
1834 && pOldExpr->op==TK_SELECT_COLUMN
1835 && (pNewExpr = pItem->pExpr)!=0
1837 if( pNewExpr->pRight ){
1838 pPriorSelectColOld = pOldExpr->pRight;
1839 pPriorSelectColNew = pNewExpr->pRight;
1840 pNewExpr->pLeft = pNewExpr->pRight;
1841 }else{
1842 if( pOldExpr->pLeft!=pPriorSelectColOld ){
1843 pPriorSelectColOld = pOldExpr->pLeft;
1844 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
1845 pNewExpr->pRight = pPriorSelectColNew;
1847 pNewExpr->pLeft = pPriorSelectColNew;
1850 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1851 pItem->fg = pOldItem->fg;
1852 pItem->fg.done = 0;
1853 pItem->u = pOldItem->u;
1855 return pNew;
1859 ** If cursors, triggers, views and subqueries are all omitted from
1860 ** the build, then none of the following routines, except for
1861 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1862 ** called with a NULL argument.
1864 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1865 || !defined(SQLITE_OMIT_SUBQUERY)
1866 SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){
1867 SrcList *pNew;
1868 int i;
1869 int nByte;
1870 assert( db!=0 );
1871 if( p==0 ) return 0;
1872 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1873 pNew = sqlite3DbMallocRawNN(db, nByte );
1874 if( pNew==0 ) return 0;
1875 pNew->nSrc = pNew->nAlloc = p->nSrc;
1876 for(i=0; i<p->nSrc; i++){
1877 SrcItem *pNewItem = &pNew->a[i];
1878 const SrcItem *pOldItem = &p->a[i];
1879 Table *pTab;
1880 pNewItem->pSchema = pOldItem->pSchema;
1881 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1882 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1883 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1884 pNewItem->fg = pOldItem->fg;
1885 pNewItem->iCursor = pOldItem->iCursor;
1886 pNewItem->addrFillSub = pOldItem->addrFillSub;
1887 pNewItem->regReturn = pOldItem->regReturn;
1888 pNewItem->regResult = pOldItem->regResult;
1889 if( pNewItem->fg.isIndexedBy ){
1890 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1891 }else if( pNewItem->fg.isTabFunc ){
1892 pNewItem->u1.pFuncArg =
1893 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1894 }else{
1895 pNewItem->u1.nRow = pOldItem->u1.nRow;
1897 pNewItem->u2 = pOldItem->u2;
1898 if( pNewItem->fg.isCte ){
1899 pNewItem->u2.pCteUse->nUse++;
1901 pTab = pNewItem->pTab = pOldItem->pTab;
1902 if( pTab ){
1903 pTab->nTabRef++;
1905 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1906 if( pOldItem->fg.isUsing ){
1907 assert( pNewItem->fg.isUsing );
1908 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
1909 }else{
1910 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
1912 pNewItem->colUsed = pOldItem->colUsed;
1914 return pNew;
1916 IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){
1917 IdList *pNew;
1918 int i;
1919 assert( db!=0 );
1920 if( p==0 ) return 0;
1921 assert( p->eU4!=EU4_EXPR );
1922 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );
1923 if( pNew==0 ) return 0;
1924 pNew->nId = p->nId;
1925 pNew->eU4 = p->eU4;
1926 for(i=0; i<p->nId; i++){
1927 struct IdList_item *pNewItem = &pNew->a[i];
1928 const struct IdList_item *pOldItem = &p->a[i];
1929 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1930 pNewItem->u4 = pOldItem->u4;
1932 return pNew;
1934 Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){
1935 Select *pRet = 0;
1936 Select *pNext = 0;
1937 Select **pp = &pRet;
1938 const Select *p;
1940 assert( db!=0 );
1941 for(p=pDup; p; p=p->pPrior){
1942 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1943 if( pNew==0 ) break;
1944 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1945 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1946 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1947 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1948 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1949 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1950 pNew->op = p->op;
1951 pNew->pNext = pNext;
1952 pNew->pPrior = 0;
1953 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1954 pNew->iLimit = 0;
1955 pNew->iOffset = 0;
1956 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1957 pNew->addrOpenEphm[0] = -1;
1958 pNew->addrOpenEphm[1] = -1;
1959 pNew->nSelectRow = p->nSelectRow;
1960 pNew->pWith = sqlite3WithDup(db, p->pWith);
1961 #ifndef SQLITE_OMIT_WINDOWFUNC
1962 pNew->pWin = 0;
1963 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1964 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1965 #endif
1966 pNew->selId = p->selId;
1967 if( db->mallocFailed ){
1968 /* Any prior OOM might have left the Select object incomplete.
1969 ** Delete the whole thing rather than allow an incomplete Select
1970 ** to be used by the code generator. */
1971 pNew->pNext = 0;
1972 sqlite3SelectDelete(db, pNew);
1973 break;
1975 *pp = pNew;
1976 pp = &pNew->pPrior;
1977 pNext = pNew;
1980 return pRet;
1982 #else
1983 Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){
1984 assert( p==0 );
1985 return 0;
1987 #endif
1991 ** Add a new element to the end of an expression list. If pList is
1992 ** initially NULL, then create a new expression list.
1994 ** The pList argument must be either NULL or a pointer to an ExprList
1995 ** obtained from a prior call to sqlite3ExprListAppend().
1997 ** If a memory allocation error occurs, the entire list is freed and
1998 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1999 ** that the new entry was successfully appended.
2001 static const struct ExprList_item zeroItem = {0};
2002 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
2003 sqlite3 *db, /* Database handle. Used for memory allocation */
2004 Expr *pExpr /* Expression to be appended. Might be NULL */
2006 struct ExprList_item *pItem;
2007 ExprList *pList;
2009 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
2010 if( pList==0 ){
2011 sqlite3ExprDelete(db, pExpr);
2012 return 0;
2014 pList->nAlloc = 4;
2015 pList->nExpr = 1;
2016 pItem = &pList->a[0];
2017 *pItem = zeroItem;
2018 pItem->pExpr = pExpr;
2019 return pList;
2021 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
2022 sqlite3 *db, /* Database handle. Used for memory allocation */
2023 ExprList *pList, /* List to which to append. Might be NULL */
2024 Expr *pExpr /* Expression to be appended. Might be NULL */
2026 struct ExprList_item *pItem;
2027 ExprList *pNew;
2028 pList->nAlloc *= 2;
2029 pNew = sqlite3DbRealloc(db, pList,
2030 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
2031 if( pNew==0 ){
2032 sqlite3ExprListDelete(db, pList);
2033 sqlite3ExprDelete(db, pExpr);
2034 return 0;
2035 }else{
2036 pList = pNew;
2038 pItem = &pList->a[pList->nExpr++];
2039 *pItem = zeroItem;
2040 pItem->pExpr = pExpr;
2041 return pList;
2043 ExprList *sqlite3ExprListAppend(
2044 Parse *pParse, /* Parsing context */
2045 ExprList *pList, /* List to which to append. Might be NULL */
2046 Expr *pExpr /* Expression to be appended. Might be NULL */
2048 struct ExprList_item *pItem;
2049 if( pList==0 ){
2050 return sqlite3ExprListAppendNew(pParse->db,pExpr);
2052 if( pList->nAlloc<pList->nExpr+1 ){
2053 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
2055 pItem = &pList->a[pList->nExpr++];
2056 *pItem = zeroItem;
2057 pItem->pExpr = pExpr;
2058 return pList;
2062 ** pColumns and pExpr form a vector assignment which is part of the SET
2063 ** clause of an UPDATE statement. Like this:
2065 ** (a,b,c) = (expr1,expr2,expr3)
2066 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
2068 ** For each term of the vector assignment, append new entries to the
2069 ** expression list pList. In the case of a subquery on the RHS, append
2070 ** TK_SELECT_COLUMN expressions.
2072 ExprList *sqlite3ExprListAppendVector(
2073 Parse *pParse, /* Parsing context */
2074 ExprList *pList, /* List to which to append. Might be NULL */
2075 IdList *pColumns, /* List of names of LHS of the assignment */
2076 Expr *pExpr /* Vector expression to be appended. Might be NULL */
2078 sqlite3 *db = pParse->db;
2079 int n;
2080 int i;
2081 int iFirst = pList ? pList->nExpr : 0;
2082 /* pColumns can only be NULL due to an OOM but an OOM will cause an
2083 ** exit prior to this routine being invoked */
2084 if( NEVER(pColumns==0) ) goto vector_append_error;
2085 if( pExpr==0 ) goto vector_append_error;
2087 /* If the RHS is a vector, then we can immediately check to see that
2088 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
2089 ** wildcards ("*") in the result set of the SELECT must be expanded before
2090 ** we can do the size check, so defer the size check until code generation.
2092 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
2093 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
2094 pColumns->nId, n);
2095 goto vector_append_error;
2098 for(i=0; i<pColumns->nId; i++){
2099 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
2100 assert( pSubExpr!=0 || db->mallocFailed );
2101 if( pSubExpr==0 ) continue;
2102 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
2103 if( pList ){
2104 assert( pList->nExpr==iFirst+i+1 );
2105 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
2106 pColumns->a[i].zName = 0;
2110 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
2111 Expr *pFirst = pList->a[iFirst].pExpr;
2112 assert( pFirst!=0 );
2113 assert( pFirst->op==TK_SELECT_COLUMN );
2115 /* Store the SELECT statement in pRight so it will be deleted when
2116 ** sqlite3ExprListDelete() is called */
2117 pFirst->pRight = pExpr;
2118 pExpr = 0;
2120 /* Remember the size of the LHS in iTable so that we can check that
2121 ** the RHS and LHS sizes match during code generation. */
2122 pFirst->iTable = pColumns->nId;
2125 vector_append_error:
2126 sqlite3ExprUnmapAndDelete(pParse, pExpr);
2127 sqlite3IdListDelete(db, pColumns);
2128 return pList;
2132 ** Set the sort order for the last element on the given ExprList.
2134 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
2135 struct ExprList_item *pItem;
2136 if( p==0 ) return;
2137 assert( p->nExpr>0 );
2139 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
2140 assert( iSortOrder==SQLITE_SO_UNDEFINED
2141 || iSortOrder==SQLITE_SO_ASC
2142 || iSortOrder==SQLITE_SO_DESC
2144 assert( eNulls==SQLITE_SO_UNDEFINED
2145 || eNulls==SQLITE_SO_ASC
2146 || eNulls==SQLITE_SO_DESC
2149 pItem = &p->a[p->nExpr-1];
2150 assert( pItem->fg.bNulls==0 );
2151 if( iSortOrder==SQLITE_SO_UNDEFINED ){
2152 iSortOrder = SQLITE_SO_ASC;
2154 pItem->fg.sortFlags = (u8)iSortOrder;
2156 if( eNulls!=SQLITE_SO_UNDEFINED ){
2157 pItem->fg.bNulls = 1;
2158 if( iSortOrder!=eNulls ){
2159 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
2165 ** Set the ExprList.a[].zEName element of the most recently added item
2166 ** on the expression list.
2168 ** pList might be NULL following an OOM error. But pName should never be
2169 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2170 ** is set.
2172 void sqlite3ExprListSetName(
2173 Parse *pParse, /* Parsing context */
2174 ExprList *pList, /* List to which to add the span. */
2175 const Token *pName, /* Name to be added */
2176 int dequote /* True to cause the name to be dequoted */
2178 assert( pList!=0 || pParse->db->mallocFailed!=0 );
2179 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
2180 if( pList ){
2181 struct ExprList_item *pItem;
2182 assert( pList->nExpr>0 );
2183 pItem = &pList->a[pList->nExpr-1];
2184 assert( pItem->zEName==0 );
2185 assert( pItem->fg.eEName==ENAME_NAME );
2186 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
2187 if( dequote ){
2188 /* If dequote==0, then pName->z does not point to part of a DDL
2189 ** statement handled by the parser. And so no token need be added
2190 ** to the token-map. */
2191 sqlite3Dequote(pItem->zEName);
2192 if( IN_RENAME_OBJECT ){
2193 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
2200 ** Set the ExprList.a[].zSpan element of the most recently added item
2201 ** on the expression list.
2203 ** pList might be NULL following an OOM error. But pSpan should never be
2204 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2205 ** is set.
2207 void sqlite3ExprListSetSpan(
2208 Parse *pParse, /* Parsing context */
2209 ExprList *pList, /* List to which to add the span. */
2210 const char *zStart, /* Start of the span */
2211 const char *zEnd /* End of the span */
2213 sqlite3 *db = pParse->db;
2214 assert( pList!=0 || db->mallocFailed!=0 );
2215 if( pList ){
2216 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
2217 assert( pList->nExpr>0 );
2218 if( pItem->zEName==0 ){
2219 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
2220 pItem->fg.eEName = ENAME_SPAN;
2226 ** If the expression list pEList contains more than iLimit elements,
2227 ** leave an error message in pParse.
2229 void sqlite3ExprListCheckLength(
2230 Parse *pParse,
2231 ExprList *pEList,
2232 const char *zObject
2234 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
2235 testcase( pEList && pEList->nExpr==mx );
2236 testcase( pEList && pEList->nExpr==mx+1 );
2237 if( pEList && pEList->nExpr>mx ){
2238 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
2243 ** Delete an entire expression list.
2245 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
2246 int i = pList->nExpr;
2247 struct ExprList_item *pItem = pList->a;
2248 assert( pList->nExpr>0 );
2249 assert( db!=0 );
2251 sqlite3ExprDelete(db, pItem->pExpr);
2252 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
2253 pItem++;
2254 }while( --i>0 );
2255 sqlite3DbNNFreeNN(db, pList);
2257 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
2258 if( pList ) exprListDeleteNN(db, pList);
2260 void sqlite3ExprListDeleteGeneric(sqlite3 *db, void *pList){
2261 if( ALWAYS(pList) ) exprListDeleteNN(db, (ExprList*)pList);
2265 ** Return the bitwise-OR of all Expr.flags fields in the given
2266 ** ExprList.
2268 u32 sqlite3ExprListFlags(const ExprList *pList){
2269 int i;
2270 u32 m = 0;
2271 assert( pList!=0 );
2272 for(i=0; i<pList->nExpr; i++){
2273 Expr *pExpr = pList->a[i].pExpr;
2274 assert( pExpr!=0 );
2275 m |= pExpr->flags;
2277 return m;
2281 ** This is a SELECT-node callback for the expression walker that
2282 ** always "fails". By "fail" in this case, we mean set
2283 ** pWalker->eCode to zero and abort.
2285 ** This callback is used by multiple expression walkers.
2287 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
2288 UNUSED_PARAMETER(NotUsed);
2289 pWalker->eCode = 0;
2290 return WRC_Abort;
2294 ** Check the input string to see if it is "true" or "false" (in any case).
2296 ** If the string is.... Return
2297 ** "true" EP_IsTrue
2298 ** "false" EP_IsFalse
2299 ** anything else 0
2301 u32 sqlite3IsTrueOrFalse(const char *zIn){
2302 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
2303 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
2304 return 0;
2309 ** If the input expression is an ID with the name "true" or "false"
2310 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2311 ** the conversion happened, and zero if the expression is unaltered.
2313 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
2314 u32 v;
2315 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
2316 if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue)
2317 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
2319 pExpr->op = TK_TRUEFALSE;
2320 ExprSetProperty(pExpr, v);
2321 return 1;
2323 return 0;
2327 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2328 ** and 0 if it is FALSE.
2330 int sqlite3ExprTruthValue(const Expr *pExpr){
2331 pExpr = sqlite3ExprSkipCollateAndLikely((Expr*)pExpr);
2332 assert( pExpr->op==TK_TRUEFALSE );
2333 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2334 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
2335 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
2336 return pExpr->u.zToken[4]==0;
2340 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2341 ** terms that are always true or false. Return the simplified expression.
2342 ** Or return the original expression if no simplification is possible.
2344 ** Examples:
2346 ** (x<10) AND true => (x<10)
2347 ** (x<10) AND false => false
2348 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2349 ** (x<10) AND (y=22 OR true) => (x<10)
2350 ** (y=22) OR true => true
2352 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
2353 assert( pExpr!=0 );
2354 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
2355 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
2356 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
2357 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
2358 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
2359 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
2360 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
2363 return pExpr;
2367 ** pExpr is a TK_FUNCTION node. Try to determine whether or not the
2368 ** function is a constant function. A function is constant if all of
2369 ** the following are true:
2371 ** (1) It is a scalar function (not an aggregate or window function)
2372 ** (2) It has either the SQLITE_FUNC_CONSTANT or SQLITE_FUNC_SLOCHNG
2373 ** property.
2374 ** (3) All of its arguments are constants
2376 ** This routine sets pWalker->eCode to 0 if pExpr is not a constant.
2377 ** It makes no changes to pWalker->eCode if pExpr is constant. In
2378 ** every case, it returns WRC_Abort.
2380 ** Called as a service subroutine from exprNodeIsConstant().
2382 static SQLITE_NOINLINE int exprNodeIsConstantFunction(
2383 Walker *pWalker,
2384 Expr *pExpr
2386 int n; /* Number of arguments */
2387 ExprList *pList; /* List of arguments */
2388 FuncDef *pDef; /* The function */
2389 sqlite3 *db; /* The database */
2391 assert( pExpr->op==TK_FUNCTION );
2392 if( ExprHasProperty(pExpr, EP_TokenOnly)
2393 || (pList = pExpr->x.pList)==0
2395 n = 0;
2396 }else{
2397 n = pList->nExpr;
2398 sqlite3WalkExprList(pWalker, pList);
2399 if( pWalker->eCode==0 ) return WRC_Abort;
2401 db = pWalker->pParse->db;
2402 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
2403 if( pDef==0
2404 || pDef->xFinalize!=0
2405 || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
2406 || ExprHasProperty(pExpr, EP_WinFunc)
2408 pWalker->eCode = 0;
2409 return WRC_Abort;
2411 return WRC_Prune;
2416 ** These routines are Walker callbacks used to check expressions to
2417 ** see if they are "constant" for some definition of constant. The
2418 ** Walker.eCode value determines the type of "constant" we are looking
2419 ** for.
2421 ** These callback routines are used to implement the following:
2423 ** sqlite3ExprIsConstant() pWalker->eCode==1
2424 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2425 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2426 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2428 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2429 ** is found to not be a constant.
2431 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2432 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2433 ** when parsing an existing schema out of the sqlite_schema table and 4
2434 ** when processing a new CREATE TABLE statement. A bound parameter raises
2435 ** an error for new statements, but is silently converted
2436 ** to NULL for existing schemas. This allows sqlite_schema tables that
2437 ** contain a bound parameter because they were generated by older versions
2438 ** of SQLite to be parsed by newer versions of SQLite without raising a
2439 ** malformed schema error.
2441 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
2442 assert( pWalker->eCode>0 );
2444 /* If pWalker->eCode is 2 then any term of the expression that comes from
2445 ** the ON or USING clauses of an outer join disqualifies the expression
2446 ** from being considered constant. */
2447 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
2448 pWalker->eCode = 0;
2449 return WRC_Abort;
2452 switch( pExpr->op ){
2453 /* Consider functions to be constant if all their arguments are constant
2454 ** and either pWalker->eCode==4 or 5 or the function has the
2455 ** SQLITE_FUNC_CONST flag. */
2456 case TK_FUNCTION:
2457 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2458 && !ExprHasProperty(pExpr, EP_WinFunc)
2460 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2461 return WRC_Continue;
2462 }else if( pWalker->pParse ){
2463 return exprNodeIsConstantFunction(pWalker, pExpr);
2464 }else{
2465 pWalker->eCode = 0;
2466 return WRC_Abort;
2468 case TK_ID:
2469 /* Convert "true" or "false" in a DEFAULT clause into the
2470 ** appropriate TK_TRUEFALSE operator */
2471 if( sqlite3ExprIdToTrueFalse(pExpr) ){
2472 return WRC_Prune;
2474 /* no break */ deliberate_fall_through
2475 case TK_COLUMN:
2476 case TK_AGG_FUNCTION:
2477 case TK_AGG_COLUMN:
2478 testcase( pExpr->op==TK_ID );
2479 testcase( pExpr->op==TK_COLUMN );
2480 testcase( pExpr->op==TK_AGG_FUNCTION );
2481 testcase( pExpr->op==TK_AGG_COLUMN );
2482 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2483 return WRC_Continue;
2485 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2486 return WRC_Continue;
2488 /* no break */ deliberate_fall_through
2489 case TK_IF_NULL_ROW:
2490 case TK_REGISTER:
2491 case TK_DOT:
2492 case TK_RAISE:
2493 testcase( pExpr->op==TK_REGISTER );
2494 testcase( pExpr->op==TK_IF_NULL_ROW );
2495 testcase( pExpr->op==TK_DOT );
2496 testcase( pExpr->op==TK_RAISE );
2497 pWalker->eCode = 0;
2498 return WRC_Abort;
2499 case TK_VARIABLE:
2500 if( pWalker->eCode==5 ){
2501 /* Silently convert bound parameters that appear inside of CREATE
2502 ** statements into a NULL when parsing the CREATE statement text out
2503 ** of the sqlite_schema table */
2504 pExpr->op = TK_NULL;
2505 }else if( pWalker->eCode==4 ){
2506 /* A bound parameter in a CREATE statement that originates from
2507 ** sqlite3_prepare() causes an error */
2508 pWalker->eCode = 0;
2509 return WRC_Abort;
2511 /* no break */ deliberate_fall_through
2512 default:
2513 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2514 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2515 return WRC_Continue;
2518 static int exprIsConst(Parse *pParse, Expr *p, int initFlag){
2519 Walker w;
2520 w.eCode = initFlag;
2521 w.pParse = pParse;
2522 w.xExprCallback = exprNodeIsConstant;
2523 w.xSelectCallback = sqlite3SelectWalkFail;
2524 #ifdef SQLITE_DEBUG
2525 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2526 #endif
2527 sqlite3WalkExpr(&w, p);
2528 return w.eCode;
2532 ** Walk an expression tree. Return non-zero if the expression is constant
2533 ** and 0 if it involves variables or function calls.
2535 ** For the purposes of this function, a double-quoted string (ex: "abc")
2536 ** is considered a variable but a single-quoted string (ex: 'abc') is
2537 ** a constant.
2539 ** The pParse parameter may be NULL. But if it is NULL, there is no way
2540 ** to determine if function calls are constant or not, and hence all
2541 ** function calls will be considered to be non-constant. If pParse is
2542 ** not NULL, then a function call might be constant, depending on the
2543 ** function and on its parameters.
2545 int sqlite3ExprIsConstant(Parse *pParse, Expr *p){
2546 return exprIsConst(pParse, p, 1);
2550 ** Walk an expression tree. Return non-zero if
2552 ** (1) the expression is constant, and
2553 ** (2) the expression does originate in the ON or USING clause
2554 ** of a LEFT JOIN, and
2555 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2556 ** operands created by the constant propagation optimization.
2558 ** When this routine returns true, it indicates that the expression
2559 ** can be added to the pParse->pConstExpr list and evaluated once when
2560 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2562 static int sqlite3ExprIsConstantNotJoin(Parse *pParse, Expr *p){
2563 return exprIsConst(pParse, p, 2);
2567 ** This routine examines sub-SELECT statements as an expression is being
2568 ** walked as part of sqlite3ExprIsTableConstant(). Sub-SELECTs are considered
2569 ** constant as long as they are uncorrelated - meaning that they do not
2570 ** contain any terms from outer contexts.
2572 static int exprSelectWalkTableConstant(Walker *pWalker, Select *pSelect){
2573 assert( pSelect!=0 );
2574 assert( pWalker->eCode==3 || pWalker->eCode==0 );
2575 if( (pSelect->selFlags & SF_Correlated)!=0 ){
2576 pWalker->eCode = 0;
2577 return WRC_Abort;
2579 return WRC_Prune;
2583 ** Walk an expression tree. Return non-zero if the expression is constant
2584 ** for any single row of the table with cursor iCur. In other words, the
2585 ** expression must not refer to any non-deterministic function nor any
2586 ** table other than iCur.
2588 ** Consider uncorrelated subqueries to be constants if the bAllowSubq
2589 ** parameter is true.
2591 static int sqlite3ExprIsTableConstant(Expr *p, int iCur, int bAllowSubq){
2592 Walker w;
2593 w.eCode = 3;
2594 w.pParse = 0;
2595 w.xExprCallback = exprNodeIsConstant;
2596 if( bAllowSubq ){
2597 w.xSelectCallback = exprSelectWalkTableConstant;
2598 }else{
2599 w.xSelectCallback = sqlite3SelectWalkFail;
2600 #ifdef SQLITE_DEBUG
2601 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2602 #endif
2604 w.u.iCur = iCur;
2605 sqlite3WalkExpr(&w, p);
2606 return w.eCode;
2610 ** Check pExpr to see if it is an constraint on the single data source
2611 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2612 ** constrains pSrc but does not depend on any other tables or data
2613 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2614 ** is a constraint on pSrc only.
2616 ** This is an optimization. False negatives will perhaps cause slower
2617 ** queries, but false positives will yield incorrect answers. So when in
2618 ** doubt, return 0.
2620 ** To be an single-source constraint, the following must be true:
2622 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2624 ** (2a) pExpr cannot use subqueries unless the bAllowSubq parameter is
2625 ** true and the subquery is non-correlated
2627 ** (2b) pExpr cannot use non-deterministic functions.
2629 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2630 ** (Is there some way to relax this constraint?)
2632 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2633 ** (4a) pExpr must come from an ON clause..
2634 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2636 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2637 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2638 ** clause, not an ON clause.
2640 ** (6) Either:
2642 ** (6a) pExpr does not originate in an ON or USING clause, or
2644 ** (6b) The ON or USING clause from which pExpr is derived is
2645 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2647 ** Without this restriction, accepting pExpr as a single-table
2648 ** constraint might move the the ON/USING filter expression
2649 ** from the left side of a RIGHT JOIN over to the right side,
2650 ** which leads to incorrect answers. See also restriction (9)
2651 ** on push-down.
2653 int sqlite3ExprIsSingleTableConstraint(
2654 Expr *pExpr, /* The constraint */
2655 const SrcList *pSrcList, /* Complete FROM clause */
2656 int iSrc, /* Which element of pSrcList to use */
2657 int bAllowSubq /* Allow non-correlated subqueries */
2659 const SrcItem *pSrc = &pSrcList->a[iSrc];
2660 if( pSrc->fg.jointype & JT_LTORJ ){
2661 return 0; /* rule (3) */
2663 if( pSrc->fg.jointype & JT_LEFT ){
2664 if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (4a) */
2665 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */
2666 }else{
2667 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (5) */
2669 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) /* (6a) */
2670 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */
2672 int jj;
2673 for(jj=0; jj<iSrc; jj++){
2674 if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
2675 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
2676 return 0; /* restriction (6) */
2678 break;
2682 /* Rules (1), (2a), and (2b) handled by the following: */
2683 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq);
2688 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2690 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2691 ExprList *pGroupBy = pWalker->u.pGroupBy;
2692 int i;
2694 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2695 ** it constant. */
2696 for(i=0; i<pGroupBy->nExpr; i++){
2697 Expr *p = pGroupBy->a[i].pExpr;
2698 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2699 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2700 if( sqlite3IsBinary(pColl) ){
2701 return WRC_Prune;
2706 /* Check if pExpr is a sub-select. If so, consider it variable. */
2707 if( ExprUseXSelect(pExpr) ){
2708 pWalker->eCode = 0;
2709 return WRC_Abort;
2712 return exprNodeIsConstant(pWalker, pExpr);
2716 ** Walk the expression tree passed as the first argument. Return non-zero
2717 ** if the expression consists entirely of constants or copies of terms
2718 ** in pGroupBy that sort with the BINARY collation sequence.
2720 ** This routine is used to determine if a term of the HAVING clause can
2721 ** be promoted into the WHERE clause. In order for such a promotion to work,
2722 ** the value of the HAVING clause term must be the same for all members of
2723 ** a "group". The requirement that the GROUP BY term must be BINARY
2724 ** assumes that no other collating sequence will have a finer-grained
2725 ** grouping than binary. In other words (A=B COLLATE binary) implies
2726 ** A=B in every other collating sequence. The requirement that the
2727 ** GROUP BY be BINARY is stricter than necessary. It would also work
2728 ** to promote HAVING clauses that use the same alternative collating
2729 ** sequence as the GROUP BY term, but that is much harder to check,
2730 ** alternative collating sequences are uncommon, and this is only an
2731 ** optimization, so we take the easy way out and simply require the
2732 ** GROUP BY to use the BINARY collating sequence.
2734 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2735 Walker w;
2736 w.eCode = 1;
2737 w.xExprCallback = exprNodeIsConstantOrGroupBy;
2738 w.xSelectCallback = 0;
2739 w.u.pGroupBy = pGroupBy;
2740 w.pParse = pParse;
2741 sqlite3WalkExpr(&w, p);
2742 return w.eCode;
2746 ** Walk an expression tree for the DEFAULT field of a column definition
2747 ** in a CREATE TABLE statement. Return non-zero if the expression is
2748 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2749 ** the expression is constant or a function call with constant arguments.
2750 ** Return and 0 if there are any variables.
2752 ** isInit is true when parsing from sqlite_schema. isInit is false when
2753 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2754 ** (such as ? or $abc) in the expression are converted into NULL. When
2755 ** isInit is false, parameters raise an error. Parameters should not be
2756 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2757 ** allowed it, so we need to support it when reading sqlite_schema for
2758 ** backwards compatibility.
2760 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2762 ** For the purposes of this function, a double-quoted string (ex: "abc")
2763 ** is considered a variable but a single-quoted string (ex: 'abc') is
2764 ** a constant.
2766 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2767 assert( isInit==0 || isInit==1 );
2768 return exprIsConst(0, p, 4+isInit);
2771 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2773 ** Walk an expression tree. Return 1 if the expression contains a
2774 ** subquery of some kind. Return 0 if there are no subqueries.
2776 int sqlite3ExprContainsSubquery(Expr *p){
2777 Walker w;
2778 w.eCode = 1;
2779 w.xExprCallback = sqlite3ExprWalkNoop;
2780 w.xSelectCallback = sqlite3SelectWalkFail;
2781 #ifdef SQLITE_DEBUG
2782 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2783 #endif
2784 sqlite3WalkExpr(&w, p);
2785 return w.eCode==0;
2787 #endif
2790 ** If the expression p codes a constant integer that is small enough
2791 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2792 ** in *pValue. If the expression is not an integer or if it is too big
2793 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2795 ** If the pParse pointer is provided, then allow the expression p to be
2796 ** a parameter (TK_VARIABLE) that is bound to an integer.
2797 ** But if pParse is NULL, then p must be a pure integer literal.
2799 int sqlite3ExprIsInteger(const Expr *p, int *pValue, Parse *pParse){
2800 int rc = 0;
2801 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
2803 /* If an expression is an integer literal that fits in a signed 32-bit
2804 ** integer, then the EP_IntValue flag will have already been set */
2805 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2806 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2808 if( p->flags & EP_IntValue ){
2809 *pValue = p->u.iValue;
2810 return 1;
2812 switch( p->op ){
2813 case TK_UPLUS: {
2814 rc = sqlite3ExprIsInteger(p->pLeft, pValue, 0);
2815 break;
2817 case TK_UMINUS: {
2818 int v = 0;
2819 if( sqlite3ExprIsInteger(p->pLeft, &v, 0) ){
2820 assert( ((unsigned int)v)!=0x80000000 );
2821 *pValue = -v;
2822 rc = 1;
2824 break;
2826 case TK_VARIABLE: {
2827 sqlite3_value *pVal;
2828 if( pParse==0 ) break;
2829 if( NEVER(pParse->pVdbe==0) ) break;
2830 if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) break;
2831 sqlite3VdbeSetVarmask(pParse->pVdbe, p->iColumn);
2832 pVal = sqlite3VdbeGetBoundValue(pParse->pReprepare, p->iColumn,
2833 SQLITE_AFF_BLOB);
2834 if( pVal ){
2835 if( sqlite3_value_type(pVal)==SQLITE_INTEGER ){
2836 sqlite3_int64 vv = sqlite3_value_int64(pVal);
2837 if( vv == (vv & 0x7fffffff) ){ /* non-negative numbers only */
2838 *pValue = (int)vv;
2839 rc = 1;
2842 sqlite3ValueFree(pVal);
2844 break;
2846 default: break;
2848 return rc;
2852 ** Return FALSE if there is no chance that the expression can be NULL.
2854 ** If the expression might be NULL or if the expression is too complex
2855 ** to tell return TRUE.
2857 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2858 ** when we know that a value cannot be NULL. Hence, a false positive
2859 ** (returning TRUE when in fact the expression can never be NULL) might
2860 ** be a small performance hit but is otherwise harmless. On the other
2861 ** hand, a false negative (returning FALSE when the result could be NULL)
2862 ** will likely result in an incorrect answer. So when in doubt, return
2863 ** TRUE.
2865 int sqlite3ExprCanBeNull(const Expr *p){
2866 u8 op;
2867 assert( p!=0 );
2868 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2869 p = p->pLeft;
2870 assert( p!=0 );
2872 op = p->op;
2873 if( op==TK_REGISTER ) op = p->op2;
2874 switch( op ){
2875 case TK_INTEGER:
2876 case TK_STRING:
2877 case TK_FLOAT:
2878 case TK_BLOB:
2879 return 0;
2880 case TK_COLUMN:
2881 assert( ExprUseYTab(p) );
2882 return ExprHasProperty(p, EP_CanBeNull)
2883 || NEVER(p->y.pTab==0) /* Reference to column of index on expr */
2884 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
2885 || (p->iColumn==XN_ROWID && IsView(p->y.pTab))
2886 #endif
2887 || (p->iColumn>=0
2888 && p->y.pTab->aCol!=0 /* Possible due to prior error */
2889 && ALWAYS(p->iColumn<p->y.pTab->nCol)
2890 && p->y.pTab->aCol[p->iColumn].notNull==0);
2891 default:
2892 return 1;
2897 ** Return TRUE if the given expression is a constant which would be
2898 ** unchanged by OP_Affinity with the affinity given in the second
2899 ** argument.
2901 ** This routine is used to determine if the OP_Affinity operation
2902 ** can be omitted. When in doubt return FALSE. A false negative
2903 ** is harmless. A false positive, however, can result in the wrong
2904 ** answer.
2906 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2907 u8 op;
2908 int unaryMinus = 0;
2909 if( aff==SQLITE_AFF_BLOB ) return 1;
2910 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2911 if( p->op==TK_UMINUS ) unaryMinus = 1;
2912 p = p->pLeft;
2914 op = p->op;
2915 if( op==TK_REGISTER ) op = p->op2;
2916 switch( op ){
2917 case TK_INTEGER: {
2918 return aff>=SQLITE_AFF_NUMERIC;
2920 case TK_FLOAT: {
2921 return aff>=SQLITE_AFF_NUMERIC;
2923 case TK_STRING: {
2924 return !unaryMinus && aff==SQLITE_AFF_TEXT;
2926 case TK_BLOB: {
2927 return !unaryMinus;
2929 case TK_COLUMN: {
2930 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2931 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2933 default: {
2934 return 0;
2940 ** Return TRUE if the given string is a row-id column name.
2942 int sqlite3IsRowid(const char *z){
2943 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2944 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2945 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2946 return 0;
2950 ** Return a pointer to a buffer containing a usable rowid alias for table
2951 ** pTab. An alias is usable if there is not an explicit user-defined column
2952 ** of the same name.
2954 const char *sqlite3RowidAlias(Table *pTab){
2955 const char *azOpt[] = {"_ROWID_", "ROWID", "OID"};
2956 int ii;
2957 assert( VisibleRowid(pTab) );
2958 for(ii=0; ii<ArraySize(azOpt); ii++){
2959 int iCol;
2960 for(iCol=0; iCol<pTab->nCol; iCol++){
2961 if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break;
2963 if( iCol==pTab->nCol ){
2964 return azOpt[ii];
2967 return 0;
2971 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2972 ** that can be simplified to a direct table access, then return
2973 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2974 ** or if the SELECT statement needs to be materialized into a transient
2975 ** table, then return NULL.
2977 #ifndef SQLITE_OMIT_SUBQUERY
2978 static Select *isCandidateForInOpt(const Expr *pX){
2979 Select *p;
2980 SrcList *pSrc;
2981 ExprList *pEList;
2982 Table *pTab;
2983 int i;
2984 if( !ExprUseXSelect(pX) ) return 0; /* Not a subquery */
2985 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
2986 p = pX->x.pSelect;
2987 if( p->pPrior ) return 0; /* Not a compound SELECT */
2988 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2989 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2990 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2991 return 0; /* No DISTINCT keyword and no aggregate functions */
2993 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
2994 if( p->pLimit ) return 0; /* Has no LIMIT clause */
2995 if( p->pWhere ) return 0; /* Has no WHERE clause */
2996 pSrc = p->pSrc;
2997 assert( pSrc!=0 );
2998 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
2999 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
3000 pTab = pSrc->a[0].pTab;
3001 assert( pTab!=0 );
3002 assert( !IsView(pTab) ); /* FROM clause is not a view */
3003 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
3004 pEList = p->pEList;
3005 assert( pEList!=0 );
3006 /* All SELECT results must be columns. */
3007 for(i=0; i<pEList->nExpr; i++){
3008 Expr *pRes = pEList->a[i].pExpr;
3009 if( pRes->op!=TK_COLUMN ) return 0;
3010 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
3012 return p;
3014 #endif /* SQLITE_OMIT_SUBQUERY */
3016 #ifndef SQLITE_OMIT_SUBQUERY
3018 ** Generate code that checks the left-most column of index table iCur to see if
3019 ** it contains any NULL entries. Cause the register at regHasNull to be set
3020 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
3021 ** to be set to NULL if iCur contains one or more NULL values.
3023 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
3024 int addr1;
3025 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
3026 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
3027 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
3028 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
3029 VdbeComment((v, "first_entry_in(%d)", iCur));
3030 sqlite3VdbeJumpHere(v, addr1);
3032 #endif
3035 #ifndef SQLITE_OMIT_SUBQUERY
3037 ** The argument is an IN operator with a list (not a subquery) on the
3038 ** right-hand side. Return TRUE if that list is constant.
3040 static int sqlite3InRhsIsConstant(Parse *pParse, Expr *pIn){
3041 Expr *pLHS;
3042 int res;
3043 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
3044 pLHS = pIn->pLeft;
3045 pIn->pLeft = 0;
3046 res = sqlite3ExprIsConstant(pParse, pIn);
3047 pIn->pLeft = pLHS;
3048 return res;
3050 #endif
3053 ** This function is used by the implementation of the IN (...) operator.
3054 ** The pX parameter is the expression on the RHS of the IN operator, which
3055 ** might be either a list of expressions or a subquery.
3057 ** The job of this routine is to find or create a b-tree object that can
3058 ** be used either to test for membership in the RHS set or to iterate through
3059 ** all members of the RHS set, skipping duplicates.
3061 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
3062 ** and the *piTab parameter is set to the index of that cursor.
3064 ** The returned value of this function indicates the b-tree type, as follows:
3066 ** IN_INDEX_ROWID - The cursor was opened on a database table.
3067 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
3068 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
3069 ** IN_INDEX_EPH - The cursor was opened on a specially created and
3070 ** populated ephemeral table.
3071 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
3072 ** implemented as a sequence of comparisons.
3074 ** An existing b-tree might be used if the RHS expression pX is a simple
3075 ** subquery such as:
3077 ** SELECT <column1>, <column2>... FROM <table>
3079 ** If the RHS of the IN operator is a list or a more complex subquery, then
3080 ** an ephemeral table might need to be generated from the RHS and then
3081 ** pX->iTable made to point to the ephemeral table instead of an
3082 ** existing table. In this case, the creation and initialization of the
3083 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
3084 ** will be set on pX and the pX->y.sub fields will be set to show where
3085 ** the subroutine is coded.
3087 ** The inFlags parameter must contain, at a minimum, one of the bits
3088 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
3089 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
3090 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
3091 ** be used to loop over all values of the RHS of the IN operator.
3093 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
3094 ** through the set members) then the b-tree must not contain duplicates.
3095 ** An ephemeral table will be created unless the selected columns are guaranteed
3096 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
3097 ** a UNIQUE constraint or index.
3099 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
3100 ** for fast set membership tests) then an ephemeral table must
3101 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
3102 ** index can be found with the specified <columns> as its left-most.
3104 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
3105 ** if the RHS of the IN operator is a list (not a subquery) then this
3106 ** routine might decide that creating an ephemeral b-tree for membership
3107 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
3108 ** calling routine should implement the IN operator using a sequence
3109 ** of Eq or Ne comparison operations.
3111 ** When the b-tree is being used for membership tests, the calling function
3112 ** might need to know whether or not the RHS side of the IN operator
3113 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
3114 ** if there is any chance that the (...) might contain a NULL value at
3115 ** runtime, then a register is allocated and the register number written
3116 ** to *prRhsHasNull. If there is no chance that the (...) contains a
3117 ** NULL value, then *prRhsHasNull is left unchanged.
3119 ** If a register is allocated and its location stored in *prRhsHasNull, then
3120 ** the value in that register will be NULL if the b-tree contains one or more
3121 ** NULL values, and it will be some non-NULL value if the b-tree contains no
3122 ** NULL values.
3124 ** If the aiMap parameter is not NULL, it must point to an array containing
3125 ** one element for each column returned by the SELECT statement on the RHS
3126 ** of the IN(...) operator. The i'th entry of the array is populated with the
3127 ** offset of the index column that matches the i'th column returned by the
3128 ** SELECT. For example, if the expression and selected index are:
3130 ** (?,?,?) IN (SELECT a, b, c FROM t1)
3131 ** CREATE INDEX i1 ON t1(b, c, a);
3133 ** then aiMap[] is populated with {2, 0, 1}.
3135 #ifndef SQLITE_OMIT_SUBQUERY
3136 int sqlite3FindInIndex(
3137 Parse *pParse, /* Parsing context */
3138 Expr *pX, /* The IN expression */
3139 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
3140 int *prRhsHasNull, /* Register holding NULL status. See notes */
3141 int *aiMap, /* Mapping from Index fields to RHS fields */
3142 int *piTab /* OUT: index to use */
3144 Select *p; /* SELECT to the right of IN operator */
3145 int eType = 0; /* Type of RHS table. IN_INDEX_* */
3146 int iTab; /* Cursor of the RHS table */
3147 int mustBeUnique; /* True if RHS must be unique */
3148 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
3150 assert( pX->op==TK_IN );
3151 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
3152 iTab = pParse->nTab++;
3154 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
3155 ** whether or not the SELECT result contains NULL values, check whether
3156 ** or not NULL is actually possible (it may not be, for example, due
3157 ** to NOT NULL constraints in the schema). If no NULL values are possible,
3158 ** set prRhsHasNull to 0 before continuing. */
3159 if( prRhsHasNull && ExprUseXSelect(pX) ){
3160 int i;
3161 ExprList *pEList = pX->x.pSelect->pEList;
3162 for(i=0; i<pEList->nExpr; i++){
3163 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
3165 if( i==pEList->nExpr ){
3166 prRhsHasNull = 0;
3170 /* Check to see if an existing table or index can be used to
3171 ** satisfy the query. This is preferable to generating a new
3172 ** ephemeral table. */
3173 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
3174 sqlite3 *db = pParse->db; /* Database connection */
3175 Table *pTab; /* Table <table>. */
3176 int iDb; /* Database idx for pTab */
3177 ExprList *pEList = p->pEList;
3178 int nExpr = pEList->nExpr;
3180 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
3181 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
3182 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
3183 pTab = p->pSrc->a[0].pTab;
3185 /* Code an OP_Transaction and OP_TableLock for <table>. */
3186 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3187 assert( iDb>=0 && iDb<SQLITE_MAX_DB );
3188 sqlite3CodeVerifySchema(pParse, iDb);
3189 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
3191 assert(v); /* sqlite3GetVdbe() has always been previously called */
3192 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
3193 /* The "x IN (SELECT rowid FROM table)" case */
3194 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
3195 VdbeCoverage(v);
3197 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3198 eType = IN_INDEX_ROWID;
3199 ExplainQueryPlan((pParse, 0,
3200 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
3201 sqlite3VdbeJumpHere(v, iAddr);
3202 }else{
3203 Index *pIdx; /* Iterator variable */
3204 int affinity_ok = 1;
3205 int i;
3207 /* Check that the affinity that will be used to perform each
3208 ** comparison is the same as the affinity of each column in table
3209 ** on the RHS of the IN operator. If it not, it is not possible to
3210 ** use any index of the RHS table. */
3211 for(i=0; i<nExpr && affinity_ok; i++){
3212 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
3213 int iCol = pEList->a[i].pExpr->iColumn;
3214 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
3215 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
3216 testcase( cmpaff==SQLITE_AFF_BLOB );
3217 testcase( cmpaff==SQLITE_AFF_TEXT );
3218 switch( cmpaff ){
3219 case SQLITE_AFF_BLOB:
3220 break;
3221 case SQLITE_AFF_TEXT:
3222 /* sqlite3CompareAffinity() only returns TEXT if one side or the
3223 ** other has no affinity and the other side is TEXT. Hence,
3224 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
3225 ** and for the term on the LHS of the IN to have no affinity. */
3226 assert( idxaff==SQLITE_AFF_TEXT );
3227 break;
3228 default:
3229 affinity_ok = sqlite3IsNumericAffinity(idxaff);
3233 if( affinity_ok ){
3234 /* Search for an existing index that will work for this IN operator */
3235 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
3236 Bitmask colUsed; /* Columns of the index used */
3237 Bitmask mCol; /* Mask for the current column */
3238 if( pIdx->nColumn<nExpr ) continue;
3239 if( pIdx->pPartIdxWhere!=0 ) continue;
3240 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
3241 ** BITMASK(nExpr) without overflowing */
3242 testcase( pIdx->nColumn==BMS-2 );
3243 testcase( pIdx->nColumn==BMS-1 );
3244 if( pIdx->nColumn>=BMS-1 ) continue;
3245 if( mustBeUnique ){
3246 if( pIdx->nKeyCol>nExpr
3247 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
3249 continue; /* This index is not unique over the IN RHS columns */
3253 colUsed = 0; /* Columns of index used so far */
3254 for(i=0; i<nExpr; i++){
3255 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
3256 Expr *pRhs = pEList->a[i].pExpr;
3257 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
3258 int j;
3260 for(j=0; j<nExpr; j++){
3261 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
3262 assert( pIdx->azColl[j] );
3263 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
3264 continue;
3266 break;
3268 if( j==nExpr ) break;
3269 mCol = MASKBIT(j);
3270 if( mCol & colUsed ) break; /* Each column used only once */
3271 colUsed |= mCol;
3272 if( aiMap ) aiMap[i] = j;
3275 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
3276 if( colUsed==(MASKBIT(nExpr)-1) ){
3277 /* If we reach this point, that means the index pIdx is usable */
3278 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3279 ExplainQueryPlan((pParse, 0,
3280 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
3281 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
3282 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
3283 VdbeComment((v, "%s", pIdx->zName));
3284 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
3285 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
3287 if( prRhsHasNull ){
3288 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3289 i64 mask = (1<<nExpr)-1;
3290 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
3291 iTab, 0, 0, (u8*)&mask, P4_INT64);
3292 #endif
3293 *prRhsHasNull = ++pParse->nMem;
3294 if( nExpr==1 ){
3295 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
3298 sqlite3VdbeJumpHere(v, iAddr);
3300 } /* End loop over indexes */
3301 } /* End if( affinity_ok ) */
3302 } /* End if not an rowid index */
3303 } /* End attempt to optimize using an index */
3305 /* If no preexisting index is available for the IN clause
3306 ** and IN_INDEX_NOOP is an allowed reply
3307 ** and the RHS of the IN operator is a list, not a subquery
3308 ** and the RHS is not constant or has two or fewer terms,
3309 ** then it is not worth creating an ephemeral table to evaluate
3310 ** the IN operator so return IN_INDEX_NOOP.
3312 if( eType==0
3313 && (inFlags & IN_INDEX_NOOP_OK)
3314 && ExprUseXList(pX)
3315 && (!sqlite3InRhsIsConstant(pParse,pX) || pX->x.pList->nExpr<=2)
3317 pParse->nTab--; /* Back out the allocation of the unused cursor */
3318 iTab = -1; /* Cursor is not allocated */
3319 eType = IN_INDEX_NOOP;
3322 if( eType==0 ){
3323 /* Could not find an existing table or index to use as the RHS b-tree.
3324 ** We will have to generate an ephemeral table to do the job.
3326 u32 savedNQueryLoop = pParse->nQueryLoop;
3327 int rMayHaveNull = 0;
3328 eType = IN_INDEX_EPH;
3329 if( inFlags & IN_INDEX_LOOP ){
3330 pParse->nQueryLoop = 0;
3331 }else if( prRhsHasNull ){
3332 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
3334 assert( pX->op==TK_IN );
3335 sqlite3CodeRhsOfIN(pParse, pX, iTab);
3336 if( rMayHaveNull ){
3337 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
3339 pParse->nQueryLoop = savedNQueryLoop;
3342 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
3343 int i, n;
3344 n = sqlite3ExprVectorSize(pX->pLeft);
3345 for(i=0; i<n; i++) aiMap[i] = i;
3347 *piTab = iTab;
3348 return eType;
3350 #endif
3352 #ifndef SQLITE_OMIT_SUBQUERY
3354 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3355 ** function allocates and returns a nul-terminated string containing
3356 ** the affinities to be used for each column of the comparison.
3358 ** It is the responsibility of the caller to ensure that the returned
3359 ** string is eventually freed using sqlite3DbFree().
3361 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
3362 Expr *pLeft = pExpr->pLeft;
3363 int nVal = sqlite3ExprVectorSize(pLeft);
3364 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
3365 char *zRet;
3367 assert( pExpr->op==TK_IN );
3368 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
3369 if( zRet ){
3370 int i;
3371 for(i=0; i<nVal; i++){
3372 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
3373 char a = sqlite3ExprAffinity(pA);
3374 if( pSelect ){
3375 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
3376 }else{
3377 zRet[i] = a;
3380 zRet[nVal] = '\0';
3382 return zRet;
3384 #endif
3386 #ifndef SQLITE_OMIT_SUBQUERY
3388 ** Load the Parse object passed as the first argument with an error
3389 ** message of the form:
3391 ** "sub-select returns N columns - expected M"
3393 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
3394 if( pParse->nErr==0 ){
3395 const char *zFmt = "sub-select returns %d columns - expected %d";
3396 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
3399 #endif
3402 ** Expression pExpr is a vector that has been used in a context where
3403 ** it is not permitted. If pExpr is a sub-select vector, this routine
3404 ** loads the Parse object with a message of the form:
3406 ** "sub-select returns N columns - expected 1"
3408 ** Or, if it is a regular scalar vector:
3410 ** "row value misused"
3412 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
3413 #ifndef SQLITE_OMIT_SUBQUERY
3414 if( ExprUseXSelect(pExpr) ){
3415 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
3416 }else
3417 #endif
3419 sqlite3ErrorMsg(pParse, "row value misused");
3423 #ifndef SQLITE_OMIT_SUBQUERY
3425 ** Generate code that will construct an ephemeral table containing all terms
3426 ** in the RHS of an IN operator. The IN operator can be in either of two
3427 ** forms:
3429 ** x IN (4,5,11) -- IN operator with list on right-hand side
3430 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3432 ** The pExpr parameter is the IN operator. The cursor number for the
3433 ** constructed ephemeral table is returned. The first time the ephemeral
3434 ** table is computed, the cursor number is also stored in pExpr->iTable,
3435 ** however the cursor number returned might not be the same, as it might
3436 ** have been duplicated using OP_OpenDup.
3438 ** If the LHS expression ("x" in the examples) is a column value, or
3439 ** the SELECT statement returns a column value, then the affinity of that
3440 ** column is used to build the index keys. If both 'x' and the
3441 ** SELECT... statement are columns, then numeric affinity is used
3442 ** if either column has NUMERIC or INTEGER affinity. If neither
3443 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3444 ** is used.
3446 void sqlite3CodeRhsOfIN(
3447 Parse *pParse, /* Parsing context */
3448 Expr *pExpr, /* The IN operator */
3449 int iTab /* Use this cursor number */
3451 int addrOnce = 0; /* Address of the OP_Once instruction at top */
3452 int addr; /* Address of OP_OpenEphemeral instruction */
3453 Expr *pLeft; /* the LHS of the IN operator */
3454 KeyInfo *pKeyInfo = 0; /* Key information */
3455 int nVal; /* Size of vector pLeft */
3456 Vdbe *v; /* The prepared statement under construction */
3458 v = pParse->pVdbe;
3459 assert( v!=0 );
3461 /* The evaluation of the IN must be repeated every time it
3462 ** is encountered if any of the following is true:
3464 ** * The right-hand side is a correlated subquery
3465 ** * The right-hand side is an expression list containing variables
3466 ** * We are inside a trigger
3468 ** If all of the above are false, then we can compute the RHS just once
3469 ** and reuse it many names.
3471 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
3472 /* Reuse of the RHS is allowed */
3473 /* If this routine has already been coded, but the previous code
3474 ** might not have been invoked yet, so invoke it now as a subroutine.
3476 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3477 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3478 if( ExprUseXSelect(pExpr) ){
3479 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
3480 pExpr->x.pSelect->selId));
3482 assert( ExprUseYSub(pExpr) );
3483 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3484 pExpr->y.sub.iAddr);
3485 assert( iTab!=pExpr->iTable );
3486 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
3487 sqlite3VdbeJumpHere(v, addrOnce);
3488 return;
3491 /* Begin coding the subroutine */
3492 assert( !ExprUseYWin(pExpr) );
3493 ExprSetProperty(pExpr, EP_Subrtn);
3494 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3495 pExpr->y.sub.regReturn = ++pParse->nMem;
3496 pExpr->y.sub.iAddr =
3497 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3499 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3502 /* Check to see if this is a vector IN operator */
3503 pLeft = pExpr->pLeft;
3504 nVal = sqlite3ExprVectorSize(pLeft);
3506 /* Construct the ephemeral table that will contain the content of
3507 ** RHS of the IN operator.
3509 pExpr->iTable = iTab;
3510 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
3511 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3512 if( ExprUseXSelect(pExpr) ){
3513 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
3514 }else{
3515 VdbeComment((v, "RHS of IN operator"));
3517 #endif
3518 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
3520 if( ExprUseXSelect(pExpr) ){
3521 /* Case 1: expr IN (SELECT ...)
3523 ** Generate code to write the results of the select into the temporary
3524 ** table allocated and opened above.
3526 Select *pSelect = pExpr->x.pSelect;
3527 ExprList *pEList = pSelect->pEList;
3529 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
3530 addrOnce?"":"CORRELATED ", pSelect->selId
3532 /* If the LHS and RHS of the IN operator do not match, that
3533 ** error will have been caught long before we reach this point. */
3534 if( ALWAYS(pEList->nExpr==nVal) ){
3535 Select *pCopy;
3536 SelectDest dest;
3537 int i;
3538 int rc;
3539 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
3540 dest.zAffSdst = exprINAffinity(pParse, pExpr);
3541 pSelect->iLimit = 0;
3542 testcase( pSelect->selFlags & SF_Distinct );
3543 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3544 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
3545 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
3546 sqlite3SelectDelete(pParse->db, pCopy);
3547 sqlite3DbFree(pParse->db, dest.zAffSdst);
3548 if( rc ){
3549 sqlite3KeyInfoUnref(pKeyInfo);
3550 return;
3552 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
3553 assert( pEList!=0 );
3554 assert( pEList->nExpr>0 );
3555 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3556 for(i=0; i<nVal; i++){
3557 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
3558 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
3559 pParse, p, pEList->a[i].pExpr
3563 }else if( ALWAYS(pExpr->x.pList!=0) ){
3564 /* Case 2: expr IN (exprlist)
3566 ** For each expression, build an index key from the evaluation and
3567 ** store it in the temporary table. If <expr> is a column, then use
3568 ** that columns affinity when building index keys. If <expr> is not
3569 ** a column, use numeric affinity.
3571 char affinity; /* Affinity of the LHS of the IN */
3572 int i;
3573 ExprList *pList = pExpr->x.pList;
3574 struct ExprList_item *pItem;
3575 int r1, r2;
3576 affinity = sqlite3ExprAffinity(pLeft);
3577 if( affinity<=SQLITE_AFF_NONE ){
3578 affinity = SQLITE_AFF_BLOB;
3579 }else if( affinity==SQLITE_AFF_REAL ){
3580 affinity = SQLITE_AFF_NUMERIC;
3582 if( pKeyInfo ){
3583 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3584 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3587 /* Loop through each expression in <exprlist>. */
3588 r1 = sqlite3GetTempReg(pParse);
3589 r2 = sqlite3GetTempReg(pParse);
3590 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
3591 Expr *pE2 = pItem->pExpr;
3593 /* If the expression is not constant then we will need to
3594 ** disable the test that was generated above that makes sure
3595 ** this code only executes once. Because for a non-constant
3596 ** expression we need to rerun this code each time.
3598 if( addrOnce && !sqlite3ExprIsConstant(pParse, pE2) ){
3599 sqlite3VdbeChangeToNoop(v, addrOnce-1);
3600 sqlite3VdbeChangeToNoop(v, addrOnce);
3601 ExprClearProperty(pExpr, EP_Subrtn);
3602 addrOnce = 0;
3605 /* Evaluate the expression and insert it into the temp table */
3606 sqlite3ExprCode(pParse, pE2, r1);
3607 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
3608 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
3610 sqlite3ReleaseTempReg(pParse, r1);
3611 sqlite3ReleaseTempReg(pParse, r2);
3613 if( pKeyInfo ){
3614 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
3616 if( addrOnce ){
3617 sqlite3VdbeAddOp1(v, OP_NullRow, iTab);
3618 sqlite3VdbeJumpHere(v, addrOnce);
3619 /* Subroutine return */
3620 assert( ExprUseYSub(pExpr) );
3621 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3622 || pParse->nErr );
3623 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3624 pExpr->y.sub.iAddr, 1);
3625 VdbeCoverage(v);
3626 sqlite3ClearTempRegCache(pParse);
3629 #endif /* SQLITE_OMIT_SUBQUERY */
3632 ** Generate code for scalar subqueries used as a subquery expression
3633 ** or EXISTS operator:
3635 ** (SELECT a FROM b) -- subquery
3636 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3638 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3640 ** Return the register that holds the result. For a multi-column SELECT,
3641 ** the result is stored in a contiguous array of registers and the
3642 ** return value is the register of the left-most result column.
3643 ** Return 0 if an error occurs.
3645 #ifndef SQLITE_OMIT_SUBQUERY
3646 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
3647 int addrOnce = 0; /* Address of OP_Once at top of subroutine */
3648 int rReg = 0; /* Register storing resulting */
3649 Select *pSel; /* SELECT statement to encode */
3650 SelectDest dest; /* How to deal with SELECT result */
3651 int nReg; /* Registers to allocate */
3652 Expr *pLimit; /* New limit expression */
3653 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3654 int addrExplain; /* Address of OP_Explain instruction */
3655 #endif
3657 Vdbe *v = pParse->pVdbe;
3658 assert( v!=0 );
3659 if( pParse->nErr ) return 0;
3660 testcase( pExpr->op==TK_EXISTS );
3661 testcase( pExpr->op==TK_SELECT );
3662 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3663 assert( ExprUseXSelect(pExpr) );
3664 pSel = pExpr->x.pSelect;
3666 /* If this routine has already been coded, then invoke it as a
3667 ** subroutine. */
3668 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3669 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3670 assert( ExprUseYSub(pExpr) );
3671 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3672 pExpr->y.sub.iAddr);
3673 return pExpr->iTable;
3676 /* Begin coding the subroutine */
3677 assert( !ExprUseYWin(pExpr) );
3678 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
3679 ExprSetProperty(pExpr, EP_Subrtn);
3680 pExpr->y.sub.regReturn = ++pParse->nMem;
3681 pExpr->y.sub.iAddr =
3682 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3684 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3685 ** is encountered if any of the following is true:
3687 ** * The right-hand side is a correlated subquery
3688 ** * The right-hand side is an expression list containing variables
3689 ** * We are inside a trigger
3691 ** If all of the above are false, then we can run this code just once
3692 ** save the results, and reuse the same result on subsequent invocations.
3694 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3695 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3698 /* For a SELECT, generate code to put the values for all columns of
3699 ** the first row into an array of registers and return the index of
3700 ** the first register.
3702 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3703 ** into a register and return that register number.
3705 ** In both cases, the query is augmented with "LIMIT 1". Any
3706 ** preexisting limit is discarded in place of the new LIMIT 1.
3708 ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d",
3709 addrOnce?"":"CORRELATED ", pSel->selId));
3710 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1);
3711 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3712 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3713 pParse->nMem += nReg;
3714 if( pExpr->op==TK_SELECT ){
3715 dest.eDest = SRT_Mem;
3716 dest.iSdst = dest.iSDParm;
3717 dest.nSdst = nReg;
3718 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3719 VdbeComment((v, "Init subquery result"));
3720 }else{
3721 dest.eDest = SRT_Exists;
3722 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3723 VdbeComment((v, "Init EXISTS result"));
3725 if( pSel->pLimit ){
3726 /* The subquery already has a limit. If the pre-existing limit is X
3727 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3728 sqlite3 *db = pParse->db;
3729 pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3730 if( pLimit ){
3731 pLimit->affExpr = SQLITE_AFF_NUMERIC;
3732 pLimit = sqlite3PExpr(pParse, TK_NE,
3733 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3735 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
3736 pSel->pLimit->pLeft = pLimit;
3737 }else{
3738 /* If there is no pre-existing limit add a limit of 1 */
3739 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3740 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3742 pSel->iLimit = 0;
3743 if( sqlite3Select(pParse, pSel, &dest) ){
3744 pExpr->op2 = pExpr->op;
3745 pExpr->op = TK_ERROR;
3746 return 0;
3748 pExpr->iTable = rReg = dest.iSDParm;
3749 ExprSetVVAProperty(pExpr, EP_NoReduce);
3750 if( addrOnce ){
3751 sqlite3VdbeJumpHere(v, addrOnce);
3753 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
3755 /* Subroutine return */
3756 assert( ExprUseYSub(pExpr) );
3757 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3758 || pParse->nErr );
3759 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3760 pExpr->y.sub.iAddr, 1);
3761 VdbeCoverage(v);
3762 sqlite3ClearTempRegCache(pParse);
3763 return rReg;
3765 #endif /* SQLITE_OMIT_SUBQUERY */
3767 #ifndef SQLITE_OMIT_SUBQUERY
3769 ** Expr pIn is an IN(...) expression. This function checks that the
3770 ** sub-select on the RHS of the IN() operator has the same number of
3771 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3772 ** a sub-query, that the LHS is a vector of size 1.
3774 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3775 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3776 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
3777 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3778 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3779 return 1;
3781 }else if( nVector!=1 ){
3782 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3783 return 1;
3785 return 0;
3787 #endif
3789 #ifndef SQLITE_OMIT_SUBQUERY
3791 ** Generate code for an IN expression.
3793 ** x IN (SELECT ...)
3794 ** x IN (value, value, ...)
3796 ** The left-hand side (LHS) is a scalar or vector expression. The
3797 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3798 ** subquery. If the RHS is a subquery, the number of result columns must
3799 ** match the number of columns in the vector on the LHS. If the RHS is
3800 ** a list of values, the LHS must be a scalar.
3802 ** The IN operator is true if the LHS value is contained within the RHS.
3803 ** The result is false if the LHS is definitely not in the RHS. The
3804 ** result is NULL if the presence of the LHS in the RHS cannot be
3805 ** determined due to NULLs.
3807 ** This routine generates code that jumps to destIfFalse if the LHS is not
3808 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3809 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3810 ** within the RHS then fall through.
3812 ** See the separate in-operator.md documentation file in the canonical
3813 ** SQLite source tree for additional information.
3815 static void sqlite3ExprCodeIN(
3816 Parse *pParse, /* Parsing and code generating context */
3817 Expr *pExpr, /* The IN expression */
3818 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
3819 int destIfNull /* Jump here if the results are unknown due to NULLs */
3821 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
3822 int eType; /* Type of the RHS */
3823 int rLhs; /* Register(s) holding the LHS values */
3824 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
3825 Vdbe *v; /* Statement under construction */
3826 int *aiMap = 0; /* Map from vector field to index column */
3827 char *zAff = 0; /* Affinity string for comparisons */
3828 int nVector; /* Size of vectors for this IN operator */
3829 int iDummy; /* Dummy parameter to exprCodeVector() */
3830 Expr *pLeft; /* The LHS of the IN operator */
3831 int i; /* loop counter */
3832 int destStep2; /* Where to jump when NULLs seen in step 2 */
3833 int destStep6 = 0; /* Start of code for Step 6 */
3834 int addrTruthOp; /* Address of opcode that determines the IN is true */
3835 int destNotNull; /* Jump here if a comparison is not true in step 6 */
3836 int addrTop; /* Top of the step-6 loop */
3837 int iTab = 0; /* Index to use */
3838 u8 okConstFactor = pParse->okConstFactor;
3840 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3841 pLeft = pExpr->pLeft;
3842 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3843 zAff = exprINAffinity(pParse, pExpr);
3844 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3845 aiMap = (int*)sqlite3DbMallocZero(
3846 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3848 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3850 /* Attempt to compute the RHS. After this step, if anything other than
3851 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3852 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3853 ** the RHS has not yet been coded. */
3854 v = pParse->pVdbe;
3855 assert( v!=0 ); /* OOM detected prior to this routine */
3856 VdbeNoopComment((v, "begin IN expr"));
3857 eType = sqlite3FindInIndex(pParse, pExpr,
3858 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3859 destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3860 aiMap, &iTab);
3862 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3863 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3865 #ifdef SQLITE_DEBUG
3866 /* Confirm that aiMap[] contains nVector integer values between 0 and
3867 ** nVector-1. */
3868 for(i=0; i<nVector; i++){
3869 int j, cnt;
3870 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3871 assert( cnt==1 );
3873 #endif
3875 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3876 ** vector, then it is stored in an array of nVector registers starting
3877 ** at r1.
3879 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3880 ** so that the fields are in the same order as an existing index. The
3881 ** aiMap[] array contains a mapping from the original LHS field order to
3882 ** the field order that matches the RHS index.
3884 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3885 ** even if it is constant, as OP_Affinity may be used on the register
3886 ** by code generated below. */
3887 assert( pParse->okConstFactor==okConstFactor );
3888 pParse->okConstFactor = 0;
3889 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3890 pParse->okConstFactor = okConstFactor;
3891 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3892 if( i==nVector ){
3893 /* LHS fields are not reordered */
3894 rLhs = rLhsOrig;
3895 }else{
3896 /* Need to reorder the LHS fields according to aiMap */
3897 rLhs = sqlite3GetTempRange(pParse, nVector);
3898 for(i=0; i<nVector; i++){
3899 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3903 /* If sqlite3FindInIndex() did not find or create an index that is
3904 ** suitable for evaluating the IN operator, then evaluate using a
3905 ** sequence of comparisons.
3907 ** This is step (1) in the in-operator.md optimized algorithm.
3909 if( eType==IN_INDEX_NOOP ){
3910 ExprList *pList;
3911 CollSeq *pColl;
3912 int labelOk = sqlite3VdbeMakeLabel(pParse);
3913 int r2, regToFree;
3914 int regCkNull = 0;
3915 int ii;
3916 assert( ExprUseXList(pExpr) );
3917 pList = pExpr->x.pList;
3918 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3919 if( destIfNull!=destIfFalse ){
3920 regCkNull = sqlite3GetTempReg(pParse);
3921 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3923 for(ii=0; ii<pList->nExpr; ii++){
3924 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3925 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3926 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3928 sqlite3ReleaseTempReg(pParse, regToFree);
3929 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3930 int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
3931 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
3932 (void*)pColl, P4_COLLSEQ);
3933 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
3934 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
3935 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
3936 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
3937 sqlite3VdbeChangeP5(v, zAff[0]);
3938 }else{
3939 int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
3940 assert( destIfNull==destIfFalse );
3941 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
3942 (void*)pColl, P4_COLLSEQ);
3943 VdbeCoverageIf(v, op==OP_Ne);
3944 VdbeCoverageIf(v, op==OP_IsNull);
3945 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3948 if( regCkNull ){
3949 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3950 sqlite3VdbeGoto(v, destIfFalse);
3952 sqlite3VdbeResolveLabel(v, labelOk);
3953 sqlite3ReleaseTempReg(pParse, regCkNull);
3954 goto sqlite3ExprCodeIN_finished;
3957 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3958 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3959 ** We will then skip the binary search of the RHS.
3961 if( destIfNull==destIfFalse ){
3962 destStep2 = destIfFalse;
3963 }else{
3964 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3966 for(i=0; i<nVector; i++){
3967 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3968 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
3969 if( sqlite3ExprCanBeNull(p) ){
3970 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3971 VdbeCoverage(v);
3975 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3976 ** of the RHS using the LHS as a probe. If found, the result is
3977 ** true.
3979 if( eType==IN_INDEX_ROWID ){
3980 /* In this case, the RHS is the ROWID of table b-tree and so we also
3981 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3982 ** into a single opcode. */
3983 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3984 VdbeCoverage(v);
3985 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
3986 }else{
3987 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3988 if( destIfFalse==destIfNull ){
3989 /* Combine Step 3 and Step 5 into a single opcode */
3990 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3991 rLhs, nVector); VdbeCoverage(v);
3992 goto sqlite3ExprCodeIN_finished;
3994 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3995 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3996 rLhs, nVector); VdbeCoverage(v);
3999 /* Step 4. If the RHS is known to be non-NULL and we did not find
4000 ** an match on the search above, then the result must be FALSE.
4002 if( rRhsHasNull && nVector==1 ){
4003 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
4004 VdbeCoverage(v);
4007 /* Step 5. If we do not care about the difference between NULL and
4008 ** FALSE, then just return false.
4010 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
4012 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
4013 ** If any comparison is NULL, then the result is NULL. If all
4014 ** comparisons are FALSE then the final result is FALSE.
4016 ** For a scalar LHS, it is sufficient to check just the first row
4017 ** of the RHS.
4019 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
4020 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
4021 VdbeCoverage(v);
4022 if( nVector>1 ){
4023 destNotNull = sqlite3VdbeMakeLabel(pParse);
4024 }else{
4025 /* For nVector==1, combine steps 6 and 7 by immediately returning
4026 ** FALSE if the first comparison is not NULL */
4027 destNotNull = destIfFalse;
4029 for(i=0; i<nVector; i++){
4030 Expr *p;
4031 CollSeq *pColl;
4032 int r3 = sqlite3GetTempReg(pParse);
4033 p = sqlite3VectorFieldSubexpr(pLeft, i);
4034 pColl = sqlite3ExprCollSeq(pParse, p);
4035 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
4036 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
4037 (void*)pColl, P4_COLLSEQ);
4038 VdbeCoverage(v);
4039 sqlite3ReleaseTempReg(pParse, r3);
4041 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
4042 if( nVector>1 ){
4043 sqlite3VdbeResolveLabel(v, destNotNull);
4044 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
4045 VdbeCoverage(v);
4047 /* Step 7: If we reach this point, we know that the result must
4048 ** be false. */
4049 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
4052 /* Jumps here in order to return true. */
4053 sqlite3VdbeJumpHere(v, addrTruthOp);
4055 sqlite3ExprCodeIN_finished:
4056 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
4057 VdbeComment((v, "end IN expr"));
4058 sqlite3ExprCodeIN_oom_error:
4059 sqlite3DbFree(pParse->db, aiMap);
4060 sqlite3DbFree(pParse->db, zAff);
4062 #endif /* SQLITE_OMIT_SUBQUERY */
4064 #ifndef SQLITE_OMIT_FLOATING_POINT
4066 ** Generate an instruction that will put the floating point
4067 ** value described by z[0..n-1] into register iMem.
4069 ** The z[] string will probably not be zero-terminated. But the
4070 ** z[n] character is guaranteed to be something that does not look
4071 ** like the continuation of the number.
4073 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
4074 if( ALWAYS(z!=0) ){
4075 double value;
4076 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
4077 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
4078 if( negateFlag ) value = -value;
4079 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
4082 #endif
4086 ** Generate an instruction that will put the integer describe by
4087 ** text z[0..n-1] into register iMem.
4089 ** Expr.u.zToken is always UTF8 and zero-terminated.
4091 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
4092 Vdbe *v = pParse->pVdbe;
4093 if( pExpr->flags & EP_IntValue ){
4094 int i = pExpr->u.iValue;
4095 assert( i>=0 );
4096 if( negFlag ) i = -i;
4097 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
4098 }else{
4099 int c;
4100 i64 value;
4101 const char *z = pExpr->u.zToken;
4102 assert( z!=0 );
4103 c = sqlite3DecOrHexToI64(z, &value);
4104 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
4105 #ifdef SQLITE_OMIT_FLOATING_POINT
4106 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
4107 #else
4108 #ifndef SQLITE_OMIT_HEX_INTEGER
4109 if( sqlite3_strnicmp(z,"0x",2)==0 ){
4110 sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T",
4111 negFlag?"-":"",pExpr);
4112 }else
4113 #endif
4115 codeReal(v, z, negFlag, iMem);
4117 #endif
4118 }else{
4119 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
4120 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
4126 /* Generate code that will load into register regOut a value that is
4127 ** appropriate for the iIdxCol-th column of index pIdx.
4129 void sqlite3ExprCodeLoadIndexColumn(
4130 Parse *pParse, /* The parsing context */
4131 Index *pIdx, /* The index whose column is to be loaded */
4132 int iTabCur, /* Cursor pointing to a table row */
4133 int iIdxCol, /* The column of the index to be loaded */
4134 int regOut /* Store the index column value in this register */
4136 i16 iTabCol = pIdx->aiColumn[iIdxCol];
4137 if( iTabCol==XN_EXPR ){
4138 assert( pIdx->aColExpr );
4139 assert( pIdx->aColExpr->nExpr>iIdxCol );
4140 pParse->iSelfTab = iTabCur + 1;
4141 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
4142 pParse->iSelfTab = 0;
4143 }else{
4144 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
4145 iTabCol, regOut);
4149 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4151 ** Generate code that will compute the value of generated column pCol
4152 ** and store the result in register regOut
4154 void sqlite3ExprCodeGeneratedColumn(
4155 Parse *pParse, /* Parsing context */
4156 Table *pTab, /* Table containing the generated column */
4157 Column *pCol, /* The generated column */
4158 int regOut /* Put the result in this register */
4160 int iAddr;
4161 Vdbe *v = pParse->pVdbe;
4162 int nErr = pParse->nErr;
4163 assert( v!=0 );
4164 assert( pParse->iSelfTab!=0 );
4165 if( pParse->iSelfTab>0 ){
4166 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
4167 }else{
4168 iAddr = 0;
4170 sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
4171 if( pCol->affinity>=SQLITE_AFF_TEXT ){
4172 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
4174 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
4175 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
4177 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4180 ** Generate code to extract the value of the iCol-th column of a table.
4182 void sqlite3ExprCodeGetColumnOfTable(
4183 Vdbe *v, /* Parsing context */
4184 Table *pTab, /* The table containing the value */
4185 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
4186 int iCol, /* Index of the column to extract */
4187 int regOut /* Extract the value into this register */
4189 Column *pCol;
4190 assert( v!=0 );
4191 assert( pTab!=0 );
4192 assert( iCol!=XN_EXPR );
4193 if( iCol<0 || iCol==pTab->iPKey ){
4194 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
4195 VdbeComment((v, "%s.rowid", pTab->zName));
4196 }else{
4197 int op;
4198 int x;
4199 if( IsVirtual(pTab) ){
4200 op = OP_VColumn;
4201 x = iCol;
4202 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4203 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
4204 Parse *pParse = sqlite3VdbeParser(v);
4205 if( pCol->colFlags & COLFLAG_BUSY ){
4206 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4207 pCol->zCnName);
4208 }else{
4209 int savedSelfTab = pParse->iSelfTab;
4210 pCol->colFlags |= COLFLAG_BUSY;
4211 pParse->iSelfTab = iTabCur+1;
4212 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut);
4213 pParse->iSelfTab = savedSelfTab;
4214 pCol->colFlags &= ~COLFLAG_BUSY;
4216 return;
4217 #endif
4218 }else if( !HasRowid(pTab) ){
4219 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
4220 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
4221 op = OP_Column;
4222 }else{
4223 x = sqlite3TableColumnToStorage(pTab,iCol);
4224 testcase( x!=iCol );
4225 op = OP_Column;
4227 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
4228 sqlite3ColumnDefault(v, pTab, iCol, regOut);
4233 ** Generate code that will extract the iColumn-th column from
4234 ** table pTab and store the column value in register iReg.
4236 ** There must be an open cursor to pTab in iTable when this routine
4237 ** is called. If iColumn<0 then code is generated that extracts the rowid.
4239 int sqlite3ExprCodeGetColumn(
4240 Parse *pParse, /* Parsing and code generating context */
4241 Table *pTab, /* Description of the table we are reading from */
4242 int iColumn, /* Index of the table column */
4243 int iTable, /* The cursor pointing to the table */
4244 int iReg, /* Store results here */
4245 u8 p5 /* P5 value for OP_Column + FLAGS */
4247 assert( pParse->pVdbe!=0 );
4248 assert( (p5 & (OPFLAG_NOCHNG|OPFLAG_TYPEOFARG|OPFLAG_LENGTHARG))==p5 );
4249 assert( IsVirtual(pTab) || (p5 & OPFLAG_NOCHNG)==0 );
4250 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
4251 if( p5 ){
4252 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
4253 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
4254 if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG);
4256 return iReg;
4260 ** Generate code to move content from registers iFrom...iFrom+nReg-1
4261 ** over to iTo..iTo+nReg-1.
4263 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
4264 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
4268 ** Convert a scalar expression node to a TK_REGISTER referencing
4269 ** register iReg. The caller must ensure that iReg already contains
4270 ** the correct value for the expression.
4272 void sqlite3ExprToRegister(Expr *pExpr, int iReg){
4273 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
4274 if( NEVER(p==0) ) return;
4275 if( p->op==TK_REGISTER ){
4276 assert( p->iTable==iReg );
4277 }else{
4278 p->op2 = p->op;
4279 p->op = TK_REGISTER;
4280 p->iTable = iReg;
4281 ExprClearProperty(p, EP_Skip);
4286 ** Evaluate an expression (either a vector or a scalar expression) and store
4287 ** the result in contiguous temporary registers. Return the index of
4288 ** the first register used to store the result.
4290 ** If the returned result register is a temporary scalar, then also write
4291 ** that register number into *piFreeable. If the returned result register
4292 ** is not a temporary or if the expression is a vector set *piFreeable
4293 ** to 0.
4295 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
4296 int iResult;
4297 int nResult = sqlite3ExprVectorSize(p);
4298 if( nResult==1 ){
4299 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
4300 }else{
4301 *piFreeable = 0;
4302 if( p->op==TK_SELECT ){
4303 #if SQLITE_OMIT_SUBQUERY
4304 iResult = 0;
4305 #else
4306 iResult = sqlite3CodeSubselect(pParse, p);
4307 #endif
4308 }else{
4309 int i;
4310 iResult = pParse->nMem+1;
4311 pParse->nMem += nResult;
4312 assert( ExprUseXList(p) );
4313 for(i=0; i<nResult; i++){
4314 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
4318 return iResult;
4322 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4323 ** so that a subsequent copy will not be merged into this one.
4325 static void setDoNotMergeFlagOnCopy(Vdbe *v){
4326 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
4327 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergeable */
4332 ** Generate code to implement special SQL functions that are implemented
4333 ** in-line rather than by using the usual callbacks.
4335 static int exprCodeInlineFunction(
4336 Parse *pParse, /* Parsing context */
4337 ExprList *pFarg, /* List of function arguments */
4338 int iFuncId, /* Function ID. One of the INTFUNC_... values */
4339 int target /* Store function result in this register */
4341 int nFarg;
4342 Vdbe *v = pParse->pVdbe;
4343 assert( v!=0 );
4344 assert( pFarg!=0 );
4345 nFarg = pFarg->nExpr;
4346 assert( nFarg>0 ); /* All in-line functions have at least one argument */
4347 switch( iFuncId ){
4348 case INLINEFUNC_coalesce: {
4349 /* Attempt a direct implementation of the built-in COALESCE() and
4350 ** IFNULL() functions. This avoids unnecessary evaluation of
4351 ** arguments past the first non-NULL argument.
4353 int endCoalesce = sqlite3VdbeMakeLabel(pParse);
4354 int i;
4355 assert( nFarg>=2 );
4356 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
4357 for(i=1; i<nFarg; i++){
4358 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
4359 VdbeCoverage(v);
4360 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
4362 setDoNotMergeFlagOnCopy(v);
4363 sqlite3VdbeResolveLabel(v, endCoalesce);
4364 break;
4366 case INLINEFUNC_iif: {
4367 Expr caseExpr;
4368 memset(&caseExpr, 0, sizeof(caseExpr));
4369 caseExpr.op = TK_CASE;
4370 caseExpr.x.pList = pFarg;
4371 return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
4373 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4374 case INLINEFUNC_sqlite_offset: {
4375 Expr *pArg = pFarg->a[0].pExpr;
4376 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
4377 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4378 }else{
4379 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4381 break;
4383 #endif
4384 default: {
4385 /* The UNLIKELY() function is a no-op. The result is the value
4386 ** of the first argument.
4388 assert( nFarg==1 || nFarg==2 );
4389 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
4390 break;
4393 /***********************************************************************
4394 ** Test-only SQL functions that are only usable if enabled
4395 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4397 #if !defined(SQLITE_UNTESTABLE)
4398 case INLINEFUNC_expr_compare: {
4399 /* Compare two expressions using sqlite3ExprCompare() */
4400 assert( nFarg==2 );
4401 sqlite3VdbeAddOp2(v, OP_Integer,
4402 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4403 target);
4404 break;
4407 case INLINEFUNC_expr_implies_expr: {
4408 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4409 assert( nFarg==2 );
4410 sqlite3VdbeAddOp2(v, OP_Integer,
4411 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4412 target);
4413 break;
4416 case INLINEFUNC_implies_nonnull_row: {
4417 /* Result of sqlite3ExprImpliesNonNullRow() */
4418 Expr *pA1;
4419 assert( nFarg==2 );
4420 pA1 = pFarg->a[1].pExpr;
4421 if( pA1->op==TK_COLUMN ){
4422 sqlite3VdbeAddOp2(v, OP_Integer,
4423 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1),
4424 target);
4425 }else{
4426 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4428 break;
4431 case INLINEFUNC_affinity: {
4432 /* The AFFINITY() function evaluates to a string that describes
4433 ** the type affinity of the argument. This is used for testing of
4434 ** the SQLite type logic.
4436 const char *azAff[] = { "blob", "text", "numeric", "integer",
4437 "real", "flexnum" };
4438 char aff;
4439 assert( nFarg==1 );
4440 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
4441 assert( aff<=SQLITE_AFF_NONE
4442 || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) );
4443 sqlite3VdbeLoadString(v, target,
4444 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
4445 break;
4447 #endif /* !defined(SQLITE_UNTESTABLE) */
4449 return target;
4453 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4454 ** If it is, then resolve the expression by reading from the index and
4455 ** return the register into which the value has been read. If pExpr is
4456 ** not an indexed expression, then return negative.
4458 static SQLITE_NOINLINE int sqlite3IndexedExprLookup(
4459 Parse *pParse, /* The parsing context */
4460 Expr *pExpr, /* The expression to potentially bypass */
4461 int target /* Where to store the result of the expression */
4463 IndexedExpr *p;
4464 Vdbe *v;
4465 for(p=pParse->pIdxEpr; p; p=p->pIENext){
4466 u8 exprAff;
4467 int iDataCur = p->iDataCur;
4468 if( iDataCur<0 ) continue;
4469 if( pParse->iSelfTab ){
4470 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
4471 iDataCur = -1;
4473 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
4474 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
4475 exprAff = sqlite3ExprAffinity(pExpr);
4476 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
4477 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
4478 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
4480 /* Affinity mismatch on a generated column */
4481 continue;
4484 v = pParse->pVdbe;
4485 assert( v!=0 );
4486 if( p->bMaybeNullRow ){
4487 /* If the index is on a NULL row due to an outer join, then we
4488 ** cannot extract the value from the index. The value must be
4489 ** computed using the original expression. */
4490 int addr = sqlite3VdbeCurrentAddr(v);
4491 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
4492 VdbeCoverage(v);
4493 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4494 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4495 sqlite3VdbeGoto(v, 0);
4496 p = pParse->pIdxEpr;
4497 pParse->pIdxEpr = 0;
4498 sqlite3ExprCode(pParse, pExpr, target);
4499 pParse->pIdxEpr = p;
4500 sqlite3VdbeJumpHere(v, addr+2);
4501 }else{
4502 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4503 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4505 return target;
4507 return -1; /* Not found */
4512 ** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
4513 ** function checks the Parse.pIdxPartExpr list to see if this column
4514 ** can be replaced with a constant value. If so, it generates code to
4515 ** put the constant value in a register (ideally, but not necessarily,
4516 ** register iTarget) and returns the register number.
4518 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
4519 ** returned.
4521 static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){
4522 IndexedExpr *p;
4523 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
4524 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
4525 Vdbe *v = pParse->pVdbe;
4526 int addr = 0;
4527 int ret;
4529 if( p->bMaybeNullRow ){
4530 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
4532 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
4533 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
4534 (const char*)&p->aff, 1);
4535 if( addr ){
4536 sqlite3VdbeJumpHere(v, addr);
4537 sqlite3VdbeChangeP3(v, addr, ret);
4539 return ret;
4542 return 0;
4547 ** Generate code into the current Vdbe to evaluate the given
4548 ** expression. Attempt to store the results in register "target".
4549 ** Return the register where results are stored.
4551 ** With this routine, there is no guarantee that results will
4552 ** be stored in target. The result might be stored in some other
4553 ** register if it is convenient to do so. The calling function
4554 ** must check the return code and move the results to the desired
4555 ** register.
4557 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
4558 Vdbe *v = pParse->pVdbe; /* The VM under construction */
4559 int op; /* The opcode being coded */
4560 int inReg = target; /* Results stored in register inReg */
4561 int regFree1 = 0; /* If non-zero free this temporary register */
4562 int regFree2 = 0; /* If non-zero free this temporary register */
4563 int r1, r2; /* Various register numbers */
4564 Expr tempX; /* Temporary expression node */
4565 int p5 = 0;
4567 assert( target>0 && target<=pParse->nMem );
4568 assert( v!=0 );
4570 expr_code_doover:
4571 if( pExpr==0 ){
4572 op = TK_NULL;
4573 }else if( pParse->pIdxEpr!=0
4574 && !ExprHasProperty(pExpr, EP_Leaf)
4575 && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0
4577 return r1;
4578 }else{
4579 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
4580 op = pExpr->op;
4582 assert( op!=TK_ORDER );
4583 switch( op ){
4584 case TK_AGG_COLUMN: {
4585 AggInfo *pAggInfo = pExpr->pAggInfo;
4586 struct AggInfo_col *pCol;
4587 assert( pAggInfo!=0 );
4588 assert( pExpr->iAgg>=0 );
4589 if( pExpr->iAgg>=pAggInfo->nColumn ){
4590 /* Happens when the left table of a RIGHT JOIN is null and
4591 ** is using an expression index */
4592 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4593 #ifdef SQLITE_VDBE_COVERAGE
4594 /* Verify that the OP_Null above is exercised by tests
4595 ** tag-20230325-2 */
4596 sqlite3VdbeAddOp3(v, OP_NotNull, target, 1, 20230325);
4597 VdbeCoverageNeverTaken(v);
4598 #endif
4599 break;
4601 pCol = &pAggInfo->aCol[pExpr->iAgg];
4602 if( !pAggInfo->directMode ){
4603 return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
4604 }else if( pAggInfo->useSortingIdx ){
4605 Table *pTab = pCol->pTab;
4606 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
4607 pCol->iSorterColumn, target);
4608 if( pTab==0 ){
4609 /* No comment added */
4610 }else if( pCol->iColumn<0 ){
4611 VdbeComment((v,"%s.rowid",pTab->zName));
4612 }else{
4613 VdbeComment((v,"%s.%s",
4614 pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
4615 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
4616 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4619 return target;
4620 }else if( pExpr->y.pTab==0 ){
4621 /* This case happens when the argument to an aggregate function
4622 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4623 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target);
4624 return target;
4626 /* Otherwise, fall thru into the TK_COLUMN case */
4627 /* no break */ deliberate_fall_through
4629 case TK_COLUMN: {
4630 int iTab = pExpr->iTable;
4631 int iReg;
4632 if( ExprHasProperty(pExpr, EP_FixedCol) ){
4633 /* This COLUMN expression is really a constant due to WHERE clause
4634 ** constraints, and that constant is coded by the pExpr->pLeft
4635 ** expression. However, make sure the constant has the correct
4636 ** datatype by applying the Affinity of the table column to the
4637 ** constant.
4639 int aff;
4640 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
4641 assert( ExprUseYTab(pExpr) );
4642 assert( pExpr->y.pTab!=0 );
4643 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
4644 if( aff>SQLITE_AFF_BLOB ){
4645 static const char zAff[] = "B\000C\000D\000E\000F";
4646 assert( SQLITE_AFF_BLOB=='A' );
4647 assert( SQLITE_AFF_TEXT=='B' );
4648 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
4649 &zAff[(aff-'B')*2], P4_STATIC);
4651 return iReg;
4653 if( iTab<0 ){
4654 if( pParse->iSelfTab<0 ){
4655 /* Other columns in the same row for CHECK constraints or
4656 ** generated columns or for inserting into partial index.
4657 ** The row is unpacked into registers beginning at
4658 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4659 ** immediately prior to the first column.
4661 Column *pCol;
4662 Table *pTab;
4663 int iSrc;
4664 int iCol = pExpr->iColumn;
4665 assert( ExprUseYTab(pExpr) );
4666 pTab = pExpr->y.pTab;
4667 assert( pTab!=0 );
4668 assert( iCol>=XN_ROWID );
4669 assert( iCol<pTab->nCol );
4670 if( iCol<0 ){
4671 return -1-pParse->iSelfTab;
4673 pCol = pTab->aCol + iCol;
4674 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
4675 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
4676 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4677 if( pCol->colFlags & COLFLAG_GENERATED ){
4678 if( pCol->colFlags & COLFLAG_BUSY ){
4679 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4680 pCol->zCnName);
4681 return 0;
4683 pCol->colFlags |= COLFLAG_BUSY;
4684 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
4685 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc);
4687 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
4688 return iSrc;
4689 }else
4690 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4691 if( pCol->affinity==SQLITE_AFF_REAL ){
4692 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
4693 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4694 return target;
4695 }else{
4696 return iSrc;
4698 }else{
4699 /* Coding an expression that is part of an index where column names
4700 ** in the index refer to the table to which the index belongs */
4701 iTab = pParse->iSelfTab - 1;
4704 else if( pParse->pIdxPartExpr
4705 && 0!=(r1 = exprPartidxExprLookup(pParse, pExpr, target))
4707 return r1;
4709 assert( ExprUseYTab(pExpr) );
4710 assert( pExpr->y.pTab!=0 );
4711 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
4712 pExpr->iColumn, iTab, target,
4713 pExpr->op2);
4714 return iReg;
4716 case TK_INTEGER: {
4717 codeInteger(pParse, pExpr, 0, target);
4718 return target;
4720 case TK_TRUEFALSE: {
4721 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
4722 return target;
4724 #ifndef SQLITE_OMIT_FLOATING_POINT
4725 case TK_FLOAT: {
4726 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4727 codeReal(v, pExpr->u.zToken, 0, target);
4728 return target;
4730 #endif
4731 case TK_STRING: {
4732 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4733 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
4734 return target;
4736 default: {
4737 /* Make NULL the default case so that if a bug causes an illegal
4738 ** Expr node to be passed into this function, it will be handled
4739 ** sanely and not crash. But keep the assert() to bring the problem
4740 ** to the attention of the developers. */
4741 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
4742 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4743 return target;
4745 #ifndef SQLITE_OMIT_BLOB_LITERAL
4746 case TK_BLOB: {
4747 int n;
4748 const char *z;
4749 char *zBlob;
4750 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4751 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
4752 assert( pExpr->u.zToken[1]=='\'' );
4753 z = &pExpr->u.zToken[2];
4754 n = sqlite3Strlen30(z) - 1;
4755 assert( z[n]=='\'' );
4756 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
4757 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
4758 return target;
4760 #endif
4761 case TK_VARIABLE: {
4762 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4763 assert( pExpr->u.zToken!=0 );
4764 assert( pExpr->u.zToken[0]!=0 );
4765 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
4766 return target;
4768 case TK_REGISTER: {
4769 return pExpr->iTable;
4771 #ifndef SQLITE_OMIT_CAST
4772 case TK_CAST: {
4773 /* Expressions of the form: CAST(pLeft AS token) */
4774 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4775 assert( inReg==target );
4776 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4777 sqlite3VdbeAddOp2(v, OP_Cast, target,
4778 sqlite3AffinityType(pExpr->u.zToken, 0));
4779 return inReg;
4781 #endif /* SQLITE_OMIT_CAST */
4782 case TK_IS:
4783 case TK_ISNOT:
4784 op = (op==TK_IS) ? TK_EQ : TK_NE;
4785 p5 = SQLITE_NULLEQ;
4786 /* fall-through */
4787 case TK_LT:
4788 case TK_LE:
4789 case TK_GT:
4790 case TK_GE:
4791 case TK_NE:
4792 case TK_EQ: {
4793 Expr *pLeft = pExpr->pLeft;
4794 if( sqlite3ExprIsVector(pLeft) ){
4795 codeVectorCompare(pParse, pExpr, target, op, p5);
4796 }else{
4797 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
4798 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4799 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
4800 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
4801 sqlite3VdbeCurrentAddr(v)+2, p5,
4802 ExprHasProperty(pExpr,EP_Commuted));
4803 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4804 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4805 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4806 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4807 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
4808 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
4809 if( p5==SQLITE_NULLEQ ){
4810 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
4811 }else{
4812 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
4814 testcase( regFree1==0 );
4815 testcase( regFree2==0 );
4817 break;
4819 case TK_AND:
4820 case TK_OR:
4821 case TK_PLUS:
4822 case TK_STAR:
4823 case TK_MINUS:
4824 case TK_REM:
4825 case TK_BITAND:
4826 case TK_BITOR:
4827 case TK_SLASH:
4828 case TK_LSHIFT:
4829 case TK_RSHIFT:
4830 case TK_CONCAT: {
4831 assert( TK_AND==OP_And ); testcase( op==TK_AND );
4832 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
4833 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
4834 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
4835 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
4836 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
4837 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
4838 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
4839 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
4840 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
4841 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
4842 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4843 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4844 sqlite3VdbeAddOp3(v, op, r2, r1, target);
4845 testcase( regFree1==0 );
4846 testcase( regFree2==0 );
4847 break;
4849 case TK_UMINUS: {
4850 Expr *pLeft = pExpr->pLeft;
4851 assert( pLeft );
4852 if( pLeft->op==TK_INTEGER ){
4853 codeInteger(pParse, pLeft, 1, target);
4854 return target;
4855 #ifndef SQLITE_OMIT_FLOATING_POINT
4856 }else if( pLeft->op==TK_FLOAT ){
4857 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4858 codeReal(v, pLeft->u.zToken, 1, target);
4859 return target;
4860 #endif
4861 }else{
4862 tempX.op = TK_INTEGER;
4863 tempX.flags = EP_IntValue|EP_TokenOnly;
4864 tempX.u.iValue = 0;
4865 ExprClearVVAProperties(&tempX);
4866 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
4867 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
4868 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
4869 testcase( regFree2==0 );
4871 break;
4873 case TK_BITNOT:
4874 case TK_NOT: {
4875 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
4876 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
4877 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4878 testcase( regFree1==0 );
4879 sqlite3VdbeAddOp2(v, op, r1, inReg);
4880 break;
4882 case TK_TRUTH: {
4883 int isTrue; /* IS TRUE or IS NOT TRUE */
4884 int bNormal; /* IS TRUE or IS FALSE */
4885 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4886 testcase( regFree1==0 );
4887 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4888 bNormal = pExpr->op2==TK_IS;
4889 testcase( isTrue && bNormal);
4890 testcase( !isTrue && bNormal);
4891 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
4892 break;
4894 case TK_ISNULL:
4895 case TK_NOTNULL: {
4896 int addr;
4897 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4898 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4899 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4900 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4901 testcase( regFree1==0 );
4902 addr = sqlite3VdbeAddOp1(v, op, r1);
4903 VdbeCoverageIf(v, op==TK_ISNULL);
4904 VdbeCoverageIf(v, op==TK_NOTNULL);
4905 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
4906 sqlite3VdbeJumpHere(v, addr);
4907 break;
4909 case TK_AGG_FUNCTION: {
4910 AggInfo *pInfo = pExpr->pAggInfo;
4911 if( pInfo==0
4912 || NEVER(pExpr->iAgg<0)
4913 || NEVER(pExpr->iAgg>=pInfo->nFunc)
4915 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4916 sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr);
4917 }else{
4918 return AggInfoFuncReg(pInfo, pExpr->iAgg);
4920 break;
4922 case TK_FUNCTION: {
4923 ExprList *pFarg; /* List of function arguments */
4924 int nFarg; /* Number of function arguments */
4925 FuncDef *pDef; /* The function definition object */
4926 const char *zId; /* The function name */
4927 u32 constMask = 0; /* Mask of function arguments that are constant */
4928 int i; /* Loop counter */
4929 sqlite3 *db = pParse->db; /* The database connection */
4930 u8 enc = ENC(db); /* The text encoding used by this database */
4931 CollSeq *pColl = 0; /* A collating sequence */
4933 #ifndef SQLITE_OMIT_WINDOWFUNC
4934 if( ExprHasProperty(pExpr, EP_WinFunc) ){
4935 return pExpr->y.pWin->regResult;
4937 #endif
4939 if( ConstFactorOk(pParse)
4940 && sqlite3ExprIsConstantNotJoin(pParse,pExpr)
4942 /* SQL functions can be expensive. So try to avoid running them
4943 ** multiple times if we know they always give the same result */
4944 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4946 assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
4947 assert( ExprUseXList(pExpr) );
4948 pFarg = pExpr->x.pList;
4949 nFarg = pFarg ? pFarg->nExpr : 0;
4950 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4951 zId = pExpr->u.zToken;
4952 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
4953 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4954 if( pDef==0 && pParse->explain ){
4955 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
4957 #endif
4958 if( pDef==0 || pDef->xFinalize!=0 ){
4959 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
4960 break;
4962 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
4963 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
4964 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
4965 return exprCodeInlineFunction(pParse, pFarg,
4966 SQLITE_PTR_TO_INT(pDef->pUserData), target);
4967 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
4968 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
4971 for(i=0; i<nFarg; i++){
4972 if( i<32 && sqlite3ExprIsConstant(pParse, pFarg->a[i].pExpr) ){
4973 testcase( i==31 );
4974 constMask |= MASKBIT32(i);
4976 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
4977 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
4980 if( pFarg ){
4981 if( constMask ){
4982 r1 = pParse->nMem+1;
4983 pParse->nMem += nFarg;
4984 }else{
4985 r1 = sqlite3GetTempRange(pParse, nFarg);
4988 /* For length() and typeof() and octet_length() functions,
4989 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4990 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
4991 ** unnecessary data loading.
4993 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
4994 u8 exprOp;
4995 assert( nFarg==1 );
4996 assert( pFarg->a[0].pExpr!=0 );
4997 exprOp = pFarg->a[0].pExpr->op;
4998 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
4999 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
5000 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
5001 assert( SQLITE_FUNC_BYTELEN==OPFLAG_BYTELENARG );
5002 assert( (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG)==OPFLAG_BYTELENARG );
5003 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG );
5004 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG );
5005 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG);
5006 pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG;
5010 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_FACTOR);
5011 }else{
5012 r1 = 0;
5014 #ifndef SQLITE_OMIT_VIRTUALTABLE
5015 /* Possibly overload the function if the first argument is
5016 ** a virtual table column.
5018 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
5019 ** second argument, not the first, as the argument to test to
5020 ** see if it is a column in a virtual table. This is done because
5021 ** the left operand of infix functions (the operand we want to
5022 ** control overloading) ends up as the second argument to the
5023 ** function. The expression "A glob B" is equivalent to
5024 ** "glob(B,A). We want to use the A in "A glob B" to test
5025 ** for function overloading. But we use the B term in "glob(B,A)".
5027 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
5028 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
5029 }else if( nFarg>0 ){
5030 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
5032 #endif
5033 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
5034 if( !pColl ) pColl = db->pDfltColl;
5035 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
5037 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
5038 pDef, pExpr->op2);
5039 if( nFarg ){
5040 if( constMask==0 ){
5041 sqlite3ReleaseTempRange(pParse, r1, nFarg);
5042 }else{
5043 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
5046 return target;
5048 #ifndef SQLITE_OMIT_SUBQUERY
5049 case TK_EXISTS:
5050 case TK_SELECT: {
5051 int nCol;
5052 testcase( op==TK_EXISTS );
5053 testcase( op==TK_SELECT );
5054 if( pParse->db->mallocFailed ){
5055 return 0;
5056 }else if( op==TK_SELECT
5057 && ALWAYS( ExprUseXSelect(pExpr) )
5058 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
5060 sqlite3SubselectError(pParse, nCol, 1);
5061 }else{
5062 return sqlite3CodeSubselect(pParse, pExpr);
5064 break;
5066 case TK_SELECT_COLUMN: {
5067 int n;
5068 Expr *pLeft = pExpr->pLeft;
5069 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
5070 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
5071 pLeft->op2 = pParse->withinRJSubrtn;
5073 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
5074 n = sqlite3ExprVectorSize(pLeft);
5075 if( pExpr->iTable!=n ){
5076 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
5077 pExpr->iTable, n);
5079 return pLeft->iTable + pExpr->iColumn;
5081 case TK_IN: {
5082 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5083 int destIfNull = sqlite3VdbeMakeLabel(pParse);
5084 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
5085 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5086 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
5087 sqlite3VdbeResolveLabel(v, destIfFalse);
5088 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
5089 sqlite3VdbeResolveLabel(v, destIfNull);
5090 return target;
5092 #endif /* SQLITE_OMIT_SUBQUERY */
5096 ** x BETWEEN y AND z
5098 ** This is equivalent to
5100 ** x>=y AND x<=z
5102 ** X is stored in pExpr->pLeft.
5103 ** Y is stored in pExpr->pList->a[0].pExpr.
5104 ** Z is stored in pExpr->pList->a[1].pExpr.
5106 case TK_BETWEEN: {
5107 exprCodeBetween(pParse, pExpr, target, 0, 0);
5108 return target;
5110 case TK_COLLATE: {
5111 if( !ExprHasProperty(pExpr, EP_Collate) ){
5112 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
5113 ** "SOFT-COLLATE" that is added to constraints that are pushed down
5114 ** from outer queries into sub-queries by the WHERE-clause push-down
5115 ** optimization. Clear subtypes as subtypes may not cross a subquery
5116 ** boundary.
5118 assert( pExpr->pLeft );
5119 sqlite3ExprCode(pParse, pExpr->pLeft, target);
5120 sqlite3VdbeAddOp1(v, OP_ClrSubtype, target);
5121 return target;
5122 }else{
5123 pExpr = pExpr->pLeft;
5124 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
5127 case TK_SPAN:
5128 case TK_UPLUS: {
5129 pExpr = pExpr->pLeft;
5130 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
5133 case TK_TRIGGER: {
5134 /* If the opcode is TK_TRIGGER, then the expression is a reference
5135 ** to a column in the new.* or old.* pseudo-tables available to
5136 ** trigger programs. In this case Expr.iTable is set to 1 for the
5137 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
5138 ** is set to the column of the pseudo-table to read, or to -1 to
5139 ** read the rowid field.
5141 ** The expression is implemented using an OP_Param opcode. The p1
5142 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
5143 ** to reference another column of the old.* pseudo-table, where
5144 ** i is the index of the column. For a new.rowid reference, p1 is
5145 ** set to (n+1), where n is the number of columns in each pseudo-table.
5146 ** For a reference to any other column in the new.* pseudo-table, p1
5147 ** is set to (n+2+i), where n and i are as defined previously. For
5148 ** example, if the table on which triggers are being fired is
5149 ** declared as:
5151 ** CREATE TABLE t1(a, b);
5153 ** Then p1 is interpreted as follows:
5155 ** p1==0 -> old.rowid p1==3 -> new.rowid
5156 ** p1==1 -> old.a p1==4 -> new.a
5157 ** p1==2 -> old.b p1==5 -> new.b
5159 Table *pTab;
5160 int iCol;
5161 int p1;
5163 assert( ExprUseYTab(pExpr) );
5164 pTab = pExpr->y.pTab;
5165 iCol = pExpr->iColumn;
5166 p1 = pExpr->iTable * (pTab->nCol+1) + 1
5167 + sqlite3TableColumnToStorage(pTab, iCol);
5169 assert( pExpr->iTable==0 || pExpr->iTable==1 );
5170 assert( iCol>=-1 && iCol<pTab->nCol );
5171 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
5172 assert( p1>=0 && p1<(pTab->nCol*2+2) );
5174 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
5175 VdbeComment((v, "r[%d]=%s.%s", target,
5176 (pExpr->iTable ? "new" : "old"),
5177 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
5180 #ifndef SQLITE_OMIT_FLOATING_POINT
5181 /* If the column has REAL affinity, it may currently be stored as an
5182 ** integer. Use OP_RealAffinity to make sure it is really real.
5184 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
5185 ** floating point when extracting it from the record. */
5186 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
5187 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
5189 #endif
5190 break;
5193 case TK_VECTOR: {
5194 sqlite3ErrorMsg(pParse, "row value misused");
5195 break;
5198 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
5199 ** that derive from the right-hand table of a LEFT JOIN. The
5200 ** Expr.iTable value is the table number for the right-hand table.
5201 ** The expression is only evaluated if that table is not currently
5202 ** on a LEFT JOIN NULL row.
5204 case TK_IF_NULL_ROW: {
5205 int addrINR;
5206 u8 okConstFactor = pParse->okConstFactor;
5207 AggInfo *pAggInfo = pExpr->pAggInfo;
5208 if( pAggInfo ){
5209 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
5210 if( !pAggInfo->directMode ){
5211 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg);
5212 break;
5214 if( pExpr->pAggInfo->useSortingIdx ){
5215 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
5216 pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
5217 target);
5218 inReg = target;
5219 break;
5222 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target);
5223 /* The OP_IfNullRow opcode above can overwrite the result register with
5224 ** NULL. So we have to ensure that the result register is not a value
5225 ** that is suppose to be a constant. Two defenses are needed:
5226 ** (1) Temporarily disable factoring of constant expressions
5227 ** (2) Make sure the computed value really is stored in register
5228 ** "target" and not someplace else.
5230 pParse->okConstFactor = 0; /* note (1) above */
5231 sqlite3ExprCode(pParse, pExpr->pLeft, target);
5232 assert( target==inReg );
5233 pParse->okConstFactor = okConstFactor;
5234 sqlite3VdbeJumpHere(v, addrINR);
5235 break;
5239 ** Form A:
5240 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5242 ** Form B:
5243 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5245 ** Form A is can be transformed into the equivalent form B as follows:
5246 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
5247 ** WHEN x=eN THEN rN ELSE y END
5249 ** X (if it exists) is in pExpr->pLeft.
5250 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
5251 ** odd. The Y is also optional. If the number of elements in x.pList
5252 ** is even, then Y is omitted and the "otherwise" result is NULL.
5253 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
5255 ** The result of the expression is the Ri for the first matching Ei,
5256 ** or if there is no matching Ei, the ELSE term Y, or if there is
5257 ** no ELSE term, NULL.
5259 case TK_CASE: {
5260 int endLabel; /* GOTO label for end of CASE stmt */
5261 int nextCase; /* GOTO label for next WHEN clause */
5262 int nExpr; /* 2x number of WHEN terms */
5263 int i; /* Loop counter */
5264 ExprList *pEList; /* List of WHEN terms */
5265 struct ExprList_item *aListelem; /* Array of WHEN terms */
5266 Expr opCompare; /* The X==Ei expression */
5267 Expr *pX; /* The X expression */
5268 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
5269 Expr *pDel = 0;
5270 sqlite3 *db = pParse->db;
5272 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
5273 assert(pExpr->x.pList->nExpr > 0);
5274 pEList = pExpr->x.pList;
5275 aListelem = pEList->a;
5276 nExpr = pEList->nExpr;
5277 endLabel = sqlite3VdbeMakeLabel(pParse);
5278 if( (pX = pExpr->pLeft)!=0 ){
5279 pDel = sqlite3ExprDup(db, pX, 0);
5280 if( db->mallocFailed ){
5281 sqlite3ExprDelete(db, pDel);
5282 break;
5284 testcase( pX->op==TK_COLUMN );
5285 sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5286 testcase( regFree1==0 );
5287 memset(&opCompare, 0, sizeof(opCompare));
5288 opCompare.op = TK_EQ;
5289 opCompare.pLeft = pDel;
5290 pTest = &opCompare;
5291 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
5292 ** The value in regFree1 might get SCopy-ed into the file result.
5293 ** So make sure that the regFree1 register is not reused for other
5294 ** purposes and possibly overwritten. */
5295 regFree1 = 0;
5297 for(i=0; i<nExpr-1; i=i+2){
5298 if( pX ){
5299 assert( pTest!=0 );
5300 opCompare.pRight = aListelem[i].pExpr;
5301 }else{
5302 pTest = aListelem[i].pExpr;
5304 nextCase = sqlite3VdbeMakeLabel(pParse);
5305 testcase( pTest->op==TK_COLUMN );
5306 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
5307 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
5308 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
5309 sqlite3VdbeGoto(v, endLabel);
5310 sqlite3VdbeResolveLabel(v, nextCase);
5312 if( (nExpr&1)!=0 ){
5313 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
5314 }else{
5315 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
5317 sqlite3ExprDelete(db, pDel);
5318 setDoNotMergeFlagOnCopy(v);
5319 sqlite3VdbeResolveLabel(v, endLabel);
5320 break;
5322 #ifndef SQLITE_OMIT_TRIGGER
5323 case TK_RAISE: {
5324 assert( pExpr->affExpr==OE_Rollback
5325 || pExpr->affExpr==OE_Abort
5326 || pExpr->affExpr==OE_Fail
5327 || pExpr->affExpr==OE_Ignore
5329 if( !pParse->pTriggerTab && !pParse->nested ){
5330 sqlite3ErrorMsg(pParse,
5331 "RAISE() may only be used within a trigger-program");
5332 return 0;
5334 if( pExpr->affExpr==OE_Abort ){
5335 sqlite3MayAbort(pParse);
5337 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5338 if( pExpr->affExpr==OE_Ignore ){
5339 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, OE_Ignore);
5340 VdbeCoverage(v);
5341 }else{
5342 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5343 sqlite3VdbeAddOp3(v, OP_Halt,
5344 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
5345 pExpr->affExpr, r1);
5347 break;
5349 #endif
5351 sqlite3ReleaseTempReg(pParse, regFree1);
5352 sqlite3ReleaseTempReg(pParse, regFree2);
5353 return inReg;
5357 ** Generate code that will evaluate expression pExpr just one time
5358 ** per prepared statement execution.
5360 ** If the expression uses functions (that might throw an exception) then
5361 ** guard them with an OP_Once opcode to ensure that the code is only executed
5362 ** once. If no functions are involved, then factor the code out and put it at
5363 ** the end of the prepared statement in the initialization section.
5365 ** If regDest>0 then the result is always stored in that register and the
5366 ** result is not reusable. If regDest<0 then this routine is free to
5367 ** store the value wherever it wants. The register where the expression
5368 ** is stored is returned. When regDest<0, two identical expressions might
5369 ** code to the same register, if they do not contain function calls and hence
5370 ** are factored out into the initialization section at the end of the
5371 ** prepared statement.
5373 int sqlite3ExprCodeRunJustOnce(
5374 Parse *pParse, /* Parsing context */
5375 Expr *pExpr, /* The expression to code when the VDBE initializes */
5376 int regDest /* Store the value in this register */
5378 ExprList *p;
5379 assert( ConstFactorOk(pParse) );
5380 assert( regDest!=0 );
5381 p = pParse->pConstExpr;
5382 if( regDest<0 && p ){
5383 struct ExprList_item *pItem;
5384 int i;
5385 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
5386 if( pItem->fg.reusable
5387 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
5389 return pItem->u.iConstExprReg;
5393 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5394 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
5395 Vdbe *v = pParse->pVdbe;
5396 int addr;
5397 assert( v );
5398 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
5399 pParse->okConstFactor = 0;
5400 if( !pParse->db->mallocFailed ){
5401 if( regDest<0 ) regDest = ++pParse->nMem;
5402 sqlite3ExprCode(pParse, pExpr, regDest);
5404 pParse->okConstFactor = 1;
5405 sqlite3ExprDelete(pParse->db, pExpr);
5406 sqlite3VdbeJumpHere(v, addr);
5407 }else{
5408 p = sqlite3ExprListAppend(pParse, p, pExpr);
5409 if( p ){
5410 struct ExprList_item *pItem = &p->a[p->nExpr-1];
5411 pItem->fg.reusable = regDest<0;
5412 if( regDest<0 ) regDest = ++pParse->nMem;
5413 pItem->u.iConstExprReg = regDest;
5415 pParse->pConstExpr = p;
5417 return regDest;
5421 ** Generate code to evaluate an expression and store the results
5422 ** into a register. Return the register number where the results
5423 ** are stored.
5425 ** If the register is a temporary register that can be deallocated,
5426 ** then write its number into *pReg. If the result register is not
5427 ** a temporary, then set *pReg to zero.
5429 ** If pExpr is a constant, then this routine might generate this
5430 ** code to fill the register in the initialization section of the
5431 ** VDBE program, in order to factor it out of the evaluation loop.
5433 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
5434 int r2;
5435 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
5436 if( ConstFactorOk(pParse)
5437 && ALWAYS(pExpr!=0)
5438 && pExpr->op!=TK_REGISTER
5439 && sqlite3ExprIsConstantNotJoin(pParse, pExpr)
5441 *pReg = 0;
5442 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
5443 }else{
5444 int r1 = sqlite3GetTempReg(pParse);
5445 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
5446 if( r2==r1 ){
5447 *pReg = r1;
5448 }else{
5449 sqlite3ReleaseTempReg(pParse, r1);
5450 *pReg = 0;
5453 return r2;
5457 ** Generate code that will evaluate expression pExpr and store the
5458 ** results in register target. The results are guaranteed to appear
5459 ** in register target.
5461 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
5462 int inReg;
5464 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
5465 assert( target>0 && target<=pParse->nMem );
5466 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
5467 if( pParse->pVdbe==0 ) return;
5468 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
5469 if( inReg!=target ){
5470 u8 op;
5471 Expr *pX = sqlite3ExprSkipCollateAndLikely(pExpr);
5472 testcase( pX!=pExpr );
5473 if( ALWAYS(pX)
5474 && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER)
5476 op = OP_Copy;
5477 }else{
5478 op = OP_SCopy;
5480 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
5485 ** Make a transient copy of expression pExpr and then code it using
5486 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5487 ** except that the input expression is guaranteed to be unchanged.
5489 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
5490 sqlite3 *db = pParse->db;
5491 pExpr = sqlite3ExprDup(db, pExpr, 0);
5492 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
5493 sqlite3ExprDelete(db, pExpr);
5497 ** Generate code that will evaluate expression pExpr and store the
5498 ** results in register target. The results are guaranteed to appear
5499 ** in register target. If the expression is constant, then this routine
5500 ** might choose to code the expression at initialization time.
5502 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
5503 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pParse,pExpr) ){
5504 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
5505 }else{
5506 sqlite3ExprCodeCopy(pParse, pExpr, target);
5511 ** Generate code that pushes the value of every element of the given
5512 ** expression list into a sequence of registers beginning at target.
5514 ** Return the number of elements evaluated. The number returned will
5515 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5516 ** is defined.
5518 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5519 ** filled using OP_SCopy. OP_Copy must be used instead.
5521 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5522 ** factored out into initialization code.
5524 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5525 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5526 ** in registers at srcReg, and so the value can be copied from there.
5527 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5528 ** are simply omitted rather than being copied from srcReg.
5530 int sqlite3ExprCodeExprList(
5531 Parse *pParse, /* Parsing context */
5532 ExprList *pList, /* The expression list to be coded */
5533 int target, /* Where to write results */
5534 int srcReg, /* Source registers if SQLITE_ECEL_REF */
5535 u8 flags /* SQLITE_ECEL_* flags */
5537 struct ExprList_item *pItem;
5538 int i, j, n;
5539 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
5540 Vdbe *v = pParse->pVdbe;
5541 assert( pList!=0 );
5542 assert( target>0 );
5543 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
5544 n = pList->nExpr;
5545 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
5546 for(pItem=pList->a, i=0; i<n; i++, pItem++){
5547 Expr *pExpr = pItem->pExpr;
5548 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5549 if( pItem->fg.bSorterRef ){
5550 i--;
5551 n--;
5552 }else
5553 #endif
5554 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
5555 if( flags & SQLITE_ECEL_OMITREF ){
5556 i--;
5557 n--;
5558 }else{
5559 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
5561 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
5562 && sqlite3ExprIsConstantNotJoin(pParse,pExpr)
5564 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
5565 }else{
5566 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
5567 if( inReg!=target+i ){
5568 VdbeOp *pOp;
5569 if( copyOp==OP_Copy
5570 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
5571 && pOp->p1+pOp->p3+1==inReg
5572 && pOp->p2+pOp->p3+1==target+i
5573 && pOp->p5==0 /* The do-not-merge flag must be clear */
5575 pOp->p3++;
5576 }else{
5577 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
5582 return n;
5586 ** Generate code for a BETWEEN operator.
5588 ** x BETWEEN y AND z
5590 ** The above is equivalent to
5592 ** x>=y AND x<=z
5594 ** Code it as such, taking care to do the common subexpression
5595 ** elimination of x.
5597 ** The xJumpIf parameter determines details:
5599 ** NULL: Store the boolean result in reg[dest]
5600 ** sqlite3ExprIfTrue: Jump to dest if true
5601 ** sqlite3ExprIfFalse: Jump to dest if false
5603 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5605 static void exprCodeBetween(
5606 Parse *pParse, /* Parsing and code generating context */
5607 Expr *pExpr, /* The BETWEEN expression */
5608 int dest, /* Jump destination or storage location */
5609 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
5610 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
5612 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
5613 Expr compLeft; /* The x>=y term */
5614 Expr compRight; /* The x<=z term */
5615 int regFree1 = 0; /* Temporary use register */
5616 Expr *pDel = 0;
5617 sqlite3 *db = pParse->db;
5619 memset(&compLeft, 0, sizeof(Expr));
5620 memset(&compRight, 0, sizeof(Expr));
5621 memset(&exprAnd, 0, sizeof(Expr));
5623 assert( ExprUseXList(pExpr) );
5624 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
5625 if( db->mallocFailed==0 ){
5626 exprAnd.op = TK_AND;
5627 exprAnd.pLeft = &compLeft;
5628 exprAnd.pRight = &compRight;
5629 compLeft.op = TK_GE;
5630 compLeft.pLeft = pDel;
5631 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
5632 compRight.op = TK_LE;
5633 compRight.pLeft = pDel;
5634 compRight.pRight = pExpr->x.pList->a[1].pExpr;
5635 sqlite3ExprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5636 if( xJump ){
5637 xJump(pParse, &exprAnd, dest, jumpIfNull);
5638 }else{
5639 /* Mark the expression is being from the ON or USING clause of a join
5640 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5641 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5642 ** for clarity, but we are out of bits in the Expr.flags field so we
5643 ** have to reuse the EP_OuterON bit. Bummer. */
5644 pDel->flags |= EP_OuterON;
5645 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
5647 sqlite3ReleaseTempReg(pParse, regFree1);
5649 sqlite3ExprDelete(db, pDel);
5651 /* Ensure adequate test coverage */
5652 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
5653 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
5654 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
5655 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
5656 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
5657 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
5658 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
5659 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
5660 testcase( xJump==0 );
5664 ** Generate code for a boolean expression such that a jump is made
5665 ** to the label "dest" if the expression is true but execution
5666 ** continues straight thru if the expression is false.
5668 ** If the expression evaluates to NULL (neither true nor false), then
5669 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5671 ** This code depends on the fact that certain token values (ex: TK_EQ)
5672 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5673 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5674 ** the make process cause these values to align. Assert()s in the code
5675 ** below verify that the numbers are aligned correctly.
5677 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5678 Vdbe *v = pParse->pVdbe;
5679 int op = 0;
5680 int regFree1 = 0;
5681 int regFree2 = 0;
5682 int r1, r2;
5684 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5685 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5686 if( NEVER(pExpr==0) ) return; /* No way this can happen */
5687 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
5688 op = pExpr->op;
5689 switch( op ){
5690 case TK_AND:
5691 case TK_OR: {
5692 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5693 if( pAlt!=pExpr ){
5694 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
5695 }else if( op==TK_AND ){
5696 int d2 = sqlite3VdbeMakeLabel(pParse);
5697 testcase( jumpIfNull==0 );
5698 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
5699 jumpIfNull^SQLITE_JUMPIFNULL);
5700 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5701 sqlite3VdbeResolveLabel(v, d2);
5702 }else{
5703 testcase( jumpIfNull==0 );
5704 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5705 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5707 break;
5709 case TK_NOT: {
5710 testcase( jumpIfNull==0 );
5711 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5712 break;
5714 case TK_TRUTH: {
5715 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5716 int isTrue; /* IS TRUE or IS NOT TRUE */
5717 testcase( jumpIfNull==0 );
5718 isNot = pExpr->op2==TK_ISNOT;
5719 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5720 testcase( isTrue && isNot );
5721 testcase( !isTrue && isNot );
5722 if( isTrue ^ isNot ){
5723 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5724 isNot ? SQLITE_JUMPIFNULL : 0);
5725 }else{
5726 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5727 isNot ? SQLITE_JUMPIFNULL : 0);
5729 break;
5731 case TK_IS:
5732 case TK_ISNOT:
5733 testcase( op==TK_IS );
5734 testcase( op==TK_ISNOT );
5735 op = (op==TK_IS) ? TK_EQ : TK_NE;
5736 jumpIfNull = SQLITE_NULLEQ;
5737 /* no break */ deliberate_fall_through
5738 case TK_LT:
5739 case TK_LE:
5740 case TK_GT:
5741 case TK_GE:
5742 case TK_NE:
5743 case TK_EQ: {
5744 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5745 testcase( jumpIfNull==0 );
5746 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5747 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5748 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5749 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
5750 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5751 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5752 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5753 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5754 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5755 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5756 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5757 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5758 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5759 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5760 testcase( regFree1==0 );
5761 testcase( regFree2==0 );
5762 break;
5764 case TK_ISNULL:
5765 case TK_NOTNULL: {
5766 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
5767 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
5768 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5769 sqlite3VdbeTypeofColumn(v, r1);
5770 sqlite3VdbeAddOp2(v, op, r1, dest);
5771 VdbeCoverageIf(v, op==TK_ISNULL);
5772 VdbeCoverageIf(v, op==TK_NOTNULL);
5773 testcase( regFree1==0 );
5774 break;
5776 case TK_BETWEEN: {
5777 testcase( jumpIfNull==0 );
5778 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
5779 break;
5781 #ifndef SQLITE_OMIT_SUBQUERY
5782 case TK_IN: {
5783 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5784 int destIfNull = jumpIfNull ? dest : destIfFalse;
5785 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5786 sqlite3VdbeGoto(v, dest);
5787 sqlite3VdbeResolveLabel(v, destIfFalse);
5788 break;
5790 #endif
5791 default: {
5792 default_expr:
5793 if( ExprAlwaysTrue(pExpr) ){
5794 sqlite3VdbeGoto(v, dest);
5795 }else if( ExprAlwaysFalse(pExpr) ){
5796 /* No-op */
5797 }else{
5798 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5799 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
5800 VdbeCoverage(v);
5801 testcase( regFree1==0 );
5802 testcase( jumpIfNull==0 );
5804 break;
5807 sqlite3ReleaseTempReg(pParse, regFree1);
5808 sqlite3ReleaseTempReg(pParse, regFree2);
5812 ** Generate code for a boolean expression such that a jump is made
5813 ** to the label "dest" if the expression is false but execution
5814 ** continues straight thru if the expression is true.
5816 ** If the expression evaluates to NULL (neither true nor false) then
5817 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5818 ** is 0.
5820 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5821 Vdbe *v = pParse->pVdbe;
5822 int op = 0;
5823 int regFree1 = 0;
5824 int regFree2 = 0;
5825 int r1, r2;
5827 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5828 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5829 if( pExpr==0 ) return;
5830 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
5832 /* The value of pExpr->op and op are related as follows:
5834 ** pExpr->op op
5835 ** --------- ----------
5836 ** TK_ISNULL OP_NotNull
5837 ** TK_NOTNULL OP_IsNull
5838 ** TK_NE OP_Eq
5839 ** TK_EQ OP_Ne
5840 ** TK_GT OP_Le
5841 ** TK_LE OP_Gt
5842 ** TK_GE OP_Lt
5843 ** TK_LT OP_Ge
5845 ** For other values of pExpr->op, op is undefined and unused.
5846 ** The value of TK_ and OP_ constants are arranged such that we
5847 ** can compute the mapping above using the following expression.
5848 ** Assert()s verify that the computation is correct.
5850 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
5852 /* Verify correct alignment of TK_ and OP_ constants
5854 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
5855 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
5856 assert( pExpr->op!=TK_NE || op==OP_Eq );
5857 assert( pExpr->op!=TK_EQ || op==OP_Ne );
5858 assert( pExpr->op!=TK_LT || op==OP_Ge );
5859 assert( pExpr->op!=TK_LE || op==OP_Gt );
5860 assert( pExpr->op!=TK_GT || op==OP_Le );
5861 assert( pExpr->op!=TK_GE || op==OP_Lt );
5863 switch( pExpr->op ){
5864 case TK_AND:
5865 case TK_OR: {
5866 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5867 if( pAlt!=pExpr ){
5868 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
5869 }else if( pExpr->op==TK_AND ){
5870 testcase( jumpIfNull==0 );
5871 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5872 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5873 }else{
5874 int d2 = sqlite3VdbeMakeLabel(pParse);
5875 testcase( jumpIfNull==0 );
5876 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
5877 jumpIfNull^SQLITE_JUMPIFNULL);
5878 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5879 sqlite3VdbeResolveLabel(v, d2);
5881 break;
5883 case TK_NOT: {
5884 testcase( jumpIfNull==0 );
5885 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5886 break;
5888 case TK_TRUTH: {
5889 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5890 int isTrue; /* IS TRUE or IS NOT TRUE */
5891 testcase( jumpIfNull==0 );
5892 isNot = pExpr->op2==TK_ISNOT;
5893 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5894 testcase( isTrue && isNot );
5895 testcase( !isTrue && isNot );
5896 if( isTrue ^ isNot ){
5897 /* IS TRUE and IS NOT FALSE */
5898 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5899 isNot ? 0 : SQLITE_JUMPIFNULL);
5901 }else{
5902 /* IS FALSE and IS NOT TRUE */
5903 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5904 isNot ? 0 : SQLITE_JUMPIFNULL);
5906 break;
5908 case TK_IS:
5909 case TK_ISNOT:
5910 testcase( pExpr->op==TK_IS );
5911 testcase( pExpr->op==TK_ISNOT );
5912 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
5913 jumpIfNull = SQLITE_NULLEQ;
5914 /* no break */ deliberate_fall_through
5915 case TK_LT:
5916 case TK_LE:
5917 case TK_GT:
5918 case TK_GE:
5919 case TK_NE:
5920 case TK_EQ: {
5921 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5922 testcase( jumpIfNull==0 );
5923 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5924 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5925 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5926 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
5927 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5928 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5929 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5930 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5931 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5932 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5933 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5934 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5935 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5936 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5937 testcase( regFree1==0 );
5938 testcase( regFree2==0 );
5939 break;
5941 case TK_ISNULL:
5942 case TK_NOTNULL: {
5943 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5944 sqlite3VdbeTypeofColumn(v, r1);
5945 sqlite3VdbeAddOp2(v, op, r1, dest);
5946 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
5947 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
5948 testcase( regFree1==0 );
5949 break;
5951 case TK_BETWEEN: {
5952 testcase( jumpIfNull==0 );
5953 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
5954 break;
5956 #ifndef SQLITE_OMIT_SUBQUERY
5957 case TK_IN: {
5958 if( jumpIfNull ){
5959 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
5960 }else{
5961 int destIfNull = sqlite3VdbeMakeLabel(pParse);
5962 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
5963 sqlite3VdbeResolveLabel(v, destIfNull);
5965 break;
5967 #endif
5968 default: {
5969 default_expr:
5970 if( ExprAlwaysFalse(pExpr) ){
5971 sqlite3VdbeGoto(v, dest);
5972 }else if( ExprAlwaysTrue(pExpr) ){
5973 /* no-op */
5974 }else{
5975 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5976 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
5977 VdbeCoverage(v);
5978 testcase( regFree1==0 );
5979 testcase( jumpIfNull==0 );
5981 break;
5984 sqlite3ReleaseTempReg(pParse, regFree1);
5985 sqlite3ReleaseTempReg(pParse, regFree2);
5989 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5990 ** code generation, and that copy is deleted after code generation. This
5991 ** ensures that the original pExpr is unchanged.
5993 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
5994 sqlite3 *db = pParse->db;
5995 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
5996 if( db->mallocFailed==0 ){
5997 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
5999 sqlite3ExprDelete(db, pCopy);
6003 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
6004 ** type of expression.
6006 ** If pExpr is a simple SQL value - an integer, real, string, blob
6007 ** or NULL value - then the VDBE currently being prepared is configured
6008 ** to re-prepare each time a new value is bound to variable pVar.
6010 ** Additionally, if pExpr is a simple SQL value and the value is the
6011 ** same as that currently bound to variable pVar, non-zero is returned.
6012 ** Otherwise, if the values are not the same or if pExpr is not a simple
6013 ** SQL value, zero is returned.
6015 static int exprCompareVariable(
6016 const Parse *pParse,
6017 const Expr *pVar,
6018 const Expr *pExpr
6020 int res = 0;
6021 int iVar;
6022 sqlite3_value *pL, *pR = 0;
6024 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
6025 if( pR ){
6026 iVar = pVar->iColumn;
6027 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
6028 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
6029 if( pL ){
6030 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
6031 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
6033 res = 0==sqlite3MemCompare(pL, pR, 0);
6035 sqlite3ValueFree(pR);
6036 sqlite3ValueFree(pL);
6039 return res;
6043 ** Do a deep comparison of two expression trees. Return 0 if the two
6044 ** expressions are completely identical. Return 1 if they differ only
6045 ** by a COLLATE operator at the top level. Return 2 if there are differences
6046 ** other than the top-level COLLATE operator.
6048 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6049 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6051 ** The pA side might be using TK_REGISTER. If that is the case and pB is
6052 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
6054 ** Sometimes this routine will return 2 even if the two expressions
6055 ** really are equivalent. If we cannot prove that the expressions are
6056 ** identical, we return 2 just to be safe. So if this routine
6057 ** returns 2, then you do not really know for certain if the two
6058 ** expressions are the same. But if you get a 0 or 1 return, then you
6059 ** can be sure the expressions are the same. In the places where
6060 ** this routine is used, it does not hurt to get an extra 2 - that
6061 ** just might result in some slightly slower code. But returning
6062 ** an incorrect 0 or 1 could lead to a malfunction.
6064 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
6065 ** pParse->pReprepare can be matched against literals in pB. The
6066 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
6067 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
6068 ** Argument pParse should normally be NULL. If it is not NULL and pA or
6069 ** pB causes a return value of 2.
6071 int sqlite3ExprCompare(
6072 const Parse *pParse,
6073 const Expr *pA,
6074 const Expr *pB,
6075 int iTab
6077 u32 combinedFlags;
6078 if( pA==0 || pB==0 ){
6079 return pB==pA ? 0 : 2;
6081 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
6082 return 0;
6084 combinedFlags = pA->flags | pB->flags;
6085 if( combinedFlags & EP_IntValue ){
6086 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
6087 return 0;
6089 return 2;
6091 if( pA->op!=pB->op || pA->op==TK_RAISE ){
6092 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
6093 return 1;
6095 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
6096 return 1;
6098 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
6099 && pB->iTable<0 && pA->iTable==iTab
6101 /* fall through */
6102 }else{
6103 return 2;
6106 assert( !ExprHasProperty(pA, EP_IntValue) );
6107 assert( !ExprHasProperty(pB, EP_IntValue) );
6108 if( pA->u.zToken ){
6109 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
6110 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
6111 #ifndef SQLITE_OMIT_WINDOWFUNC
6112 assert( pA->op==pB->op );
6113 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
6114 return 2;
6116 if( ExprHasProperty(pA,EP_WinFunc) ){
6117 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
6118 return 2;
6121 #endif
6122 }else if( pA->op==TK_NULL ){
6123 return 0;
6124 }else if( pA->op==TK_COLLATE ){
6125 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
6126 }else
6127 if( pB->u.zToken!=0
6128 && pA->op!=TK_COLUMN
6129 && pA->op!=TK_AGG_COLUMN
6130 && strcmp(pA->u.zToken,pB->u.zToken)!=0
6132 return 2;
6135 if( (pA->flags & (EP_Distinct|EP_Commuted))
6136 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
6137 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
6138 if( combinedFlags & EP_xIsSelect ) return 2;
6139 if( (combinedFlags & EP_FixedCol)==0
6140 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
6141 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
6142 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
6143 if( pA->op!=TK_STRING
6144 && pA->op!=TK_TRUEFALSE
6145 && ALWAYS((combinedFlags & EP_Reduced)==0)
6147 if( pA->iColumn!=pB->iColumn ) return 2;
6148 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
6149 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
6150 return 2;
6154 return 0;
6158 ** Compare two ExprList objects. Return 0 if they are identical, 1
6159 ** if they are certainly different, or 2 if it is not possible to
6160 ** determine if they are identical or not.
6162 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6163 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6165 ** This routine might return non-zero for equivalent ExprLists. The
6166 ** only consequence will be disabled optimizations. But this routine
6167 ** must never return 0 if the two ExprList objects are different, or
6168 ** a malfunction will result.
6170 ** Two NULL pointers are considered to be the same. But a NULL pointer
6171 ** always differs from a non-NULL pointer.
6173 int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){
6174 int i;
6175 if( pA==0 && pB==0 ) return 0;
6176 if( pA==0 || pB==0 ) return 1;
6177 if( pA->nExpr!=pB->nExpr ) return 1;
6178 for(i=0; i<pA->nExpr; i++){
6179 int res;
6180 Expr *pExprA = pA->a[i].pExpr;
6181 Expr *pExprB = pB->a[i].pExpr;
6182 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
6183 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
6185 return 0;
6189 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
6190 ** are ignored.
6192 int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
6193 return sqlite3ExprCompare(0,
6194 sqlite3ExprSkipCollate(pA),
6195 sqlite3ExprSkipCollate(pB),
6196 iTab);
6200 ** Return non-zero if Expr p can only be true if pNN is not NULL.
6202 ** Or if seenNot is true, return non-zero if Expr p can only be
6203 ** non-NULL if pNN is not NULL
6205 static int exprImpliesNotNull(
6206 const Parse *pParse,/* Parsing context */
6207 const Expr *p, /* The expression to be checked */
6208 const Expr *pNN, /* The expression that is NOT NULL */
6209 int iTab, /* Table being evaluated */
6210 int seenNot /* Return true only if p can be any non-NULL value */
6212 assert( p );
6213 assert( pNN );
6214 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
6215 return pNN->op!=TK_NULL;
6217 switch( p->op ){
6218 case TK_IN: {
6219 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
6220 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
6221 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6223 case TK_BETWEEN: {
6224 ExprList *pList;
6225 assert( ExprUseXList(p) );
6226 pList = p->x.pList;
6227 assert( pList!=0 );
6228 assert( pList->nExpr==2 );
6229 if( seenNot ) return 0;
6230 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
6231 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
6233 return 1;
6235 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6237 case TK_EQ:
6238 case TK_NE:
6239 case TK_LT:
6240 case TK_LE:
6241 case TK_GT:
6242 case TK_GE:
6243 case TK_PLUS:
6244 case TK_MINUS:
6245 case TK_BITOR:
6246 case TK_LSHIFT:
6247 case TK_RSHIFT:
6248 case TK_CONCAT:
6249 seenNot = 1;
6250 /* no break */ deliberate_fall_through
6251 case TK_STAR:
6252 case TK_REM:
6253 case TK_BITAND:
6254 case TK_SLASH: {
6255 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
6256 /* no break */ deliberate_fall_through
6258 case TK_SPAN:
6259 case TK_COLLATE:
6260 case TK_UPLUS:
6261 case TK_UMINUS: {
6262 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
6264 case TK_TRUTH: {
6265 if( seenNot ) return 0;
6266 if( p->op2!=TK_IS ) return 0;
6267 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6269 case TK_BITNOT:
6270 case TK_NOT: {
6271 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6274 return 0;
6278 ** Return true if we can prove the pE2 will always be true if pE1 is
6279 ** true. Return false if we cannot complete the proof or if pE2 might
6280 ** be false. Examples:
6282 ** pE1: x==5 pE2: x==5 Result: true
6283 ** pE1: x>0 pE2: x==5 Result: false
6284 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
6285 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
6286 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
6287 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
6288 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false
6290 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
6291 ** Expr.iTable<0 then assume a table number given by iTab.
6293 ** If pParse is not NULL, then the values of bound variables in pE1 are
6294 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
6295 ** modified to record which bound variables are referenced. If pParse
6296 ** is NULL, then false will be returned if pE1 contains any bound variables.
6298 ** When in doubt, return false. Returning true might give a performance
6299 ** improvement. Returning false might cause a performance reduction, but
6300 ** it will always give the correct answer and is hence always safe.
6302 int sqlite3ExprImpliesExpr(
6303 const Parse *pParse,
6304 const Expr *pE1,
6305 const Expr *pE2,
6306 int iTab
6308 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
6309 return 1;
6311 if( pE2->op==TK_OR
6312 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
6313 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
6315 return 1;
6317 if( pE2->op==TK_NOTNULL
6318 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
6320 return 1;
6322 return 0;
6325 /* This is a helper function to impliesNotNullRow(). In this routine,
6326 ** set pWalker->eCode to one only if *both* of the input expressions
6327 ** separately have the implies-not-null-row property.
6329 static void bothImplyNotNullRow(Walker *pWalker, Expr *pE1, Expr *pE2){
6330 if( pWalker->eCode==0 ){
6331 sqlite3WalkExpr(pWalker, pE1);
6332 if( pWalker->eCode ){
6333 pWalker->eCode = 0;
6334 sqlite3WalkExpr(pWalker, pE2);
6340 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
6341 ** If the expression node requires that the table at pWalker->iCur
6342 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
6344 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
6345 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when
6346 ** evaluating terms in the ON clause of an inner join.
6348 ** This routine controls an optimization. False positives (setting
6349 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6350 ** (never setting pWalker->eCode) is a harmless missed optimization.
6352 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
6353 testcase( pExpr->op==TK_AGG_COLUMN );
6354 testcase( pExpr->op==TK_AGG_FUNCTION );
6355 if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune;
6356 if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){
6357 /* If iCur is used in an inner-join ON clause to the left of a
6358 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
6359 ** But it is difficult to check for that condition precisely.
6360 ** To keep things simple, any use of iCur from any inner-join is
6361 ** ignored while attempting to simplify a RIGHT JOIN. */
6362 return WRC_Prune;
6364 switch( pExpr->op ){
6365 case TK_ISNOT:
6366 case TK_ISNULL:
6367 case TK_NOTNULL:
6368 case TK_IS:
6369 case TK_VECTOR:
6370 case TK_FUNCTION:
6371 case TK_TRUTH:
6372 case TK_CASE:
6373 testcase( pExpr->op==TK_ISNOT );
6374 testcase( pExpr->op==TK_ISNULL );
6375 testcase( pExpr->op==TK_NOTNULL );
6376 testcase( pExpr->op==TK_IS );
6377 testcase( pExpr->op==TK_VECTOR );
6378 testcase( pExpr->op==TK_FUNCTION );
6379 testcase( pExpr->op==TK_TRUTH );
6380 testcase( pExpr->op==TK_CASE );
6381 return WRC_Prune;
6383 case TK_COLUMN:
6384 if( pWalker->u.iCur==pExpr->iTable ){
6385 pWalker->eCode = 1;
6386 return WRC_Abort;
6388 return WRC_Prune;
6390 case TK_OR:
6391 case TK_AND:
6392 /* Both sides of an AND or OR must separately imply non-null-row.
6393 ** Consider these cases:
6394 ** 1. NOT (x AND y)
6395 ** 2. x OR y
6396 ** If only one of x or y is non-null-row, then the overall expression
6397 ** can be true if the other arm is false (case 1) or true (case 2).
6399 testcase( pExpr->op==TK_OR );
6400 testcase( pExpr->op==TK_AND );
6401 bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight);
6402 return WRC_Prune;
6404 case TK_IN:
6405 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
6406 ** both of which can be true. But apart from these cases, if
6407 ** the left-hand side of the IN is NULL then the IN itself will be
6408 ** NULL. */
6409 if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){
6410 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6412 return WRC_Prune;
6414 case TK_BETWEEN:
6415 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
6416 ** both y and z must be non-null row */
6417 assert( ExprUseXList(pExpr) );
6418 assert( pExpr->x.pList->nExpr==2 );
6419 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6420 bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr,
6421 pExpr->x.pList->a[1].pExpr);
6422 return WRC_Prune;
6424 /* Virtual tables are allowed to use constraints like x=NULL. So
6425 ** a term of the form x=y does not prove that y is not null if x
6426 ** is the column of a virtual table */
6427 case TK_EQ:
6428 case TK_NE:
6429 case TK_LT:
6430 case TK_LE:
6431 case TK_GT:
6432 case TK_GE: {
6433 Expr *pLeft = pExpr->pLeft;
6434 Expr *pRight = pExpr->pRight;
6435 testcase( pExpr->op==TK_EQ );
6436 testcase( pExpr->op==TK_NE );
6437 testcase( pExpr->op==TK_LT );
6438 testcase( pExpr->op==TK_LE );
6439 testcase( pExpr->op==TK_GT );
6440 testcase( pExpr->op==TK_GE );
6441 /* The y.pTab=0 assignment in wherecode.c always happens after the
6442 ** impliesNotNullRow() test */
6443 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
6444 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
6445 if( (pLeft->op==TK_COLUMN
6446 && ALWAYS(pLeft->y.pTab!=0)
6447 && IsVirtual(pLeft->y.pTab))
6448 || (pRight->op==TK_COLUMN
6449 && ALWAYS(pRight->y.pTab!=0)
6450 && IsVirtual(pRight->y.pTab))
6452 return WRC_Prune;
6454 /* no break */ deliberate_fall_through
6456 default:
6457 return WRC_Continue;
6462 ** Return true (non-zero) if expression p can only be true if at least
6463 ** one column of table iTab is non-null. In other words, return true
6464 ** if expression p will always be NULL or false if every column of iTab
6465 ** is NULL.
6467 ** False negatives are acceptable. In other words, it is ok to return
6468 ** zero even if expression p will never be true of every column of iTab
6469 ** is NULL. A false negative is merely a missed optimization opportunity.
6471 ** False positives are not allowed, however. A false positive may result
6472 ** in an incorrect answer.
6474 ** Terms of p that are marked with EP_OuterON (and hence that come from
6475 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6477 ** This routine is used to check if a LEFT JOIN can be converted into
6478 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6479 ** clause requires that some column of the right table of the LEFT JOIN
6480 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6481 ** ordinary join.
6483 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab, int isRJ){
6484 Walker w;
6485 p = sqlite3ExprSkipCollateAndLikely(p);
6486 if( p==0 ) return 0;
6487 if( p->op==TK_NOTNULL ){
6488 p = p->pLeft;
6489 }else{
6490 while( p->op==TK_AND ){
6491 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1;
6492 p = p->pRight;
6495 w.xExprCallback = impliesNotNullRow;
6496 w.xSelectCallback = 0;
6497 w.xSelectCallback2 = 0;
6498 w.eCode = 0;
6499 w.mWFlags = isRJ!=0;
6500 w.u.iCur = iTab;
6501 sqlite3WalkExpr(&w, p);
6502 return w.eCode;
6506 ** An instance of the following structure is used by the tree walker
6507 ** to determine if an expression can be evaluated by reference to the
6508 ** index only, without having to do a search for the corresponding
6509 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6510 ** is the cursor for the table.
6512 struct IdxCover {
6513 Index *pIdx; /* The index to be tested for coverage */
6514 int iCur; /* Cursor number for the table corresponding to the index */
6518 ** Check to see if there are references to columns in table
6519 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6520 ** pWalker->u.pIdxCover->pIdx.
6522 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
6523 if( pExpr->op==TK_COLUMN
6524 && pExpr->iTable==pWalker->u.pIdxCover->iCur
6525 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
6527 pWalker->eCode = 1;
6528 return WRC_Abort;
6530 return WRC_Continue;
6534 ** Determine if an index pIdx on table with cursor iCur contains will
6535 ** the expression pExpr. Return true if the index does cover the
6536 ** expression and false if the pExpr expression references table columns
6537 ** that are not found in the index pIdx.
6539 ** An index covering an expression means that the expression can be
6540 ** evaluated using only the index and without having to lookup the
6541 ** corresponding table entry.
6543 int sqlite3ExprCoveredByIndex(
6544 Expr *pExpr, /* The index to be tested */
6545 int iCur, /* The cursor number for the corresponding table */
6546 Index *pIdx /* The index that might be used for coverage */
6548 Walker w;
6549 struct IdxCover xcov;
6550 memset(&w, 0, sizeof(w));
6551 xcov.iCur = iCur;
6552 xcov.pIdx = pIdx;
6553 w.xExprCallback = exprIdxCover;
6554 w.u.pIdxCover = &xcov;
6555 sqlite3WalkExpr(&w, pExpr);
6556 return !w.eCode;
6560 /* Structure used to pass information throughout the Walker in order to
6561 ** implement sqlite3ReferencesSrcList().
6563 struct RefSrcList {
6564 sqlite3 *db; /* Database connection used for sqlite3DbRealloc() */
6565 SrcList *pRef; /* Looking for references to these tables */
6566 i64 nExclude; /* Number of tables to exclude from the search */
6567 int *aiExclude; /* Cursor IDs for tables to exclude from the search */
6571 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6573 ** When entering a new subquery on the pExpr argument, add all FROM clause
6574 ** entries for that subquery to the exclude list.
6576 ** When leaving the subquery, remove those entries from the exclude list.
6578 static int selectRefEnter(Walker *pWalker, Select *pSelect){
6579 struct RefSrcList *p = pWalker->u.pRefSrcList;
6580 SrcList *pSrc = pSelect->pSrc;
6581 i64 i, j;
6582 int *piNew;
6583 if( pSrc->nSrc==0 ) return WRC_Continue;
6584 j = p->nExclude;
6585 p->nExclude += pSrc->nSrc;
6586 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
6587 if( piNew==0 ){
6588 p->nExclude = 0;
6589 return WRC_Abort;
6590 }else{
6591 p->aiExclude = piNew;
6593 for(i=0; i<pSrc->nSrc; i++, j++){
6594 p->aiExclude[j] = pSrc->a[i].iCursor;
6596 return WRC_Continue;
6598 static void selectRefLeave(Walker *pWalker, Select *pSelect){
6599 struct RefSrcList *p = pWalker->u.pRefSrcList;
6600 SrcList *pSrc = pSelect->pSrc;
6601 if( p->nExclude ){
6602 assert( p->nExclude>=pSrc->nSrc );
6603 p->nExclude -= pSrc->nSrc;
6607 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6609 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6610 ** of the tables shown in RefSrcList.pRef.
6612 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6613 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6615 static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){
6616 if( pExpr->op==TK_COLUMN
6617 || pExpr->op==TK_AGG_COLUMN
6619 int i;
6620 struct RefSrcList *p = pWalker->u.pRefSrcList;
6621 SrcList *pSrc = p->pRef;
6622 int nSrc = pSrc ? pSrc->nSrc : 0;
6623 for(i=0; i<nSrc; i++){
6624 if( pExpr->iTable==pSrc->a[i].iCursor ){
6625 pWalker->eCode |= 1;
6626 return WRC_Continue;
6629 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
6630 if( i>=p->nExclude ){
6631 pWalker->eCode |= 2;
6634 return WRC_Continue;
6638 ** Check to see if pExpr references any tables in pSrcList.
6639 ** Possible return values:
6641 ** 1 pExpr does references a table in pSrcList.
6643 ** 0 pExpr references some table that is not defined in either
6644 ** pSrcList or in subqueries of pExpr itself.
6646 ** -1 pExpr only references no tables at all, or it only
6647 ** references tables defined in subqueries of pExpr itself.
6649 ** As currently used, pExpr is always an aggregate function call. That
6650 ** fact is exploited for efficiency.
6652 int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){
6653 Walker w;
6654 struct RefSrcList x;
6655 assert( pParse->db!=0 );
6656 memset(&w, 0, sizeof(w));
6657 memset(&x, 0, sizeof(x));
6658 w.xExprCallback = exprRefToSrcList;
6659 w.xSelectCallback = selectRefEnter;
6660 w.xSelectCallback2 = selectRefLeave;
6661 w.u.pRefSrcList = &x;
6662 x.db = pParse->db;
6663 x.pRef = pSrcList;
6664 assert( pExpr->op==TK_AGG_FUNCTION );
6665 assert( ExprUseXList(pExpr) );
6666 sqlite3WalkExprList(&w, pExpr->x.pList);
6667 if( pExpr->pLeft ){
6668 assert( pExpr->pLeft->op==TK_ORDER );
6669 assert( ExprUseXList(pExpr->pLeft) );
6670 assert( pExpr->pLeft->x.pList!=0 );
6671 sqlite3WalkExprList(&w, pExpr->pLeft->x.pList);
6673 #ifndef SQLITE_OMIT_WINDOWFUNC
6674 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6675 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
6677 #endif
6678 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
6679 if( w.eCode & 0x01 ){
6680 return 1;
6681 }else if( w.eCode ){
6682 return 0;
6683 }else{
6684 return -1;
6689 ** This is a Walker expression node callback.
6691 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6692 ** object that is referenced does not refer directly to the Expr. If
6693 ** it does, make a copy. This is done because the pExpr argument is
6694 ** subject to change.
6696 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6697 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6699 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
6700 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
6701 && pExpr->pAggInfo!=0
6703 AggInfo *pAggInfo = pExpr->pAggInfo;
6704 int iAgg = pExpr->iAgg;
6705 Parse *pParse = pWalker->pParse;
6706 sqlite3 *db = pParse->db;
6707 assert( iAgg>=0 );
6708 if( pExpr->op!=TK_AGG_FUNCTION ){
6709 if( iAgg<pAggInfo->nColumn
6710 && pAggInfo->aCol[iAgg].pCExpr==pExpr
6712 pExpr = sqlite3ExprDup(db, pExpr, 0);
6713 if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
6714 pAggInfo->aCol[iAgg].pCExpr = pExpr;
6717 }else{
6718 assert( pExpr->op==TK_AGG_FUNCTION );
6719 if( ALWAYS(iAgg<pAggInfo->nFunc)
6720 && pAggInfo->aFunc[iAgg].pFExpr==pExpr
6722 pExpr = sqlite3ExprDup(db, pExpr, 0);
6723 if( pExpr && !sqlite3ExprDeferredDelete(pParse, pExpr) ){
6724 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
6729 return WRC_Continue;
6733 ** Initialize a Walker object so that will persist AggInfo entries referenced
6734 ** by the tree that is walked.
6736 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
6737 memset(pWalker, 0, sizeof(*pWalker));
6738 pWalker->pParse = pParse;
6739 pWalker->xExprCallback = agginfoPersistExprCb;
6740 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
6744 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6745 ** the new element. Return a negative number if malloc fails.
6747 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
6748 int i;
6749 pInfo->aCol = sqlite3ArrayAllocate(
6751 pInfo->aCol,
6752 sizeof(pInfo->aCol[0]),
6753 &pInfo->nColumn,
6756 return i;
6760 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6761 ** the new element. Return a negative number if malloc fails.
6763 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
6764 int i;
6765 pInfo->aFunc = sqlite3ArrayAllocate(
6767 pInfo->aFunc,
6768 sizeof(pInfo->aFunc[0]),
6769 &pInfo->nFunc,
6772 return i;
6776 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6777 ** Return the index in aCol[] of the entry that describes that column.
6779 ** If no prior entry is found, create a new one and return -1. The
6780 ** new column will have an index of pAggInfo->nColumn-1.
6782 static void findOrCreateAggInfoColumn(
6783 Parse *pParse, /* Parsing context */
6784 AggInfo *pAggInfo, /* The AggInfo object to search and/or modify */
6785 Expr *pExpr /* Expr describing the column to find or insert */
6787 struct AggInfo_col *pCol;
6788 int k;
6790 assert( pAggInfo->iFirstReg==0 );
6791 pCol = pAggInfo->aCol;
6792 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
6793 if( pCol->pCExpr==pExpr ) return;
6794 if( pCol->iTable==pExpr->iTable
6795 && pCol->iColumn==pExpr->iColumn
6796 && pExpr->op!=TK_IF_NULL_ROW
6798 goto fix_up_expr;
6801 k = addAggInfoColumn(pParse->db, pAggInfo);
6802 if( k<0 ){
6803 /* OOM on resize */
6804 assert( pParse->db->mallocFailed );
6805 return;
6807 pCol = &pAggInfo->aCol[k];
6808 assert( ExprUseYTab(pExpr) );
6809 pCol->pTab = pExpr->y.pTab;
6810 pCol->iTable = pExpr->iTable;
6811 pCol->iColumn = pExpr->iColumn;
6812 pCol->iSorterColumn = -1;
6813 pCol->pCExpr = pExpr;
6814 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
6815 int j, n;
6816 ExprList *pGB = pAggInfo->pGroupBy;
6817 struct ExprList_item *pTerm = pGB->a;
6818 n = pGB->nExpr;
6819 for(j=0; j<n; j++, pTerm++){
6820 Expr *pE = pTerm->pExpr;
6821 if( pE->op==TK_COLUMN
6822 && pE->iTable==pExpr->iTable
6823 && pE->iColumn==pExpr->iColumn
6825 pCol->iSorterColumn = j;
6826 break;
6830 if( pCol->iSorterColumn<0 ){
6831 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
6833 fix_up_expr:
6834 ExprSetVVAProperty(pExpr, EP_NoReduce);
6835 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo );
6836 pExpr->pAggInfo = pAggInfo;
6837 if( pExpr->op==TK_COLUMN ){
6838 pExpr->op = TK_AGG_COLUMN;
6840 pExpr->iAgg = (i16)k;
6844 ** This is the xExprCallback for a tree walker. It is used to
6845 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6846 ** for additional information.
6848 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
6849 int i;
6850 NameContext *pNC = pWalker->u.pNC;
6851 Parse *pParse = pNC->pParse;
6852 SrcList *pSrcList = pNC->pSrcList;
6853 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
6855 assert( pNC->ncFlags & NC_UAggInfo );
6856 assert( pAggInfo->iFirstReg==0 );
6857 switch( pExpr->op ){
6858 default: {
6859 IndexedExpr *pIEpr;
6860 Expr tmp;
6861 assert( pParse->iSelfTab==0 );
6862 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
6863 if( pParse->pIdxEpr==0 ) break;
6864 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6865 int iDataCur = pIEpr->iDataCur;
6866 if( iDataCur<0 ) continue;
6867 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
6869 if( pIEpr==0 ) break;
6870 if( NEVER(!ExprUseYTab(pExpr)) ) break;
6871 for(i=0; i<pSrcList->nSrc; i++){
6872 if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
6874 if( i>=pSrcList->nSrc ) break;
6875 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
6876 if( pParse->nErr ){ return WRC_Abort; }
6878 /* If we reach this point, it means that expression pExpr can be
6879 ** translated into a reference to an index column as described by
6880 ** pIEpr.
6882 memset(&tmp, 0, sizeof(tmp));
6883 tmp.op = TK_AGG_COLUMN;
6884 tmp.iTable = pIEpr->iIdxCur;
6885 tmp.iColumn = pIEpr->iIdxCol;
6886 findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);
6887 if( pParse->nErr ){ return WRC_Abort; }
6888 assert( pAggInfo->aCol!=0 );
6889 assert( tmp.iAgg<pAggInfo->nColumn );
6890 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
6891 pExpr->pAggInfo = pAggInfo;
6892 pExpr->iAgg = tmp.iAgg;
6893 return WRC_Prune;
6895 case TK_IF_NULL_ROW:
6896 case TK_AGG_COLUMN:
6897 case TK_COLUMN: {
6898 testcase( pExpr->op==TK_AGG_COLUMN );
6899 testcase( pExpr->op==TK_COLUMN );
6900 testcase( pExpr->op==TK_IF_NULL_ROW );
6901 /* Check to see if the column is in one of the tables in the FROM
6902 ** clause of the aggregate query */
6903 if( ALWAYS(pSrcList!=0) ){
6904 SrcItem *pItem = pSrcList->a;
6905 for(i=0; i<pSrcList->nSrc; i++, pItem++){
6906 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6907 if( pExpr->iTable==pItem->iCursor ){
6908 findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
6909 break;
6910 } /* endif pExpr->iTable==pItem->iCursor */
6911 } /* end loop over pSrcList */
6913 return WRC_Continue;
6915 case TK_AGG_FUNCTION: {
6916 if( (pNC->ncFlags & NC_InAggFunc)==0
6917 && pWalker->walkerDepth==pExpr->op2
6918 && pExpr->pAggInfo==0
6920 /* Check to see if pExpr is a duplicate of another aggregate
6921 ** function that is already in the pAggInfo structure
6923 struct AggInfo_func *pItem = pAggInfo->aFunc;
6924 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
6925 if( NEVER(pItem->pFExpr==pExpr) ) break;
6926 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
6927 break;
6930 if( i>=pAggInfo->nFunc ){
6931 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6933 u8 enc = ENC(pParse->db);
6934 i = addAggInfoFunc(pParse->db, pAggInfo);
6935 if( i>=0 ){
6936 int nArg;
6937 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
6938 pItem = &pAggInfo->aFunc[i];
6939 pItem->pFExpr = pExpr;
6940 assert( ExprUseUToken(pExpr) );
6941 nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
6942 pItem->pFunc = sqlite3FindFunction(pParse->db,
6943 pExpr->u.zToken, nArg, enc, 0);
6944 assert( pItem->bOBUnique==0 );
6945 if( pExpr->pLeft
6946 && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0
6948 /* The NEEDCOLL test above causes any ORDER BY clause on
6949 ** aggregate min() or max() to be ignored. */
6950 ExprList *pOBList;
6951 assert( nArg>0 );
6952 assert( pExpr->pLeft->op==TK_ORDER );
6953 assert( ExprUseXList(pExpr->pLeft) );
6954 pItem->iOBTab = pParse->nTab++;
6955 pOBList = pExpr->pLeft->x.pList;
6956 assert( pOBList->nExpr>0 );
6957 assert( pItem->bOBUnique==0 );
6958 if( pOBList->nExpr==1
6959 && nArg==1
6960 && sqlite3ExprCompare(0,pOBList->a[0].pExpr,
6961 pExpr->x.pList->a[0].pExpr,0)==0
6963 pItem->bOBPayload = 0;
6964 pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct);
6965 }else{
6966 pItem->bOBPayload = 1;
6968 pItem->bUseSubtype =
6969 (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0;
6970 }else{
6971 pItem->iOBTab = -1;
6973 if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){
6974 pItem->iDistinct = pParse->nTab++;
6975 }else{
6976 pItem->iDistinct = -1;
6980 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6982 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6983 ExprSetVVAProperty(pExpr, EP_NoReduce);
6984 pExpr->iAgg = (i16)i;
6985 pExpr->pAggInfo = pAggInfo;
6986 return WRC_Prune;
6987 }else{
6988 return WRC_Continue;
6992 return WRC_Continue;
6996 ** Analyze the pExpr expression looking for aggregate functions and
6997 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6998 ** points to. Additional entries are made on the AggInfo object as
6999 ** necessary.
7001 ** This routine should only be called after the expression has been
7002 ** analyzed by sqlite3ResolveExprNames().
7004 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
7005 Walker w;
7006 w.xExprCallback = analyzeAggregate;
7007 w.xSelectCallback = sqlite3WalkerDepthIncrease;
7008 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
7009 w.walkerDepth = 0;
7010 w.u.pNC = pNC;
7011 w.pParse = 0;
7012 assert( pNC->pSrcList!=0 );
7013 sqlite3WalkExpr(&w, pExpr);
7017 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
7018 ** expression list. Return the number of errors.
7020 ** If an error is found, the analysis is cut short.
7022 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
7023 struct ExprList_item *pItem;
7024 int i;
7025 if( pList ){
7026 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
7027 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
7033 ** Allocate a single new register for use to hold some intermediate result.
7035 int sqlite3GetTempReg(Parse *pParse){
7036 if( pParse->nTempReg==0 ){
7037 return ++pParse->nMem;
7039 return pParse->aTempReg[--pParse->nTempReg];
7043 ** Deallocate a register, making available for reuse for some other
7044 ** purpose.
7046 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
7047 if( iReg ){
7048 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
7049 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
7050 pParse->aTempReg[pParse->nTempReg++] = iReg;
7056 ** Allocate or deallocate a block of nReg consecutive registers.
7058 int sqlite3GetTempRange(Parse *pParse, int nReg){
7059 int i, n;
7060 if( nReg==1 ) return sqlite3GetTempReg(pParse);
7061 i = pParse->iRangeReg;
7062 n = pParse->nRangeReg;
7063 if( nReg<=n ){
7064 pParse->iRangeReg += nReg;
7065 pParse->nRangeReg -= nReg;
7066 }else{
7067 i = pParse->nMem+1;
7068 pParse->nMem += nReg;
7070 return i;
7072 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
7073 if( nReg==1 ){
7074 sqlite3ReleaseTempReg(pParse, iReg);
7075 return;
7077 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
7078 if( nReg>pParse->nRangeReg ){
7079 pParse->nRangeReg = nReg;
7080 pParse->iRangeReg = iReg;
7085 ** Mark all temporary registers as being unavailable for reuse.
7087 ** Always invoke this procedure after coding a subroutine or co-routine
7088 ** that might be invoked from other parts of the code, to ensure that
7089 ** the sub/co-routine does not use registers in common with the code that
7090 ** invokes the sub/co-routine.
7092 void sqlite3ClearTempRegCache(Parse *pParse){
7093 pParse->nTempReg = 0;
7094 pParse->nRangeReg = 0;
7098 ** Make sure sufficient registers have been allocated so that
7099 ** iReg is a valid register number.
7101 void sqlite3TouchRegister(Parse *pParse, int iReg){
7102 if( pParse->nMem<iReg ) pParse->nMem = iReg;
7105 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
7107 ** Return the latest reusable register in the set of all registers.
7108 ** The value returned is no less than iMin. If any register iMin or
7109 ** greater is in permanent use, then return one more than that last
7110 ** permanent register.
7112 int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){
7113 const ExprList *pList = pParse->pConstExpr;
7114 if( pList ){
7115 int i;
7116 for(i=0; i<pList->nExpr; i++){
7117 if( pList->a[i].u.iConstExprReg>=iMin ){
7118 iMin = pList->a[i].u.iConstExprReg + 1;
7122 pParse->nTempReg = 0;
7123 pParse->nRangeReg = 0;
7124 return iMin;
7126 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
7129 ** Validate that no temporary register falls within the range of
7130 ** iFirst..iLast, inclusive. This routine is only call from within assert()
7131 ** statements.
7133 #ifdef SQLITE_DEBUG
7134 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
7135 int i;
7136 if( pParse->nRangeReg>0
7137 && pParse->iRangeReg+pParse->nRangeReg > iFirst
7138 && pParse->iRangeReg <= iLast
7140 return 0;
7142 for(i=0; i<pParse->nTempReg; i++){
7143 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
7144 return 0;
7147 if( pParse->pConstExpr ){
7148 ExprList *pList = pParse->pConstExpr;
7149 for(i=0; i<pList->nExpr; i++){
7150 int iReg = pList->a[i].u.iConstExprReg;
7151 if( iReg==0 ) continue;
7152 if( iReg>=iFirst && iReg<=iLast ) return 0;
7155 return 1;
7157 #endif /* SQLITE_DEBUG */