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