Avoid some OP_SCopy instructions in "INSERT INTO .. VALUES" statements that insert...
[sqlite.git] / src / expr.c
blobe4bfa995d7bb490f69b7f624dffe3a3e1217ea03
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
15 #include "sqliteInt.h"
17 /* Forward declarations */
18 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
22 ** Return the affinity character for a single column of a table.
24 char sqlite3TableColumnAffinity(const Table *pTab, int iCol){
25 if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;
26 return pTab->aCol[iCol].affinity;
30 ** Return the 'affinity' of the expression pExpr if any.
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
37 ** i.e. the WHERE clause expressions in the following statements all
38 ** have an affinity:
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
45 char sqlite3ExprAffinity(const Expr *pExpr){
46 int op;
47 op = pExpr->op;
48 while( 1 /* exit-by-break */ ){
49 if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){
50 assert( ExprUseYTab(pExpr) );
51 assert( pExpr->y.pTab!=0 );
52 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
54 if( op==TK_SELECT ){
55 assert( ExprUseXSelect(pExpr) );
56 assert( pExpr->x.pSelect!=0 );
57 assert( pExpr->x.pSelect->pEList!=0 );
58 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
59 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
61 #ifndef SQLITE_OMIT_CAST
62 if( op==TK_CAST ){
63 assert( !ExprHasProperty(pExpr, EP_IntValue) );
64 return sqlite3AffinityType(pExpr->u.zToken, 0);
66 #endif
67 if( op==TK_SELECT_COLUMN ){
68 assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );
69 assert( pExpr->iColumn < pExpr->iTable );
70 assert( pExpr->iColumn >= 0 );
71 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
72 return sqlite3ExprAffinity(
73 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
76 if( op==TK_VECTOR ){
77 assert( ExprUseXList(pExpr) );
78 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
80 if( ExprHasProperty(pExpr, EP_Skip|EP_IfNullRow) ){
81 assert( pExpr->op==TK_COLLATE
82 || pExpr->op==TK_IF_NULL_ROW
83 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
84 pExpr = pExpr->pLeft;
85 op = pExpr->op;
86 continue;
88 if( op!=TK_REGISTER || (op = pExpr->op2)==TK_REGISTER ) break;
90 return pExpr->affExpr;
94 ** Make a guess at all the possible datatypes of the result that could
95 ** be returned by an expression. Return a bitmask indicating the answer:
97 ** 0x01 Numeric
98 ** 0x02 Text
99 ** 0x04 Blob
101 ** If the expression must return NULL, then 0x00 is returned.
103 int sqlite3ExprDataType(const Expr *pExpr){
104 while( pExpr ){
105 switch( pExpr->op ){
106 case TK_COLLATE:
107 case TK_IF_NULL_ROW:
108 case TK_UPLUS: {
109 pExpr = pExpr->pLeft;
110 break;
112 case TK_NULL: {
113 pExpr = 0;
114 break;
116 case TK_STRING: {
117 return 0x02;
119 case TK_BLOB: {
120 return 0x04;
122 case TK_CONCAT: {
123 return 0x06;
125 case TK_VARIABLE:
126 case TK_AGG_FUNCTION:
127 case TK_FUNCTION: {
128 return 0x07;
130 case TK_COLUMN:
131 case TK_AGG_COLUMN:
132 case TK_SELECT:
133 case TK_CAST:
134 case TK_SELECT_COLUMN:
135 case TK_VECTOR: {
136 int aff = sqlite3ExprAffinity(pExpr);
137 if( aff>=SQLITE_AFF_NUMERIC ) return 0x05;
138 if( aff==SQLITE_AFF_TEXT ) return 0x06;
139 return 0x07;
141 case TK_CASE: {
142 int res = 0;
143 int ii;
144 ExprList *pList = pExpr->x.pList;
145 assert( ExprUseXList(pExpr) && pList!=0 );
146 assert( pList->nExpr > 0);
147 for(ii=1; ii<pList->nExpr; ii+=2){
148 res |= sqlite3ExprDataType(pList->a[ii].pExpr);
150 if( pList->nExpr % 2 ){
151 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);
153 return res;
155 default: {
156 return 0x01;
158 } /* End of switch(op) */
159 } /* End of while(pExpr) */
160 return 0x00;
164 ** Set the collating sequence for expression pExpr to be the collating
165 ** sequence named by pToken. Return a pointer to a new Expr node that
166 ** implements the COLLATE operator.
168 ** If a memory allocation error occurs, that fact is recorded in pParse->db
169 ** and the pExpr parameter is returned unchanged.
171 Expr *sqlite3ExprAddCollateToken(
172 const Parse *pParse, /* Parsing context */
173 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
174 const Token *pCollName, /* Name of collating sequence */
175 int dequote /* True to dequote pCollName */
177 if( pCollName->n>0 ){
178 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
179 if( pNew ){
180 pNew->pLeft = pExpr;
181 pNew->flags |= EP_Collate|EP_Skip;
182 pExpr = pNew;
185 return pExpr;
187 Expr *sqlite3ExprAddCollateString(
188 const Parse *pParse, /* Parsing context */
189 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
190 const char *zC /* The collating sequence name */
192 Token s;
193 assert( zC!=0 );
194 sqlite3TokenInit(&s, (char*)zC);
195 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
199 ** Skip over any TK_COLLATE operators.
201 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
202 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
203 assert( pExpr->op==TK_COLLATE );
204 pExpr = pExpr->pLeft;
206 return pExpr;
210 ** Skip over any TK_COLLATE operators and/or any unlikely()
211 ** or likelihood() or likely() functions at the root of an
212 ** expression.
214 Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
215 while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
216 if( ExprHasProperty(pExpr, EP_Unlikely) ){
217 assert( ExprUseXList(pExpr) );
218 assert( pExpr->x.pList->nExpr>0 );
219 assert( pExpr->op==TK_FUNCTION );
220 pExpr = pExpr->x.pList->a[0].pExpr;
221 }else{
222 assert( pExpr->op==TK_COLLATE );
223 pExpr = pExpr->pLeft;
226 return pExpr;
230 ** Return the collation sequence for the expression pExpr. If
231 ** there is no defined collating sequence, return NULL.
233 ** See also: sqlite3ExprNNCollSeq()
235 ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
236 ** default collation if pExpr has no defined collation.
238 ** The collating sequence might be determined by a COLLATE operator
239 ** or by the presence of a column with a defined collating sequence.
240 ** COLLATE operators take first precedence. Left operands take
241 ** precedence over right operands.
243 CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
244 sqlite3 *db = pParse->db;
245 CollSeq *pColl = 0;
246 const Expr *p = pExpr;
247 while( p ){
248 int op = p->op;
249 if( op==TK_REGISTER ) op = p->op2;
250 if( (op==TK_AGG_COLUMN && p->y.pTab!=0)
251 || op==TK_COLUMN || op==TK_TRIGGER
253 int j;
254 assert( ExprUseYTab(p) );
255 assert( p->y.pTab!=0 );
256 if( (j = p->iColumn)>=0 ){
257 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
258 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
260 break;
262 if( op==TK_CAST || op==TK_UPLUS ){
263 p = p->pLeft;
264 continue;
266 if( op==TK_VECTOR ){
267 assert( ExprUseXList(p) );
268 p = p->x.pList->a[0].pExpr;
269 continue;
271 if( op==TK_COLLATE ){
272 assert( !ExprHasProperty(p, EP_IntValue) );
273 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
274 break;
276 if( p->flags & EP_Collate ){
277 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
278 p = p->pLeft;
279 }else{
280 Expr *pNext = p->pRight;
281 /* The Expr.x union is never used at the same time as Expr.pRight */
282 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
283 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
284 int i;
285 for(i=0; i<p->x.pList->nExpr; i++){
286 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
287 pNext = p->x.pList->a[i].pExpr;
288 break;
292 p = pNext;
294 }else{
295 break;
298 if( sqlite3CheckCollSeq(pParse, pColl) ){
299 pColl = 0;
301 return pColl;
305 ** Return the collation sequence for the expression pExpr. If
306 ** there is no defined collating sequence, return a pointer to the
307 ** default collation sequence.
309 ** See also: sqlite3ExprCollSeq()
311 ** The sqlite3ExprCollSeq() routine works the same except that it
312 ** returns NULL if there is no defined collation.
314 CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
315 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
316 if( p==0 ) p = pParse->db->pDfltColl;
317 assert( p!=0 );
318 return p;
322 ** Return TRUE if the two expressions have equivalent collating sequences.
324 int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
325 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
326 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
327 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
331 ** pExpr is an operand of a comparison operator. aff2 is the
332 ** type affinity of the other operand. This routine returns the
333 ** type affinity that should be used for the comparison operator.
335 char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
336 char aff1 = sqlite3ExprAffinity(pExpr);
337 if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
338 /* Both sides of the comparison are columns. If one has numeric
339 ** affinity, use that. Otherwise use no affinity.
341 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
342 return SQLITE_AFF_NUMERIC;
343 }else{
344 return SQLITE_AFF_BLOB;
346 }else{
347 /* One side is a column, the other is not. Use the columns affinity. */
348 assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
349 return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
354 ** pExpr is a comparison operator. Return the type affinity that should
355 ** be applied to both operands prior to doing the comparison.
357 static char comparisonAffinity(const Expr *pExpr){
358 char aff;
359 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
360 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
361 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
362 assert( pExpr->pLeft );
363 aff = sqlite3ExprAffinity(pExpr->pLeft);
364 if( pExpr->pRight ){
365 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
366 }else if( ExprUseXSelect(pExpr) ){
367 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
368 }else if( aff==0 ){
369 aff = SQLITE_AFF_BLOB;
371 return aff;
375 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
376 ** idx_affinity is the affinity of an indexed column. Return true
377 ** if the index with affinity idx_affinity may be used to implement
378 ** the comparison in pExpr.
380 int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
381 char aff = comparisonAffinity(pExpr);
382 if( aff<SQLITE_AFF_TEXT ){
383 return 1;
385 if( aff==SQLITE_AFF_TEXT ){
386 return idx_affinity==SQLITE_AFF_TEXT;
388 return sqlite3IsNumericAffinity(idx_affinity);
392 ** Return the P5 value that should be used for a binary comparison
393 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
395 static u8 binaryCompareP5(
396 const Expr *pExpr1, /* Left operand */
397 const Expr *pExpr2, /* Right operand */
398 int jumpIfNull /* Extra flags added to P5 */
400 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
401 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
402 return aff;
406 ** Return a pointer to the collation sequence that should be used by
407 ** a binary comparison operator comparing pLeft and pRight.
409 ** If the left hand expression has a collating sequence type, then it is
410 ** used. Otherwise the collation sequence for the right hand expression
411 ** is used, or the default (BINARY) if neither expression has a collating
412 ** type.
414 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
415 ** it is not considered.
417 CollSeq *sqlite3BinaryCompareCollSeq(
418 Parse *pParse,
419 const Expr *pLeft,
420 const Expr *pRight
422 CollSeq *pColl;
423 assert( pLeft );
424 if( pLeft->flags & EP_Collate ){
425 pColl = sqlite3ExprCollSeq(pParse, pLeft);
426 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
427 pColl = sqlite3ExprCollSeq(pParse, pRight);
428 }else{
429 pColl = sqlite3ExprCollSeq(pParse, pLeft);
430 if( !pColl ){
431 pColl = sqlite3ExprCollSeq(pParse, pRight);
434 return pColl;
437 /* Expression p is a comparison operator. Return a collation sequence
438 ** appropriate for the comparison operator.
440 ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
441 ** However, if the OP_Commuted flag is set, then the order of the operands
442 ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
443 ** correct collating sequence is found.
445 CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
446 if( ExprHasProperty(p, EP_Commuted) ){
447 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
448 }else{
449 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
454 ** Generate code for a comparison operator.
456 static int codeCompare(
457 Parse *pParse, /* The parsing (and code generating) context */
458 Expr *pLeft, /* The left operand */
459 Expr *pRight, /* The right operand */
460 int opcode, /* The comparison opcode */
461 int in1, int in2, /* Register holding operands */
462 int dest, /* Jump here if true. */
463 int jumpIfNull, /* If true, jump if either operand is NULL */
464 int isCommuted /* The comparison has been commuted */
466 int p5;
467 int addr;
468 CollSeq *p4;
470 if( pParse->nErr ) return 0;
471 if( isCommuted ){
472 p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
473 }else{
474 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
476 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
477 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
478 (void*)p4, P4_COLLSEQ);
479 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
480 return addr;
484 ** Return true if expression pExpr is a vector, or false otherwise.
486 ** A vector is defined as any expression that results in two or more
487 ** columns of result. Every TK_VECTOR node is an vector because the
488 ** parser will not generate a TK_VECTOR with fewer than two entries.
489 ** But a TK_SELECT might be either a vector or a scalar. It is only
490 ** considered a vector if it has two or more result columns.
492 int sqlite3ExprIsVector(const Expr *pExpr){
493 return sqlite3ExprVectorSize(pExpr)>1;
497 ** If the expression passed as the only argument is of type TK_VECTOR
498 ** return the number of expressions in the vector. Or, if the expression
499 ** is a sub-select, return the number of columns in the sub-select. For
500 ** any other type of expression, return 1.
502 int sqlite3ExprVectorSize(const Expr *pExpr){
503 u8 op = pExpr->op;
504 if( op==TK_REGISTER ) op = pExpr->op2;
505 if( op==TK_VECTOR ){
506 assert( ExprUseXList(pExpr) );
507 return pExpr->x.pList->nExpr;
508 }else if( op==TK_SELECT ){
509 assert( ExprUseXSelect(pExpr) );
510 return pExpr->x.pSelect->pEList->nExpr;
511 }else{
512 return 1;
517 ** Return a pointer to a subexpression of pVector that is the i-th
518 ** column of the vector (numbered starting with 0). The caller must
519 ** ensure that i is within range.
521 ** If pVector is really a scalar (and "scalar" here includes subqueries
522 ** that return a single column!) then return pVector unmodified.
524 ** pVector retains ownership of the returned subexpression.
526 ** If the vector is a (SELECT ...) then the expression returned is
527 ** just the expression for the i-th term of the result set, and may
528 ** not be ready for evaluation because the table cursor has not yet
529 ** been positioned.
531 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
532 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
533 if( sqlite3ExprIsVector(pVector) ){
534 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
535 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
536 assert( ExprUseXSelect(pVector) );
537 return pVector->x.pSelect->pEList->a[i].pExpr;
538 }else{
539 assert( ExprUseXList(pVector) );
540 return pVector->x.pList->a[i].pExpr;
543 return pVector;
547 ** Compute and return a new Expr object which when passed to
548 ** sqlite3ExprCode() will generate all necessary code to compute
549 ** the iField-th column of the vector expression pVector.
551 ** It is ok for pVector to be a scalar (as long as iField==0).
552 ** In that case, this routine works like sqlite3ExprDup().
554 ** The caller owns the returned Expr object and is responsible for
555 ** ensuring that the returned value eventually gets freed.
557 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
558 ** then the returned object will reference pVector and so pVector must remain
559 ** valid for the life of the returned object. If pVector is a TK_VECTOR
560 ** or a scalar expression, then it can be deleted as soon as this routine
561 ** returns.
563 ** A trick to cause a TK_SELECT pVector to be deleted together with
564 ** the returned Expr object is to attach the pVector to the pRight field
565 ** of the returned TK_SELECT_COLUMN Expr object.
567 Expr *sqlite3ExprForVectorField(
568 Parse *pParse, /* Parsing context */
569 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
570 int iField, /* Which column of the vector to return */
571 int nField /* Total number of columns in the vector */
573 Expr *pRet;
574 if( pVector->op==TK_SELECT ){
575 assert( ExprUseXSelect(pVector) );
576 /* The TK_SELECT_COLUMN Expr node:
578 ** pLeft: pVector containing TK_SELECT. Not deleted.
579 ** pRight: not used. But recursively deleted.
580 ** iColumn: Index of a column in pVector
581 ** iTable: 0 or the number of columns on the LHS of an assignment
582 ** pLeft->iTable: First in an array of register holding result, or 0
583 ** if the result is not yet computed.
585 ** sqlite3ExprDelete() specifically skips the recursive delete of
586 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
587 ** can be attached to pRight to cause this node to take ownership of
588 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
589 ** with the same pLeft pointer to the pVector, but only one of them
590 ** will own the pVector.
592 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
593 if( pRet ){
594 ExprSetProperty(pRet, EP_FullSize);
595 pRet->iTable = nField;
596 pRet->iColumn = iField;
597 pRet->pLeft = pVector;
599 }else{
600 if( pVector->op==TK_VECTOR ){
601 Expr **ppVector;
602 assert( ExprUseXList(pVector) );
603 ppVector = &pVector->x.pList->a[iField].pExpr;
604 pVector = *ppVector;
605 if( IN_RENAME_OBJECT ){
606 /* This must be a vector UPDATE inside a trigger */
607 *ppVector = 0;
608 return pVector;
611 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
613 return pRet;
617 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
618 ** it. Return the register in which the result is stored (or, if the
619 ** sub-select returns more than one column, the first in an array
620 ** of registers in which the result is stored).
622 ** If pExpr is not a TK_SELECT expression, return 0.
624 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
625 int reg = 0;
626 #ifndef SQLITE_OMIT_SUBQUERY
627 if( pExpr->op==TK_SELECT ){
628 reg = sqlite3CodeSubselect(pParse, pExpr);
630 #endif
631 return reg;
635 ** Argument pVector points to a vector expression - either a TK_VECTOR
636 ** or TK_SELECT that returns more than one column. This function returns
637 ** the register number of a register that contains the value of
638 ** element iField of the vector.
640 ** If pVector is a TK_SELECT expression, then code for it must have
641 ** already been generated using the exprCodeSubselect() routine. In this
642 ** case parameter regSelect should be the first in an array of registers
643 ** containing the results of the sub-select.
645 ** If pVector is of type TK_VECTOR, then code for the requested field
646 ** is generated. In this case (*pRegFree) may be set to the number of
647 ** a temporary register to be freed by the caller before returning.
649 ** Before returning, output parameter (*ppExpr) is set to point to the
650 ** Expr object corresponding to element iElem of the vector.
652 static int exprVectorRegister(
653 Parse *pParse, /* Parse context */
654 Expr *pVector, /* Vector to extract element from */
655 int iField, /* Field to extract from pVector */
656 int regSelect, /* First in array of registers */
657 Expr **ppExpr, /* OUT: Expression element */
658 int *pRegFree /* OUT: Temp register to free */
660 u8 op = pVector->op;
661 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT || op==TK_ERROR );
662 if( op==TK_REGISTER ){
663 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
664 return pVector->iTable+iField;
666 if( op==TK_SELECT ){
667 assert( ExprUseXSelect(pVector) );
668 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
669 return regSelect+iField;
671 if( op==TK_VECTOR ){
672 assert( ExprUseXList(pVector) );
673 *ppExpr = pVector->x.pList->a[iField].pExpr;
674 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
676 return 0;
680 ** Expression pExpr is a comparison between two vector values. Compute
681 ** the result of the comparison (1, 0, or NULL) and write that
682 ** result into register dest.
684 ** The caller must satisfy the following preconditions:
686 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
687 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
688 ** otherwise: op==pExpr->op and p5==0
690 static void codeVectorCompare(
691 Parse *pParse, /* Code generator context */
692 Expr *pExpr, /* The comparison operation */
693 int dest, /* Write results into this register */
694 u8 op, /* Comparison operator */
695 u8 p5 /* SQLITE_NULLEQ or zero */
697 Vdbe *v = pParse->pVdbe;
698 Expr *pLeft = pExpr->pLeft;
699 Expr *pRight = pExpr->pRight;
700 int nLeft = sqlite3ExprVectorSize(pLeft);
701 int i;
702 int regLeft = 0;
703 int regRight = 0;
704 u8 opx = op;
705 int addrCmp = 0;
706 int addrDone = sqlite3VdbeMakeLabel(pParse);
707 int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
709 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
710 if( pParse->nErr ) return;
711 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
712 sqlite3ErrorMsg(pParse, "row value misused");
713 return;
715 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
716 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
717 || pExpr->op==TK_LT || pExpr->op==TK_GT
718 || pExpr->op==TK_LE || pExpr->op==TK_GE
720 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
721 || (pExpr->op==TK_ISNOT && op==TK_NE) );
722 assert( p5==0 || pExpr->op!=op );
723 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
725 if( op==TK_LE ) opx = TK_LT;
726 if( op==TK_GE ) opx = TK_GT;
727 if( op==TK_NE ) opx = TK_EQ;
729 regLeft = exprCodeSubselect(pParse, pLeft);
730 regRight = exprCodeSubselect(pParse, pRight);
732 sqlite3VdbeAddOp2(v, OP_Integer, 1, dest);
733 for(i=0; 1 /*Loop exits by "break"*/; i++){
734 int regFree1 = 0, regFree2 = 0;
735 Expr *pL = 0, *pR = 0;
736 int r1, r2;
737 assert( i>=0 && i<nLeft );
738 if( addrCmp ) sqlite3VdbeJumpHere(v, addrCmp);
739 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
740 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
741 addrCmp = sqlite3VdbeCurrentAddr(v);
742 codeCompare(pParse, pL, pR, opx, r1, r2, addrDone, p5, isCommuted);
743 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
744 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
745 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
746 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
747 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
748 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
749 sqlite3ReleaseTempReg(pParse, regFree1);
750 sqlite3ReleaseTempReg(pParse, regFree2);
751 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
752 addrCmp = sqlite3VdbeAddOp0(v, OP_ElseEq);
753 testcase(opx==TK_LT); VdbeCoverageIf(v,opx==TK_LT);
754 testcase(opx==TK_GT); VdbeCoverageIf(v,opx==TK_GT);
756 if( p5==SQLITE_NULLEQ ){
757 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest);
758 }else{
759 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, dest, r2);
761 if( i==nLeft-1 ){
762 break;
764 if( opx==TK_EQ ){
765 sqlite3VdbeAddOp2(v, OP_NotNull, dest, addrDone); VdbeCoverage(v);
766 }else{
767 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
768 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrDone);
769 if( i==nLeft-2 ) opx = op;
772 sqlite3VdbeJumpHere(v, addrCmp);
773 sqlite3VdbeResolveLabel(v, addrDone);
774 if( op==TK_NE ){
775 sqlite3VdbeAddOp2(v, OP_Not, dest, dest);
779 #if SQLITE_MAX_EXPR_DEPTH>0
781 ** Check that argument nHeight is less than or equal to the maximum
782 ** expression depth allowed. If it is not, leave an error message in
783 ** pParse.
785 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
786 int rc = SQLITE_OK;
787 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
788 if( nHeight>mxHeight ){
789 sqlite3ErrorMsg(pParse,
790 "Expression tree is too large (maximum depth %d)", mxHeight
792 rc = SQLITE_ERROR;
794 return rc;
797 /* The following three functions, heightOfExpr(), heightOfExprList()
798 ** and heightOfSelect(), are used to determine the maximum height
799 ** of any expression tree referenced by the structure passed as the
800 ** first argument.
802 ** If this maximum height is greater than the current value pointed
803 ** to by pnHeight, the second parameter, then set *pnHeight to that
804 ** value.
806 static void heightOfExpr(const Expr *p, int *pnHeight){
807 if( p ){
808 if( p->nHeight>*pnHeight ){
809 *pnHeight = p->nHeight;
813 static void heightOfExprList(const ExprList *p, int *pnHeight){
814 if( p ){
815 int i;
816 for(i=0; i<p->nExpr; i++){
817 heightOfExpr(p->a[i].pExpr, pnHeight);
821 static void heightOfSelect(const Select *pSelect, int *pnHeight){
822 const Select *p;
823 for(p=pSelect; p; p=p->pPrior){
824 heightOfExpr(p->pWhere, pnHeight);
825 heightOfExpr(p->pHaving, pnHeight);
826 heightOfExpr(p->pLimit, pnHeight);
827 heightOfExprList(p->pEList, pnHeight);
828 heightOfExprList(p->pGroupBy, pnHeight);
829 heightOfExprList(p->pOrderBy, pnHeight);
834 ** Set the Expr.nHeight variable in the structure passed as an
835 ** argument. An expression with no children, Expr.pList or
836 ** Expr.pSelect member has a height of 1. Any other expression
837 ** has a height equal to the maximum height of any other
838 ** referenced Expr plus one.
840 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
841 ** if appropriate.
843 static void exprSetHeight(Expr *p){
844 int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
845 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
846 nHeight = p->pRight->nHeight;
848 if( ExprUseXSelect(p) ){
849 heightOfSelect(p->x.pSelect, &nHeight);
850 }else if( p->x.pList ){
851 heightOfExprList(p->x.pList, &nHeight);
852 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
854 p->nHeight = nHeight + 1;
858 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
859 ** the height is greater than the maximum allowed expression depth,
860 ** leave an error in pParse.
862 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
863 ** Expr.flags.
865 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
866 if( pParse->nErr ) return;
867 exprSetHeight(p);
868 sqlite3ExprCheckHeight(pParse, p->nHeight);
872 ** Return the maximum height of any expression tree referenced
873 ** by the select statement passed as an argument.
875 int sqlite3SelectExprHeight(const Select *p){
876 int nHeight = 0;
877 heightOfSelect(p, &nHeight);
878 return nHeight;
880 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
882 ** Propagate all EP_Propagate flags from the Expr.x.pList into
883 ** Expr.flags.
885 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
886 if( pParse->nErr ) return;
887 if( p && ExprUseXList(p) && p->x.pList ){
888 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
891 #define exprSetHeight(y)
892 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
895 ** Set the error offset for an Expr node, if possible.
897 void sqlite3ExprSetErrorOffset(Expr *pExpr, int iOfst){
898 if( pExpr==0 ) return;
899 if( NEVER(ExprUseWJoin(pExpr)) ) return;
900 pExpr->w.iOfst = iOfst;
904 ** This routine is the core allocator for Expr nodes.
906 ** Construct a new expression node and return a pointer to it. Memory
907 ** for this node and for the pToken argument is a single allocation
908 ** obtained from sqlite3DbMalloc(). The calling function
909 ** is responsible for making sure the node eventually gets freed.
911 ** If dequote is true, then the token (if it exists) is dequoted.
912 ** If dequote is false, no dequoting is performed. The deQuote
913 ** parameter is ignored if pToken is NULL or if the token does not
914 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
915 ** then the EP_DblQuoted flag is set on the expression node.
917 ** Special case (tag-20240227-a): If op==TK_INTEGER and pToken points to
918 ** a string that can be translated into a 32-bit integer, then the token is
919 ** not stored in u.zToken. Instead, the integer values is written
920 ** into u.iValue and the EP_IntValue flag is set. No extra storage
921 ** is allocated to hold the integer text and the dequote flag is ignored.
922 ** See also tag-20240227-b.
924 Expr *sqlite3ExprAlloc(
925 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
926 int op, /* Expression opcode */
927 const Token *pToken, /* Token argument. Might be NULL */
928 int dequote /* True to dequote */
930 Expr *pNew;
931 int nExtra = 0;
932 int iValue = 0;
934 assert( db!=0 );
935 if( pToken ){
936 if( op!=TK_INTEGER || pToken->z==0
937 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
938 nExtra = pToken->n+1; /* tag-20240227-a */
939 assert( iValue>=0 );
942 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
943 if( pNew ){
944 memset(pNew, 0, sizeof(Expr));
945 pNew->op = (u8)op;
946 pNew->iAgg = -1;
947 if( pToken ){
948 if( nExtra==0 ){
949 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
950 pNew->u.iValue = iValue;
951 }else{
952 pNew->u.zToken = (char*)&pNew[1];
953 assert( pToken->z!=0 || pToken->n==0 );
954 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
955 pNew->u.zToken[pToken->n] = 0;
956 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
957 sqlite3DequoteExpr(pNew);
961 #if SQLITE_MAX_EXPR_DEPTH>0
962 pNew->nHeight = 1;
963 #endif
965 return pNew;
969 ** Allocate a new expression node from a zero-terminated token that has
970 ** already been dequoted.
972 Expr *sqlite3Expr(
973 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
974 int op, /* Expression opcode */
975 const char *zToken /* Token argument. Might be NULL */
977 Token x;
978 x.z = zToken;
979 x.n = sqlite3Strlen30(zToken);
980 return sqlite3ExprAlloc(db, op, &x, 0);
984 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
986 ** If pRoot==NULL that means that a memory allocation error has occurred.
987 ** In that case, delete the subtrees pLeft and pRight.
989 void sqlite3ExprAttachSubtrees(
990 sqlite3 *db,
991 Expr *pRoot,
992 Expr *pLeft,
993 Expr *pRight
995 if( pRoot==0 ){
996 assert( db->mallocFailed );
997 sqlite3ExprDelete(db, pLeft);
998 sqlite3ExprDelete(db, pRight);
999 }else{
1000 assert( ExprUseXList(pRoot) );
1001 assert( pRoot->x.pSelect==0 );
1002 if( pRight ){
1003 pRoot->pRight = pRight;
1004 pRoot->flags |= EP_Propagate & pRight->flags;
1005 #if SQLITE_MAX_EXPR_DEPTH>0
1006 pRoot->nHeight = pRight->nHeight+1;
1007 }else{
1008 pRoot->nHeight = 1;
1009 #endif
1011 if( pLeft ){
1012 pRoot->pLeft = pLeft;
1013 pRoot->flags |= EP_Propagate & pLeft->flags;
1014 #if SQLITE_MAX_EXPR_DEPTH>0
1015 if( pLeft->nHeight>=pRoot->nHeight ){
1016 pRoot->nHeight = pLeft->nHeight+1;
1018 #endif
1024 ** Allocate an Expr node which joins as many as two subtrees.
1026 ** One or both of the subtrees can be NULL. Return a pointer to the new
1027 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
1028 ** free the subtrees and return NULL.
1030 Expr *sqlite3PExpr(
1031 Parse *pParse, /* Parsing context */
1032 int op, /* Expression opcode */
1033 Expr *pLeft, /* Left operand */
1034 Expr *pRight /* Right operand */
1036 Expr *p;
1037 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
1038 if( p ){
1039 memset(p, 0, sizeof(Expr));
1040 p->op = op & 0xff;
1041 p->iAgg = -1;
1042 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
1043 sqlite3ExprCheckHeight(pParse, p->nHeight);
1044 }else{
1045 sqlite3ExprDelete(pParse->db, pLeft);
1046 sqlite3ExprDelete(pParse->db, pRight);
1048 return p;
1052 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
1053 ** do a memory allocation failure) then delete the pSelect object.
1055 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
1056 if( pExpr ){
1057 pExpr->x.pSelect = pSelect;
1058 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
1059 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
1060 }else{
1061 assert( pParse->db->mallocFailed );
1062 sqlite3SelectDelete(pParse->db, pSelect);
1067 ** Expression list pEList is a list of vector values. This function
1068 ** converts the contents of pEList to a VALUES(...) Select statement
1069 ** returning 1 row for each element of the list. For example, the
1070 ** expression list:
1072 ** ( (1,2), (3,4) (5,6) )
1074 ** is translated to the equivalent of:
1076 ** VALUES(1,2), (3,4), (5,6)
1078 ** Each of the vector values in pEList must contain exactly nElem terms.
1079 ** If a list element that is not a vector or does not contain nElem terms,
1080 ** an error message is left in pParse.
1082 ** This is used as part of processing IN(...) expressions with a list
1083 ** of vectors on the RHS. e.g. "... IN ((1,2), (3,4), (5,6))".
1085 Select *sqlite3ExprListToValues(Parse *pParse, int nElem, ExprList *pEList){
1086 int ii;
1087 Select *pRet = 0;
1088 assert( nElem>1 );
1089 for(ii=0; ii<pEList->nExpr; ii++){
1090 Select *pSel;
1091 Expr *pExpr = pEList->a[ii].pExpr;
1092 int nExprElem;
1093 if( pExpr->op==TK_VECTOR ){
1094 assert( ExprUseXList(pExpr) );
1095 nExprElem = pExpr->x.pList->nExpr;
1096 }else{
1097 nExprElem = 1;
1099 if( nExprElem!=nElem ){
1100 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
1101 nExprElem, nExprElem>1?"s":"", nElem
1103 break;
1105 assert( ExprUseXList(pExpr) );
1106 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
1107 pExpr->x.pList = 0;
1108 if( pSel ){
1109 if( pRet ){
1110 pSel->op = TK_ALL;
1111 pSel->pPrior = pRet;
1113 pRet = pSel;
1117 if( pRet && pRet->pPrior ){
1118 pRet->selFlags |= SF_MultiValue;
1120 sqlite3ExprListDelete(pParse->db, pEList);
1121 return pRet;
1125 ** Join two expressions using an AND operator. If either expression is
1126 ** NULL, then just return the other expression.
1128 ** If one side or the other of the AND is known to be false, and neither side
1129 ** is part of an ON clause, then instead of returning an AND expression,
1130 ** just return a constant expression with a value of false.
1132 Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
1133 sqlite3 *db = pParse->db;
1134 if( pLeft==0 ){
1135 return pRight;
1136 }else if( pRight==0 ){
1137 return pLeft;
1138 }else{
1139 u32 f = pLeft->flags | pRight->flags;
1140 if( (f&(EP_OuterON|EP_InnerON|EP_IsFalse))==EP_IsFalse
1141 && !IN_RENAME_OBJECT
1143 sqlite3ExprDeferredDelete(pParse, pLeft);
1144 sqlite3ExprDeferredDelete(pParse, pRight);
1145 return sqlite3Expr(db, TK_INTEGER, "0");
1146 }else{
1147 return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
1153 ** Construct a new expression node for a function with multiple
1154 ** arguments.
1156 Expr *sqlite3ExprFunction(
1157 Parse *pParse, /* Parsing context */
1158 ExprList *pList, /* Argument list */
1159 const Token *pToken, /* Name of the function */
1160 int eDistinct /* SF_Distinct or SF_ALL or 0 */
1162 Expr *pNew;
1163 sqlite3 *db = pParse->db;
1164 assert( pToken );
1165 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
1166 if( pNew==0 ){
1167 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
1168 return 0;
1170 assert( !ExprHasProperty(pNew, EP_InnerON|EP_OuterON) );
1171 pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
1172 if( pList
1173 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
1174 && !pParse->nested
1176 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
1178 pNew->x.pList = pList;
1179 ExprSetProperty(pNew, EP_HasFunc);
1180 assert( ExprUseXList(pNew) );
1181 sqlite3ExprSetHeightAndFlags(pParse, pNew);
1182 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
1183 return pNew;
1187 ** Report an error when attempting to use an ORDER BY clause within
1188 ** the arguments of a non-aggregate function.
1190 void sqlite3ExprOrderByAggregateError(Parse *pParse, Expr *p){
1191 sqlite3ErrorMsg(pParse,
1192 "ORDER BY may not be used with non-aggregate %#T()", p
1197 ** Attach an ORDER BY clause to a function call.
1199 ** functionname( arguments ORDER BY sortlist )
1200 ** \_____________________/ \______/
1201 ** pExpr pOrderBy
1203 ** The ORDER BY clause is inserted into a new Expr node of type TK_ORDER
1204 ** and added to the Expr.pLeft field of the parent TK_FUNCTION node.
1206 void sqlite3ExprAddFunctionOrderBy(
1207 Parse *pParse, /* Parsing context */
1208 Expr *pExpr, /* The function call to which ORDER BY is to be added */
1209 ExprList *pOrderBy /* The ORDER BY clause to add */
1211 Expr *pOB;
1212 sqlite3 *db = pParse->db;
1213 if( NEVER(pOrderBy==0) ){
1214 assert( db->mallocFailed );
1215 return;
1217 if( pExpr==0 ){
1218 assert( db->mallocFailed );
1219 sqlite3ExprListDelete(db, pOrderBy);
1220 return;
1222 assert( pExpr->op==TK_FUNCTION );
1223 assert( pExpr->pLeft==0 );
1224 assert( ExprUseXList(pExpr) );
1225 if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){
1226 /* Ignore ORDER BY on zero-argument aggregates */
1227 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pOrderBy);
1228 return;
1230 if( IsWindowFunc(pExpr) ){
1231 sqlite3ExprOrderByAggregateError(pParse, pExpr);
1232 sqlite3ExprListDelete(db, pOrderBy);
1233 return;
1236 pOB = sqlite3ExprAlloc(db, TK_ORDER, 0, 0);
1237 if( pOB==0 ){
1238 sqlite3ExprListDelete(db, pOrderBy);
1239 return;
1241 pOB->x.pList = pOrderBy;
1242 assert( ExprUseXList(pOB) );
1243 pExpr->pLeft = pOB;
1244 ExprSetProperty(pOB, EP_FullSize);
1248 ** Check to see if a function is usable according to current access
1249 ** rules:
1251 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
1253 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
1254 ** top-level SQL
1256 ** If the function is not usable, create an error.
1258 void sqlite3ExprFunctionUsable(
1259 Parse *pParse, /* Parsing and code generating context */
1260 const Expr *pExpr, /* The function invocation */
1261 const FuncDef *pDef /* The function being invoked */
1263 assert( !IN_RENAME_OBJECT );
1264 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
1265 if( ExprHasProperty(pExpr, EP_FromDDL) ){
1266 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
1267 || (pParse->db->flags & SQLITE_TrustedSchema)==0
1269 /* Functions prohibited in triggers and views if:
1270 ** (1) tagged with SQLITE_DIRECTONLY
1271 ** (2) not tagged with SQLITE_INNOCUOUS (which means it
1272 ** is tagged with SQLITE_FUNC_UNSAFE) and
1273 ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
1274 ** that the schema is possibly tainted).
1276 sqlite3ErrorMsg(pParse, "unsafe use of %#T()", pExpr);
1282 ** Assign a variable number to an expression that encodes a wildcard
1283 ** in the original SQL statement.
1285 ** Wildcards consisting of a single "?" are assigned the next sequential
1286 ** variable number.
1288 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
1289 ** sure "nnn" is not too big to avoid a denial of service attack when
1290 ** the SQL statement comes from an external source.
1292 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
1293 ** as the previous instance of the same wildcard. Or if this is the first
1294 ** instance of the wildcard, the next sequential variable number is
1295 ** assigned.
1297 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
1298 sqlite3 *db = pParse->db;
1299 const char *z;
1300 ynVar x;
1302 if( pExpr==0 ) return;
1303 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
1304 z = pExpr->u.zToken;
1305 assert( z!=0 );
1306 assert( z[0]!=0 );
1307 assert( n==(u32)sqlite3Strlen30(z) );
1308 if( z[1]==0 ){
1309 /* Wildcard of the form "?". Assign the next variable number */
1310 assert( z[0]=='?' );
1311 x = (ynVar)(++pParse->nVar);
1312 }else{
1313 int doAdd = 0;
1314 if( z[0]=='?' ){
1315 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1316 ** use it as the variable number */
1317 i64 i;
1318 int bOk;
1319 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1320 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1321 bOk = 1;
1322 }else{
1323 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1325 testcase( i==0 );
1326 testcase( i==1 );
1327 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1328 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1329 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1330 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1331 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
1332 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1333 return;
1335 x = (ynVar)i;
1336 if( x>pParse->nVar ){
1337 pParse->nVar = (int)x;
1338 doAdd = 1;
1339 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1340 doAdd = 1;
1342 }else{
1343 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1344 ** number as the prior appearance of the same name, or if the name
1345 ** has never appeared before, reuse the same variable number
1347 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1348 if( x==0 ){
1349 x = (ynVar)(++pParse->nVar);
1350 doAdd = 1;
1353 if( doAdd ){
1354 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1357 pExpr->iColumn = x;
1358 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1359 sqlite3ErrorMsg(pParse, "too many SQL variables");
1360 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1365 ** Recursively delete an expression tree.
1367 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1368 assert( p!=0 );
1369 assert( db!=0 );
1370 assert( !ExprUseUValue(p) || p->u.iValue>=0 );
1371 assert( !ExprUseYWin(p) || !ExprUseYSub(p) );
1372 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
1373 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
1374 #ifdef SQLITE_DEBUG
1375 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1376 assert( p->pLeft==0 );
1377 assert( p->pRight==0 );
1378 assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
1379 assert( !ExprUseXList(p) || p->x.pList==0 );
1381 #endif
1382 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1383 /* The Expr.x union is never used at the same time as Expr.pRight */
1384 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
1385 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1386 if( p->pRight ){
1387 assert( !ExprHasProperty(p, EP_WinFunc) );
1388 sqlite3ExprDeleteNN(db, p->pRight);
1389 }else if( ExprUseXSelect(p) ){
1390 assert( !ExprHasProperty(p, EP_WinFunc) );
1391 sqlite3SelectDelete(db, p->x.pSelect);
1392 }else{
1393 sqlite3ExprListDelete(db, p->x.pList);
1394 #ifndef SQLITE_OMIT_WINDOWFUNC
1395 if( ExprHasProperty(p, EP_WinFunc) ){
1396 sqlite3WindowDelete(db, p->y.pWin);
1398 #endif
1401 if( !ExprHasProperty(p, EP_Static) ){
1402 sqlite3DbNNFreeNN(db, p);
1405 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1406 if( p ) sqlite3ExprDeleteNN(db, p);
1408 void sqlite3ExprDeleteGeneric(sqlite3 *db, void *p){
1409 if( ALWAYS(p) ) sqlite3ExprDeleteNN(db, (Expr*)p);
1413 ** Clear both elements of an OnOrUsing object
1415 void sqlite3ClearOnOrUsing(sqlite3 *db, OnOrUsing *p){
1416 if( p==0 ){
1417 /* Nothing to clear */
1418 }else if( p->pOn ){
1419 sqlite3ExprDeleteNN(db, p->pOn);
1420 }else if( p->pUsing ){
1421 sqlite3IdListDelete(db, p->pUsing);
1426 ** Arrange to cause pExpr to be deleted when the pParse is deleted.
1427 ** This is similar to sqlite3ExprDelete() except that the delete is
1428 ** deferred until the pParse is deleted.
1430 ** The pExpr might be deleted immediately on an OOM error.
1432 ** The deferred delete is (currently) implemented by adding the
1433 ** pExpr to the pParse->pConstExpr list with a register number of 0.
1435 void sqlite3ExprDeferredDelete(Parse *pParse, Expr *pExpr){
1436 sqlite3ParserAddCleanup(pParse, sqlite3ExprDeleteGeneric, pExpr);
1439 /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
1440 ** expression.
1442 void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
1443 if( p ){
1444 if( IN_RENAME_OBJECT ){
1445 sqlite3RenameExprUnmap(pParse, p);
1447 sqlite3ExprDeleteNN(pParse->db, p);
1452 ** Return the number of bytes allocated for the expression structure
1453 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1454 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1456 static int exprStructSize(const Expr *p){
1457 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1458 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1459 return EXPR_FULLSIZE;
1463 ** The dupedExpr*Size() routines each return the number of bytes required
1464 ** to store a copy of an expression or expression tree. They differ in
1465 ** how much of the tree is measured.
1467 ** dupedExprStructSize() Size of only the Expr structure
1468 ** dupedExprNodeSize() Size of Expr + space for token
1469 ** dupedExprSize() Expr + token + subtree components
1471 ***************************************************************************
1473 ** The dupedExprStructSize() function returns two values OR-ed together:
1474 ** (1) the space required for a copy of the Expr structure only and
1475 ** (2) the EP_xxx flags that indicate what the structure size should be.
1476 ** The return values is always one of:
1478 ** EXPR_FULLSIZE
1479 ** EXPR_REDUCEDSIZE | EP_Reduced
1480 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1482 ** The size of the structure can be found by masking the return value
1483 ** of this routine with 0xfff. The flags can be found by masking the
1484 ** return value with EP_Reduced|EP_TokenOnly.
1486 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1487 ** (unreduced) Expr objects as they or originally constructed by the parser.
1488 ** During expression analysis, extra information is computed and moved into
1489 ** later parts of the Expr object and that extra information might get chopped
1490 ** off if the expression is reduced. Note also that it does not work to
1491 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1492 ** to reduce a pristine expression tree from the parser. The implementation
1493 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1494 ** to enforce this constraint.
1496 static int dupedExprStructSize(const Expr *p, int flags){
1497 int nSize;
1498 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1499 assert( EXPR_FULLSIZE<=0xfff );
1500 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1501 if( 0==flags || ExprHasProperty(p, EP_FullSize) ){
1502 nSize = EXPR_FULLSIZE;
1503 }else{
1504 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1505 assert( !ExprHasProperty(p, EP_OuterON) );
1506 assert( !ExprHasVVAProperty(p, EP_NoReduce) );
1507 if( p->pLeft || p->x.pList ){
1508 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1509 }else{
1510 assert( p->pRight==0 );
1511 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1514 return nSize;
1518 ** This function returns the space in bytes required to store the copy
1519 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1520 ** string is defined.)
1522 static int dupedExprNodeSize(const Expr *p, int flags){
1523 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1524 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1525 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
1527 return ROUND8(nByte);
1531 ** Return the number of bytes required to create a duplicate of the
1532 ** expression passed as the first argument.
1534 ** The value returned includes space to create a copy of the Expr struct
1535 ** itself and the buffer referred to by Expr.u.zToken, if any.
1537 ** The return value includes space to duplicate all Expr nodes in the
1538 ** tree formed by Expr.pLeft and Expr.pRight, but not any other
1539 ** substructure such as Expr.x.pList, Expr.x.pSelect, and Expr.y.pWin.
1541 static int dupedExprSize(const Expr *p){
1542 int nByte;
1543 assert( p!=0 );
1544 nByte = dupedExprNodeSize(p, EXPRDUP_REDUCE);
1545 if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
1546 if( p->pRight ) nByte += dupedExprSize(p->pRight);
1547 assert( nByte==ROUND8(nByte) );
1548 return nByte;
1552 ** An EdupBuf is a memory allocation used to stored multiple Expr objects
1553 ** together with their Expr.zToken content. This is used to help implement
1554 ** compression while doing sqlite3ExprDup(). The top-level Expr does the
1555 ** allocation for itself and many of its decendents, then passes an instance
1556 ** of the structure down into exprDup() so that they decendents can have
1557 ** access to that memory.
1559 typedef struct EdupBuf EdupBuf;
1560 struct EdupBuf {
1561 u8 *zAlloc; /* Memory space available for storage */
1562 #ifdef SQLITE_DEBUG
1563 u8 *zEnd; /* First byte past the end of memory */
1564 #endif
1568 ** This function is similar to sqlite3ExprDup(), except that if pEdupBuf
1569 ** is not NULL then it points to memory that can be used to store a copy
1570 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf
1571 ** is updated with the new buffer tail prior to returning.
1573 static Expr *exprDup(
1574 sqlite3 *db, /* Database connection (for memory allocation) */
1575 const Expr *p, /* Expr tree to be duplicated */
1576 int dupFlags, /* EXPRDUP_REDUCE for compression. 0 if not */
1577 EdupBuf *pEdupBuf /* Preallocated storage space, or NULL */
1579 Expr *pNew; /* Value to return */
1580 EdupBuf sEdupBuf; /* Memory space from which to build Expr object */
1581 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1582 int nToken = -1; /* Space needed for p->u.zToken. -1 means unknown */
1584 assert( db!=0 );
1585 assert( p );
1586 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1587 assert( pEdupBuf==0 || dupFlags==EXPRDUP_REDUCE );
1589 /* Figure out where to write the new Expr structure. */
1590 if( pEdupBuf ){
1591 sEdupBuf.zAlloc = pEdupBuf->zAlloc;
1592 #ifdef SQLITE_DEBUG
1593 sEdupBuf.zEnd = pEdupBuf->zEnd;
1594 #endif
1595 staticFlag = EP_Static;
1596 assert( sEdupBuf.zAlloc!=0 );
1597 assert( dupFlags==EXPRDUP_REDUCE );
1598 }else{
1599 int nAlloc;
1600 if( dupFlags ){
1601 nAlloc = dupedExprSize(p);
1602 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1603 nToken = sqlite3Strlen30NN(p->u.zToken)+1;
1604 nAlloc = ROUND8(EXPR_FULLSIZE + nToken);
1605 }else{
1606 nToken = 0;
1607 nAlloc = ROUND8(EXPR_FULLSIZE);
1609 assert( nAlloc==ROUND8(nAlloc) );
1610 sEdupBuf.zAlloc = sqlite3DbMallocRawNN(db, nAlloc);
1611 #ifdef SQLITE_DEBUG
1612 sEdupBuf.zEnd = sEdupBuf.zAlloc ? sEdupBuf.zAlloc+nAlloc : 0;
1613 #endif
1615 staticFlag = 0;
1617 pNew = (Expr *)sEdupBuf.zAlloc;
1618 assert( EIGHT_BYTE_ALIGNMENT(pNew) );
1620 if( pNew ){
1621 /* Set nNewSize to the size allocated for the structure pointed to
1622 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1623 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1624 ** by the copy of the p->u.zToken string (if any).
1626 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1627 int nNewSize = nStructSize & 0xfff;
1628 if( nToken<0 ){
1629 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1630 nToken = sqlite3Strlen30(p->u.zToken) + 1;
1631 }else{
1632 nToken = 0;
1635 if( dupFlags ){
1636 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken );
1637 assert( ExprHasProperty(p, EP_Reduced)==0 );
1638 memcpy(sEdupBuf.zAlloc, p, nNewSize);
1639 }else{
1640 u32 nSize = (u32)exprStructSize(p);
1641 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >=
1642 (int)EXPR_FULLSIZE+nToken );
1643 memcpy(sEdupBuf.zAlloc, p, nSize);
1644 if( nSize<EXPR_FULLSIZE ){
1645 memset(&sEdupBuf.zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1647 nNewSize = EXPR_FULLSIZE;
1650 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1651 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
1652 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1653 pNew->flags |= staticFlag;
1654 ExprClearVVAProperties(pNew);
1655 if( dupFlags ){
1656 ExprSetVVAProperty(pNew, EP_Immutable);
1659 /* Copy the p->u.zToken string, if any. */
1660 assert( nToken>=0 );
1661 if( nToken>0 ){
1662 char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize];
1663 memcpy(zToken, p->u.zToken, nToken);
1664 nNewSize += nToken;
1666 sEdupBuf.zAlloc += ROUND8(nNewSize);
1668 if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){
1670 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1671 if( ExprUseXSelect(p) ){
1672 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1673 }else{
1674 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList,
1675 p->op!=TK_ORDER ? dupFlags : 0);
1678 #ifndef SQLITE_OMIT_WINDOWFUNC
1679 if( ExprHasProperty(p, EP_WinFunc) ){
1680 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
1681 assert( ExprHasProperty(pNew, EP_WinFunc) );
1683 #endif /* SQLITE_OMIT_WINDOWFUNC */
1685 /* Fill in pNew->pLeft and pNew->pRight. */
1686 if( dupFlags ){
1687 if( p->op==TK_SELECT_COLUMN ){
1688 pNew->pLeft = p->pLeft;
1689 assert( p->pRight==0
1690 || p->pRight==p->pLeft
1691 || ExprHasProperty(p->pLeft, EP_Subquery) );
1692 }else{
1693 pNew->pLeft = p->pLeft ?
1694 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0;
1696 pNew->pRight = p->pRight ?
1697 exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0;
1698 }else{
1699 if( p->op==TK_SELECT_COLUMN ){
1700 pNew->pLeft = p->pLeft;
1701 assert( p->pRight==0
1702 || p->pRight==p->pLeft
1703 || ExprHasProperty(p->pLeft, EP_Subquery) );
1704 }else{
1705 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1707 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1711 if( pEdupBuf ) memcpy(pEdupBuf, &sEdupBuf, sizeof(sEdupBuf));
1712 assert( sEdupBuf.zAlloc <= sEdupBuf.zEnd );
1713 return pNew;
1717 ** Create and return a deep copy of the object passed as the second
1718 ** argument. If an OOM condition is encountered, NULL is returned
1719 ** and the db->mallocFailed flag set.
1721 #ifndef SQLITE_OMIT_CTE
1722 With *sqlite3WithDup(sqlite3 *db, With *p){
1723 With *pRet = 0;
1724 if( p ){
1725 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1726 pRet = sqlite3DbMallocZero(db, nByte);
1727 if( pRet ){
1728 int i;
1729 pRet->nCte = p->nCte;
1730 for(i=0; i<p->nCte; i++){
1731 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1732 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1733 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1734 pRet->a[i].eM10d = p->a[i].eM10d;
1738 return pRet;
1740 #else
1741 # define sqlite3WithDup(x,y) 0
1742 #endif
1744 #ifndef SQLITE_OMIT_WINDOWFUNC
1746 ** The gatherSelectWindows() procedure and its helper routine
1747 ** gatherSelectWindowsCallback() are used to scan all the expressions
1748 ** an a newly duplicated SELECT statement and gather all of the Window
1749 ** objects found there, assembling them onto the linked list at Select->pWin.
1751 static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
1752 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
1753 Select *pSelect = pWalker->u.pSelect;
1754 Window *pWin = pExpr->y.pWin;
1755 assert( pWin );
1756 assert( IsWindowFunc(pExpr) );
1757 assert( pWin->ppThis==0 );
1758 sqlite3WindowLink(pSelect, pWin);
1760 return WRC_Continue;
1762 static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
1763 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
1765 static void gatherSelectWindows(Select *p){
1766 Walker w;
1767 w.xExprCallback = gatherSelectWindowsCallback;
1768 w.xSelectCallback = gatherSelectWindowsSelectCallback;
1769 w.xSelectCallback2 = 0;
1770 w.pParse = 0;
1771 w.u.pSelect = p;
1772 sqlite3WalkSelect(&w, p);
1774 #endif
1778 ** The following group of routines make deep copies of expressions,
1779 ** expression lists, ID lists, and select statements. The copies can
1780 ** be deleted (by being passed to their respective ...Delete() routines)
1781 ** without effecting the originals.
1783 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1784 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1785 ** by subsequent calls to sqlite*ListAppend() routines.
1787 ** Any tables that the SrcList might point to are not duplicated.
1789 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1790 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1791 ** truncated version of the usual Expr structure that will be stored as
1792 ** part of the in-memory representation of the database schema.
1794 Expr *sqlite3ExprDup(sqlite3 *db, const Expr *p, int flags){
1795 assert( flags==0 || flags==EXPRDUP_REDUCE );
1796 return p ? exprDup(db, p, flags, 0) : 0;
1798 ExprList *sqlite3ExprListDup(sqlite3 *db, const ExprList *p, int flags){
1799 ExprList *pNew;
1800 struct ExprList_item *pItem;
1801 const struct ExprList_item *pOldItem;
1802 int i;
1803 Expr *pPriorSelectColOld = 0;
1804 Expr *pPriorSelectColNew = 0;
1805 assert( db!=0 );
1806 if( p==0 ) return 0;
1807 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
1808 if( pNew==0 ) return 0;
1809 pNew->nExpr = p->nExpr;
1810 pNew->nAlloc = p->nAlloc;
1811 pItem = pNew->a;
1812 pOldItem = p->a;
1813 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1814 Expr *pOldExpr = pOldItem->pExpr;
1815 Expr *pNewExpr;
1816 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1817 if( pOldExpr
1818 && pOldExpr->op==TK_SELECT_COLUMN
1819 && (pNewExpr = pItem->pExpr)!=0
1821 if( pNewExpr->pRight ){
1822 pPriorSelectColOld = pOldExpr->pRight;
1823 pPriorSelectColNew = pNewExpr->pRight;
1824 pNewExpr->pLeft = pNewExpr->pRight;
1825 }else{
1826 if( pOldExpr->pLeft!=pPriorSelectColOld ){
1827 pPriorSelectColOld = pOldExpr->pLeft;
1828 pPriorSelectColNew = sqlite3ExprDup(db, pPriorSelectColOld, flags);
1829 pNewExpr->pRight = pPriorSelectColNew;
1831 pNewExpr->pLeft = pPriorSelectColNew;
1834 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
1835 pItem->fg = pOldItem->fg;
1836 pItem->fg.done = 0;
1837 pItem->u = pOldItem->u;
1839 return pNew;
1843 ** If cursors, triggers, views and subqueries are all omitted from
1844 ** the build, then none of the following routines, except for
1845 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1846 ** called with a NULL argument.
1848 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1849 || !defined(SQLITE_OMIT_SUBQUERY)
1850 SrcList *sqlite3SrcListDup(sqlite3 *db, const SrcList *p, int flags){
1851 SrcList *pNew;
1852 int i;
1853 int nByte;
1854 assert( db!=0 );
1855 if( p==0 ) return 0;
1856 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1857 pNew = sqlite3DbMallocRawNN(db, nByte );
1858 if( pNew==0 ) return 0;
1859 pNew->nSrc = pNew->nAlloc = p->nSrc;
1860 for(i=0; i<p->nSrc; i++){
1861 SrcItem *pNewItem = &pNew->a[i];
1862 const SrcItem *pOldItem = &p->a[i];
1863 Table *pTab;
1864 pNewItem->pSchema = pOldItem->pSchema;
1865 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1866 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1867 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1868 pNewItem->fg = pOldItem->fg;
1869 pNewItem->iCursor = pOldItem->iCursor;
1870 pNewItem->addrFillSub = pOldItem->addrFillSub;
1871 pNewItem->regReturn = pOldItem->regReturn;
1872 pNewItem->regResult = pOldItem->regResult;
1873 if( pNewItem->fg.isIndexedBy ){
1874 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1876 pNewItem->u2 = pOldItem->u2;
1877 if( pNewItem->fg.isCte ){
1878 pNewItem->u2.pCteUse->nUse++;
1880 if( pNewItem->fg.isTabFunc ){
1881 pNewItem->u1.pFuncArg =
1882 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1884 pTab = pNewItem->pTab = pOldItem->pTab;
1885 if( pTab ){
1886 pTab->nTabRef++;
1888 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1889 if( pOldItem->fg.isUsing ){
1890 assert( pNewItem->fg.isUsing );
1891 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
1892 }else{
1893 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
1895 pNewItem->colUsed = pOldItem->colUsed;
1897 return pNew;
1899 IdList *sqlite3IdListDup(sqlite3 *db, const IdList *p){
1900 IdList *pNew;
1901 int i;
1902 assert( db!=0 );
1903 if( p==0 ) return 0;
1904 assert( p->eU4!=EU4_EXPR );
1905 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );
1906 if( pNew==0 ) return 0;
1907 pNew->nId = p->nId;
1908 pNew->eU4 = p->eU4;
1909 for(i=0; i<p->nId; i++){
1910 struct IdList_item *pNewItem = &pNew->a[i];
1911 const struct IdList_item *pOldItem = &p->a[i];
1912 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1913 pNewItem->u4 = pOldItem->u4;
1915 return pNew;
1917 Select *sqlite3SelectDup(sqlite3 *db, const Select *pDup, int flags){
1918 Select *pRet = 0;
1919 Select *pNext = 0;
1920 Select **pp = &pRet;
1921 const Select *p;
1923 assert( db!=0 );
1924 for(p=pDup; p; p=p->pPrior){
1925 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1926 if( pNew==0 ) break;
1927 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1928 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1929 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1930 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1931 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1932 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1933 pNew->op = p->op;
1934 pNew->pNext = pNext;
1935 pNew->pPrior = 0;
1936 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1937 pNew->iLimit = 0;
1938 pNew->iOffset = 0;
1939 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1940 pNew->addrOpenEphm[0] = -1;
1941 pNew->addrOpenEphm[1] = -1;
1942 pNew->nSelectRow = p->nSelectRow;
1943 pNew->pWith = sqlite3WithDup(db, p->pWith);
1944 #ifndef SQLITE_OMIT_WINDOWFUNC
1945 pNew->pWin = 0;
1946 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
1947 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
1948 #endif
1949 pNew->selId = p->selId;
1950 if( db->mallocFailed ){
1951 /* Any prior OOM might have left the Select object incomplete.
1952 ** Delete the whole thing rather than allow an incomplete Select
1953 ** to be used by the code generator. */
1954 pNew->pNext = 0;
1955 sqlite3SelectDelete(db, pNew);
1956 break;
1958 *pp = pNew;
1959 pp = &pNew->pPrior;
1960 pNext = pNew;
1963 return pRet;
1965 #else
1966 Select *sqlite3SelectDup(sqlite3 *db, const Select *p, int flags){
1967 assert( p==0 );
1968 return 0;
1970 #endif
1974 ** Add a new element to the end of an expression list. If pList is
1975 ** initially NULL, then create a new expression list.
1977 ** The pList argument must be either NULL or a pointer to an ExprList
1978 ** obtained from a prior call to sqlite3ExprListAppend().
1980 ** If a memory allocation error occurs, the entire list is freed and
1981 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1982 ** that the new entry was successfully appended.
1984 static const struct ExprList_item zeroItem = {0};
1985 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendNew(
1986 sqlite3 *db, /* Database handle. Used for memory allocation */
1987 Expr *pExpr /* Expression to be appended. Might be NULL */
1989 struct ExprList_item *pItem;
1990 ExprList *pList;
1992 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
1993 if( pList==0 ){
1994 sqlite3ExprDelete(db, pExpr);
1995 return 0;
1997 pList->nAlloc = 4;
1998 pList->nExpr = 1;
1999 pItem = &pList->a[0];
2000 *pItem = zeroItem;
2001 pItem->pExpr = pExpr;
2002 return pList;
2004 SQLITE_NOINLINE ExprList *sqlite3ExprListAppendGrow(
2005 sqlite3 *db, /* Database handle. Used for memory allocation */
2006 ExprList *pList, /* List to which to append. Might be NULL */
2007 Expr *pExpr /* Expression to be appended. Might be NULL */
2009 struct ExprList_item *pItem;
2010 ExprList *pNew;
2011 pList->nAlloc *= 2;
2012 pNew = sqlite3DbRealloc(db, pList,
2013 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
2014 if( pNew==0 ){
2015 sqlite3ExprListDelete(db, pList);
2016 sqlite3ExprDelete(db, pExpr);
2017 return 0;
2018 }else{
2019 pList = pNew;
2021 pItem = &pList->a[pList->nExpr++];
2022 *pItem = zeroItem;
2023 pItem->pExpr = pExpr;
2024 return pList;
2026 ExprList *sqlite3ExprListAppend(
2027 Parse *pParse, /* Parsing context */
2028 ExprList *pList, /* List to which to append. Might be NULL */
2029 Expr *pExpr /* Expression to be appended. Might be NULL */
2031 struct ExprList_item *pItem;
2032 if( pList==0 ){
2033 return sqlite3ExprListAppendNew(pParse->db,pExpr);
2035 if( pList->nAlloc<pList->nExpr+1 ){
2036 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
2038 pItem = &pList->a[pList->nExpr++];
2039 *pItem = zeroItem;
2040 pItem->pExpr = pExpr;
2041 return pList;
2045 ** pColumns and pExpr form a vector assignment which is part of the SET
2046 ** clause of an UPDATE statement. Like this:
2048 ** (a,b,c) = (expr1,expr2,expr3)
2049 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
2051 ** For each term of the vector assignment, append new entries to the
2052 ** expression list pList. In the case of a subquery on the RHS, append
2053 ** TK_SELECT_COLUMN expressions.
2055 ExprList *sqlite3ExprListAppendVector(
2056 Parse *pParse, /* Parsing context */
2057 ExprList *pList, /* List to which to append. Might be NULL */
2058 IdList *pColumns, /* List of names of LHS of the assignment */
2059 Expr *pExpr /* Vector expression to be appended. Might be NULL */
2061 sqlite3 *db = pParse->db;
2062 int n;
2063 int i;
2064 int iFirst = pList ? pList->nExpr : 0;
2065 /* pColumns can only be NULL due to an OOM but an OOM will cause an
2066 ** exit prior to this routine being invoked */
2067 if( NEVER(pColumns==0) ) goto vector_append_error;
2068 if( pExpr==0 ) goto vector_append_error;
2070 /* If the RHS is a vector, then we can immediately check to see that
2071 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
2072 ** wildcards ("*") in the result set of the SELECT must be expanded before
2073 ** we can do the size check, so defer the size check until code generation.
2075 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
2076 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
2077 pColumns->nId, n);
2078 goto vector_append_error;
2081 for(i=0; i<pColumns->nId; i++){
2082 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
2083 assert( pSubExpr!=0 || db->mallocFailed );
2084 if( pSubExpr==0 ) continue;
2085 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
2086 if( pList ){
2087 assert( pList->nExpr==iFirst+i+1 );
2088 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
2089 pColumns->a[i].zName = 0;
2093 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
2094 Expr *pFirst = pList->a[iFirst].pExpr;
2095 assert( pFirst!=0 );
2096 assert( pFirst->op==TK_SELECT_COLUMN );
2098 /* Store the SELECT statement in pRight so it will be deleted when
2099 ** sqlite3ExprListDelete() is called */
2100 pFirst->pRight = pExpr;
2101 pExpr = 0;
2103 /* Remember the size of the LHS in iTable so that we can check that
2104 ** the RHS and LHS sizes match during code generation. */
2105 pFirst->iTable = pColumns->nId;
2108 vector_append_error:
2109 sqlite3ExprUnmapAndDelete(pParse, pExpr);
2110 sqlite3IdListDelete(db, pColumns);
2111 return pList;
2115 ** Set the sort order for the last element on the given ExprList.
2117 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
2118 struct ExprList_item *pItem;
2119 if( p==0 ) return;
2120 assert( p->nExpr>0 );
2122 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
2123 assert( iSortOrder==SQLITE_SO_UNDEFINED
2124 || iSortOrder==SQLITE_SO_ASC
2125 || iSortOrder==SQLITE_SO_DESC
2127 assert( eNulls==SQLITE_SO_UNDEFINED
2128 || eNulls==SQLITE_SO_ASC
2129 || eNulls==SQLITE_SO_DESC
2132 pItem = &p->a[p->nExpr-1];
2133 assert( pItem->fg.bNulls==0 );
2134 if( iSortOrder==SQLITE_SO_UNDEFINED ){
2135 iSortOrder = SQLITE_SO_ASC;
2137 pItem->fg.sortFlags = (u8)iSortOrder;
2139 if( eNulls!=SQLITE_SO_UNDEFINED ){
2140 pItem->fg.bNulls = 1;
2141 if( iSortOrder!=eNulls ){
2142 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
2148 ** Set the ExprList.a[].zEName element of the most recently added item
2149 ** on the expression list.
2151 ** pList might be NULL following an OOM error. But pName should never be
2152 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2153 ** is set.
2155 void sqlite3ExprListSetName(
2156 Parse *pParse, /* Parsing context */
2157 ExprList *pList, /* List to which to add the span. */
2158 const Token *pName, /* Name to be added */
2159 int dequote /* True to cause the name to be dequoted */
2161 assert( pList!=0 || pParse->db->mallocFailed!=0 );
2162 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
2163 if( pList ){
2164 struct ExprList_item *pItem;
2165 assert( pList->nExpr>0 );
2166 pItem = &pList->a[pList->nExpr-1];
2167 assert( pItem->zEName==0 );
2168 assert( pItem->fg.eEName==ENAME_NAME );
2169 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
2170 if( dequote ){
2171 /* If dequote==0, then pName->z does not point to part of a DDL
2172 ** statement handled by the parser. And so no token need be added
2173 ** to the token-map. */
2174 sqlite3Dequote(pItem->zEName);
2175 if( IN_RENAME_OBJECT ){
2176 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
2183 ** Set the ExprList.a[].zSpan element of the most recently added item
2184 ** on the expression list.
2186 ** pList might be NULL following an OOM error. But pSpan should never be
2187 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
2188 ** is set.
2190 void sqlite3ExprListSetSpan(
2191 Parse *pParse, /* Parsing context */
2192 ExprList *pList, /* List to which to add the span. */
2193 const char *zStart, /* Start of the span */
2194 const char *zEnd /* End of the span */
2196 sqlite3 *db = pParse->db;
2197 assert( pList!=0 || db->mallocFailed!=0 );
2198 if( pList ){
2199 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
2200 assert( pList->nExpr>0 );
2201 if( pItem->zEName==0 ){
2202 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
2203 pItem->fg.eEName = ENAME_SPAN;
2209 ** If the expression list pEList contains more than iLimit elements,
2210 ** leave an error message in pParse.
2212 void sqlite3ExprListCheckLength(
2213 Parse *pParse,
2214 ExprList *pEList,
2215 const char *zObject
2217 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
2218 testcase( pEList && pEList->nExpr==mx );
2219 testcase( pEList && pEList->nExpr==mx+1 );
2220 if( pEList && pEList->nExpr>mx ){
2221 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
2226 ** Delete an entire expression list.
2228 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
2229 int i = pList->nExpr;
2230 struct ExprList_item *pItem = pList->a;
2231 assert( pList->nExpr>0 );
2232 assert( db!=0 );
2234 sqlite3ExprDelete(db, pItem->pExpr);
2235 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
2236 pItem++;
2237 }while( --i>0 );
2238 sqlite3DbNNFreeNN(db, pList);
2240 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
2241 if( pList ) exprListDeleteNN(db, pList);
2243 void sqlite3ExprListDeleteGeneric(sqlite3 *db, void *pList){
2244 if( ALWAYS(pList) ) exprListDeleteNN(db, (ExprList*)pList);
2248 ** Return the bitwise-OR of all Expr.flags fields in the given
2249 ** ExprList.
2251 u32 sqlite3ExprListFlags(const ExprList *pList){
2252 int i;
2253 u32 m = 0;
2254 assert( pList!=0 );
2255 for(i=0; i<pList->nExpr; i++){
2256 Expr *pExpr = pList->a[i].pExpr;
2257 assert( pExpr!=0 );
2258 m |= pExpr->flags;
2260 return m;
2264 ** This is a SELECT-node callback for the expression walker that
2265 ** always "fails". By "fail" in this case, we mean set
2266 ** pWalker->eCode to zero and abort.
2268 ** This callback is used by multiple expression walkers.
2270 int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
2271 UNUSED_PARAMETER(NotUsed);
2272 pWalker->eCode = 0;
2273 return WRC_Abort;
2277 ** Check the input string to see if it is "true" or "false" (in any case).
2279 ** If the string is.... Return
2280 ** "true" EP_IsTrue
2281 ** "false" EP_IsFalse
2282 ** anything else 0
2284 u32 sqlite3IsTrueOrFalse(const char *zIn){
2285 if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
2286 if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
2287 return 0;
2292 ** If the input expression is an ID with the name "true" or "false"
2293 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
2294 ** the conversion happened, and zero if the expression is unaltered.
2296 int sqlite3ExprIdToTrueFalse(Expr *pExpr){
2297 u32 v;
2298 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
2299 if( !ExprHasProperty(pExpr, EP_Quoted|EP_IntValue)
2300 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
2302 pExpr->op = TK_TRUEFALSE;
2303 ExprSetProperty(pExpr, v);
2304 return 1;
2306 return 0;
2310 ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
2311 ** and 0 if it is FALSE.
2313 int sqlite3ExprTruthValue(const Expr *pExpr){
2314 pExpr = sqlite3ExprSkipCollateAndLikely((Expr*)pExpr);
2315 assert( pExpr->op==TK_TRUEFALSE );
2316 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2317 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
2318 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
2319 return pExpr->u.zToken[4]==0;
2323 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
2324 ** terms that are always true or false. Return the simplified expression.
2325 ** Or return the original expression if no simplification is possible.
2327 ** Examples:
2329 ** (x<10) AND true => (x<10)
2330 ** (x<10) AND false => false
2331 ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
2332 ** (x<10) AND (y=22 OR true) => (x<10)
2333 ** (y=22) OR true => true
2335 Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
2336 assert( pExpr!=0 );
2337 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
2338 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
2339 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
2340 if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
2341 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
2342 }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
2343 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
2346 return pExpr;
2351 ** These routines are Walker callbacks used to check expressions to
2352 ** see if they are "constant" for some definition of constant. The
2353 ** Walker.eCode value determines the type of "constant" we are looking
2354 ** for.
2356 ** These callback routines are used to implement the following:
2358 ** sqlite3ExprIsConstant() pWalker->eCode==1
2359 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
2360 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
2361 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
2363 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
2364 ** is found to not be a constant.
2366 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
2367 ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
2368 ** when parsing an existing schema out of the sqlite_schema table and 4
2369 ** when processing a new CREATE TABLE statement. A bound parameter raises
2370 ** an error for new statements, but is silently converted
2371 ** to NULL for existing schemas. This allows sqlite_schema tables that
2372 ** contain a bound parameter because they were generated by older versions
2373 ** of SQLite to be parsed by newer versions of SQLite without raising a
2374 ** malformed schema error.
2376 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
2378 /* If pWalker->eCode is 2 then any term of the expression that comes from
2379 ** the ON or USING clauses of an outer join disqualifies the expression
2380 ** from being considered constant. */
2381 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
2382 pWalker->eCode = 0;
2383 return WRC_Abort;
2386 switch( pExpr->op ){
2387 /* Consider functions to be constant if all their arguments are constant
2388 ** and either pWalker->eCode==4 or 5 or the function has the
2389 ** SQLITE_FUNC_CONST flag. */
2390 case TK_FUNCTION:
2391 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
2392 && !ExprHasProperty(pExpr, EP_WinFunc)
2394 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
2395 return WRC_Continue;
2396 }else{
2397 pWalker->eCode = 0;
2398 return WRC_Abort;
2400 case TK_ID:
2401 /* Convert "true" or "false" in a DEFAULT clause into the
2402 ** appropriate TK_TRUEFALSE operator */
2403 if( sqlite3ExprIdToTrueFalse(pExpr) ){
2404 return WRC_Prune;
2406 /* no break */ deliberate_fall_through
2407 case TK_COLUMN:
2408 case TK_AGG_FUNCTION:
2409 case TK_AGG_COLUMN:
2410 testcase( pExpr->op==TK_ID );
2411 testcase( pExpr->op==TK_COLUMN );
2412 testcase( pExpr->op==TK_AGG_FUNCTION );
2413 testcase( pExpr->op==TK_AGG_COLUMN );
2414 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
2415 return WRC_Continue;
2417 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
2418 return WRC_Continue;
2420 /* no break */ deliberate_fall_through
2421 case TK_IF_NULL_ROW:
2422 case TK_REGISTER:
2423 case TK_DOT:
2424 testcase( pExpr->op==TK_REGISTER );
2425 testcase( pExpr->op==TK_IF_NULL_ROW );
2426 testcase( pExpr->op==TK_DOT );
2427 pWalker->eCode = 0;
2428 return WRC_Abort;
2429 case TK_VARIABLE:
2430 if( pWalker->eCode==5 ){
2431 /* Silently convert bound parameters that appear inside of CREATE
2432 ** statements into a NULL when parsing the CREATE statement text out
2433 ** of the sqlite_schema table */
2434 pExpr->op = TK_NULL;
2435 }else if( pWalker->eCode==4 ){
2436 /* A bound parameter in a CREATE statement that originates from
2437 ** sqlite3_prepare() causes an error */
2438 pWalker->eCode = 0;
2439 return WRC_Abort;
2441 /* no break */ deliberate_fall_through
2442 default:
2443 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
2444 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
2445 return WRC_Continue;
2448 static int exprIsConst(Expr *p, int initFlag, int iCur){
2449 Walker w;
2450 w.eCode = initFlag;
2451 w.xExprCallback = exprNodeIsConstant;
2452 w.xSelectCallback = sqlite3SelectWalkFail;
2453 #ifdef SQLITE_DEBUG
2454 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2455 #endif
2456 w.u.iCur = iCur;
2457 sqlite3WalkExpr(&w, p);
2458 return w.eCode;
2462 ** Walk an expression tree. Return non-zero if the expression is constant
2463 ** and 0 if it involves variables or function calls.
2465 ** For the purposes of this function, a double-quoted string (ex: "abc")
2466 ** is considered a variable but a single-quoted string (ex: 'abc') is
2467 ** a constant.
2469 int sqlite3ExprIsConstant(Expr *p){
2470 return exprIsConst(p, 1, 0);
2474 ** Walk an expression tree. Return non-zero if
2476 ** (1) the expression is constant, and
2477 ** (2) the expression does originate in the ON or USING clause
2478 ** of a LEFT JOIN, and
2479 ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2480 ** operands created by the constant propagation optimization.
2482 ** When this routine returns true, it indicates that the expression
2483 ** can be added to the pParse->pConstExpr list and evaluated once when
2484 ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
2486 int sqlite3ExprIsConstantNotJoin(Expr *p){
2487 return exprIsConst(p, 2, 0);
2491 ** Walk an expression tree. Return non-zero if the expression is constant
2492 ** for any single row of the table with cursor iCur. In other words, the
2493 ** expression must not refer to any non-deterministic function nor any
2494 ** table other than iCur.
2496 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2497 return exprIsConst(p, 3, iCur);
2501 ** Check pExpr to see if it is an constraint on the single data source
2502 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
2503 ** constrains pSrc but does not depend on any other tables or data
2504 ** sources anywhere else in the query. Return true (non-zero) if pExpr
2505 ** is a constraint on pSrc only.
2507 ** This is an optimization. False negatives will perhaps cause slower
2508 ** queries, but false positives will yield incorrect answers. So when in
2509 ** doubt, return 0.
2511 ** To be an single-source constraint, the following must be true:
2513 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
2515 ** (2) pExpr cannot use subqueries or non-deterministic functions.
2517 ** (3) pSrc cannot be part of the left operand for a RIGHT JOIN.
2518 ** (Is there some way to relax this constraint?)
2520 ** (4) If pSrc is the right operand of a LEFT JOIN, then...
2521 ** (4a) pExpr must come from an ON clause..
2522 ** (4b) and specifically the ON clause associated with the LEFT JOIN.
2524 ** (5) If pSrc is not the right operand of a LEFT JOIN or the left
2525 ** operand of a RIGHT JOIN, then pExpr must be from the WHERE
2526 ** clause, not an ON clause.
2528 ** (6) Either:
2530 ** (6a) pExpr does not originate in an ON or USING clause, or
2532 ** (6b) The ON or USING clause from which pExpr is derived is
2533 ** not to the left of a RIGHT JOIN (or FULL JOIN).
2535 ** Without this restriction, accepting pExpr as a single-table
2536 ** constraint might move the the ON/USING filter expression
2537 ** from the left side of a RIGHT JOIN over to the right side,
2538 ** which leads to incorrect answers. See also restriction (9)
2539 ** on push-down.
2541 int sqlite3ExprIsSingleTableConstraint(
2542 Expr *pExpr, /* The constraint */
2543 const SrcList *pSrcList, /* Complete FROM clause */
2544 int iSrc /* Which element of pSrcList to use */
2546 const SrcItem *pSrc = &pSrcList->a[iSrc];
2547 if( pSrc->fg.jointype & JT_LTORJ ){
2548 return 0; /* rule (3) */
2550 if( pSrc->fg.jointype & JT_LEFT ){
2551 if( !ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (4a) */
2552 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */
2553 }else{
2554 if( ExprHasProperty(pExpr, EP_OuterON) ) return 0; /* rule (5) */
2556 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON) /* (6a) */
2557 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */
2559 int jj;
2560 for(jj=0; jj<iSrc; jj++){
2561 if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
2562 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
2563 return 0; /* restriction (6) */
2565 break;
2569 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor); /* rules (1), (2) */
2574 ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2576 static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2577 ExprList *pGroupBy = pWalker->u.pGroupBy;
2578 int i;
2580 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2581 ** it constant. */
2582 for(i=0; i<pGroupBy->nExpr; i++){
2583 Expr *p = pGroupBy->a[i].pExpr;
2584 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
2585 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
2586 if( sqlite3IsBinary(pColl) ){
2587 return WRC_Prune;
2592 /* Check if pExpr is a sub-select. If so, consider it variable. */
2593 if( ExprUseXSelect(pExpr) ){
2594 pWalker->eCode = 0;
2595 return WRC_Abort;
2598 return exprNodeIsConstant(pWalker, pExpr);
2602 ** Walk the expression tree passed as the first argument. Return non-zero
2603 ** if the expression consists entirely of constants or copies of terms
2604 ** in pGroupBy that sort with the BINARY collation sequence.
2606 ** This routine is used to determine if a term of the HAVING clause can
2607 ** be promoted into the WHERE clause. In order for such a promotion to work,
2608 ** the value of the HAVING clause term must be the same for all members of
2609 ** a "group". The requirement that the GROUP BY term must be BINARY
2610 ** assumes that no other collating sequence will have a finer-grained
2611 ** grouping than binary. In other words (A=B COLLATE binary) implies
2612 ** A=B in every other collating sequence. The requirement that the
2613 ** GROUP BY be BINARY is stricter than necessary. It would also work
2614 ** to promote HAVING clauses that use the same alternative collating
2615 ** sequence as the GROUP BY term, but that is much harder to check,
2616 ** alternative collating sequences are uncommon, and this is only an
2617 ** optimization, so we take the easy way out and simply require the
2618 ** GROUP BY to use the BINARY collating sequence.
2620 int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2621 Walker w;
2622 w.eCode = 1;
2623 w.xExprCallback = exprNodeIsConstantOrGroupBy;
2624 w.xSelectCallback = 0;
2625 w.u.pGroupBy = pGroupBy;
2626 w.pParse = pParse;
2627 sqlite3WalkExpr(&w, p);
2628 return w.eCode;
2632 ** Walk an expression tree for the DEFAULT field of a column definition
2633 ** in a CREATE TABLE statement. Return non-zero if the expression is
2634 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
2635 ** the expression is constant or a function call with constant arguments.
2636 ** Return and 0 if there are any variables.
2638 ** isInit is true when parsing from sqlite_schema. isInit is false when
2639 ** processing a new CREATE TABLE statement. When isInit is true, parameters
2640 ** (such as ? or $abc) in the expression are converted into NULL. When
2641 ** isInit is false, parameters raise an error. Parameters should not be
2642 ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
2643 ** allowed it, so we need to support it when reading sqlite_schema for
2644 ** backwards compatibility.
2646 ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
2648 ** For the purposes of this function, a double-quoted string (ex: "abc")
2649 ** is considered a variable but a single-quoted string (ex: 'abc') is
2650 ** a constant.
2652 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2653 assert( isInit==0 || isInit==1 );
2654 return exprIsConst(p, 4+isInit, 0);
2657 #ifdef SQLITE_ENABLE_CURSOR_HINTS
2659 ** Walk an expression tree. Return 1 if the expression contains a
2660 ** subquery of some kind. Return 0 if there are no subqueries.
2662 int sqlite3ExprContainsSubquery(Expr *p){
2663 Walker w;
2664 w.eCode = 1;
2665 w.xExprCallback = sqlite3ExprWalkNoop;
2666 w.xSelectCallback = sqlite3SelectWalkFail;
2667 #ifdef SQLITE_DEBUG
2668 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2669 #endif
2670 sqlite3WalkExpr(&w, p);
2671 return w.eCode==0;
2673 #endif
2676 ** If the expression p codes a constant integer that is small enough
2677 ** to fit in a 32-bit integer, return 1 and put the value of the integer
2678 ** in *pValue. If the expression is not an integer or if it is too big
2679 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
2681 int sqlite3ExprIsInteger(const Expr *p, int *pValue){
2682 int rc = 0;
2683 if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
2685 /* If an expression is an integer literal that fits in a signed 32-bit
2686 ** integer, then the EP_IntValue flag will have already been set */
2687 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2688 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2690 if( p->flags & EP_IntValue ){
2691 *pValue = p->u.iValue;
2692 return 1;
2694 switch( p->op ){
2695 case TK_UPLUS: {
2696 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
2697 break;
2699 case TK_UMINUS: {
2700 int v = 0;
2701 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
2702 assert( ((unsigned int)v)!=0x80000000 );
2703 *pValue = -v;
2704 rc = 1;
2706 break;
2708 default: break;
2710 return rc;
2714 ** Return FALSE if there is no chance that the expression can be NULL.
2716 ** If the expression might be NULL or if the expression is too complex
2717 ** to tell return TRUE.
2719 ** This routine is used as an optimization, to skip OP_IsNull opcodes
2720 ** when we know that a value cannot be NULL. Hence, a false positive
2721 ** (returning TRUE when in fact the expression can never be NULL) might
2722 ** be a small performance hit but is otherwise harmless. On the other
2723 ** hand, a false negative (returning FALSE when the result could be NULL)
2724 ** will likely result in an incorrect answer. So when in doubt, return
2725 ** TRUE.
2727 int sqlite3ExprCanBeNull(const Expr *p){
2728 u8 op;
2729 assert( p!=0 );
2730 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2731 p = p->pLeft;
2732 assert( p!=0 );
2734 op = p->op;
2735 if( op==TK_REGISTER ) op = p->op2;
2736 switch( op ){
2737 case TK_INTEGER:
2738 case TK_STRING:
2739 case TK_FLOAT:
2740 case TK_BLOB:
2741 return 0;
2742 case TK_COLUMN:
2743 assert( ExprUseYTab(p) );
2744 return ExprHasProperty(p, EP_CanBeNull) ||
2745 NEVER(p->y.pTab==0) || /* Reference to column of index on expr */
2746 (p->iColumn>=0
2747 && p->y.pTab->aCol!=0 /* Possible due to prior error */
2748 && ALWAYS(p->iColumn<p->y.pTab->nCol)
2749 && p->y.pTab->aCol[p->iColumn].notNull==0);
2750 default:
2751 return 1;
2756 ** Return TRUE if the given expression is a constant which would be
2757 ** unchanged by OP_Affinity with the affinity given in the second
2758 ** argument.
2760 ** This routine is used to determine if the OP_Affinity operation
2761 ** can be omitted. When in doubt return FALSE. A false negative
2762 ** is harmless. A false positive, however, can result in the wrong
2763 ** answer.
2765 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2766 u8 op;
2767 int unaryMinus = 0;
2768 if( aff==SQLITE_AFF_BLOB ) return 1;
2769 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
2770 if( p->op==TK_UMINUS ) unaryMinus = 1;
2771 p = p->pLeft;
2773 op = p->op;
2774 if( op==TK_REGISTER ) op = p->op2;
2775 switch( op ){
2776 case TK_INTEGER: {
2777 return aff>=SQLITE_AFF_NUMERIC;
2779 case TK_FLOAT: {
2780 return aff>=SQLITE_AFF_NUMERIC;
2782 case TK_STRING: {
2783 return !unaryMinus && aff==SQLITE_AFF_TEXT;
2785 case TK_BLOB: {
2786 return !unaryMinus;
2788 case TK_COLUMN: {
2789 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2790 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
2792 default: {
2793 return 0;
2799 ** Return TRUE if the given string is a row-id column name.
2801 int sqlite3IsRowid(const char *z){
2802 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2803 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2804 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
2805 return 0;
2809 ** Return a pointer to a buffer containing a usable rowid alias for table
2810 ** pTab. An alias is usable if there is not an explicit user-defined column
2811 ** of the same name.
2813 const char *sqlite3RowidAlias(Table *pTab){
2814 const char *azOpt[] = {"_ROWID_", "ROWID", "OID"};
2815 int ii;
2816 assert( VisibleRowid(pTab) );
2817 for(ii=0; ii<ArraySize(azOpt); ii++){
2818 int iCol;
2819 for(iCol=0; iCol<pTab->nCol; iCol++){
2820 if( sqlite3_stricmp(azOpt[ii], pTab->aCol[iCol].zCnName)==0 ) break;
2822 if( iCol==pTab->nCol ){
2823 return azOpt[ii];
2826 return 0;
2830 ** pX is the RHS of an IN operator. If pX is a SELECT statement
2831 ** that can be simplified to a direct table access, then return
2832 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
2833 ** or if the SELECT statement needs to be materialized into a transient
2834 ** table, then return NULL.
2836 #ifndef SQLITE_OMIT_SUBQUERY
2837 static Select *isCandidateForInOpt(const Expr *pX){
2838 Select *p;
2839 SrcList *pSrc;
2840 ExprList *pEList;
2841 Table *pTab;
2842 int i;
2843 if( !ExprUseXSelect(pX) ) return 0; /* Not a subquery */
2844 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
2845 p = pX->x.pSelect;
2846 if( p->pPrior ) return 0; /* Not a compound SELECT */
2847 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
2848 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2849 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2850 return 0; /* No DISTINCT keyword and no aggregate functions */
2852 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
2853 if( p->pLimit ) return 0; /* Has no LIMIT clause */
2854 if( p->pWhere ) return 0; /* Has no WHERE clause */
2855 pSrc = p->pSrc;
2856 assert( pSrc!=0 );
2857 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
2858 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
2859 pTab = pSrc->a[0].pTab;
2860 assert( pTab!=0 );
2861 assert( !IsView(pTab) ); /* FROM clause is not a view */
2862 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
2863 pEList = p->pEList;
2864 assert( pEList!=0 );
2865 /* All SELECT results must be columns. */
2866 for(i=0; i<pEList->nExpr; i++){
2867 Expr *pRes = pEList->a[i].pExpr;
2868 if( pRes->op!=TK_COLUMN ) return 0;
2869 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
2871 return p;
2873 #endif /* SQLITE_OMIT_SUBQUERY */
2875 #ifndef SQLITE_OMIT_SUBQUERY
2877 ** Generate code that checks the left-most column of index table iCur to see if
2878 ** it contains any NULL entries. Cause the register at regHasNull to be set
2879 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2880 ** to be set to NULL if iCur contains one or more NULL values.
2882 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2883 int addr1;
2884 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2885 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2886 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2887 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2888 VdbeComment((v, "first_entry_in(%d)", iCur));
2889 sqlite3VdbeJumpHere(v, addr1);
2891 #endif
2894 #ifndef SQLITE_OMIT_SUBQUERY
2896 ** The argument is an IN operator with a list (not a subquery) on the
2897 ** right-hand side. Return TRUE if that list is constant.
2899 static int sqlite3InRhsIsConstant(Expr *pIn){
2900 Expr *pLHS;
2901 int res;
2902 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2903 pLHS = pIn->pLeft;
2904 pIn->pLeft = 0;
2905 res = sqlite3ExprIsConstant(pIn);
2906 pIn->pLeft = pLHS;
2907 return res;
2909 #endif
2912 ** This function is used by the implementation of the IN (...) operator.
2913 ** The pX parameter is the expression on the RHS of the IN operator, which
2914 ** might be either a list of expressions or a subquery.
2916 ** The job of this routine is to find or create a b-tree object that can
2917 ** be used either to test for membership in the RHS set or to iterate through
2918 ** all members of the RHS set, skipping duplicates.
2920 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2921 ** and the *piTab parameter is set to the index of that cursor.
2923 ** The returned value of this function indicates the b-tree type, as follows:
2925 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2926 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2927 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2928 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2929 ** populated ephemeral table.
2930 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2931 ** implemented as a sequence of comparisons.
2933 ** An existing b-tree might be used if the RHS expression pX is a simple
2934 ** subquery such as:
2936 ** SELECT <column1>, <column2>... FROM <table>
2938 ** If the RHS of the IN operator is a list or a more complex subquery, then
2939 ** an ephemeral table might need to be generated from the RHS and then
2940 ** pX->iTable made to point to the ephemeral table instead of an
2941 ** existing table. In this case, the creation and initialization of the
2942 ** ephemeral table might be put inside of a subroutine, the EP_Subrtn flag
2943 ** will be set on pX and the pX->y.sub fields will be set to show where
2944 ** the subroutine is coded.
2946 ** The inFlags parameter must contain, at a minimum, one of the bits
2947 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2948 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2949 ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2950 ** be used to loop over all values of the RHS of the IN operator.
2952 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2953 ** through the set members) then the b-tree must not contain duplicates.
2954 ** An ephemeral table will be created unless the selected columns are guaranteed
2955 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2956 ** a UNIQUE constraint or index.
2958 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2959 ** for fast set membership tests) then an ephemeral table must
2960 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2961 ** index can be found with the specified <columns> as its left-most.
2963 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2964 ** if the RHS of the IN operator is a list (not a subquery) then this
2965 ** routine might decide that creating an ephemeral b-tree for membership
2966 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2967 ** calling routine should implement the IN operator using a sequence
2968 ** of Eq or Ne comparison operations.
2970 ** When the b-tree is being used for membership tests, the calling function
2971 ** might need to know whether or not the RHS side of the IN operator
2972 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2973 ** if there is any chance that the (...) might contain a NULL value at
2974 ** runtime, then a register is allocated and the register number written
2975 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2976 ** NULL value, then *prRhsHasNull is left unchanged.
2978 ** If a register is allocated and its location stored in *prRhsHasNull, then
2979 ** the value in that register will be NULL if the b-tree contains one or more
2980 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2981 ** NULL values.
2983 ** If the aiMap parameter is not NULL, it must point to an array containing
2984 ** one element for each column returned by the SELECT statement on the RHS
2985 ** of the IN(...) operator. The i'th entry of the array is populated with the
2986 ** offset of the index column that matches the i'th column returned by the
2987 ** SELECT. For example, if the expression and selected index are:
2989 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2990 ** CREATE INDEX i1 ON t1(b, c, a);
2992 ** then aiMap[] is populated with {2, 0, 1}.
2994 #ifndef SQLITE_OMIT_SUBQUERY
2995 int sqlite3FindInIndex(
2996 Parse *pParse, /* Parsing context */
2997 Expr *pX, /* The IN expression */
2998 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2999 int *prRhsHasNull, /* Register holding NULL status. See notes */
3000 int *aiMap, /* Mapping from Index fields to RHS fields */
3001 int *piTab /* OUT: index to use */
3003 Select *p; /* SELECT to the right of IN operator */
3004 int eType = 0; /* Type of RHS table. IN_INDEX_* */
3005 int iTab; /* Cursor of the RHS table */
3006 int mustBeUnique; /* True if RHS must be unique */
3007 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
3009 assert( pX->op==TK_IN );
3010 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
3011 iTab = pParse->nTab++;
3013 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
3014 ** whether or not the SELECT result contains NULL values, check whether
3015 ** or not NULL is actually possible (it may not be, for example, due
3016 ** to NOT NULL constraints in the schema). If no NULL values are possible,
3017 ** set prRhsHasNull to 0 before continuing. */
3018 if( prRhsHasNull && ExprUseXSelect(pX) ){
3019 int i;
3020 ExprList *pEList = pX->x.pSelect->pEList;
3021 for(i=0; i<pEList->nExpr; i++){
3022 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
3024 if( i==pEList->nExpr ){
3025 prRhsHasNull = 0;
3029 /* Check to see if an existing table or index can be used to
3030 ** satisfy the query. This is preferable to generating a new
3031 ** ephemeral table. */
3032 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
3033 sqlite3 *db = pParse->db; /* Database connection */
3034 Table *pTab; /* Table <table>. */
3035 int iDb; /* Database idx for pTab */
3036 ExprList *pEList = p->pEList;
3037 int nExpr = pEList->nExpr;
3039 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
3040 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
3041 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
3042 pTab = p->pSrc->a[0].pTab;
3044 /* Code an OP_Transaction and OP_TableLock for <table>. */
3045 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3046 assert( iDb>=0 && iDb<SQLITE_MAX_DB );
3047 sqlite3CodeVerifySchema(pParse, iDb);
3048 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
3050 assert(v); /* sqlite3GetVdbe() has always been previously called */
3051 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
3052 /* The "x IN (SELECT rowid FROM table)" case */
3053 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
3054 VdbeCoverage(v);
3056 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3057 eType = IN_INDEX_ROWID;
3058 ExplainQueryPlan((pParse, 0,
3059 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
3060 sqlite3VdbeJumpHere(v, iAddr);
3061 }else{
3062 Index *pIdx; /* Iterator variable */
3063 int affinity_ok = 1;
3064 int i;
3066 /* Check that the affinity that will be used to perform each
3067 ** comparison is the same as the affinity of each column in table
3068 ** on the RHS of the IN operator. If it not, it is not possible to
3069 ** use any index of the RHS table. */
3070 for(i=0; i<nExpr && affinity_ok; i++){
3071 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
3072 int iCol = pEList->a[i].pExpr->iColumn;
3073 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
3074 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
3075 testcase( cmpaff==SQLITE_AFF_BLOB );
3076 testcase( cmpaff==SQLITE_AFF_TEXT );
3077 switch( cmpaff ){
3078 case SQLITE_AFF_BLOB:
3079 break;
3080 case SQLITE_AFF_TEXT:
3081 /* sqlite3CompareAffinity() only returns TEXT if one side or the
3082 ** other has no affinity and the other side is TEXT. Hence,
3083 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
3084 ** and for the term on the LHS of the IN to have no affinity. */
3085 assert( idxaff==SQLITE_AFF_TEXT );
3086 break;
3087 default:
3088 affinity_ok = sqlite3IsNumericAffinity(idxaff);
3092 if( affinity_ok ){
3093 /* Search for an existing index that will work for this IN operator */
3094 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
3095 Bitmask colUsed; /* Columns of the index used */
3096 Bitmask mCol; /* Mask for the current column */
3097 if( pIdx->nColumn<nExpr ) continue;
3098 if( pIdx->pPartIdxWhere!=0 ) continue;
3099 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
3100 ** BITMASK(nExpr) without overflowing */
3101 testcase( pIdx->nColumn==BMS-2 );
3102 testcase( pIdx->nColumn==BMS-1 );
3103 if( pIdx->nColumn>=BMS-1 ) continue;
3104 if( mustBeUnique ){
3105 if( pIdx->nKeyCol>nExpr
3106 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
3108 continue; /* This index is not unique over the IN RHS columns */
3112 colUsed = 0; /* Columns of index used so far */
3113 for(i=0; i<nExpr; i++){
3114 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
3115 Expr *pRhs = pEList->a[i].pExpr;
3116 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
3117 int j;
3119 for(j=0; j<nExpr; j++){
3120 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
3121 assert( pIdx->azColl[j] );
3122 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
3123 continue;
3125 break;
3127 if( j==nExpr ) break;
3128 mCol = MASKBIT(j);
3129 if( mCol & colUsed ) break; /* Each column used only once */
3130 colUsed |= mCol;
3131 if( aiMap ) aiMap[i] = j;
3134 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
3135 if( colUsed==(MASKBIT(nExpr)-1) ){
3136 /* If we reach this point, that means the index pIdx is usable */
3137 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3138 ExplainQueryPlan((pParse, 0,
3139 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
3140 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
3141 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
3142 VdbeComment((v, "%s", pIdx->zName));
3143 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
3144 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
3146 if( prRhsHasNull ){
3147 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
3148 i64 mask = (1<<nExpr)-1;
3149 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
3150 iTab, 0, 0, (u8*)&mask, P4_INT64);
3151 #endif
3152 *prRhsHasNull = ++pParse->nMem;
3153 if( nExpr==1 ){
3154 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
3157 sqlite3VdbeJumpHere(v, iAddr);
3159 } /* End loop over indexes */
3160 } /* End if( affinity_ok ) */
3161 } /* End if not an rowid index */
3162 } /* End attempt to optimize using an index */
3164 /* If no preexisting index is available for the IN clause
3165 ** and IN_INDEX_NOOP is an allowed reply
3166 ** and the RHS of the IN operator is a list, not a subquery
3167 ** and the RHS is not constant or has two or fewer terms,
3168 ** then it is not worth creating an ephemeral table to evaluate
3169 ** the IN operator so return IN_INDEX_NOOP.
3171 if( eType==0
3172 && (inFlags & IN_INDEX_NOOP_OK)
3173 && ExprUseXList(pX)
3174 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
3176 pParse->nTab--; /* Back out the allocation of the unused cursor */
3177 iTab = -1; /* Cursor is not allocated */
3178 eType = IN_INDEX_NOOP;
3181 if( eType==0 ){
3182 /* Could not find an existing table or index to use as the RHS b-tree.
3183 ** We will have to generate an ephemeral table to do the job.
3185 u32 savedNQueryLoop = pParse->nQueryLoop;
3186 int rMayHaveNull = 0;
3187 eType = IN_INDEX_EPH;
3188 if( inFlags & IN_INDEX_LOOP ){
3189 pParse->nQueryLoop = 0;
3190 }else if( prRhsHasNull ){
3191 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
3193 assert( pX->op==TK_IN );
3194 sqlite3CodeRhsOfIN(pParse, pX, iTab);
3195 if( rMayHaveNull ){
3196 sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
3198 pParse->nQueryLoop = savedNQueryLoop;
3201 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
3202 int i, n;
3203 n = sqlite3ExprVectorSize(pX->pLeft);
3204 for(i=0; i<n; i++) aiMap[i] = i;
3206 *piTab = iTab;
3207 return eType;
3209 #endif
3211 #ifndef SQLITE_OMIT_SUBQUERY
3213 ** Argument pExpr is an (?, ?...) IN(...) expression. This
3214 ** function allocates and returns a nul-terminated string containing
3215 ** the affinities to be used for each column of the comparison.
3217 ** It is the responsibility of the caller to ensure that the returned
3218 ** string is eventually freed using sqlite3DbFree().
3220 static char *exprINAffinity(Parse *pParse, const Expr *pExpr){
3221 Expr *pLeft = pExpr->pLeft;
3222 int nVal = sqlite3ExprVectorSize(pLeft);
3223 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
3224 char *zRet;
3226 assert( pExpr->op==TK_IN );
3227 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
3228 if( zRet ){
3229 int i;
3230 for(i=0; i<nVal; i++){
3231 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
3232 char a = sqlite3ExprAffinity(pA);
3233 if( pSelect ){
3234 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
3235 }else{
3236 zRet[i] = a;
3239 zRet[nVal] = '\0';
3241 return zRet;
3243 #endif
3245 #ifndef SQLITE_OMIT_SUBQUERY
3247 ** Load the Parse object passed as the first argument with an error
3248 ** message of the form:
3250 ** "sub-select returns N columns - expected M"
3252 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
3253 if( pParse->nErr==0 ){
3254 const char *zFmt = "sub-select returns %d columns - expected %d";
3255 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
3258 #endif
3261 ** Expression pExpr is a vector that has been used in a context where
3262 ** it is not permitted. If pExpr is a sub-select vector, this routine
3263 ** loads the Parse object with a message of the form:
3265 ** "sub-select returns N columns - expected 1"
3267 ** Or, if it is a regular scalar vector:
3269 ** "row value misused"
3271 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
3272 #ifndef SQLITE_OMIT_SUBQUERY
3273 if( ExprUseXSelect(pExpr) ){
3274 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
3275 }else
3276 #endif
3278 sqlite3ErrorMsg(pParse, "row value misused");
3282 #ifndef SQLITE_OMIT_SUBQUERY
3284 ** Generate code that will construct an ephemeral table containing all terms
3285 ** in the RHS of an IN operator. The IN operator can be in either of two
3286 ** forms:
3288 ** x IN (4,5,11) -- IN operator with list on right-hand side
3289 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
3291 ** The pExpr parameter is the IN operator. The cursor number for the
3292 ** constructed ephemeral table is returned. The first time the ephemeral
3293 ** table is computed, the cursor number is also stored in pExpr->iTable,
3294 ** however the cursor number returned might not be the same, as it might
3295 ** have been duplicated using OP_OpenDup.
3297 ** If the LHS expression ("x" in the examples) is a column value, or
3298 ** the SELECT statement returns a column value, then the affinity of that
3299 ** column is used to build the index keys. If both 'x' and the
3300 ** SELECT... statement are columns, then numeric affinity is used
3301 ** if either column has NUMERIC or INTEGER affinity. If neither
3302 ** 'x' nor the SELECT... statement are columns, then numeric affinity
3303 ** is used.
3305 void sqlite3CodeRhsOfIN(
3306 Parse *pParse, /* Parsing context */
3307 Expr *pExpr, /* The IN operator */
3308 int iTab /* Use this cursor number */
3310 int addrOnce = 0; /* Address of the OP_Once instruction at top */
3311 int addr; /* Address of OP_OpenEphemeral instruction */
3312 Expr *pLeft; /* the LHS of the IN operator */
3313 KeyInfo *pKeyInfo = 0; /* Key information */
3314 int nVal; /* Size of vector pLeft */
3315 Vdbe *v; /* The prepared statement under construction */
3317 v = pParse->pVdbe;
3318 assert( v!=0 );
3320 /* The evaluation of the IN must be repeated every time it
3321 ** is encountered if any of the following is true:
3323 ** * The right-hand side is a correlated subquery
3324 ** * The right-hand side is an expression list containing variables
3325 ** * We are inside a trigger
3327 ** If all of the above are false, then we can compute the RHS just once
3328 ** and reuse it many names.
3330 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
3331 /* Reuse of the RHS is allowed */
3332 /* If this routine has already been coded, but the previous code
3333 ** might not have been invoked yet, so invoke it now as a subroutine.
3335 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3336 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3337 if( ExprUseXSelect(pExpr) ){
3338 ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
3339 pExpr->x.pSelect->selId));
3341 assert( ExprUseYSub(pExpr) );
3342 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3343 pExpr->y.sub.iAddr);
3344 assert( iTab!=pExpr->iTable );
3345 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
3346 sqlite3VdbeJumpHere(v, addrOnce);
3347 return;
3350 /* Begin coding the subroutine */
3351 assert( !ExprUseYWin(pExpr) );
3352 ExprSetProperty(pExpr, EP_Subrtn);
3353 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3354 pExpr->y.sub.regReturn = ++pParse->nMem;
3355 pExpr->y.sub.iAddr =
3356 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3358 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3361 /* Check to see if this is a vector IN operator */
3362 pLeft = pExpr->pLeft;
3363 nVal = sqlite3ExprVectorSize(pLeft);
3365 /* Construct the ephemeral table that will contain the content of
3366 ** RHS of the IN operator.
3368 pExpr->iTable = iTab;
3369 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
3370 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
3371 if( ExprUseXSelect(pExpr) ){
3372 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
3373 }else{
3374 VdbeComment((v, "RHS of IN operator"));
3376 #endif
3377 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
3379 if( ExprUseXSelect(pExpr) ){
3380 /* Case 1: expr IN (SELECT ...)
3382 ** Generate code to write the results of the select into the temporary
3383 ** table allocated and opened above.
3385 Select *pSelect = pExpr->x.pSelect;
3386 ExprList *pEList = pSelect->pEList;
3388 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
3389 addrOnce?"":"CORRELATED ", pSelect->selId
3391 /* If the LHS and RHS of the IN operator do not match, that
3392 ** error will have been caught long before we reach this point. */
3393 if( ALWAYS(pEList->nExpr==nVal) ){
3394 Select *pCopy;
3395 SelectDest dest;
3396 int i;
3397 int rc;
3398 sqlite3SelectDestInit(&dest, SRT_Set, iTab);
3399 dest.zAffSdst = exprINAffinity(pParse, pExpr);
3400 pSelect->iLimit = 0;
3401 testcase( pSelect->selFlags & SF_Distinct );
3402 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
3403 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
3404 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
3405 sqlite3SelectDelete(pParse->db, pCopy);
3406 sqlite3DbFree(pParse->db, dest.zAffSdst);
3407 if( rc ){
3408 sqlite3KeyInfoUnref(pKeyInfo);
3409 return;
3411 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
3412 assert( pEList!=0 );
3413 assert( pEList->nExpr>0 );
3414 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3415 for(i=0; i<nVal; i++){
3416 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
3417 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
3418 pParse, p, pEList->a[i].pExpr
3422 }else if( ALWAYS(pExpr->x.pList!=0) ){
3423 /* Case 2: expr IN (exprlist)
3425 ** For each expression, build an index key from the evaluation and
3426 ** store it in the temporary table. If <expr> is a column, then use
3427 ** that columns affinity when building index keys. If <expr> is not
3428 ** a column, use numeric affinity.
3430 char affinity; /* Affinity of the LHS of the IN */
3431 int i;
3432 ExprList *pList = pExpr->x.pList;
3433 struct ExprList_item *pItem;
3434 int r1, r2;
3435 affinity = sqlite3ExprAffinity(pLeft);
3436 if( affinity<=SQLITE_AFF_NONE ){
3437 affinity = SQLITE_AFF_BLOB;
3438 }else if( affinity==SQLITE_AFF_REAL ){
3439 affinity = SQLITE_AFF_NUMERIC;
3441 if( pKeyInfo ){
3442 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
3443 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3446 /* Loop through each expression in <exprlist>. */
3447 r1 = sqlite3GetTempReg(pParse);
3448 r2 = sqlite3GetTempReg(pParse);
3449 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
3450 Expr *pE2 = pItem->pExpr;
3452 /* If the expression is not constant then we will need to
3453 ** disable the test that was generated above that makes sure
3454 ** this code only executes once. Because for a non-constant
3455 ** expression we need to rerun this code each time.
3457 if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
3458 sqlite3VdbeChangeToNoop(v, addrOnce-1);
3459 sqlite3VdbeChangeToNoop(v, addrOnce);
3460 ExprClearProperty(pExpr, EP_Subrtn);
3461 addrOnce = 0;
3464 /* Evaluate the expression and insert it into the temp table */
3465 sqlite3ExprCode(pParse, pE2, r1);
3466 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
3467 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
3469 sqlite3ReleaseTempReg(pParse, r1);
3470 sqlite3ReleaseTempReg(pParse, r2);
3472 if( pKeyInfo ){
3473 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
3475 if( addrOnce ){
3476 sqlite3VdbeAddOp1(v, OP_NullRow, iTab);
3477 sqlite3VdbeJumpHere(v, addrOnce);
3478 /* Subroutine return */
3479 assert( ExprUseYSub(pExpr) );
3480 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3481 || pParse->nErr );
3482 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3483 pExpr->y.sub.iAddr, 1);
3484 VdbeCoverage(v);
3485 sqlite3ClearTempRegCache(pParse);
3488 #endif /* SQLITE_OMIT_SUBQUERY */
3491 ** Generate code for scalar subqueries used as a subquery expression
3492 ** or EXISTS operator:
3494 ** (SELECT a FROM b) -- subquery
3495 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
3497 ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
3499 ** Return the register that holds the result. For a multi-column SELECT,
3500 ** the result is stored in a contiguous array of registers and the
3501 ** return value is the register of the left-most result column.
3502 ** Return 0 if an error occurs.
3504 #ifndef SQLITE_OMIT_SUBQUERY
3505 int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
3506 int addrOnce = 0; /* Address of OP_Once at top of subroutine */
3507 int rReg = 0; /* Register storing resulting */
3508 Select *pSel; /* SELECT statement to encode */
3509 SelectDest dest; /* How to deal with SELECT result */
3510 int nReg; /* Registers to allocate */
3511 Expr *pLimit; /* New limit expression */
3512 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
3513 int addrExplain; /* Address of OP_Explain instruction */
3514 #endif
3516 Vdbe *v = pParse->pVdbe;
3517 assert( v!=0 );
3518 if( pParse->nErr ) return 0;
3519 testcase( pExpr->op==TK_EXISTS );
3520 testcase( pExpr->op==TK_SELECT );
3521 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
3522 assert( ExprUseXSelect(pExpr) );
3523 pSel = pExpr->x.pSelect;
3525 /* If this routine has already been coded, then invoke it as a
3526 ** subroutine. */
3527 if( ExprHasProperty(pExpr, EP_Subrtn) ){
3528 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
3529 assert( ExprUseYSub(pExpr) );
3530 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
3531 pExpr->y.sub.iAddr);
3532 return pExpr->iTable;
3535 /* Begin coding the subroutine */
3536 assert( !ExprUseYWin(pExpr) );
3537 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
3538 ExprSetProperty(pExpr, EP_Subrtn);
3539 pExpr->y.sub.regReturn = ++pParse->nMem;
3540 pExpr->y.sub.iAddr =
3541 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
3543 /* The evaluation of the EXISTS/SELECT must be repeated every time it
3544 ** is encountered if any of the following is true:
3546 ** * The right-hand side is a correlated subquery
3547 ** * The right-hand side is an expression list containing variables
3548 ** * We are inside a trigger
3550 ** If all of the above are false, then we can run this code just once
3551 ** save the results, and reuse the same result on subsequent invocations.
3553 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
3554 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
3557 /* For a SELECT, generate code to put the values for all columns of
3558 ** the first row into an array of registers and return the index of
3559 ** the first register.
3561 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
3562 ** into a register and return that register number.
3564 ** In both cases, the query is augmented with "LIMIT 1". Any
3565 ** preexisting limit is discarded in place of the new LIMIT 1.
3567 ExplainQueryPlan2(addrExplain, (pParse, 1, "%sSCALAR SUBQUERY %d",
3568 addrOnce?"":"CORRELATED ", pSel->selId));
3569 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1);
3570 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
3571 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
3572 pParse->nMem += nReg;
3573 if( pExpr->op==TK_SELECT ){
3574 dest.eDest = SRT_Mem;
3575 dest.iSdst = dest.iSDParm;
3576 dest.nSdst = nReg;
3577 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
3578 VdbeComment((v, "Init subquery result"));
3579 }else{
3580 dest.eDest = SRT_Exists;
3581 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
3582 VdbeComment((v, "Init EXISTS result"));
3584 if( pSel->pLimit ){
3585 /* The subquery already has a limit. If the pre-existing limit is X
3586 ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
3587 sqlite3 *db = pParse->db;
3588 pLimit = sqlite3Expr(db, TK_INTEGER, "0");
3589 if( pLimit ){
3590 pLimit->affExpr = SQLITE_AFF_NUMERIC;
3591 pLimit = sqlite3PExpr(pParse, TK_NE,
3592 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
3594 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
3595 pSel->pLimit->pLeft = pLimit;
3596 }else{
3597 /* If there is no pre-existing limit add a limit of 1 */
3598 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
3599 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
3601 pSel->iLimit = 0;
3602 if( sqlite3Select(pParse, pSel, &dest) ){
3603 pExpr->op2 = pExpr->op;
3604 pExpr->op = TK_ERROR;
3605 return 0;
3607 pExpr->iTable = rReg = dest.iSDParm;
3608 ExprSetVVAProperty(pExpr, EP_NoReduce);
3609 if( addrOnce ){
3610 sqlite3VdbeJumpHere(v, addrOnce);
3612 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
3614 /* Subroutine return */
3615 assert( ExprUseYSub(pExpr) );
3616 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
3617 || pParse->nErr );
3618 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
3619 pExpr->y.sub.iAddr, 1);
3620 VdbeCoverage(v);
3621 sqlite3ClearTempRegCache(pParse);
3622 return rReg;
3624 #endif /* SQLITE_OMIT_SUBQUERY */
3626 #ifndef SQLITE_OMIT_SUBQUERY
3628 ** Expr pIn is an IN(...) expression. This function checks that the
3629 ** sub-select on the RHS of the IN() operator has the same number of
3630 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
3631 ** a sub-query, that the LHS is a vector of size 1.
3633 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
3634 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
3635 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
3636 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
3637 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
3638 return 1;
3640 }else if( nVector!=1 ){
3641 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
3642 return 1;
3644 return 0;
3646 #endif
3648 #ifndef SQLITE_OMIT_SUBQUERY
3650 ** Generate code for an IN expression.
3652 ** x IN (SELECT ...)
3653 ** x IN (value, value, ...)
3655 ** The left-hand side (LHS) is a scalar or vector expression. The
3656 ** right-hand side (RHS) is an array of zero or more scalar values, or a
3657 ** subquery. If the RHS is a subquery, the number of result columns must
3658 ** match the number of columns in the vector on the LHS. If the RHS is
3659 ** a list of values, the LHS must be a scalar.
3661 ** The IN operator is true if the LHS value is contained within the RHS.
3662 ** The result is false if the LHS is definitely not in the RHS. The
3663 ** result is NULL if the presence of the LHS in the RHS cannot be
3664 ** determined due to NULLs.
3666 ** This routine generates code that jumps to destIfFalse if the LHS is not
3667 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
3668 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
3669 ** within the RHS then fall through.
3671 ** See the separate in-operator.md documentation file in the canonical
3672 ** SQLite source tree for additional information.
3674 static void sqlite3ExprCodeIN(
3675 Parse *pParse, /* Parsing and code generating context */
3676 Expr *pExpr, /* The IN expression */
3677 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
3678 int destIfNull /* Jump here if the results are unknown due to NULLs */
3680 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
3681 int eType; /* Type of the RHS */
3682 int rLhs; /* Register(s) holding the LHS values */
3683 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
3684 Vdbe *v; /* Statement under construction */
3685 int *aiMap = 0; /* Map from vector field to index column */
3686 char *zAff = 0; /* Affinity string for comparisons */
3687 int nVector; /* Size of vectors for this IN operator */
3688 int iDummy; /* Dummy parameter to exprCodeVector() */
3689 Expr *pLeft; /* The LHS of the IN operator */
3690 int i; /* loop counter */
3691 int destStep2; /* Where to jump when NULLs seen in step 2 */
3692 int destStep6 = 0; /* Start of code for Step 6 */
3693 int addrTruthOp; /* Address of opcode that determines the IN is true */
3694 int destNotNull; /* Jump here if a comparison is not true in step 6 */
3695 int addrTop; /* Top of the step-6 loop */
3696 int iTab = 0; /* Index to use */
3697 u8 okConstFactor = pParse->okConstFactor;
3699 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
3700 pLeft = pExpr->pLeft;
3701 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
3702 zAff = exprINAffinity(pParse, pExpr);
3703 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3704 aiMap = (int*)sqlite3DbMallocZero(
3705 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3707 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
3709 /* Attempt to compute the RHS. After this step, if anything other than
3710 ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
3711 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3712 ** the RHS has not yet been coded. */
3713 v = pParse->pVdbe;
3714 assert( v!=0 ); /* OOM detected prior to this routine */
3715 VdbeNoopComment((v, "begin IN expr"));
3716 eType = sqlite3FindInIndex(pParse, pExpr,
3717 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
3718 destIfFalse==destIfNull ? 0 : &rRhsHasNull,
3719 aiMap, &iTab);
3721 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3722 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3724 #ifdef SQLITE_DEBUG
3725 /* Confirm that aiMap[] contains nVector integer values between 0 and
3726 ** nVector-1. */
3727 for(i=0; i<nVector; i++){
3728 int j, cnt;
3729 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3730 assert( cnt==1 );
3732 #endif
3734 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3735 ** vector, then it is stored in an array of nVector registers starting
3736 ** at r1.
3738 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3739 ** so that the fields are in the same order as an existing index. The
3740 ** aiMap[] array contains a mapping from the original LHS field order to
3741 ** the field order that matches the RHS index.
3743 ** Avoid factoring the LHS of the IN(...) expression out of the loop,
3744 ** even if it is constant, as OP_Affinity may be used on the register
3745 ** by code generated below. */
3746 assert( pParse->okConstFactor==okConstFactor );
3747 pParse->okConstFactor = 0;
3748 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3749 pParse->okConstFactor = okConstFactor;
3750 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
3751 if( i==nVector ){
3752 /* LHS fields are not reordered */
3753 rLhs = rLhsOrig;
3754 }else{
3755 /* Need to reorder the LHS fields according to aiMap */
3756 rLhs = sqlite3GetTempRange(pParse, nVector);
3757 for(i=0; i<nVector; i++){
3758 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
3762 /* If sqlite3FindInIndex() did not find or create an index that is
3763 ** suitable for evaluating the IN operator, then evaluate using a
3764 ** sequence of comparisons.
3766 ** This is step (1) in the in-operator.md optimized algorithm.
3768 if( eType==IN_INDEX_NOOP ){
3769 ExprList *pList;
3770 CollSeq *pColl;
3771 int labelOk = sqlite3VdbeMakeLabel(pParse);
3772 int r2, regToFree;
3773 int regCkNull = 0;
3774 int ii;
3775 assert( ExprUseXList(pExpr) );
3776 pList = pExpr->x.pList;
3777 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3778 if( destIfNull!=destIfFalse ){
3779 regCkNull = sqlite3GetTempReg(pParse);
3780 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
3782 for(ii=0; ii<pList->nExpr; ii++){
3783 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
3784 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
3785 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3787 sqlite3ReleaseTempReg(pParse, regToFree);
3788 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
3789 int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
3790 sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
3791 (void*)pColl, P4_COLLSEQ);
3792 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
3793 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
3794 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
3795 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
3796 sqlite3VdbeChangeP5(v, zAff[0]);
3797 }else{
3798 int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
3799 assert( destIfNull==destIfFalse );
3800 sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
3801 (void*)pColl, P4_COLLSEQ);
3802 VdbeCoverageIf(v, op==OP_Ne);
3803 VdbeCoverageIf(v, op==OP_IsNull);
3804 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
3807 if( regCkNull ){
3808 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
3809 sqlite3VdbeGoto(v, destIfFalse);
3811 sqlite3VdbeResolveLabel(v, labelOk);
3812 sqlite3ReleaseTempReg(pParse, regCkNull);
3813 goto sqlite3ExprCodeIN_finished;
3816 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3817 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3818 ** We will then skip the binary search of the RHS.
3820 if( destIfNull==destIfFalse ){
3821 destStep2 = destIfFalse;
3822 }else{
3823 destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
3825 for(i=0; i<nVector; i++){
3826 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3827 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
3828 if( sqlite3ExprCanBeNull(p) ){
3829 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
3830 VdbeCoverage(v);
3834 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3835 ** of the RHS using the LHS as a probe. If found, the result is
3836 ** true.
3838 if( eType==IN_INDEX_ROWID ){
3839 /* In this case, the RHS is the ROWID of table b-tree and so we also
3840 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3841 ** into a single opcode. */
3842 sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
3843 VdbeCoverage(v);
3844 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
3845 }else{
3846 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3847 if( destIfFalse==destIfNull ){
3848 /* Combine Step 3 and Step 5 into a single opcode */
3849 sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
3850 rLhs, nVector); VdbeCoverage(v);
3851 goto sqlite3ExprCodeIN_finished;
3853 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3854 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
3855 rLhs, nVector); VdbeCoverage(v);
3858 /* Step 4. If the RHS is known to be non-NULL and we did not find
3859 ** an match on the search above, then the result must be FALSE.
3861 if( rRhsHasNull && nVector==1 ){
3862 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3863 VdbeCoverage(v);
3866 /* Step 5. If we do not care about the difference between NULL and
3867 ** FALSE, then just return false.
3869 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3871 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3872 ** If any comparison is NULL, then the result is NULL. If all
3873 ** comparisons are FALSE then the final result is FALSE.
3875 ** For a scalar LHS, it is sufficient to check just the first row
3876 ** of the RHS.
3878 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3879 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
3880 VdbeCoverage(v);
3881 if( nVector>1 ){
3882 destNotNull = sqlite3VdbeMakeLabel(pParse);
3883 }else{
3884 /* For nVector==1, combine steps 6 and 7 by immediately returning
3885 ** FALSE if the first comparison is not NULL */
3886 destNotNull = destIfFalse;
3888 for(i=0; i<nVector; i++){
3889 Expr *p;
3890 CollSeq *pColl;
3891 int r3 = sqlite3GetTempReg(pParse);
3892 p = sqlite3VectorFieldSubexpr(pLeft, i);
3893 pColl = sqlite3ExprCollSeq(pParse, p);
3894 sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
3895 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3896 (void*)pColl, P4_COLLSEQ);
3897 VdbeCoverage(v);
3898 sqlite3ReleaseTempReg(pParse, r3);
3900 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3901 if( nVector>1 ){
3902 sqlite3VdbeResolveLabel(v, destNotNull);
3903 sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
3904 VdbeCoverage(v);
3906 /* Step 7: If we reach this point, we know that the result must
3907 ** be false. */
3908 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3911 /* Jumps here in order to return true. */
3912 sqlite3VdbeJumpHere(v, addrTruthOp);
3914 sqlite3ExprCodeIN_finished:
3915 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
3916 VdbeComment((v, "end IN expr"));
3917 sqlite3ExprCodeIN_oom_error:
3918 sqlite3DbFree(pParse->db, aiMap);
3919 sqlite3DbFree(pParse->db, zAff);
3921 #endif /* SQLITE_OMIT_SUBQUERY */
3923 #ifndef SQLITE_OMIT_FLOATING_POINT
3925 ** Generate an instruction that will put the floating point
3926 ** value described by z[0..n-1] into register iMem.
3928 ** The z[] string will probably not be zero-terminated. But the
3929 ** z[n] character is guaranteed to be something that does not look
3930 ** like the continuation of the number.
3932 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
3933 if( ALWAYS(z!=0) ){
3934 double value;
3935 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
3936 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3937 if( negateFlag ) value = -value;
3938 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
3941 #endif
3945 ** Generate an instruction that will put the integer describe by
3946 ** text z[0..n-1] into register iMem.
3948 ** Expr.u.zToken is always UTF8 and zero-terminated.
3950 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3951 Vdbe *v = pParse->pVdbe;
3952 if( pExpr->flags & EP_IntValue ){
3953 int i = pExpr->u.iValue;
3954 assert( i>=0 );
3955 if( negFlag ) i = -i;
3956 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3957 }else{
3958 int c;
3959 i64 value;
3960 const char *z = pExpr->u.zToken;
3961 assert( z!=0 );
3962 c = sqlite3DecOrHexToI64(z, &value);
3963 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
3964 #ifdef SQLITE_OMIT_FLOATING_POINT
3965 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
3966 #else
3967 #ifndef SQLITE_OMIT_HEX_INTEGER
3968 if( sqlite3_strnicmp(z,"0x",2)==0 ){
3969 sqlite3ErrorMsg(pParse, "hex literal too big: %s%#T",
3970 negFlag?"-":"",pExpr);
3971 }else
3972 #endif
3974 codeReal(v, z, negFlag, iMem);
3976 #endif
3977 }else{
3978 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
3979 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3985 /* Generate code that will load into register regOut a value that is
3986 ** appropriate for the iIdxCol-th column of index pIdx.
3988 void sqlite3ExprCodeLoadIndexColumn(
3989 Parse *pParse, /* The parsing context */
3990 Index *pIdx, /* The index whose column is to be loaded */
3991 int iTabCur, /* Cursor pointing to a table row */
3992 int iIdxCol, /* The column of the index to be loaded */
3993 int regOut /* Store the index column value in this register */
3995 i16 iTabCol = pIdx->aiColumn[iIdxCol];
3996 if( iTabCol==XN_EXPR ){
3997 assert( pIdx->aColExpr );
3998 assert( pIdx->aColExpr->nExpr>iIdxCol );
3999 pParse->iSelfTab = iTabCur + 1;
4000 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
4001 pParse->iSelfTab = 0;
4002 }else{
4003 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
4004 iTabCol, regOut);
4008 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4010 ** Generate code that will compute the value of generated column pCol
4011 ** and store the result in register regOut
4013 void sqlite3ExprCodeGeneratedColumn(
4014 Parse *pParse, /* Parsing context */
4015 Table *pTab, /* Table containing the generated column */
4016 Column *pCol, /* The generated column */
4017 int regOut /* Put the result in this register */
4019 int iAddr;
4020 Vdbe *v = pParse->pVdbe;
4021 int nErr = pParse->nErr;
4022 assert( v!=0 );
4023 assert( pParse->iSelfTab!=0 );
4024 if( pParse->iSelfTab>0 ){
4025 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
4026 }else{
4027 iAddr = 0;
4029 sqlite3ExprCodeCopy(pParse, sqlite3ColumnExpr(pTab,pCol), regOut);
4030 if( pCol->affinity>=SQLITE_AFF_TEXT ){
4031 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
4033 if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
4034 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
4036 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4039 ** Generate code to extract the value of the iCol-th column of a table.
4041 void sqlite3ExprCodeGetColumnOfTable(
4042 Vdbe *v, /* Parsing context */
4043 Table *pTab, /* The table containing the value */
4044 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
4045 int iCol, /* Index of the column to extract */
4046 int regOut /* Extract the value into this register */
4048 Column *pCol;
4049 assert( v!=0 );
4050 assert( pTab!=0 );
4051 assert( iCol!=XN_EXPR );
4052 if( iCol<0 || iCol==pTab->iPKey ){
4053 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
4054 VdbeComment((v, "%s.rowid", pTab->zName));
4055 }else{
4056 int op;
4057 int x;
4058 if( IsVirtual(pTab) ){
4059 op = OP_VColumn;
4060 x = iCol;
4061 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4062 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
4063 Parse *pParse = sqlite3VdbeParser(v);
4064 if( pCol->colFlags & COLFLAG_BUSY ){
4065 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4066 pCol->zCnName);
4067 }else{
4068 int savedSelfTab = pParse->iSelfTab;
4069 pCol->colFlags |= COLFLAG_BUSY;
4070 pParse->iSelfTab = iTabCur+1;
4071 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, regOut);
4072 pParse->iSelfTab = savedSelfTab;
4073 pCol->colFlags &= ~COLFLAG_BUSY;
4075 return;
4076 #endif
4077 }else if( !HasRowid(pTab) ){
4078 testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
4079 x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
4080 op = OP_Column;
4081 }else{
4082 x = sqlite3TableColumnToStorage(pTab,iCol);
4083 testcase( x!=iCol );
4084 op = OP_Column;
4086 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
4087 sqlite3ColumnDefault(v, pTab, iCol, regOut);
4092 ** Generate code that will extract the iColumn-th column from
4093 ** table pTab and store the column value in register iReg.
4095 ** There must be an open cursor to pTab in iTable when this routine
4096 ** is called. If iColumn<0 then code is generated that extracts the rowid.
4098 int sqlite3ExprCodeGetColumn(
4099 Parse *pParse, /* Parsing and code generating context */
4100 Table *pTab, /* Description of the table we are reading from */
4101 int iColumn, /* Index of the table column */
4102 int iTable, /* The cursor pointing to the table */
4103 int iReg, /* Store results here */
4104 u8 p5 /* P5 value for OP_Column + FLAGS */
4106 assert( pParse->pVdbe!=0 );
4107 assert( (p5 & (OPFLAG_NOCHNG|OPFLAG_TYPEOFARG|OPFLAG_LENGTHARG))==p5 );
4108 assert( IsVirtual(pTab) || (p5 & OPFLAG_NOCHNG)==0 );
4109 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
4110 if( p5 ){
4111 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
4112 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
4113 if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG);
4115 return iReg;
4119 ** Generate code to move content from registers iFrom...iFrom+nReg-1
4120 ** over to iTo..iTo+nReg-1.
4122 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
4123 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
4127 ** Convert a scalar expression node to a TK_REGISTER referencing
4128 ** register iReg. The caller must ensure that iReg already contains
4129 ** the correct value for the expression.
4131 static void exprToRegister(Expr *pExpr, int iReg){
4132 Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
4133 if( NEVER(p==0) ) return;
4134 p->op2 = p->op;
4135 p->op = TK_REGISTER;
4136 p->iTable = iReg;
4137 ExprClearProperty(p, EP_Skip);
4141 ** Evaluate an expression (either a vector or a scalar expression) and store
4142 ** the result in contiguous temporary registers. Return the index of
4143 ** the first register used to store the result.
4145 ** If the returned result register is a temporary scalar, then also write
4146 ** that register number into *piFreeable. If the returned result register
4147 ** is not a temporary or if the expression is a vector set *piFreeable
4148 ** to 0.
4150 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
4151 int iResult;
4152 int nResult = sqlite3ExprVectorSize(p);
4153 if( nResult==1 ){
4154 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
4155 }else{
4156 *piFreeable = 0;
4157 if( p->op==TK_SELECT ){
4158 #if SQLITE_OMIT_SUBQUERY
4159 iResult = 0;
4160 #else
4161 iResult = sqlite3CodeSubselect(pParse, p);
4162 #endif
4163 }else{
4164 int i;
4165 iResult = pParse->nMem+1;
4166 pParse->nMem += nResult;
4167 assert( ExprUseXList(p) );
4168 for(i=0; i<nResult; i++){
4169 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
4173 return iResult;
4177 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
4178 ** so that a subsequent copy will not be merged into this one.
4180 static void setDoNotMergeFlagOnCopy(Vdbe *v){
4181 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
4182 sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergeable */
4187 ** Generate code to implement special SQL functions that are implemented
4188 ** in-line rather than by using the usual callbacks.
4190 static int exprCodeInlineFunction(
4191 Parse *pParse, /* Parsing context */
4192 ExprList *pFarg, /* List of function arguments */
4193 int iFuncId, /* Function ID. One of the INTFUNC_... values */
4194 int target /* Store function result in this register */
4196 int nFarg;
4197 Vdbe *v = pParse->pVdbe;
4198 assert( v!=0 );
4199 assert( pFarg!=0 );
4200 nFarg = pFarg->nExpr;
4201 assert( nFarg>0 ); /* All in-line functions have at least one argument */
4202 switch( iFuncId ){
4203 case INLINEFUNC_coalesce: {
4204 /* Attempt a direct implementation of the built-in COALESCE() and
4205 ** IFNULL() functions. This avoids unnecessary evaluation of
4206 ** arguments past the first non-NULL argument.
4208 int endCoalesce = sqlite3VdbeMakeLabel(pParse);
4209 int i;
4210 assert( nFarg>=2 );
4211 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
4212 for(i=1; i<nFarg; i++){
4213 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
4214 VdbeCoverage(v);
4215 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
4217 setDoNotMergeFlagOnCopy(v);
4218 sqlite3VdbeResolveLabel(v, endCoalesce);
4219 break;
4221 case INLINEFUNC_iif: {
4222 Expr caseExpr;
4223 memset(&caseExpr, 0, sizeof(caseExpr));
4224 caseExpr.op = TK_CASE;
4225 caseExpr.x.pList = pFarg;
4226 return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
4228 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4229 case INLINEFUNC_sqlite_offset: {
4230 Expr *pArg = pFarg->a[0].pExpr;
4231 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
4232 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
4233 }else{
4234 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4236 break;
4238 #endif
4239 default: {
4240 /* The UNLIKELY() function is a no-op. The result is the value
4241 ** of the first argument.
4243 assert( nFarg==1 || nFarg==2 );
4244 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
4245 break;
4248 /***********************************************************************
4249 ** Test-only SQL functions that are only usable if enabled
4250 ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
4252 #if !defined(SQLITE_UNTESTABLE)
4253 case INLINEFUNC_expr_compare: {
4254 /* Compare two expressions using sqlite3ExprCompare() */
4255 assert( nFarg==2 );
4256 sqlite3VdbeAddOp2(v, OP_Integer,
4257 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4258 target);
4259 break;
4262 case INLINEFUNC_expr_implies_expr: {
4263 /* Compare two expressions using sqlite3ExprImpliesExpr() */
4264 assert( nFarg==2 );
4265 sqlite3VdbeAddOp2(v, OP_Integer,
4266 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
4267 target);
4268 break;
4271 case INLINEFUNC_implies_nonnull_row: {
4272 /* Result of sqlite3ExprImpliesNonNullRow() */
4273 Expr *pA1;
4274 assert( nFarg==2 );
4275 pA1 = pFarg->a[1].pExpr;
4276 if( pA1->op==TK_COLUMN ){
4277 sqlite3VdbeAddOp2(v, OP_Integer,
4278 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1),
4279 target);
4280 }else{
4281 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4283 break;
4286 case INLINEFUNC_affinity: {
4287 /* The AFFINITY() function evaluates to a string that describes
4288 ** the type affinity of the argument. This is used for testing of
4289 ** the SQLite type logic.
4291 const char *azAff[] = { "blob", "text", "numeric", "integer",
4292 "real", "flexnum" };
4293 char aff;
4294 assert( nFarg==1 );
4295 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
4296 assert( aff<=SQLITE_AFF_NONE
4297 || (aff>=SQLITE_AFF_BLOB && aff<=SQLITE_AFF_FLEXNUM) );
4298 sqlite3VdbeLoadString(v, target,
4299 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
4300 break;
4302 #endif /* !defined(SQLITE_UNTESTABLE) */
4304 return target;
4308 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
4309 ** If it is, then resolve the expression by reading from the index and
4310 ** return the register into which the value has been read. If pExpr is
4311 ** not an indexed expression, then return negative.
4313 static SQLITE_NOINLINE int sqlite3IndexedExprLookup(
4314 Parse *pParse, /* The parsing context */
4315 Expr *pExpr, /* The expression to potentially bypass */
4316 int target /* Where to store the result of the expression */
4318 IndexedExpr *p;
4319 Vdbe *v;
4320 for(p=pParse->pIdxEpr; p; p=p->pIENext){
4321 u8 exprAff;
4322 int iDataCur = p->iDataCur;
4323 if( iDataCur<0 ) continue;
4324 if( pParse->iSelfTab ){
4325 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
4326 iDataCur = -1;
4328 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
4329 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
4330 exprAff = sqlite3ExprAffinity(pExpr);
4331 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
4332 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
4333 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
4335 /* Affinity mismatch on a generated column */
4336 continue;
4339 v = pParse->pVdbe;
4340 assert( v!=0 );
4341 if( p->bMaybeNullRow ){
4342 /* If the index is on a NULL row due to an outer join, then we
4343 ** cannot extract the value from the index. The value must be
4344 ** computed using the original expression. */
4345 int addr = sqlite3VdbeCurrentAddr(v);
4346 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
4347 VdbeCoverage(v);
4348 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4349 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4350 sqlite3VdbeGoto(v, 0);
4351 p = pParse->pIdxEpr;
4352 pParse->pIdxEpr = 0;
4353 sqlite3ExprCode(pParse, pExpr, target);
4354 pParse->pIdxEpr = p;
4355 sqlite3VdbeJumpHere(v, addr+2);
4356 }else{
4357 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
4358 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
4360 return target;
4362 return -1; /* Not found */
4367 ** Expresion pExpr is guaranteed to be a TK_COLUMN or equivalent. This
4368 ** function checks the Parse.pIdxPartExpr list to see if this column
4369 ** can be replaced with a constant value. If so, it generates code to
4370 ** put the constant value in a register (ideally, but not necessarily,
4371 ** register iTarget) and returns the register number.
4373 ** Or, if the TK_COLUMN cannot be replaced by a constant, zero is
4374 ** returned.
4376 static int exprPartidxExprLookup(Parse *pParse, Expr *pExpr, int iTarget){
4377 IndexedExpr *p;
4378 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
4379 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
4380 Vdbe *v = pParse->pVdbe;
4381 int addr = 0;
4382 int ret;
4384 if( p->bMaybeNullRow ){
4385 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
4387 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
4388 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
4389 (const char*)&p->aff, 1);
4390 if( addr ){
4391 sqlite3VdbeJumpHere(v, addr);
4392 sqlite3VdbeChangeP3(v, addr, ret);
4394 return ret;
4397 return 0;
4402 ** Generate code into the current Vdbe to evaluate the given
4403 ** expression. Attempt to store the results in register "target".
4404 ** Return the register where results are stored.
4406 ** With this routine, there is no guarantee that results will
4407 ** be stored in target. The result might be stored in some other
4408 ** register if it is convenient to do so. The calling function
4409 ** must check the return code and move the results to the desired
4410 ** register.
4412 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
4413 Vdbe *v = pParse->pVdbe; /* The VM under construction */
4414 int op; /* The opcode being coded */
4415 int inReg = target; /* Results stored in register inReg */
4416 int regFree1 = 0; /* If non-zero free this temporary register */
4417 int regFree2 = 0; /* If non-zero free this temporary register */
4418 int r1, r2; /* Various register numbers */
4419 Expr tempX; /* Temporary expression node */
4420 int p5 = 0;
4422 assert( target>0 && target<=pParse->nMem );
4423 assert( v!=0 );
4425 expr_code_doover:
4426 if( pExpr==0 ){
4427 op = TK_NULL;
4428 }else if( pParse->pIdxEpr!=0
4429 && !ExprHasProperty(pExpr, EP_Leaf)
4430 && (r1 = sqlite3IndexedExprLookup(pParse, pExpr, target))>=0
4432 return r1;
4433 }else{
4434 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
4435 op = pExpr->op;
4437 assert( op!=TK_ORDER );
4438 switch( op ){
4439 case TK_AGG_COLUMN: {
4440 AggInfo *pAggInfo = pExpr->pAggInfo;
4441 struct AggInfo_col *pCol;
4442 assert( pAggInfo!=0 );
4443 assert( pExpr->iAgg>=0 );
4444 if( pExpr->iAgg>=pAggInfo->nColumn ){
4445 /* Happens when the left table of a RIGHT JOIN is null and
4446 ** is using an expression index */
4447 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4448 #ifdef SQLITE_VDBE_COVERAGE
4449 /* Verify that the OP_Null above is exercised by tests
4450 ** tag-20230325-2 */
4451 sqlite3VdbeAddOp3(v, OP_NotNull, target, 1, 20230325);
4452 VdbeCoverageNeverTaken(v);
4453 #endif
4454 break;
4456 pCol = &pAggInfo->aCol[pExpr->iAgg];
4457 if( !pAggInfo->directMode ){
4458 return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
4459 }else if( pAggInfo->useSortingIdx ){
4460 Table *pTab = pCol->pTab;
4461 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
4462 pCol->iSorterColumn, target);
4463 if( pTab==0 ){
4464 /* No comment added */
4465 }else if( pCol->iColumn<0 ){
4466 VdbeComment((v,"%s.rowid",pTab->zName));
4467 }else{
4468 VdbeComment((v,"%s.%s",
4469 pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
4470 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
4471 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4474 return target;
4475 }else if( pExpr->y.pTab==0 ){
4476 /* This case happens when the argument to an aggregate function
4477 ** is rewritten by aggregateConvertIndexedExprRefToColumn() */
4478 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target);
4479 return target;
4481 /* Otherwise, fall thru into the TK_COLUMN case */
4482 /* no break */ deliberate_fall_through
4484 case TK_COLUMN: {
4485 int iTab = pExpr->iTable;
4486 int iReg;
4487 if( ExprHasProperty(pExpr, EP_FixedCol) ){
4488 /* This COLUMN expression is really a constant due to WHERE clause
4489 ** constraints, and that constant is coded by the pExpr->pLeft
4490 ** expression. However, make sure the constant has the correct
4491 ** datatype by applying the Affinity of the table column to the
4492 ** constant.
4494 int aff;
4495 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
4496 assert( ExprUseYTab(pExpr) );
4497 assert( pExpr->y.pTab!=0 );
4498 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
4499 if( aff>SQLITE_AFF_BLOB ){
4500 static const char zAff[] = "B\000C\000D\000E\000F";
4501 assert( SQLITE_AFF_BLOB=='A' );
4502 assert( SQLITE_AFF_TEXT=='B' );
4503 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
4504 &zAff[(aff-'B')*2], P4_STATIC);
4506 return iReg;
4508 if( iTab<0 ){
4509 if( pParse->iSelfTab<0 ){
4510 /* Other columns in the same row for CHECK constraints or
4511 ** generated columns or for inserting into partial index.
4512 ** The row is unpacked into registers beginning at
4513 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
4514 ** immediately prior to the first column.
4516 Column *pCol;
4517 Table *pTab;
4518 int iSrc;
4519 int iCol = pExpr->iColumn;
4520 assert( ExprUseYTab(pExpr) );
4521 pTab = pExpr->y.pTab;
4522 assert( pTab!=0 );
4523 assert( iCol>=XN_ROWID );
4524 assert( iCol<pTab->nCol );
4525 if( iCol<0 ){
4526 return -1-pParse->iSelfTab;
4528 pCol = pTab->aCol + iCol;
4529 testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
4530 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
4531 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
4532 if( pCol->colFlags & COLFLAG_GENERATED ){
4533 if( pCol->colFlags & COLFLAG_BUSY ){
4534 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
4535 pCol->zCnName);
4536 return 0;
4538 pCol->colFlags |= COLFLAG_BUSY;
4539 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
4540 sqlite3ExprCodeGeneratedColumn(pParse, pTab, pCol, iSrc);
4542 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
4543 return iSrc;
4544 }else
4545 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
4546 if( pCol->affinity==SQLITE_AFF_REAL ){
4547 sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
4548 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
4549 return target;
4550 }else{
4551 return iSrc;
4553 }else{
4554 /* Coding an expression that is part of an index where column names
4555 ** in the index refer to the table to which the index belongs */
4556 iTab = pParse->iSelfTab - 1;
4559 else if( pParse->pIdxPartExpr
4560 && 0!=(r1 = exprPartidxExprLookup(pParse, pExpr, target))
4562 return r1;
4564 assert( ExprUseYTab(pExpr) );
4565 assert( pExpr->y.pTab!=0 );
4566 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
4567 pExpr->iColumn, iTab, target,
4568 pExpr->op2);
4569 return iReg;
4571 case TK_INTEGER: {
4572 codeInteger(pParse, pExpr, 0, target);
4573 return target;
4575 case TK_TRUEFALSE: {
4576 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
4577 return target;
4579 #ifndef SQLITE_OMIT_FLOATING_POINT
4580 case TK_FLOAT: {
4581 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4582 codeReal(v, pExpr->u.zToken, 0, target);
4583 return target;
4585 #endif
4586 case TK_STRING: {
4587 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4588 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
4589 return target;
4591 default: {
4592 /* Make NULL the default case so that if a bug causes an illegal
4593 ** Expr node to be passed into this function, it will be handled
4594 ** sanely and not crash. But keep the assert() to bring the problem
4595 ** to the attention of the developers. */
4596 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
4597 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4598 return target;
4600 #ifndef SQLITE_OMIT_BLOB_LITERAL
4601 case TK_BLOB: {
4602 int n;
4603 const char *z;
4604 char *zBlob;
4605 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4606 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
4607 assert( pExpr->u.zToken[1]=='\'' );
4608 z = &pExpr->u.zToken[2];
4609 n = sqlite3Strlen30(z) - 1;
4610 assert( z[n]=='\'' );
4611 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
4612 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
4613 return target;
4615 #endif
4616 case TK_VARIABLE: {
4617 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4618 assert( pExpr->u.zToken!=0 );
4619 assert( pExpr->u.zToken[0]!=0 );
4620 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
4621 return target;
4623 case TK_REGISTER: {
4624 return pExpr->iTable;
4626 #ifndef SQLITE_OMIT_CAST
4627 case TK_CAST: {
4628 /* Expressions of the form: CAST(pLeft AS token) */
4629 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4630 assert( inReg==target );
4631 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4632 sqlite3VdbeAddOp2(v, OP_Cast, target,
4633 sqlite3AffinityType(pExpr->u.zToken, 0));
4634 return inReg;
4636 #endif /* SQLITE_OMIT_CAST */
4637 case TK_IS:
4638 case TK_ISNOT:
4639 op = (op==TK_IS) ? TK_EQ : TK_NE;
4640 p5 = SQLITE_NULLEQ;
4641 /* fall-through */
4642 case TK_LT:
4643 case TK_LE:
4644 case TK_GT:
4645 case TK_GE:
4646 case TK_NE:
4647 case TK_EQ: {
4648 Expr *pLeft = pExpr->pLeft;
4649 if( sqlite3ExprIsVector(pLeft) ){
4650 codeVectorCompare(pParse, pExpr, target, op, p5);
4651 }else{
4652 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
4653 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4654 sqlite3VdbeAddOp2(v, OP_Integer, 1, inReg);
4655 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
4656 sqlite3VdbeCurrentAddr(v)+2, p5,
4657 ExprHasProperty(pExpr,EP_Commuted));
4658 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4659 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4660 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4661 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4662 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
4663 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
4664 if( p5==SQLITE_NULLEQ ){
4665 sqlite3VdbeAddOp2(v, OP_Integer, 0, inReg);
4666 }else{
4667 sqlite3VdbeAddOp3(v, OP_ZeroOrNull, r1, inReg, r2);
4669 testcase( regFree1==0 );
4670 testcase( regFree2==0 );
4672 break;
4674 case TK_AND:
4675 case TK_OR:
4676 case TK_PLUS:
4677 case TK_STAR:
4678 case TK_MINUS:
4679 case TK_REM:
4680 case TK_BITAND:
4681 case TK_BITOR:
4682 case TK_SLASH:
4683 case TK_LSHIFT:
4684 case TK_RSHIFT:
4685 case TK_CONCAT: {
4686 assert( TK_AND==OP_And ); testcase( op==TK_AND );
4687 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
4688 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
4689 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
4690 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
4691 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
4692 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
4693 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
4694 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
4695 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
4696 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
4697 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4698 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4699 sqlite3VdbeAddOp3(v, op, r2, r1, target);
4700 testcase( regFree1==0 );
4701 testcase( regFree2==0 );
4702 break;
4704 case TK_UMINUS: {
4705 Expr *pLeft = pExpr->pLeft;
4706 assert( pLeft );
4707 if( pLeft->op==TK_INTEGER ){
4708 codeInteger(pParse, pLeft, 1, target);
4709 return target;
4710 #ifndef SQLITE_OMIT_FLOATING_POINT
4711 }else if( pLeft->op==TK_FLOAT ){
4712 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4713 codeReal(v, pLeft->u.zToken, 1, target);
4714 return target;
4715 #endif
4716 }else{
4717 tempX.op = TK_INTEGER;
4718 tempX.flags = EP_IntValue|EP_TokenOnly;
4719 tempX.u.iValue = 0;
4720 ExprClearVVAProperties(&tempX);
4721 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
4722 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
4723 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
4724 testcase( regFree2==0 );
4726 break;
4728 case TK_BITNOT:
4729 case TK_NOT: {
4730 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
4731 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
4732 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4733 testcase( regFree1==0 );
4734 sqlite3VdbeAddOp2(v, op, r1, inReg);
4735 break;
4737 case TK_TRUTH: {
4738 int isTrue; /* IS TRUE or IS NOT TRUE */
4739 int bNormal; /* IS TRUE or IS FALSE */
4740 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4741 testcase( regFree1==0 );
4742 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
4743 bNormal = pExpr->op2==TK_IS;
4744 testcase( isTrue && bNormal);
4745 testcase( !isTrue && bNormal);
4746 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
4747 break;
4749 case TK_ISNULL:
4750 case TK_NOTNULL: {
4751 int addr;
4752 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4753 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4754 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4755 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4756 testcase( regFree1==0 );
4757 addr = sqlite3VdbeAddOp1(v, op, r1);
4758 VdbeCoverageIf(v, op==TK_ISNULL);
4759 VdbeCoverageIf(v, op==TK_NOTNULL);
4760 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
4761 sqlite3VdbeJumpHere(v, addr);
4762 break;
4764 case TK_AGG_FUNCTION: {
4765 AggInfo *pInfo = pExpr->pAggInfo;
4766 if( pInfo==0
4767 || NEVER(pExpr->iAgg<0)
4768 || NEVER(pExpr->iAgg>=pInfo->nFunc)
4770 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4771 sqlite3ErrorMsg(pParse, "misuse of aggregate: %#T()", pExpr);
4772 }else{
4773 return AggInfoFuncReg(pInfo, pExpr->iAgg);
4775 break;
4777 case TK_FUNCTION: {
4778 ExprList *pFarg; /* List of function arguments */
4779 int nFarg; /* Number of function arguments */
4780 FuncDef *pDef; /* The function definition object */
4781 const char *zId; /* The function name */
4782 u32 constMask = 0; /* Mask of function arguments that are constant */
4783 int i; /* Loop counter */
4784 sqlite3 *db = pParse->db; /* The database connection */
4785 u8 enc = ENC(db); /* The text encoding used by this database */
4786 CollSeq *pColl = 0; /* A collating sequence */
4788 #ifndef SQLITE_OMIT_WINDOWFUNC
4789 if( ExprHasProperty(pExpr, EP_WinFunc) ){
4790 return pExpr->y.pWin->regResult;
4792 #endif
4794 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
4795 /* SQL functions can be expensive. So try to avoid running them
4796 ** multiple times if we know they always give the same result */
4797 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
4799 assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
4800 assert( ExprUseXList(pExpr) );
4801 pFarg = pExpr->x.pList;
4802 nFarg = pFarg ? pFarg->nExpr : 0;
4803 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4804 zId = pExpr->u.zToken;
4805 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
4806 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
4807 if( pDef==0 && pParse->explain ){
4808 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
4810 #endif
4811 if( pDef==0 || pDef->xFinalize!=0 ){
4812 sqlite3ErrorMsg(pParse, "unknown function: %#T()", pExpr);
4813 break;
4815 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
4816 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
4817 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
4818 return exprCodeInlineFunction(pParse, pFarg,
4819 SQLITE_PTR_TO_INT(pDef->pUserData), target);
4820 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
4821 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
4824 for(i=0; i<nFarg; i++){
4825 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
4826 testcase( i==31 );
4827 constMask |= MASKBIT32(i);
4829 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
4830 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
4833 if( pFarg ){
4834 if( constMask ){
4835 r1 = pParse->nMem+1;
4836 pParse->nMem += nFarg;
4837 }else{
4838 r1 = sqlite3GetTempRange(pParse, nFarg);
4841 /* For length() and typeof() and octet_length() functions,
4842 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
4843 ** or OPFLAG_TYPEOFARG or OPFLAG_BYTELENARG respectively, to avoid
4844 ** unnecessary data loading.
4846 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
4847 u8 exprOp;
4848 assert( nFarg==1 );
4849 assert( pFarg->a[0].pExpr!=0 );
4850 exprOp = pFarg->a[0].pExpr->op;
4851 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
4852 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
4853 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
4854 assert( SQLITE_FUNC_BYTELEN==OPFLAG_BYTELENARG );
4855 assert( (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG)==OPFLAG_BYTELENARG );
4856 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG );
4857 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG );
4858 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG);
4859 pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG;
4863 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0, SQLITE_ECEL_FACTOR);
4864 }else{
4865 r1 = 0;
4867 #ifndef SQLITE_OMIT_VIRTUALTABLE
4868 /* Possibly overload the function if the first argument is
4869 ** a virtual table column.
4871 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
4872 ** second argument, not the first, as the argument to test to
4873 ** see if it is a column in a virtual table. This is done because
4874 ** the left operand of infix functions (the operand we want to
4875 ** control overloading) ends up as the second argument to the
4876 ** function. The expression "A glob B" is equivalent to
4877 ** "glob(B,A). We want to use the A in "A glob B" to test
4878 ** for function overloading. But we use the B term in "glob(B,A)".
4880 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
4881 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
4882 }else if( nFarg>0 ){
4883 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
4885 #endif
4886 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
4887 if( !pColl ) pColl = db->pDfltColl;
4888 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
4890 sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
4891 pDef, pExpr->op2);
4892 if( nFarg ){
4893 if( constMask==0 ){
4894 sqlite3ReleaseTempRange(pParse, r1, nFarg);
4895 }else{
4896 sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
4899 return target;
4901 #ifndef SQLITE_OMIT_SUBQUERY
4902 case TK_EXISTS:
4903 case TK_SELECT: {
4904 int nCol;
4905 testcase( op==TK_EXISTS );
4906 testcase( op==TK_SELECT );
4907 if( pParse->db->mallocFailed ){
4908 return 0;
4909 }else if( op==TK_SELECT
4910 && ALWAYS( ExprUseXSelect(pExpr) )
4911 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
4913 sqlite3SubselectError(pParse, nCol, 1);
4914 }else{
4915 return sqlite3CodeSubselect(pParse, pExpr);
4917 break;
4919 case TK_SELECT_COLUMN: {
4920 int n;
4921 Expr *pLeft = pExpr->pLeft;
4922 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
4923 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
4924 pLeft->op2 = pParse->withinRJSubrtn;
4926 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
4927 n = sqlite3ExprVectorSize(pLeft);
4928 if( pExpr->iTable!=n ){
4929 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
4930 pExpr->iTable, n);
4932 return pLeft->iTable + pExpr->iColumn;
4934 case TK_IN: {
4935 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
4936 int destIfNull = sqlite3VdbeMakeLabel(pParse);
4937 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
4938 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4939 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
4940 sqlite3VdbeResolveLabel(v, destIfFalse);
4941 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
4942 sqlite3VdbeResolveLabel(v, destIfNull);
4943 return target;
4945 #endif /* SQLITE_OMIT_SUBQUERY */
4949 ** x BETWEEN y AND z
4951 ** This is equivalent to
4953 ** x>=y AND x<=z
4955 ** X is stored in pExpr->pLeft.
4956 ** Y is stored in pExpr->pList->a[0].pExpr.
4957 ** Z is stored in pExpr->pList->a[1].pExpr.
4959 case TK_BETWEEN: {
4960 exprCodeBetween(pParse, pExpr, target, 0, 0);
4961 return target;
4963 case TK_COLLATE: {
4964 if( !ExprHasProperty(pExpr, EP_Collate) ){
4965 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
4966 ** "SOFT-COLLATE" that is added to constraints that are pushed down
4967 ** from outer queries into sub-queries by the push-down optimization.
4968 ** Clear subtypes as subtypes may not cross a subquery boundary.
4970 assert( pExpr->pLeft );
4971 sqlite3ExprCode(pParse, pExpr->pLeft, target);
4972 sqlite3VdbeAddOp1(v, OP_ClrSubtype, target);
4973 return target;
4974 }else{
4975 pExpr = pExpr->pLeft;
4976 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
4979 case TK_SPAN:
4980 case TK_UPLUS: {
4981 pExpr = pExpr->pLeft;
4982 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
4985 case TK_TRIGGER: {
4986 /* If the opcode is TK_TRIGGER, then the expression is a reference
4987 ** to a column in the new.* or old.* pseudo-tables available to
4988 ** trigger programs. In this case Expr.iTable is set to 1 for the
4989 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
4990 ** is set to the column of the pseudo-table to read, or to -1 to
4991 ** read the rowid field.
4993 ** The expression is implemented using an OP_Param opcode. The p1
4994 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
4995 ** to reference another column of the old.* pseudo-table, where
4996 ** i is the index of the column. For a new.rowid reference, p1 is
4997 ** set to (n+1), where n is the number of columns in each pseudo-table.
4998 ** For a reference to any other column in the new.* pseudo-table, p1
4999 ** is set to (n+2+i), where n and i are as defined previously. For
5000 ** example, if the table on which triggers are being fired is
5001 ** declared as:
5003 ** CREATE TABLE t1(a, b);
5005 ** Then p1 is interpreted as follows:
5007 ** p1==0 -> old.rowid p1==3 -> new.rowid
5008 ** p1==1 -> old.a p1==4 -> new.a
5009 ** p1==2 -> old.b p1==5 -> new.b
5011 Table *pTab;
5012 int iCol;
5013 int p1;
5015 assert( ExprUseYTab(pExpr) );
5016 pTab = pExpr->y.pTab;
5017 iCol = pExpr->iColumn;
5018 p1 = pExpr->iTable * (pTab->nCol+1) + 1
5019 + sqlite3TableColumnToStorage(pTab, iCol);
5021 assert( pExpr->iTable==0 || pExpr->iTable==1 );
5022 assert( iCol>=-1 && iCol<pTab->nCol );
5023 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
5024 assert( p1>=0 && p1<(pTab->nCol*2+2) );
5026 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
5027 VdbeComment((v, "r[%d]=%s.%s", target,
5028 (pExpr->iTable ? "new" : "old"),
5029 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
5032 #ifndef SQLITE_OMIT_FLOATING_POINT
5033 /* If the column has REAL affinity, it may currently be stored as an
5034 ** integer. Use OP_RealAffinity to make sure it is really real.
5036 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
5037 ** floating point when extracting it from the record. */
5038 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
5039 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
5041 #endif
5042 break;
5045 case TK_VECTOR: {
5046 sqlite3ErrorMsg(pParse, "row value misused");
5047 break;
5050 /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
5051 ** that derive from the right-hand table of a LEFT JOIN. The
5052 ** Expr.iTable value is the table number for the right-hand table.
5053 ** The expression is only evaluated if that table is not currently
5054 ** on a LEFT JOIN NULL row.
5056 case TK_IF_NULL_ROW: {
5057 int addrINR;
5058 u8 okConstFactor = pParse->okConstFactor;
5059 AggInfo *pAggInfo = pExpr->pAggInfo;
5060 if( pAggInfo ){
5061 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
5062 if( !pAggInfo->directMode ){
5063 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg);
5064 break;
5066 if( pExpr->pAggInfo->useSortingIdx ){
5067 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
5068 pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
5069 target);
5070 inReg = target;
5071 break;
5074 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target);
5075 /* The OP_IfNullRow opcode above can overwrite the result register with
5076 ** NULL. So we have to ensure that the result register is not a value
5077 ** that is suppose to be a constant. Two defenses are needed:
5078 ** (1) Temporarily disable factoring of constant expressions
5079 ** (2) Make sure the computed value really is stored in register
5080 ** "target" and not someplace else.
5082 pParse->okConstFactor = 0; /* note (1) above */
5083 sqlite3ExprCode(pParse, pExpr->pLeft, target);
5084 assert( target==inReg );
5085 pParse->okConstFactor = okConstFactor;
5086 sqlite3VdbeJumpHere(v, addrINR);
5087 break;
5091 ** Form A:
5092 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5094 ** Form B:
5095 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
5097 ** Form A is can be transformed into the equivalent form B as follows:
5098 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
5099 ** WHEN x=eN THEN rN ELSE y END
5101 ** X (if it exists) is in pExpr->pLeft.
5102 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
5103 ** odd. The Y is also optional. If the number of elements in x.pList
5104 ** is even, then Y is omitted and the "otherwise" result is NULL.
5105 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
5107 ** The result of the expression is the Ri for the first matching Ei,
5108 ** or if there is no matching Ei, the ELSE term Y, or if there is
5109 ** no ELSE term, NULL.
5111 case TK_CASE: {
5112 int endLabel; /* GOTO label for end of CASE stmt */
5113 int nextCase; /* GOTO label for next WHEN clause */
5114 int nExpr; /* 2x number of WHEN terms */
5115 int i; /* Loop counter */
5116 ExprList *pEList; /* List of WHEN terms */
5117 struct ExprList_item *aListelem; /* Array of WHEN terms */
5118 Expr opCompare; /* The X==Ei expression */
5119 Expr *pX; /* The X expression */
5120 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
5121 Expr *pDel = 0;
5122 sqlite3 *db = pParse->db;
5124 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
5125 assert(pExpr->x.pList->nExpr > 0);
5126 pEList = pExpr->x.pList;
5127 aListelem = pEList->a;
5128 nExpr = pEList->nExpr;
5129 endLabel = sqlite3VdbeMakeLabel(pParse);
5130 if( (pX = pExpr->pLeft)!=0 ){
5131 pDel = sqlite3ExprDup(db, pX, 0);
5132 if( db->mallocFailed ){
5133 sqlite3ExprDelete(db, pDel);
5134 break;
5136 testcase( pX->op==TK_COLUMN );
5137 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5138 testcase( regFree1==0 );
5139 memset(&opCompare, 0, sizeof(opCompare));
5140 opCompare.op = TK_EQ;
5141 opCompare.pLeft = pDel;
5142 pTest = &opCompare;
5143 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
5144 ** The value in regFree1 might get SCopy-ed into the file result.
5145 ** So make sure that the regFree1 register is not reused for other
5146 ** purposes and possibly overwritten. */
5147 regFree1 = 0;
5149 for(i=0; i<nExpr-1; i=i+2){
5150 if( pX ){
5151 assert( pTest!=0 );
5152 opCompare.pRight = aListelem[i].pExpr;
5153 }else{
5154 pTest = aListelem[i].pExpr;
5156 nextCase = sqlite3VdbeMakeLabel(pParse);
5157 testcase( pTest->op==TK_COLUMN );
5158 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
5159 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
5160 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
5161 sqlite3VdbeGoto(v, endLabel);
5162 sqlite3VdbeResolveLabel(v, nextCase);
5164 if( (nExpr&1)!=0 ){
5165 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
5166 }else{
5167 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
5169 sqlite3ExprDelete(db, pDel);
5170 setDoNotMergeFlagOnCopy(v);
5171 sqlite3VdbeResolveLabel(v, endLabel);
5172 break;
5174 #ifndef SQLITE_OMIT_TRIGGER
5175 case TK_RAISE: {
5176 assert( pExpr->affExpr==OE_Rollback
5177 || pExpr->affExpr==OE_Abort
5178 || pExpr->affExpr==OE_Fail
5179 || pExpr->affExpr==OE_Ignore
5181 if( !pParse->pTriggerTab && !pParse->nested ){
5182 sqlite3ErrorMsg(pParse,
5183 "RAISE() may only be used within a trigger-program");
5184 return 0;
5186 if( pExpr->affExpr==OE_Abort ){
5187 sqlite3MayAbort(pParse);
5189 assert( !ExprHasProperty(pExpr, EP_IntValue) );
5190 if( pExpr->affExpr==OE_Ignore ){
5191 sqlite3VdbeAddOp4(
5192 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
5193 VdbeCoverage(v);
5194 }else{
5195 sqlite3HaltConstraint(pParse,
5196 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
5197 pExpr->affExpr, pExpr->u.zToken, 0, 0);
5200 break;
5202 #endif
5204 sqlite3ReleaseTempReg(pParse, regFree1);
5205 sqlite3ReleaseTempReg(pParse, regFree2);
5206 return inReg;
5210 ** Generate code that will evaluate expression pExpr just one time
5211 ** per prepared statement execution.
5213 ** If the expression uses functions (that might throw an exception) then
5214 ** guard them with an OP_Once opcode to ensure that the code is only executed
5215 ** once. If no functions are involved, then factor the code out and put it at
5216 ** the end of the prepared statement in the initialization section.
5218 ** If regDest>0 then the result is always stored in that register and the
5219 ** result is not reusable. If regDest<0 then this routine is free to
5220 ** store the value wherever it wants. The register where the expression
5221 ** is stored is returned. When regDest<0, two identical expressions might
5222 ** code to the same register, if they do not contain function calls and hence
5223 ** are factored out into the initialization section at the end of the
5224 ** prepared statement.
5226 int sqlite3ExprCodeRunJustOnce(
5227 Parse *pParse, /* Parsing context */
5228 Expr *pExpr, /* The expression to code when the VDBE initializes */
5229 int regDest /* Store the value in this register */
5231 ExprList *p;
5232 assert( ConstFactorOk(pParse) );
5233 assert( regDest!=0 );
5234 p = pParse->pConstExpr;
5235 if( regDest<0 && p ){
5236 struct ExprList_item *pItem;
5237 int i;
5238 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
5239 if( pItem->fg.reusable
5240 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
5242 return pItem->u.iConstExprReg;
5246 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
5247 if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
5248 Vdbe *v = pParse->pVdbe;
5249 int addr;
5250 assert( v );
5251 addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
5252 pParse->okConstFactor = 0;
5253 if( !pParse->db->mallocFailed ){
5254 if( regDest<0 ) regDest = ++pParse->nMem;
5255 sqlite3ExprCode(pParse, pExpr, regDest);
5257 pParse->okConstFactor = 1;
5258 sqlite3ExprDelete(pParse->db, pExpr);
5259 sqlite3VdbeJumpHere(v, addr);
5260 }else{
5261 p = sqlite3ExprListAppend(pParse, p, pExpr);
5262 if( p ){
5263 struct ExprList_item *pItem = &p->a[p->nExpr-1];
5264 pItem->fg.reusable = regDest<0;
5265 if( regDest<0 ) regDest = ++pParse->nMem;
5266 pItem->u.iConstExprReg = regDest;
5268 pParse->pConstExpr = p;
5270 return regDest;
5274 ** Generate code to evaluate an expression and store the results
5275 ** into a register. Return the register number where the results
5276 ** are stored.
5278 ** If the register is a temporary register that can be deallocated,
5279 ** then write its number into *pReg. If the result register is not
5280 ** a temporary, then set *pReg to zero.
5282 ** If pExpr is a constant, then this routine might generate this
5283 ** code to fill the register in the initialization section of the
5284 ** VDBE program, in order to factor it out of the evaluation loop.
5286 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
5287 int r2;
5288 pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
5289 if( ConstFactorOk(pParse)
5290 && ALWAYS(pExpr!=0)
5291 && pExpr->op!=TK_REGISTER
5292 && sqlite3ExprIsConstantNotJoin(pExpr)
5294 *pReg = 0;
5295 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
5296 }else{
5297 int r1 = sqlite3GetTempReg(pParse);
5298 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
5299 if( r2==r1 ){
5300 *pReg = r1;
5301 }else{
5302 sqlite3ReleaseTempReg(pParse, r1);
5303 *pReg = 0;
5306 return r2;
5310 ** Generate code that will evaluate expression pExpr and store the
5311 ** results in register target. The results are guaranteed to appear
5312 ** in register target.
5314 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
5315 int inReg;
5317 assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
5318 assert( target>0 && target<=pParse->nMem );
5319 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
5320 if( pParse->pVdbe==0 ) return;
5321 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
5322 if( inReg!=target ){
5323 u8 op;
5324 Expr *pX = sqlite3ExprSkipCollateAndLikely(pExpr);
5325 testcase( pX!=pExpr );
5326 if( ALWAYS(pX)
5327 && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER)
5329 op = OP_Copy;
5330 }else{
5331 op = OP_SCopy;
5333 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
5338 ** Make a transient copy of expression pExpr and then code it using
5339 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
5340 ** except that the input expression is guaranteed to be unchanged.
5342 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
5343 sqlite3 *db = pParse->db;
5344 pExpr = sqlite3ExprDup(db, pExpr, 0);
5345 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
5346 sqlite3ExprDelete(db, pExpr);
5350 ** Generate code that will evaluate expression pExpr and store the
5351 ** results in register target. The results are guaranteed to appear
5352 ** in register target. If the expression is constant, then this routine
5353 ** might choose to code the expression at initialization time.
5355 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
5356 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
5357 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
5358 }else{
5359 sqlite3ExprCodeCopy(pParse, pExpr, target);
5364 ** Generate code that pushes the value of every element of the given
5365 ** expression list into a sequence of registers beginning at target.
5367 ** Return the number of elements evaluated. The number returned will
5368 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
5369 ** is defined.
5371 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
5372 ** filled using OP_SCopy. OP_Copy must be used instead.
5374 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
5375 ** factored out into initialization code.
5377 ** The SQLITE_ECEL_REF flag means that expressions in the list with
5378 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
5379 ** in registers at srcReg, and so the value can be copied from there.
5380 ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
5381 ** are simply omitted rather than being copied from srcReg.
5383 int sqlite3ExprCodeExprList(
5384 Parse *pParse, /* Parsing context */
5385 ExprList *pList, /* The expression list to be coded */
5386 int target, /* Where to write results */
5387 int srcReg, /* Source registers if SQLITE_ECEL_REF */
5388 u8 flags /* SQLITE_ECEL_* flags */
5390 struct ExprList_item *pItem;
5391 int i, j, n;
5392 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
5393 Vdbe *v = pParse->pVdbe;
5394 assert( pList!=0 );
5395 assert( target>0 );
5396 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
5397 n = pList->nExpr;
5398 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
5399 for(pItem=pList->a, i=0; i<n; i++, pItem++){
5400 Expr *pExpr = pItem->pExpr;
5401 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
5402 if( pItem->fg.bSorterRef ){
5403 i--;
5404 n--;
5405 }else
5406 #endif
5407 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
5408 if( flags & SQLITE_ECEL_OMITREF ){
5409 i--;
5410 n--;
5411 }else{
5412 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
5414 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
5415 && sqlite3ExprIsConstantNotJoin(pExpr)
5417 sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
5418 }else{
5419 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
5420 if( inReg!=target+i ){
5421 VdbeOp *pOp;
5422 if( copyOp==OP_Copy
5423 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
5424 && pOp->p1+pOp->p3+1==inReg
5425 && pOp->p2+pOp->p3+1==target+i
5426 && pOp->p5==0 /* The do-not-merge flag must be clear */
5428 pOp->p3++;
5429 }else{
5430 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
5435 return n;
5439 ** Generate code for a BETWEEN operator.
5441 ** x BETWEEN y AND z
5443 ** The above is equivalent to
5445 ** x>=y AND x<=z
5447 ** Code it as such, taking care to do the common subexpression
5448 ** elimination of x.
5450 ** The xJumpIf parameter determines details:
5452 ** NULL: Store the boolean result in reg[dest]
5453 ** sqlite3ExprIfTrue: Jump to dest if true
5454 ** sqlite3ExprIfFalse: Jump to dest if false
5456 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
5458 static void exprCodeBetween(
5459 Parse *pParse, /* Parsing and code generating context */
5460 Expr *pExpr, /* The BETWEEN expression */
5461 int dest, /* Jump destination or storage location */
5462 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
5463 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
5465 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
5466 Expr compLeft; /* The x>=y term */
5467 Expr compRight; /* The x<=z term */
5468 int regFree1 = 0; /* Temporary use register */
5469 Expr *pDel = 0;
5470 sqlite3 *db = pParse->db;
5472 memset(&compLeft, 0, sizeof(Expr));
5473 memset(&compRight, 0, sizeof(Expr));
5474 memset(&exprAnd, 0, sizeof(Expr));
5476 assert( ExprUseXList(pExpr) );
5477 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
5478 if( db->mallocFailed==0 ){
5479 exprAnd.op = TK_AND;
5480 exprAnd.pLeft = &compLeft;
5481 exprAnd.pRight = &compRight;
5482 compLeft.op = TK_GE;
5483 compLeft.pLeft = pDel;
5484 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
5485 compRight.op = TK_LE;
5486 compRight.pLeft = pDel;
5487 compRight.pRight = pExpr->x.pList->a[1].pExpr;
5488 exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
5489 if( xJump ){
5490 xJump(pParse, &exprAnd, dest, jumpIfNull);
5491 }else{
5492 /* Mark the expression is being from the ON or USING clause of a join
5493 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
5494 ** it into the Parse.pConstExpr list. We should use a new bit for this,
5495 ** for clarity, but we are out of bits in the Expr.flags field so we
5496 ** have to reuse the EP_OuterON bit. Bummer. */
5497 pDel->flags |= EP_OuterON;
5498 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
5500 sqlite3ReleaseTempReg(pParse, regFree1);
5502 sqlite3ExprDelete(db, pDel);
5504 /* Ensure adequate test coverage */
5505 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
5506 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
5507 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
5508 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
5509 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
5510 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
5511 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
5512 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
5513 testcase( xJump==0 );
5517 ** Generate code for a boolean expression such that a jump is made
5518 ** to the label "dest" if the expression is true but execution
5519 ** continues straight thru if the expression is false.
5521 ** If the expression evaluates to NULL (neither true nor false), then
5522 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
5524 ** This code depends on the fact that certain token values (ex: TK_EQ)
5525 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
5526 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
5527 ** the make process cause these values to align. Assert()s in the code
5528 ** below verify that the numbers are aligned correctly.
5530 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5531 Vdbe *v = pParse->pVdbe;
5532 int op = 0;
5533 int regFree1 = 0;
5534 int regFree2 = 0;
5535 int r1, r2;
5537 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5538 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5539 if( NEVER(pExpr==0) ) return; /* No way this can happen */
5540 assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
5541 op = pExpr->op;
5542 switch( op ){
5543 case TK_AND:
5544 case TK_OR: {
5545 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5546 if( pAlt!=pExpr ){
5547 sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
5548 }else if( op==TK_AND ){
5549 int d2 = sqlite3VdbeMakeLabel(pParse);
5550 testcase( jumpIfNull==0 );
5551 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
5552 jumpIfNull^SQLITE_JUMPIFNULL);
5553 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5554 sqlite3VdbeResolveLabel(v, d2);
5555 }else{
5556 testcase( jumpIfNull==0 );
5557 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5558 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
5560 break;
5562 case TK_NOT: {
5563 testcase( jumpIfNull==0 );
5564 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5565 break;
5567 case TK_TRUTH: {
5568 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5569 int isTrue; /* IS TRUE or IS NOT TRUE */
5570 testcase( jumpIfNull==0 );
5571 isNot = pExpr->op2==TK_ISNOT;
5572 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5573 testcase( isTrue && isNot );
5574 testcase( !isTrue && isNot );
5575 if( isTrue ^ isNot ){
5576 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5577 isNot ? SQLITE_JUMPIFNULL : 0);
5578 }else{
5579 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5580 isNot ? SQLITE_JUMPIFNULL : 0);
5582 break;
5584 case TK_IS:
5585 case TK_ISNOT:
5586 testcase( op==TK_IS );
5587 testcase( op==TK_ISNOT );
5588 op = (op==TK_IS) ? TK_EQ : TK_NE;
5589 jumpIfNull = SQLITE_NULLEQ;
5590 /* no break */ deliberate_fall_through
5591 case TK_LT:
5592 case TK_LE:
5593 case TK_GT:
5594 case TK_GE:
5595 case TK_NE:
5596 case TK_EQ: {
5597 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5598 testcase( jumpIfNull==0 );
5599 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5600 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5601 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5602 r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
5603 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5604 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5605 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5606 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5607 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5608 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5609 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5610 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5611 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5612 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5613 testcase( regFree1==0 );
5614 testcase( regFree2==0 );
5615 break;
5617 case TK_ISNULL:
5618 case TK_NOTNULL: {
5619 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
5620 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
5621 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5622 sqlite3VdbeTypeofColumn(v, r1);
5623 sqlite3VdbeAddOp2(v, op, r1, dest);
5624 VdbeCoverageIf(v, op==TK_ISNULL);
5625 VdbeCoverageIf(v, op==TK_NOTNULL);
5626 testcase( regFree1==0 );
5627 break;
5629 case TK_BETWEEN: {
5630 testcase( jumpIfNull==0 );
5631 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
5632 break;
5634 #ifndef SQLITE_OMIT_SUBQUERY
5635 case TK_IN: {
5636 int destIfFalse = sqlite3VdbeMakeLabel(pParse);
5637 int destIfNull = jumpIfNull ? dest : destIfFalse;
5638 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
5639 sqlite3VdbeGoto(v, dest);
5640 sqlite3VdbeResolveLabel(v, destIfFalse);
5641 break;
5643 #endif
5644 default: {
5645 default_expr:
5646 if( ExprAlwaysTrue(pExpr) ){
5647 sqlite3VdbeGoto(v, dest);
5648 }else if( ExprAlwaysFalse(pExpr) ){
5649 /* No-op */
5650 }else{
5651 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5652 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
5653 VdbeCoverage(v);
5654 testcase( regFree1==0 );
5655 testcase( jumpIfNull==0 );
5657 break;
5660 sqlite3ReleaseTempReg(pParse, regFree1);
5661 sqlite3ReleaseTempReg(pParse, regFree2);
5665 ** Generate code for a boolean expression such that a jump is made
5666 ** to the label "dest" if the expression is false but execution
5667 ** continues straight thru if the expression is true.
5669 ** If the expression evaluates to NULL (neither true nor false) then
5670 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
5671 ** is 0.
5673 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
5674 Vdbe *v = pParse->pVdbe;
5675 int op = 0;
5676 int regFree1 = 0;
5677 int regFree2 = 0;
5678 int r1, r2;
5680 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
5681 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
5682 if( pExpr==0 ) return;
5683 assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
5685 /* The value of pExpr->op and op are related as follows:
5687 ** pExpr->op op
5688 ** --------- ----------
5689 ** TK_ISNULL OP_NotNull
5690 ** TK_NOTNULL OP_IsNull
5691 ** TK_NE OP_Eq
5692 ** TK_EQ OP_Ne
5693 ** TK_GT OP_Le
5694 ** TK_LE OP_Gt
5695 ** TK_GE OP_Lt
5696 ** TK_LT OP_Ge
5698 ** For other values of pExpr->op, op is undefined and unused.
5699 ** The value of TK_ and OP_ constants are arranged such that we
5700 ** can compute the mapping above using the following expression.
5701 ** Assert()s verify that the computation is correct.
5703 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
5705 /* Verify correct alignment of TK_ and OP_ constants
5707 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
5708 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
5709 assert( pExpr->op!=TK_NE || op==OP_Eq );
5710 assert( pExpr->op!=TK_EQ || op==OP_Ne );
5711 assert( pExpr->op!=TK_LT || op==OP_Ge );
5712 assert( pExpr->op!=TK_LE || op==OP_Gt );
5713 assert( pExpr->op!=TK_GT || op==OP_Le );
5714 assert( pExpr->op!=TK_GE || op==OP_Lt );
5716 switch( pExpr->op ){
5717 case TK_AND:
5718 case TK_OR: {
5719 Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
5720 if( pAlt!=pExpr ){
5721 sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
5722 }else if( pExpr->op==TK_AND ){
5723 testcase( jumpIfNull==0 );
5724 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
5725 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5726 }else{
5727 int d2 = sqlite3VdbeMakeLabel(pParse);
5728 testcase( jumpIfNull==0 );
5729 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
5730 jumpIfNull^SQLITE_JUMPIFNULL);
5731 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
5732 sqlite3VdbeResolveLabel(v, d2);
5734 break;
5736 case TK_NOT: {
5737 testcase( jumpIfNull==0 );
5738 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
5739 break;
5741 case TK_TRUTH: {
5742 int isNot; /* IS NOT TRUE or IS NOT FALSE */
5743 int isTrue; /* IS TRUE or IS NOT TRUE */
5744 testcase( jumpIfNull==0 );
5745 isNot = pExpr->op2==TK_ISNOT;
5746 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
5747 testcase( isTrue && isNot );
5748 testcase( !isTrue && isNot );
5749 if( isTrue ^ isNot ){
5750 /* IS TRUE and IS NOT FALSE */
5751 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
5752 isNot ? 0 : SQLITE_JUMPIFNULL);
5754 }else{
5755 /* IS FALSE and IS NOT TRUE */
5756 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
5757 isNot ? 0 : SQLITE_JUMPIFNULL);
5759 break;
5761 case TK_IS:
5762 case TK_ISNOT:
5763 testcase( pExpr->op==TK_IS );
5764 testcase( pExpr->op==TK_ISNOT );
5765 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
5766 jumpIfNull = SQLITE_NULLEQ;
5767 /* no break */ deliberate_fall_through
5768 case TK_LT:
5769 case TK_LE:
5770 case TK_GT:
5771 case TK_GE:
5772 case TK_NE:
5773 case TK_EQ: {
5774 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
5775 testcase( jumpIfNull==0 );
5776 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5777 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
5778 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
5779 r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
5780 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
5781 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
5782 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
5783 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
5784 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
5785 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
5786 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
5787 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
5788 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
5789 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
5790 testcase( regFree1==0 );
5791 testcase( regFree2==0 );
5792 break;
5794 case TK_ISNULL:
5795 case TK_NOTNULL: {
5796 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
5797 sqlite3VdbeTypeofColumn(v, r1);
5798 sqlite3VdbeAddOp2(v, op, r1, dest);
5799 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
5800 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
5801 testcase( regFree1==0 );
5802 break;
5804 case TK_BETWEEN: {
5805 testcase( jumpIfNull==0 );
5806 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
5807 break;
5809 #ifndef SQLITE_OMIT_SUBQUERY
5810 case TK_IN: {
5811 if( jumpIfNull ){
5812 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
5813 }else{
5814 int destIfNull = sqlite3VdbeMakeLabel(pParse);
5815 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
5816 sqlite3VdbeResolveLabel(v, destIfNull);
5818 break;
5820 #endif
5821 default: {
5822 default_expr:
5823 if( ExprAlwaysFalse(pExpr) ){
5824 sqlite3VdbeGoto(v, dest);
5825 }else if( ExprAlwaysTrue(pExpr) ){
5826 /* no-op */
5827 }else{
5828 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
5829 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
5830 VdbeCoverage(v);
5831 testcase( regFree1==0 );
5832 testcase( jumpIfNull==0 );
5834 break;
5837 sqlite3ReleaseTempReg(pParse, regFree1);
5838 sqlite3ReleaseTempReg(pParse, regFree2);
5842 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
5843 ** code generation, and that copy is deleted after code generation. This
5844 ** ensures that the original pExpr is unchanged.
5846 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
5847 sqlite3 *db = pParse->db;
5848 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
5849 if( db->mallocFailed==0 ){
5850 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
5852 sqlite3ExprDelete(db, pCopy);
5856 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
5857 ** type of expression.
5859 ** If pExpr is a simple SQL value - an integer, real, string, blob
5860 ** or NULL value - then the VDBE currently being prepared is configured
5861 ** to re-prepare each time a new value is bound to variable pVar.
5863 ** Additionally, if pExpr is a simple SQL value and the value is the
5864 ** same as that currently bound to variable pVar, non-zero is returned.
5865 ** Otherwise, if the values are not the same or if pExpr is not a simple
5866 ** SQL value, zero is returned.
5868 static int exprCompareVariable(
5869 const Parse *pParse,
5870 const Expr *pVar,
5871 const Expr *pExpr
5873 int res = 0;
5874 int iVar;
5875 sqlite3_value *pL, *pR = 0;
5877 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
5878 if( pR ){
5879 iVar = pVar->iColumn;
5880 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
5881 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
5882 if( pL ){
5883 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
5884 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
5886 res = 0==sqlite3MemCompare(pL, pR, 0);
5888 sqlite3ValueFree(pR);
5889 sqlite3ValueFree(pL);
5892 return res;
5896 ** Do a deep comparison of two expression trees. Return 0 if the two
5897 ** expressions are completely identical. Return 1 if they differ only
5898 ** by a COLLATE operator at the top level. Return 2 if there are differences
5899 ** other than the top-level COLLATE operator.
5901 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
5902 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
5904 ** The pA side might be using TK_REGISTER. If that is the case and pB is
5905 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
5907 ** Sometimes this routine will return 2 even if the two expressions
5908 ** really are equivalent. If we cannot prove that the expressions are
5909 ** identical, we return 2 just to be safe. So if this routine
5910 ** returns 2, then you do not really know for certain if the two
5911 ** expressions are the same. But if you get a 0 or 1 return, then you
5912 ** can be sure the expressions are the same. In the places where
5913 ** this routine is used, it does not hurt to get an extra 2 - that
5914 ** just might result in some slightly slower code. But returning
5915 ** an incorrect 0 or 1 could lead to a malfunction.
5917 ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
5918 ** pParse->pReprepare can be matched against literals in pB. The
5919 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
5920 ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
5921 ** Argument pParse should normally be NULL. If it is not NULL and pA or
5922 ** pB causes a return value of 2.
5924 int sqlite3ExprCompare(
5925 const Parse *pParse,
5926 const Expr *pA,
5927 const Expr *pB,
5928 int iTab
5930 u32 combinedFlags;
5931 if( pA==0 || pB==0 ){
5932 return pB==pA ? 0 : 2;
5934 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
5935 return 0;
5937 combinedFlags = pA->flags | pB->flags;
5938 if( combinedFlags & EP_IntValue ){
5939 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
5940 return 0;
5942 return 2;
5944 if( pA->op!=pB->op || pA->op==TK_RAISE ){
5945 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
5946 return 1;
5948 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
5949 return 1;
5951 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
5952 && pB->iTable<0 && pA->iTable==iTab
5954 /* fall through */
5955 }else{
5956 return 2;
5959 assert( !ExprHasProperty(pA, EP_IntValue) );
5960 assert( !ExprHasProperty(pB, EP_IntValue) );
5961 if( pA->u.zToken ){
5962 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
5963 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5964 #ifndef SQLITE_OMIT_WINDOWFUNC
5965 assert( pA->op==pB->op );
5966 if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
5967 return 2;
5969 if( ExprHasProperty(pA,EP_WinFunc) ){
5970 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
5971 return 2;
5974 #endif
5975 }else if( pA->op==TK_NULL ){
5976 return 0;
5977 }else if( pA->op==TK_COLLATE ){
5978 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
5979 }else
5980 if( pB->u.zToken!=0
5981 && pA->op!=TK_COLUMN
5982 && pA->op!=TK_AGG_COLUMN
5983 && strcmp(pA->u.zToken,pB->u.zToken)!=0
5985 return 2;
5988 if( (pA->flags & (EP_Distinct|EP_Commuted))
5989 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
5990 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
5991 if( combinedFlags & EP_xIsSelect ) return 2;
5992 if( (combinedFlags & EP_FixedCol)==0
5993 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
5994 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
5995 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
5996 if( pA->op!=TK_STRING
5997 && pA->op!=TK_TRUEFALSE
5998 && ALWAYS((combinedFlags & EP_Reduced)==0)
6000 if( pA->iColumn!=pB->iColumn ) return 2;
6001 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
6002 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
6003 return 2;
6007 return 0;
6011 ** Compare two ExprList objects. Return 0 if they are identical, 1
6012 ** if they are certainly different, or 2 if it is not possible to
6013 ** determine if they are identical or not.
6015 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
6016 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
6018 ** This routine might return non-zero for equivalent ExprLists. The
6019 ** only consequence will be disabled optimizations. But this routine
6020 ** must never return 0 if the two ExprList objects are different, or
6021 ** a malfunction will result.
6023 ** Two NULL pointers are considered to be the same. But a NULL pointer
6024 ** always differs from a non-NULL pointer.
6026 int sqlite3ExprListCompare(const ExprList *pA, const ExprList *pB, int iTab){
6027 int i;
6028 if( pA==0 && pB==0 ) return 0;
6029 if( pA==0 || pB==0 ) return 1;
6030 if( pA->nExpr!=pB->nExpr ) return 1;
6031 for(i=0; i<pA->nExpr; i++){
6032 int res;
6033 Expr *pExprA = pA->a[i].pExpr;
6034 Expr *pExprB = pB->a[i].pExpr;
6035 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
6036 if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
6038 return 0;
6042 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
6043 ** are ignored.
6045 int sqlite3ExprCompareSkip(Expr *pA,Expr *pB, int iTab){
6046 return sqlite3ExprCompare(0,
6047 sqlite3ExprSkipCollate(pA),
6048 sqlite3ExprSkipCollate(pB),
6049 iTab);
6053 ** Return non-zero if Expr p can only be true if pNN is not NULL.
6055 ** Or if seenNot is true, return non-zero if Expr p can only be
6056 ** non-NULL if pNN is not NULL
6058 static int exprImpliesNotNull(
6059 const Parse *pParse,/* Parsing context */
6060 const Expr *p, /* The expression to be checked */
6061 const Expr *pNN, /* The expression that is NOT NULL */
6062 int iTab, /* Table being evaluated */
6063 int seenNot /* Return true only if p can be any non-NULL value */
6065 assert( p );
6066 assert( pNN );
6067 if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
6068 return pNN->op!=TK_NULL;
6070 switch( p->op ){
6071 case TK_IN: {
6072 if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
6073 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
6074 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6076 case TK_BETWEEN: {
6077 ExprList *pList;
6078 assert( ExprUseXList(p) );
6079 pList = p->x.pList;
6080 assert( pList!=0 );
6081 assert( pList->nExpr==2 );
6082 if( seenNot ) return 0;
6083 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
6084 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
6086 return 1;
6088 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6090 case TK_EQ:
6091 case TK_NE:
6092 case TK_LT:
6093 case TK_LE:
6094 case TK_GT:
6095 case TK_GE:
6096 case TK_PLUS:
6097 case TK_MINUS:
6098 case TK_BITOR:
6099 case TK_LSHIFT:
6100 case TK_RSHIFT:
6101 case TK_CONCAT:
6102 seenNot = 1;
6103 /* no break */ deliberate_fall_through
6104 case TK_STAR:
6105 case TK_REM:
6106 case TK_BITAND:
6107 case TK_SLASH: {
6108 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
6109 /* no break */ deliberate_fall_through
6111 case TK_SPAN:
6112 case TK_COLLATE:
6113 case TK_UPLUS:
6114 case TK_UMINUS: {
6115 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
6117 case TK_TRUTH: {
6118 if( seenNot ) return 0;
6119 if( p->op2!=TK_IS ) return 0;
6120 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6122 case TK_BITNOT:
6123 case TK_NOT: {
6124 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
6127 return 0;
6131 ** Return true if we can prove the pE2 will always be true if pE1 is
6132 ** true. Return false if we cannot complete the proof or if pE2 might
6133 ** be false. Examples:
6135 ** pE1: x==5 pE2: x==5 Result: true
6136 ** pE1: x>0 pE2: x==5 Result: false
6137 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
6138 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
6139 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
6140 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
6141 ** pE1: x IS ?2 pE2: x IS NOT NULL Result: false
6143 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
6144 ** Expr.iTable<0 then assume a table number given by iTab.
6146 ** If pParse is not NULL, then the values of bound variables in pE1 are
6147 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
6148 ** modified to record which bound variables are referenced. If pParse
6149 ** is NULL, then false will be returned if pE1 contains any bound variables.
6151 ** When in doubt, return false. Returning true might give a performance
6152 ** improvement. Returning false might cause a performance reduction, but
6153 ** it will always give the correct answer and is hence always safe.
6155 int sqlite3ExprImpliesExpr(
6156 const Parse *pParse,
6157 const Expr *pE1,
6158 const Expr *pE2,
6159 int iTab
6161 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
6162 return 1;
6164 if( pE2->op==TK_OR
6165 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
6166 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
6168 return 1;
6170 if( pE2->op==TK_NOTNULL
6171 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
6173 return 1;
6175 return 0;
6178 /* This is a helper function to impliesNotNullRow(). In this routine,
6179 ** set pWalker->eCode to one only if *both* of the input expressions
6180 ** separately have the implies-not-null-row property.
6182 static void bothImplyNotNullRow(Walker *pWalker, Expr *pE1, Expr *pE2){
6183 if( pWalker->eCode==0 ){
6184 sqlite3WalkExpr(pWalker, pE1);
6185 if( pWalker->eCode ){
6186 pWalker->eCode = 0;
6187 sqlite3WalkExpr(pWalker, pE2);
6193 ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
6194 ** If the expression node requires that the table at pWalker->iCur
6195 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
6197 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
6198 ** behalf of a RIGHT JOIN (or FULL JOIN). That makes a difference when
6199 ** evaluating terms in the ON clause of an inner join.
6201 ** This routine controls an optimization. False positives (setting
6202 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
6203 ** (never setting pWalker->eCode) is a harmless missed optimization.
6205 static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
6206 testcase( pExpr->op==TK_AGG_COLUMN );
6207 testcase( pExpr->op==TK_AGG_FUNCTION );
6208 if( ExprHasProperty(pExpr, EP_OuterON) ) return WRC_Prune;
6209 if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){
6210 /* If iCur is used in an inner-join ON clause to the left of a
6211 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
6212 ** But it is difficult to check for that condition precisely.
6213 ** To keep things simple, any use of iCur from any inner-join is
6214 ** ignored while attempting to simplify a RIGHT JOIN. */
6215 return WRC_Prune;
6217 switch( pExpr->op ){
6218 case TK_ISNOT:
6219 case TK_ISNULL:
6220 case TK_NOTNULL:
6221 case TK_IS:
6222 case TK_VECTOR:
6223 case TK_FUNCTION:
6224 case TK_TRUTH:
6225 case TK_CASE:
6226 testcase( pExpr->op==TK_ISNOT );
6227 testcase( pExpr->op==TK_ISNULL );
6228 testcase( pExpr->op==TK_NOTNULL );
6229 testcase( pExpr->op==TK_IS );
6230 testcase( pExpr->op==TK_VECTOR );
6231 testcase( pExpr->op==TK_FUNCTION );
6232 testcase( pExpr->op==TK_TRUTH );
6233 testcase( pExpr->op==TK_CASE );
6234 return WRC_Prune;
6236 case TK_COLUMN:
6237 if( pWalker->u.iCur==pExpr->iTable ){
6238 pWalker->eCode = 1;
6239 return WRC_Abort;
6241 return WRC_Prune;
6243 case TK_OR:
6244 case TK_AND:
6245 /* Both sides of an AND or OR must separately imply non-null-row.
6246 ** Consider these cases:
6247 ** 1. NOT (x AND y)
6248 ** 2. x OR y
6249 ** If only one of x or y is non-null-row, then the overall expression
6250 ** can be true if the other arm is false (case 1) or true (case 2).
6252 testcase( pExpr->op==TK_OR );
6253 testcase( pExpr->op==TK_AND );
6254 bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight);
6255 return WRC_Prune;
6257 case TK_IN:
6258 /* Beware of "x NOT IN ()" and "x NOT IN (SELECT 1 WHERE false)",
6259 ** both of which can be true. But apart from these cases, if
6260 ** the left-hand side of the IN is NULL then the IN itself will be
6261 ** NULL. */
6262 if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){
6263 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6265 return WRC_Prune;
6267 case TK_BETWEEN:
6268 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
6269 ** both y and z must be non-null row */
6270 assert( ExprUseXList(pExpr) );
6271 assert( pExpr->x.pList->nExpr==2 );
6272 sqlite3WalkExpr(pWalker, pExpr->pLeft);
6273 bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr,
6274 pExpr->x.pList->a[1].pExpr);
6275 return WRC_Prune;
6277 /* Virtual tables are allowed to use constraints like x=NULL. So
6278 ** a term of the form x=y does not prove that y is not null if x
6279 ** is the column of a virtual table */
6280 case TK_EQ:
6281 case TK_NE:
6282 case TK_LT:
6283 case TK_LE:
6284 case TK_GT:
6285 case TK_GE: {
6286 Expr *pLeft = pExpr->pLeft;
6287 Expr *pRight = pExpr->pRight;
6288 testcase( pExpr->op==TK_EQ );
6289 testcase( pExpr->op==TK_NE );
6290 testcase( pExpr->op==TK_LT );
6291 testcase( pExpr->op==TK_LE );
6292 testcase( pExpr->op==TK_GT );
6293 testcase( pExpr->op==TK_GE );
6294 /* The y.pTab=0 assignment in wherecode.c always happens after the
6295 ** impliesNotNullRow() test */
6296 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
6297 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
6298 if( (pLeft->op==TK_COLUMN
6299 && ALWAYS(pLeft->y.pTab!=0)
6300 && IsVirtual(pLeft->y.pTab))
6301 || (pRight->op==TK_COLUMN
6302 && ALWAYS(pRight->y.pTab!=0)
6303 && IsVirtual(pRight->y.pTab))
6305 return WRC_Prune;
6307 /* no break */ deliberate_fall_through
6309 default:
6310 return WRC_Continue;
6315 ** Return true (non-zero) if expression p can only be true if at least
6316 ** one column of table iTab is non-null. In other words, return true
6317 ** if expression p will always be NULL or false if every column of iTab
6318 ** is NULL.
6320 ** False negatives are acceptable. In other words, it is ok to return
6321 ** zero even if expression p will never be true of every column of iTab
6322 ** is NULL. A false negative is merely a missed optimization opportunity.
6324 ** False positives are not allowed, however. A false positive may result
6325 ** in an incorrect answer.
6327 ** Terms of p that are marked with EP_OuterON (and hence that come from
6328 ** the ON or USING clauses of OUTER JOINS) are excluded from the analysis.
6330 ** This routine is used to check if a LEFT JOIN can be converted into
6331 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
6332 ** clause requires that some column of the right table of the LEFT JOIN
6333 ** be non-NULL, then the LEFT JOIN can be safely converted into an
6334 ** ordinary join.
6336 int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab, int isRJ){
6337 Walker w;
6338 p = sqlite3ExprSkipCollateAndLikely(p);
6339 if( p==0 ) return 0;
6340 if( p->op==TK_NOTNULL ){
6341 p = p->pLeft;
6342 }else{
6343 while( p->op==TK_AND ){
6344 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1;
6345 p = p->pRight;
6348 w.xExprCallback = impliesNotNullRow;
6349 w.xSelectCallback = 0;
6350 w.xSelectCallback2 = 0;
6351 w.eCode = 0;
6352 w.mWFlags = isRJ!=0;
6353 w.u.iCur = iTab;
6354 sqlite3WalkExpr(&w, p);
6355 return w.eCode;
6359 ** An instance of the following structure is used by the tree walker
6360 ** to determine if an expression can be evaluated by reference to the
6361 ** index only, without having to do a search for the corresponding
6362 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
6363 ** is the cursor for the table.
6365 struct IdxCover {
6366 Index *pIdx; /* The index to be tested for coverage */
6367 int iCur; /* Cursor number for the table corresponding to the index */
6371 ** Check to see if there are references to columns in table
6372 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
6373 ** pWalker->u.pIdxCover->pIdx.
6375 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
6376 if( pExpr->op==TK_COLUMN
6377 && pExpr->iTable==pWalker->u.pIdxCover->iCur
6378 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
6380 pWalker->eCode = 1;
6381 return WRC_Abort;
6383 return WRC_Continue;
6387 ** Determine if an index pIdx on table with cursor iCur contains will
6388 ** the expression pExpr. Return true if the index does cover the
6389 ** expression and false if the pExpr expression references table columns
6390 ** that are not found in the index pIdx.
6392 ** An index covering an expression means that the expression can be
6393 ** evaluated using only the index and without having to lookup the
6394 ** corresponding table entry.
6396 int sqlite3ExprCoveredByIndex(
6397 Expr *pExpr, /* The index to be tested */
6398 int iCur, /* The cursor number for the corresponding table */
6399 Index *pIdx /* The index that might be used for coverage */
6401 Walker w;
6402 struct IdxCover xcov;
6403 memset(&w, 0, sizeof(w));
6404 xcov.iCur = iCur;
6405 xcov.pIdx = pIdx;
6406 w.xExprCallback = exprIdxCover;
6407 w.u.pIdxCover = &xcov;
6408 sqlite3WalkExpr(&w, pExpr);
6409 return !w.eCode;
6413 /* Structure used to pass information throughout the Walker in order to
6414 ** implement sqlite3ReferencesSrcList().
6416 struct RefSrcList {
6417 sqlite3 *db; /* Database connection used for sqlite3DbRealloc() */
6418 SrcList *pRef; /* Looking for references to these tables */
6419 i64 nExclude; /* Number of tables to exclude from the search */
6420 int *aiExclude; /* Cursor IDs for tables to exclude from the search */
6424 ** Walker SELECT callbacks for sqlite3ReferencesSrcList().
6426 ** When entering a new subquery on the pExpr argument, add all FROM clause
6427 ** entries for that subquery to the exclude list.
6429 ** When leaving the subquery, remove those entries from the exclude list.
6431 static int selectRefEnter(Walker *pWalker, Select *pSelect){
6432 struct RefSrcList *p = pWalker->u.pRefSrcList;
6433 SrcList *pSrc = pSelect->pSrc;
6434 i64 i, j;
6435 int *piNew;
6436 if( pSrc->nSrc==0 ) return WRC_Continue;
6437 j = p->nExclude;
6438 p->nExclude += pSrc->nSrc;
6439 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
6440 if( piNew==0 ){
6441 p->nExclude = 0;
6442 return WRC_Abort;
6443 }else{
6444 p->aiExclude = piNew;
6446 for(i=0; i<pSrc->nSrc; i++, j++){
6447 p->aiExclude[j] = pSrc->a[i].iCursor;
6449 return WRC_Continue;
6451 static void selectRefLeave(Walker *pWalker, Select *pSelect){
6452 struct RefSrcList *p = pWalker->u.pRefSrcList;
6453 SrcList *pSrc = pSelect->pSrc;
6454 if( p->nExclude ){
6455 assert( p->nExclude>=pSrc->nSrc );
6456 p->nExclude -= pSrc->nSrc;
6460 /* This is the Walker EXPR callback for sqlite3ReferencesSrcList().
6462 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
6463 ** of the tables shown in RefSrcList.pRef.
6465 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
6466 ** table is in neither RefSrcList.pRef nor RefSrcList.aiExclude.
6468 static int exprRefToSrcList(Walker *pWalker, Expr *pExpr){
6469 if( pExpr->op==TK_COLUMN
6470 || pExpr->op==TK_AGG_COLUMN
6472 int i;
6473 struct RefSrcList *p = pWalker->u.pRefSrcList;
6474 SrcList *pSrc = p->pRef;
6475 int nSrc = pSrc ? pSrc->nSrc : 0;
6476 for(i=0; i<nSrc; i++){
6477 if( pExpr->iTable==pSrc->a[i].iCursor ){
6478 pWalker->eCode |= 1;
6479 return WRC_Continue;
6482 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
6483 if( i>=p->nExclude ){
6484 pWalker->eCode |= 2;
6487 return WRC_Continue;
6491 ** Check to see if pExpr references any tables in pSrcList.
6492 ** Possible return values:
6494 ** 1 pExpr does references a table in pSrcList.
6496 ** 0 pExpr references some table that is not defined in either
6497 ** pSrcList or in subqueries of pExpr itself.
6499 ** -1 pExpr only references no tables at all, or it only
6500 ** references tables defined in subqueries of pExpr itself.
6502 ** As currently used, pExpr is always an aggregate function call. That
6503 ** fact is exploited for efficiency.
6505 int sqlite3ReferencesSrcList(Parse *pParse, Expr *pExpr, SrcList *pSrcList){
6506 Walker w;
6507 struct RefSrcList x;
6508 assert( pParse->db!=0 );
6509 memset(&w, 0, sizeof(w));
6510 memset(&x, 0, sizeof(x));
6511 w.xExprCallback = exprRefToSrcList;
6512 w.xSelectCallback = selectRefEnter;
6513 w.xSelectCallback2 = selectRefLeave;
6514 w.u.pRefSrcList = &x;
6515 x.db = pParse->db;
6516 x.pRef = pSrcList;
6517 assert( pExpr->op==TK_AGG_FUNCTION );
6518 assert( ExprUseXList(pExpr) );
6519 sqlite3WalkExprList(&w, pExpr->x.pList);
6520 if( pExpr->pLeft ){
6521 assert( pExpr->pLeft->op==TK_ORDER );
6522 assert( ExprUseXList(pExpr->pLeft) );
6523 assert( pExpr->pLeft->x.pList!=0 );
6524 sqlite3WalkExprList(&w, pExpr->pLeft->x.pList);
6526 #ifndef SQLITE_OMIT_WINDOWFUNC
6527 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6528 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
6530 #endif
6531 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
6532 if( w.eCode & 0x01 ){
6533 return 1;
6534 }else if( w.eCode ){
6535 return 0;
6536 }else{
6537 return -1;
6542 ** This is a Walker expression node callback.
6544 ** For Expr nodes that contain pAggInfo pointers, make sure the AggInfo
6545 ** object that is referenced does not refer directly to the Expr. If
6546 ** it does, make a copy. This is done because the pExpr argument is
6547 ** subject to change.
6549 ** The copy is scheduled for deletion using the sqlite3ExprDeferredDelete()
6550 ** which builds on the sqlite3ParserAddCleanup() mechanism.
6552 static int agginfoPersistExprCb(Walker *pWalker, Expr *pExpr){
6553 if( ALWAYS(!ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced))
6554 && pExpr->pAggInfo!=0
6556 AggInfo *pAggInfo = pExpr->pAggInfo;
6557 int iAgg = pExpr->iAgg;
6558 Parse *pParse = pWalker->pParse;
6559 sqlite3 *db = pParse->db;
6560 assert( iAgg>=0 );
6561 if( pExpr->op!=TK_AGG_FUNCTION ){
6562 if( iAgg<pAggInfo->nColumn
6563 && pAggInfo->aCol[iAgg].pCExpr==pExpr
6565 pExpr = sqlite3ExprDup(db, pExpr, 0);
6566 if( pExpr ){
6567 pAggInfo->aCol[iAgg].pCExpr = pExpr;
6568 sqlite3ExprDeferredDelete(pParse, pExpr);
6571 }else{
6572 assert( pExpr->op==TK_AGG_FUNCTION );
6573 if( ALWAYS(iAgg<pAggInfo->nFunc)
6574 && pAggInfo->aFunc[iAgg].pFExpr==pExpr
6576 pExpr = sqlite3ExprDup(db, pExpr, 0);
6577 if( pExpr ){
6578 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
6579 sqlite3ExprDeferredDelete(pParse, pExpr);
6584 return WRC_Continue;
6588 ** Initialize a Walker object so that will persist AggInfo entries referenced
6589 ** by the tree that is walked.
6591 void sqlite3AggInfoPersistWalkerInit(Walker *pWalker, Parse *pParse){
6592 memset(pWalker, 0, sizeof(*pWalker));
6593 pWalker->pParse = pParse;
6594 pWalker->xExprCallback = agginfoPersistExprCb;
6595 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
6599 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
6600 ** the new element. Return a negative number if malloc fails.
6602 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
6603 int i;
6604 pInfo->aCol = sqlite3ArrayAllocate(
6606 pInfo->aCol,
6607 sizeof(pInfo->aCol[0]),
6608 &pInfo->nColumn,
6611 return i;
6615 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
6616 ** the new element. Return a negative number if malloc fails.
6618 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
6619 int i;
6620 pInfo->aFunc = sqlite3ArrayAllocate(
6622 pInfo->aFunc,
6623 sizeof(pInfo->aFunc[0]),
6624 &pInfo->nFunc,
6627 return i;
6631 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
6632 ** Return the index in aCol[] of the entry that describes that column.
6634 ** If no prior entry is found, create a new one and return -1. The
6635 ** new column will have an index of pAggInfo->nColumn-1.
6637 static void findOrCreateAggInfoColumn(
6638 Parse *pParse, /* Parsing context */
6639 AggInfo *pAggInfo, /* The AggInfo object to search and/or modify */
6640 Expr *pExpr /* Expr describing the column to find or insert */
6642 struct AggInfo_col *pCol;
6643 int k;
6645 assert( pAggInfo->iFirstReg==0 );
6646 pCol = pAggInfo->aCol;
6647 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
6648 if( pCol->pCExpr==pExpr ) return;
6649 if( pCol->iTable==pExpr->iTable
6650 && pCol->iColumn==pExpr->iColumn
6651 && pExpr->op!=TK_IF_NULL_ROW
6653 goto fix_up_expr;
6656 k = addAggInfoColumn(pParse->db, pAggInfo);
6657 if( k<0 ){
6658 /* OOM on resize */
6659 assert( pParse->db->mallocFailed );
6660 return;
6662 pCol = &pAggInfo->aCol[k];
6663 assert( ExprUseYTab(pExpr) );
6664 pCol->pTab = pExpr->y.pTab;
6665 pCol->iTable = pExpr->iTable;
6666 pCol->iColumn = pExpr->iColumn;
6667 pCol->iSorterColumn = -1;
6668 pCol->pCExpr = pExpr;
6669 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
6670 int j, n;
6671 ExprList *pGB = pAggInfo->pGroupBy;
6672 struct ExprList_item *pTerm = pGB->a;
6673 n = pGB->nExpr;
6674 for(j=0; j<n; j++, pTerm++){
6675 Expr *pE = pTerm->pExpr;
6676 if( pE->op==TK_COLUMN
6677 && pE->iTable==pExpr->iTable
6678 && pE->iColumn==pExpr->iColumn
6680 pCol->iSorterColumn = j;
6681 break;
6685 if( pCol->iSorterColumn<0 ){
6686 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
6688 fix_up_expr:
6689 ExprSetVVAProperty(pExpr, EP_NoReduce);
6690 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo );
6691 pExpr->pAggInfo = pAggInfo;
6692 if( pExpr->op==TK_COLUMN ){
6693 pExpr->op = TK_AGG_COLUMN;
6695 pExpr->iAgg = (i16)k;
6699 ** This is the xExprCallback for a tree walker. It is used to
6700 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
6701 ** for additional information.
6703 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
6704 int i;
6705 NameContext *pNC = pWalker->u.pNC;
6706 Parse *pParse = pNC->pParse;
6707 SrcList *pSrcList = pNC->pSrcList;
6708 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
6710 assert( pNC->ncFlags & NC_UAggInfo );
6711 assert( pAggInfo->iFirstReg==0 );
6712 switch( pExpr->op ){
6713 default: {
6714 IndexedExpr *pIEpr;
6715 Expr tmp;
6716 assert( pParse->iSelfTab==0 );
6717 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
6718 if( pParse->pIdxEpr==0 ) break;
6719 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6720 int iDataCur = pIEpr->iDataCur;
6721 if( iDataCur<0 ) continue;
6722 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
6724 if( pIEpr==0 ) break;
6725 if( NEVER(!ExprUseYTab(pExpr)) ) break;
6726 for(i=0; i<pSrcList->nSrc; i++){
6727 if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
6729 if( i>=pSrcList->nSrc ) break;
6730 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
6731 if( pParse->nErr ){ return WRC_Abort; }
6733 /* If we reach this point, it means that expression pExpr can be
6734 ** translated into a reference to an index column as described by
6735 ** pIEpr.
6737 memset(&tmp, 0, sizeof(tmp));
6738 tmp.op = TK_AGG_COLUMN;
6739 tmp.iTable = pIEpr->iIdxCur;
6740 tmp.iColumn = pIEpr->iIdxCol;
6741 findOrCreateAggInfoColumn(pParse, pAggInfo, &tmp);
6742 if( pParse->nErr ){ return WRC_Abort; }
6743 assert( pAggInfo->aCol!=0 );
6744 assert( tmp.iAgg<pAggInfo->nColumn );
6745 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
6746 pExpr->pAggInfo = pAggInfo;
6747 pExpr->iAgg = tmp.iAgg;
6748 return WRC_Prune;
6750 case TK_IF_NULL_ROW:
6751 case TK_AGG_COLUMN:
6752 case TK_COLUMN: {
6753 testcase( pExpr->op==TK_AGG_COLUMN );
6754 testcase( pExpr->op==TK_COLUMN );
6755 testcase( pExpr->op==TK_IF_NULL_ROW );
6756 /* Check to see if the column is in one of the tables in the FROM
6757 ** clause of the aggregate query */
6758 if( ALWAYS(pSrcList!=0) ){
6759 SrcItem *pItem = pSrcList->a;
6760 for(i=0; i<pSrcList->nSrc; i++, pItem++){
6761 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6762 if( pExpr->iTable==pItem->iCursor ){
6763 findOrCreateAggInfoColumn(pParse, pAggInfo, pExpr);
6764 break;
6765 } /* endif pExpr->iTable==pItem->iCursor */
6766 } /* end loop over pSrcList */
6768 return WRC_Continue;
6770 case TK_AGG_FUNCTION: {
6771 if( (pNC->ncFlags & NC_InAggFunc)==0
6772 && pWalker->walkerDepth==pExpr->op2
6773 && pExpr->pAggInfo==0
6775 /* Check to see if pExpr is a duplicate of another aggregate
6776 ** function that is already in the pAggInfo structure
6778 struct AggInfo_func *pItem = pAggInfo->aFunc;
6779 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
6780 if( NEVER(pItem->pFExpr==pExpr) ) break;
6781 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
6782 break;
6785 if( i>=pAggInfo->nFunc ){
6786 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
6788 u8 enc = ENC(pParse->db);
6789 i = addAggInfoFunc(pParse->db, pAggInfo);
6790 if( i>=0 ){
6791 int nArg;
6792 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
6793 pItem = &pAggInfo->aFunc[i];
6794 pItem->pFExpr = pExpr;
6795 assert( ExprUseUToken(pExpr) );
6796 nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
6797 pItem->pFunc = sqlite3FindFunction(pParse->db,
6798 pExpr->u.zToken, nArg, enc, 0);
6799 assert( pItem->bOBUnique==0 );
6800 if( pExpr->pLeft
6801 && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0
6803 /* The NEEDCOLL test above causes any ORDER BY clause on
6804 ** aggregate min() or max() to be ignored. */
6805 ExprList *pOBList;
6806 assert( nArg>0 );
6807 assert( pExpr->pLeft->op==TK_ORDER );
6808 assert( ExprUseXList(pExpr->pLeft) );
6809 pItem->iOBTab = pParse->nTab++;
6810 pOBList = pExpr->pLeft->x.pList;
6811 assert( pOBList->nExpr>0 );
6812 assert( pItem->bOBUnique==0 );
6813 if( pOBList->nExpr==1
6814 && nArg==1
6815 && sqlite3ExprCompare(0,pOBList->a[0].pExpr,
6816 pExpr->x.pList->a[0].pExpr,0)==0
6818 pItem->bOBPayload = 0;
6819 pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct);
6820 }else{
6821 pItem->bOBPayload = 1;
6823 pItem->bUseSubtype =
6824 (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0;
6825 }else{
6826 pItem->iOBTab = -1;
6828 if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){
6829 pItem->iDistinct = pParse->nTab++;
6830 }else{
6831 pItem->iDistinct = -1;
6835 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
6837 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
6838 ExprSetVVAProperty(pExpr, EP_NoReduce);
6839 pExpr->iAgg = (i16)i;
6840 pExpr->pAggInfo = pAggInfo;
6841 return WRC_Prune;
6842 }else{
6843 return WRC_Continue;
6847 return WRC_Continue;
6851 ** Analyze the pExpr expression looking for aggregate functions and
6852 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
6853 ** points to. Additional entries are made on the AggInfo object as
6854 ** necessary.
6856 ** This routine should only be called after the expression has been
6857 ** analyzed by sqlite3ResolveExprNames().
6859 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
6860 Walker w;
6861 w.xExprCallback = analyzeAggregate;
6862 w.xSelectCallback = sqlite3WalkerDepthIncrease;
6863 w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
6864 w.walkerDepth = 0;
6865 w.u.pNC = pNC;
6866 w.pParse = 0;
6867 assert( pNC->pSrcList!=0 );
6868 sqlite3WalkExpr(&w, pExpr);
6872 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
6873 ** expression list. Return the number of errors.
6875 ** If an error is found, the analysis is cut short.
6877 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
6878 struct ExprList_item *pItem;
6879 int i;
6880 if( pList ){
6881 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
6882 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
6888 ** Allocate a single new register for use to hold some intermediate result.
6890 int sqlite3GetTempReg(Parse *pParse){
6891 if( pParse->nTempReg==0 ){
6892 return ++pParse->nMem;
6894 return pParse->aTempReg[--pParse->nTempReg];
6898 ** Deallocate a register, making available for reuse for some other
6899 ** purpose.
6901 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
6902 if( iReg ){
6903 sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
6904 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
6905 pParse->aTempReg[pParse->nTempReg++] = iReg;
6911 ** Allocate or deallocate a block of nReg consecutive registers.
6913 int sqlite3GetTempRange(Parse *pParse, int nReg){
6914 int i, n;
6915 if( nReg==1 ) return sqlite3GetTempReg(pParse);
6916 i = pParse->iRangeReg;
6917 n = pParse->nRangeReg;
6918 if( nReg<=n ){
6919 pParse->iRangeReg += nReg;
6920 pParse->nRangeReg -= nReg;
6921 }else{
6922 i = pParse->nMem+1;
6923 pParse->nMem += nReg;
6925 return i;
6927 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
6928 if( nReg==1 ){
6929 sqlite3ReleaseTempReg(pParse, iReg);
6930 return;
6932 sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
6933 if( nReg>pParse->nRangeReg ){
6934 pParse->nRangeReg = nReg;
6935 pParse->iRangeReg = iReg;
6940 ** Mark all temporary registers as being unavailable for reuse.
6942 ** Always invoke this procedure after coding a subroutine or co-routine
6943 ** that might be invoked from other parts of the code, to ensure that
6944 ** the sub/co-routine does not use registers in common with the code that
6945 ** invokes the sub/co-routine.
6947 void sqlite3ClearTempRegCache(Parse *pParse){
6948 pParse->nTempReg = 0;
6949 pParse->nRangeReg = 0;
6953 ** Make sure sufficient registers have been allocated so that
6954 ** iReg is a valid register number.
6956 void sqlite3TouchRegister(Parse *pParse, int iReg){
6957 if( pParse->nMem<iReg ) pParse->nMem = iReg;
6960 #if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_DEBUG)
6962 ** Return the latest reusable register in the set of all registers.
6963 ** The value returned is no less than iMin. If any register iMin or
6964 ** greater is in permanent use, then return one more than that last
6965 ** permanent register.
6967 int sqlite3FirstAvailableRegister(Parse *pParse, int iMin){
6968 const ExprList *pList = pParse->pConstExpr;
6969 if( pList ){
6970 int i;
6971 for(i=0; i<pList->nExpr; i++){
6972 if( pList->a[i].u.iConstExprReg>=iMin ){
6973 iMin = pList->a[i].u.iConstExprReg + 1;
6977 pParse->nTempReg = 0;
6978 pParse->nRangeReg = 0;
6979 return iMin;
6981 #endif /* SQLITE_ENABLE_STAT4 || SQLITE_DEBUG */
6984 ** Validate that no temporary register falls within the range of
6985 ** iFirst..iLast, inclusive. This routine is only call from within assert()
6986 ** statements.
6988 #ifdef SQLITE_DEBUG
6989 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
6990 int i;
6991 if( pParse->nRangeReg>0
6992 && pParse->iRangeReg+pParse->nRangeReg > iFirst
6993 && pParse->iRangeReg <= iLast
6995 return 0;
6997 for(i=0; i<pParse->nTempReg; i++){
6998 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
6999 return 0;
7002 if( pParse->pConstExpr ){
7003 ExprList *pList = pParse->pConstExpr;
7004 for(i=0; i<pList->nExpr; i++){
7005 int iReg = pList->a[i].u.iConstExprReg;
7006 if( iReg==0 ) continue;
7007 if( iReg>=iFirst && iReg<=iLast ) return 0;
7010 return 1;
7012 #endif /* SQLITE_DEBUG */