xref: /sqlite-3.40.0/src/whereexpr.c (revision 9bccde3d)
1 /*
2 ** 2015-06-08
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This module contains C code that generates VDBE code used to process
13 ** the WHERE clause of SQL statements.
14 **
15 ** This file was originally part of where.c but was split out to improve
16 ** readability and editabiliity.  This file contains utility routines for
17 ** analyzing Expr objects in the WHERE clause.
18 */
19 #include "sqliteInt.h"
20 #include "whereInt.h"
21 
22 /* Forward declarations */
23 static void exprAnalyze(SrcList*, WhereClause*, int);
24 
25 /*
26 ** Deallocate all memory associated with a WhereOrInfo object.
27 */
28 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
29   sqlite3WhereClauseClear(&p->wc);
30   sqlite3DbFree(db, p);
31 }
32 
33 /*
34 ** Deallocate all memory associated with a WhereAndInfo object.
35 */
36 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
37   sqlite3WhereClauseClear(&p->wc);
38   sqlite3DbFree(db, p);
39 }
40 
41 /*
42 ** Add a single new WhereTerm entry to the WhereClause object pWC.
43 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
44 ** The index in pWC->a[] of the new WhereTerm is returned on success.
45 ** 0 is returned if the new WhereTerm could not be added due to a memory
46 ** allocation error.  The memory allocation failure will be recorded in
47 ** the db->mallocFailed flag so that higher-level functions can detect it.
48 **
49 ** This routine will increase the size of the pWC->a[] array as necessary.
50 **
51 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
52 ** for freeing the expression p is assumed by the WhereClause object pWC.
53 ** This is true even if this routine fails to allocate a new WhereTerm.
54 **
55 ** WARNING:  This routine might reallocate the space used to store
56 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
57 ** calling this routine.  Such pointers may be reinitialized by referencing
58 ** the pWC->a[] array.
59 */
60 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
61   WhereTerm *pTerm;
62   int idx;
63   testcase( wtFlags & TERM_VIRTUAL );
64   if( pWC->nTerm>=pWC->nSlot ){
65     WhereTerm *pOld = pWC->a;
66     sqlite3 *db = pWC->pWInfo->pParse->db;
67     pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
68     if( pWC->a==0 ){
69       if( wtFlags & TERM_DYNAMIC ){
70         sqlite3ExprDelete(db, p);
71       }
72       pWC->a = pOld;
73       return 0;
74     }
75     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
76     if( pOld!=pWC->aStatic ){
77       sqlite3DbFree(db, pOld);
78     }
79     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
80     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   memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
537   sqlite3WhereClauseInit(pOrWc, pWInfo);
538   sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
539   sqlite3WhereExprAnalyze(pSrc, pOrWc);
540   if( db->mallocFailed ) return;
541   assert( pOrWc->nTerm>=2 );
542 
543   /*
544   ** Compute the set of tables that might satisfy cases 1 or 3.
545   */
546   indexable = ~(Bitmask)0;
547   chngToIN = ~(Bitmask)0;
548   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
549     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
550       WhereAndInfo *pAndInfo;
551       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
552       chngToIN = 0;
553       pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
554       if( pAndInfo ){
555         WhereClause *pAndWC;
556         WhereTerm *pAndTerm;
557         int j;
558         Bitmask b = 0;
559         pOrTerm->u.pAndInfo = pAndInfo;
560         pOrTerm->wtFlags |= TERM_ANDINFO;
561         pOrTerm->eOperator = WO_AND;
562         pAndWC = &pAndInfo->wc;
563         memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
564         sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
565         sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
566         sqlite3WhereExprAnalyze(pSrc, pAndWC);
567         pAndWC->pOuter = pWC;
568         if( !db->mallocFailed ){
569           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
570             assert( pAndTerm->pExpr );
571             if( allowedOp(pAndTerm->pExpr->op) ){
572               b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
573             }
574           }
575         }
576         indexable &= b;
577       }
578     }else if( pOrTerm->wtFlags & TERM_COPIED ){
579       /* Skip this term for now.  We revisit it when we process the
580       ** corresponding TERM_VIRTUAL term */
581     }else{
582       Bitmask b;
583       b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
584       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
585         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
586         b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
587       }
588       indexable &= b;
589       if( (pOrTerm->eOperator & WO_EQ)==0 ){
590         chngToIN = 0;
591       }else{
592         chngToIN &= b;
593       }
594     }
595   }
596 
597   /*
598   ** Record the set of tables that satisfy case 3.  The set might be
599   ** empty.
600   */
601   pOrInfo->indexable = indexable;
602   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
603 
604   /* For a two-way OR, attempt to implementation case 2.
605   */
606   if( indexable && pOrWc->nTerm==2 ){
607     int iOne = 0;
608     WhereTerm *pOne;
609     while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
610       int iTwo = 0;
611       WhereTerm *pTwo;
612       while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
613         whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
614       }
615     }
616   }
617 
618   /*
619   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
620   ** we have to do some additional checking to see if case 1 really
621   ** is satisfied.
622   **
623   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
624   ** that there is no possibility of transforming the OR clause into an
625   ** IN operator because one or more terms in the OR clause contain
626   ** something other than == on a column in the single table.  The 1-bit
627   ** case means that every term of the OR clause is of the form
628   ** "table.column=expr" for some single table.  The one bit that is set
629   ** will correspond to the common table.  We still need to check to make
630   ** sure the same column is used on all terms.  The 2-bit case is when
631   ** the all terms are of the form "table1.column=table2.column".  It
632   ** might be possible to form an IN operator with either table1.column
633   ** or table2.column as the LHS if either is common to every term of
634   ** the OR clause.
635   **
636   ** Note that terms of the form "table.column1=table.column2" (the
637   ** same table on both sizes of the ==) cannot be optimized.
638   */
639   if( chngToIN ){
640     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
641     int iColumn = -1;         /* Column index on lhs of IN operator */
642     int iCursor = -1;         /* Table cursor common to all terms */
643     int j = 0;                /* Loop counter */
644 
645     /* Search for a table and column that appears on one side or the
646     ** other of the == operator in every subterm.  That table and column
647     ** will be recorded in iCursor and iColumn.  There might not be any
648     ** such table and column.  Set okToChngToIN if an appropriate table
649     ** and column is found but leave okToChngToIN false if not found.
650     */
651     for(j=0; j<2 && !okToChngToIN; j++){
652       pOrTerm = pOrWc->a;
653       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
654         assert( pOrTerm->eOperator & WO_EQ );
655         pOrTerm->wtFlags &= ~TERM_OR_OK;
656         if( pOrTerm->leftCursor==iCursor ){
657           /* This is the 2-bit case and we are on the second iteration and
658           ** current term is from the first iteration.  So skip this term. */
659           assert( j==1 );
660           continue;
661         }
662         if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
663                                             pOrTerm->leftCursor))==0 ){
664           /* This term must be of the form t1.a==t2.b where t2 is in the
665           ** chngToIN set but t1 is not.  This term will be either preceded
666           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
667           ** and use its inversion. */
668           testcase( pOrTerm->wtFlags & TERM_COPIED );
669           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
670           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
671           continue;
672         }
673         iColumn = pOrTerm->u.leftColumn;
674         iCursor = pOrTerm->leftCursor;
675         break;
676       }
677       if( i<0 ){
678         /* No candidate table+column was found.  This can only occur
679         ** on the second iteration */
680         assert( j==1 );
681         assert( IsPowerOfTwo(chngToIN) );
682         assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
683         break;
684       }
685       testcase( j==1 );
686 
687       /* We have found a candidate table and column.  Check to see if that
688       ** table and column is common to every term in the OR clause */
689       okToChngToIN = 1;
690       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
691         assert( pOrTerm->eOperator & WO_EQ );
692         if( pOrTerm->leftCursor!=iCursor ){
693           pOrTerm->wtFlags &= ~TERM_OR_OK;
694         }else if( pOrTerm->u.leftColumn!=iColumn ){
695           okToChngToIN = 0;
696         }else{
697           int affLeft, affRight;
698           /* If the right-hand side is also a column, then the affinities
699           ** of both right and left sides must be such that no type
700           ** conversions are required on the right.  (Ticket #2249)
701           */
702           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
703           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
704           if( affRight!=0 && affRight!=affLeft ){
705             okToChngToIN = 0;
706           }else{
707             pOrTerm->wtFlags |= TERM_OR_OK;
708           }
709         }
710       }
711     }
712 
713     /* At this point, okToChngToIN is true if original pTerm satisfies
714     ** case 1.  In that case, construct a new virtual term that is
715     ** pTerm converted into an IN operator.
716     */
717     if( okToChngToIN ){
718       Expr *pDup;            /* A transient duplicate expression */
719       ExprList *pList = 0;   /* The RHS of the IN operator */
720       Expr *pLeft = 0;       /* The LHS of the IN operator */
721       Expr *pNew;            /* The complete IN operator */
722 
723       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
724         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
725         assert( pOrTerm->eOperator & WO_EQ );
726         assert( pOrTerm->leftCursor==iCursor );
727         assert( pOrTerm->u.leftColumn==iColumn );
728         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
729         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
730         pLeft = pOrTerm->pExpr->pLeft;
731       }
732       assert( pLeft!=0 );
733       pDup = sqlite3ExprDup(db, pLeft, 0);
734       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
735       if( pNew ){
736         int idxNew;
737         transferJoinMarkings(pNew, pExpr);
738         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
739         pNew->x.pList = pList;
740         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
741         testcase( idxNew==0 );
742         exprAnalyze(pSrc, pWC, idxNew);
743         pTerm = &pWC->a[idxTerm];
744         markTermAsChild(pWC, idxNew, idxTerm);
745       }else{
746         sqlite3ExprListDelete(db, pList);
747       }
748       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
749     }
750   }
751 }
752 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
753 
754 /*
755 ** We already know that pExpr is a binary operator where both operands are
756 ** column references.  This routine checks to see if pExpr is an equivalence
757 ** relation:
758 **   1.  The SQLITE_Transitive optimization must be enabled
759 **   2.  Must be either an == or an IS operator
760 **   3.  Not originating in the ON clause of an OUTER JOIN
761 **   4.  The affinities of A and B must be compatible
762 **   5a. Both operands use the same collating sequence OR
763 **   5b. The overall collating sequence is BINARY
764 ** If this routine returns TRUE, that means that the RHS can be substituted
765 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
766 ** This is an optimization.  No harm comes from returning 0.  But if 1 is
767 ** returned when it should not be, then incorrect answers might result.
768 */
769 static int termIsEquivalence(Parse *pParse, Expr *pExpr){
770   char aff1, aff2;
771   CollSeq *pColl;
772   const char *zColl1, *zColl2;
773   if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
774   if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
775   if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
776   aff1 = sqlite3ExprAffinity(pExpr->pLeft);
777   aff2 = sqlite3ExprAffinity(pExpr->pRight);
778   if( aff1!=aff2
779    && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
780   ){
781     return 0;
782   }
783   pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
784   if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
785   pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
786   /* Since pLeft and pRight are both a column references, their collating
787   ** sequence should always be defined. */
788   zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
789   pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
790   zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
791   return sqlite3StrICmp(zColl1, zColl2)==0;
792 }
793 
794 /*
795 ** Recursively walk the expressions of a SELECT statement and generate
796 ** a bitmask indicating which tables are used in that expression
797 ** tree.
798 */
799 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
800   Bitmask mask = 0;
801   while( pS ){
802     SrcList *pSrc = pS->pSrc;
803     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
804     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
805     mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
806     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
807     mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
808     if( ALWAYS(pSrc!=0) ){
809       int i;
810       for(i=0; i<pSrc->nSrc; i++){
811         mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
812         mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
813       }
814     }
815     pS = pS->pPrior;
816   }
817   return mask;
818 }
819 
820 /*
821 ** Expression pExpr is one operand of a comparison operator that might
822 ** be useful for indexing.  This routine checks to see if pExpr appears
823 ** in any index.  Return TRUE (1) if pExpr is an indexed term and return
824 ** FALSE (0) if not.  If TRUE is returned, also set *piCur to the cursor
825 ** number of the table that is indexed and *piColumn to the column number
826 ** of the column that is indexed, or -2 if an expression is being indexed.
827 **
828 ** If pExpr is a TK_COLUMN column reference, then this routine always returns
829 ** true even if that particular column is not indexed, because the column
830 ** might be added to an automatic index later.
831 */
832 static int exprMightBeIndexed(
833   SrcList *pFrom,        /* The FROM clause */
834   Bitmask mPrereq,       /* Bitmask of FROM clause terms referenced by pExpr */
835   Expr *pExpr,           /* An operand of a comparison operator */
836   int *piCur,            /* Write the referenced table cursor number here */
837   int *piColumn          /* Write the referenced table column number here */
838 ){
839   Index *pIdx;
840   int i;
841   int iCur;
842   if( pExpr->op==TK_COLUMN ){
843     *piCur = pExpr->iTable;
844     *piColumn = pExpr->iColumn;
845     return 1;
846   }
847   if( mPrereq==0 ) return 0;                 /* No table references */
848   if( (mPrereq&(mPrereq-1))!=0 ) return 0;   /* Refs more than one table */
849   for(i=0; mPrereq>1; i++, mPrereq>>=1){}
850   iCur = pFrom->a[i].iCursor;
851   for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
852     if( pIdx->aColExpr==0 ) continue;
853     for(i=0; i<pIdx->nKeyCol; i++){
854       if( pIdx->aiColumn[i]!=(-2) ) continue;
855       if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
856         *piCur = iCur;
857         *piColumn = -2;
858         return 1;
859       }
860     }
861   }
862   return 0;
863 }
864 
865 /*
866 ** The input to this routine is an WhereTerm structure with only the
867 ** "pExpr" field filled in.  The job of this routine is to analyze the
868 ** subexpression and populate all the other fields of the WhereTerm
869 ** structure.
870 **
871 ** If the expression is of the form "<expr> <op> X" it gets commuted
872 ** to the standard form of "X <op> <expr>".
873 **
874 ** If the expression is of the form "X <op> Y" where both X and Y are
875 ** columns, then the original expression is unchanged and a new virtual
876 ** term of the form "Y <op> X" is added to the WHERE clause and
877 ** analyzed separately.  The original term is marked with TERM_COPIED
878 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
879 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
880 ** is a commuted copy of a prior term.)  The original term has nChild=1
881 ** and the copy has idxParent set to the index of the original term.
882 */
883 static void exprAnalyze(
884   SrcList *pSrc,            /* the FROM clause */
885   WhereClause *pWC,         /* the WHERE clause */
886   int idxTerm               /* Index of the term to be analyzed */
887 ){
888   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
889   WhereTerm *pTerm;                /* The term to be analyzed */
890   WhereMaskSet *pMaskSet;          /* Set of table index masks */
891   Expr *pExpr;                     /* The expression to be analyzed */
892   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
893   Bitmask prereqAll;               /* Prerequesites of pExpr */
894   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
895   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
896   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
897   int noCase = 0;                  /* uppercase equivalent to lowercase */
898   int op;                          /* Top-level operator.  pExpr->op */
899   Parse *pParse = pWInfo->pParse;  /* Parsing context */
900   sqlite3 *db = pParse->db;        /* Database connection */
901   unsigned char eOp2;              /* op2 value for LIKE/REGEXP/GLOB */
902 
903   if( db->mallocFailed ){
904     return;
905   }
906   pTerm = &pWC->a[idxTerm];
907   pMaskSet = &pWInfo->sMaskSet;
908   pExpr = pTerm->pExpr;
909   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
910   prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
911   op = pExpr->op;
912   if( op==TK_IN ){
913     assert( pExpr->pRight==0 );
914     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
915       pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
916     }else{
917       pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
918     }
919   }else if( op==TK_ISNULL ){
920     pTerm->prereqRight = 0;
921   }else{
922     pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
923   }
924   prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
925   if( ExprHasProperty(pExpr, EP_FromJoin) ){
926     Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
927     prereqAll |= x;
928     extraRight = x-1;  /* ON clause terms may not be used with an index
929                        ** on left table of a LEFT JOIN.  Ticket #3015 */
930   }
931   pTerm->prereqAll = prereqAll;
932   pTerm->leftCursor = -1;
933   pTerm->iParent = -1;
934   pTerm->eOperator = 0;
935   if( allowedOp(op) ){
936     int iCur, iColumn;
937     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
938     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
939     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
940     if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
941       pTerm->leftCursor = iCur;
942       pTerm->u.leftColumn = iColumn;
943       pTerm->eOperator = operatorMask(op) & opMask;
944     }
945     if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
946     if( pRight
947      && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
948     ){
949       WhereTerm *pNew;
950       Expr *pDup;
951       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
952       if( pTerm->leftCursor>=0 ){
953         int idxNew;
954         pDup = sqlite3ExprDup(db, pExpr, 0);
955         if( db->mallocFailed ){
956           sqlite3ExprDelete(db, pDup);
957           return;
958         }
959         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
960         if( idxNew==0 ) return;
961         pNew = &pWC->a[idxNew];
962         markTermAsChild(pWC, idxNew, idxTerm);
963         if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
964         pTerm = &pWC->a[idxTerm];
965         pTerm->wtFlags |= TERM_COPIED;
966 
967         if( termIsEquivalence(pParse, pDup) ){
968           pTerm->eOperator |= WO_EQUIV;
969           eExtraOp = WO_EQUIV;
970         }
971       }else{
972         pDup = pExpr;
973         pNew = pTerm;
974       }
975       exprCommute(pParse, pDup);
976       pNew->leftCursor = iCur;
977       pNew->u.leftColumn = iColumn;
978       testcase( (prereqLeft | extraRight) != prereqLeft );
979       pNew->prereqRight = prereqLeft | extraRight;
980       pNew->prereqAll = prereqAll;
981       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
982     }
983   }
984 
985 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
986   /* If a term is the BETWEEN operator, create two new virtual terms
987   ** that define the range that the BETWEEN implements.  For example:
988   **
989   **      a BETWEEN b AND c
990   **
991   ** is converted into:
992   **
993   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
994   **
995   ** The two new terms are added onto the end of the WhereClause object.
996   ** The new terms are "dynamic" and are children of the original BETWEEN
997   ** term.  That means that if the BETWEEN term is coded, the children are
998   ** skipped.  Or, if the children are satisfied by an index, the original
999   ** BETWEEN term is skipped.
1000   */
1001   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1002     ExprList *pList = pExpr->x.pList;
1003     int i;
1004     static const u8 ops[] = {TK_GE, TK_LE};
1005     assert( pList!=0 );
1006     assert( pList->nExpr==2 );
1007     for(i=0; i<2; i++){
1008       Expr *pNewExpr;
1009       int idxNew;
1010       pNewExpr = sqlite3PExpr(pParse, ops[i],
1011                              sqlite3ExprDup(db, pExpr->pLeft, 0),
1012                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
1013       transferJoinMarkings(pNewExpr, pExpr);
1014       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1015       testcase( idxNew==0 );
1016       exprAnalyze(pSrc, pWC, idxNew);
1017       pTerm = &pWC->a[idxTerm];
1018       markTermAsChild(pWC, idxNew, idxTerm);
1019     }
1020   }
1021 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1022 
1023 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1024   /* Analyze a term that is composed of two or more subterms connected by
1025   ** an OR operator.
1026   */
1027   else if( pExpr->op==TK_OR ){
1028     assert( pWC->op==TK_AND );
1029     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1030     pTerm = &pWC->a[idxTerm];
1031   }
1032 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1033 
1034 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1035   /* Add constraints to reduce the search space on a LIKE or GLOB
1036   ** operator.
1037   **
1038   ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1039   **
1040   **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1041   **
1042   ** The last character of the prefix "abc" is incremented to form the
1043   ** termination condition "abd".  If case is not significant (the default
1044   ** for LIKE) then the lower-bound is made all uppercase and the upper-
1045   ** bound is made all lowercase so that the bounds also work when comparing
1046   ** BLOBs.
1047   */
1048   if( pWC->op==TK_AND
1049    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1050   ){
1051     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
1052     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1053     Expr *pNewExpr1;
1054     Expr *pNewExpr2;
1055     int idxNew1;
1056     int idxNew2;
1057     const char *zCollSeqName;     /* Name of collating sequence */
1058     const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1059 
1060     pLeft = pExpr->x.pList->a[1].pExpr;
1061     pStr2 = sqlite3ExprDup(db, pStr1, 0);
1062 
1063     /* Convert the lower bound to upper-case and the upper bound to
1064     ** lower-case (upper-case is less than lower-case in ASCII) so that
1065     ** the range constraints also work for BLOBs
1066     */
1067     if( noCase && !pParse->db->mallocFailed ){
1068       int i;
1069       char c;
1070       pTerm->wtFlags |= TERM_LIKE;
1071       for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1072         pStr1->u.zToken[i] = sqlite3Toupper(c);
1073         pStr2->u.zToken[i] = sqlite3Tolower(c);
1074       }
1075     }
1076 
1077     if( !db->mallocFailed ){
1078       u8 c, *pC;       /* Last character before the first wildcard */
1079       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1080       c = *pC;
1081       if( noCase ){
1082         /* The point is to increment the last character before the first
1083         ** wildcard.  But if we increment '@', that will push it into the
1084         ** alphabetic range where case conversions will mess up the
1085         ** inequality.  To avoid this, make sure to also run the full
1086         ** LIKE on all candidate expressions by clearing the isComplete flag
1087         */
1088         if( c=='A'-1 ) isComplete = 0;
1089         c = sqlite3UpperToLower[c];
1090       }
1091       *pC = c + 1;
1092     }
1093     zCollSeqName = noCase ? "NOCASE" : "BINARY";
1094     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1095     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1096            sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
1097            pStr1, 0);
1098     transferJoinMarkings(pNewExpr1, pExpr);
1099     idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1100     testcase( idxNew1==0 );
1101     exprAnalyze(pSrc, pWC, idxNew1);
1102     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1103     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1104            sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
1105            pStr2, 0);
1106     transferJoinMarkings(pNewExpr2, pExpr);
1107     idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1108     testcase( idxNew2==0 );
1109     exprAnalyze(pSrc, pWC, idxNew2);
1110     pTerm = &pWC->a[idxTerm];
1111     if( isComplete ){
1112       markTermAsChild(pWC, idxNew1, idxTerm);
1113       markTermAsChild(pWC, idxNew2, idxTerm);
1114     }
1115   }
1116 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1117 
1118 #ifndef SQLITE_OMIT_VIRTUALTABLE
1119   /* Add a WO_MATCH auxiliary term to the constraint set if the
1120   ** current expression is of the form:  column MATCH expr.
1121   ** This information is used by the xBestIndex methods of
1122   ** virtual tables.  The native query optimizer does not attempt
1123   ** to do anything with MATCH functions.
1124   */
1125   if( isMatchOfColumn(pExpr, &eOp2) ){
1126     int idxNew;
1127     Expr *pRight, *pLeft;
1128     WhereTerm *pNewTerm;
1129     Bitmask prereqColumn, prereqExpr;
1130 
1131     pRight = pExpr->x.pList->a[0].pExpr;
1132     pLeft = pExpr->x.pList->a[1].pExpr;
1133     prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1134     prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1135     if( (prereqExpr & prereqColumn)==0 ){
1136       Expr *pNewExpr;
1137       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1138                               0, sqlite3ExprDup(db, pRight, 0), 0);
1139       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1140       testcase( idxNew==0 );
1141       pNewTerm = &pWC->a[idxNew];
1142       pNewTerm->prereqRight = prereqExpr;
1143       pNewTerm->leftCursor = pLeft->iTable;
1144       pNewTerm->u.leftColumn = pLeft->iColumn;
1145       pNewTerm->eOperator = WO_MATCH;
1146       pNewTerm->eMatchOp = eOp2;
1147       markTermAsChild(pWC, idxNew, idxTerm);
1148       pTerm = &pWC->a[idxTerm];
1149       pTerm->wtFlags |= TERM_COPIED;
1150       pNewTerm->prereqAll = pTerm->prereqAll;
1151     }
1152   }
1153 #endif /* SQLITE_OMIT_VIRTUALTABLE */
1154 
1155 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1156   /* When sqlite_stat3 histogram data is available an operator of the
1157   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1158   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
1159   ** virtual term of that form.
1160   **
1161   ** Note that the virtual term must be tagged with TERM_VNULL.
1162   */
1163   if( pExpr->op==TK_NOTNULL
1164    && pExpr->pLeft->op==TK_COLUMN
1165    && pExpr->pLeft->iColumn>=0
1166    && OptimizationEnabled(db, SQLITE_Stat34)
1167   ){
1168     Expr *pNewExpr;
1169     Expr *pLeft = pExpr->pLeft;
1170     int idxNew;
1171     WhereTerm *pNewTerm;
1172 
1173     pNewExpr = sqlite3PExpr(pParse, TK_GT,
1174                             sqlite3ExprDup(db, pLeft, 0),
1175                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1176 
1177     idxNew = whereClauseInsert(pWC, pNewExpr,
1178                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1179     if( idxNew ){
1180       pNewTerm = &pWC->a[idxNew];
1181       pNewTerm->prereqRight = 0;
1182       pNewTerm->leftCursor = pLeft->iTable;
1183       pNewTerm->u.leftColumn = pLeft->iColumn;
1184       pNewTerm->eOperator = WO_GT;
1185       markTermAsChild(pWC, idxNew, idxTerm);
1186       pTerm = &pWC->a[idxTerm];
1187       pTerm->wtFlags |= TERM_COPIED;
1188       pNewTerm->prereqAll = pTerm->prereqAll;
1189     }
1190   }
1191 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1192 
1193   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1194   ** an index for tables to the left of the join.
1195   */
1196   pTerm->prereqRight |= extraRight;
1197 }
1198 
1199 /***************************************************************************
1200 ** Routines with file scope above.  Interface to the rest of the where.c
1201 ** subsystem follows.
1202 ***************************************************************************/
1203 
1204 /*
1205 ** This routine identifies subexpressions in the WHERE clause where
1206 ** each subexpression is separated by the AND operator or some other
1207 ** operator specified in the op parameter.  The WhereClause structure
1208 ** is filled with pointers to subexpressions.  For example:
1209 **
1210 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1211 **           \________/     \_______________/     \________________/
1212 **            slot[0]            slot[1]               slot[2]
1213 **
1214 ** The original WHERE clause in pExpr is unaltered.  All this routine
1215 ** does is make slot[] entries point to substructure within pExpr.
1216 **
1217 ** In the previous sentence and in the diagram, "slot[]" refers to
1218 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
1219 ** all terms of the WHERE clause.
1220 */
1221 void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1222   Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1223   pWC->op = op;
1224   if( pE2==0 ) return;
1225   if( pE2->op!=op ){
1226     whereClauseInsert(pWC, pExpr, 0);
1227   }else{
1228     sqlite3WhereSplit(pWC, pE2->pLeft, op);
1229     sqlite3WhereSplit(pWC, pE2->pRight, op);
1230   }
1231 }
1232 
1233 /*
1234 ** Initialize a preallocated WhereClause structure.
1235 */
1236 void sqlite3WhereClauseInit(
1237   WhereClause *pWC,        /* The WhereClause to be initialized */
1238   WhereInfo *pWInfo        /* The WHERE processing context */
1239 ){
1240   pWC->pWInfo = pWInfo;
1241   pWC->pOuter = 0;
1242   pWC->nTerm = 0;
1243   pWC->nSlot = ArraySize(pWC->aStatic);
1244   pWC->a = pWC->aStatic;
1245 }
1246 
1247 /*
1248 ** Deallocate a WhereClause structure.  The WhereClause structure
1249 ** itself is not freed.  This routine is the inverse of
1250 ** sqlite3WhereClauseInit().
1251 */
1252 void sqlite3WhereClauseClear(WhereClause *pWC){
1253   int i;
1254   WhereTerm *a;
1255   sqlite3 *db = pWC->pWInfo->pParse->db;
1256   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1257     if( a->wtFlags & TERM_DYNAMIC ){
1258       sqlite3ExprDelete(db, a->pExpr);
1259     }
1260     if( a->wtFlags & TERM_ORINFO ){
1261       whereOrInfoDelete(db, a->u.pOrInfo);
1262     }else if( a->wtFlags & TERM_ANDINFO ){
1263       whereAndInfoDelete(db, a->u.pAndInfo);
1264     }
1265   }
1266   if( pWC->a!=pWC->aStatic ){
1267     sqlite3DbFree(db, pWC->a);
1268   }
1269 }
1270 
1271 
1272 /*
1273 ** These routines walk (recursively) an expression tree and generate
1274 ** a bitmask indicating which tables are used in that expression
1275 ** tree.
1276 */
1277 Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
1278   Bitmask mask = 0;
1279   if( p==0 ) return 0;
1280   if( p->op==TK_COLUMN ){
1281     mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
1282     return mask;
1283   }
1284   mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
1285   mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
1286   if( ExprHasProperty(p, EP_xIsSelect) ){
1287     mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
1288   }else{
1289     mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1290   }
1291   return mask;
1292 }
1293 Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1294   int i;
1295   Bitmask mask = 0;
1296   if( pList ){
1297     for(i=0; i<pList->nExpr; i++){
1298       mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1299     }
1300   }
1301   return mask;
1302 }
1303 
1304 
1305 /*
1306 ** Call exprAnalyze on all terms in a WHERE clause.
1307 **
1308 ** Note that exprAnalyze() might add new virtual terms onto the
1309 ** end of the WHERE clause.  We do not want to analyze these new
1310 ** virtual terms, so start analyzing at the end and work forward
1311 ** so that the added virtual terms are never processed.
1312 */
1313 void sqlite3WhereExprAnalyze(
1314   SrcList *pTabList,       /* the FROM clause */
1315   WhereClause *pWC         /* the WHERE clause to be analyzed */
1316 ){
1317   int i;
1318   for(i=pWC->nTerm-1; i>=0; i--){
1319     exprAnalyze(pTabList, pWC, i);
1320   }
1321 }
1322 
1323 /*
1324 ** For table-valued-functions, transform the function arguments into
1325 ** new WHERE clause terms.
1326 **
1327 ** Each function argument translates into an equality constraint against
1328 ** a HIDDEN column in the table.
1329 */
1330 void sqlite3WhereTabFuncArgs(
1331   Parse *pParse,                    /* Parsing context */
1332   struct SrcList_item *pItem,       /* The FROM clause term to process */
1333   WhereClause *pWC                  /* Xfer function arguments to here */
1334 ){
1335   Table *pTab;
1336   int j, k;
1337   ExprList *pArgs;
1338   Expr *pColRef;
1339   Expr *pTerm;
1340   if( pItem->fg.isTabFunc==0 ) return;
1341   pTab = pItem->pTab;
1342   assert( pTab!=0 );
1343   pArgs = pItem->u1.pFuncArg;
1344   if( pArgs==0 ) return;
1345   for(j=k=0; j<pArgs->nExpr; j++){
1346     while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
1347     if( k>=pTab->nCol ){
1348       sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
1349                       pTab->zName, j);
1350       return;
1351     }
1352     pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
1353     if( pColRef==0 ) return;
1354     pColRef->iTable = pItem->iCursor;
1355     pColRef->iColumn = k++;
1356     pColRef->pTab = pTab;
1357     pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
1358                          sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
1359     whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1360   }
1361 }
1362