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