xref: /sqlite-3.40.0/src/whereexpr.c (revision dac7e69d)
1 /*
2 ** 2015-06-08
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.
10 **
11 *************************************************************************
12 ** This module contains C code that generates VDBE code used to process
13 ** the WHERE clause of SQL statements.
14 **
15 ** This file was originally part of where.c but was split out to improve
16 ** readability and editabiliity.  This file contains utility routines for
17 ** analyzing Expr objects in the WHERE clause.
18 */
19 #include "sqliteInt.h"
20 #include "whereInt.h"
21 
22 /* Forward declarations */
23 static void exprAnalyze(SrcList*, WhereClause*, int);
24 
25 /*
26 ** Deallocate all memory associated with a WhereOrInfo object.
27 */
28 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
29   sqlite3WhereClauseClear(&p->wc);
30   sqlite3DbFree(db, p);
31 }
32 
33 /*
34 ** Deallocate all memory associated with a WhereAndInfo object.
35 */
36 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
37   sqlite3WhereClauseClear(&p->wc);
38   sqlite3DbFree(db, p);
39 }
40 
41 /*
42 ** Add a single new WhereTerm entry to the WhereClause object pWC.
43 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
44 ** The index in pWC->a[] of the new WhereTerm is returned on success.
45 ** 0 is returned if the new WhereTerm could not be added due to a memory
46 ** allocation error.  The memory allocation failure will be recorded in
47 ** the db->mallocFailed flag so that higher-level functions can detect it.
48 **
49 ** This routine will increase the size of the pWC->a[] array as necessary.
50 **
51 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
52 ** for freeing the expression p is assumed by the WhereClause object pWC.
53 ** This is true even if this routine fails to allocate a new WhereTerm.
54 **
55 ** WARNING:  This routine might reallocate the space used to store
56 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
57 ** calling this routine.  Such pointers may be reinitialized by referencing
58 ** the pWC->a[] array.
59 */
60 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
61   WhereTerm *pTerm;
62   int idx;
63   testcase( wtFlags & TERM_VIRTUAL );
64   if( pWC->nTerm>=pWC->nSlot ){
65     WhereTerm *pOld = pWC->a;
66     sqlite3 *db = pWC->pWInfo->pParse->db;
67     pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
68     if( pWC->a==0 ){
69       if( wtFlags & TERM_DYNAMIC ){
70         sqlite3ExprDelete(db, p);
71       }
72       pWC->a = pOld;
73       return 0;
74     }
75     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
76     if( pOld!=pWC->aStatic ){
77       sqlite3DbFree(db, pOld);
78     }
79     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
80   }
81   pTerm = &pWC->a[idx = pWC->nTerm++];
82   if( p && ExprHasProperty(p, EP_Unlikely) ){
83     pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
84   }else{
85     pTerm->truthProb = 1;
86   }
87   pTerm->pExpr = sqlite3ExprSkipCollate(p);
88   pTerm->wtFlags = wtFlags;
89   pTerm->pWC = pWC;
90   pTerm->iParent = -1;
91   memset(&pTerm->eOperator, 0,
92          sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
93   return idx;
94 }
95 
96 /*
97 ** Return TRUE if the given operator is one of the operators that is
98 ** allowed for an indexable WHERE clause term.  The allowed operators are
99 ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
100 */
101 static int allowedOp(int op){
102   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
104   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
105   assert( TK_GE==TK_EQ+4 );
106   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
107 }
108 
109 /*
110 ** Commute a comparison operator.  Expressions of the form "X op Y"
111 ** are converted into "Y op X".
112 **
113 ** If left/right precedence rules come into play when determining the
114 ** collating sequence, then COLLATE operators are adjusted to ensure
115 ** that the collating sequence does not change.  For example:
116 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
117 ** the left hand side of a comparison overrides any collation sequence
118 ** attached to the right. For the same reason the EP_Collate flag
119 ** is not commuted.
120 */
121 static void exprCommute(Parse *pParse, Expr *pExpr){
122   u16 expRight = (pExpr->pRight->flags & EP_Collate);
123   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
124   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
125   if( expRight==expLeft ){
126     /* Either X and Y both have COLLATE operator or neither do */
127     if( expRight ){
128       /* Both X and Y have COLLATE operators.  Make sure X is always
129       ** used by clearing the EP_Collate flag from Y. */
130       pExpr->pRight->flags &= ~EP_Collate;
131     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
132       /* Neither X nor Y have COLLATE operators, but X has a non-default
133       ** collating sequence.  So add the EP_Collate marker on X to cause
134       ** it to be searched first. */
135       pExpr->pLeft->flags |= EP_Collate;
136     }
137   }
138   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
139   if( pExpr->op>=TK_GT ){
140     assert( TK_LT==TK_GT+2 );
141     assert( TK_GE==TK_LE+2 );
142     assert( TK_GT>TK_EQ );
143     assert( TK_GT<TK_LE );
144     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
145     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
146   }
147 }
148 
149 /*
150 ** Translate from TK_xx operator to WO_xx bitmask.
151 */
152 static u16 operatorMask(int op){
153   u16 c;
154   assert( allowedOp(op) );
155   if( op==TK_IN ){
156     c = WO_IN;
157   }else if( op==TK_ISNULL ){
158     c = WO_ISNULL;
159   }else if( op==TK_IS ){
160     c = WO_IS;
161   }else{
162     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
163     c = (u16)(WO_EQ<<(op-TK_EQ));
164   }
165   assert( op!=TK_ISNULL || c==WO_ISNULL );
166   assert( op!=TK_IN || c==WO_IN );
167   assert( op!=TK_EQ || c==WO_EQ );
168   assert( op!=TK_LT || c==WO_LT );
169   assert( op!=TK_LE || c==WO_LE );
170   assert( op!=TK_GT || c==WO_GT );
171   assert( op!=TK_GE || c==WO_GE );
172   assert( op!=TK_IS || c==WO_IS );
173   return c;
174 }
175 
176 
177 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
178 /*
179 ** Check to see if the given expression is a LIKE or GLOB operator that
180 ** can be optimized using inequality constraints.  Return TRUE if it is
181 ** so and false if not.
182 **
183 ** In order for the operator to be optimizible, the RHS must be a string
184 ** literal that does not begin with a wildcard.  The LHS must be a column
185 ** that may only be NULL, a string, or a BLOB, never a number. (This means
186 ** that virtual tables cannot participate in the LIKE optimization.)  The
187 ** collating sequence for the column on the LHS must be appropriate for
188 ** the operator.
189 */
190 static int isLikeOrGlob(
191   Parse *pParse,    /* Parsing and code generating context */
192   Expr *pExpr,      /* Test this expression */
193   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
194   int *pisComplete, /* True if the only wildcard is % in the last character */
195   int *pnoCase      /* True if uppercase is equivalent to lowercase */
196 ){
197   const u8 *z = 0;           /* String on RHS of LIKE operator */
198   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
199   ExprList *pList;           /* List of operands to the LIKE operator */
200   u8 c;                      /* One character in z[] */
201   int cnt;                   /* Number of non-wildcard prefix characters */
202   u8 wc[4];                  /* Wildcard characters */
203   sqlite3 *db = pParse->db;  /* Database connection */
204   sqlite3_value *pVal = 0;
205   int op;                    /* Opcode of pRight */
206   int rc;                    /* Result code to return */
207 
208   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
209     return 0;
210   }
211 #ifdef SQLITE_EBCDIC
212   if( *pnoCase ) return 0;
213 #endif
214   pList = pExpr->x.pList;
215   pLeft = pList->a[1].pExpr;
216 
217   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
218   op = pRight->op;
219   if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
220     Vdbe *pReprepare = pParse->pReprepare;
221     int iCol = pRight->iColumn;
222     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
223     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
224       z = sqlite3_value_text(pVal);
225     }
226     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
227     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
228   }else if( op==TK_STRING ){
229     z = (u8*)pRight->u.zToken;
230   }
231   if( z ){
232 
233     /* Count the number of prefix characters prior to the first wildcard */
234     cnt = 0;
235     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
236       cnt++;
237       if( c==wc[3] && z[cnt]!=0 ) cnt++;
238     }
239 
240     /* The optimization is possible only if (1) the pattern does not begin
241     ** with a wildcard and if (2) the non-wildcard prefix does not end with
242     ** an (illegal 0xff) character, or (3) the pattern does not consist of
243     ** a single escape character. The second condition is necessary so
244     ** that we can increment the prefix key to find an upper bound for the
245     ** range search. The third is because the caller assumes that the pattern
246     ** consists of at least one character after all escapes have been
247     ** removed.  */
248     if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
249       Expr *pPrefix;
250 
251       /* A "complete" match if the pattern ends with "*" or "%" */
252       *pisComplete = c==wc[0] && z[cnt+1]==0;
253 
254       /* Get the pattern prefix.  Remove all escapes from the prefix. */
255       pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
256       if( pPrefix ){
257         int iFrom, iTo;
258         char *zNew = pPrefix->u.zToken;
259         zNew[cnt] = 0;
260         for(iFrom=iTo=0; iFrom<cnt; iFrom++){
261           if( zNew[iFrom]==wc[3] ) iFrom++;
262           zNew[iTo++] = zNew[iFrom];
263         }
264         zNew[iTo] = 0;
265         assert( iTo>0 );
266 
267         /* If the LHS is not an ordinary column with TEXT affinity, then the
268         ** pattern prefix boundaries (both the start and end boundaries) must
269         ** not look like a number.  Otherwise the pattern might be treated as
270         ** a number, which will invalidate the LIKE optimization.
271         **
272         ** Getting this right has been a persistent source of bugs in the
273         ** LIKE optimization.  See, for example:
274         **    2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
275         **    2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
276         **    2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
277         **    2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
278         */
279         if( pLeft->op!=TK_COLUMN
280          || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
281          || IsVirtual(pLeft->y.pTab)  /* Value might be numeric */
282         ){
283           int isNum;
284           double rDummy;
285           isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
286           if( isNum<=0 ){
287             zNew[iTo-1]++;
288             isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
289             zNew[iTo-1]--;
290           }
291           if( isNum>0 ){
292             sqlite3ExprDelete(db, pPrefix);
293             sqlite3ValueFree(pVal);
294             return 0;
295           }
296         }
297       }
298       *ppPrefix = pPrefix;
299 
300       /* If the RHS pattern is a bound parameter, make arrangements to
301       ** reprepare the statement when that parameter is rebound */
302       if( op==TK_VARIABLE ){
303         Vdbe *v = pParse->pVdbe;
304         sqlite3VdbeSetVarmask(v, pRight->iColumn);
305         if( *pisComplete && pRight->u.zToken[1] ){
306           /* If the rhs of the LIKE expression is a variable, and the current
307           ** value of the variable means there is no need to invoke the LIKE
308           ** function, then no OP_Variable will be added to the program.
309           ** This causes problems for the sqlite3_bind_parameter_name()
310           ** API. To work around them, add a dummy OP_Variable here.
311           */
312           int r1 = sqlite3GetTempReg(pParse);
313           sqlite3ExprCodeTarget(pParse, pRight, r1);
314           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
315           sqlite3ReleaseTempReg(pParse, r1);
316         }
317       }
318     }else{
319       z = 0;
320     }
321   }
322 
323   rc = (z!=0);
324   sqlite3ValueFree(pVal);
325   return rc;
326 }
327 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
328 
329 
330 #ifndef SQLITE_OMIT_VIRTUALTABLE
331 /*
332 ** Check to see if the pExpr expression is a form that needs to be passed
333 ** to the xBestIndex method of virtual tables.  Forms of interest include:
334 **
335 **          Expression                   Virtual Table Operator
336 **          -----------------------      ---------------------------------
337 **      1.  column MATCH expr            SQLITE_INDEX_CONSTRAINT_MATCH
338 **      2.  column GLOB expr             SQLITE_INDEX_CONSTRAINT_GLOB
339 **      3.  column LIKE expr             SQLITE_INDEX_CONSTRAINT_LIKE
340 **      4.  column REGEXP expr           SQLITE_INDEX_CONSTRAINT_REGEXP
341 **      5.  column != expr               SQLITE_INDEX_CONSTRAINT_NE
342 **      6.  expr != column               SQLITE_INDEX_CONSTRAINT_NE
343 **      7.  column IS NOT expr           SQLITE_INDEX_CONSTRAINT_ISNOT
344 **      8.  expr IS NOT column           SQLITE_INDEX_CONSTRAINT_ISNOT
345 **      9.  column IS NOT NULL           SQLITE_INDEX_CONSTRAINT_ISNOTNULL
346 **
347 ** In every case, "column" must be a column of a virtual table.  If there
348 ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
349 ** "expr" expression (even though in forms (6) and (8) the column is on the
350 ** right and the expression is on the left).  Also set *peOp2 to the
351 ** appropriate virtual table operator.  The return value is 1 or 2 if there
352 ** is a match.  The usual return is 1, but if the RHS is also a column
353 ** of virtual table in forms (5) or (7) then return 2.
354 **
355 ** If the expression matches none of the patterns above, return 0.
356 */
357 static int isAuxiliaryVtabOperator(
358   sqlite3 *db,                    /* Parsing context */
359   Expr *pExpr,                    /* Test this expression */
360   unsigned char *peOp2,           /* OUT: 0 for MATCH, or else an op2 value */
361   Expr **ppLeft,                  /* Column expression to left of MATCH/op2 */
362   Expr **ppRight                  /* Expression to left of MATCH/op2 */
363 ){
364   if( pExpr->op==TK_FUNCTION ){
365     static const struct Op2 {
366       const char *zOp;
367       unsigned char eOp2;
368     } aOp[] = {
369       { "match",  SQLITE_INDEX_CONSTRAINT_MATCH },
370       { "glob",   SQLITE_INDEX_CONSTRAINT_GLOB },
371       { "like",   SQLITE_INDEX_CONSTRAINT_LIKE },
372       { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
373     };
374     ExprList *pList;
375     Expr *pCol;                     /* Column reference */
376     int i;
377 
378     pList = pExpr->x.pList;
379     if( pList==0 || pList->nExpr!=2 ){
380       return 0;
381     }
382 
383     /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
384     ** virtual table on their second argument, which is the same as
385     ** the left-hand side operand in their in-fix form.
386     **
387     **       vtab_column MATCH expression
388     **       MATCH(expression,vtab_column)
389     */
390     pCol = pList->a[1].pExpr;
391     if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
392       for(i=0; i<ArraySize(aOp); i++){
393         if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
394           *peOp2 = aOp[i].eOp2;
395           *ppRight = pList->a[0].pExpr;
396           *ppLeft = pCol;
397           return 1;
398         }
399       }
400     }
401 
402     /* We can also match against the first column of overloaded
403     ** functions where xFindFunction returns a value of at least
404     ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
405     **
406     **      OVERLOADED(vtab_column,expression)
407     **
408     ** Historically, xFindFunction expected to see lower-case function
409     ** names.  But for this use case, xFindFunction is expected to deal
410     ** with function names in an arbitrary case.
411     */
412     pCol = pList->a[0].pExpr;
413     if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){
414       sqlite3_vtab *pVtab;
415       sqlite3_module *pMod;
416       void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
417       void *pNotUsed;
418       pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
419       assert( pVtab!=0 );
420       assert( pVtab->pModule!=0 );
421       pMod = (sqlite3_module *)pVtab->pModule;
422       if( pMod->xFindFunction!=0 ){
423         i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
424         if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
425           *peOp2 = i;
426           *ppRight = pList->a[1].pExpr;
427           *ppLeft = pCol;
428           return 1;
429         }
430       }
431     }
432   }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
433     int res = 0;
434     Expr *pLeft = pExpr->pLeft;
435     Expr *pRight = pExpr->pRight;
436     if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){
437       res++;
438     }
439     if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){
440       res++;
441       SWAP(Expr*, pLeft, pRight);
442     }
443     *ppLeft = pLeft;
444     *ppRight = pRight;
445     if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
446     if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
447     if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
448     return res;
449   }
450   return 0;
451 }
452 #endif /* SQLITE_OMIT_VIRTUALTABLE */
453 
454 /*
455 ** If the pBase expression originated in the ON or USING clause of
456 ** a join, then transfer the appropriate markings over to derived.
457 */
458 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
459   if( pDerived ){
460     pDerived->flags |= pBase->flags & EP_FromJoin;
461     pDerived->iRightJoinTable = pBase->iRightJoinTable;
462   }
463 }
464 
465 /*
466 ** Mark term iChild as being a child of term iParent
467 */
468 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
469   pWC->a[iChild].iParent = iParent;
470   pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
471   pWC->a[iParent].nChild++;
472 }
473 
474 /*
475 ** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
476 ** a conjunction, then return just pTerm when N==0.  If N is exceeds
477 ** the number of available subterms, return NULL.
478 */
479 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
480   if( pTerm->eOperator!=WO_AND ){
481     return N==0 ? pTerm : 0;
482   }
483   if( N<pTerm->u.pAndInfo->wc.nTerm ){
484     return &pTerm->u.pAndInfo->wc.a[N];
485   }
486   return 0;
487 }
488 
489 /*
490 ** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
491 ** two subterms are in disjunction - they are OR-ed together.
492 **
493 ** If these two terms are both of the form:  "A op B" with the same
494 ** A and B values but different operators and if the operators are
495 ** compatible (if one is = and the other is <, for example) then
496 ** add a new virtual AND term to pWC that is the combination of the
497 ** two.
498 **
499 ** Some examples:
500 **
501 **    x<y OR x=y    -->     x<=y
502 **    x=y OR x=y    -->     x=y
503 **    x<=y OR x<y   -->     x<=y
504 **
505 ** The following is NOT generated:
506 **
507 **    x<y OR x>y    -->     x!=y
508 */
509 static void whereCombineDisjuncts(
510   SrcList *pSrc,         /* the FROM clause */
511   WhereClause *pWC,      /* The complete WHERE clause */
512   WhereTerm *pOne,       /* First disjunct */
513   WhereTerm *pTwo        /* Second disjunct */
514 ){
515   u16 eOp = pOne->eOperator | pTwo->eOperator;
516   sqlite3 *db;           /* Database connection (for malloc) */
517   Expr *pNew;            /* New virtual expression */
518   int op;                /* Operator for the combined expression */
519   int idxNew;            /* Index in pWC of the next virtual term */
520 
521   if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
522   if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
523   if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
524    && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
525   assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
526   assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
527   if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
528   if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
529   /* If we reach this point, it means the two subterms can be combined */
530   if( (eOp & (eOp-1))!=0 ){
531     if( eOp & (WO_LT|WO_LE) ){
532       eOp = WO_LE;
533     }else{
534       assert( eOp & (WO_GT|WO_GE) );
535       eOp = WO_GE;
536     }
537   }
538   db = pWC->pWInfo->pParse->db;
539   pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
540   if( pNew==0 ) return;
541   for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
542   pNew->op = op;
543   idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
544   exprAnalyze(pSrc, pWC, idxNew);
545 }
546 
547 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
548 /*
549 ** Analyze a term that consists of two or more OR-connected
550 ** subterms.  So in:
551 **
552 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
553 **                          ^^^^^^^^^^^^^^^^^^^^
554 **
555 ** This routine analyzes terms such as the middle term in the above example.
556 ** A WhereOrTerm object is computed and attached to the term under
557 ** analysis, regardless of the outcome of the analysis.  Hence:
558 **
559 **     WhereTerm.wtFlags   |=  TERM_ORINFO
560 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
561 **
562 ** The term being analyzed must have two or more of OR-connected subterms.
563 ** A single subterm might be a set of AND-connected sub-subterms.
564 ** Examples of terms under analysis:
565 **
566 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
567 **     (B)     x=expr1 OR expr2=x OR x=expr3
568 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
569 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
570 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
571 **     (F)     x>A OR (x=A AND y>=B)
572 **
573 ** CASE 1:
574 **
575 ** If all subterms are of the form T.C=expr for some single column of C and
576 ** a single table T (as shown in example B above) then create a new virtual
577 ** term that is an equivalent IN expression.  In other words, if the term
578 ** being analyzed is:
579 **
580 **      x = expr1  OR  expr2 = x  OR  x = expr3
581 **
582 ** then create a new virtual term like this:
583 **
584 **      x IN (expr1,expr2,expr3)
585 **
586 ** CASE 2:
587 **
588 ** If there are exactly two disjuncts and one side has x>A and the other side
589 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
590 ** WHERE clause of the form "x>=A".  Example:
591 **
592 **      x>A OR (x=A AND y>B)    adds:    x>=A
593 **
594 ** The added conjunct can sometimes be helpful in query planning.
595 **
596 ** CASE 3:
597 **
598 ** If all subterms are indexable by a single table T, then set
599 **
600 **     WhereTerm.eOperator              =  WO_OR
601 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
602 **
603 ** A subterm is "indexable" if it is of the form
604 ** "T.C <op> <expr>" where C is any column of table T and
605 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
606 ** A subterm is also indexable if it is an AND of two or more
607 ** subsubterms at least one of which is indexable.  Indexable AND
608 ** subterms have their eOperator set to WO_AND and they have
609 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
610 **
611 ** From another point of view, "indexable" means that the subterm could
612 ** potentially be used with an index if an appropriate index exists.
613 ** This analysis does not consider whether or not the index exists; that
614 ** is decided elsewhere.  This analysis only looks at whether subterms
615 ** appropriate for indexing exist.
616 **
617 ** All examples A through E above satisfy case 3.  But if a term
618 ** also satisfies case 1 (such as B) we know that the optimizer will
619 ** always prefer case 1, so in that case we pretend that case 3 is not
620 ** satisfied.
621 **
622 ** It might be the case that multiple tables are indexable.  For example,
623 ** (E) above is indexable on tables P, Q, and R.
624 **
625 ** Terms that satisfy case 3 are candidates for lookup by using
626 ** separate indices to find rowids for each subterm and composing
627 ** the union of all rowids using a RowSet object.  This is similar
628 ** to "bitmap indices" in other database engines.
629 **
630 ** OTHERWISE:
631 **
632 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
633 ** zero.  This term is not useful for search.
634 */
635 static void exprAnalyzeOrTerm(
636   SrcList *pSrc,            /* the FROM clause */
637   WhereClause *pWC,         /* the complete WHERE clause */
638   int idxTerm               /* Index of the OR-term to be analyzed */
639 ){
640   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
641   Parse *pParse = pWInfo->pParse;         /* Parser context */
642   sqlite3 *db = pParse->db;               /* Database connection */
643   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
644   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
645   int i;                                  /* Loop counters */
646   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
647   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
648   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
649   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
650   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
651 
652   /*
653   ** Break the OR clause into its separate subterms.  The subterms are
654   ** stored in a WhereClause structure containing within the WhereOrInfo
655   ** object that is attached to the original OR clause term.
656   */
657   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
658   assert( pExpr->op==TK_OR );
659   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
660   if( pOrInfo==0 ) return;
661   pTerm->wtFlags |= TERM_ORINFO;
662   pOrWc = &pOrInfo->wc;
663   memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
664   sqlite3WhereClauseInit(pOrWc, pWInfo);
665   sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
666   sqlite3WhereExprAnalyze(pSrc, pOrWc);
667   if( db->mallocFailed ) return;
668   assert( pOrWc->nTerm>=2 );
669 
670   /*
671   ** Compute the set of tables that might satisfy cases 1 or 3.
672   */
673   indexable = ~(Bitmask)0;
674   chngToIN = ~(Bitmask)0;
675   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
676     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
677       WhereAndInfo *pAndInfo;
678       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
679       chngToIN = 0;
680       pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
681       if( pAndInfo ){
682         WhereClause *pAndWC;
683         WhereTerm *pAndTerm;
684         int j;
685         Bitmask b = 0;
686         pOrTerm->u.pAndInfo = pAndInfo;
687         pOrTerm->wtFlags |= TERM_ANDINFO;
688         pOrTerm->eOperator = WO_AND;
689         pAndWC = &pAndInfo->wc;
690         memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
691         sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
692         sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
693         sqlite3WhereExprAnalyze(pSrc, pAndWC);
694         pAndWC->pOuter = pWC;
695         if( !db->mallocFailed ){
696           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
697             assert( pAndTerm->pExpr );
698             if( allowedOp(pAndTerm->pExpr->op)
699              || pAndTerm->eOperator==WO_AUX
700             ){
701               b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
702             }
703           }
704         }
705         indexable &= b;
706       }
707     }else if( pOrTerm->wtFlags & TERM_COPIED ){
708       /* Skip this term for now.  We revisit it when we process the
709       ** corresponding TERM_VIRTUAL term */
710     }else{
711       Bitmask b;
712       b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
713       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
714         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
715         b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
716       }
717       indexable &= b;
718       if( (pOrTerm->eOperator & WO_EQ)==0 ){
719         chngToIN = 0;
720       }else{
721         chngToIN &= b;
722       }
723     }
724   }
725 
726   /*
727   ** Record the set of tables that satisfy case 3.  The set might be
728   ** empty.
729   */
730   pOrInfo->indexable = indexable;
731   if( indexable ){
732     pTerm->eOperator = WO_OR;
733     pWC->hasOr = 1;
734   }else{
735     pTerm->eOperator = WO_OR;
736   }
737 
738   /* For a two-way OR, attempt to implementation case 2.
739   */
740   if( indexable && pOrWc->nTerm==2 ){
741     int iOne = 0;
742     WhereTerm *pOne;
743     while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
744       int iTwo = 0;
745       WhereTerm *pTwo;
746       while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
747         whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
748       }
749     }
750   }
751 
752   /*
753   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
754   ** we have to do some additional checking to see if case 1 really
755   ** is satisfied.
756   **
757   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
758   ** that there is no possibility of transforming the OR clause into an
759   ** IN operator because one or more terms in the OR clause contain
760   ** something other than == on a column in the single table.  The 1-bit
761   ** case means that every term of the OR clause is of the form
762   ** "table.column=expr" for some single table.  The one bit that is set
763   ** will correspond to the common table.  We still need to check to make
764   ** sure the same column is used on all terms.  The 2-bit case is when
765   ** the all terms are of the form "table1.column=table2.column".  It
766   ** might be possible to form an IN operator with either table1.column
767   ** or table2.column as the LHS if either is common to every term of
768   ** the OR clause.
769   **
770   ** Note that terms of the form "table.column1=table.column2" (the
771   ** same table on both sizes of the ==) cannot be optimized.
772   */
773   if( chngToIN ){
774     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
775     int iColumn = -1;         /* Column index on lhs of IN operator */
776     int iCursor = -1;         /* Table cursor common to all terms */
777     int j = 0;                /* Loop counter */
778 
779     /* Search for a table and column that appears on one side or the
780     ** other of the == operator in every subterm.  That table and column
781     ** will be recorded in iCursor and iColumn.  There might not be any
782     ** such table and column.  Set okToChngToIN if an appropriate table
783     ** and column is found but leave okToChngToIN false if not found.
784     */
785     for(j=0; j<2 && !okToChngToIN; j++){
786       Expr *pLeft = 0;
787       pOrTerm = pOrWc->a;
788       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
789         assert( pOrTerm->eOperator & WO_EQ );
790         pOrTerm->wtFlags &= ~TERM_OR_OK;
791         if( pOrTerm->leftCursor==iCursor ){
792           /* This is the 2-bit case and we are on the second iteration and
793           ** current term is from the first iteration.  So skip this term. */
794           assert( j==1 );
795           continue;
796         }
797         if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
798                                             pOrTerm->leftCursor))==0 ){
799           /* This term must be of the form t1.a==t2.b where t2 is in the
800           ** chngToIN set but t1 is not.  This term will be either preceded
801           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
802           ** and use its inversion. */
803           testcase( pOrTerm->wtFlags & TERM_COPIED );
804           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
805           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
806           continue;
807         }
808         iColumn = pOrTerm->u.leftColumn;
809         iCursor = pOrTerm->leftCursor;
810         pLeft = pOrTerm->pExpr->pLeft;
811         break;
812       }
813       if( i<0 ){
814         /* No candidate table+column was found.  This can only occur
815         ** on the second iteration */
816         assert( j==1 );
817         assert( IsPowerOfTwo(chngToIN) );
818         assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
819         break;
820       }
821       testcase( j==1 );
822 
823       /* We have found a candidate table and column.  Check to see if that
824       ** table and column is common to every term in the OR clause */
825       okToChngToIN = 1;
826       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
827         assert( pOrTerm->eOperator & WO_EQ );
828         if( pOrTerm->leftCursor!=iCursor ){
829           pOrTerm->wtFlags &= ~TERM_OR_OK;
830         }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR
831                && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
832         )){
833           okToChngToIN = 0;
834         }else{
835           int affLeft, affRight;
836           /* If the right-hand side is also a column, then the affinities
837           ** of both right and left sides must be such that no type
838           ** conversions are required on the right.  (Ticket #2249)
839           */
840           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
841           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
842           if( affRight!=0 && affRight!=affLeft ){
843             okToChngToIN = 0;
844           }else{
845             pOrTerm->wtFlags |= TERM_OR_OK;
846           }
847         }
848       }
849     }
850 
851     /* At this point, okToChngToIN is true if original pTerm satisfies
852     ** case 1.  In that case, construct a new virtual term that is
853     ** pTerm converted into an IN operator.
854     */
855     if( okToChngToIN ){
856       Expr *pDup;            /* A transient duplicate expression */
857       ExprList *pList = 0;   /* The RHS of the IN operator */
858       Expr *pLeft = 0;       /* The LHS of the IN operator */
859       Expr *pNew;            /* The complete IN operator */
860 
861       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
862         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
863         assert( pOrTerm->eOperator & WO_EQ );
864         assert( pOrTerm->leftCursor==iCursor );
865         assert( pOrTerm->u.leftColumn==iColumn );
866         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
867         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
868         pLeft = pOrTerm->pExpr->pLeft;
869       }
870       assert( pLeft!=0 );
871       pDup = sqlite3ExprDup(db, pLeft, 0);
872       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
873       if( pNew ){
874         int idxNew;
875         transferJoinMarkings(pNew, pExpr);
876         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
877         pNew->x.pList = pList;
878         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
879         testcase( idxNew==0 );
880         exprAnalyze(pSrc, pWC, idxNew);
881         /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
882         markTermAsChild(pWC, idxNew, idxTerm);
883       }else{
884         sqlite3ExprListDelete(db, pList);
885       }
886     }
887   }
888 }
889 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
890 
891 /*
892 ** We already know that pExpr is a binary operator where both operands are
893 ** column references.  This routine checks to see if pExpr is an equivalence
894 ** relation:
895 **   1.  The SQLITE_Transitive optimization must be enabled
896 **   2.  Must be either an == or an IS operator
897 **   3.  Not originating in the ON clause of an OUTER JOIN
898 **   4.  The affinities of A and B must be compatible
899 **   5a. Both operands use the same collating sequence OR
900 **   5b. The overall collating sequence is BINARY
901 ** If this routine returns TRUE, that means that the RHS can be substituted
902 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
903 ** This is an optimization.  No harm comes from returning 0.  But if 1 is
904 ** returned when it should not be, then incorrect answers might result.
905 */
906 static int termIsEquivalence(Parse *pParse, Expr *pExpr){
907   char aff1, aff2;
908   CollSeq *pColl;
909   if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
910   if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
911   if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
912   aff1 = sqlite3ExprAffinity(pExpr->pLeft);
913   aff2 = sqlite3ExprAffinity(pExpr->pRight);
914   if( aff1!=aff2
915    && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
916   ){
917     return 0;
918   }
919   pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
920   if( sqlite3IsBinary(pColl) ) return 1;
921   return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
922 }
923 
924 /*
925 ** Recursively walk the expressions of a SELECT statement and generate
926 ** a bitmask indicating which tables are used in that expression
927 ** tree.
928 */
929 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
930   Bitmask mask = 0;
931   while( pS ){
932     SrcList *pSrc = pS->pSrc;
933     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
934     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
935     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
936     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
937     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
938     if( ALWAYS(pSrc!=0) ){
939       int i;
940       for(i=0; i<pSrc->nSrc; i++){
941         mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
942         mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
943         if( pSrc->a[i].fg.isTabFunc ){
944           mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
945         }
946       }
947     }
948     pS = pS->pPrior;
949   }
950   return mask;
951 }
952 
953 /*
954 ** Expression pExpr is one operand of a comparison operator that might
955 ** be useful for indexing.  This routine checks to see if pExpr appears
956 ** in any index.  Return TRUE (1) if pExpr is an indexed term and return
957 ** FALSE (0) if not.  If TRUE is returned, also set aiCurCol[0] to the cursor
958 ** number of the table that is indexed and aiCurCol[1] to the column number
959 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
960 ** indexed.
961 **
962 ** If pExpr is a TK_COLUMN column reference, then this routine always returns
963 ** true even if that particular column is not indexed, because the column
964 ** might be added to an automatic index later.
965 */
966 static SQLITE_NOINLINE int exprMightBeIndexed2(
967   SrcList *pFrom,        /* The FROM clause */
968   Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
969   int *aiCurCol,         /* Write the referenced table cursor and column here */
970   Expr *pExpr            /* An operand of a comparison operator */
971 ){
972   Index *pIdx;
973   int i;
974   int iCur;
975   for(i=0; mPrereq>1; i++, mPrereq>>=1){}
976   iCur = pFrom->a[i].iCursor;
977   for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
978     if( pIdx->aColExpr==0 ) continue;
979     for(i=0; i<pIdx->nKeyCol; i++){
980       if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
981       if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
982         aiCurCol[0] = iCur;
983         aiCurCol[1] = XN_EXPR;
984         return 1;
985       }
986     }
987   }
988   return 0;
989 }
990 static int exprMightBeIndexed(
991   SrcList *pFrom,        /* The FROM clause */
992   Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
993   int *aiCurCol,         /* Write the referenced table cursor & column here */
994   Expr *pExpr,           /* An operand of a comparison operator */
995   int op                 /* The specific comparison operator */
996 ){
997   /* If this expression is a vector to the left or right of a
998   ** inequality constraint (>, <, >= or <=), perform the processing
999   ** on the first element of the vector.  */
1000   assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
1001   assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
1002   assert( op<=TK_GE );
1003   if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
1004     pExpr = pExpr->x.pList->a[0].pExpr;
1005   }
1006 
1007   if( pExpr->op==TK_COLUMN ){
1008     aiCurCol[0] = pExpr->iTable;
1009     aiCurCol[1] = pExpr->iColumn;
1010     return 1;
1011   }
1012   if( mPrereq==0 ) return 0;                 /* No table references */
1013   if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
1014   return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
1015 }
1016 
1017 /*
1018 ** The input to this routine is an WhereTerm structure with only the
1019 ** "pExpr" field filled in.  The job of this routine is to analyze the
1020 ** subexpression and populate all the other fields of the WhereTerm
1021 ** structure.
1022 **
1023 ** If the expression is of the form "<expr> <op> X" it gets commuted
1024 ** to the standard form of "X <op> <expr>".
1025 **
1026 ** If the expression is of the form "X <op> Y" where both X and Y are
1027 ** columns, then the original expression is unchanged and a new virtual
1028 ** term of the form "Y <op> X" is added to the WHERE clause and
1029 ** analyzed separately.  The original term is marked with TERM_COPIED
1030 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1031 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1032 ** is a commuted copy of a prior term.)  The original term has nChild=1
1033 ** and the copy has idxParent set to the index of the original term.
1034 */
1035 static void exprAnalyze(
1036   SrcList *pSrc,            /* the FROM clause */
1037   WhereClause *pWC,         /* the WHERE clause */
1038   int idxTerm               /* Index of the term to be analyzed */
1039 ){
1040   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1041   WhereTerm *pTerm;                /* The term to be analyzed */
1042   WhereMaskSet *pMaskSet;          /* Set of table index masks */
1043   Expr *pExpr;                     /* The expression to be analyzed */
1044   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
1045   Bitmask prereqAll;               /* Prerequesites of pExpr */
1046   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
1047   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
1048   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
1049   int noCase = 0;                  /* uppercase equivalent to lowercase */
1050   int op;                          /* Top-level operator.  pExpr->op */
1051   Parse *pParse = pWInfo->pParse;  /* Parsing context */
1052   sqlite3 *db = pParse->db;        /* Database connection */
1053   unsigned char eOp2 = 0;          /* op2 value for LIKE/REGEXP/GLOB */
1054   int nLeft;                       /* Number of elements on left side vector */
1055 
1056   if( db->mallocFailed ){
1057     return;
1058   }
1059   pTerm = &pWC->a[idxTerm];
1060   pMaskSet = &pWInfo->sMaskSet;
1061   pExpr = pTerm->pExpr;
1062   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1063   prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
1064   op = pExpr->op;
1065   if( op==TK_IN ){
1066     assert( pExpr->pRight==0 );
1067     if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
1068     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1069       pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
1070     }else{
1071       pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
1072     }
1073   }else if( op==TK_ISNULL ){
1074     pTerm->prereqRight = 0;
1075   }else{
1076     pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
1077   }
1078   pMaskSet->bVarSelect = 0;
1079   prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
1080   if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
1081   if( ExprHasProperty(pExpr, EP_FromJoin) ){
1082     Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
1083     prereqAll |= x;
1084     extraRight = x-1;  /* ON clause terms may not be used with an index
1085                        ** on left table of a LEFT JOIN.  Ticket #3015 */
1086     if( (prereqAll>>1)>=x ){
1087       sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
1088       return;
1089     }
1090   }
1091   pTerm->prereqAll = prereqAll;
1092   pTerm->leftCursor = -1;
1093   pTerm->iParent = -1;
1094   pTerm->eOperator = 0;
1095   if( allowedOp(op) ){
1096     int aiCurCol[2];
1097     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1098     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1099     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
1100 
1101     if( pTerm->iField>0 ){
1102       assert( op==TK_IN );
1103       assert( pLeft->op==TK_VECTOR );
1104       pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
1105     }
1106 
1107     if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
1108       pTerm->leftCursor = aiCurCol[0];
1109       pTerm->u.leftColumn = aiCurCol[1];
1110       pTerm->eOperator = operatorMask(op) & opMask;
1111     }
1112     if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
1113     if( pRight
1114      && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
1115     ){
1116       WhereTerm *pNew;
1117       Expr *pDup;
1118       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
1119       assert( pTerm->iField==0 );
1120       if( pTerm->leftCursor>=0 ){
1121         int idxNew;
1122         pDup = sqlite3ExprDup(db, pExpr, 0);
1123         if( db->mallocFailed ){
1124           sqlite3ExprDelete(db, pDup);
1125           return;
1126         }
1127         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1128         if( idxNew==0 ) return;
1129         pNew = &pWC->a[idxNew];
1130         markTermAsChild(pWC, idxNew, idxTerm);
1131         if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
1132         pTerm = &pWC->a[idxTerm];
1133         pTerm->wtFlags |= TERM_COPIED;
1134 
1135         if( termIsEquivalence(pParse, pDup) ){
1136           pTerm->eOperator |= WO_EQUIV;
1137           eExtraOp = WO_EQUIV;
1138         }
1139       }else{
1140         pDup = pExpr;
1141         pNew = pTerm;
1142       }
1143       exprCommute(pParse, pDup);
1144       pNew->leftCursor = aiCurCol[0];
1145       pNew->u.leftColumn = aiCurCol[1];
1146       testcase( (prereqLeft | extraRight) != prereqLeft );
1147       pNew->prereqRight = prereqLeft | extraRight;
1148       pNew->prereqAll = prereqAll;
1149       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1150     }
1151   }
1152 
1153 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1154   /* If a term is the BETWEEN operator, create two new virtual terms
1155   ** that define the range that the BETWEEN implements.  For example:
1156   **
1157   **      a BETWEEN b AND c
1158   **
1159   ** is converted into:
1160   **
1161   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1162   **
1163   ** The two new terms are added onto the end of the WhereClause object.
1164   ** The new terms are "dynamic" and are children of the original BETWEEN
1165   ** term.  That means that if the BETWEEN term is coded, the children are
1166   ** skipped.  Or, if the children are satisfied by an index, the original
1167   ** BETWEEN term is skipped.
1168   */
1169   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1170     ExprList *pList = pExpr->x.pList;
1171     int i;
1172     static const u8 ops[] = {TK_GE, TK_LE};
1173     assert( pList!=0 );
1174     assert( pList->nExpr==2 );
1175     for(i=0; i<2; i++){
1176       Expr *pNewExpr;
1177       int idxNew;
1178       pNewExpr = sqlite3PExpr(pParse, ops[i],
1179                              sqlite3ExprDup(db, pExpr->pLeft, 0),
1180                              sqlite3ExprDup(db, pList->a[i].pExpr, 0));
1181       transferJoinMarkings(pNewExpr, pExpr);
1182       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1183       testcase( idxNew==0 );
1184       exprAnalyze(pSrc, pWC, idxNew);
1185       pTerm = &pWC->a[idxTerm];
1186       markTermAsChild(pWC, idxNew, idxTerm);
1187     }
1188   }
1189 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1190 
1191 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1192   /* Analyze a term that is composed of two or more subterms connected by
1193   ** an OR operator.
1194   */
1195   else if( pExpr->op==TK_OR ){
1196     assert( pWC->op==TK_AND );
1197     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1198     pTerm = &pWC->a[idxTerm];
1199   }
1200 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1201 
1202 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1203   /* Add constraints to reduce the search space on a LIKE or GLOB
1204   ** operator.
1205   **
1206   ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1207   **
1208   **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1209   **
1210   ** The last character of the prefix "abc" is incremented to form the
1211   ** termination condition "abd".  If case is not significant (the default
1212   ** for LIKE) then the lower-bound is made all uppercase and the upper-
1213   ** bound is made all lowercase so that the bounds also work when comparing
1214   ** BLOBs.
1215   */
1216   if( pWC->op==TK_AND
1217    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1218   ){
1219     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
1220     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1221     Expr *pNewExpr1;
1222     Expr *pNewExpr2;
1223     int idxNew1;
1224     int idxNew2;
1225     const char *zCollSeqName;     /* Name of collating sequence */
1226     const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1227 
1228     pLeft = pExpr->x.pList->a[1].pExpr;
1229     pStr2 = sqlite3ExprDup(db, pStr1, 0);
1230 
1231     /* Convert the lower bound to upper-case and the upper bound to
1232     ** lower-case (upper-case is less than lower-case in ASCII) so that
1233     ** the range constraints also work for BLOBs
1234     */
1235     if( noCase && !pParse->db->mallocFailed ){
1236       int i;
1237       char c;
1238       pTerm->wtFlags |= TERM_LIKE;
1239       for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1240         pStr1->u.zToken[i] = sqlite3Toupper(c);
1241         pStr2->u.zToken[i] = sqlite3Tolower(c);
1242       }
1243     }
1244 
1245     if( !db->mallocFailed ){
1246       u8 c, *pC;       /* Last character before the first wildcard */
1247       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1248       c = *pC;
1249       if( noCase ){
1250         /* The point is to increment the last character before the first
1251         ** wildcard.  But if we increment '@', that will push it into the
1252         ** alphabetic range where case conversions will mess up the
1253         ** inequality.  To avoid this, make sure to also run the full
1254         ** LIKE on all candidate expressions by clearing the isComplete flag
1255         */
1256         if( c=='A'-1 ) isComplete = 0;
1257         c = sqlite3UpperToLower[c];
1258       }
1259       *pC = c + 1;
1260     }
1261     zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
1262     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1263     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1264            sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
1265            pStr1);
1266     transferJoinMarkings(pNewExpr1, pExpr);
1267     idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1268     testcase( idxNew1==0 );
1269     exprAnalyze(pSrc, pWC, idxNew1);
1270     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1271     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1272            sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
1273            pStr2);
1274     transferJoinMarkings(pNewExpr2, pExpr);
1275     idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1276     testcase( idxNew2==0 );
1277     exprAnalyze(pSrc, pWC, idxNew2);
1278     pTerm = &pWC->a[idxTerm];
1279     if( isComplete ){
1280       markTermAsChild(pWC, idxNew1, idxTerm);
1281       markTermAsChild(pWC, idxNew2, idxTerm);
1282     }
1283   }
1284 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1285 
1286 #ifndef SQLITE_OMIT_VIRTUALTABLE
1287   /* Add a WO_AUX auxiliary term to the constraint set if the
1288   ** current expression is of the form "column OP expr" where OP
1289   ** is an operator that gets passed into virtual tables but which is
1290   ** not normally optimized for ordinary tables.  In other words, OP
1291   ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
1292   ** This information is used by the xBestIndex methods of
1293   ** virtual tables.  The native query optimizer does not attempt
1294   ** to do anything with MATCH functions.
1295   */
1296   if( pWC->op==TK_AND ){
1297     Expr *pRight = 0, *pLeft = 0;
1298     int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
1299     while( res-- > 0 ){
1300       int idxNew;
1301       WhereTerm *pNewTerm;
1302       Bitmask prereqColumn, prereqExpr;
1303 
1304       prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1305       prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1306       if( (prereqExpr & prereqColumn)==0 ){
1307         Expr *pNewExpr;
1308         pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1309             0, sqlite3ExprDup(db, pRight, 0));
1310         if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
1311           ExprSetProperty(pNewExpr, EP_FromJoin);
1312         }
1313         idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1314         testcase( idxNew==0 );
1315         pNewTerm = &pWC->a[idxNew];
1316         pNewTerm->prereqRight = prereqExpr;
1317         pNewTerm->leftCursor = pLeft->iTable;
1318         pNewTerm->u.leftColumn = pLeft->iColumn;
1319         pNewTerm->eOperator = WO_AUX;
1320         pNewTerm->eMatchOp = eOp2;
1321         markTermAsChild(pWC, idxNew, idxTerm);
1322         pTerm = &pWC->a[idxTerm];
1323         pTerm->wtFlags |= TERM_COPIED;
1324         pNewTerm->prereqAll = pTerm->prereqAll;
1325       }
1326       SWAP(Expr*, pLeft, pRight);
1327     }
1328   }
1329 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1330 
1331   /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
1332   ** new terms for each component comparison - "a = ?" and "b = ?".  The
1333   ** new terms completely replace the original vector comparison, which is
1334   ** no longer used.
1335   **
1336   ** This is only required if at least one side of the comparison operation
1337   ** is not a sub-select.  */
1338   if( pWC->op==TK_AND
1339   && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
1340   && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
1341   && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
1342   && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
1343     || (pExpr->pRight->flags & EP_xIsSelect)==0)
1344   ){
1345     int i;
1346     for(i=0; i<nLeft; i++){
1347       int idxNew;
1348       Expr *pNew;
1349       Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
1350       Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
1351 
1352       pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
1353       transferJoinMarkings(pNew, pExpr);
1354       idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
1355       exprAnalyze(pSrc, pWC, idxNew);
1356     }
1357     pTerm = &pWC->a[idxTerm];
1358     pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL;  /* Disable the original */
1359     pTerm->eOperator = 0;
1360   }
1361 
1362   /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1363   ** a virtual term for each vector component. The expression object
1364   ** used by each such virtual term is pExpr (the full vector IN(...)
1365   ** expression). The WhereTerm.iField variable identifies the index within
1366   ** the vector on the LHS that the virtual term represents.
1367   **
1368   ** This only works if the RHS is a simple SELECT, not a compound
1369   */
1370   if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
1371    && pExpr->pLeft->op==TK_VECTOR
1372    && pExpr->x.pSelect->pPrior==0
1373   ){
1374     int i;
1375     for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1376       int idxNew;
1377       idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
1378       pWC->a[idxNew].iField = i+1;
1379       exprAnalyze(pSrc, pWC, idxNew);
1380       markTermAsChild(pWC, idxNew, idxTerm);
1381     }
1382   }
1383 
1384 #ifdef SQLITE_ENABLE_STAT4
1385   /* When sqlite_stat4 histogram data is available an operator of the
1386   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1387   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
1388   ** virtual term of that form.
1389   **
1390   ** Note that the virtual term must be tagged with TERM_VNULL.
1391   */
1392   if( pExpr->op==TK_NOTNULL
1393    && pExpr->pLeft->op==TK_COLUMN
1394    && pExpr->pLeft->iColumn>=0
1395    && !ExprHasProperty(pExpr, EP_FromJoin)
1396    && OptimizationEnabled(db, SQLITE_Stat4)
1397   ){
1398     Expr *pNewExpr;
1399     Expr *pLeft = pExpr->pLeft;
1400     int idxNew;
1401     WhereTerm *pNewTerm;
1402 
1403     pNewExpr = sqlite3PExpr(pParse, TK_GT,
1404                             sqlite3ExprDup(db, pLeft, 0),
1405                             sqlite3ExprAlloc(db, TK_NULL, 0, 0));
1406 
1407     idxNew = whereClauseInsert(pWC, pNewExpr,
1408                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1409     if( idxNew ){
1410       pNewTerm = &pWC->a[idxNew];
1411       pNewTerm->prereqRight = 0;
1412       pNewTerm->leftCursor = pLeft->iTable;
1413       pNewTerm->u.leftColumn = pLeft->iColumn;
1414       pNewTerm->eOperator = WO_GT;
1415       markTermAsChild(pWC, idxNew, idxTerm);
1416       pTerm = &pWC->a[idxTerm];
1417       pTerm->wtFlags |= TERM_COPIED;
1418       pNewTerm->prereqAll = pTerm->prereqAll;
1419     }
1420   }
1421 #endif /* SQLITE_ENABLE_STAT4 */
1422 
1423   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1424   ** an index for tables to the left of the join.
1425   */
1426   testcase( pTerm!=&pWC->a[idxTerm] );
1427   pTerm = &pWC->a[idxTerm];
1428   pTerm->prereqRight |= extraRight;
1429 }
1430 
1431 /***************************************************************************
1432 ** Routines with file scope above.  Interface to the rest of the where.c
1433 ** subsystem follows.
1434 ***************************************************************************/
1435 
1436 /*
1437 ** This routine identifies subexpressions in the WHERE clause where
1438 ** each subexpression is separated by the AND operator or some other
1439 ** operator specified in the op parameter.  The WhereClause structure
1440 ** is filled with pointers to subexpressions.  For example:
1441 **
1442 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1443 **           \________/     \_______________/     \________________/
1444 **            slot[0]            slot[1]               slot[2]
1445 **
1446 ** The original WHERE clause in pExpr is unaltered.  All this routine
1447 ** does is make slot[] entries point to substructure within pExpr.
1448 **
1449 ** In the previous sentence and in the diagram, "slot[]" refers to
1450 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
1451 ** all terms of the WHERE clause.
1452 */
1453 void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1454   Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1455   pWC->op = op;
1456   if( pE2==0 ) return;
1457   if( pE2->op!=op ){
1458     whereClauseInsert(pWC, pExpr, 0);
1459   }else{
1460     sqlite3WhereSplit(pWC, pE2->pLeft, op);
1461     sqlite3WhereSplit(pWC, pE2->pRight, op);
1462   }
1463 }
1464 
1465 /*
1466 ** Initialize a preallocated WhereClause structure.
1467 */
1468 void sqlite3WhereClauseInit(
1469   WhereClause *pWC,        /* The WhereClause to be initialized */
1470   WhereInfo *pWInfo        /* The WHERE processing context */
1471 ){
1472   pWC->pWInfo = pWInfo;
1473   pWC->hasOr = 0;
1474   pWC->pOuter = 0;
1475   pWC->nTerm = 0;
1476   pWC->nSlot = ArraySize(pWC->aStatic);
1477   pWC->a = pWC->aStatic;
1478 }
1479 
1480 /*
1481 ** Deallocate a WhereClause structure.  The WhereClause structure
1482 ** itself is not freed.  This routine is the inverse of
1483 ** sqlite3WhereClauseInit().
1484 */
1485 void sqlite3WhereClauseClear(WhereClause *pWC){
1486   int i;
1487   WhereTerm *a;
1488   sqlite3 *db = pWC->pWInfo->pParse->db;
1489   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1490     if( a->wtFlags & TERM_DYNAMIC ){
1491       sqlite3ExprDelete(db, a->pExpr);
1492     }
1493     if( a->wtFlags & TERM_ORINFO ){
1494       whereOrInfoDelete(db, a->u.pOrInfo);
1495     }else if( a->wtFlags & TERM_ANDINFO ){
1496       whereAndInfoDelete(db, a->u.pAndInfo);
1497     }
1498   }
1499   if( pWC->a!=pWC->aStatic ){
1500     sqlite3DbFree(db, pWC->a);
1501   }
1502 }
1503 
1504 
1505 /*
1506 ** These routines walk (recursively) an expression tree and generate
1507 ** a bitmask indicating which tables are used in that expression
1508 ** tree.
1509 */
1510 Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
1511   Bitmask mask;
1512   if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
1513     return sqlite3WhereGetMask(pMaskSet, p->iTable);
1514   }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1515     assert( p->op!=TK_IF_NULL_ROW );
1516     return 0;
1517   }
1518   mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
1519   if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
1520   if( p->pRight ){
1521     mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
1522     assert( p->x.pList==0 );
1523   }else if( ExprHasProperty(p, EP_xIsSelect) ){
1524     if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
1525     mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
1526   }else if( p->x.pList ){
1527     mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1528   }
1529 #ifndef SQLITE_OMIT_WINDOWFUNC
1530   if( p->op==TK_FUNCTION && p->y.pWin ){
1531     mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
1532     mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
1533   }
1534 #endif
1535   return mask;
1536 }
1537 Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
1538   return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
1539 }
1540 Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1541   int i;
1542   Bitmask mask = 0;
1543   if( pList ){
1544     for(i=0; i<pList->nExpr; i++){
1545       mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1546     }
1547   }
1548   return mask;
1549 }
1550 
1551 
1552 /*
1553 ** Call exprAnalyze on all terms in a WHERE clause.
1554 **
1555 ** Note that exprAnalyze() might add new virtual terms onto the
1556 ** end of the WHERE clause.  We do not want to analyze these new
1557 ** virtual terms, so start analyzing at the end and work forward
1558 ** so that the added virtual terms are never processed.
1559 */
1560 void sqlite3WhereExprAnalyze(
1561   SrcList *pTabList,       /* the FROM clause */
1562   WhereClause *pWC         /* the WHERE clause to be analyzed */
1563 ){
1564   int i;
1565   for(i=pWC->nTerm-1; i>=0; i--){
1566     exprAnalyze(pTabList, pWC, i);
1567   }
1568 }
1569 
1570 /*
1571 ** For table-valued-functions, transform the function arguments into
1572 ** new WHERE clause terms.
1573 **
1574 ** Each function argument translates into an equality constraint against
1575 ** a HIDDEN column in the table.
1576 */
1577 void sqlite3WhereTabFuncArgs(
1578   Parse *pParse,                    /* Parsing context */
1579   struct SrcList_item *pItem,       /* The FROM clause term to process */
1580   WhereClause *pWC                  /* Xfer function arguments to here */
1581 ){
1582   Table *pTab;
1583   int j, k;
1584   ExprList *pArgs;
1585   Expr *pColRef;
1586   Expr *pTerm;
1587   if( pItem->fg.isTabFunc==0 ) return;
1588   pTab = pItem->pTab;
1589   assert( pTab!=0 );
1590   pArgs = pItem->u1.pFuncArg;
1591   if( pArgs==0 ) return;
1592   for(j=k=0; j<pArgs->nExpr; j++){
1593     Expr *pRhs;
1594     while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
1595     if( k>=pTab->nCol ){
1596       sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
1597                       pTab->zName, j);
1598       return;
1599     }
1600     pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
1601     if( pColRef==0 ) return;
1602     pColRef->iTable = pItem->iCursor;
1603     pColRef->iColumn = k++;
1604     pColRef->y.pTab = pTab;
1605     pRhs = sqlite3PExpr(pParse, TK_UPLUS,
1606         sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
1607     pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
1608     whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1609   }
1610 }
1611