blob: cc5fad4fd6801b3a13ac35a1fa671a402725f1d7 [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){
drh3d6bedf2018-09-19 14:54:38 +0000122 u16 expRight, expLeft;
123 assert( pExpr->eX==EX_Right );
124 expRight = (pExpr->x.pRight->flags & EP_Collate);
125 expLeft = (pExpr->pLeft->flags & EP_Collate);
drh6c1f4ef2015-06-08 14:23:15 +0000126 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
127 if( expRight==expLeft ){
128 /* Either X and Y both have COLLATE operator or neither do */
129 if( expRight ){
130 /* Both X and Y have COLLATE operators. Make sure X is always
131 ** used by clearing the EP_Collate flag from Y. */
drh3d6bedf2018-09-19 14:54:38 +0000132 pExpr->x.pRight->flags &= ~EP_Collate;
drh6c1f4ef2015-06-08 14:23:15 +0000133 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
134 /* Neither X nor Y have COLLATE operators, but X has a non-default
135 ** collating sequence. So add the EP_Collate marker on X to cause
136 ** it to be searched first. */
137 pExpr->pLeft->flags |= EP_Collate;
138 }
139 }
drh3d6bedf2018-09-19 14:54:38 +0000140 SWAP(Expr*,pExpr->x.pRight,pExpr->pLeft);
drh6c1f4ef2015-06-08 14:23:15 +0000141 if( pExpr->op>=TK_GT ){
142 assert( TK_LT==TK_GT+2 );
143 assert( TK_GE==TK_LE+2 );
144 assert( TK_GT>TK_EQ );
145 assert( TK_GT<TK_LE );
146 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
147 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
148 }
149}
150
151/*
152** Translate from TK_xx operator to WO_xx bitmask.
153*/
154static u16 operatorMask(int op){
155 u16 c;
156 assert( allowedOp(op) );
157 if( op==TK_IN ){
158 c = WO_IN;
159 }else if( op==TK_ISNULL ){
160 c = WO_ISNULL;
161 }else if( op==TK_IS ){
162 c = WO_IS;
163 }else{
164 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
165 c = (u16)(WO_EQ<<(op-TK_EQ));
166 }
167 assert( op!=TK_ISNULL || c==WO_ISNULL );
168 assert( op!=TK_IN || c==WO_IN );
169 assert( op!=TK_EQ || c==WO_EQ );
170 assert( op!=TK_LT || c==WO_LT );
171 assert( op!=TK_LE || c==WO_LE );
172 assert( op!=TK_GT || c==WO_GT );
173 assert( op!=TK_GE || c==WO_GE );
174 assert( op!=TK_IS || c==WO_IS );
175 return c;
176}
177
178
179#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
180/*
181** Check to see if the given expression is a LIKE or GLOB operator that
182** can be optimized using inequality constraints. Return TRUE if it is
183** so and false if not.
184**
185** In order for the operator to be optimizible, the RHS must be a string
186** literal that does not begin with a wildcard. The LHS must be a column
187** that may only be NULL, a string, or a BLOB, never a number. (This means
188** that virtual tables cannot participate in the LIKE optimization.) The
189** collating sequence for the column on the LHS must be appropriate for
190** the operator.
191*/
192static int isLikeOrGlob(
193 Parse *pParse, /* Parsing and code generating context */
194 Expr *pExpr, /* Test this expression */
195 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
196 int *pisComplete, /* True if the only wildcard is % in the last character */
197 int *pnoCase /* True if uppercase is equivalent to lowercase */
198){
drhad9f5152018-08-09 21:45:45 +0000199 const u8 *z = 0; /* String on RHS of LIKE operator */
drh6c1f4ef2015-06-08 14:23:15 +0000200 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
201 ExprList *pList; /* List of operands to the LIKE operator */
drhad9f5152018-08-09 21:45:45 +0000202 u8 c; /* One character in z[] */
drh6c1f4ef2015-06-08 14:23:15 +0000203 int cnt; /* Number of non-wildcard prefix characters */
drhad9f5152018-08-09 21:45:45 +0000204 u8 wc[4]; /* Wildcard characters */
drh6c1f4ef2015-06-08 14:23:15 +0000205 sqlite3 *db = pParse->db; /* Database connection */
206 sqlite3_value *pVal = 0;
207 int op; /* Opcode of pRight */
drhb8763632016-01-19 17:54:21 +0000208 int rc; /* Result code to return */
drh6c1f4ef2015-06-08 14:23:15 +0000209
drhad9f5152018-08-09 21:45:45 +0000210 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
drh6c1f4ef2015-06-08 14:23:15 +0000211 return 0;
212 }
213#ifdef SQLITE_EBCDIC
214 if( *pnoCase ) return 0;
215#endif
216 pList = pExpr->x.pList;
217 pLeft = pList->a[1].pExpr;
drh6c1f4ef2015-06-08 14:23:15 +0000218
219 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
220 op = pRight->op;
drh7df74752017-06-26 14:46:05 +0000221 if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
drh6c1f4ef2015-06-08 14:23:15 +0000222 Vdbe *pReprepare = pParse->pReprepare;
223 int iCol = pRight->iColumn;
224 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
225 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
drhb8313cc2017-08-08 21:30:43 +0000226 z = sqlite3_value_text(pVal);
drh6c1f4ef2015-06-08 14:23:15 +0000227 }
228 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
229 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
230 }else if( op==TK_STRING ){
drhb8313cc2017-08-08 21:30:43 +0000231 z = (u8*)pRight->u.zToken;
drh6c1f4ef2015-06-08 14:23:15 +0000232 }
233 if( z ){
drh1c84bd42017-02-10 21:37:57 +0000234
drh1d42ea72017-07-27 20:24:29 +0000235 /* Count the number of prefix characters prior to the first wildcard */
drh6c1f4ef2015-06-08 14:23:15 +0000236 cnt = 0;
237 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
238 cnt++;
drhf41a8d32017-08-11 03:47:21 +0000239 if( c==wc[3] && z[cnt]!=0 ) cnt++;
drh6c1f4ef2015-06-08 14:23:15 +0000240 }
drh1d42ea72017-07-27 20:24:29 +0000241
242 /* The optimization is possible only if (1) the pattern does not begin
243 ** with a wildcard and if (2) the non-wildcard prefix does not end with
dan6b4b8822018-07-02 15:03:50 +0000244 ** an (illegal 0xff) character, or (3) the pattern does not consist of
245 ** a single escape character. The second condition is necessary so
drh1d42ea72017-07-27 20:24:29 +0000246 ** that we can increment the prefix key to find an upper bound for the
dan6b4b8822018-07-02 15:03:50 +0000247 ** range search. The third is because the caller assumes that the pattern
248 ** consists of at least one character after all escapes have been
249 ** removed. */
250 if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
drh6c1f4ef2015-06-08 14:23:15 +0000251 Expr *pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000252
253 /* A "complete" match if the pattern ends with "*" or "%" */
drh6c1f4ef2015-06-08 14:23:15 +0000254 *pisComplete = c==wc[0] && z[cnt+1]==0;
drh1d42ea72017-07-27 20:24:29 +0000255
256 /* Get the pattern prefix. Remove all escapes from the prefix. */
drhb8313cc2017-08-08 21:30:43 +0000257 pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
drh1d42ea72017-07-27 20:24:29 +0000258 if( pPrefix ){
259 int iFrom, iTo;
260 char *zNew = pPrefix->u.zToken;
261 zNew[cnt] = 0;
262 for(iFrom=iTo=0; iFrom<cnt; iFrom++){
263 if( zNew[iFrom]==wc[3] ) iFrom++;
264 zNew[iTo++] = zNew[iFrom];
265 }
266 zNew[iTo] = 0;
drhb7a002f2018-09-10 12:40:57 +0000267
268 /* If the RHS begins with a digit or a minus sign, then the LHS must be
269 ** an ordinary column (not a virtual table column) with TEXT affinity.
270 ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
271 ** even though "lhs LIKE rhs" is true. But if the RHS does not start
272 ** with a digit or '-', then "lhs LIKE rhs" will always be false if
273 ** the LHS is numeric and so the optimization still works.
274 **
275 ** 2018-09-10 ticket c94369cae9b561b1f996d0054bfab11389f9d033
276 ** The RHS pattern must not be '/%' because the termination condition
277 ** will then become "x<'0'" and if the affinity is numeric, will then
278 ** be converted into "x<0", which is incorrect.
279 */
280 if( sqlite3Isdigit(zNew[0])
281 || zNew[0]=='-'
282 || (zNew[0]+1=='0' && iTo==1)
283 ){
284 if( pLeft->op!=TK_COLUMN
drh8477f7f2018-09-19 20:14:48 +0000285 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
286 || NEVER(pLeft->eX!=EX_Tab)
287 || IsVirtual(pLeft->x.pTab) /* Value might be numeric */
drhb7a002f2018-09-10 12:40:57 +0000288 ){
289 sqlite3ExprDelete(db, pPrefix);
290 sqlite3ValueFree(pVal);
291 return 0;
292 }
293 }
drh1d42ea72017-07-27 20:24:29 +0000294 }
drh6c1f4ef2015-06-08 14:23:15 +0000295 *ppPrefix = pPrefix;
drh1d42ea72017-07-27 20:24:29 +0000296
297 /* If the RHS pattern is a bound parameter, make arrangements to
298 ** reprepare the statement when that parameter is rebound */
drh6c1f4ef2015-06-08 14:23:15 +0000299 if( op==TK_VARIABLE ){
300 Vdbe *v = pParse->pVdbe;
301 sqlite3VdbeSetVarmask(v, pRight->iColumn);
302 if( *pisComplete && pRight->u.zToken[1] ){
303 /* If the rhs of the LIKE expression is a variable, and the current
304 ** value of the variable means there is no need to invoke the LIKE
305 ** function, then no OP_Variable will be added to the program.
306 ** This causes problems for the sqlite3_bind_parameter_name()
307 ** API. To work around them, add a dummy OP_Variable here.
308 */
309 int r1 = sqlite3GetTempReg(pParse);
310 sqlite3ExprCodeTarget(pParse, pRight, r1);
311 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
312 sqlite3ReleaseTempReg(pParse, r1);
313 }
314 }
315 }else{
316 z = 0;
317 }
318 }
319
drhb8763632016-01-19 17:54:21 +0000320 rc = (z!=0);
drh6c1f4ef2015-06-08 14:23:15 +0000321 sqlite3ValueFree(pVal);
drhb8763632016-01-19 17:54:21 +0000322 return rc;
drh6c1f4ef2015-06-08 14:23:15 +0000323}
324#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
325
326
327#ifndef SQLITE_OMIT_VIRTUALTABLE
328/*
drh303a69b2017-09-11 19:47:37 +0000329** Check to see if the pExpr expression is a form that needs to be passed
330** to the xBestIndex method of virtual tables. Forms of interest include:
drh6c1f4ef2015-06-08 14:23:15 +0000331**
drh303a69b2017-09-11 19:47:37 +0000332** Expression Virtual Table Operator
333** ----------------------- ---------------------------------
334** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
335** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
336** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
337** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
338** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
339** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
340** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
341** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
342** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
dan43970dd2015-11-24 17:39:01 +0000343**
drh303a69b2017-09-11 19:47:37 +0000344** In every case, "column" must be a column of a virtual table. If there
345** is a match, set *ppLeft to the "column" expression, set *ppRight to the
346** "expr" expression (even though in forms (6) and (8) the column is on the
347** right and the expression is on the left). Also set *peOp2 to the
348** appropriate virtual table operator. The return value is 1 or 2 if there
349** is a match. The usual return is 1, but if the RHS is also a column
350** of virtual table in forms (5) or (7) then return 2.
dand03024d2017-09-09 19:41:12 +0000351**
352** If the expression matches none of the patterns above, return 0.
drh6c1f4ef2015-06-08 14:23:15 +0000353*/
drh303a69b2017-09-11 19:47:37 +0000354static int isAuxiliaryVtabOperator(
drh59155062018-05-26 18:03:48 +0000355 sqlite3 *db, /* Parsing context */
dan07bdba82015-11-23 21:09:54 +0000356 Expr *pExpr, /* Test this expression */
dand03024d2017-09-09 19:41:12 +0000357 unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
358 Expr **ppLeft, /* Column expression to left of MATCH/op2 */
359 Expr **ppRight /* Expression to left of MATCH/op2 */
drh6c1f4ef2015-06-08 14:23:15 +0000360){
dand03024d2017-09-09 19:41:12 +0000361 if( pExpr->op==TK_FUNCTION ){
362 static const struct Op2 {
363 const char *zOp;
364 unsigned char eOp2;
365 } aOp[] = {
366 { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
367 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
368 { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
369 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
370 };
371 ExprList *pList;
372 Expr *pCol; /* Column reference */
373 int i;
drh6c1f4ef2015-06-08 14:23:15 +0000374
dand03024d2017-09-09 19:41:12 +0000375 pList = pExpr->x.pList;
376 if( pList==0 || pList->nExpr!=2 ){
377 return 0;
378 }
drh59155062018-05-26 18:03:48 +0000379
380 /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
381 ** virtual table on their second argument, which is the same as
382 ** the left-hand side operand in their in-fix form.
383 **
384 ** vtab_column MATCH expression
385 ** MATCH(expression,vtab_column)
386 */
dand03024d2017-09-09 19:41:12 +0000387 pCol = pList->a[1].pExpr;
drh8477f7f2018-09-19 20:14:48 +0000388 if( pCol->op==TK_COLUMN && pCol->eX==EX_Tab && IsVirtual(pCol->x.pTab) ){
drh59155062018-05-26 18:03:48 +0000389 for(i=0; i<ArraySize(aOp); i++){
390 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
391 *peOp2 = aOp[i].eOp2;
392 *ppRight = pList->a[0].pExpr;
393 *ppLeft = pCol;
394 return 1;
395 }
396 }
dand03024d2017-09-09 19:41:12 +0000397 }
drh59155062018-05-26 18:03:48 +0000398
399 /* We can also match against the first column of overloaded
400 ** functions where xFindFunction returns a value of at least
401 ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
402 **
403 ** OVERLOADED(vtab_column,expression)
404 **
405 ** Historically, xFindFunction expected to see lower-case function
406 ** names. But for this use case, xFindFunction is expected to deal
407 ** with function names in an arbitrary case.
408 */
409 pCol = pList->a[0].pExpr;
drh8477f7f2018-09-19 20:14:48 +0000410 if( pCol->op==TK_COLUMN && pCol->eX==EX_Tab && IsVirtual(pCol->x.pTab) ){
drh59155062018-05-26 18:03:48 +0000411 sqlite3_vtab *pVtab;
412 sqlite3_module *pMod;
413 void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
414 void *pNotUsed;
drh8477f7f2018-09-19 20:14:48 +0000415 pVtab = sqlite3GetVTable(db, pCol->x.pTab)->pVtab;
drh59155062018-05-26 18:03:48 +0000416 assert( pVtab!=0 );
417 assert( pVtab->pModule!=0 );
418 pMod = (sqlite3_module *)pVtab->pModule;
419 if( pMod->xFindFunction!=0 ){
420 i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
421 if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
422 *peOp2 = i;
423 *ppRight = pList->a[1].pExpr;
424 *ppLeft = pCol;
425 return 1;
426 }
dand03024d2017-09-09 19:41:12 +0000427 }
428 }
429 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
430 int res = 0;
431 Expr *pLeft = pExpr->pLeft;
drh8477f7f2018-09-19 20:14:48 +0000432 Expr *pRight = 0;
433 if( pLeft->op==TK_COLUMN && pLeft->eX==EX_Tab && IsVirtual(pLeft->x.pTab) ){
dand03024d2017-09-09 19:41:12 +0000434 res++;
435 }
drh8477f7f2018-09-19 20:14:48 +0000436 if( pExpr->eX==EX_Right && (pRight = pExpr->x.pRight)->op==TK_COLUMN
437 && pRight->eX==EX_Tab && IsVirtual(pRight->x.pTab) ){
dand03024d2017-09-09 19:41:12 +0000438 res++;
439 SWAP(Expr*, pLeft, pRight);
440 }
441 *ppLeft = pLeft;
442 *ppRight = pRight;
443 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
444 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
445 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
446 return res;
dan07bdba82015-11-23 21:09:54 +0000447 }
448 return 0;
drh6c1f4ef2015-06-08 14:23:15 +0000449}
450#endif /* SQLITE_OMIT_VIRTUALTABLE */
451
452/*
453** If the pBase expression originated in the ON or USING clause of
454** a join, then transfer the appropriate markings over to derived.
455*/
456static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
457 if( pDerived ){
458 pDerived->flags |= pBase->flags & EP_FromJoin;
459 pDerived->iRightJoinTable = pBase->iRightJoinTable;
460 }
461}
462
463/*
464** Mark term iChild as being a child of term iParent
465*/
466static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
467 pWC->a[iChild].iParent = iParent;
468 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
469 pWC->a[iParent].nChild++;
470}
471
472/*
473** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
474** a conjunction, then return just pTerm when N==0. If N is exceeds
475** the number of available subterms, return NULL.
476*/
477static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
478 if( pTerm->eOperator!=WO_AND ){
479 return N==0 ? pTerm : 0;
480 }
481 if( N<pTerm->u.pAndInfo->wc.nTerm ){
482 return &pTerm->u.pAndInfo->wc.a[N];
483 }
484 return 0;
485}
486
487/*
488** Subterms pOne and pTwo are contained within WHERE clause pWC. The
489** two subterms are in disjunction - they are OR-ed together.
490**
491** If these two terms are both of the form: "A op B" with the same
492** A and B values but different operators and if the operators are
493** compatible (if one is = and the other is <, for example) then
494** add a new virtual AND term to pWC that is the combination of the
495** two.
496**
497** Some examples:
498**
499** x<y OR x=y --> x<=y
500** x=y OR x=y --> x=y
501** x<=y OR x<y --> x<=y
502**
503** The following is NOT generated:
504**
505** x<y OR x>y --> x!=y
506*/
507static void whereCombineDisjuncts(
508 SrcList *pSrc, /* the FROM clause */
509 WhereClause *pWC, /* The complete WHERE clause */
510 WhereTerm *pOne, /* First disjunct */
511 WhereTerm *pTwo /* Second disjunct */
512){
513 u16 eOp = pOne->eOperator | pTwo->eOperator;
514 sqlite3 *db; /* Database connection (for malloc) */
515 Expr *pNew; /* New virtual expression */
516 int op; /* Operator for the combined expression */
517 int idxNew; /* Index in pWC of the next virtual term */
518
519 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
520 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
521 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
522 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
drh3d6bedf2018-09-19 14:54:38 +0000523 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->eX==EX_Right );
524 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->eX==EX_Right );
525 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ){
526 return;
527 }
528 if( sqlite3ExprCompare(0,pOne->pExpr->x.pRight, pTwo->pExpr->x.pRight,-1) ){
529 return;
530 }
drh6c1f4ef2015-06-08 14:23:15 +0000531 /* If we reach this point, it means the two subterms can be combined */
532 if( (eOp & (eOp-1))!=0 ){
533 if( eOp & (WO_LT|WO_LE) ){
534 eOp = WO_LE;
535 }else{
536 assert( eOp & (WO_GT|WO_GE) );
537 eOp = WO_GE;
538 }
539 }
540 db = pWC->pWInfo->pParse->db;
541 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
542 if( pNew==0 ) return;
543 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
544 pNew->op = op;
545 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
546 exprAnalyze(pSrc, pWC, idxNew);
547}
548
549#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
550/*
551** Analyze a term that consists of two or more OR-connected
552** subterms. So in:
553**
554** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
555** ^^^^^^^^^^^^^^^^^^^^
556**
557** This routine analyzes terms such as the middle term in the above example.
558** A WhereOrTerm object is computed and attached to the term under
559** analysis, regardless of the outcome of the analysis. Hence:
560**
561** WhereTerm.wtFlags |= TERM_ORINFO
562** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
563**
564** The term being analyzed must have two or more of OR-connected subterms.
565** A single subterm might be a set of AND-connected sub-subterms.
566** Examples of terms under analysis:
567**
568** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
569** (B) x=expr1 OR expr2=x OR x=expr3
570** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
571** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
572** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
573** (F) x>A OR (x=A AND y>=B)
574**
575** CASE 1:
576**
577** If all subterms are of the form T.C=expr for some single column of C and
578** a single table T (as shown in example B above) then create a new virtual
579** term that is an equivalent IN expression. In other words, if the term
580** being analyzed is:
581**
582** x = expr1 OR expr2 = x OR x = expr3
583**
584** then create a new virtual term like this:
585**
586** x IN (expr1,expr2,expr3)
587**
588** CASE 2:
589**
590** If there are exactly two disjuncts and one side has x>A and the other side
591** has x=A (for the same x and A) then add a new virtual conjunct term to the
592** WHERE clause of the form "x>=A". Example:
593**
594** x>A OR (x=A AND y>B) adds: x>=A
595**
596** The added conjunct can sometimes be helpful in query planning.
597**
598** CASE 3:
599**
600** If all subterms are indexable by a single table T, then set
601**
602** WhereTerm.eOperator = WO_OR
603** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
604**
605** A subterm is "indexable" if it is of the form
606** "T.C <op> <expr>" where C is any column of table T and
607** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
608** A subterm is also indexable if it is an AND of two or more
609** subsubterms at least one of which is indexable. Indexable AND
610** subterms have their eOperator set to WO_AND and they have
611** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
612**
613** From another point of view, "indexable" means that the subterm could
614** potentially be used with an index if an appropriate index exists.
615** This analysis does not consider whether or not the index exists; that
616** is decided elsewhere. This analysis only looks at whether subterms
617** appropriate for indexing exist.
618**
619** All examples A through E above satisfy case 3. But if a term
620** also satisfies case 1 (such as B) we know that the optimizer will
621** always prefer case 1, so in that case we pretend that case 3 is not
622** satisfied.
623**
624** It might be the case that multiple tables are indexable. For example,
625** (E) above is indexable on tables P, Q, and R.
626**
627** Terms that satisfy case 3 are candidates for lookup by using
628** separate indices to find rowids for each subterm and composing
629** the union of all rowids using a RowSet object. This is similar
630** to "bitmap indices" in other database engines.
631**
632** OTHERWISE:
633**
634** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
635** zero. This term is not useful for search.
636*/
637static void exprAnalyzeOrTerm(
638 SrcList *pSrc, /* the FROM clause */
639 WhereClause *pWC, /* the complete WHERE clause */
640 int idxTerm /* Index of the OR-term to be analyzed */
641){
642 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
643 Parse *pParse = pWInfo->pParse; /* Parser context */
644 sqlite3 *db = pParse->db; /* Database connection */
645 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
646 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
647 int i; /* Loop counters */
648 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
649 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
650 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
651 Bitmask chngToIN; /* Tables that might satisfy case 1 */
652 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
653
654 /*
655 ** Break the OR clause into its separate subterms. The subterms are
656 ** stored in a WhereClause structure containing within the WhereOrInfo
657 ** object that is attached to the original OR clause term.
658 */
659 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
660 assert( pExpr->op==TK_OR );
661 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
662 if( pOrInfo==0 ) return;
663 pTerm->wtFlags |= TERM_ORINFO;
664 pOrWc = &pOrInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000665 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000666 sqlite3WhereClauseInit(pOrWc, pWInfo);
667 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
668 sqlite3WhereExprAnalyze(pSrc, pOrWc);
669 if( db->mallocFailed ) return;
670 assert( pOrWc->nTerm>=2 );
671
672 /*
673 ** Compute the set of tables that might satisfy cases 1 or 3.
674 */
675 indexable = ~(Bitmask)0;
676 chngToIN = ~(Bitmask)0;
677 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
678 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
679 WhereAndInfo *pAndInfo;
680 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
681 chngToIN = 0;
drh575fad62016-02-05 13:38:36 +0000682 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
drh6c1f4ef2015-06-08 14:23:15 +0000683 if( pAndInfo ){
684 WhereClause *pAndWC;
685 WhereTerm *pAndTerm;
686 int j;
687 Bitmask b = 0;
688 pOrTerm->u.pAndInfo = pAndInfo;
689 pOrTerm->wtFlags |= TERM_ANDINFO;
690 pOrTerm->eOperator = WO_AND;
691 pAndWC = &pAndInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000692 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000693 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
694 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
695 sqlite3WhereExprAnalyze(pSrc, pAndWC);
696 pAndWC->pOuter = pWC;
drh6c1f4ef2015-06-08 14:23:15 +0000697 if( !db->mallocFailed ){
698 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
699 assert( pAndTerm->pExpr );
dandbd2dcb2016-05-28 18:53:55 +0000700 if( allowedOp(pAndTerm->pExpr->op)
drh303a69b2017-09-11 19:47:37 +0000701 || pAndTerm->eOperator==WO_AUX
dandbd2dcb2016-05-28 18:53:55 +0000702 ){
drh6c1f4ef2015-06-08 14:23:15 +0000703 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
704 }
705 }
706 }
707 indexable &= b;
708 }
709 }else if( pOrTerm->wtFlags & TERM_COPIED ){
710 /* Skip this term for now. We revisit it when we process the
711 ** corresponding TERM_VIRTUAL term */
712 }else{
713 Bitmask b;
714 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
715 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
716 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
717 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
718 }
719 indexable &= b;
720 if( (pOrTerm->eOperator & WO_EQ)==0 ){
721 chngToIN = 0;
722 }else{
723 chngToIN &= b;
724 }
725 }
726 }
727
728 /*
729 ** Record the set of tables that satisfy case 3. The set might be
730 ** empty.
731 */
732 pOrInfo->indexable = indexable;
drhda230bd2018-06-09 00:09:58 +0000733 if( indexable ){
734 pTerm->eOperator = WO_OR;
735 pWC->hasOr = 1;
736 }else{
737 pTerm->eOperator = WO_OR;
738 }
drh6c1f4ef2015-06-08 14:23:15 +0000739
740 /* For a two-way OR, attempt to implementation case 2.
741 */
742 if( indexable && pOrWc->nTerm==2 ){
743 int iOne = 0;
744 WhereTerm *pOne;
745 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
746 int iTwo = 0;
747 WhereTerm *pTwo;
748 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
749 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
750 }
751 }
752 }
753
754 /*
755 ** chngToIN holds a set of tables that *might* satisfy case 1. But
756 ** we have to do some additional checking to see if case 1 really
757 ** is satisfied.
758 **
759 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
760 ** that there is no possibility of transforming the OR clause into an
761 ** IN operator because one or more terms in the OR clause contain
762 ** something other than == on a column in the single table. The 1-bit
763 ** case means that every term of the OR clause is of the form
764 ** "table.column=expr" for some single table. The one bit that is set
765 ** will correspond to the common table. We still need to check to make
766 ** sure the same column is used on all terms. The 2-bit case is when
767 ** the all terms are of the form "table1.column=table2.column". It
768 ** might be possible to form an IN operator with either table1.column
769 ** or table2.column as the LHS if either is common to every term of
770 ** the OR clause.
771 **
772 ** Note that terms of the form "table.column1=table.column2" (the
773 ** same table on both sizes of the ==) cannot be optimized.
774 */
775 if( chngToIN ){
776 int okToChngToIN = 0; /* True if the conversion to IN is valid */
777 int iColumn = -1; /* Column index on lhs of IN operator */
778 int iCursor = -1; /* Table cursor common to all terms */
779 int j = 0; /* Loop counter */
780
781 /* Search for a table and column that appears on one side or the
782 ** other of the == operator in every subterm. That table and column
783 ** will be recorded in iCursor and iColumn. There might not be any
784 ** such table and column. Set okToChngToIN if an appropriate table
785 ** and column is found but leave okToChngToIN false if not found.
786 */
787 for(j=0; j<2 && !okToChngToIN; j++){
788 pOrTerm = pOrWc->a;
789 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
790 assert( pOrTerm->eOperator & WO_EQ );
791 pOrTerm->wtFlags &= ~TERM_OR_OK;
792 if( pOrTerm->leftCursor==iCursor ){
793 /* This is the 2-bit case and we are on the second iteration and
794 ** current term is from the first iteration. So skip this term. */
795 assert( j==1 );
796 continue;
797 }
798 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
799 pOrTerm->leftCursor))==0 ){
800 /* This term must be of the form t1.a==t2.b where t2 is in the
801 ** chngToIN set but t1 is not. This term will be either preceded
802 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
803 ** and use its inversion. */
804 testcase( pOrTerm->wtFlags & TERM_COPIED );
805 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
806 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
807 continue;
808 }
809 iColumn = pOrTerm->u.leftColumn;
810 iCursor = pOrTerm->leftCursor;
811 break;
812 }
813 if( i<0 ){
814 /* No candidate table+column was found. This can only occur
815 ** on the second iteration */
816 assert( j==1 );
817 assert( IsPowerOfTwo(chngToIN) );
818 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
819 break;
820 }
821 testcase( j==1 );
822
823 /* We have found a candidate table and column. Check to see if that
824 ** table and column is common to every term in the OR clause */
825 okToChngToIN = 1;
826 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
827 assert( pOrTerm->eOperator & WO_EQ );
828 if( pOrTerm->leftCursor!=iCursor ){
829 pOrTerm->wtFlags &= ~TERM_OR_OK;
830 }else if( pOrTerm->u.leftColumn!=iColumn ){
831 okToChngToIN = 0;
832 }else{
833 int affLeft, affRight;
834 /* If the right-hand side is also a column, then the affinities
835 ** of both right and left sides must be such that no type
836 ** conversions are required on the right. (Ticket #2249)
837 */
drh3d6bedf2018-09-19 14:54:38 +0000838 assert( pOrTerm->pExpr->eX==EX_Right );
839 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->x.pRight);
drh6c1f4ef2015-06-08 14:23:15 +0000840 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
841 if( affRight!=0 && affRight!=affLeft ){
842 okToChngToIN = 0;
843 }else{
844 pOrTerm->wtFlags |= TERM_OR_OK;
845 }
846 }
847 }
848 }
849
850 /* At this point, okToChngToIN is true if original pTerm satisfies
851 ** case 1. In that case, construct a new virtual term that is
852 ** pTerm converted into an IN operator.
853 */
854 if( okToChngToIN ){
855 Expr *pDup; /* A transient duplicate expression */
856 ExprList *pList = 0; /* The RHS of the IN operator */
857 Expr *pLeft = 0; /* The LHS of the IN operator */
858 Expr *pNew; /* The complete IN operator */
859
860 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
861 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
862 assert( pOrTerm->eOperator & WO_EQ );
863 assert( pOrTerm->leftCursor==iCursor );
864 assert( pOrTerm->u.leftColumn==iColumn );
drh3d6bedf2018-09-19 14:54:38 +0000865 assert( pOrTerm->pExpr->eX==EX_Right );
866 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->x.pRight, 0);
drh6c1f4ef2015-06-08 14:23:15 +0000867 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
868 pLeft = pOrTerm->pExpr->pLeft;
869 }
870 assert( pLeft!=0 );
871 pDup = sqlite3ExprDup(db, pLeft, 0);
drhabfd35e2016-12-06 22:47:23 +0000872 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
drh3b3c86a2018-09-18 21:35:31 +0000873 if( pNew && pList ){
drh6c1f4ef2015-06-08 14:23:15 +0000874 int idxNew;
875 transferJoinMarkings(pNew, pExpr);
drh3b3c86a2018-09-18 21:35:31 +0000876 assert( pNew->eX==EX_None );
877 pNew->eX = EX_List;
drh6c1f4ef2015-06-08 14:23:15 +0000878 pNew->x.pList = pList;
879 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
880 testcase( idxNew==0 );
881 exprAnalyze(pSrc, pWC, idxNew);
drh3b3c86a2018-09-18 21:35:31 +0000882 /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm used again */
drh6c1f4ef2015-06-08 14:23:15 +0000883 markTermAsChild(pWC, idxNew, idxTerm);
884 }else{
885 sqlite3ExprListDelete(db, pList);
drh3b3c86a2018-09-18 21:35:31 +0000886 sqlite3ExprDelete(db, pNew);
drh6c1f4ef2015-06-08 14:23:15 +0000887 }
drh6c1f4ef2015-06-08 14:23:15 +0000888 }
889 }
890}
891#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
892
893/*
894** We already know that pExpr is a binary operator where both operands are
895** column references. This routine checks to see if pExpr is an equivalence
896** relation:
897** 1. The SQLITE_Transitive optimization must be enabled
898** 2. Must be either an == or an IS operator
899** 3. Not originating in the ON clause of an OUTER JOIN
900** 4. The affinities of A and B must be compatible
901** 5a. Both operands use the same collating sequence OR
902** 5b. The overall collating sequence is BINARY
903** If this routine returns TRUE, that means that the RHS can be substituted
904** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
905** This is an optimization. No harm comes from returning 0. But if 1 is
906** returned when it should not be, then incorrect answers might result.
907*/
908static int termIsEquivalence(Parse *pParse, Expr *pExpr){
909 char aff1, aff2;
910 CollSeq *pColl;
drh6c1f4ef2015-06-08 14:23:15 +0000911 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
912 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
913 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
914 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
drh3d6bedf2018-09-19 14:54:38 +0000915 assert( pExpr->eX==EX_Right );
916 aff2 = sqlite3ExprAffinity(pExpr->x.pRight);
drh6c1f4ef2015-06-08 14:23:15 +0000917 if( aff1!=aff2
918 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
919 ){
920 return 0;
921 }
drh3d6bedf2018-09-19 14:54:38 +0000922 pColl = sqlite3ComparisonExprCollSeq(pParse, pExpr);
drhefad2e22018-07-27 16:57:11 +0000923 if( sqlite3IsBinary(pColl) ) return 1;
drh3d6bedf2018-09-19 14:54:38 +0000924 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->x.pRight);
drh6c1f4ef2015-06-08 14:23:15 +0000925}
926
927/*
928** Recursively walk the expressions of a SELECT statement and generate
929** a bitmask indicating which tables are used in that expression
930** tree.
931*/
932static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
933 Bitmask mask = 0;
934 while( pS ){
935 SrcList *pSrc = pS->pSrc;
936 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
937 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
938 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
939 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
940 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
941 if( ALWAYS(pSrc!=0) ){
942 int i;
943 for(i=0; i<pSrc->nSrc; i++){
944 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
945 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
drh33f763d2018-01-26 22:41:59 +0000946 if( pSrc->a[i].fg.isTabFunc ){
947 mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
948 }
drh6c1f4ef2015-06-08 14:23:15 +0000949 }
950 }
951 pS = pS->pPrior;
952 }
953 return mask;
954}
955
956/*
drh47991422015-08-31 15:58:06 +0000957** Expression pExpr is one operand of a comparison operator that might
958** be useful for indexing. This routine checks to see if pExpr appears
959** in any index. Return TRUE (1) if pExpr is an indexed term and return
drhe97c9ff2017-04-11 18:06:48 +0000960** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
961** number of the table that is indexed and aiCurCol[1] to the column number
drh8d25cb92016-08-19 19:58:06 +0000962** of the column that is indexed, or XN_EXPR (-2) if an expression is being
963** indexed.
drh47991422015-08-31 15:58:06 +0000964**
965** If pExpr is a TK_COLUMN column reference, then this routine always returns
966** true even if that particular column is not indexed, because the column
967** might be added to an automatic index later.
968*/
drhe97c9ff2017-04-11 18:06:48 +0000969static SQLITE_NOINLINE int exprMightBeIndexed2(
drh47991422015-08-31 15:58:06 +0000970 SrcList *pFrom, /* The FROM clause */
971 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
drhe97c9ff2017-04-11 18:06:48 +0000972 int *aiCurCol, /* Write the referenced table cursor and column here */
973 Expr *pExpr /* An operand of a comparison operator */
drh47991422015-08-31 15:58:06 +0000974){
975 Index *pIdx;
976 int i;
977 int iCur;
drhe97c9ff2017-04-11 18:06:48 +0000978 for(i=0; mPrereq>1; i++, mPrereq>>=1){}
979 iCur = pFrom->a[i].iCursor;
980 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
981 if( pIdx->aColExpr==0 ) continue;
982 for(i=0; i<pIdx->nKeyCol; i++){
983 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
984 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
985 aiCurCol[0] = iCur;
986 aiCurCol[1] = XN_EXPR;
987 return 1;
988 }
989 }
990 }
991 return 0;
992}
993static int exprMightBeIndexed(
994 SrcList *pFrom, /* The FROM clause */
995 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
996 int *aiCurCol, /* Write the referenced table cursor & column here */
997 Expr *pExpr, /* An operand of a comparison operator */
998 int op /* The specific comparison operator */
999){
dan71c57db2016-07-09 20:23:55 +00001000 /* If this expression is a vector to the left or right of a
1001 ** inequality constraint (>, <, >= or <=), perform the processing
1002 ** on the first element of the vector. */
1003 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
drh64bcb8c2016-08-26 03:42:57 +00001004 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
1005 assert( op<=TK_GE );
1006 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
dan71c57db2016-07-09 20:23:55 +00001007 pExpr = pExpr->x.pList->a[0].pExpr;
1008 }
1009
drh47991422015-08-31 15:58:06 +00001010 if( pExpr->op==TK_COLUMN ){
drhe97c9ff2017-04-11 18:06:48 +00001011 aiCurCol[0] = pExpr->iTable;
1012 aiCurCol[1] = pExpr->iColumn;
drh47991422015-08-31 15:58:06 +00001013 return 1;
1014 }
1015 if( mPrereq==0 ) return 0; /* No table references */
1016 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
drhe97c9ff2017-04-11 18:06:48 +00001017 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
drh47991422015-08-31 15:58:06 +00001018}
1019
dan870a0702016-08-01 16:37:43 +00001020/*
drh6c1f4ef2015-06-08 14:23:15 +00001021** The input to this routine is an WhereTerm structure with only the
1022** "pExpr" field filled in. The job of this routine is to analyze the
1023** subexpression and populate all the other fields of the WhereTerm
1024** structure.
1025**
1026** If the expression is of the form "<expr> <op> X" it gets commuted
1027** to the standard form of "X <op> <expr>".
1028**
1029** If the expression is of the form "X <op> Y" where both X and Y are
1030** columns, then the original expression is unchanged and a new virtual
1031** term of the form "Y <op> X" is added to the WHERE clause and
1032** analyzed separately. The original term is marked with TERM_COPIED
1033** and the new term is marked with TERM_DYNAMIC (because it's pExpr
1034** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
1035** is a commuted copy of a prior term.) The original term has nChild=1
1036** and the copy has idxParent set to the index of the original term.
1037*/
1038static void exprAnalyze(
1039 SrcList *pSrc, /* the FROM clause */
1040 WhereClause *pWC, /* the WHERE clause */
1041 int idxTerm /* Index of the term to be analyzed */
1042){
1043 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
1044 WhereTerm *pTerm; /* The term to be analyzed */
1045 WhereMaskSet *pMaskSet; /* Set of table index masks */
1046 Expr *pExpr; /* The expression to be analyzed */
1047 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
1048 Bitmask prereqAll; /* Prerequesites of pExpr */
1049 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
1050 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
1051 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
1052 int noCase = 0; /* uppercase equivalent to lowercase */
1053 int op; /* Top-level operator. pExpr->op */
1054 Parse *pParse = pWInfo->pParse; /* Parsing context */
1055 sqlite3 *db = pParse->db; /* Database connection */
mistachkin53be36b2017-11-03 06:45:37 +00001056 unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
drhd9bcb322017-01-10 15:08:06 +00001057 int nLeft; /* Number of elements on left side vector */
drh6c1f4ef2015-06-08 14:23:15 +00001058
1059 if( db->mallocFailed ){
1060 return;
1061 }
1062 pTerm = &pWC->a[idxTerm];
1063 pMaskSet = &pWInfo->sMaskSet;
1064 pExpr = pTerm->pExpr;
1065 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
1066 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
1067 op = pExpr->op;
1068 if( op==TK_IN ){
drh3d6bedf2018-09-19 14:54:38 +00001069 assert( pExpr->eX!=EX_Right );
dan7b35a772016-07-28 19:47:15 +00001070 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
drh3b3c86a2018-09-18 21:35:31 +00001071 switch( pExpr->eX ){
1072 case EX_Select: {
1073 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
1074 break;
1075 }
1076 case EX_List: {
1077 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet,pExpr->x.pList);
1078 break;
1079 }
drh6c1f4ef2015-06-08 14:23:15 +00001080 }
drh6c1f4ef2015-06-08 14:23:15 +00001081 }else{
drh3d6bedf2018-09-19 14:54:38 +00001082 assert( op!=TK_ISNULL || pExpr->eX!=EX_Right );
1083 if( pExpr->eX==EX_Right ){
1084 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->x.pRight);
1085 }else{
1086 pTerm->prereqRight = 0;
1087 }
drh6c1f4ef2015-06-08 14:23:15 +00001088 }
dand3930b12017-07-10 15:17:30 +00001089 pMaskSet->bVarSelect = 0;
drhccf6db52018-06-09 02:49:11 +00001090 prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
dand3930b12017-07-10 15:17:30 +00001091 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
drh6c1f4ef2015-06-08 14:23:15 +00001092 if( ExprHasProperty(pExpr, EP_FromJoin) ){
1093 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
1094 prereqAll |= x;
1095 extraRight = x-1; /* ON clause terms may not be used with an index
1096 ** on left table of a LEFT JOIN. Ticket #3015 */
drh8e36ddd2017-01-10 17:33:43 +00001097 if( (prereqAll>>1)>=x ){
1098 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
1099 return;
1100 }
drh6c1f4ef2015-06-08 14:23:15 +00001101 }
1102 pTerm->prereqAll = prereqAll;
1103 pTerm->leftCursor = -1;
1104 pTerm->iParent = -1;
1105 pTerm->eOperator = 0;
1106 if( allowedOp(op) ){
drhe97c9ff2017-04-11 18:06:48 +00001107 int aiCurCol[2];
drh3d6bedf2018-09-19 14:54:38 +00001108 Expr *pLeft, *pRight;
1109 u16 opMask;
dan8da209b2016-07-26 18:06:08 +00001110
drh3d6bedf2018-09-19 14:54:38 +00001111 pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
1112 if( pExpr->eX==EX_Right ){
1113 pRight = sqlite3ExprSkipCollate(pExpr->x.pRight);
1114 }else{
1115 pRight = 0;
1116 }
1117 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
dan145b4ea2016-07-29 18:12:12 +00001118 if( pTerm->iField>0 ){
1119 assert( op==TK_IN );
dan8da209b2016-07-26 18:06:08 +00001120 assert( pLeft->op==TK_VECTOR );
1121 pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
1122 }
1123
drhe97c9ff2017-04-11 18:06:48 +00001124 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
1125 pTerm->leftCursor = aiCurCol[0];
1126 pTerm->u.leftColumn = aiCurCol[1];
drh6860e6f2015-08-27 18:24:02 +00001127 pTerm->eOperator = operatorMask(op) & opMask;
drh6c1f4ef2015-06-08 14:23:15 +00001128 }
1129 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh47991422015-08-31 15:58:06 +00001130 if( pRight
drhe97c9ff2017-04-11 18:06:48 +00001131 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
drh47991422015-08-31 15:58:06 +00001132 ){
drh6c1f4ef2015-06-08 14:23:15 +00001133 WhereTerm *pNew;
1134 Expr *pDup;
1135 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
dan145b4ea2016-07-29 18:12:12 +00001136 assert( pTerm->iField==0 );
drh6c1f4ef2015-06-08 14:23:15 +00001137 if( pTerm->leftCursor>=0 ){
1138 int idxNew;
1139 pDup = sqlite3ExprDup(db, pExpr, 0);
1140 if( db->mallocFailed ){
1141 sqlite3ExprDelete(db, pDup);
1142 return;
1143 }
1144 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1145 if( idxNew==0 ) return;
1146 pNew = &pWC->a[idxNew];
1147 markTermAsChild(pWC, idxNew, idxTerm);
1148 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
1149 pTerm = &pWC->a[idxTerm];
1150 pTerm->wtFlags |= TERM_COPIED;
1151
1152 if( termIsEquivalence(pParse, pDup) ){
1153 pTerm->eOperator |= WO_EQUIV;
1154 eExtraOp = WO_EQUIV;
1155 }
1156 }else{
1157 pDup = pExpr;
1158 pNew = pTerm;
1159 }
1160 exprCommute(pParse, pDup);
drhe97c9ff2017-04-11 18:06:48 +00001161 pNew->leftCursor = aiCurCol[0];
1162 pNew->u.leftColumn = aiCurCol[1];
drh6c1f4ef2015-06-08 14:23:15 +00001163 testcase( (prereqLeft | extraRight) != prereqLeft );
1164 pNew->prereqRight = prereqLeft | extraRight;
1165 pNew->prereqAll = prereqAll;
1166 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1167 }
1168 }
1169
1170#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1171 /* If a term is the BETWEEN operator, create two new virtual terms
1172 ** that define the range that the BETWEEN implements. For example:
1173 **
1174 ** a BETWEEN b AND c
1175 **
1176 ** is converted into:
1177 **
1178 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1179 **
1180 ** The two new terms are added onto the end of the WhereClause object.
1181 ** The new terms are "dynamic" and are children of the original BETWEEN
1182 ** term. That means that if the BETWEEN term is coded, the children are
1183 ** skipped. Or, if the children are satisfied by an index, the original
1184 ** BETWEEN term is skipped.
1185 */
1186 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1187 ExprList *pList = pExpr->x.pList;
1188 int i;
1189 static const u8 ops[] = {TK_GE, TK_LE};
1190 assert( pList!=0 );
1191 assert( pList->nExpr==2 );
1192 for(i=0; i<2; i++){
1193 Expr *pNewExpr;
1194 int idxNew;
1195 pNewExpr = sqlite3PExpr(pParse, ops[i],
1196 sqlite3ExprDup(db, pExpr->pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001197 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001198 transferJoinMarkings(pNewExpr, pExpr);
1199 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1200 testcase( idxNew==0 );
1201 exprAnalyze(pSrc, pWC, idxNew);
1202 pTerm = &pWC->a[idxTerm];
1203 markTermAsChild(pWC, idxNew, idxTerm);
1204 }
1205 }
1206#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1207
1208#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1209 /* Analyze a term that is composed of two or more subterms connected by
1210 ** an OR operator.
1211 */
1212 else if( pExpr->op==TK_OR ){
1213 assert( pWC->op==TK_AND );
1214 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1215 pTerm = &pWC->a[idxTerm];
1216 }
1217#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1218
1219#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1220 /* Add constraints to reduce the search space on a LIKE or GLOB
1221 ** operator.
1222 **
1223 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1224 **
1225 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1226 **
1227 ** The last character of the prefix "abc" is incremented to form the
1228 ** termination condition "abd". If case is not significant (the default
1229 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1230 ** bound is made all lowercase so that the bounds also work when comparing
1231 ** BLOBs.
1232 */
1233 if( pWC->op==TK_AND
1234 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1235 ){
1236 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1237 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1238 Expr *pNewExpr1;
1239 Expr *pNewExpr2;
1240 int idxNew1;
1241 int idxNew2;
1242 const char *zCollSeqName; /* Name of collating sequence */
1243 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1244
1245 pLeft = pExpr->x.pList->a[1].pExpr;
1246 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1247
1248 /* Convert the lower bound to upper-case and the upper bound to
1249 ** lower-case (upper-case is less than lower-case in ASCII) so that
1250 ** the range constraints also work for BLOBs
1251 */
1252 if( noCase && !pParse->db->mallocFailed ){
1253 int i;
1254 char c;
1255 pTerm->wtFlags |= TERM_LIKE;
1256 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1257 pStr1->u.zToken[i] = sqlite3Toupper(c);
1258 pStr2->u.zToken[i] = sqlite3Tolower(c);
1259 }
1260 }
1261
1262 if( !db->mallocFailed ){
1263 u8 c, *pC; /* Last character before the first wildcard */
1264 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1265 c = *pC;
1266 if( noCase ){
1267 /* The point is to increment the last character before the first
1268 ** wildcard. But if we increment '@', that will push it into the
1269 ** alphabetic range where case conversions will mess up the
1270 ** inequality. To avoid this, make sure to also run the full
1271 ** LIKE on all candidate expressions by clearing the isComplete flag
1272 */
1273 if( c=='A'-1 ) isComplete = 0;
1274 c = sqlite3UpperToLower[c];
1275 }
1276 *pC = c + 1;
1277 }
drh7810ab62018-07-27 17:51:20 +00001278 zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
drh6c1f4ef2015-06-08 14:23:15 +00001279 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1280 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1281 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001282 pStr1);
drh6c1f4ef2015-06-08 14:23:15 +00001283 transferJoinMarkings(pNewExpr1, pExpr);
1284 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1285 testcase( idxNew1==0 );
1286 exprAnalyze(pSrc, pWC, idxNew1);
1287 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1288 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1289 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001290 pStr2);
drh6c1f4ef2015-06-08 14:23:15 +00001291 transferJoinMarkings(pNewExpr2, pExpr);
1292 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1293 testcase( idxNew2==0 );
1294 exprAnalyze(pSrc, pWC, idxNew2);
1295 pTerm = &pWC->a[idxTerm];
1296 if( isComplete ){
1297 markTermAsChild(pWC, idxNew1, idxTerm);
1298 markTermAsChild(pWC, idxNew2, idxTerm);
1299 }
1300 }
1301#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1302
1303#ifndef SQLITE_OMIT_VIRTUALTABLE
drh303a69b2017-09-11 19:47:37 +00001304 /* Add a WO_AUX auxiliary term to the constraint set if the
1305 ** current expression is of the form "column OP expr" where OP
1306 ** is an operator that gets passed into virtual tables but which is
1307 ** not normally optimized for ordinary tables. In other words, OP
1308 ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
drh6c1f4ef2015-06-08 14:23:15 +00001309 ** This information is used by the xBestIndex methods of
1310 ** virtual tables. The native query optimizer does not attempt
1311 ** to do anything with MATCH functions.
1312 */
dand03024d2017-09-09 19:41:12 +00001313 if( pWC->op==TK_AND ){
mistachkin53be36b2017-11-03 06:45:37 +00001314 Expr *pRight = 0, *pLeft = 0;
drh59155062018-05-26 18:03:48 +00001315 int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
drh303a69b2017-09-11 19:47:37 +00001316 while( res-- > 0 ){
dand03024d2017-09-09 19:41:12 +00001317 int idxNew;
1318 WhereTerm *pNewTerm;
1319 Bitmask prereqColumn, prereqExpr;
drh6c1f4ef2015-06-08 14:23:15 +00001320
dand03024d2017-09-09 19:41:12 +00001321 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1322 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1323 if( (prereqExpr & prereqColumn)==0 ){
1324 Expr *pNewExpr;
1325 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
1326 0, sqlite3ExprDup(db, pRight, 0));
1327 if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
1328 ExprSetProperty(pNewExpr, EP_FromJoin);
1329 }
1330 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1331 testcase( idxNew==0 );
1332 pNewTerm = &pWC->a[idxNew];
1333 pNewTerm->prereqRight = prereqExpr;
1334 pNewTerm->leftCursor = pLeft->iTable;
1335 pNewTerm->u.leftColumn = pLeft->iColumn;
drh303a69b2017-09-11 19:47:37 +00001336 pNewTerm->eOperator = WO_AUX;
dand03024d2017-09-09 19:41:12 +00001337 pNewTerm->eMatchOp = eOp2;
1338 markTermAsChild(pWC, idxNew, idxTerm);
1339 pTerm = &pWC->a[idxTerm];
1340 pTerm->wtFlags |= TERM_COPIED;
1341 pNewTerm->prereqAll = pTerm->prereqAll;
dan210ec4c2017-06-27 16:39:01 +00001342 }
dand03024d2017-09-09 19:41:12 +00001343 SWAP(Expr*, pLeft, pRight);
drh6c1f4ef2015-06-08 14:23:15 +00001344 }
1345 }
1346#endif /* SQLITE_OMIT_VIRTUALTABLE */
1347
dan95a08c02016-08-02 16:18:35 +00001348 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
drh9e730f02016-08-20 12:00:05 +00001349 ** new terms for each component comparison - "a = ?" and "b = ?". The
1350 ** new terms completely replace the original vector comparison, which is
1351 ** no longer used.
1352 **
dan95a08c02016-08-02 16:18:35 +00001353 ** This is only required if at least one side of the comparison operation
1354 ** is not a sub-select. */
dan71c57db2016-07-09 20:23:55 +00001355 if( pWC->op==TK_AND
1356 && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
drhd9bcb322017-01-10 15:08:06 +00001357 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
drh3d6bedf2018-09-19 14:54:38 +00001358 && ALWAYS(pExpr->eX==EX_Right)
1359 && sqlite3ExprVectorSize(pExpr->x.pRight)==nLeft
1360 && ( pExpr->pLeft->eX!=EX_Select || pExpr->x.pRight->eX!=EX_Select )
drhd9bcb322017-01-10 15:08:06 +00001361 ){
drhb29e60c2016-09-05 12:02:34 +00001362 int i;
drhb29e60c2016-09-05 12:02:34 +00001363 for(i=0; i<nLeft; i++){
1364 int idxNew;
drh3d6bedf2018-09-19 14:54:38 +00001365 Expr *pNew, *pLeft, *pRight;
dan71c57db2016-07-09 20:23:55 +00001366
drh3d6bedf2018-09-19 14:54:38 +00001367 pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
1368 assert( pExpr->eX==EX_Right );
1369 pRight = sqlite3ExprForVectorField(pParse, pExpr->x.pRight, i);
drhabfd35e2016-12-06 22:47:23 +00001370 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
drhc52496f2016-10-27 01:02:20 +00001371 transferJoinMarkings(pNew, pExpr);
drhb29e60c2016-09-05 12:02:34 +00001372 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
1373 exprAnalyze(pSrc, pWC, idxNew);
dan71c57db2016-07-09 20:23:55 +00001374 }
drhb29e60c2016-09-05 12:02:34 +00001375 pTerm = &pWC->a[idxTerm];
drhe28eb642018-02-18 17:50:03 +00001376 pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
drhb29e60c2016-09-05 12:02:34 +00001377 pTerm->eOperator = 0;
dan71c57db2016-07-09 20:23:55 +00001378 }
1379
dan95a08c02016-08-02 16:18:35 +00001380 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1381 ** a virtual term for each vector component. The expression object
1382 ** used by each such virtual term is pExpr (the full vector IN(...)
1383 ** expression). The WhereTerm.iField variable identifies the index within
drh14318072016-09-06 18:51:25 +00001384 ** the vector on the LHS that the virtual term represents.
1385 **
1386 ** This only works if the RHS is a simple SELECT, not a compound
1387 */
dan8da209b2016-07-26 18:06:08 +00001388 if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
1389 && pExpr->pLeft->op==TK_VECTOR
drh14318072016-09-06 18:51:25 +00001390 && pExpr->x.pSelect->pPrior==0
dan8da209b2016-07-26 18:06:08 +00001391 ){
1392 int i;
1393 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1394 int idxNew;
1395 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
1396 pWC->a[idxNew].iField = i+1;
1397 exprAnalyze(pSrc, pWC, idxNew);
1398 markTermAsChild(pWC, idxNew, idxTerm);
1399 }
1400 }
1401
drh6c1f4ef2015-06-08 14:23:15 +00001402#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1403 /* When sqlite_stat3 histogram data is available an operator of the
1404 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1405 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1406 ** virtual term of that form.
1407 **
1408 ** Note that the virtual term must be tagged with TERM_VNULL.
1409 */
1410 if( pExpr->op==TK_NOTNULL
1411 && pExpr->pLeft->op==TK_COLUMN
1412 && pExpr->pLeft->iColumn>=0
1413 && OptimizationEnabled(db, SQLITE_Stat34)
1414 ){
1415 Expr *pNewExpr;
1416 Expr *pLeft = pExpr->pLeft;
1417 int idxNew;
1418 WhereTerm *pNewTerm;
1419
1420 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1421 sqlite3ExprDup(db, pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001422 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001423
1424 idxNew = whereClauseInsert(pWC, pNewExpr,
1425 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1426 if( idxNew ){
1427 pNewTerm = &pWC->a[idxNew];
1428 pNewTerm->prereqRight = 0;
1429 pNewTerm->leftCursor = pLeft->iTable;
1430 pNewTerm->u.leftColumn = pLeft->iColumn;
1431 pNewTerm->eOperator = WO_GT;
1432 markTermAsChild(pWC, idxNew, idxTerm);
1433 pTerm = &pWC->a[idxTerm];
1434 pTerm->wtFlags |= TERM_COPIED;
1435 pNewTerm->prereqAll = pTerm->prereqAll;
1436 }
1437 }
1438#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1439
1440 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1441 ** an index for tables to the left of the join.
1442 */
drh0f85b2f2016-11-20 12:00:27 +00001443 testcase( pTerm!=&pWC->a[idxTerm] );
1444 pTerm = &pWC->a[idxTerm];
drh6c1f4ef2015-06-08 14:23:15 +00001445 pTerm->prereqRight |= extraRight;
1446}
1447
1448/***************************************************************************
1449** Routines with file scope above. Interface to the rest of the where.c
1450** subsystem follows.
1451***************************************************************************/
1452
1453/*
1454** This routine identifies subexpressions in the WHERE clause where
1455** each subexpression is separated by the AND operator or some other
1456** operator specified in the op parameter. The WhereClause structure
1457** is filled with pointers to subexpressions. For example:
1458**
1459** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1460** \________/ \_______________/ \________________/
1461** slot[0] slot[1] slot[2]
1462**
1463** The original WHERE clause in pExpr is unaltered. All this routine
1464** does is make slot[] entries point to substructure within pExpr.
1465**
1466** In the previous sentence and in the diagram, "slot[]" refers to
1467** the WhereClause.a[] array. The slot[] array grows as needed to contain
1468** all terms of the WHERE clause.
1469*/
1470void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1471 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1472 pWC->op = op;
1473 if( pE2==0 ) return;
1474 if( pE2->op!=op ){
1475 whereClauseInsert(pWC, pExpr, 0);
1476 }else{
drh3d6bedf2018-09-19 14:54:38 +00001477 assert( pE2->eX==EX_Right );
drh6c1f4ef2015-06-08 14:23:15 +00001478 sqlite3WhereSplit(pWC, pE2->pLeft, op);
drh3d6bedf2018-09-19 14:54:38 +00001479 sqlite3WhereSplit(pWC, pE2->x.pRight, op);
drh6c1f4ef2015-06-08 14:23:15 +00001480 }
1481}
1482
1483/*
1484** Initialize a preallocated WhereClause structure.
1485*/
1486void sqlite3WhereClauseInit(
1487 WhereClause *pWC, /* The WhereClause to be initialized */
1488 WhereInfo *pWInfo /* The WHERE processing context */
1489){
1490 pWC->pWInfo = pWInfo;
drh9c3549a2018-06-11 01:30:03 +00001491 pWC->hasOr = 0;
drh6c1f4ef2015-06-08 14:23:15 +00001492 pWC->pOuter = 0;
1493 pWC->nTerm = 0;
1494 pWC->nSlot = ArraySize(pWC->aStatic);
1495 pWC->a = pWC->aStatic;
1496}
1497
1498/*
1499** Deallocate a WhereClause structure. The WhereClause structure
drh62aaa6c2015-11-21 17:27:42 +00001500** itself is not freed. This routine is the inverse of
1501** sqlite3WhereClauseInit().
drh6c1f4ef2015-06-08 14:23:15 +00001502*/
1503void sqlite3WhereClauseClear(WhereClause *pWC){
1504 int i;
1505 WhereTerm *a;
1506 sqlite3 *db = pWC->pWInfo->pParse->db;
1507 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1508 if( a->wtFlags & TERM_DYNAMIC ){
1509 sqlite3ExprDelete(db, a->pExpr);
1510 }
1511 if( a->wtFlags & TERM_ORINFO ){
1512 whereOrInfoDelete(db, a->u.pOrInfo);
1513 }else if( a->wtFlags & TERM_ANDINFO ){
1514 whereAndInfoDelete(db, a->u.pAndInfo);
1515 }
1516 }
1517 if( pWC->a!=pWC->aStatic ){
1518 sqlite3DbFree(db, pWC->a);
1519 }
1520}
1521
1522
1523/*
1524** These routines walk (recursively) an expression tree and generate
1525** a bitmask indicating which tables are used in that expression
1526** tree.
1527*/
drhccf6db52018-06-09 02:49:11 +00001528Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
drh93ca3932016-08-10 20:02:21 +00001529 Bitmask mask;
drhefad2e22018-07-27 16:57:11 +00001530 if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
drhf43ce0b2017-05-25 00:08:48 +00001531 return sqlite3WhereGetMask(pMaskSet, p->iTable);
drhccf6db52018-06-09 02:49:11 +00001532 }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1533 assert( p->op!=TK_IF_NULL_ROW );
1534 return 0;
drh6c1f4ef2015-06-08 14:23:15 +00001535 }
drhf43ce0b2017-05-25 00:08:48 +00001536 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
drhccf6db52018-06-09 02:49:11 +00001537 if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
drh3d6bedf2018-09-19 14:54:38 +00001538 switch( p->eX ){
1539 case EX_Right: {
1540 mask |= sqlite3WhereExprUsageNN(pMaskSet, p->x.pRight);
1541 break;
1542 }
1543 case EX_Select: {
1544 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
1545 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
1546 break;
1547 }
1548 case EX_List: {
1549 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1550 break;
drh3b3c86a2018-09-18 21:35:31 +00001551 }
drh6c1f4ef2015-06-08 14:23:15 +00001552 }
1553 return mask;
1554}
drhccf6db52018-06-09 02:49:11 +00001555Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
1556 return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
1557}
drh6c1f4ef2015-06-08 14:23:15 +00001558Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1559 int i;
1560 Bitmask mask = 0;
1561 if( pList ){
1562 for(i=0; i<pList->nExpr; i++){
1563 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1564 }
1565 }
1566 return mask;
1567}
1568
1569
1570/*
1571** Call exprAnalyze on all terms in a WHERE clause.
1572**
1573** Note that exprAnalyze() might add new virtual terms onto the
1574** end of the WHERE clause. We do not want to analyze these new
1575** virtual terms, so start analyzing at the end and work forward
1576** so that the added virtual terms are never processed.
1577*/
1578void sqlite3WhereExprAnalyze(
1579 SrcList *pTabList, /* the FROM clause */
1580 WhereClause *pWC /* the WHERE clause to be analyzed */
1581){
1582 int i;
1583 for(i=pWC->nTerm-1; i>=0; i--){
1584 exprAnalyze(pTabList, pWC, i);
1585 }
1586}
drh01d230c2015-08-19 17:11:37 +00001587
1588/*
1589** For table-valued-functions, transform the function arguments into
1590** new WHERE clause terms.
1591**
1592** Each function argument translates into an equality constraint against
1593** a HIDDEN column in the table.
1594*/
1595void sqlite3WhereTabFuncArgs(
1596 Parse *pParse, /* Parsing context */
1597 struct SrcList_item *pItem, /* The FROM clause term to process */
1598 WhereClause *pWC /* Xfer function arguments to here */
1599){
1600 Table *pTab;
1601 int j, k;
1602 ExprList *pArgs;
1603 Expr *pColRef;
1604 Expr *pTerm;
1605 if( pItem->fg.isTabFunc==0 ) return;
1606 pTab = pItem->pTab;
1607 assert( pTab!=0 );
1608 pArgs = pItem->u1.pFuncArg;
drh20292312015-11-21 13:24:46 +00001609 if( pArgs==0 ) return;
drh01d230c2015-08-19 17:11:37 +00001610 for(j=k=0; j<pArgs->nExpr; j++){
drh62aaa6c2015-11-21 17:27:42 +00001611 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
drh01d230c2015-08-19 17:11:37 +00001612 if( k>=pTab->nCol ){
drhd8b1bfc2015-08-20 23:21:34 +00001613 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
drh01d230c2015-08-19 17:11:37 +00001614 pTab->zName, j);
1615 return;
1616 }
drhe1c03b62016-09-23 20:59:31 +00001617 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
drh01d230c2015-08-19 17:11:37 +00001618 if( pColRef==0 ) return;
1619 pColRef->iTable = pItem->iCursor;
1620 pColRef->iColumn = k++;
drh8477f7f2018-09-19 20:14:48 +00001621 pColRef->x.pTab = pTab;
1622 pColRef->eX = EX_Tab;
drh01d230c2015-08-19 17:11:37 +00001623 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
drhabfd35e2016-12-06 22:47:23 +00001624 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
drh01d230c2015-08-19 17:11:37 +00001625 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1626 }
1627}