blob: b177a7d9957bdb29a0af1f7a9677a4979a93e288 [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++;
drhf41a8d32017-08-11 03:47:21 +0000254 if( c==wc[3] && z[cnt]!=0 ) cnt++;
drh6c1f4ef2015-06-08 14:23:15 +0000255 }
drh1d42ea72017-07-27 20:24:29 +0000256
257 /* The optimization is possible only if (1) the pattern does not begin
258 ** with a wildcard and if (2) the non-wildcard prefix does not end with
259 ** an (illegal 0xff) character. The second condition is necessary so
260 ** that we can increment the prefix key to find an upper bound for the
261 ** range search.
262 */
drh6c1f4ef2015-06-08 14:23:15 +0000263 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
264 Expr *pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000265
266 /* A "complete" match if the pattern ends with "*" or "%" */
drh6c1f4ef2015-06-08 14:23:15 +0000267 *pisComplete = c==wc[0] && z[cnt+1]==0;
drh1d42ea72017-07-27 20:24:29 +0000268
269 /* Get the pattern prefix. Remove all escapes from the prefix. */
drhb8313cc2017-08-08 21:30:43 +0000270 pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
drh1d42ea72017-07-27 20:24:29 +0000271 if( pPrefix ){
272 int iFrom, iTo;
273 char *zNew = pPrefix->u.zToken;
274 zNew[cnt] = 0;
275 for(iFrom=iTo=0; iFrom<cnt; iFrom++){
276 if( zNew[iFrom]==wc[3] ) iFrom++;
277 zNew[iTo++] = zNew[iFrom];
278 }
279 zNew[iTo] = 0;
280 }
drh6c1f4ef2015-06-08 14:23:15 +0000281 *ppPrefix = pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000282
283 /* If the RHS pattern is a bound parameter, make arrangements to
284 ** reprepare the statement when that parameter is rebound */
drh6c1f4ef2015-06-08 14:23:15 +0000285 if( op==TK_VARIABLE ){
286 Vdbe *v = pParse->pVdbe;
287 sqlite3VdbeSetVarmask(v, pRight->iColumn);
288 if( *pisComplete && pRight->u.zToken[1] ){
289 /* If the rhs of the LIKE expression is a variable, and the current
290 ** value of the variable means there is no need to invoke the LIKE
291 ** function, then no OP_Variable will be added to the program.
292 ** This causes problems for the sqlite3_bind_parameter_name()
293 ** API. To work around them, add a dummy OP_Variable here.
294 */
295 int r1 = sqlite3GetTempReg(pParse);
296 sqlite3ExprCodeTarget(pParse, pRight, r1);
297 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
298 sqlite3ReleaseTempReg(pParse, r1);
299 }
300 }
301 }else{
302 z = 0;
303 }
304 }
305
drhb8763632016-01-19 17:54:21 +0000306 rc = (z!=0);
drh6c1f4ef2015-06-08 14:23:15 +0000307 sqlite3ValueFree(pVal);
drhb8763632016-01-19 17:54:21 +0000308 return rc;
drh6c1f4ef2015-06-08 14:23:15 +0000309}
310#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
311
312
313#ifndef SQLITE_OMIT_VIRTUALTABLE
314/*
drh303a69b2017-09-11 19:47:37 +0000315** Check to see if the pExpr expression is a form that needs to be passed
316** to the xBestIndex method of virtual tables. Forms of interest include:
drh6c1f4ef2015-06-08 14:23:15 +0000317**
drh303a69b2017-09-11 19:47:37 +0000318** Expression Virtual Table Operator
319** ----------------------- ---------------------------------
320** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
321** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
322** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
323** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
324** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
325** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
326** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
327** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
328** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
dan43970dd2015-11-24 17:39:01 +0000329**
drh303a69b2017-09-11 19:47:37 +0000330** In every case, "column" must be a column of a virtual table. If there
331** is a match, set *ppLeft to the "column" expression, set *ppRight to the
332** "expr" expression (even though in forms (6) and (8) the column is on the
333** right and the expression is on the left). Also set *peOp2 to the
334** appropriate virtual table operator. The return value is 1 or 2 if there
335** is a match. The usual return is 1, but if the RHS is also a column
336** of virtual table in forms (5) or (7) then return 2.
dand03024d2017-09-09 19:41:12 +0000337**
338** If the expression matches none of the patterns above, return 0.
drh6c1f4ef2015-06-08 14:23:15 +0000339*/
drh303a69b2017-09-11 19:47:37 +0000340static int isAuxiliaryVtabOperator(
drh59155062018-05-26 18:03:48 +0000341 sqlite3 *db, /* Parsing context */
dan07bdba82015-11-23 21:09:54 +0000342 Expr *pExpr, /* Test this expression */
dand03024d2017-09-09 19:41:12 +0000343 unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
344 Expr **ppLeft, /* Column expression to left of MATCH/op2 */
345 Expr **ppRight /* Expression to left of MATCH/op2 */
drh6c1f4ef2015-06-08 14:23:15 +0000346){
dand03024d2017-09-09 19:41:12 +0000347 if( pExpr->op==TK_FUNCTION ){
348 static const struct Op2 {
349 const char *zOp;
350 unsigned char eOp2;
351 } aOp[] = {
352 { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
353 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
354 { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
355 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
356 };
357 ExprList *pList;
358 Expr *pCol; /* Column reference */
359 int i;
drh6c1f4ef2015-06-08 14:23:15 +0000360
dand03024d2017-09-09 19:41:12 +0000361 pList = pExpr->x.pList;
362 if( pList==0 || pList->nExpr!=2 ){
363 return 0;
364 }
drh59155062018-05-26 18:03:48 +0000365
366 /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
367 ** virtual table on their second argument, which is the same as
368 ** the left-hand side operand in their in-fix form.
369 **
370 ** vtab_column MATCH expression
371 ** MATCH(expression,vtab_column)
372 */
dand03024d2017-09-09 19:41:12 +0000373 pCol = pList->a[1].pExpr;
drh59155062018-05-26 18:03:48 +0000374 if( pCol->op==TK_COLUMN && IsVirtual(pCol->pTab) ){
375 for(i=0; i<ArraySize(aOp); i++){
376 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
377 *peOp2 = aOp[i].eOp2;
378 *ppRight = pList->a[0].pExpr;
379 *ppLeft = pCol;
380 return 1;
381 }
382 }
dand03024d2017-09-09 19:41:12 +0000383 }
drh59155062018-05-26 18:03:48 +0000384
385 /* We can also match against the first column of overloaded
386 ** functions where xFindFunction returns a value of at least
387 ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
388 **
389 ** OVERLOADED(vtab_column,expression)
390 **
391 ** Historically, xFindFunction expected to see lower-case function
392 ** names. But for this use case, xFindFunction is expected to deal
393 ** with function names in an arbitrary case.
394 */
395 pCol = pList->a[0].pExpr;
396 if( pCol->op==TK_COLUMN && IsVirtual(pCol->pTab) ){
397 sqlite3_vtab *pVtab;
398 sqlite3_module *pMod;
399 void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
400 void *pNotUsed;
401 pVtab = sqlite3GetVTable(db, pCol->pTab)->pVtab;
402 assert( pVtab!=0 );
403 assert( pVtab->pModule!=0 );
404 pMod = (sqlite3_module *)pVtab->pModule;
405 if( pMod->xFindFunction!=0 ){
406 i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
407 if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
408 *peOp2 = i;
409 *ppRight = pList->a[1].pExpr;
410 *ppLeft = pCol;
411 return 1;
412 }
dand03024d2017-09-09 19:41:12 +0000413 }
414 }
415 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
416 int res = 0;
417 Expr *pLeft = pExpr->pLeft;
418 Expr *pRight = pExpr->pRight;
419 if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
420 res++;
421 }
422 if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
423 res++;
424 SWAP(Expr*, pLeft, pRight);
425 }
426 *ppLeft = pLeft;
427 *ppRight = pRight;
428 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
429 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
430 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
431 return res;
dan07bdba82015-11-23 21:09:54 +0000432 }
433 return 0;
drh6c1f4ef2015-06-08 14:23:15 +0000434}
435#endif /* SQLITE_OMIT_VIRTUALTABLE */
436
437/*
438** If the pBase expression originated in the ON or USING clause of
439** a join, then transfer the appropriate markings over to derived.
440*/
441static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
442 if( pDerived ){
443 pDerived->flags |= pBase->flags & EP_FromJoin;
444 pDerived->iRightJoinTable = pBase->iRightJoinTable;
445 }
446}
447
448/*
449** Mark term iChild as being a child of term iParent
450*/
451static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
452 pWC->a[iChild].iParent = iParent;
453 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
454 pWC->a[iParent].nChild++;
455}
456
457/*
458** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
459** a conjunction, then return just pTerm when N==0. If N is exceeds
460** the number of available subterms, return NULL.
461*/
462static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
463 if( pTerm->eOperator!=WO_AND ){
464 return N==0 ? pTerm : 0;
465 }
466 if( N<pTerm->u.pAndInfo->wc.nTerm ){
467 return &pTerm->u.pAndInfo->wc.a[N];
468 }
469 return 0;
470}
471
472/*
473** Subterms pOne and pTwo are contained within WHERE clause pWC. The
474** two subterms are in disjunction - they are OR-ed together.
475**
476** If these two terms are both of the form: "A op B" with the same
477** A and B values but different operators and if the operators are
478** compatible (if one is = and the other is <, for example) then
479** add a new virtual AND term to pWC that is the combination of the
480** two.
481**
482** Some examples:
483**
484** x<y OR x=y --> x<=y
485** x=y OR x=y --> x=y
486** x<=y OR x<y --> x<=y
487**
488** The following is NOT generated:
489**
490** x<y OR x>y --> x!=y
491*/
492static void whereCombineDisjuncts(
493 SrcList *pSrc, /* the FROM clause */
494 WhereClause *pWC, /* The complete WHERE clause */
495 WhereTerm *pOne, /* First disjunct */
496 WhereTerm *pTwo /* Second disjunct */
497){
498 u16 eOp = pOne->eOperator | pTwo->eOperator;
499 sqlite3 *db; /* Database connection (for malloc) */
500 Expr *pNew; /* New virtual expression */
501 int op; /* Operator for the combined expression */
502 int idxNew; /* Index in pWC of the next virtual term */
503
504 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
505 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
506 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
507 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
508 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
509 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
dan5aa550c2017-06-24 18:10:29 +0000510 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
511 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
drh6c1f4ef2015-06-08 14:23:15 +0000512 /* If we reach this point, it means the two subterms can be combined */
513 if( (eOp & (eOp-1))!=0 ){
514 if( eOp & (WO_LT|WO_LE) ){
515 eOp = WO_LE;
516 }else{
517 assert( eOp & (WO_GT|WO_GE) );
518 eOp = WO_GE;
519 }
520 }
521 db = pWC->pWInfo->pParse->db;
522 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
523 if( pNew==0 ) return;
524 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
525 pNew->op = op;
526 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
527 exprAnalyze(pSrc, pWC, idxNew);
528}
529
530#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
531/*
532** Analyze a term that consists of two or more OR-connected
533** subterms. So in:
534**
535** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
536** ^^^^^^^^^^^^^^^^^^^^
537**
538** This routine analyzes terms such as the middle term in the above example.
539** A WhereOrTerm object is computed and attached to the term under
540** analysis, regardless of the outcome of the analysis. Hence:
541**
542** WhereTerm.wtFlags |= TERM_ORINFO
543** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
544**
545** The term being analyzed must have two or more of OR-connected subterms.
546** A single subterm might be a set of AND-connected sub-subterms.
547** Examples of terms under analysis:
548**
549** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
550** (B) x=expr1 OR expr2=x OR x=expr3
551** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
552** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
553** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
554** (F) x>A OR (x=A AND y>=B)
555**
556** CASE 1:
557**
558** If all subterms are of the form T.C=expr for some single column of C and
559** a single table T (as shown in example B above) then create a new virtual
560** term that is an equivalent IN expression. In other words, if the term
561** being analyzed is:
562**
563** x = expr1 OR expr2 = x OR x = expr3
564**
565** then create a new virtual term like this:
566**
567** x IN (expr1,expr2,expr3)
568**
569** CASE 2:
570**
571** If there are exactly two disjuncts and one side has x>A and the other side
572** has x=A (for the same x and A) then add a new virtual conjunct term to the
573** WHERE clause of the form "x>=A". Example:
574**
575** x>A OR (x=A AND y>B) adds: x>=A
576**
577** The added conjunct can sometimes be helpful in query planning.
578**
579** CASE 3:
580**
581** If all subterms are indexable by a single table T, then set
582**
583** WhereTerm.eOperator = WO_OR
584** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
585**
586** A subterm is "indexable" if it is of the form
587** "T.C <op> <expr>" where C is any column of table T and
588** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
589** A subterm is also indexable if it is an AND of two or more
590** subsubterms at least one of which is indexable. Indexable AND
591** subterms have their eOperator set to WO_AND and they have
592** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
593**
594** From another point of view, "indexable" means that the subterm could
595** potentially be used with an index if an appropriate index exists.
596** This analysis does not consider whether or not the index exists; that
597** is decided elsewhere. This analysis only looks at whether subterms
598** appropriate for indexing exist.
599**
600** All examples A through E above satisfy case 3. But if a term
601** also satisfies case 1 (such as B) we know that the optimizer will
602** always prefer case 1, so in that case we pretend that case 3 is not
603** satisfied.
604**
605** It might be the case that multiple tables are indexable. For example,
606** (E) above is indexable on tables P, Q, and R.
607**
608** Terms that satisfy case 3 are candidates for lookup by using
609** separate indices to find rowids for each subterm and composing
610** the union of all rowids using a RowSet object. This is similar
611** to "bitmap indices" in other database engines.
612**
613** OTHERWISE:
614**
615** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
616** zero. This term is not useful for search.
617*/
618static void exprAnalyzeOrTerm(
619 SrcList *pSrc, /* the FROM clause */
620 WhereClause *pWC, /* the complete WHERE clause */
621 int idxTerm /* Index of the OR-term to be analyzed */
622){
623 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
624 Parse *pParse = pWInfo->pParse; /* Parser context */
625 sqlite3 *db = pParse->db; /* Database connection */
626 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
627 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
628 int i; /* Loop counters */
629 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
630 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
631 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
632 Bitmask chngToIN; /* Tables that might satisfy case 1 */
633 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
634
635 /*
636 ** Break the OR clause into its separate subterms. The subterms are
637 ** stored in a WhereClause structure containing within the WhereOrInfo
638 ** object that is attached to the original OR clause term.
639 */
640 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
641 assert( pExpr->op==TK_OR );
642 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
643 if( pOrInfo==0 ) return;
644 pTerm->wtFlags |= TERM_ORINFO;
645 pOrWc = &pOrInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000646 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000647 sqlite3WhereClauseInit(pOrWc, pWInfo);
648 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
649 sqlite3WhereExprAnalyze(pSrc, pOrWc);
650 if( db->mallocFailed ) return;
651 assert( pOrWc->nTerm>=2 );
652
653 /*
654 ** Compute the set of tables that might satisfy cases 1 or 3.
655 */
656 indexable = ~(Bitmask)0;
657 chngToIN = ~(Bitmask)0;
658 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
659 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
660 WhereAndInfo *pAndInfo;
661 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
662 chngToIN = 0;
drh575fad62016-02-05 13:38:36 +0000663 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
drh6c1f4ef2015-06-08 14:23:15 +0000664 if( pAndInfo ){
665 WhereClause *pAndWC;
666 WhereTerm *pAndTerm;
667 int j;
668 Bitmask b = 0;
669 pOrTerm->u.pAndInfo = pAndInfo;
670 pOrTerm->wtFlags |= TERM_ANDINFO;
671 pOrTerm->eOperator = WO_AND;
672 pAndWC = &pAndInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000673 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000674 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
675 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
676 sqlite3WhereExprAnalyze(pSrc, pAndWC);
677 pAndWC->pOuter = pWC;
drh6c1f4ef2015-06-08 14:23:15 +0000678 if( !db->mallocFailed ){
679 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
680 assert( pAndTerm->pExpr );
dandbd2dcb2016-05-28 18:53:55 +0000681 if( allowedOp(pAndTerm->pExpr->op)
drh303a69b2017-09-11 19:47:37 +0000682 || pAndTerm->eOperator==WO_AUX
dandbd2dcb2016-05-28 18:53:55 +0000683 ){
drh6c1f4ef2015-06-08 14:23:15 +0000684 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
685 }
686 }
687 }
688 indexable &= b;
689 }
690 }else if( pOrTerm->wtFlags & TERM_COPIED ){
691 /* Skip this term for now. We revisit it when we process the
692 ** corresponding TERM_VIRTUAL term */
693 }else{
694 Bitmask b;
695 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
696 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
697 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
698 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
699 }
700 indexable &= b;
701 if( (pOrTerm->eOperator & WO_EQ)==0 ){
702 chngToIN = 0;
703 }else{
704 chngToIN &= b;
705 }
706 }
707 }
708
709 /*
710 ** Record the set of tables that satisfy case 3. The set might be
711 ** empty.
712 */
713 pOrInfo->indexable = indexable;
714 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
715
716 /* For a two-way OR, attempt to implementation case 2.
717 */
718 if( indexable && pOrWc->nTerm==2 ){
719 int iOne = 0;
720 WhereTerm *pOne;
721 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
722 int iTwo = 0;
723 WhereTerm *pTwo;
724 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
725 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
726 }
727 }
728 }
729
730 /*
731 ** chngToIN holds a set of tables that *might* satisfy case 1. But
732 ** we have to do some additional checking to see if case 1 really
733 ** is satisfied.
734 **
735 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
736 ** that there is no possibility of transforming the OR clause into an
737 ** IN operator because one or more terms in the OR clause contain
738 ** something other than == on a column in the single table. The 1-bit
739 ** case means that every term of the OR clause is of the form
740 ** "table.column=expr" for some single table. The one bit that is set
741 ** will correspond to the common table. We still need to check to make
742 ** sure the same column is used on all terms. The 2-bit case is when
743 ** the all terms are of the form "table1.column=table2.column". It
744 ** might be possible to form an IN operator with either table1.column
745 ** or table2.column as the LHS if either is common to every term of
746 ** the OR clause.
747 **
748 ** Note that terms of the form "table.column1=table.column2" (the
749 ** same table on both sizes of the ==) cannot be optimized.
750 */
751 if( chngToIN ){
752 int okToChngToIN = 0; /* True if the conversion to IN is valid */
753 int iColumn = -1; /* Column index on lhs of IN operator */
754 int iCursor = -1; /* Table cursor common to all terms */
755 int j = 0; /* Loop counter */
756
757 /* Search for a table and column that appears on one side or the
758 ** other of the == operator in every subterm. That table and column
759 ** will be recorded in iCursor and iColumn. There might not be any
760 ** such table and column. Set okToChngToIN if an appropriate table
761 ** and column is found but leave okToChngToIN false if not found.
762 */
763 for(j=0; j<2 && !okToChngToIN; j++){
764 pOrTerm = pOrWc->a;
765 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
766 assert( pOrTerm->eOperator & WO_EQ );
767 pOrTerm->wtFlags &= ~TERM_OR_OK;
768 if( pOrTerm->leftCursor==iCursor ){
769 /* This is the 2-bit case and we are on the second iteration and
770 ** current term is from the first iteration. So skip this term. */
771 assert( j==1 );
772 continue;
773 }
774 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
775 pOrTerm->leftCursor))==0 ){
776 /* This term must be of the form t1.a==t2.b where t2 is in the
777 ** chngToIN set but t1 is not. This term will be either preceded
778 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
779 ** and use its inversion. */
780 testcase( pOrTerm->wtFlags & TERM_COPIED );
781 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
782 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
783 continue;
784 }
785 iColumn = pOrTerm->u.leftColumn;
786 iCursor = pOrTerm->leftCursor;
787 break;
788 }
789 if( i<0 ){
790 /* No candidate table+column was found. This can only occur
791 ** on the second iteration */
792 assert( j==1 );
793 assert( IsPowerOfTwo(chngToIN) );
794 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
795 break;
796 }
797 testcase( j==1 );
798
799 /* We have found a candidate table and column. Check to see if that
800 ** table and column is common to every term in the OR clause */
801 okToChngToIN = 1;
802 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
803 assert( pOrTerm->eOperator & WO_EQ );
804 if( pOrTerm->leftCursor!=iCursor ){
805 pOrTerm->wtFlags &= ~TERM_OR_OK;
806 }else if( pOrTerm->u.leftColumn!=iColumn ){
807 okToChngToIN = 0;
808 }else{
809 int affLeft, affRight;
810 /* If the right-hand side is also a column, then the affinities
811 ** of both right and left sides must be such that no type
812 ** conversions are required on the right. (Ticket #2249)
813 */
814 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
815 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
816 if( affRight!=0 && affRight!=affLeft ){
817 okToChngToIN = 0;
818 }else{
819 pOrTerm->wtFlags |= TERM_OR_OK;
820 }
821 }
822 }
823 }
824
825 /* At this point, okToChngToIN is true if original pTerm satisfies
826 ** case 1. In that case, construct a new virtual term that is
827 ** pTerm converted into an IN operator.
828 */
829 if( okToChngToIN ){
830 Expr *pDup; /* A transient duplicate expression */
831 ExprList *pList = 0; /* The RHS of the IN operator */
832 Expr *pLeft = 0; /* The LHS of the IN operator */
833 Expr *pNew; /* The complete IN operator */
834
835 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
836 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
837 assert( pOrTerm->eOperator & WO_EQ );
838 assert( pOrTerm->leftCursor==iCursor );
839 assert( pOrTerm->u.leftColumn==iColumn );
840 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
841 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
842 pLeft = pOrTerm->pExpr->pLeft;
843 }
844 assert( pLeft!=0 );
845 pDup = sqlite3ExprDup(db, pLeft, 0);
drhabfd35e2016-12-06 22:47:23 +0000846 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
drh6c1f4ef2015-06-08 14:23:15 +0000847 if( pNew ){
848 int idxNew;
849 transferJoinMarkings(pNew, pExpr);
850 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
851 pNew->x.pList = pList;
852 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
853 testcase( idxNew==0 );
854 exprAnalyze(pSrc, pWC, idxNew);
855 pTerm = &pWC->a[idxTerm];
856 markTermAsChild(pWC, idxNew, idxTerm);
857 }else{
858 sqlite3ExprListDelete(db, pList);
859 }
drh6c1f4ef2015-06-08 14:23:15 +0000860 }
861 }
862}
863#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
864
865/*
866** We already know that pExpr is a binary operator where both operands are
867** column references. This routine checks to see if pExpr is an equivalence
868** relation:
869** 1. The SQLITE_Transitive optimization must be enabled
870** 2. Must be either an == or an IS operator
871** 3. Not originating in the ON clause of an OUTER JOIN
872** 4. The affinities of A and B must be compatible
873** 5a. Both operands use the same collating sequence OR
874** 5b. The overall collating sequence is BINARY
875** If this routine returns TRUE, that means that the RHS can be substituted
876** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
877** This is an optimization. No harm comes from returning 0. But if 1 is
878** returned when it should not be, then incorrect answers might result.
879*/
880static int termIsEquivalence(Parse *pParse, Expr *pExpr){
881 char aff1, aff2;
882 CollSeq *pColl;
drh6c1f4ef2015-06-08 14:23:15 +0000883 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
884 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
885 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
886 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
887 aff2 = sqlite3ExprAffinity(pExpr->pRight);
888 if( aff1!=aff2
889 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
890 ){
891 return 0;
892 }
893 pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
894 if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
drh70efa842017-09-28 01:58:23 +0000895 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
drh6c1f4ef2015-06-08 14:23:15 +0000896}
897
898/*
899** Recursively walk the expressions of a SELECT statement and generate
900** a bitmask indicating which tables are used in that expression
901** tree.
902*/
903static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
904 Bitmask mask = 0;
905 while( pS ){
906 SrcList *pSrc = pS->pSrc;
907 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
908 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
909 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
910 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
911 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
912 if( ALWAYS(pSrc!=0) ){
913 int i;
914 for(i=0; i<pSrc->nSrc; i++){
915 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
916 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
drh33f763d2018-01-26 22:41:59 +0000917 if( pSrc->a[i].fg.isTabFunc ){
918 mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
919 }
drh6c1f4ef2015-06-08 14:23:15 +0000920 }
921 }
922 pS = pS->pPrior;
923 }
924 return mask;
925}
926
927/*
drh47991422015-08-31 15:58:06 +0000928** Expression pExpr is one operand of a comparison operator that might
929** be useful for indexing. This routine checks to see if pExpr appears
930** in any index. Return TRUE (1) if pExpr is an indexed term and return
drhe97c9ff2017-04-11 18:06:48 +0000931** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
932** number of the table that is indexed and aiCurCol[1] to the column number
drh8d25cb92016-08-19 19:58:06 +0000933** of the column that is indexed, or XN_EXPR (-2) if an expression is being
934** indexed.
drh47991422015-08-31 15:58:06 +0000935**
936** If pExpr is a TK_COLUMN column reference, then this routine always returns
937** true even if that particular column is not indexed, because the column
938** might be added to an automatic index later.
939*/
drhe97c9ff2017-04-11 18:06:48 +0000940static SQLITE_NOINLINE int exprMightBeIndexed2(
drh47991422015-08-31 15:58:06 +0000941 SrcList *pFrom, /* The FROM clause */
942 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
drhe97c9ff2017-04-11 18:06:48 +0000943 int *aiCurCol, /* Write the referenced table cursor and column here */
944 Expr *pExpr /* An operand of a comparison operator */
drh47991422015-08-31 15:58:06 +0000945){
946 Index *pIdx;
947 int i;
948 int iCur;
drhe97c9ff2017-04-11 18:06:48 +0000949 for(i=0; mPrereq>1; i++, mPrereq>>=1){}
950 iCur = pFrom->a[i].iCursor;
951 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
952 if( pIdx->aColExpr==0 ) continue;
953 for(i=0; i<pIdx->nKeyCol; i++){
954 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
955 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
956 aiCurCol[0] = iCur;
957 aiCurCol[1] = XN_EXPR;
958 return 1;
959 }
960 }
961 }
962 return 0;
963}
964static int exprMightBeIndexed(
965 SrcList *pFrom, /* The FROM clause */
966 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
967 int *aiCurCol, /* Write the referenced table cursor & column here */
968 Expr *pExpr, /* An operand of a comparison operator */
969 int op /* The specific comparison operator */
970){
dan71c57db2016-07-09 20:23:55 +0000971 /* If this expression is a vector to the left or right of a
972 ** inequality constraint (>, <, >= or <=), perform the processing
973 ** on the first element of the vector. */
974 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
drh64bcb8c2016-08-26 03:42:57 +0000975 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
976 assert( op<=TK_GE );
977 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
dan71c57db2016-07-09 20:23:55 +0000978 pExpr = pExpr->x.pList->a[0].pExpr;
979 }
980
drh47991422015-08-31 15:58:06 +0000981 if( pExpr->op==TK_COLUMN ){
drhe97c9ff2017-04-11 18:06:48 +0000982 aiCurCol[0] = pExpr->iTable;
983 aiCurCol[1] = pExpr->iColumn;
drh47991422015-08-31 15:58:06 +0000984 return 1;
985 }
986 if( mPrereq==0 ) return 0; /* No table references */
987 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
drhe97c9ff2017-04-11 18:06:48 +0000988 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
drh47991422015-08-31 15:58:06 +0000989}
990
dan870a0702016-08-01 16:37:43 +0000991/*
drh6c1f4ef2015-06-08 14:23:15 +0000992** The input to this routine is an WhereTerm structure with only the
993** "pExpr" field filled in. The job of this routine is to analyze the
994** subexpression and populate all the other fields of the WhereTerm
995** structure.
996**
997** If the expression is of the form "<expr> <op> X" it gets commuted
998** to the standard form of "X <op> <expr>".
999**
1000** If the expression is of the form "X <op> Y" where both X and Y are
1001** columns, then the original expression is unchanged and a new virtual
1002** term of the form "Y <op> X" is added to the WHERE clause and
1003** analyzed separately. The original term is marked with TERM_COPIED
1004** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1005** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1006** is a commuted copy of a prior term.) The original term has nChild=1
1007** and the copy has idxParent set to the index of the original term.
1008*/
1009static void exprAnalyze(
1010 SrcList *pSrc, /* the FROM clause */
1011 WhereClause *pWC, /* the WHERE clause */
1012 int idxTerm /* Index of the term to be analyzed */
1013){
1014 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1015 WhereTerm *pTerm; /* The term to be analyzed */
1016 WhereMaskSet *pMaskSet; /* Set of table index masks */
1017 Expr *pExpr; /* The expression to be analyzed */
1018 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1019 Bitmask prereqAll; /* Prerequesites of pExpr */
1020 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
1021 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1022 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1023 int noCase = 0; /* uppercase equivalent to lowercase */
1024 int op; /* Top-level operator. pExpr->op */
1025 Parse *pParse = pWInfo->pParse; /* Parsing context */
1026 sqlite3 *db = pParse->db; /* Database connection */
mistachkin53be36b2017-11-03 06:45:37 +00001027 unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
drhd9bcb322017-01-10 15:08:06 +00001028 int nLeft; /* Number of elements on left side vector */
drh6c1f4ef2015-06-08 14:23:15 +00001029
1030 if( db->mallocFailed ){
1031 return;
1032 }
1033 pTerm = &pWC->a[idxTerm];
1034 pMaskSet = &pWInfo->sMaskSet;
1035 pExpr = pTerm->pExpr;
1036 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1037 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
1038 op = pExpr->op;
1039 if( op==TK_IN ){
1040 assert( pExpr->pRight==0 );
dan7b35a772016-07-28 19:47:15 +00001041 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
drh6c1f4ef2015-06-08 14:23:15 +00001042 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1043 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
1044 }else{
1045 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
1046 }
1047 }else if( op==TK_ISNULL ){
1048 pTerm->prereqRight = 0;
1049 }else{
1050 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
1051 }
dand3930b12017-07-10 15:17:30 +00001052 pMaskSet->bVarSelect = 0;
drh6c1f4ef2015-06-08 14:23:15 +00001053 prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
dand3930b12017-07-10 15:17:30 +00001054 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
drh6c1f4ef2015-06-08 14:23:15 +00001055 if( ExprHasProperty(pExpr, EP_FromJoin) ){
1056 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
1057 prereqAll |= x;
1058 extraRight = x-1; /* ON clause terms may not be used with an index
1059 ** on left table of a LEFT JOIN. Ticket #3015 */
drh8e36ddd2017-01-10 17:33:43 +00001060 if( (prereqAll>>1)>=x ){
1061 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
1062 return;
1063 }
drh6c1f4ef2015-06-08 14:23:15 +00001064 }
1065 pTerm->prereqAll = prereqAll;
1066 pTerm->leftCursor = -1;
1067 pTerm->iParent = -1;
1068 pTerm->eOperator = 0;
1069 if( allowedOp(op) ){
drhe97c9ff2017-04-11 18:06:48 +00001070 int aiCurCol[2];
drh6c1f4ef2015-06-08 14:23:15 +00001071 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1072 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
1073 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
dan8da209b2016-07-26 18:06:08 +00001074
dan145b4ea2016-07-29 18:12:12 +00001075 if( pTerm->iField>0 ){
1076 assert( op==TK_IN );
dan8da209b2016-07-26 18:06:08 +00001077 assert( pLeft->op==TK_VECTOR );
1078 pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
1079 }
1080
drhe97c9ff2017-04-11 18:06:48 +00001081 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
1082 pTerm->leftCursor = aiCurCol[0];
1083 pTerm->u.leftColumn = aiCurCol[1];
drh6860e6f2015-08-27 18:24:02 +00001084 pTerm->eOperator = operatorMask(op) & opMask;
drh6c1f4ef2015-06-08 14:23:15 +00001085 }
1086 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh47991422015-08-31 15:58:06 +00001087 if( pRight
drhe97c9ff2017-04-11 18:06:48 +00001088 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
drh47991422015-08-31 15:58:06 +00001089 ){
drh6c1f4ef2015-06-08 14:23:15 +00001090 WhereTerm *pNew;
1091 Expr *pDup;
1092 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
dan145b4ea2016-07-29 18:12:12 +00001093 assert( pTerm->iField==0 );
drh6c1f4ef2015-06-08 14:23:15 +00001094 if( pTerm->leftCursor>=0 ){
1095 int idxNew;
1096 pDup = sqlite3ExprDup(db, pExpr, 0);
1097 if( db->mallocFailed ){
1098 sqlite3ExprDelete(db, pDup);
1099 return;
1100 }
1101 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1102 if( idxNew==0 ) return;
1103 pNew = &pWC->a[idxNew];
1104 markTermAsChild(pWC, idxNew, idxTerm);
1105 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
1106 pTerm = &pWC->a[idxTerm];
1107 pTerm->wtFlags |= TERM_COPIED;
1108
1109 if( termIsEquivalence(pParse, pDup) ){
1110 pTerm->eOperator |= WO_EQUIV;
1111 eExtraOp = WO_EQUIV;
1112 }
1113 }else{
1114 pDup = pExpr;
1115 pNew = pTerm;
1116 }
1117 exprCommute(pParse, pDup);
drhe97c9ff2017-04-11 18:06:48 +00001118 pNew->leftCursor = aiCurCol[0];
1119 pNew->u.leftColumn = aiCurCol[1];
drh6c1f4ef2015-06-08 14:23:15 +00001120 testcase( (prereqLeft | extraRight) != prereqLeft );
1121 pNew->prereqRight = prereqLeft | extraRight;
1122 pNew->prereqAll = prereqAll;
1123 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1124 }
1125 }
1126
1127#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1128 /* If a term is the BETWEEN operator, create two new virtual terms
1129 ** that define the range that the BETWEEN implements. For example:
1130 **
1131 ** a BETWEEN b AND c
1132 **
1133 ** is converted into:
1134 **
1135 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1136 **
1137 ** The two new terms are added onto the end of the WhereClause object.
1138 ** The new terms are "dynamic" and are children of the original BETWEEN
1139 ** term. That means that if the BETWEEN term is coded, the children are
1140 ** skipped. Or, if the children are satisfied by an index, the original
1141 ** BETWEEN term is skipped.
1142 */
1143 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1144 ExprList *pList = pExpr->x.pList;
1145 int i;
1146 static const u8 ops[] = {TK_GE, TK_LE};
1147 assert( pList!=0 );
1148 assert( pList->nExpr==2 );
1149 for(i=0; i<2; i++){
1150 Expr *pNewExpr;
1151 int idxNew;
1152 pNewExpr = sqlite3PExpr(pParse, ops[i],
1153 sqlite3ExprDup(db, pExpr->pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001154 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001155 transferJoinMarkings(pNewExpr, pExpr);
1156 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1157 testcase( idxNew==0 );
1158 exprAnalyze(pSrc, pWC, idxNew);
1159 pTerm = &pWC->a[idxTerm];
1160 markTermAsChild(pWC, idxNew, idxTerm);
1161 }
1162 }
1163#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1164
1165#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1166 /* Analyze a term that is composed of two or more subterms connected by
1167 ** an OR operator.
1168 */
1169 else if( pExpr->op==TK_OR ){
1170 assert( pWC->op==TK_AND );
1171 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1172 pTerm = &pWC->a[idxTerm];
1173 }
1174#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1175
1176#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1177 /* Add constraints to reduce the search space on a LIKE or GLOB
1178 ** operator.
1179 **
1180 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1181 **
1182 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1183 **
1184 ** The last character of the prefix "abc" is incremented to form the
1185 ** termination condition "abd". If case is not significant (the default
1186 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1187 ** bound is made all lowercase so that the bounds also work when comparing
1188 ** BLOBs.
1189 */
1190 if( pWC->op==TK_AND
1191 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1192 ){
1193 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1194 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1195 Expr *pNewExpr1;
1196 Expr *pNewExpr2;
1197 int idxNew1;
1198 int idxNew2;
1199 const char *zCollSeqName; /* Name of collating sequence */
1200 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1201
1202 pLeft = pExpr->x.pList->a[1].pExpr;
1203 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1204
1205 /* Convert the lower bound to upper-case and the upper bound to
1206 ** lower-case (upper-case is less than lower-case in ASCII) so that
1207 ** the range constraints also work for BLOBs
1208 */
1209 if( noCase && !pParse->db->mallocFailed ){
1210 int i;
1211 char c;
1212 pTerm->wtFlags |= TERM_LIKE;
1213 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1214 pStr1->u.zToken[i] = sqlite3Toupper(c);
1215 pStr2->u.zToken[i] = sqlite3Tolower(c);
1216 }
1217 }
1218
1219 if( !db->mallocFailed ){
1220 u8 c, *pC; /* Last character before the first wildcard */
1221 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1222 c = *pC;
1223 if( noCase ){
1224 /* The point is to increment the last character before the first
1225 ** wildcard. But if we increment '@', that will push it into the
1226 ** alphabetic range where case conversions will mess up the
1227 ** inequality. To avoid this, make sure to also run the full
1228 ** LIKE on all candidate expressions by clearing the isComplete flag
1229 */
1230 if( c=='A'-1 ) isComplete = 0;
1231 c = sqlite3UpperToLower[c];
1232 }
1233 *pC = c + 1;
1234 }
1235 zCollSeqName = noCase ? "NOCASE" : "BINARY";
1236 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1237 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1238 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001239 pStr1);
drh6c1f4ef2015-06-08 14:23:15 +00001240 transferJoinMarkings(pNewExpr1, pExpr);
1241 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1242 testcase( idxNew1==0 );
1243 exprAnalyze(pSrc, pWC, idxNew1);
1244 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1245 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1246 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001247 pStr2);
drh6c1f4ef2015-06-08 14:23:15 +00001248 transferJoinMarkings(pNewExpr2, pExpr);
1249 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1250 testcase( idxNew2==0 );
1251 exprAnalyze(pSrc, pWC, idxNew2);
1252 pTerm = &pWC->a[idxTerm];
1253 if( isComplete ){
1254 markTermAsChild(pWC, idxNew1, idxTerm);
1255 markTermAsChild(pWC, idxNew2, idxTerm);
1256 }
1257 }
1258#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1259
1260#ifndef SQLITE_OMIT_VIRTUALTABLE
drh303a69b2017-09-11 19:47:37 +00001261 /* Add a WO_AUX auxiliary term to the constraint set if the
1262 ** current expression is of the form "column OP expr" where OP
1263 ** is an operator that gets passed into virtual tables but which is
1264 ** not normally optimized for ordinary tables. In other words, OP
1265 ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
drh6c1f4ef2015-06-08 14:23:15 +00001266 ** This information is used by the xBestIndex methods of
1267 ** virtual tables. The native query optimizer does not attempt
1268 ** to do anything with MATCH functions.
1269 */
dand03024d2017-09-09 19:41:12 +00001270 if( pWC->op==TK_AND ){
mistachkin53be36b2017-11-03 06:45:37 +00001271 Expr *pRight = 0, *pLeft = 0;
drh59155062018-05-26 18:03:48 +00001272 int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
drh303a69b2017-09-11 19:47:37 +00001273 while( res-- > 0 ){
dand03024d2017-09-09 19:41:12 +00001274 int idxNew;
1275 WhereTerm *pNewTerm;
1276 Bitmask prereqColumn, prereqExpr;
drh6c1f4ef2015-06-08 14:23:15 +00001277
dand03024d2017-09-09 19:41:12 +00001278 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1279 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1280 if( (prereqExpr & prereqColumn)==0 ){
1281 Expr *pNewExpr;
1282 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1283 0, sqlite3ExprDup(db, pRight, 0));
1284 if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
1285 ExprSetProperty(pNewExpr, EP_FromJoin);
1286 }
1287 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1288 testcase( idxNew==0 );
1289 pNewTerm = &pWC->a[idxNew];
1290 pNewTerm->prereqRight = prereqExpr;
1291 pNewTerm->leftCursor = pLeft->iTable;
1292 pNewTerm->u.leftColumn = pLeft->iColumn;
drh303a69b2017-09-11 19:47:37 +00001293 pNewTerm->eOperator = WO_AUX;
dand03024d2017-09-09 19:41:12 +00001294 pNewTerm->eMatchOp = eOp2;
1295 markTermAsChild(pWC, idxNew, idxTerm);
1296 pTerm = &pWC->a[idxTerm];
1297 pTerm->wtFlags |= TERM_COPIED;
1298 pNewTerm->prereqAll = pTerm->prereqAll;
dan210ec4c2017-06-27 16:39:01 +00001299 }
dand03024d2017-09-09 19:41:12 +00001300 SWAP(Expr*, pLeft, pRight);
drh6c1f4ef2015-06-08 14:23:15 +00001301 }
1302 }
1303#endif /* SQLITE_OMIT_VIRTUALTABLE */
1304
dan95a08c02016-08-02 16:18:35 +00001305 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
drh9e730f02016-08-20 12:00:05 +00001306 ** new terms for each component comparison - "a = ?" and "b = ?". The
1307 ** new terms completely replace the original vector comparison, which is
1308 ** no longer used.
1309 **
dan95a08c02016-08-02 16:18:35 +00001310 ** This is only required if at least one side of the comparison operation
1311 ** is not a sub-select. */
dan71c57db2016-07-09 20:23:55 +00001312 if( pWC->op==TK_AND
1313 && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
drhd9bcb322017-01-10 15:08:06 +00001314 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
1315 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
dan71c57db2016-07-09 20:23:55 +00001316 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
drhd9bcb322017-01-10 15:08:06 +00001317 || (pExpr->pRight->flags & EP_xIsSelect)==0)
1318 ){
drhb29e60c2016-09-05 12:02:34 +00001319 int i;
drhb29e60c2016-09-05 12:02:34 +00001320 for(i=0; i<nLeft; i++){
1321 int idxNew;
1322 Expr *pNew;
1323 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
1324 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
dan71c57db2016-07-09 20:23:55 +00001325
drhabfd35e2016-12-06 22:47:23 +00001326 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
drhc52496f2016-10-27 01:02:20 +00001327 transferJoinMarkings(pNew, pExpr);
drhb29e60c2016-09-05 12:02:34 +00001328 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
1329 exprAnalyze(pSrc, pWC, idxNew);
dan71c57db2016-07-09 20:23:55 +00001330 }
drhb29e60c2016-09-05 12:02:34 +00001331 pTerm = &pWC->a[idxTerm];
drhe28eb642018-02-18 17:50:03 +00001332 pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
drhb29e60c2016-09-05 12:02:34 +00001333 pTerm->eOperator = 0;
dan71c57db2016-07-09 20:23:55 +00001334 }
1335
dan95a08c02016-08-02 16:18:35 +00001336 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1337 ** a virtual term for each vector component. The expression object
1338 ** used by each such virtual term is pExpr (the full vector IN(...)
1339 ** expression). The WhereTerm.iField variable identifies the index within
drh14318072016-09-06 18:51:25 +00001340 ** the vector on the LHS that the virtual term represents.
1341 **
1342 ** This only works if the RHS is a simple SELECT, not a compound
1343 */
dan8da209b2016-07-26 18:06:08 +00001344 if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
1345 && pExpr->pLeft->op==TK_VECTOR
drh14318072016-09-06 18:51:25 +00001346 && pExpr->x.pSelect->pPrior==0
dan8da209b2016-07-26 18:06:08 +00001347 ){
1348 int i;
1349 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1350 int idxNew;
1351 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
1352 pWC->a[idxNew].iField = i+1;
1353 exprAnalyze(pSrc, pWC, idxNew);
1354 markTermAsChild(pWC, idxNew, idxTerm);
1355 }
1356 }
1357
drh6c1f4ef2015-06-08 14:23:15 +00001358#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1359 /* When sqlite_stat3 histogram data is available an operator of the
1360 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1361 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1362 ** virtual term of that form.
1363 **
1364 ** Note that the virtual term must be tagged with TERM_VNULL.
1365 */
1366 if( pExpr->op==TK_NOTNULL
1367 && pExpr->pLeft->op==TK_COLUMN
1368 && pExpr->pLeft->iColumn>=0
1369 && OptimizationEnabled(db, SQLITE_Stat34)
1370 ){
1371 Expr *pNewExpr;
1372 Expr *pLeft = pExpr->pLeft;
1373 int idxNew;
1374 WhereTerm *pNewTerm;
1375
1376 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1377 sqlite3ExprDup(db, pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001378 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001379
1380 idxNew = whereClauseInsert(pWC, pNewExpr,
1381 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1382 if( idxNew ){
1383 pNewTerm = &pWC->a[idxNew];
1384 pNewTerm->prereqRight = 0;
1385 pNewTerm->leftCursor = pLeft->iTable;
1386 pNewTerm->u.leftColumn = pLeft->iColumn;
1387 pNewTerm->eOperator = WO_GT;
1388 markTermAsChild(pWC, idxNew, idxTerm);
1389 pTerm = &pWC->a[idxTerm];
1390 pTerm->wtFlags |= TERM_COPIED;
1391 pNewTerm->prereqAll = pTerm->prereqAll;
1392 }
1393 }
1394#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1395
1396 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1397 ** an index for tables to the left of the join.
1398 */
drh0f85b2f2016-11-20 12:00:27 +00001399 testcase( pTerm!=&pWC->a[idxTerm] );
1400 pTerm = &pWC->a[idxTerm];
drh6c1f4ef2015-06-08 14:23:15 +00001401 pTerm->prereqRight |= extraRight;
1402}
1403
1404/***************************************************************************
1405** Routines with file scope above. Interface to the rest of the where.c
1406** subsystem follows.
1407***************************************************************************/
1408
1409/*
1410** This routine identifies subexpressions in the WHERE clause where
1411** each subexpression is separated by the AND operator or some other
1412** operator specified in the op parameter. The WhereClause structure
1413** is filled with pointers to subexpressions. For example:
1414**
1415** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1416** \________/ \_______________/ \________________/
1417** slot[0] slot[1] slot[2]
1418**
1419** The original WHERE clause in pExpr is unaltered. All this routine
1420** does is make slot[] entries point to substructure within pExpr.
1421**
1422** In the previous sentence and in the diagram, "slot[]" refers to
1423** the WhereClause.a[] array. The slot[] array grows as needed to contain
1424** all terms of the WHERE clause.
1425*/
1426void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1427 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1428 pWC->op = op;
1429 if( pE2==0 ) return;
1430 if( pE2->op!=op ){
1431 whereClauseInsert(pWC, pExpr, 0);
1432 }else{
1433 sqlite3WhereSplit(pWC, pE2->pLeft, op);
1434 sqlite3WhereSplit(pWC, pE2->pRight, op);
1435 }
1436}
1437
1438/*
1439** Initialize a preallocated WhereClause structure.
1440*/
1441void sqlite3WhereClauseInit(
1442 WhereClause *pWC, /* The WhereClause to be initialized */
1443 WhereInfo *pWInfo /* The WHERE processing context */
1444){
1445 pWC->pWInfo = pWInfo;
1446 pWC->pOuter = 0;
1447 pWC->nTerm = 0;
1448 pWC->nSlot = ArraySize(pWC->aStatic);
1449 pWC->a = pWC->aStatic;
1450}
1451
1452/*
1453** Deallocate a WhereClause structure. The WhereClause structure
drh62aaa6c2015-11-21 17:27:42 +00001454** itself is not freed. This routine is the inverse of
1455** sqlite3WhereClauseInit().
drh6c1f4ef2015-06-08 14:23:15 +00001456*/
1457void sqlite3WhereClauseClear(WhereClause *pWC){
1458 int i;
1459 WhereTerm *a;
1460 sqlite3 *db = pWC->pWInfo->pParse->db;
1461 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1462 if( a->wtFlags & TERM_DYNAMIC ){
1463 sqlite3ExprDelete(db, a->pExpr);
1464 }
1465 if( a->wtFlags & TERM_ORINFO ){
1466 whereOrInfoDelete(db, a->u.pOrInfo);
1467 }else if( a->wtFlags & TERM_ANDINFO ){
1468 whereAndInfoDelete(db, a->u.pAndInfo);
1469 }
1470 }
1471 if( pWC->a!=pWC->aStatic ){
1472 sqlite3DbFree(db, pWC->a);
1473 }
1474}
1475
1476
1477/*
1478** These routines walk (recursively) an expression tree and generate
1479** a bitmask indicating which tables are used in that expression
1480** tree.
1481*/
1482Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
drh93ca3932016-08-10 20:02:21 +00001483 Bitmask mask;
drh6c1f4ef2015-06-08 14:23:15 +00001484 if( p==0 ) return 0;
1485 if( p->op==TK_COLUMN ){
drhf43ce0b2017-05-25 00:08:48 +00001486 return sqlite3WhereGetMask(pMaskSet, p->iTable);
drh6c1f4ef2015-06-08 14:23:15 +00001487 }
drhf43ce0b2017-05-25 00:08:48 +00001488 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
drh93ca3932016-08-10 20:02:21 +00001489 assert( !ExprHasProperty(p, EP_TokenOnly) );
drh926957f2016-04-12 00:00:33 +00001490 if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
drhe24b92b2017-07-10 15:26:09 +00001491 if( p->pRight ){
1492 mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
1493 assert( p->x.pList==0 );
1494 }else if( ExprHasProperty(p, EP_xIsSelect) ){
dand3930b12017-07-10 15:17:30 +00001495 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
drh6c1f4ef2015-06-08 14:23:15 +00001496 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
drh926957f2016-04-12 00:00:33 +00001497 }else if( p->x.pList ){
drh6c1f4ef2015-06-08 14:23:15 +00001498 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1499 }
1500 return mask;
1501}
1502Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1503 int i;
1504 Bitmask mask = 0;
1505 if( pList ){
1506 for(i=0; i<pList->nExpr; i++){
1507 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1508 }
1509 }
1510 return mask;
1511}
1512
1513
1514/*
1515** Call exprAnalyze on all terms in a WHERE clause.
1516**
1517** Note that exprAnalyze() might add new virtual terms onto the
1518** end of the WHERE clause. We do not want to analyze these new
1519** virtual terms, so start analyzing at the end and work forward
1520** so that the added virtual terms are never processed.
1521*/
1522void sqlite3WhereExprAnalyze(
1523 SrcList *pTabList, /* the FROM clause */
1524 WhereClause *pWC /* the WHERE clause to be analyzed */
1525){
1526 int i;
1527 for(i=pWC->nTerm-1; i>=0; i--){
1528 exprAnalyze(pTabList, pWC, i);
1529 }
1530}
drh01d230c2015-08-19 17:11:37 +00001531
1532/*
1533** For table-valued-functions, transform the function arguments into
1534** new WHERE clause terms.
1535**
1536** Each function argument translates into an equality constraint against
1537** a HIDDEN column in the table.
1538*/
1539void sqlite3WhereTabFuncArgs(
1540 Parse *pParse, /* Parsing context */
1541 struct SrcList_item *pItem, /* The FROM clause term to process */
1542 WhereClause *pWC /* Xfer function arguments to here */
1543){
1544 Table *pTab;
1545 int j, k;
1546 ExprList *pArgs;
1547 Expr *pColRef;
1548 Expr *pTerm;
1549 if( pItem->fg.isTabFunc==0 ) return;
1550 pTab = pItem->pTab;
1551 assert( pTab!=0 );
1552 pArgs = pItem->u1.pFuncArg;
drh20292312015-11-21 13:24:46 +00001553 if( pArgs==0 ) return;
drh01d230c2015-08-19 17:11:37 +00001554 for(j=k=0; j<pArgs->nExpr; j++){
drh62aaa6c2015-11-21 17:27:42 +00001555 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
drh01d230c2015-08-19 17:11:37 +00001556 if( k>=pTab->nCol ){
drhd8b1bfc2015-08-20 23:21:34 +00001557 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
drh01d230c2015-08-19 17:11:37 +00001558 pTab->zName, j);
1559 return;
1560 }
drhe1c03b62016-09-23 20:59:31 +00001561 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
drh01d230c2015-08-19 17:11:37 +00001562 if( pColRef==0 ) return;
1563 pColRef->iTable = pItem->iCursor;
1564 pColRef->iColumn = k++;
drh1f2fc282015-08-21 17:14:48 +00001565 pColRef->pTab = pTab;
drh01d230c2015-08-19 17:11:37 +00001566 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
drhabfd35e2016-12-06 22:47:23 +00001567 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
drh01d230c2015-08-19 17:11:37 +00001568 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1569 }
1570}