blob: 325b054ea20857b1cdccec06eae5a3ec2932c242 [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]);
drh6c1f4ef2015-06-08 14:23:15 +000080 }
81 pTerm = &pWC->a[idx = pWC->nTerm++];
82 if( p && ExprHasProperty(p, EP_Unlikely) ){
83 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
84 }else{
85 pTerm->truthProb = 1;
86 }
87 pTerm->pExpr = sqlite3ExprSkipCollate(p);
88 pTerm->wtFlags = wtFlags;
89 pTerm->pWC = pWC;
90 pTerm->iParent = -1;
drh87c05f02016-10-03 14:44:47 +000091 memset(&pTerm->eOperator, 0,
92 sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
drh6c1f4ef2015-06-08 14:23:15 +000093 return idx;
94}
95
96/*
97** Return TRUE if the given operator is one of the operators that is
98** allowed for an indexable WHERE clause term. The allowed operators are
dan71c57db2016-07-09 20:23:55 +000099** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
drh6c1f4ef2015-06-08 14:23:15 +0000100*/
101static int allowedOp(int op){
102 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
104 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
105 assert( TK_GE==TK_EQ+4 );
106 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
107}
108
109/*
110** Commute a comparison operator. Expressions of the form "X op Y"
111** are converted into "Y op X".
112**
113** If left/right precedence rules come into play when determining the
114** collating sequence, then COLLATE operators are adjusted to ensure
115** that the collating sequence does not change. For example:
116** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
117** the left hand side of a comparison overrides any collation sequence
118** attached to the right. For the same reason the EP_Collate flag
119** is not commuted.
120*/
121static void exprCommute(Parse *pParse, Expr *pExpr){
122 u16 expRight = (pExpr->pRight->flags & EP_Collate);
123 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
124 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
125 if( expRight==expLeft ){
126 /* Either X and Y both have COLLATE operator or neither do */
127 if( expRight ){
128 /* Both X and Y have COLLATE operators. Make sure X is always
129 ** used by clearing the EP_Collate flag from Y. */
130 pExpr->pRight->flags &= ~EP_Collate;
131 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
132 /* Neither X nor Y have COLLATE operators, but X has a non-default
133 ** collating sequence. So add the EP_Collate marker on X to cause
134 ** it to be searched first. */
135 pExpr->pLeft->flags |= EP_Collate;
136 }
137 }
138 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
139 if( pExpr->op>=TK_GT ){
140 assert( TK_LT==TK_GT+2 );
141 assert( TK_GE==TK_LE+2 );
142 assert( TK_GT>TK_EQ );
143 assert( TK_GT<TK_LE );
144 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
145 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
146 }
147}
148
149/*
150** Translate from TK_xx operator to WO_xx bitmask.
151*/
152static u16 operatorMask(int op){
153 u16 c;
154 assert( allowedOp(op) );
155 if( op==TK_IN ){
156 c = WO_IN;
157 }else if( op==TK_ISNULL ){
158 c = WO_ISNULL;
159 }else if( op==TK_IS ){
160 c = WO_IS;
161 }else{
162 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
163 c = (u16)(WO_EQ<<(op-TK_EQ));
164 }
165 assert( op!=TK_ISNULL || c==WO_ISNULL );
166 assert( op!=TK_IN || c==WO_IN );
167 assert( op!=TK_EQ || c==WO_EQ );
168 assert( op!=TK_LT || c==WO_LT );
169 assert( op!=TK_LE || c==WO_LE );
170 assert( op!=TK_GT || c==WO_GT );
171 assert( op!=TK_GE || c==WO_GE );
172 assert( op!=TK_IS || c==WO_IS );
173 return c;
174}
175
176
177#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
178/*
179** Check to see if the given expression is a LIKE or GLOB operator that
180** can be optimized using inequality constraints. Return TRUE if it is
181** so and false if not.
182**
183** In order for the operator to be optimizible, the RHS must be a string
184** literal that does not begin with a wildcard. The LHS must be a column
185** that may only be NULL, a string, or a BLOB, never a number. (This means
186** that virtual tables cannot participate in the LIKE optimization.) The
187** collating sequence for the column on the LHS must be appropriate for
188** the operator.
189*/
190static int isLikeOrGlob(
191 Parse *pParse, /* Parsing and code generating context */
192 Expr *pExpr, /* Test this expression */
193 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
194 int *pisComplete, /* True if the only wildcard is % in the last character */
195 int *pnoCase /* True if uppercase is equivalent to lowercase */
196){
drhb8313cc2017-08-08 21:30:43 +0000197 const u8 *z = 0; /* String on RHS of LIKE operator */
drh6c1f4ef2015-06-08 14:23:15 +0000198 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
199 ExprList *pList; /* List of operands to the LIKE operator */
200 int c; /* One character in z[] */
201 int cnt; /* Number of non-wildcard prefix characters */
drh1d42ea72017-07-27 20:24:29 +0000202 char wc[4]; /* Wildcard characters */
drh6c1f4ef2015-06-08 14:23:15 +0000203 sqlite3 *db = pParse->db; /* Database connection */
204 sqlite3_value *pVal = 0;
205 int op; /* Opcode of pRight */
drhb8763632016-01-19 17:54:21 +0000206 int rc; /* Result code to return */
drh6c1f4ef2015-06-08 14:23:15 +0000207
208 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
209 return 0;
210 }
211#ifdef SQLITE_EBCDIC
212 if( *pnoCase ) return 0;
213#endif
214 pList = pExpr->x.pList;
215 pLeft = pList->a[1].pExpr;
drh6c1f4ef2015-06-08 14:23:15 +0000216
217 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
218 op = pRight->op;
drh7df74752017-06-26 14:46:05 +0000219 if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
drh6c1f4ef2015-06-08 14:23:15 +0000220 Vdbe *pReprepare = pParse->pReprepare;
221 int iCol = pRight->iColumn;
222 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
223 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
drhb8313cc2017-08-08 21:30:43 +0000224 z = sqlite3_value_text(pVal);
drh6c1f4ef2015-06-08 14:23:15 +0000225 }
226 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
227 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
228 }else if( op==TK_STRING ){
drhb8313cc2017-08-08 21:30:43 +0000229 z = (u8*)pRight->u.zToken;
drh6c1f4ef2015-06-08 14:23:15 +0000230 }
231 if( z ){
drh1c84bd42017-02-10 21:37:57 +0000232
233 /* If the RHS begins with a digit or a minus sign, then the LHS must
234 ** be an ordinary column (not a virtual table column) with TEXT affinity.
235 ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
236 ** even though "lhs LIKE rhs" is true. But if the RHS does not start
237 ** with a digit or '-', then "lhs LIKE rhs" will always be false if
238 ** the LHS is numeric and so the optimization still works.
239 */
240 if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
241 if( pLeft->op!=TK_COLUMN
242 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
243 || IsVirtual(pLeft->pTab) /* Value might be numeric */
244 ){
245 sqlite3ValueFree(pVal);
246 return 0;
247 }
248 }
drh1d42ea72017-07-27 20:24:29 +0000249
250 /* Count the number of prefix characters prior to the first wildcard */
drh6c1f4ef2015-06-08 14:23:15 +0000251 cnt = 0;
252 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
253 cnt++;
drh1d42ea72017-07-27 20:24:29 +0000254 if( c==wc[3] && z[cnt]!=0 ){
255 if( z[cnt++]>0xc0 ) while( (z[cnt]&0xc0)==0x80 ){ cnt++; }
256 }
drh6c1f4ef2015-06-08 14:23:15 +0000257 }
drh1d42ea72017-07-27 20:24:29 +0000258
259 /* The optimization is possible only if (1) the pattern does not begin
260 ** with a wildcard and if (2) the non-wildcard prefix does not end with
261 ** an (illegal 0xff) character. The second condition is necessary so
262 ** that we can increment the prefix key to find an upper bound for the
263 ** range search.
264 */
drh6c1f4ef2015-06-08 14:23:15 +0000265 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
266 Expr *pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000267
268 /* A "complete" match if the pattern ends with "*" or "%" */
drh6c1f4ef2015-06-08 14:23:15 +0000269 *pisComplete = c==wc[0] && z[cnt+1]==0;
drh1d42ea72017-07-27 20:24:29 +0000270
271 /* Get the pattern prefix. Remove all escapes from the prefix. */
drhb8313cc2017-08-08 21:30:43 +0000272 pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
drh1d42ea72017-07-27 20:24:29 +0000273 if( pPrefix ){
274 int iFrom, iTo;
275 char *zNew = pPrefix->u.zToken;
276 zNew[cnt] = 0;
277 for(iFrom=iTo=0; iFrom<cnt; iFrom++){
278 if( zNew[iFrom]==wc[3] ) iFrom++;
279 zNew[iTo++] = zNew[iFrom];
280 }
281 zNew[iTo] = 0;
282 }
drh6c1f4ef2015-06-08 14:23:15 +0000283 *ppPrefix = pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000284
285 /* If the RHS pattern is a bound parameter, make arrangements to
286 ** reprepare the statement when that parameter is rebound */
drh6c1f4ef2015-06-08 14:23:15 +0000287 if( op==TK_VARIABLE ){
288 Vdbe *v = pParse->pVdbe;
289 sqlite3VdbeSetVarmask(v, pRight->iColumn);
290 if( *pisComplete && pRight->u.zToken[1] ){
291 /* If the rhs of the LIKE expression is a variable, and the current
292 ** value of the variable means there is no need to invoke the LIKE
293 ** function, then no OP_Variable will be added to the program.
294 ** This causes problems for the sqlite3_bind_parameter_name()
295 ** API. To work around them, add a dummy OP_Variable here.
296 */
297 int r1 = sqlite3GetTempReg(pParse);
298 sqlite3ExprCodeTarget(pParse, pRight, r1);
299 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
300 sqlite3ReleaseTempReg(pParse, r1);
301 }
302 }
303 }else{
304 z = 0;
305 }
306 }
307
drhb8763632016-01-19 17:54:21 +0000308 rc = (z!=0);
drh6c1f4ef2015-06-08 14:23:15 +0000309 sqlite3ValueFree(pVal);
drhb8763632016-01-19 17:54:21 +0000310 return rc;
drh6c1f4ef2015-06-08 14:23:15 +0000311}
312#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
313
314
315#ifndef SQLITE_OMIT_VIRTUALTABLE
316/*
317** Check to see if the given expression is of the form
318**
dan43970dd2015-11-24 17:39:01 +0000319** column OP expr
320**
321** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
322** column of a virtual table.
drh6c1f4ef2015-06-08 14:23:15 +0000323**
324** If it is then return TRUE. If not, return FALSE.
325*/
326static int isMatchOfColumn(
dan07bdba82015-11-23 21:09:54 +0000327 Expr *pExpr, /* Test this expression */
328 unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
drh6c1f4ef2015-06-08 14:23:15 +0000329){
drhe104dd32016-08-10 19:43:29 +0000330 static const struct Op2 {
dan07bdba82015-11-23 21:09:54 +0000331 const char *zOp;
332 unsigned char eOp2;
333 } aOp[] = {
dan43970dd2015-11-24 17:39:01 +0000334 { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
335 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
336 { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
337 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
dan07bdba82015-11-23 21:09:54 +0000338 };
drh6c1f4ef2015-06-08 14:23:15 +0000339 ExprList *pList;
dan43970dd2015-11-24 17:39:01 +0000340 Expr *pCol; /* Column reference */
dan07bdba82015-11-23 21:09:54 +0000341 int i;
drh6c1f4ef2015-06-08 14:23:15 +0000342
343 if( pExpr->op!=TK_FUNCTION ){
344 return 0;
345 }
drh6c1f4ef2015-06-08 14:23:15 +0000346 pList = pExpr->x.pList;
danff7b22b2015-11-24 18:16:15 +0000347 if( pList==0 || pList->nExpr!=2 ){
drh6c1f4ef2015-06-08 14:23:15 +0000348 return 0;
349 }
dan43970dd2015-11-24 17:39:01 +0000350 pCol = pList->a[1].pExpr;
351 if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
drh6c1f4ef2015-06-08 14:23:15 +0000352 return 0;
353 }
dan07bdba82015-11-23 21:09:54 +0000354 for(i=0; i<ArraySize(aOp); i++){
355 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
356 *peOp2 = aOp[i].eOp2;
357 return 1;
358 }
359 }
360 return 0;
drh6c1f4ef2015-06-08 14:23:15 +0000361}
362#endif /* SQLITE_OMIT_VIRTUALTABLE */
363
364/*
365** If the pBase expression originated in the ON or USING clause of
366** a join, then transfer the appropriate markings over to derived.
367*/
368static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
369 if( pDerived ){
370 pDerived->flags |= pBase->flags & EP_FromJoin;
371 pDerived->iRightJoinTable = pBase->iRightJoinTable;
372 }
373}
374
375/*
376** Mark term iChild as being a child of term iParent
377*/
378static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
379 pWC->a[iChild].iParent = iParent;
380 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
381 pWC->a[iParent].nChild++;
382}
383
384/*
385** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
386** a conjunction, then return just pTerm when N==0. If N is exceeds
387** the number of available subterms, return NULL.
388*/
389static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
390 if( pTerm->eOperator!=WO_AND ){
391 return N==0 ? pTerm : 0;
392 }
393 if( N<pTerm->u.pAndInfo->wc.nTerm ){
394 return &pTerm->u.pAndInfo->wc.a[N];
395 }
396 return 0;
397}
398
399/*
400** Subterms pOne and pTwo are contained within WHERE clause pWC. The
401** two subterms are in disjunction - they are OR-ed together.
402**
403** If these two terms are both of the form: "A op B" with the same
404** A and B values but different operators and if the operators are
405** compatible (if one is = and the other is <, for example) then
406** add a new virtual AND term to pWC that is the combination of the
407** two.
408**
409** Some examples:
410**
411** x<y OR x=y --> x<=y
412** x=y OR x=y --> x=y
413** x<=y OR x<y --> x<=y
414**
415** The following is NOT generated:
416**
417** x<y OR x>y --> x!=y
418*/
419static void whereCombineDisjuncts(
420 SrcList *pSrc, /* the FROM clause */
421 WhereClause *pWC, /* The complete WHERE clause */
422 WhereTerm *pOne, /* First disjunct */
423 WhereTerm *pTwo /* Second disjunct */
424){
425 u16 eOp = pOne->eOperator | pTwo->eOperator;
426 sqlite3 *db; /* Database connection (for malloc) */
427 Expr *pNew; /* New virtual expression */
428 int op; /* Operator for the combined expression */
429 int idxNew; /* Index in pWC of the next virtual term */
430
431 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
432 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
433 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
434 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
435 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
436 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
dan5aa550c2017-06-24 18:10:29 +0000437 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
438 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
drh6c1f4ef2015-06-08 14:23:15 +0000439 /* If we reach this point, it means the two subterms can be combined */
440 if( (eOp & (eOp-1))!=0 ){
441 if( eOp & (WO_LT|WO_LE) ){
442 eOp = WO_LE;
443 }else{
444 assert( eOp & (WO_GT|WO_GE) );
445 eOp = WO_GE;
446 }
447 }
448 db = pWC->pWInfo->pParse->db;
449 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
450 if( pNew==0 ) return;
451 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
452 pNew->op = op;
453 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
454 exprAnalyze(pSrc, pWC, idxNew);
455}
456
457#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
458/*
459** Analyze a term that consists of two or more OR-connected
460** subterms. So in:
461**
462** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
463** ^^^^^^^^^^^^^^^^^^^^
464**
465** This routine analyzes terms such as the middle term in the above example.
466** A WhereOrTerm object is computed and attached to the term under
467** analysis, regardless of the outcome of the analysis. Hence:
468**
469** WhereTerm.wtFlags |= TERM_ORINFO
470** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
471**
472** The term being analyzed must have two or more of OR-connected subterms.
473** A single subterm might be a set of AND-connected sub-subterms.
474** Examples of terms under analysis:
475**
476** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
477** (B) x=expr1 OR expr2=x OR x=expr3
478** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
479** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
480** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
481** (F) x>A OR (x=A AND y>=B)
482**
483** CASE 1:
484**
485** If all subterms are of the form T.C=expr for some single column of C and
486** a single table T (as shown in example B above) then create a new virtual
487** term that is an equivalent IN expression. In other words, if the term
488** being analyzed is:
489**
490** x = expr1 OR expr2 = x OR x = expr3
491**
492** then create a new virtual term like this:
493**
494** x IN (expr1,expr2,expr3)
495**
496** CASE 2:
497**
498** If there are exactly two disjuncts and one side has x>A and the other side
499** has x=A (for the same x and A) then add a new virtual conjunct term to the
500** WHERE clause of the form "x>=A". Example:
501**
502** x>A OR (x=A AND y>B) adds: x>=A
503**
504** The added conjunct can sometimes be helpful in query planning.
505**
506** CASE 3:
507**
508** If all subterms are indexable by a single table T, then set
509**
510** WhereTerm.eOperator = WO_OR
511** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
512**
513** A subterm is "indexable" if it is of the form
514** "T.C <op> <expr>" where C is any column of table T and
515** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
516** A subterm is also indexable if it is an AND of two or more
517** subsubterms at least one of which is indexable. Indexable AND
518** subterms have their eOperator set to WO_AND and they have
519** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
520**
521** From another point of view, "indexable" means that the subterm could
522** potentially be used with an index if an appropriate index exists.
523** This analysis does not consider whether or not the index exists; that
524** is decided elsewhere. This analysis only looks at whether subterms
525** appropriate for indexing exist.
526**
527** All examples A through E above satisfy case 3. But if a term
528** also satisfies case 1 (such as B) we know that the optimizer will
529** always prefer case 1, so in that case we pretend that case 3 is not
530** satisfied.
531**
532** It might be the case that multiple tables are indexable. For example,
533** (E) above is indexable on tables P, Q, and R.
534**
535** Terms that satisfy case 3 are candidates for lookup by using
536** separate indices to find rowids for each subterm and composing
537** the union of all rowids using a RowSet object. This is similar
538** to "bitmap indices" in other database engines.
539**
540** OTHERWISE:
541**
542** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
543** zero. This term is not useful for search.
544*/
545static void exprAnalyzeOrTerm(
546 SrcList *pSrc, /* the FROM clause */
547 WhereClause *pWC, /* the complete WHERE clause */
548 int idxTerm /* Index of the OR-term to be analyzed */
549){
550 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
551 Parse *pParse = pWInfo->pParse; /* Parser context */
552 sqlite3 *db = pParse->db; /* Database connection */
553 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
554 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
555 int i; /* Loop counters */
556 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
557 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
558 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
559 Bitmask chngToIN; /* Tables that might satisfy case 1 */
560 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
561
562 /*
563 ** Break the OR clause into its separate subterms. The subterms are
564 ** stored in a WhereClause structure containing within the WhereOrInfo
565 ** object that is attached to the original OR clause term.
566 */
567 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
568 assert( pExpr->op==TK_OR );
569 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
570 if( pOrInfo==0 ) return;
571 pTerm->wtFlags |= TERM_ORINFO;
572 pOrWc = &pOrInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000573 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000574 sqlite3WhereClauseInit(pOrWc, pWInfo);
575 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
576 sqlite3WhereExprAnalyze(pSrc, pOrWc);
577 if( db->mallocFailed ) return;
578 assert( pOrWc->nTerm>=2 );
579
580 /*
581 ** Compute the set of tables that might satisfy cases 1 or 3.
582 */
583 indexable = ~(Bitmask)0;
584 chngToIN = ~(Bitmask)0;
585 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
586 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
587 WhereAndInfo *pAndInfo;
588 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
589 chngToIN = 0;
drh575fad62016-02-05 13:38:36 +0000590 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
drh6c1f4ef2015-06-08 14:23:15 +0000591 if( pAndInfo ){
592 WhereClause *pAndWC;
593 WhereTerm *pAndTerm;
594 int j;
595 Bitmask b = 0;
596 pOrTerm->u.pAndInfo = pAndInfo;
597 pOrTerm->wtFlags |= TERM_ANDINFO;
598 pOrTerm->eOperator = WO_AND;
599 pAndWC = &pAndInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000600 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000601 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
602 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
603 sqlite3WhereExprAnalyze(pSrc, pAndWC);
604 pAndWC->pOuter = pWC;
drh6c1f4ef2015-06-08 14:23:15 +0000605 if( !db->mallocFailed ){
606 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
607 assert( pAndTerm->pExpr );
dandbd2dcb2016-05-28 18:53:55 +0000608 if( allowedOp(pAndTerm->pExpr->op)
609 || pAndTerm->eOperator==WO_MATCH
610 ){
drh6c1f4ef2015-06-08 14:23:15 +0000611 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
612 }
613 }
614 }
615 indexable &= b;
616 }
617 }else if( pOrTerm->wtFlags & TERM_COPIED ){
618 /* Skip this term for now. We revisit it when we process the
619 ** corresponding TERM_VIRTUAL term */
620 }else{
621 Bitmask b;
622 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
623 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
624 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
625 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
626 }
627 indexable &= b;
628 if( (pOrTerm->eOperator & WO_EQ)==0 ){
629 chngToIN = 0;
630 }else{
631 chngToIN &= b;
632 }
633 }
634 }
635
636 /*
637 ** Record the set of tables that satisfy case 3. The set might be
638 ** empty.
639 */
640 pOrInfo->indexable = indexable;
641 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
642
643 /* For a two-way OR, attempt to implementation case 2.
644 */
645 if( indexable && pOrWc->nTerm==2 ){
646 int iOne = 0;
647 WhereTerm *pOne;
648 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
649 int iTwo = 0;
650 WhereTerm *pTwo;
651 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
652 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
653 }
654 }
655 }
656
657 /*
658 ** chngToIN holds a set of tables that *might* satisfy case 1. But
659 ** we have to do some additional checking to see if case 1 really
660 ** is satisfied.
661 **
662 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
663 ** that there is no possibility of transforming the OR clause into an
664 ** IN operator because one or more terms in the OR clause contain
665 ** something other than == on a column in the single table. The 1-bit
666 ** case means that every term of the OR clause is of the form
667 ** "table.column=expr" for some single table. The one bit that is set
668 ** will correspond to the common table. We still need to check to make
669 ** sure the same column is used on all terms. The 2-bit case is when
670 ** the all terms are of the form "table1.column=table2.column". It
671 ** might be possible to form an IN operator with either table1.column
672 ** or table2.column as the LHS if either is common to every term of
673 ** the OR clause.
674 **
675 ** Note that terms of the form "table.column1=table.column2" (the
676 ** same table on both sizes of the ==) cannot be optimized.
677 */
678 if( chngToIN ){
679 int okToChngToIN = 0; /* True if the conversion to IN is valid */
680 int iColumn = -1; /* Column index on lhs of IN operator */
681 int iCursor = -1; /* Table cursor common to all terms */
682 int j = 0; /* Loop counter */
683
684 /* Search for a table and column that appears on one side or the
685 ** other of the == operator in every subterm. That table and column
686 ** will be recorded in iCursor and iColumn. There might not be any
687 ** such table and column. Set okToChngToIN if an appropriate table
688 ** and column is found but leave okToChngToIN false if not found.
689 */
690 for(j=0; j<2 && !okToChngToIN; j++){
691 pOrTerm = pOrWc->a;
692 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
693 assert( pOrTerm->eOperator & WO_EQ );
694 pOrTerm->wtFlags &= ~TERM_OR_OK;
695 if( pOrTerm->leftCursor==iCursor ){
696 /* This is the 2-bit case and we are on the second iteration and
697 ** current term is from the first iteration. So skip this term. */
698 assert( j==1 );
699 continue;
700 }
701 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
702 pOrTerm->leftCursor))==0 ){
703 /* This term must be of the form t1.a==t2.b where t2 is in the
704 ** chngToIN set but t1 is not. This term will be either preceded
705 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
706 ** and use its inversion. */
707 testcase( pOrTerm->wtFlags & TERM_COPIED );
708 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
709 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
710 continue;
711 }
712 iColumn = pOrTerm->u.leftColumn;
713 iCursor = pOrTerm->leftCursor;
714 break;
715 }
716 if( i<0 ){
717 /* No candidate table+column was found. This can only occur
718 ** on the second iteration */
719 assert( j==1 );
720 assert( IsPowerOfTwo(chngToIN) );
721 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
722 break;
723 }
724 testcase( j==1 );
725
726 /* We have found a candidate table and column. Check to see if that
727 ** table and column is common to every term in the OR clause */
728 okToChngToIN = 1;
729 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
730 assert( pOrTerm->eOperator & WO_EQ );
731 if( pOrTerm->leftCursor!=iCursor ){
732 pOrTerm->wtFlags &= ~TERM_OR_OK;
733 }else if( pOrTerm->u.leftColumn!=iColumn ){
734 okToChngToIN = 0;
735 }else{
736 int affLeft, affRight;
737 /* If the right-hand side is also a column, then the affinities
738 ** of both right and left sides must be such that no type
739 ** conversions are required on the right. (Ticket #2249)
740 */
741 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
742 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
743 if( affRight!=0 && affRight!=affLeft ){
744 okToChngToIN = 0;
745 }else{
746 pOrTerm->wtFlags |= TERM_OR_OK;
747 }
748 }
749 }
750 }
751
752 /* At this point, okToChngToIN is true if original pTerm satisfies
753 ** case 1. In that case, construct a new virtual term that is
754 ** pTerm converted into an IN operator.
755 */
756 if( okToChngToIN ){
757 Expr *pDup; /* A transient duplicate expression */
758 ExprList *pList = 0; /* The RHS of the IN operator */
759 Expr *pLeft = 0; /* The LHS of the IN operator */
760 Expr *pNew; /* The complete IN operator */
761
762 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
763 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
764 assert( pOrTerm->eOperator & WO_EQ );
765 assert( pOrTerm->leftCursor==iCursor );
766 assert( pOrTerm->u.leftColumn==iColumn );
767 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
768 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
769 pLeft = pOrTerm->pExpr->pLeft;
770 }
771 assert( pLeft!=0 );
772 pDup = sqlite3ExprDup(db, pLeft, 0);
drhabfd35e2016-12-06 22:47:23 +0000773 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
drh6c1f4ef2015-06-08 14:23:15 +0000774 if( pNew ){
775 int idxNew;
776 transferJoinMarkings(pNew, pExpr);
777 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
778 pNew->x.pList = pList;
779 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
780 testcase( idxNew==0 );
781 exprAnalyze(pSrc, pWC, idxNew);
782 pTerm = &pWC->a[idxTerm];
783 markTermAsChild(pWC, idxNew, idxTerm);
784 }else{
785 sqlite3ExprListDelete(db, pList);
786 }
787 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
788 }
789 }
790}
791#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
792
793/*
794** We already know that pExpr is a binary operator where both operands are
795** column references. This routine checks to see if pExpr is an equivalence
796** relation:
797** 1. The SQLITE_Transitive optimization must be enabled
798** 2. Must be either an == or an IS operator
799** 3. Not originating in the ON clause of an OUTER JOIN
800** 4. The affinities of A and B must be compatible
801** 5a. Both operands use the same collating sequence OR
802** 5b. The overall collating sequence is BINARY
803** If this routine returns TRUE, that means that the RHS can be substituted
804** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
805** This is an optimization. No harm comes from returning 0. But if 1 is
806** returned when it should not be, then incorrect answers might result.
807*/
808static int termIsEquivalence(Parse *pParse, Expr *pExpr){
809 char aff1, aff2;
810 CollSeq *pColl;
811 const char *zColl1, *zColl2;
812 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
813 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
814 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
815 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
816 aff2 = sqlite3ExprAffinity(pExpr->pRight);
817 if( aff1!=aff2
818 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
819 ){
820 return 0;
821 }
822 pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
823 if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
824 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
drha2fbe3b2016-06-28 22:27:56 +0000825 zColl1 = pColl ? pColl->zName : 0;
drh6c1f4ef2015-06-08 14:23:15 +0000826 pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
drha2fbe3b2016-06-28 22:27:56 +0000827 zColl2 = pColl ? pColl->zName : 0;
828 return sqlite3_stricmp(zColl1, zColl2)==0;
drh6c1f4ef2015-06-08 14:23:15 +0000829}
830
831/*
832** Recursively walk the expressions of a SELECT statement and generate
833** a bitmask indicating which tables are used in that expression
834** tree.
835*/
836static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
837 Bitmask mask = 0;
838 while( pS ){
839 SrcList *pSrc = pS->pSrc;
840 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
841 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
842 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
843 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
844 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
845 if( ALWAYS(pSrc!=0) ){
846 int i;
847 for(i=0; i<pSrc->nSrc; i++){
848 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
849 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
850 }
851 }
852 pS = pS->pPrior;
853 }
854 return mask;
855}
856
857/*
drh47991422015-08-31 15:58:06 +0000858** Expression pExpr is one operand of a comparison operator that might
859** be useful for indexing. This routine checks to see if pExpr appears
860** in any index. Return TRUE (1) if pExpr is an indexed term and return
drhe97c9ff2017-04-11 18:06:48 +0000861** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
862** number of the table that is indexed and aiCurCol[1] to the column number
drh8d25cb92016-08-19 19:58:06 +0000863** of the column that is indexed, or XN_EXPR (-2) if an expression is being
864** indexed.
drh47991422015-08-31 15:58:06 +0000865**
866** If pExpr is a TK_COLUMN column reference, then this routine always returns
867** true even if that particular column is not indexed, because the column
868** might be added to an automatic index later.
869*/
drhe97c9ff2017-04-11 18:06:48 +0000870static SQLITE_NOINLINE int exprMightBeIndexed2(
drh47991422015-08-31 15:58:06 +0000871 SrcList *pFrom, /* The FROM clause */
872 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
drhe97c9ff2017-04-11 18:06:48 +0000873 int *aiCurCol, /* Write the referenced table cursor and column here */
874 Expr *pExpr /* An operand of a comparison operator */
drh47991422015-08-31 15:58:06 +0000875){
876 Index *pIdx;
877 int i;
878 int iCur;
drhe97c9ff2017-04-11 18:06:48 +0000879 for(i=0; mPrereq>1; i++, mPrereq>>=1){}
880 iCur = pFrom->a[i].iCursor;
881 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
882 if( pIdx->aColExpr==0 ) continue;
883 for(i=0; i<pIdx->nKeyCol; i++){
884 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
885 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
886 aiCurCol[0] = iCur;
887 aiCurCol[1] = XN_EXPR;
888 return 1;
889 }
890 }
891 }
892 return 0;
893}
894static int exprMightBeIndexed(
895 SrcList *pFrom, /* The FROM clause */
896 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
897 int *aiCurCol, /* Write the referenced table cursor & column here */
898 Expr *pExpr, /* An operand of a comparison operator */
899 int op /* The specific comparison operator */
900){
dan71c57db2016-07-09 20:23:55 +0000901 /* If this expression is a vector to the left or right of a
902 ** inequality constraint (>, <, >= or <=), perform the processing
903 ** on the first element of the vector. */
904 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
drh64bcb8c2016-08-26 03:42:57 +0000905 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
906 assert( op<=TK_GE );
907 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
dan71c57db2016-07-09 20:23:55 +0000908 pExpr = pExpr->x.pList->a[0].pExpr;
909 }
910
drh47991422015-08-31 15:58:06 +0000911 if( pExpr->op==TK_COLUMN ){
drhe97c9ff2017-04-11 18:06:48 +0000912 aiCurCol[0] = pExpr->iTable;
913 aiCurCol[1] = pExpr->iColumn;
drh47991422015-08-31 15:58:06 +0000914 return 1;
915 }
916 if( mPrereq==0 ) return 0; /* No table references */
917 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
drhe97c9ff2017-04-11 18:06:48 +0000918 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
drh47991422015-08-31 15:58:06 +0000919}
920
dan870a0702016-08-01 16:37:43 +0000921/*
drh6c1f4ef2015-06-08 14:23:15 +0000922** The input to this routine is an WhereTerm structure with only the
923** "pExpr" field filled in. The job of this routine is to analyze the
924** subexpression and populate all the other fields of the WhereTerm
925** structure.
926**
927** If the expression is of the form "<expr> <op> X" it gets commuted
928** to the standard form of "X <op> <expr>".
929**
930** If the expression is of the form "X <op> Y" where both X and Y are
931** columns, then the original expression is unchanged and a new virtual
932** term of the form "Y <op> X" is added to the WHERE clause and
933** analyzed separately. The original term is marked with TERM_COPIED
934** and the new term is marked with TERM_DYNAMIC (because it's pExpr
935** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
936** is a commuted copy of a prior term.) The original term has nChild=1
937** and the copy has idxParent set to the index of the original term.
938*/
939static void exprAnalyze(
940 SrcList *pSrc, /* the FROM clause */
941 WhereClause *pWC, /* the WHERE clause */
942 int idxTerm /* Index of the term to be analyzed */
943){
944 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
945 WhereTerm *pTerm; /* The term to be analyzed */
946 WhereMaskSet *pMaskSet; /* Set of table index masks */
947 Expr *pExpr; /* The expression to be analyzed */
948 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
949 Bitmask prereqAll; /* Prerequesites of pExpr */
950 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
951 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
952 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
953 int noCase = 0; /* uppercase equivalent to lowercase */
954 int op; /* Top-level operator. pExpr->op */
955 Parse *pParse = pWInfo->pParse; /* Parsing context */
956 sqlite3 *db = pParse->db; /* Database connection */
dan07bdba82015-11-23 21:09:54 +0000957 unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
drhd9bcb322017-01-10 15:08:06 +0000958 int nLeft; /* Number of elements on left side vector */
drh6c1f4ef2015-06-08 14:23:15 +0000959
960 if( db->mallocFailed ){
961 return;
962 }
963 pTerm = &pWC->a[idxTerm];
964 pMaskSet = &pWInfo->sMaskSet;
965 pExpr = pTerm->pExpr;
966 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
967 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
968 op = pExpr->op;
969 if( op==TK_IN ){
970 assert( pExpr->pRight==0 );
dan7b35a772016-07-28 19:47:15 +0000971 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
drh6c1f4ef2015-06-08 14:23:15 +0000972 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
973 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
974 }else{
975 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
976 }
977 }else if( op==TK_ISNULL ){
978 pTerm->prereqRight = 0;
979 }else{
980 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
981 }
dand3930b12017-07-10 15:17:30 +0000982 pMaskSet->bVarSelect = 0;
drh6c1f4ef2015-06-08 14:23:15 +0000983 prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
dand3930b12017-07-10 15:17:30 +0000984 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
drh6c1f4ef2015-06-08 14:23:15 +0000985 if( ExprHasProperty(pExpr, EP_FromJoin) ){
986 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
987 prereqAll |= x;
988 extraRight = x-1; /* ON clause terms may not be used with an index
989 ** on left table of a LEFT JOIN. Ticket #3015 */
drh8e36ddd2017-01-10 17:33:43 +0000990 if( (prereqAll>>1)>=x ){
991 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
992 return;
993 }
drh6c1f4ef2015-06-08 14:23:15 +0000994 }
995 pTerm->prereqAll = prereqAll;
996 pTerm->leftCursor = -1;
997 pTerm->iParent = -1;
998 pTerm->eOperator = 0;
999 if( allowedOp(op) ){
drhe97c9ff2017-04-11 18:06:48 +00001000 int aiCurCol[2];
drh6c1f4ef2015-06-08 14:23:15 +00001001 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1002 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1003 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
dan8da209b2016-07-26 18:06:08 +00001004
dan145b4ea2016-07-29 18:12:12 +00001005 if( pTerm->iField>0 ){
1006 assert( op==TK_IN );
dan8da209b2016-07-26 18:06:08 +00001007 assert( pLeft->op==TK_VECTOR );
1008 pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
1009 }
1010
drhe97c9ff2017-04-11 18:06:48 +00001011 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
1012 pTerm->leftCursor = aiCurCol[0];
1013 pTerm->u.leftColumn = aiCurCol[1];
drh6860e6f2015-08-27 18:24:02 +00001014 pTerm->eOperator = operatorMask(op) & opMask;
drh6c1f4ef2015-06-08 14:23:15 +00001015 }
1016 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh47991422015-08-31 15:58:06 +00001017 if( pRight
drhe97c9ff2017-04-11 18:06:48 +00001018 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
drh47991422015-08-31 15:58:06 +00001019 ){
drh6c1f4ef2015-06-08 14:23:15 +00001020 WhereTerm *pNew;
1021 Expr *pDup;
1022 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
dan145b4ea2016-07-29 18:12:12 +00001023 assert( pTerm->iField==0 );
drh6c1f4ef2015-06-08 14:23:15 +00001024 if( pTerm->leftCursor>=0 ){
1025 int idxNew;
1026 pDup = sqlite3ExprDup(db, pExpr, 0);
1027 if( db->mallocFailed ){
1028 sqlite3ExprDelete(db, pDup);
1029 return;
1030 }
1031 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1032 if( idxNew==0 ) return;
1033 pNew = &pWC->a[idxNew];
1034 markTermAsChild(pWC, idxNew, idxTerm);
1035 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
1036 pTerm = &pWC->a[idxTerm];
1037 pTerm->wtFlags |= TERM_COPIED;
1038
1039 if( termIsEquivalence(pParse, pDup) ){
1040 pTerm->eOperator |= WO_EQUIV;
1041 eExtraOp = WO_EQUIV;
1042 }
1043 }else{
1044 pDup = pExpr;
1045 pNew = pTerm;
1046 }
1047 exprCommute(pParse, pDup);
drhe97c9ff2017-04-11 18:06:48 +00001048 pNew->leftCursor = aiCurCol[0];
1049 pNew->u.leftColumn = aiCurCol[1];
drh6c1f4ef2015-06-08 14:23:15 +00001050 testcase( (prereqLeft | extraRight) != prereqLeft );
1051 pNew->prereqRight = prereqLeft | extraRight;
1052 pNew->prereqAll = prereqAll;
1053 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1054 }
1055 }
1056
1057#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1058 /* If a term is the BETWEEN operator, create two new virtual terms
1059 ** that define the range that the BETWEEN implements. For example:
1060 **
1061 ** a BETWEEN b AND c
1062 **
1063 ** is converted into:
1064 **
1065 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1066 **
1067 ** The two new terms are added onto the end of the WhereClause object.
1068 ** The new terms are "dynamic" and are children of the original BETWEEN
1069 ** term. That means that if the BETWEEN term is coded, the children are
1070 ** skipped. Or, if the children are satisfied by an index, the original
1071 ** BETWEEN term is skipped.
1072 */
1073 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1074 ExprList *pList = pExpr->x.pList;
1075 int i;
1076 static const u8 ops[] = {TK_GE, TK_LE};
1077 assert( pList!=0 );
1078 assert( pList->nExpr==2 );
1079 for(i=0; i<2; i++){
1080 Expr *pNewExpr;
1081 int idxNew;
1082 pNewExpr = sqlite3PExpr(pParse, ops[i],
1083 sqlite3ExprDup(db, pExpr->pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001084 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001085 transferJoinMarkings(pNewExpr, pExpr);
1086 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1087 testcase( idxNew==0 );
1088 exprAnalyze(pSrc, pWC, idxNew);
1089 pTerm = &pWC->a[idxTerm];
1090 markTermAsChild(pWC, idxNew, idxTerm);
1091 }
1092 }
1093#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1094
1095#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1096 /* Analyze a term that is composed of two or more subterms connected by
1097 ** an OR operator.
1098 */
1099 else if( pExpr->op==TK_OR ){
1100 assert( pWC->op==TK_AND );
1101 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1102 pTerm = &pWC->a[idxTerm];
1103 }
1104#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1105
1106#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1107 /* Add constraints to reduce the search space on a LIKE or GLOB
1108 ** operator.
1109 **
1110 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1111 **
1112 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1113 **
1114 ** The last character of the prefix "abc" is incremented to form the
1115 ** termination condition "abd". If case is not significant (the default
1116 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1117 ** bound is made all lowercase so that the bounds also work when comparing
1118 ** BLOBs.
1119 */
1120 if( pWC->op==TK_AND
1121 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1122 ){
1123 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1124 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1125 Expr *pNewExpr1;
1126 Expr *pNewExpr2;
1127 int idxNew1;
1128 int idxNew2;
1129 const char *zCollSeqName; /* Name of collating sequence */
1130 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1131
1132 pLeft = pExpr->x.pList->a[1].pExpr;
1133 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1134
1135 /* Convert the lower bound to upper-case and the upper bound to
1136 ** lower-case (upper-case is less than lower-case in ASCII) so that
1137 ** the range constraints also work for BLOBs
1138 */
1139 if( noCase && !pParse->db->mallocFailed ){
1140 int i;
1141 char c;
1142 pTerm->wtFlags |= TERM_LIKE;
1143 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1144 pStr1->u.zToken[i] = sqlite3Toupper(c);
1145 pStr2->u.zToken[i] = sqlite3Tolower(c);
1146 }
1147 }
1148
1149 if( !db->mallocFailed ){
1150 u8 c, *pC; /* Last character before the first wildcard */
1151 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1152 c = *pC;
1153 if( noCase ){
1154 /* The point is to increment the last character before the first
1155 ** wildcard. But if we increment '@', that will push it into the
1156 ** alphabetic range where case conversions will mess up the
1157 ** inequality. To avoid this, make sure to also run the full
1158 ** LIKE on all candidate expressions by clearing the isComplete flag
1159 */
1160 if( c=='A'-1 ) isComplete = 0;
1161 c = sqlite3UpperToLower[c];
1162 }
1163 *pC = c + 1;
1164 }
1165 zCollSeqName = noCase ? "NOCASE" : "BINARY";
1166 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1167 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1168 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001169 pStr1);
drh6c1f4ef2015-06-08 14:23:15 +00001170 transferJoinMarkings(pNewExpr1, pExpr);
1171 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1172 testcase( idxNew1==0 );
1173 exprAnalyze(pSrc, pWC, idxNew1);
1174 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1175 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1176 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001177 pStr2);
drh6c1f4ef2015-06-08 14:23:15 +00001178 transferJoinMarkings(pNewExpr2, pExpr);
1179 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1180 testcase( idxNew2==0 );
1181 exprAnalyze(pSrc, pWC, idxNew2);
1182 pTerm = &pWC->a[idxTerm];
1183 if( isComplete ){
1184 markTermAsChild(pWC, idxNew1, idxTerm);
1185 markTermAsChild(pWC, idxNew2, idxTerm);
1186 }
1187 }
1188#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1189
1190#ifndef SQLITE_OMIT_VIRTUALTABLE
1191 /* Add a WO_MATCH auxiliary term to the constraint set if the
1192 ** current expression is of the form: column MATCH expr.
1193 ** This information is used by the xBestIndex methods of
1194 ** virtual tables. The native query optimizer does not attempt
1195 ** to do anything with MATCH functions.
1196 */
dandbd2dcb2016-05-28 18:53:55 +00001197 if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
drh6c1f4ef2015-06-08 14:23:15 +00001198 int idxNew;
1199 Expr *pRight, *pLeft;
1200 WhereTerm *pNewTerm;
1201 Bitmask prereqColumn, prereqExpr;
1202
1203 pRight = pExpr->x.pList->a[0].pExpr;
1204 pLeft = pExpr->x.pList->a[1].pExpr;
1205 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1206 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1207 if( (prereqExpr & prereqColumn)==0 ){
1208 Expr *pNewExpr;
1209 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
drhabfd35e2016-12-06 22:47:23 +00001210 0, sqlite3ExprDup(db, pRight, 0));
dan210ec4c2017-06-27 16:39:01 +00001211 if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
1212 ExprSetProperty(pNewExpr, EP_FromJoin);
1213 }
drh6c1f4ef2015-06-08 14:23:15 +00001214 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1215 testcase( idxNew==0 );
1216 pNewTerm = &pWC->a[idxNew];
1217 pNewTerm->prereqRight = prereqExpr;
1218 pNewTerm->leftCursor = pLeft->iTable;
1219 pNewTerm->u.leftColumn = pLeft->iColumn;
1220 pNewTerm->eOperator = WO_MATCH;
dan07bdba82015-11-23 21:09:54 +00001221 pNewTerm->eMatchOp = eOp2;
drh6c1f4ef2015-06-08 14:23:15 +00001222 markTermAsChild(pWC, idxNew, idxTerm);
1223 pTerm = &pWC->a[idxTerm];
1224 pTerm->wtFlags |= TERM_COPIED;
1225 pNewTerm->prereqAll = pTerm->prereqAll;
1226 }
1227 }
1228#endif /* SQLITE_OMIT_VIRTUALTABLE */
1229
dan95a08c02016-08-02 16:18:35 +00001230 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
drh9e730f02016-08-20 12:00:05 +00001231 ** new terms for each component comparison - "a = ?" and "b = ?". The
1232 ** new terms completely replace the original vector comparison, which is
1233 ** no longer used.
1234 **
dan95a08c02016-08-02 16:18:35 +00001235 ** This is only required if at least one side of the comparison operation
1236 ** is not a sub-select. */
dan71c57db2016-07-09 20:23:55 +00001237 if( pWC->op==TK_AND
1238 && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
drhd9bcb322017-01-10 15:08:06 +00001239 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
1240 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
dan71c57db2016-07-09 20:23:55 +00001241 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
drhd9bcb322017-01-10 15:08:06 +00001242 || (pExpr->pRight->flags & EP_xIsSelect)==0)
1243 ){
drhb29e60c2016-09-05 12:02:34 +00001244 int i;
drhb29e60c2016-09-05 12:02:34 +00001245 for(i=0; i<nLeft; i++){
1246 int idxNew;
1247 Expr *pNew;
1248 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
1249 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
dan71c57db2016-07-09 20:23:55 +00001250
drhabfd35e2016-12-06 22:47:23 +00001251 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
drhc52496f2016-10-27 01:02:20 +00001252 transferJoinMarkings(pNew, pExpr);
drhb29e60c2016-09-05 12:02:34 +00001253 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
1254 exprAnalyze(pSrc, pWC, idxNew);
dan71c57db2016-07-09 20:23:55 +00001255 }
drhb29e60c2016-09-05 12:02:34 +00001256 pTerm = &pWC->a[idxTerm];
1257 pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
1258 pTerm->eOperator = 0;
dan71c57db2016-07-09 20:23:55 +00001259 }
1260
dan95a08c02016-08-02 16:18:35 +00001261 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1262 ** a virtual term for each vector component. The expression object
1263 ** used by each such virtual term is pExpr (the full vector IN(...)
1264 ** expression). The WhereTerm.iField variable identifies the index within
drh14318072016-09-06 18:51:25 +00001265 ** the vector on the LHS that the virtual term represents.
1266 **
1267 ** This only works if the RHS is a simple SELECT, not a compound
1268 */
dan8da209b2016-07-26 18:06:08 +00001269 if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
1270 && pExpr->pLeft->op==TK_VECTOR
drh14318072016-09-06 18:51:25 +00001271 && pExpr->x.pSelect->pPrior==0
dan8da209b2016-07-26 18:06:08 +00001272 ){
1273 int i;
1274 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1275 int idxNew;
1276 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
1277 pWC->a[idxNew].iField = i+1;
1278 exprAnalyze(pSrc, pWC, idxNew);
1279 markTermAsChild(pWC, idxNew, idxTerm);
1280 }
1281 }
1282
drh6c1f4ef2015-06-08 14:23:15 +00001283#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1284 /* When sqlite_stat3 histogram data is available an operator of the
1285 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1286 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1287 ** virtual term of that form.
1288 **
1289 ** Note that the virtual term must be tagged with TERM_VNULL.
1290 */
1291 if( pExpr->op==TK_NOTNULL
1292 && pExpr->pLeft->op==TK_COLUMN
1293 && pExpr->pLeft->iColumn>=0
1294 && OptimizationEnabled(db, SQLITE_Stat34)
1295 ){
1296 Expr *pNewExpr;
1297 Expr *pLeft = pExpr->pLeft;
1298 int idxNew;
1299 WhereTerm *pNewTerm;
1300
1301 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1302 sqlite3ExprDup(db, pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001303 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001304
1305 idxNew = whereClauseInsert(pWC, pNewExpr,
1306 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1307 if( idxNew ){
1308 pNewTerm = &pWC->a[idxNew];
1309 pNewTerm->prereqRight = 0;
1310 pNewTerm->leftCursor = pLeft->iTable;
1311 pNewTerm->u.leftColumn = pLeft->iColumn;
1312 pNewTerm->eOperator = WO_GT;
1313 markTermAsChild(pWC, idxNew, idxTerm);
1314 pTerm = &pWC->a[idxTerm];
1315 pTerm->wtFlags |= TERM_COPIED;
1316 pNewTerm->prereqAll = pTerm->prereqAll;
1317 }
1318 }
1319#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1320
1321 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1322 ** an index for tables to the left of the join.
1323 */
drh0f85b2f2016-11-20 12:00:27 +00001324 testcase( pTerm!=&pWC->a[idxTerm] );
1325 pTerm = &pWC->a[idxTerm];
drh6c1f4ef2015-06-08 14:23:15 +00001326 pTerm->prereqRight |= extraRight;
1327}
1328
1329/***************************************************************************
1330** Routines with file scope above. Interface to the rest of the where.c
1331** subsystem follows.
1332***************************************************************************/
1333
1334/*
1335** This routine identifies subexpressions in the WHERE clause where
1336** each subexpression is separated by the AND operator or some other
1337** operator specified in the op parameter. The WhereClause structure
1338** is filled with pointers to subexpressions. For example:
1339**
1340** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1341** \________/ \_______________/ \________________/
1342** slot[0] slot[1] slot[2]
1343**
1344** The original WHERE clause in pExpr is unaltered. All this routine
1345** does is make slot[] entries point to substructure within pExpr.
1346**
1347** In the previous sentence and in the diagram, "slot[]" refers to
1348** the WhereClause.a[] array. The slot[] array grows as needed to contain
1349** all terms of the WHERE clause.
1350*/
1351void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1352 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1353 pWC->op = op;
1354 if( pE2==0 ) return;
1355 if( pE2->op!=op ){
1356 whereClauseInsert(pWC, pExpr, 0);
1357 }else{
1358 sqlite3WhereSplit(pWC, pE2->pLeft, op);
1359 sqlite3WhereSplit(pWC, pE2->pRight, op);
1360 }
1361}
1362
1363/*
1364** Initialize a preallocated WhereClause structure.
1365*/
1366void sqlite3WhereClauseInit(
1367 WhereClause *pWC, /* The WhereClause to be initialized */
1368 WhereInfo *pWInfo /* The WHERE processing context */
1369){
1370 pWC->pWInfo = pWInfo;
1371 pWC->pOuter = 0;
1372 pWC->nTerm = 0;
1373 pWC->nSlot = ArraySize(pWC->aStatic);
1374 pWC->a = pWC->aStatic;
1375}
1376
1377/*
1378** Deallocate a WhereClause structure. The WhereClause structure
drh62aaa6c2015-11-21 17:27:42 +00001379** itself is not freed. This routine is the inverse of
1380** sqlite3WhereClauseInit().
drh6c1f4ef2015-06-08 14:23:15 +00001381*/
1382void sqlite3WhereClauseClear(WhereClause *pWC){
1383 int i;
1384 WhereTerm *a;
1385 sqlite3 *db = pWC->pWInfo->pParse->db;
1386 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1387 if( a->wtFlags & TERM_DYNAMIC ){
1388 sqlite3ExprDelete(db, a->pExpr);
1389 }
1390 if( a->wtFlags & TERM_ORINFO ){
1391 whereOrInfoDelete(db, a->u.pOrInfo);
1392 }else if( a->wtFlags & TERM_ANDINFO ){
1393 whereAndInfoDelete(db, a->u.pAndInfo);
1394 }
1395 }
1396 if( pWC->a!=pWC->aStatic ){
1397 sqlite3DbFree(db, pWC->a);
1398 }
1399}
1400
1401
1402/*
1403** These routines walk (recursively) an expression tree and generate
1404** a bitmask indicating which tables are used in that expression
1405** tree.
1406*/
1407Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
drh93ca3932016-08-10 20:02:21 +00001408 Bitmask mask;
drh6c1f4ef2015-06-08 14:23:15 +00001409 if( p==0 ) return 0;
1410 if( p->op==TK_COLUMN ){
drhf43ce0b2017-05-25 00:08:48 +00001411 return sqlite3WhereGetMask(pMaskSet, p->iTable);
drh6c1f4ef2015-06-08 14:23:15 +00001412 }
drhf43ce0b2017-05-25 00:08:48 +00001413 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
drh93ca3932016-08-10 20:02:21 +00001414 assert( !ExprHasProperty(p, EP_TokenOnly) );
drh926957f2016-04-12 00:00:33 +00001415 if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
drhe24b92b2017-07-10 15:26:09 +00001416 if( p->pRight ){
1417 mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
1418 assert( p->x.pList==0 );
1419 }else if( ExprHasProperty(p, EP_xIsSelect) ){
dand3930b12017-07-10 15:17:30 +00001420 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
drh6c1f4ef2015-06-08 14:23:15 +00001421 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
drh926957f2016-04-12 00:00:33 +00001422 }else if( p->x.pList ){
drh6c1f4ef2015-06-08 14:23:15 +00001423 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1424 }
1425 return mask;
1426}
1427Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1428 int i;
1429 Bitmask mask = 0;
1430 if( pList ){
1431 for(i=0; i<pList->nExpr; i++){
1432 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1433 }
1434 }
1435 return mask;
1436}
1437
1438
1439/*
1440** Call exprAnalyze on all terms in a WHERE clause.
1441**
1442** Note that exprAnalyze() might add new virtual terms onto the
1443** end of the WHERE clause. We do not want to analyze these new
1444** virtual terms, so start analyzing at the end and work forward
1445** so that the added virtual terms are never processed.
1446*/
1447void sqlite3WhereExprAnalyze(
1448 SrcList *pTabList, /* the FROM clause */
1449 WhereClause *pWC /* the WHERE clause to be analyzed */
1450){
1451 int i;
1452 for(i=pWC->nTerm-1; i>=0; i--){
1453 exprAnalyze(pTabList, pWC, i);
1454 }
1455}
drh01d230c2015-08-19 17:11:37 +00001456
1457/*
1458** For table-valued-functions, transform the function arguments into
1459** new WHERE clause terms.
1460**
1461** Each function argument translates into an equality constraint against
1462** a HIDDEN column in the table.
1463*/
1464void sqlite3WhereTabFuncArgs(
1465 Parse *pParse, /* Parsing context */
1466 struct SrcList_item *pItem, /* The FROM clause term to process */
1467 WhereClause *pWC /* Xfer function arguments to here */
1468){
1469 Table *pTab;
1470 int j, k;
1471 ExprList *pArgs;
1472 Expr *pColRef;
1473 Expr *pTerm;
1474 if( pItem->fg.isTabFunc==0 ) return;
1475 pTab = pItem->pTab;
1476 assert( pTab!=0 );
1477 pArgs = pItem->u1.pFuncArg;
drh20292312015-11-21 13:24:46 +00001478 if( pArgs==0 ) return;
drh01d230c2015-08-19 17:11:37 +00001479 for(j=k=0; j<pArgs->nExpr; j++){
drh62aaa6c2015-11-21 17:27:42 +00001480 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
drh01d230c2015-08-19 17:11:37 +00001481 if( k>=pTab->nCol ){
drhd8b1bfc2015-08-20 23:21:34 +00001482 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
drh01d230c2015-08-19 17:11:37 +00001483 pTab->zName, j);
1484 return;
1485 }
drhe1c03b62016-09-23 20:59:31 +00001486 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
drh01d230c2015-08-19 17:11:37 +00001487 if( pColRef==0 ) return;
1488 pColRef->iTable = pItem->iCursor;
1489 pColRef->iColumn = k++;
drh1f2fc282015-08-21 17:14:48 +00001490 pColRef->pTab = pTab;
drh01d230c2015-08-19 17:11:37 +00001491 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
drhabfd35e2016-12-06 22:47:23 +00001492 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
drh01d230c2015-08-19 17:11:37 +00001493 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1494 }
1495}