blob: a0f7c822aff0ec8a3b0cbacac18e86b3cc1528e3 [file] [log] [blame]
drh6c1f4ef2015-06-08 14:23:15 +00001/*
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 */
23static void exprAnalyze(SrcList*, WhereClause*, int);
24
25/*
26** Deallocate all memory associated with a WhereOrInfo object.
27*/
28static 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*/
36static 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*/
60static 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*/
100static 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*/
120static 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*/
151static 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*/
189static 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*/
284static 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*/
310static 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*/
320static 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*/
331static 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*/
361static 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*/
487static 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*/
747static 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*/
777static 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** The input to this routine is an WhereTerm structure with only the
800** "pExpr" field filled in. The job of this routine is to analyze the
801** subexpression and populate all the other fields of the WhereTerm
802** structure.
803**
804** If the expression is of the form "<expr> <op> X" it gets commuted
805** to the standard form of "X <op> <expr>".
806**
807** If the expression is of the form "X <op> Y" where both X and Y are
808** columns, then the original expression is unchanged and a new virtual
809** term of the form "Y <op> X" is added to the WHERE clause and
810** analyzed separately. The original term is marked with TERM_COPIED
811** and the new term is marked with TERM_DYNAMIC (because it's pExpr
812** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
813** is a commuted copy of a prior term.) The original term has nChild=1
814** and the copy has idxParent set to the index of the original term.
815*/
816static void exprAnalyze(
817 SrcList *pSrc, /* the FROM clause */
818 WhereClause *pWC, /* the WHERE clause */
819 int idxTerm /* Index of the term to be analyzed */
820){
821 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
822 WhereTerm *pTerm; /* The term to be analyzed */
823 WhereMaskSet *pMaskSet; /* Set of table index masks */
824 Expr *pExpr; /* The expression to be analyzed */
825 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
826 Bitmask prereqAll; /* Prerequesites of pExpr */
827 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
828 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
829 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
830 int noCase = 0; /* uppercase equivalent to lowercase */
831 int op; /* Top-level operator. pExpr->op */
832 Parse *pParse = pWInfo->pParse; /* Parsing context */
833 sqlite3 *db = pParse->db; /* Database connection */
834
835 if( db->mallocFailed ){
836 return;
837 }
838 pTerm = &pWC->a[idxTerm];
839 pMaskSet = &pWInfo->sMaskSet;
840 pExpr = pTerm->pExpr;
841 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
842 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
843 op = pExpr->op;
844 if( op==TK_IN ){
845 assert( pExpr->pRight==0 );
846 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
847 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
848 }else{
849 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
850 }
851 }else if( op==TK_ISNULL ){
852 pTerm->prereqRight = 0;
853 }else{
854 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
855 }
856 prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
857 if( ExprHasProperty(pExpr, EP_FromJoin) ){
858 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
859 prereqAll |= x;
860 extraRight = x-1; /* ON clause terms may not be used with an index
861 ** on left table of a LEFT JOIN. Ticket #3015 */
862 }
863 pTerm->prereqAll = prereqAll;
864 pTerm->leftCursor = -1;
865 pTerm->iParent = -1;
866 pTerm->eOperator = 0;
867 if( allowedOp(op) ){
868 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
869 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
870 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
871 if( pLeft->op==TK_COLUMN ){
872 pTerm->leftCursor = pLeft->iTable;
873 pTerm->u.leftColumn = pLeft->iColumn;
874 pTerm->eOperator = operatorMask(op) & opMask;
875 }
876 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
877 if( pRight && pRight->op==TK_COLUMN ){
878 WhereTerm *pNew;
879 Expr *pDup;
880 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
881 if( pTerm->leftCursor>=0 ){
882 int idxNew;
883 pDup = sqlite3ExprDup(db, pExpr, 0);
884 if( db->mallocFailed ){
885 sqlite3ExprDelete(db, pDup);
886 return;
887 }
888 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
889 if( idxNew==0 ) return;
890 pNew = &pWC->a[idxNew];
891 markTermAsChild(pWC, idxNew, idxTerm);
892 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
893 pTerm = &pWC->a[idxTerm];
894 pTerm->wtFlags |= TERM_COPIED;
895
896 if( termIsEquivalence(pParse, pDup) ){
897 pTerm->eOperator |= WO_EQUIV;
898 eExtraOp = WO_EQUIV;
899 }
900 }else{
901 pDup = pExpr;
902 pNew = pTerm;
903 }
904 exprCommute(pParse, pDup);
905 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
906 pNew->leftCursor = pLeft->iTable;
907 pNew->u.leftColumn = pLeft->iColumn;
908 testcase( (prereqLeft | extraRight) != prereqLeft );
909 pNew->prereqRight = prereqLeft | extraRight;
910 pNew->prereqAll = prereqAll;
911 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
912 }
913 }
914
915#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
916 /* If a term is the BETWEEN operator, create two new virtual terms
917 ** that define the range that the BETWEEN implements. For example:
918 **
919 ** a BETWEEN b AND c
920 **
921 ** is converted into:
922 **
923 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
924 **
925 ** The two new terms are added onto the end of the WhereClause object.
926 ** The new terms are "dynamic" and are children of the original BETWEEN
927 ** term. That means that if the BETWEEN term is coded, the children are
928 ** skipped. Or, if the children are satisfied by an index, the original
929 ** BETWEEN term is skipped.
930 */
931 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
932 ExprList *pList = pExpr->x.pList;
933 int i;
934 static const u8 ops[] = {TK_GE, TK_LE};
935 assert( pList!=0 );
936 assert( pList->nExpr==2 );
937 for(i=0; i<2; i++){
938 Expr *pNewExpr;
939 int idxNew;
940 pNewExpr = sqlite3PExpr(pParse, ops[i],
941 sqlite3ExprDup(db, pExpr->pLeft, 0),
942 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
943 transferJoinMarkings(pNewExpr, pExpr);
944 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
945 testcase( idxNew==0 );
946 exprAnalyze(pSrc, pWC, idxNew);
947 pTerm = &pWC->a[idxTerm];
948 markTermAsChild(pWC, idxNew, idxTerm);
949 }
950 }
951#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
952
953#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
954 /* Analyze a term that is composed of two or more subterms connected by
955 ** an OR operator.
956 */
957 else if( pExpr->op==TK_OR ){
958 assert( pWC->op==TK_AND );
959 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
960 pTerm = &pWC->a[idxTerm];
961 }
962#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
963
964#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
965 /* Add constraints to reduce the search space on a LIKE or GLOB
966 ** operator.
967 **
968 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
969 **
970 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
971 **
972 ** The last character of the prefix "abc" is incremented to form the
973 ** termination condition "abd". If case is not significant (the default
974 ** for LIKE) then the lower-bound is made all uppercase and the upper-
975 ** bound is made all lowercase so that the bounds also work when comparing
976 ** BLOBs.
977 */
978 if( pWC->op==TK_AND
979 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
980 ){
981 Expr *pLeft; /* LHS of LIKE/GLOB operator */
982 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
983 Expr *pNewExpr1;
984 Expr *pNewExpr2;
985 int idxNew1;
986 int idxNew2;
987 const char *zCollSeqName; /* Name of collating sequence */
988 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
989
990 pLeft = pExpr->x.pList->a[1].pExpr;
991 pStr2 = sqlite3ExprDup(db, pStr1, 0);
992
993 /* Convert the lower bound to upper-case and the upper bound to
994 ** lower-case (upper-case is less than lower-case in ASCII) so that
995 ** the range constraints also work for BLOBs
996 */
997 if( noCase && !pParse->db->mallocFailed ){
998 int i;
999 char c;
1000 pTerm->wtFlags |= TERM_LIKE;
1001 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1002 pStr1->u.zToken[i] = sqlite3Toupper(c);
1003 pStr2->u.zToken[i] = sqlite3Tolower(c);
1004 }
1005 }
1006
1007 if( !db->mallocFailed ){
1008 u8 c, *pC; /* Last character before the first wildcard */
1009 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1010 c = *pC;
1011 if( noCase ){
1012 /* The point is to increment the last character before the first
1013 ** wildcard. But if we increment '@', that will push it into the
1014 ** alphabetic range where case conversions will mess up the
1015 ** inequality. To avoid this, make sure to also run the full
1016 ** LIKE on all candidate expressions by clearing the isComplete flag
1017 */
1018 if( c=='A'-1 ) isComplete = 0;
1019 c = sqlite3UpperToLower[c];
1020 }
1021 *pC = c + 1;
1022 }
1023 zCollSeqName = noCase ? "NOCASE" : "BINARY";
1024 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1025 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1026 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
1027 pStr1, 0);
1028 transferJoinMarkings(pNewExpr1, pExpr);
1029 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1030 testcase( idxNew1==0 );
1031 exprAnalyze(pSrc, pWC, idxNew1);
1032 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1033 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1034 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
1035 pStr2, 0);
1036 transferJoinMarkings(pNewExpr2, pExpr);
1037 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1038 testcase( idxNew2==0 );
1039 exprAnalyze(pSrc, pWC, idxNew2);
1040 pTerm = &pWC->a[idxTerm];
1041 if( isComplete ){
1042 markTermAsChild(pWC, idxNew1, idxTerm);
1043 markTermAsChild(pWC, idxNew2, idxTerm);
1044 }
1045 }
1046#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1047
1048#ifndef SQLITE_OMIT_VIRTUALTABLE
1049 /* Add a WO_MATCH auxiliary term to the constraint set if the
1050 ** current expression is of the form: column MATCH expr.
1051 ** This information is used by the xBestIndex methods of
1052 ** virtual tables. The native query optimizer does not attempt
1053 ** to do anything with MATCH functions.
1054 */
1055 if( isMatchOfColumn(pExpr) ){
1056 int idxNew;
1057 Expr *pRight, *pLeft;
1058 WhereTerm *pNewTerm;
1059 Bitmask prereqColumn, prereqExpr;
1060
1061 pRight = pExpr->x.pList->a[0].pExpr;
1062 pLeft = pExpr->x.pList->a[1].pExpr;
1063 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1064 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1065 if( (prereqExpr & prereqColumn)==0 ){
1066 Expr *pNewExpr;
1067 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1068 0, sqlite3ExprDup(db, pRight, 0), 0);
1069 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1070 testcase( idxNew==0 );
1071 pNewTerm = &pWC->a[idxNew];
1072 pNewTerm->prereqRight = prereqExpr;
1073 pNewTerm->leftCursor = pLeft->iTable;
1074 pNewTerm->u.leftColumn = pLeft->iColumn;
1075 pNewTerm->eOperator = WO_MATCH;
1076 markTermAsChild(pWC, idxNew, idxTerm);
1077 pTerm = &pWC->a[idxTerm];
1078 pTerm->wtFlags |= TERM_COPIED;
1079 pNewTerm->prereqAll = pTerm->prereqAll;
1080 }
1081 }
1082#endif /* SQLITE_OMIT_VIRTUALTABLE */
1083
1084#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1085 /* When sqlite_stat3 histogram data is available an operator of the
1086 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1087 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1088 ** virtual term of that form.
1089 **
1090 ** Note that the virtual term must be tagged with TERM_VNULL.
1091 */
1092 if( pExpr->op==TK_NOTNULL
1093 && pExpr->pLeft->op==TK_COLUMN
1094 && pExpr->pLeft->iColumn>=0
1095 && OptimizationEnabled(db, SQLITE_Stat34)
1096 ){
1097 Expr *pNewExpr;
1098 Expr *pLeft = pExpr->pLeft;
1099 int idxNew;
1100 WhereTerm *pNewTerm;
1101
1102 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1103 sqlite3ExprDup(db, pLeft, 0),
1104 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1105
1106 idxNew = whereClauseInsert(pWC, pNewExpr,
1107 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1108 if( idxNew ){
1109 pNewTerm = &pWC->a[idxNew];
1110 pNewTerm->prereqRight = 0;
1111 pNewTerm->leftCursor = pLeft->iTable;
1112 pNewTerm->u.leftColumn = pLeft->iColumn;
1113 pNewTerm->eOperator = WO_GT;
1114 markTermAsChild(pWC, idxNew, idxTerm);
1115 pTerm = &pWC->a[idxTerm];
1116 pTerm->wtFlags |= TERM_COPIED;
1117 pNewTerm->prereqAll = pTerm->prereqAll;
1118 }
1119 }
1120#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1121
1122 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1123 ** an index for tables to the left of the join.
1124 */
1125 pTerm->prereqRight |= extraRight;
1126}
1127
1128/***************************************************************************
1129** Routines with file scope above. Interface to the rest of the where.c
1130** subsystem follows.
1131***************************************************************************/
1132
1133/*
1134** This routine identifies subexpressions in the WHERE clause where
1135** each subexpression is separated by the AND operator or some other
1136** operator specified in the op parameter. The WhereClause structure
1137** is filled with pointers to subexpressions. For example:
1138**
1139** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1140** \________/ \_______________/ \________________/
1141** slot[0] slot[1] slot[2]
1142**
1143** The original WHERE clause in pExpr is unaltered. All this routine
1144** does is make slot[] entries point to substructure within pExpr.
1145**
1146** In the previous sentence and in the diagram, "slot[]" refers to
1147** the WhereClause.a[] array. The slot[] array grows as needed to contain
1148** all terms of the WHERE clause.
1149*/
1150void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1151 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1152 pWC->op = op;
1153 if( pE2==0 ) return;
1154 if( pE2->op!=op ){
1155 whereClauseInsert(pWC, pExpr, 0);
1156 }else{
1157 sqlite3WhereSplit(pWC, pE2->pLeft, op);
1158 sqlite3WhereSplit(pWC, pE2->pRight, op);
1159 }
1160}
1161
1162/*
1163** Initialize a preallocated WhereClause structure.
1164*/
1165void sqlite3WhereClauseInit(
1166 WhereClause *pWC, /* The WhereClause to be initialized */
1167 WhereInfo *pWInfo /* The WHERE processing context */
1168){
1169 pWC->pWInfo = pWInfo;
1170 pWC->pOuter = 0;
1171 pWC->nTerm = 0;
1172 pWC->nSlot = ArraySize(pWC->aStatic);
1173 pWC->a = pWC->aStatic;
1174}
1175
1176/*
1177** Deallocate a WhereClause structure. The WhereClause structure
1178** itself is not freed. This routine is the inverse of sqlite3WhereClauseInit().
1179*/
1180void sqlite3WhereClauseClear(WhereClause *pWC){
1181 int i;
1182 WhereTerm *a;
1183 sqlite3 *db = pWC->pWInfo->pParse->db;
1184 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1185 if( a->wtFlags & TERM_DYNAMIC ){
1186 sqlite3ExprDelete(db, a->pExpr);
1187 }
1188 if( a->wtFlags & TERM_ORINFO ){
1189 whereOrInfoDelete(db, a->u.pOrInfo);
1190 }else if( a->wtFlags & TERM_ANDINFO ){
1191 whereAndInfoDelete(db, a->u.pAndInfo);
1192 }
1193 }
1194 if( pWC->a!=pWC->aStatic ){
1195 sqlite3DbFree(db, pWC->a);
1196 }
1197}
1198
1199
1200/*
1201** These routines walk (recursively) an expression tree and generate
1202** a bitmask indicating which tables are used in that expression
1203** tree.
1204*/
1205Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
1206 Bitmask mask = 0;
1207 if( p==0 ) return 0;
1208 if( p->op==TK_COLUMN ){
1209 mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
1210 return mask;
1211 }
1212 mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
1213 mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
1214 if( ExprHasProperty(p, EP_xIsSelect) ){
1215 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
1216 }else{
1217 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1218 }
1219 return mask;
1220}
1221Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1222 int i;
1223 Bitmask mask = 0;
1224 if( pList ){
1225 for(i=0; i<pList->nExpr; i++){
1226 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1227 }
1228 }
1229 return mask;
1230}
1231
1232
1233/*
1234** Call exprAnalyze on all terms in a WHERE clause.
1235**
1236** Note that exprAnalyze() might add new virtual terms onto the
1237** end of the WHERE clause. We do not want to analyze these new
1238** virtual terms, so start analyzing at the end and work forward
1239** so that the added virtual terms are never processed.
1240*/
1241void sqlite3WhereExprAnalyze(
1242 SrcList *pTabList, /* the FROM clause */
1243 WhereClause *pWC /* the WHERE clause to be analyzed */
1244){
1245 int i;
1246 for(i=pWC->nTerm-1; i>=0; i--){
1247 exprAnalyze(pTabList, pWC, i);
1248 }
1249}
drh01d230c2015-08-19 17:11:37 +00001250
1251/*
1252** For table-valued-functions, transform the function arguments into
1253** new WHERE clause terms.
1254**
1255** Each function argument translates into an equality constraint against
1256** a HIDDEN column in the table.
1257*/
1258void sqlite3WhereTabFuncArgs(
1259 Parse *pParse, /* Parsing context */
1260 struct SrcList_item *pItem, /* The FROM clause term to process */
1261 WhereClause *pWC /* Xfer function arguments to here */
1262){
1263 Table *pTab;
1264 int j, k;
1265 ExprList *pArgs;
1266 Expr *pColRef;
1267 Expr *pTerm;
1268 if( pItem->fg.isTabFunc==0 ) return;
1269 pTab = pItem->pTab;
1270 assert( pTab!=0 );
1271 pArgs = pItem->u1.pFuncArg;
1272 assert( pArgs!=0 );
1273 for(j=k=0; j<pArgs->nExpr; j++){
1274 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){ k++; }
1275 if( k>=pTab->nCol ){
1276 sqlite3ErrorMsg(pParse, "too many arguments on %s - max %d",
1277 pTab->zName, j);
1278 return;
1279 }
1280 pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
1281 if( pColRef==0 ) return;
1282 pColRef->iTable = pItem->iCursor;
1283 pColRef->iColumn = k++;
1284 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
1285 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
1286 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1287 }
1288}