blob: e1059f73b4d49d5c39f02aacb37631384be73f20 [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
dan71c57db2016-07-09 20:23:55 +000098** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
drh6c1f4ef2015-06-08 14:23:15 +000099*/
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){
drhe104dd32016-08-10 19:43:29 +0000293 static const struct Op2 {
dan07bdba82015-11-23 21:09:54 +0000294 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;
drh81fd3492016-02-19 14:10:44 +0000536 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000537 sqlite3WhereClauseInit(pOrWc, pWInfo);
538 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
539 sqlite3WhereExprAnalyze(pSrc, pOrWc);
540 if( db->mallocFailed ) return;
541 assert( pOrWc->nTerm>=2 );
542
543 /*
544 ** Compute the set of tables that might satisfy cases 1 or 3.
545 */
546 indexable = ~(Bitmask)0;
547 chngToIN = ~(Bitmask)0;
548 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
549 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
550 WhereAndInfo *pAndInfo;
551 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
552 chngToIN = 0;
drh575fad62016-02-05 13:38:36 +0000553 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
drh6c1f4ef2015-06-08 14:23:15 +0000554 if( pAndInfo ){
555 WhereClause *pAndWC;
556 WhereTerm *pAndTerm;
557 int j;
558 Bitmask b = 0;
559 pOrTerm->u.pAndInfo = pAndInfo;
560 pOrTerm->wtFlags |= TERM_ANDINFO;
561 pOrTerm->eOperator = WO_AND;
562 pAndWC = &pAndInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000563 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000564 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
565 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
566 sqlite3WhereExprAnalyze(pSrc, pAndWC);
567 pAndWC->pOuter = pWC;
drh6c1f4ef2015-06-08 14:23:15 +0000568 if( !db->mallocFailed ){
569 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
570 assert( pAndTerm->pExpr );
dandbd2dcb2016-05-28 18:53:55 +0000571 if( allowedOp(pAndTerm->pExpr->op)
572 || pAndTerm->eOperator==WO_MATCH
573 ){
drh6c1f4ef2015-06-08 14:23:15 +0000574 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
575 }
576 }
577 }
578 indexable &= b;
579 }
580 }else if( pOrTerm->wtFlags & TERM_COPIED ){
581 /* Skip this term for now. We revisit it when we process the
582 ** corresponding TERM_VIRTUAL term */
583 }else{
584 Bitmask b;
585 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
586 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
587 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
588 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
589 }
590 indexable &= b;
591 if( (pOrTerm->eOperator & WO_EQ)==0 ){
592 chngToIN = 0;
593 }else{
594 chngToIN &= b;
595 }
596 }
597 }
598
599 /*
600 ** Record the set of tables that satisfy case 3. The set might be
601 ** empty.
602 */
603 pOrInfo->indexable = indexable;
604 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
605
606 /* For a two-way OR, attempt to implementation case 2.
607 */
608 if( indexable && pOrWc->nTerm==2 ){
609 int iOne = 0;
610 WhereTerm *pOne;
611 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
612 int iTwo = 0;
613 WhereTerm *pTwo;
614 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
615 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
616 }
617 }
618 }
619
620 /*
621 ** chngToIN holds a set of tables that *might* satisfy case 1. But
622 ** we have to do some additional checking to see if case 1 really
623 ** is satisfied.
624 **
625 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
626 ** that there is no possibility of transforming the OR clause into an
627 ** IN operator because one or more terms in the OR clause contain
628 ** something other than == on a column in the single table. The 1-bit
629 ** case means that every term of the OR clause is of the form
630 ** "table.column=expr" for some single table. The one bit that is set
631 ** will correspond to the common table. We still need to check to make
632 ** sure the same column is used on all terms. The 2-bit case is when
633 ** the all terms are of the form "table1.column=table2.column". It
634 ** might be possible to form an IN operator with either table1.column
635 ** or table2.column as the LHS if either is common to every term of
636 ** the OR clause.
637 **
638 ** Note that terms of the form "table.column1=table.column2" (the
639 ** same table on both sizes of the ==) cannot be optimized.
640 */
641 if( chngToIN ){
642 int okToChngToIN = 0; /* True if the conversion to IN is valid */
643 int iColumn = -1; /* Column index on lhs of IN operator */
644 int iCursor = -1; /* Table cursor common to all terms */
645 int j = 0; /* Loop counter */
646
647 /* Search for a table and column that appears on one side or the
648 ** other of the == operator in every subterm. That table and column
649 ** will be recorded in iCursor and iColumn. There might not be any
650 ** such table and column. Set okToChngToIN if an appropriate table
651 ** and column is found but leave okToChngToIN false if not found.
652 */
653 for(j=0; j<2 && !okToChngToIN; j++){
654 pOrTerm = pOrWc->a;
655 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
656 assert( pOrTerm->eOperator & WO_EQ );
657 pOrTerm->wtFlags &= ~TERM_OR_OK;
658 if( pOrTerm->leftCursor==iCursor ){
659 /* This is the 2-bit case and we are on the second iteration and
660 ** current term is from the first iteration. So skip this term. */
661 assert( j==1 );
662 continue;
663 }
664 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
665 pOrTerm->leftCursor))==0 ){
666 /* This term must be of the form t1.a==t2.b where t2 is in the
667 ** chngToIN set but t1 is not. This term will be either preceded
668 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
669 ** and use its inversion. */
670 testcase( pOrTerm->wtFlags & TERM_COPIED );
671 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
672 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
673 continue;
674 }
675 iColumn = pOrTerm->u.leftColumn;
676 iCursor = pOrTerm->leftCursor;
677 break;
678 }
679 if( i<0 ){
680 /* No candidate table+column was found. This can only occur
681 ** on the second iteration */
682 assert( j==1 );
683 assert( IsPowerOfTwo(chngToIN) );
684 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
685 break;
686 }
687 testcase( j==1 );
688
689 /* We have found a candidate table and column. Check to see if that
690 ** table and column is common to every term in the OR clause */
691 okToChngToIN = 1;
692 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
693 assert( pOrTerm->eOperator & WO_EQ );
694 if( pOrTerm->leftCursor!=iCursor ){
695 pOrTerm->wtFlags &= ~TERM_OR_OK;
696 }else if( pOrTerm->u.leftColumn!=iColumn ){
697 okToChngToIN = 0;
698 }else{
699 int affLeft, affRight;
700 /* If the right-hand side is also a column, then the affinities
701 ** of both right and left sides must be such that no type
702 ** conversions are required on the right. (Ticket #2249)
703 */
704 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
705 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
706 if( affRight!=0 && affRight!=affLeft ){
707 okToChngToIN = 0;
708 }else{
709 pOrTerm->wtFlags |= TERM_OR_OK;
710 }
711 }
712 }
713 }
714
715 /* At this point, okToChngToIN is true if original pTerm satisfies
716 ** case 1. In that case, construct a new virtual term that is
717 ** pTerm converted into an IN operator.
718 */
719 if( okToChngToIN ){
720 Expr *pDup; /* A transient duplicate expression */
721 ExprList *pList = 0; /* The RHS of the IN operator */
722 Expr *pLeft = 0; /* The LHS of the IN operator */
723 Expr *pNew; /* The complete IN operator */
724
725 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
726 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
727 assert( pOrTerm->eOperator & WO_EQ );
728 assert( pOrTerm->leftCursor==iCursor );
729 assert( pOrTerm->u.leftColumn==iColumn );
730 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
731 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
732 pLeft = pOrTerm->pExpr->pLeft;
733 }
734 assert( pLeft!=0 );
735 pDup = sqlite3ExprDup(db, pLeft, 0);
736 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
737 if( pNew ){
738 int idxNew;
739 transferJoinMarkings(pNew, pExpr);
740 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
741 pNew->x.pList = pList;
742 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
743 testcase( idxNew==0 );
744 exprAnalyze(pSrc, pWC, idxNew);
745 pTerm = &pWC->a[idxTerm];
746 markTermAsChild(pWC, idxNew, idxTerm);
747 }else{
748 sqlite3ExprListDelete(db, pList);
749 }
750 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
751 }
752 }
753}
754#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
755
756/*
757** We already know that pExpr is a binary operator where both operands are
758** column references. This routine checks to see if pExpr is an equivalence
759** relation:
760** 1. The SQLITE_Transitive optimization must be enabled
761** 2. Must be either an == or an IS operator
762** 3. Not originating in the ON clause of an OUTER JOIN
763** 4. The affinities of A and B must be compatible
764** 5a. Both operands use the same collating sequence OR
765** 5b. The overall collating sequence is BINARY
766** If this routine returns TRUE, that means that the RHS can be substituted
767** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
768** This is an optimization. No harm comes from returning 0. But if 1 is
769** returned when it should not be, then incorrect answers might result.
770*/
771static int termIsEquivalence(Parse *pParse, Expr *pExpr){
772 char aff1, aff2;
773 CollSeq *pColl;
774 const char *zColl1, *zColl2;
775 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
776 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
777 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
778 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
779 aff2 = sqlite3ExprAffinity(pExpr->pRight);
780 if( aff1!=aff2
781 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
782 ){
783 return 0;
784 }
785 pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
786 if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
787 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
drha2fbe3b2016-06-28 22:27:56 +0000788 zColl1 = pColl ? pColl->zName : 0;
drh6c1f4ef2015-06-08 14:23:15 +0000789 pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
drha2fbe3b2016-06-28 22:27:56 +0000790 zColl2 = pColl ? pColl->zName : 0;
791 return sqlite3_stricmp(zColl1, zColl2)==0;
drh6c1f4ef2015-06-08 14:23:15 +0000792}
793
794/*
795** Recursively walk the expressions of a SELECT statement and generate
796** a bitmask indicating which tables are used in that expression
797** tree.
798*/
799static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
800 Bitmask mask = 0;
801 while( pS ){
802 SrcList *pSrc = pS->pSrc;
803 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
804 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
805 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
806 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
807 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
808 if( ALWAYS(pSrc!=0) ){
809 int i;
810 for(i=0; i<pSrc->nSrc; i++){
811 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
812 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
813 }
814 }
815 pS = pS->pPrior;
816 }
817 return mask;
818}
819
820/*
drh47991422015-08-31 15:58:06 +0000821** Expression pExpr is one operand of a comparison operator that might
822** be useful for indexing. This routine checks to see if pExpr appears
823** in any index. Return TRUE (1) if pExpr is an indexed term and return
824** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor
825** number of the table that is indexed and *piColumn to the column number
drh8d25cb92016-08-19 19:58:06 +0000826** of the column that is indexed, or XN_EXPR (-2) if an expression is being
827** indexed.
drh47991422015-08-31 15:58:06 +0000828**
829** If pExpr is a TK_COLUMN column reference, then this routine always returns
830** true even if that particular column is not indexed, because the column
831** might be added to an automatic index later.
832*/
833static int exprMightBeIndexed(
834 SrcList *pFrom, /* The FROM clause */
dan95a08c02016-08-02 16:18:35 +0000835 int op, /* The specific comparison operator */
drh47991422015-08-31 15:58:06 +0000836 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
837 Expr *pExpr, /* An operand of a comparison operator */
838 int *piCur, /* Write the referenced table cursor number here */
839 int *piColumn /* Write the referenced table column number here */
840){
841 Index *pIdx;
842 int i;
843 int iCur;
dan71c57db2016-07-09 20:23:55 +0000844
845 /* If this expression is a vector to the left or right of a
846 ** inequality constraint (>, <, >= or <=), perform the processing
847 ** on the first element of the vector. */
848 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
drh64bcb8c2016-08-26 03:42:57 +0000849 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
850 assert( op<=TK_GE );
851 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
dan71c57db2016-07-09 20:23:55 +0000852 pExpr = pExpr->x.pList->a[0].pExpr;
853 }
854
drh47991422015-08-31 15:58:06 +0000855 if( pExpr->op==TK_COLUMN ){
856 *piCur = pExpr->iTable;
857 *piColumn = pExpr->iColumn;
858 return 1;
859 }
860 if( mPrereq==0 ) return 0; /* No table references */
861 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
862 for(i=0; mPrereq>1; i++, mPrereq>>=1){}
863 iCur = pFrom->a[i].iCursor;
864 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
865 if( pIdx->aColExpr==0 ) continue;
866 for(i=0; i<pIdx->nKeyCol; i++){
drh8d25cb92016-08-19 19:58:06 +0000867 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
drh47991422015-08-31 15:58:06 +0000868 if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
869 *piCur = iCur;
drh8d25cb92016-08-19 19:58:06 +0000870 *piColumn = XN_EXPR;
drh47991422015-08-31 15:58:06 +0000871 return 1;
872 }
873 }
874 }
875 return 0;
876}
877
dan870a0702016-08-01 16:37:43 +0000878/*
drh6c1f4ef2015-06-08 14:23:15 +0000879** The input to this routine is an WhereTerm structure with only the
880** "pExpr" field filled in. The job of this routine is to analyze the
881** subexpression and populate all the other fields of the WhereTerm
882** structure.
883**
884** If the expression is of the form "<expr> <op> X" it gets commuted
885** to the standard form of "X <op> <expr>".
886**
887** If the expression is of the form "X <op> Y" where both X and Y are
888** columns, then the original expression is unchanged and a new virtual
889** term of the form "Y <op> X" is added to the WHERE clause and
890** analyzed separately. The original term is marked with TERM_COPIED
891** and the new term is marked with TERM_DYNAMIC (because it's pExpr
892** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
893** is a commuted copy of a prior term.) The original term has nChild=1
894** and the copy has idxParent set to the index of the original term.
895*/
896static void exprAnalyze(
897 SrcList *pSrc, /* the FROM clause */
898 WhereClause *pWC, /* the WHERE clause */
899 int idxTerm /* Index of the term to be analyzed */
900){
901 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
902 WhereTerm *pTerm; /* The term to be analyzed */
903 WhereMaskSet *pMaskSet; /* Set of table index masks */
904 Expr *pExpr; /* The expression to be analyzed */
905 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
906 Bitmask prereqAll; /* Prerequesites of pExpr */
907 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
908 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
909 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
910 int noCase = 0; /* uppercase equivalent to lowercase */
911 int op; /* Top-level operator. pExpr->op */
912 Parse *pParse = pWInfo->pParse; /* Parsing context */
913 sqlite3 *db = pParse->db; /* Database connection */
dan07bdba82015-11-23 21:09:54 +0000914 unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
drh6c1f4ef2015-06-08 14:23:15 +0000915
916 if( db->mallocFailed ){
917 return;
918 }
919 pTerm = &pWC->a[idxTerm];
920 pMaskSet = &pWInfo->sMaskSet;
921 pExpr = pTerm->pExpr;
922 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
923 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
924 op = pExpr->op;
925 if( op==TK_IN ){
926 assert( pExpr->pRight==0 );
dan7b35a772016-07-28 19:47:15 +0000927 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
drh6c1f4ef2015-06-08 14:23:15 +0000928 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
929 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
930 }else{
931 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
932 }
933 }else if( op==TK_ISNULL ){
934 pTerm->prereqRight = 0;
935 }else{
936 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
937 }
938 prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
939 if( ExprHasProperty(pExpr, EP_FromJoin) ){
940 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
941 prereqAll |= x;
942 extraRight = x-1; /* ON clause terms may not be used with an index
943 ** on left table of a LEFT JOIN. Ticket #3015 */
944 }
945 pTerm->prereqAll = prereqAll;
946 pTerm->leftCursor = -1;
947 pTerm->iParent = -1;
948 pTerm->eOperator = 0;
949 if( allowedOp(op) ){
drh47991422015-08-31 15:58:06 +0000950 int iCur, iColumn;
drh6c1f4ef2015-06-08 14:23:15 +0000951 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
952 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
953 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
dan8da209b2016-07-26 18:06:08 +0000954
dan145b4ea2016-07-29 18:12:12 +0000955 if( pTerm->iField>0 ){
956 assert( op==TK_IN );
dan8da209b2016-07-26 18:06:08 +0000957 assert( pLeft->op==TK_VECTOR );
958 pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
959 }
960
dan71c57db2016-07-09 20:23:55 +0000961 if( exprMightBeIndexed(pSrc, op, prereqLeft, pLeft, &iCur, &iColumn) ){
drh47991422015-08-31 15:58:06 +0000962 pTerm->leftCursor = iCur;
963 pTerm->u.leftColumn = iColumn;
drh6860e6f2015-08-27 18:24:02 +0000964 pTerm->eOperator = operatorMask(op) & opMask;
drh6c1f4ef2015-06-08 14:23:15 +0000965 }
966 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh47991422015-08-31 15:58:06 +0000967 if( pRight
dan71c57db2016-07-09 20:23:55 +0000968 && exprMightBeIndexed(pSrc, op, pTerm->prereqRight, pRight, &iCur,&iColumn)
drh47991422015-08-31 15:58:06 +0000969 ){
drh6c1f4ef2015-06-08 14:23:15 +0000970 WhereTerm *pNew;
971 Expr *pDup;
972 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
dan145b4ea2016-07-29 18:12:12 +0000973 assert( pTerm->iField==0 );
drh6c1f4ef2015-06-08 14:23:15 +0000974 if( pTerm->leftCursor>=0 ){
975 int idxNew;
976 pDup = sqlite3ExprDup(db, pExpr, 0);
977 if( db->mallocFailed ){
978 sqlite3ExprDelete(db, pDup);
979 return;
980 }
981 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
982 if( idxNew==0 ) return;
983 pNew = &pWC->a[idxNew];
984 markTermAsChild(pWC, idxNew, idxTerm);
985 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
986 pTerm = &pWC->a[idxTerm];
987 pTerm->wtFlags |= TERM_COPIED;
988
989 if( termIsEquivalence(pParse, pDup) ){
990 pTerm->eOperator |= WO_EQUIV;
991 eExtraOp = WO_EQUIV;
992 }
993 }else{
994 pDup = pExpr;
995 pNew = pTerm;
996 }
997 exprCommute(pParse, pDup);
drh47991422015-08-31 15:58:06 +0000998 pNew->leftCursor = iCur;
999 pNew->u.leftColumn = iColumn;
drh6c1f4ef2015-06-08 14:23:15 +00001000 testcase( (prereqLeft | extraRight) != prereqLeft );
1001 pNew->prereqRight = prereqLeft | extraRight;
1002 pNew->prereqAll = prereqAll;
1003 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1004 }
1005 }
1006
1007#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1008 /* If a term is the BETWEEN operator, create two new virtual terms
1009 ** that define the range that the BETWEEN implements. For example:
1010 **
1011 ** a BETWEEN b AND c
1012 **
1013 ** is converted into:
1014 **
1015 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1016 **
1017 ** The two new terms are added onto the end of the WhereClause object.
1018 ** The new terms are "dynamic" and are children of the original BETWEEN
1019 ** term. That means that if the BETWEEN term is coded, the children are
1020 ** skipped. Or, if the children are satisfied by an index, the original
1021 ** BETWEEN term is skipped.
1022 */
1023 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1024 ExprList *pList = pExpr->x.pList;
1025 int i;
1026 static const u8 ops[] = {TK_GE, TK_LE};
1027 assert( pList!=0 );
1028 assert( pList->nExpr==2 );
1029 for(i=0; i<2; i++){
1030 Expr *pNewExpr;
1031 int idxNew;
1032 pNewExpr = sqlite3PExpr(pParse, ops[i],
1033 sqlite3ExprDup(db, pExpr->pLeft, 0),
1034 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
1035 transferJoinMarkings(pNewExpr, pExpr);
1036 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1037 testcase( idxNew==0 );
1038 exprAnalyze(pSrc, pWC, idxNew);
1039 pTerm = &pWC->a[idxTerm];
1040 markTermAsChild(pWC, idxNew, idxTerm);
1041 }
1042 }
1043#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1044
1045#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1046 /* Analyze a term that is composed of two or more subterms connected by
1047 ** an OR operator.
1048 */
1049 else if( pExpr->op==TK_OR ){
1050 assert( pWC->op==TK_AND );
1051 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1052 pTerm = &pWC->a[idxTerm];
1053 }
1054#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1055
1056#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1057 /* Add constraints to reduce the search space on a LIKE or GLOB
1058 ** operator.
1059 **
1060 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1061 **
1062 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1063 **
1064 ** The last character of the prefix "abc" is incremented to form the
1065 ** termination condition "abd". If case is not significant (the default
1066 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1067 ** bound is made all lowercase so that the bounds also work when comparing
1068 ** BLOBs.
1069 */
1070 if( pWC->op==TK_AND
1071 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1072 ){
1073 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1074 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1075 Expr *pNewExpr1;
1076 Expr *pNewExpr2;
1077 int idxNew1;
1078 int idxNew2;
1079 const char *zCollSeqName; /* Name of collating sequence */
1080 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1081
1082 pLeft = pExpr->x.pList->a[1].pExpr;
1083 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1084
1085 /* Convert the lower bound to upper-case and the upper bound to
1086 ** lower-case (upper-case is less than lower-case in ASCII) so that
1087 ** the range constraints also work for BLOBs
1088 */
1089 if( noCase && !pParse->db->mallocFailed ){
1090 int i;
1091 char c;
1092 pTerm->wtFlags |= TERM_LIKE;
1093 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1094 pStr1->u.zToken[i] = sqlite3Toupper(c);
1095 pStr2->u.zToken[i] = sqlite3Tolower(c);
1096 }
1097 }
1098
1099 if( !db->mallocFailed ){
1100 u8 c, *pC; /* Last character before the first wildcard */
1101 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1102 c = *pC;
1103 if( noCase ){
1104 /* The point is to increment the last character before the first
1105 ** wildcard. But if we increment '@', that will push it into the
1106 ** alphabetic range where case conversions will mess up the
1107 ** inequality. To avoid this, make sure to also run the full
1108 ** LIKE on all candidate expressions by clearing the isComplete flag
1109 */
1110 if( c=='A'-1 ) isComplete = 0;
1111 c = sqlite3UpperToLower[c];
1112 }
1113 *pC = c + 1;
1114 }
1115 zCollSeqName = noCase ? "NOCASE" : "BINARY";
1116 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1117 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1118 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
1119 pStr1, 0);
1120 transferJoinMarkings(pNewExpr1, pExpr);
1121 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1122 testcase( idxNew1==0 );
1123 exprAnalyze(pSrc, pWC, idxNew1);
1124 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1125 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1126 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
1127 pStr2, 0);
1128 transferJoinMarkings(pNewExpr2, pExpr);
1129 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1130 testcase( idxNew2==0 );
1131 exprAnalyze(pSrc, pWC, idxNew2);
1132 pTerm = &pWC->a[idxTerm];
1133 if( isComplete ){
1134 markTermAsChild(pWC, idxNew1, idxTerm);
1135 markTermAsChild(pWC, idxNew2, idxTerm);
1136 }
1137 }
1138#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1139
1140#ifndef SQLITE_OMIT_VIRTUALTABLE
1141 /* Add a WO_MATCH auxiliary term to the constraint set if the
1142 ** current expression is of the form: column MATCH expr.
1143 ** This information is used by the xBestIndex methods of
1144 ** virtual tables. The native query optimizer does not attempt
1145 ** to do anything with MATCH functions.
1146 */
dandbd2dcb2016-05-28 18:53:55 +00001147 if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
drh6c1f4ef2015-06-08 14:23:15 +00001148 int idxNew;
1149 Expr *pRight, *pLeft;
1150 WhereTerm *pNewTerm;
1151 Bitmask prereqColumn, prereqExpr;
1152
1153 pRight = pExpr->x.pList->a[0].pExpr;
1154 pLeft = pExpr->x.pList->a[1].pExpr;
1155 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1156 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1157 if( (prereqExpr & prereqColumn)==0 ){
1158 Expr *pNewExpr;
1159 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1160 0, sqlite3ExprDup(db, pRight, 0), 0);
1161 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1162 testcase( idxNew==0 );
1163 pNewTerm = &pWC->a[idxNew];
1164 pNewTerm->prereqRight = prereqExpr;
1165 pNewTerm->leftCursor = pLeft->iTable;
1166 pNewTerm->u.leftColumn = pLeft->iColumn;
1167 pNewTerm->eOperator = WO_MATCH;
dan07bdba82015-11-23 21:09:54 +00001168 pNewTerm->eMatchOp = eOp2;
drh6c1f4ef2015-06-08 14:23:15 +00001169 markTermAsChild(pWC, idxNew, idxTerm);
1170 pTerm = &pWC->a[idxTerm];
1171 pTerm->wtFlags |= TERM_COPIED;
1172 pNewTerm->prereqAll = pTerm->prereqAll;
1173 }
1174 }
1175#endif /* SQLITE_OMIT_VIRTUALTABLE */
1176
dan95a08c02016-08-02 16:18:35 +00001177 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
drh9e730f02016-08-20 12:00:05 +00001178 ** new terms for each component comparison - "a = ?" and "b = ?". The
1179 ** new terms completely replace the original vector comparison, which is
1180 ** no longer used.
1181 **
dan95a08c02016-08-02 16:18:35 +00001182 ** This is only required if at least one side of the comparison operation
1183 ** is not a sub-select. */
dan71c57db2016-07-09 20:23:55 +00001184 if( pWC->op==TK_AND
1185 && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
dan625015e2016-07-30 16:39:28 +00001186 && sqlite3ExprIsVector(pExpr->pLeft)
dan71c57db2016-07-09 20:23:55 +00001187 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
1188 || (pExpr->pRight->flags & EP_xIsSelect)==0
1189 )){
dan19ff12d2016-07-29 20:58:19 +00001190 int nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
drhb29e60c2016-09-05 12:02:34 +00001191 int i;
1192 assert( nLeft==sqlite3ExprVectorSize(pExpr->pRight) );
1193 for(i=0; i<nLeft; i++){
1194 int idxNew;
1195 Expr *pNew;
1196 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
1197 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
dan71c57db2016-07-09 20:23:55 +00001198
drhb29e60c2016-09-05 12:02:34 +00001199 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight, 0);
1200 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
1201 exprAnalyze(pSrc, pWC, idxNew);
dan71c57db2016-07-09 20:23:55 +00001202 }
drhb29e60c2016-09-05 12:02:34 +00001203 pTerm = &pWC->a[idxTerm];
1204 pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
1205 pTerm->eOperator = 0;
dan71c57db2016-07-09 20:23:55 +00001206 }
1207
dan95a08c02016-08-02 16:18:35 +00001208 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1209 ** a virtual term for each vector component. The expression object
1210 ** used by each such virtual term is pExpr (the full vector IN(...)
1211 ** expression). The WhereTerm.iField variable identifies the index within
drh14318072016-09-06 18:51:25 +00001212 ** the vector on the LHS that the virtual term represents.
1213 **
1214 ** This only works if the RHS is a simple SELECT, not a compound
1215 */
dan8da209b2016-07-26 18:06:08 +00001216 if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
1217 && pExpr->pLeft->op==TK_VECTOR
drh14318072016-09-06 18:51:25 +00001218 && pExpr->x.pSelect->pPrior==0
dan8da209b2016-07-26 18:06:08 +00001219 ){
1220 int i;
1221 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1222 int idxNew;
1223 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
1224 pWC->a[idxNew].iField = i+1;
1225 exprAnalyze(pSrc, pWC, idxNew);
1226 markTermAsChild(pWC, idxNew, idxTerm);
1227 }
1228 }
1229
drh6c1f4ef2015-06-08 14:23:15 +00001230#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1231 /* When sqlite_stat3 histogram data is available an operator of the
1232 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1233 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1234 ** virtual term of that form.
1235 **
1236 ** Note that the virtual term must be tagged with TERM_VNULL.
1237 */
1238 if( pExpr->op==TK_NOTNULL
1239 && pExpr->pLeft->op==TK_COLUMN
1240 && pExpr->pLeft->iColumn>=0
1241 && OptimizationEnabled(db, SQLITE_Stat34)
1242 ){
1243 Expr *pNewExpr;
1244 Expr *pLeft = pExpr->pLeft;
1245 int idxNew;
1246 WhereTerm *pNewTerm;
1247
1248 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1249 sqlite3ExprDup(db, pLeft, 0),
1250 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
1251
1252 idxNew = whereClauseInsert(pWC, pNewExpr,
1253 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1254 if( idxNew ){
1255 pNewTerm = &pWC->a[idxNew];
1256 pNewTerm->prereqRight = 0;
1257 pNewTerm->leftCursor = pLeft->iTable;
1258 pNewTerm->u.leftColumn = pLeft->iColumn;
1259 pNewTerm->eOperator = WO_GT;
1260 markTermAsChild(pWC, idxNew, idxTerm);
1261 pTerm = &pWC->a[idxTerm];
1262 pTerm->wtFlags |= TERM_COPIED;
1263 pNewTerm->prereqAll = pTerm->prereqAll;
1264 }
1265 }
1266#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1267
1268 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1269 ** an index for tables to the left of the join.
1270 */
1271 pTerm->prereqRight |= extraRight;
1272}
1273
1274/***************************************************************************
1275** Routines with file scope above. Interface to the rest of the where.c
1276** subsystem follows.
1277***************************************************************************/
1278
1279/*
1280** This routine identifies subexpressions in the WHERE clause where
1281** each subexpression is separated by the AND operator or some other
1282** operator specified in the op parameter. The WhereClause structure
1283** is filled with pointers to subexpressions. For example:
1284**
1285** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1286** \________/ \_______________/ \________________/
1287** slot[0] slot[1] slot[2]
1288**
1289** The original WHERE clause in pExpr is unaltered. All this routine
1290** does is make slot[] entries point to substructure within pExpr.
1291**
1292** In the previous sentence and in the diagram, "slot[]" refers to
1293** the WhereClause.a[] array. The slot[] array grows as needed to contain
1294** all terms of the WHERE clause.
1295*/
1296void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1297 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1298 pWC->op = op;
1299 if( pE2==0 ) return;
1300 if( pE2->op!=op ){
1301 whereClauseInsert(pWC, pExpr, 0);
1302 }else{
1303 sqlite3WhereSplit(pWC, pE2->pLeft, op);
1304 sqlite3WhereSplit(pWC, pE2->pRight, op);
1305 }
1306}
1307
1308/*
1309** Initialize a preallocated WhereClause structure.
1310*/
1311void sqlite3WhereClauseInit(
1312 WhereClause *pWC, /* The WhereClause to be initialized */
1313 WhereInfo *pWInfo /* The WHERE processing context */
1314){
1315 pWC->pWInfo = pWInfo;
1316 pWC->pOuter = 0;
1317 pWC->nTerm = 0;
1318 pWC->nSlot = ArraySize(pWC->aStatic);
1319 pWC->a = pWC->aStatic;
1320}
1321
1322/*
1323** Deallocate a WhereClause structure. The WhereClause structure
drh62aaa6c2015-11-21 17:27:42 +00001324** itself is not freed. This routine is the inverse of
1325** sqlite3WhereClauseInit().
drh6c1f4ef2015-06-08 14:23:15 +00001326*/
1327void sqlite3WhereClauseClear(WhereClause *pWC){
1328 int i;
1329 WhereTerm *a;
1330 sqlite3 *db = pWC->pWInfo->pParse->db;
1331 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1332 if( a->wtFlags & TERM_DYNAMIC ){
1333 sqlite3ExprDelete(db, a->pExpr);
1334 }
1335 if( a->wtFlags & TERM_ORINFO ){
1336 whereOrInfoDelete(db, a->u.pOrInfo);
1337 }else if( a->wtFlags & TERM_ANDINFO ){
1338 whereAndInfoDelete(db, a->u.pAndInfo);
1339 }
1340 }
1341 if( pWC->a!=pWC->aStatic ){
1342 sqlite3DbFree(db, pWC->a);
1343 }
1344}
1345
1346
1347/*
1348** These routines walk (recursively) an expression tree and generate
1349** a bitmask indicating which tables are used in that expression
1350** tree.
1351*/
1352Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
drh93ca3932016-08-10 20:02:21 +00001353 Bitmask mask;
drh6c1f4ef2015-06-08 14:23:15 +00001354 if( p==0 ) return 0;
1355 if( p->op==TK_COLUMN ){
1356 mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
1357 return mask;
1358 }
drh93ca3932016-08-10 20:02:21 +00001359 assert( !ExprHasProperty(p, EP_TokenOnly) );
1360 mask = p->pRight ? sqlite3WhereExprUsage(pMaskSet, p->pRight) : 0;
drh926957f2016-04-12 00:00:33 +00001361 if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
drh6c1f4ef2015-06-08 14:23:15 +00001362 if( ExprHasProperty(p, EP_xIsSelect) ){
1363 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
drh926957f2016-04-12 00:00:33 +00001364 }else if( p->x.pList ){
drh6c1f4ef2015-06-08 14:23:15 +00001365 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1366 }
1367 return mask;
1368}
1369Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1370 int i;
1371 Bitmask mask = 0;
1372 if( pList ){
1373 for(i=0; i<pList->nExpr; i++){
1374 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1375 }
1376 }
1377 return mask;
1378}
1379
1380
1381/*
1382** Call exprAnalyze on all terms in a WHERE clause.
1383**
1384** Note that exprAnalyze() might add new virtual terms onto the
1385** end of the WHERE clause. We do not want to analyze these new
1386** virtual terms, so start analyzing at the end and work forward
1387** so that the added virtual terms are never processed.
1388*/
1389void sqlite3WhereExprAnalyze(
1390 SrcList *pTabList, /* the FROM clause */
1391 WhereClause *pWC /* the WHERE clause to be analyzed */
1392){
1393 int i;
1394 for(i=pWC->nTerm-1; i>=0; i--){
1395 exprAnalyze(pTabList, pWC, i);
1396 }
1397}
drh01d230c2015-08-19 17:11:37 +00001398
1399/*
1400** For table-valued-functions, transform the function arguments into
1401** new WHERE clause terms.
1402**
1403** Each function argument translates into an equality constraint against
1404** a HIDDEN column in the table.
1405*/
1406void sqlite3WhereTabFuncArgs(
1407 Parse *pParse, /* Parsing context */
1408 struct SrcList_item *pItem, /* The FROM clause term to process */
1409 WhereClause *pWC /* Xfer function arguments to here */
1410){
1411 Table *pTab;
1412 int j, k;
1413 ExprList *pArgs;
1414 Expr *pColRef;
1415 Expr *pTerm;
1416 if( pItem->fg.isTabFunc==0 ) return;
1417 pTab = pItem->pTab;
1418 assert( pTab!=0 );
1419 pArgs = pItem->u1.pFuncArg;
drh20292312015-11-21 13:24:46 +00001420 if( pArgs==0 ) return;
drh01d230c2015-08-19 17:11:37 +00001421 for(j=k=0; j<pArgs->nExpr; j++){
drh62aaa6c2015-11-21 17:27:42 +00001422 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
drh01d230c2015-08-19 17:11:37 +00001423 if( k>=pTab->nCol ){
drhd8b1bfc2015-08-20 23:21:34 +00001424 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
drh01d230c2015-08-19 17:11:37 +00001425 pTab->zName, j);
1426 return;
1427 }
1428 pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
1429 if( pColRef==0 ) return;
1430 pColRef->iTable = pItem->iCursor;
1431 pColRef->iColumn = k++;
drh1f2fc282015-08-21 17:14:48 +00001432 pColRef->pTab = pTab;
drh01d230c2015-08-19 17:11:37 +00001433 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
1434 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
1435 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1436 }
1437}