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